feat: main 병합 + 인스타 올리기 API(/v1/card/{id}/instagram), 관리자 올릴 곳 선택(로컬·킹서버), 만든 카드 화면

This commit is contained in:
minaChoi committed 2026-10-23 15:48:09 +09:00
commit 572b2a05c8
188 files changed
+16605 -741

No files matched your search

+3 -12
View File
@@ -10,6 +10,7 @@
gtag('config', 'G-D378J4X373');
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4414665130371841" crossorigin="anonymous"></script>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
@@ -67,18 +68,6 @@
"image": "%VITE_SITE_URL%/og.png",
"offers": { "@type": "Offer", "price": "0", "priceCurrency": "KRW" },
"publisher": { "@id": "%VITE_SITE_URL%/#organization" }
},
{
"@type": "FAQPage",
"mainEntity": [
{ "@type": "Question", "name": "날씨각은 어떤 서비스인가요?", "acceptedAnswer": { "@type": "Answer", "text": "우리 동네 날씨로 세차, 빨래, 러닝 같은 일을 하기 좋은지 점수로 알려 주는 서비스예요. 오늘 노을이 예쁜 시간과 이번 주말 행사도 함께 볼 수 있어요." } },
{ "@type": "Question", "name": "세차하기 좋은 날은 어떻게 알 수 있나요?", "acceptedAnswer": { "@type": "Answer", "text": "세차각 점수를 보면 돼요. 오늘뿐 아니라 이틀 뒤까지 비 소식을 함께 봐서, 세차하고 곧 비가 오는 날은 점수가 낮아요." } },
{ "@type": "Question", "name": "빨래가 잘 마르는 날은 언제인가요?", "acceptedAnswer": { "@type": "Answer", "text": "빨래각 점수를 보면 돼요. 비가 안 오고, 따뜻하고, 바람이 적당히 불고, 덜 습할수록 점수가 높아요." } },
{ "@type": "Question", "name": "러닝하기 좋은 시간은 언제인가요?", "acceptedAnswer": { "@type": "Answer", "text": "러닝각은 아침 6~8시와 저녁 7~10시 날씨로 계산해요. 선선하고 비와 바람이 적을수록 점수가 높아요." } },
{ "@type": "Question", "name": "오늘 노을은 몇 시에 가장 예쁜가요?", "acceptedAnswer": { "@type": "Answer", "text": "노을 탭에서 우리 동네 노을이 가장 붉은 시각을 알려 드려요. 보통 해 지고 10~20분 뒤예요. 오늘 노을이 얼마나 물들지와 가까운 노을 명소도 함께 볼 수 있어요." } },
{ "@type": "Question", "name": "이번 주말 가 볼 만한 축제는 어디서 보나요?", "acceptedAnswer": { "@type": "Answer", "text": "주말·행사 탭에서 가까운 축제, 전시, 공연, 팝업을 볼 수 있어요. 주말 날씨와 나들이하기 좋은 곳도 함께 알려 드려요." } },
{ "@type": "Question", "name": "날씨 정보는 얼마나 자주 바뀌나요?", "acceptedAnswer": { "@type": "Answer", "text": "기상청 예보가 나올 때마다 하루 8번, 미세먼지는 매시간 새로 반영해요." } }
]
}
]
}
@@ -115,6 +104,8 @@
<p>이번 주말 날씨와 나들이하기 좋은 곳, 가까운 축제와 전시, 공연을 모아 드려요.</p>
<h2><a href="/season">계절·상식</a></h2>
<p>지금 계절에 볼 만한 소식과 알아 두면 좋은 날씨 상식을 읽을 수 있어요.</p>
<h2><a href="/faq">자주 묻는 질문</a></h2>
<p>비 오는 날, 맑은 날, 미세먼지 나쁜 날 뭐 하면 좋을지와 지역별 오늘 날씨 보는 법을 정리했어요.</p>
<p>기상청 예보와 에어코리아 미세먼지 정보로 매일 새로 계산해요.</p>
</main>
</div>
+8 -2
View File
@@ -5,6 +5,12 @@ server {
index index.html;
# 폴더 주소로 넘길 때 포트가 빠지지 않게 상대 주소로 보낸다
absolute_redirect off;
# 앞단 프록시(사설망)가 붙인 X-Forwarded-For 에서 실제 접속 주소를 꺼내 $remote_addr 로 쓴다 (비로그인 좋아요를 IP 로 세려고)
set_real_ip_from 172.16.0.0/12;
set_real_ip_from 10.0.0.0/8;
set_real_ip_from 192.168.0.0/16;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
gzip on;
gzip_types text/css application/javascript image/svg+xml application/json;
@@ -31,8 +37,8 @@ server {
proxy_set_header X-Forwarded-Proto $scheme;
}
# 지역 검색 페이지: 백엔드가 정적 HTML(today/…/….html)에 오늘 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로
location ~ ^/today/[a-z]+/[a-z]+(/[a-z]+)?$ {
# 지역 검색 페이지: 백엔드가 정적 HTML(today·tomorrow/…/….html)에 오늘·내일 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로
location ~ ^/(today|tomorrow)/[a-z]+/[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
View File
@@ -0,0 +1 @@
google.com, pub-4414665130371841, DIRECT, f08c47fec0942fa0
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

+25 -4
View File
@@ -3,12 +3,33 @@
"short_name": "날씨각",
"description": "오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 이번 주말 가까운 축제까지.",
"lang": "ko-KR",
"start_url": "/",
"start_url": "/?source=homescreen",
"display": "standalone",
"background_color": "#d6ebff",
"theme_color": "#d6ebff",
"icons": [
{ "src": "/favicon.svg", "sizes": "any", "type": "image/svg+xml" },
{ "src": "/apple-touch-icon.png", "sizes": "180x180", "type": "image/png" }
]
{
"src": "/app/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/app/icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "/app/icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/favicon.svg",
"sizes": "any",
"type": "image/svg+xml"
}
],
"id": "/",
"scope": "/"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+1 -1
View File
@@ -36,7 +36,7 @@
<p>회원 정보는 회원 탈퇴 시까지 보관하며, 탈퇴 요청을 받으면 지체 없이 파기합니다. 접속 기록은 「통신비밀보호법」에 따라 3개월간 보관합니다.</p>
<h2>3. 제3자 제공 및 처리 위탁</h2>
<p>회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.</p>
<p>회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 광고 게재를 위해 Google AdSense(Google LLC)를 사용하며, Google은 쿠키로 이 사이트와 다른 사이트 방문 기록을 바탕으로 광고를 보여 줄 수 있습니다. 맞춤 광고는 Google 광고 설정(https://adssettings.google.com)에서 끌 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.</p>
<h2>4. 파기 절차 및 방법</h2>
<p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p>
+4
View File
@@ -0,0 +1,4 @@
// 홈 화면 설치 조건을 맞추려고 둔 서비스 워커. 화면을 캐시하지 않고 네트워크로 그대로 보낸다 (옛 화면이 남지 않게)
self.addEventListener('install', () => self.skipWaiting())
self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()))
self.addEventListener('fetch', () => {})
+97
View File
@@ -0,0 +1,97 @@
[
{
"category": "날씨별로 뭐 하면 좋을까",
"items": [
{
"q": "비 오는 날 뭐 하면 좋을까요?",
"a": "비 오는 날엔 파전에 막걸리, 짬뽕처럼 뜨끈한 음식이나 집에서 영화 보기가 잘 어울려요. 날씨각에서는 비가 오면 우산각·파전각·막걸리각·감성노래각·넷플릭스각 점수가 올라가요. 빨래는 실내 건조로 돌리고, 세차는 비가 그친 뒤 이틀쯤 미루는 게 좋아요."
},
{
"q": "맑은 날 뭐 하면 좋을까요?",
"a": "맑고 바람이 잔잔한 날엔 빨래, 세차, 피크닉, 자전거, 드라이브가 좋아요. 낮 기온이 20~26°면 피크닉각, 해가 잘 들고 바람이 솔솔 불면 빨래각 점수가 높아요. 저녁엔 노을과 별보기도 함께 확인해 보세요."
},
{
"q": "미세먼지 나쁜 날 뭐 하면 좋을까요?",
"a": "초미세먼지가 나쁜 날엔 바깥 운동과 환기를 줄이고 실내에서 지내는 게 좋아요. 날씨각의 환기각은 초미세먼지가 75㎍/㎥ 이상이면 0점이 되고, 반대로 집콕각 점수는 올라가요. 공기가 맑아지는 시간에 짧게 환기하세요."
},
{
"q": "더운 날 뭐 하면 좋을까요?",
"a": "더운 날엔 낮엔 물놀이·빙수·냉면, 운동은 해 뜨기 전 아침이나 해 진 뒤가 좋아요. 러닝각은 체감 35° 이상이면 0점이라 아침 6~8시나 저녁 7~10시 중 시원한 쪽을 고르세요. 빨래는 잘 마르니 이불 빨래하기 좋은 날이에요."
},
{
"q": "추운 날 뭐 하면 좋을까요?",
"a": "추운 날엔 군고구마, 붕어빵, 군밤처럼 따뜻한 간식과 뜨끈한 국물이 당겨요. 날씨각에서는 기온이 내려가면 군밤각·붕어빵각·짬뽕각·뜨아각 점수가 올라가요. 빨래는 잘 안 마르니 얇은 것만 널거나 실내 건조를 하세요."
},
{
"q": "바람 많이 부는 날 뭐 하면 좋을까요?",
"a": "바람이 센 날엔 캠핑·등산·자전거를 미루고 실내에서 지내는 게 좋아요. 캠핑각은 바람이 초속 14m 이상이면 0점이에요. 초속 2~5m 정도로 적당히 부는 날은 연날리기, 빨래, 환기하기 좋아요."
},
{
"q": "흐린 날 뭐 하면 좋을까요?",
"a": "비 없이 흐린 날엔 햇볕이 덜 따가워 산책, 러닝, 등산하기 좋아요. 다만 빨래는 햇빛이 부족해 잘 안 마르고, 별보기와 노을은 구름에 가려 점수가 낮아요."
}
]
},
{
"category": "이런 일 하기 좋은 날씨",
"items": [
{
"q": "세차하기 좋은 날씨는 언제인가요?",
"a": "세차는 앞으로 이틀 동안 비 소식이 없고 습도가 낮은 날이 좋아요. 세차각은 오늘뿐 아니라 이틀 뒤까지 비를 함께 봐서, 세차하고 곧 비가 오는 날은 점수가 낮아요. 미세먼지가 적고 바람이 잔잔하면 깨끗함이 더 오래가요."
},
{
"q": "빨래가 잘 마르는 날씨는 언제인가요?",
"a": "빨래는 비가 안 오고, 해가 잘 들고, 따뜻하고, 바람이 적당히 부는 날 잘 말라요. 빨래각은 낮 9~16시 날씨로 계산하고, 기온 25° 이상·습도 40% 이하·바람 초속 2~5m에 가까울수록 점수가 높아요. 비 확률이 60% 이상이면 0점이에요."
},
{
"q": "러닝하기 좋은 날씨와 시간은 언제인가요?",
"a": "러닝은 체감 8~18°에 습도가 낮고 바람이 잔잔한 날이 좋아요. 러닝각은 아침 6~8시와 저녁 7~10시 날씨로 계산해 둘 중 좋은 쪽 점수를 보여 드려요."
},
{
"q": "캠핑하기 좋은 날씨는 언제인가요?",
"a": "캠핑은 밤새 기온이 12~22°이고 비와 바람이 없는 날이 좋아요. 캠핑각은 저녁 6시부터 다음 날 아침 8시까지 날씨로 계산하고, 비 확률 60% 이상이거나 바람이 초속 14m 이상이면 0점이에요."
},
{
"q": "등산하기 좋은 날씨는 언제인가요?",
"a": "등산은 오전 기온이 선선하고 비와 바람이 없고 멀리까지 잘 보이는 날이 좋아요. 등산각은 산 위가 아래보다 6° 낮다고 보고 체감 10~20°를 가장 좋게 쳐요. 비 확률 70% 이상이거나 강풍 특보가 있으면 0점이에요."
},
{
"q": "피크닉하기 좋은 날씨는 언제인가요?",
"a": "피크닉은 낮 기온 20~26°에 바람이 잔잔하고 자외선이 강하지 않은 날이 좋아요. 피크닉각은 오전 11시~오후 4시 날씨로 계산하고 비 확률이 60% 이상이면 0점이에요."
},
{
"q": "창문 열어 환기하기 좋은 시간은 언제인가요?",
"a": "환기는 초미세먼지가 낮고 바람이 적당히 부는 시간이 좋아요. 환기각은 오전 10시부터 오후 6시까지 두 시간씩 나눠 가장 공기가 맑은 시간을 알려 드려요."
},
{
"q": "노을이 예쁜 날은 언제인가요?",
"a": "노을은 높은 구름이 적당히 끼고 공기가 맑은 날 가장 붉게 물들어요. 하늘이 완전히 맑거나 낮은 구름이 두껍게 덮으면 덜 물들어요. 보통 해 진 뒤 10~20분이 가장 붉어요."
}
]
},
{
"category": "날씨각 이용",
"items": [
{
"q": "날씨각은 어떤 서비스인가요?",
"a": "날씨각은 우리 동네 날씨로 세차, 빨래, 러닝 같은 일을 하기 좋은지 점수로 알려 주는 무료 서비스예요. 오늘 노을이 예쁜 시간과 이번 주말 행사도 함께 볼 수 있어요."
},
{
"q": "어느 지역 날씨를 볼 수 있나요?",
"a": "전국 시·군·구 날씨를 볼 수 있어요. 서울 강남구, 전북 군산시, 부산 해운대구처럼 지역마다 따로 계산하고, 성남시처럼 구로 나뉜 시는 구마다 나눠 보여 드려요."
},
{
"q": "각 점수는 어떻게 계산하나요?",
"a": "각마다 기온, 비, 바람, 습도, 미세먼지, 시간대를 0~100점으로 매긴 뒤 각에 맞는 비중으로 섞어요. 아침, 낮, 저녁, 밤마다 따로 계산하고, 비가 쏟아지는 날의 피크닉처럼 하기 어려운 조건이면 0점이 돼요."
},
{
"q": "날씨 정보는 어디서 가져오고 얼마나 자주 바뀌나요?",
"a": "기상청 예보와 에어코리아 미세먼지 정보를 써요. 기상청 예보가 나올 때마다 하루 8번, 미세먼지는 매시간 새로 반영해요."
},
{
"q": "이번 주말 가 볼 만한 축제는 어디서 보나요?",
"a": "주말·행사 탭에서 가까운 축제, 전시, 공연, 팝업을 볼 수 있어요. 주말 날씨와 나들이하기 좋은 곳도 함께 알려 드려요."
}
]
}
]
+661
View File
@@ -0,0 +1,661 @@
{
"source": "산림청·국립수목원·국립산림과학원 「2026년 한반도 단풍절정 예측지도」(2026.9.22 보도자료, 단풍나무류·은행나무 지도)",
"source_url": "https://www.korea.kr/briefing/pressReleaseView.do?newsId=156782827",
"map_image_url": "https://www.korea.kr/common/download.do?fileId=198558074&tblKey=GMN",
"basis": "절정: 그 수종 잎의 50% 이상이 물든 때. 첫 단풍: 발표에 시작일이 없어 절정 14일 전부터로 추정. 예측 지점이 아닌 명소는 basis에 적은 가장 가까운 예측 지점 날짜를 씀",
"license": "공공누리 제1유형(출처표시) — 정책브리핑 게재본은 '텍스트에 한하여' 1유형, 사진·이미지는 저작권자 허락 필요(지도 이미지 자체 재사용은 확인 필요)",
"coord_source": "한국관광공사 TourAPI(KorService2 searchKeyword2) 좌표; 소리봉(포천)은 광릉숲길 좌표로 근사(가까운 지점 계산용, 지도엔 안 나옴)",
"updated": "2026-10-21",
"spots": [
{
"name": "설악산",
"kind": "maple",
"region": "강원 속초·양양·인제",
"lat": 38.119,
"lon": 128.465,
"peak": "2026-10-20",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "설악산 대청봉"
},
{
"name": "점봉산",
"kind": "maple",
"region": "강원 인제·양양",
"lat": 38.036,
"lon": 128.471,
"peak": "2026-10-21",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "점봉산 곰배령"
},
{
"name": "광덕산",
"kind": "maple",
"region": "강원 화천·경기 포천",
"lat": 38.115,
"lon": 127.439,
"peak": "2026-10-22",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "광덕산(화천)"
},
{
"name": "화악산",
"kind": "maple",
"region": "강원 화천·경기 가평",
"lat": 38.048,
"lon": 127.522,
"peak": "2026-10-20",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "화악산"
},
{
"name": "축령산",
"kind": "maple",
"region": "경기 남양주·가평",
"lat": 37.753,
"lon": 127.309,
"peak": "2026-10-26",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "축령산"
},
{
"name": "용문산",
"kind": "maple",
"region": "경기 양평",
"lat": 37.551,
"lon": 127.569,
"peak": "2026-10-23",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "용문산"
},
{
"name": "수리산",
"kind": "maple",
"region": "경기 군포·안양·안산",
"lat": 37.348,
"lon": 126.901,
"peak": "2026-11-02",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "수리산도립공원"
},
{
"name": "가야산(충남)",
"kind": "maple",
"region": "충남 서산·예산",
"lat": 36.704,
"lon": 126.609,
"peak": "2026-10-31",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "가야산(서산)"
},
{
"name": "소백산",
"kind": "maple",
"region": "충북 단양·경북 영주",
"lat": 36.935,
"lon": 128.457,
"peak": "2026-10-20",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "소백산 천문대"
},
{
"name": "속리산",
"kind": "maple",
"region": "충북 보은·경북 상주",
"lat": 36.517,
"lon": 127.817,
"peak": "2026-10-28",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "속리산국립공원(충북)"
},
{
"name": "계룡산",
"kind": "maple",
"region": "충남 공주·계룡, 대전",
"lat": 36.357,
"lon": 127.232,
"peak": "2026-11-01",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "계룡산국립공원"
},
{
"name": "주왕산",
"kind": "maple",
"region": "경북 청송",
"lat": 36.394,
"lon": 129.142,
"peak": "2026-10-26",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "주왕산국립공원"
},
{
"name": "팔공산",
"kind": "maple",
"region": "대구·경북",
"lat": 35.99,
"lon": 128.696,
"peak": "2026-10-30",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "팔공산국립공원(동화사지구)"
},
{
"name": "가야산(경북)",
"kind": "maple",
"region": "경북 성주·경남 합천",
"lat": 35.8,
"lon": 128.142,
"peak": "2026-10-28",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "가야산국립공원(백운동 지구)"
},
{
"name": "금원산",
"kind": "maple",
"region": "경남 거창",
"lat": 35.731,
"lon": 127.761,
"peak": "2026-10-25",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "금원산"
},
{
"name": "지리산",
"kind": "maple",
"region": "경남·전남·전북",
"lat": 35.304,
"lon": 127.749,
"peak": "2026-10-27",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "지리산 천왕봉"
},
{
"name": "변산반도",
"kind": "maple",
"region": "전북 부안",
"lat": 35.642,
"lon": 126.58,
"peak": "2026-11-04",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "변산반도국립공원"
},
{
"name": "내장산",
"kind": "maple",
"region": "전북 정읍·전남 장성",
"lat": 35.471,
"lon": 126.867,
"peak": "2026-11-04",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "내장산국립공원"
},
{
"name": "월출산",
"kind": "maple",
"region": "전남 영암·강진",
"lat": 34.775,
"lon": 126.722,
"peak": "2026-11-09",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "월출산국립공원"
},
{
"name": "두륜산",
"kind": "maple",
"region": "전남 해남",
"lat": 34.49,
"lon": 126.616,
"peak": "2026-11-11",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "두륜산도립공원"
},
{
"name": "상왕봉",
"kind": "maple",
"region": "전남 완도",
"lat": 34.348,
"lon": 126.693,
"peak": "2026-11-11",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "상왕산"
},
{
"name": "교래곶자왈",
"kind": "maple",
"region": "제주 제주시 조천",
"lat": 33.442,
"lon": 126.667,
"peak": "2026-11-02",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "제주 교래자연휴양림"
},
{
"name": "한라산(1100도로)",
"kind": "maple",
"region": "제주",
"lat": 33.358,
"lon": 126.463,
"peak": "2026-11-06",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "1100고지습지"
},
{
"name": "국립수목원",
"kind": "ginkgo",
"region": "경기 포천",
"lat": 37.75954,
"lon": 127.16892,
"peak": "2026-10-31",
"basis": "산림청 예측(은행나무)",
"coord_point": "국립수목원"
},
{
"name": "물향기수목원",
"kind": "ginkgo",
"region": "경기 오산",
"lat": 37.16737,
"lon": 127.0622,
"peak": "2026-11-06",
"basis": "산림청 예측(은행나무)",
"coord_point": "물향기수목원"
},
{
"name": "강원도립화목원",
"kind": "ginkgo",
"region": "강원 춘천",
"lat": 37.92264,
"lon": 127.72516,
"peak": "2026-10-27",
"basis": "산림청 예측(은행나무)",
"coord_point": "강원도립화목원"
},
{
"name": "미동산수목원",
"kind": "ginkgo",
"region": "충북 청주",
"lat": 36.62743,
"lon": 127.66884,
"peak": "2026-10-29",
"basis": "산림청 예측(은행나무)",
"coord_point": "미동산수목원"
},
{
"name": "금강수목원",
"kind": "ginkgo",
"region": "세종",
"lat": 36.4377,
"lon": 127.23274,
"peak": "2026-11-04",
"basis": "산림청 예측(은행나무)",
"coord_point": "금강수목원"
},
{
"name": "대구수목원",
"kind": "ginkgo",
"region": "대구 달서",
"lat": 35.80265,
"lon": 128.52063,
"peak": "2026-11-04",
"basis": "산림청 예측(은행나무)",
"coord_point": "대구수목원"
},
{
"name": "대아수목원",
"kind": "ginkgo",
"region": "전북 완주",
"lat": 35.97624,
"lon": 127.30039,
"peak": "2026-11-02",
"basis": "산림청 예측(은행나무)",
"coord_point": "대아수목원"
},
{
"name": "경남수목원",
"kind": "ginkgo",
"region": "경남 진주",
"lat": 35.1572,
"lon": 128.29574,
"peak": "2026-11-05",
"basis": "산림청 예측(은행나무)",
"coord_point": "경남수목원"
},
{
"name": "완도수목원",
"kind": "ginkgo",
"region": "전남 완도",
"lat": 34.36065,
"lon": 126.66353,
"peak": "2026-11-12",
"basis": "산림청 예측(은행나무)",
"coord_point": "완도수목원"
},
{
"name": "한라수목원",
"kind": "ginkgo",
"region": "제주 제주",
"lat": 33.46959,
"lon": 126.49324,
"peak": "2026-11-16",
"basis": "산림청 예측(은행나무)",
"coord_point": "한라수목원"
},
{
"name": "북한산",
"kind": "maple",
"region": "서울 강북",
"lat": 37.65831,
"lon": 126.99095,
"peak": "2026-10-26",
"basis": "가장 가까운 산림청 예측 지점(축령산, 단풍나무류) 날짜",
"coord_point": "북한산 백운대(우이동)"
},
{
"name": "도봉산",
"kind": "maple",
"region": "서울 도봉",
"lat": 37.69945,
"lon": 127.01578,
"peak": "2026-10-26",
"basis": "가장 가까운 산림청 예측 지점(축령산, 단풍나무류) 날짜",
"coord_point": "도봉산"
},
{
"name": "남산공원",
"kind": "maple",
"region": "서울 중구",
"lat": 37.55563,
"lon": 126.99222,
"peak": "2026-11-02",
"basis": "가장 가까운 산림청 예측 지점(수리산, 단풍나무류) 날짜",
"coord_point": "남산공원(서울)"
},
{
"name": "창덕궁",
"kind": "maple",
"region": "서울 종로",
"lat": 37.5777,
"lon": 126.99024,
"peak": "2026-11-02",
"basis": "가장 가까운 산림청 예측 지점(수리산, 단풍나무류) 날짜",
"coord_point": "창덕궁 낙선재"
},
{
"name": "화담숲",
"kind": "maple",
"region": "경기 광주",
"lat": 37.34076,
"lon": 127.28942,
"peak": "2026-10-23",
"basis": "가장 가까운 산림청 예측 지점(용문산, 단풍나무류) 날짜",
"coord_point": "화담숲"
},
{
"name": "오대산",
"kind": "maple",
"region": "강원 평창",
"lat": 37.78652,
"lon": 128.56441,
"peak": "2026-10-21",
"basis": "가장 가까운 산림청 예측 지점(점봉산, 단풍나무류) 날짜",
"coord_point": "상원사(오대산)"
},
{
"name": "치악산",
"kind": "maple",
"region": "강원 원주",
"lat": 37.408,
"lon": 128.0455,
"peak": "2026-10-23",
"basis": "가장 가까운 산림청 예측 지점(용문산, 단풍나무류) 날짜",
"coord_point": "치악산 구룡자동차야영장"
},
{
"name": "덕유산",
"kind": "maple",
"region": "전북 무주",
"lat": 35.89192,
"lon": 127.74295,
"peak": "2026-10-25",
"basis": "가장 가까운 산림청 예측 지점(금원산, 단풍나무류) 날짜",
"coord_point": "덕유산 향적봉"
},
{
"name": "대둔산",
"kind": "maple",
"region": "충남 논산·전북 완주",
"lat": 36.14381,
"lon": 127.30481,
"peak": "2026-11-01",
"basis": "가장 가까운 산림청 예측 지점(계룡산, 단풍나무류) 날짜",
"coord_point": "대둔산 도립공원 수락캠핑장"
},
{
"name": "마이산",
"kind": "maple",
"region": "전북 진안",
"lat": 35.75846,
"lon": 127.41119,
"peak": "2026-10-25",
"basis": "가장 가까운 산림청 예측 지점(금원산, 단풍나무류) 날짜",
"coord_point": "마이산 탑사"
},
{
"name": "강천산",
"kind": "maple",
"region": "전북 순창",
"lat": 35.40879,
"lon": 127.0675,
"peak": "2026-11-04",
"basis": "가장 가까운 산림청 예측 지점(내장산, 단풍나무류) 날짜",
"coord_point": "강천산 군립공원"
},
{
"name": "선운산",
"kind": "maple",
"region": "전북 고창",
"lat": 35.49769,
"lon": 126.57953,
"peak": "2026-11-04",
"basis": "가장 가까운 산림청 예측 지점(변산반도, 단풍나무류) 날짜",
"coord_point": "도솔계곡(선운산)"
},
{
"name": "백양사",
"kind": "maple",
"region": "전남 장성",
"lat": 35.43966,
"lon": 126.88372,
"peak": "2026-11-04",
"basis": "가장 가까운 산림청 예측 지점(내장산, 단풍나무류) 날짜",
"coord_point": "백양사"
},
{
"name": "무등산",
"kind": "maple",
"region": "광주 동구",
"lat": 35.13148,
"lon": 126.981,
"peak": "2026-11-04",
"basis": "가장 가까운 산림청 예측 지점(내장산, 단풍나무류) 날짜",
"coord_point": "덕산너덜(무등산)"
},
{
"name": "청량산",
"kind": "maple",
"region": "경북 봉화",
"lat": 36.78866,
"lon": 128.89501,
"peak": "2026-10-20",
"basis": "가장 가까운 산림청 예측 지점(소백산, 단풍나무류) 날짜",
"coord_point": "청량산도립공원"
},
{
"name": "가지산",
"kind": "maple",
"region": "경남 밀양·울산 울주",
"lat": 35.58033,
"lon": 128.98046,
"peak": "2026-10-30",
"basis": "가장 가까운 산림청 예측 지점(팔공산, 단풍나무류) 날짜",
"coord_point": "가지산도립공원(밀양)"
},
{
"name": "반계리 은행나무",
"kind": "ginkgo",
"region": "강원 원주",
"lat": 37.29388,
"lon": 127.78795,
"peak": "2026-10-29",
"basis": "가장 가까운 산림청 예측 지점(용문산, 은행나무) 날짜",
"coord_point": "반계리 은행나무"
},
{
"name": "남이섬",
"kind": "ginkgo",
"region": "강원 춘천",
"lat": 37.79627,
"lon": 127.52549,
"peak": "2026-10-25",
"basis": "가장 가까운 산림청 예측 지점(축령산, 은행나무) 날짜",
"coord_point": "남이섬"
},
{
"name": "서울숲",
"kind": "ginkgo",
"region": "서울 성동",
"lat": 37.54307,
"lon": 127.0418,
"peak": "2026-11-04",
"basis": "가장 가까운 산림청 예측 지점(수리산, 은행나무) 날짜",
"coord_point": "서울숲"
},
{
"name": "덕수궁 돌담길",
"kind": "ginkgo",
"region": "서울 중구",
"lat": 37.56608,
"lon": 126.97489,
"peak": "2026-11-04",
"basis": "가장 가까운 산림청 예측 지점(수리산, 은행나무) 날짜",
"coord_point": "덕수궁 돌담길"
},
{
"name": "성균관 명륜당",
"kind": "ginkgo",
"region": "서울 종로",
"lat": 37.5861,
"lon": 126.9957,
"peak": "2026-10-31",
"basis": "가장 가까운 산림청 예측 지점(국립수목원, 은행나무) 날짜",
"coord_point": "성균관 명륜당"
},
{
"name": "용문사 은행나무",
"kind": "ginkgo",
"region": "경기 양평",
"lat": 37.55022,
"lon": 127.57169,
"peak": "2026-10-29",
"basis": "가장 가까운 산림청 예측 지점(용문산, 은행나무) 날짜",
"coord_point": "용문사 은행나무"
},
{
"name": "곡교천 은행나무길",
"kind": "ginkgo",
"region": "충남 아산",
"lat": 36.79955,
"lon": 127.01683,
"peak": "2026-10-26",
"basis": "가장 가까운 산림청 예측 지점(가야산(충남), 은행나무) 날짜",
"coord_point": "곡교천 은행나무길"
},
{
"name": "현충사",
"kind": "ginkgo",
"region": "충남 아산",
"lat": 36.80655,
"lon": 127.0312,
"peak": "2026-10-26",
"basis": "가장 가까운 산림청 예측 지점(가야산(충남), 은행나무) 날짜",
"coord_point": "현충사"
},
{
"name": "문광저수지",
"kind": "ginkgo",
"region": "충북 괴산",
"lat": 36.76832,
"lon": 127.75077,
"peak": "2026-10-29",
"basis": "가장 가까운 산림청 예측 지점(미동산수목원, 은행나무) 날짜",
"coord_point": "문광저수지"
},
{
"name": "홍천 은행나무숲",
"kind": "ginkgo",
"region": "강원 홍천",
"lat": 37.83213,
"lon": 128.47071,
"peak": "2026-10-27",
"basis": "가장 가까운 산림청 예측 지점(강원도립화목원, 은행나무) 날짜",
"coord_point": "홍천 은행나무숲"
},
{
"name": "운곡서원",
"kind": "ginkgo",
"region": "경북 경주",
"lat": 35.941,
"lon": 129.30208,
"peak": "2026-10-29",
"basis": "가장 가까운 산림청 예측 지점(주왕산, 은행나무) 날짜",
"coord_point": "운곡서원"
},
{
"name": "도리마을 은행나무숲",
"kind": "ginkgo",
"region": "경북 경주",
"lat": 35.9185,
"lon": 129.0908,
"peak": "2026-11-04",
"basis": "가장 가까운 산림청 예측 지점(대구수목원, 은행나무) 날짜",
"coord_point": "도리마을 은행나무숲"
},
{
"name": "청라 은행마을",
"kind": "ginkgo",
"region": "충남 보령",
"lat": 36.42721,
"lon": 126.6756,
"peak": "2026-10-26",
"basis": "가장 가까운 산림청 예측 지점(가야산(충남), 은행나무) 날짜",
"coord_point": "청라 은행마을"
},
{
"name": "전주향교",
"kind": "ginkgo",
"region": "전북 전주",
"lat": 35.81295,
"lon": 127.15654,
"peak": "2026-11-02",
"basis": "가장 가까운 산림청 예측 지점(대아수목원, 은행나무) 날짜",
"coord_point": "전주향교"
},
{
"name": "부석사",
"kind": "ginkgo",
"region": "경북 영주",
"lat": 36.9984,
"lon": 128.6871,
"peak": "2026-10-29",
"basis": "가장 가까운 산림청 예측 지점(주왕산, 은행나무) 날짜",
"coord_point": "부석사"
},
{
"name": "보석사",
"kind": "ginkgo",
"region": "충남 금산",
"lat": 36.05436,
"lon": 127.47587,
"peak": "2026-11-02",
"basis": "가장 가까운 산림청 예측 지점(대아수목원, 은행나무) 날짜",
"coord_point": "보석사"
}
]
}
+166
View File
@@ -0,0 +1,166 @@
{
"busan/jung": {
"outdoor": [
"40계단 문화관광테마거리",
"부산대교",
"광복로패션거리"
],
"indoor": [],
"sunset": []
},
"busan/seo": {
"outdoor": [
"BIFF 광장",
"누리바라기전망대",
"부산 송도해수욕장"
],
"indoor": [],
"sunset": []
},
"busan/dong": {
"outdoor": [
"범일 이중섭거리",
"이중섭전망대",
"책마루전망대"
],
"indoor": [],
"sunset": []
},
"busan/yeongdo": {
"outdoor": [
"감지해변",
"아미르공원",
"영도 하늘전망대"
],
"indoor": [
"아르떼뮤지엄 부산"
],
"sunset": [
"감지해변",
"영도 하늘전망대"
]
},
"busan/busanjin": {
"outdoor": [
"부산시민공원",
"부산진 별빛산책길",
"부산정중앙공원"
],
"indoor": [],
"sunset": []
},
"busan/dongnae": {
"outdoor": [
"금강공원",
"동래온천길(온천천 카페거리)",
"온천천시민공원"
],
"indoor": [],
"sunset": []
},
"busan/nam": {
"outdoor": [
"대연수목전시원",
"우암동 도시숲",
"평화공원"
],
"indoor": [],
"sunset": []
},
"busan/buk": {
"outdoor": [
"백양산 웰빙숲"
],
"indoor": [],
"sunset": []
},
"busan/haeundae": {
"outdoor": [
"동백공원",
"부산 영화의 거리",
"부산엑스더스카이"
],
"indoor": [
"갤러리이알디 부산",
"씨라이프부산아쿠아리움"
],
"sunset": [
"청사포 다릿돌전망대",
"해월전망대"
]
},
"busan/saha": {
"outdoor": [
"[부산 갈맷길] 5코스",
"가덕도외양포전망대",
"다대포해수욕장"
],
"indoor": [
"부산현대미술관"
],
"sunset": [
"낙조정",
"다대포해수욕장"
]
},
"busan/geumjeong": {
"outdoor": [
"가톨릭 특성화 거리",
"금강식물원",
"오륜대전망대"
],
"indoor": [
"킴스아트필드미술관"
],
"sunset": []
},
"busan/gangseo": {
"outdoor": [
"강서체육공원",
"구포만세거리",
"금빛노을브릿지"
],
"indoor": [],
"sunset": [
"금빛노을브릿지"
]
},
"busan/yeonje": {
"outdoor": [
"망미단길",
"황령산 전망대",
"황령산레포츠공원"
],
"indoor": [],
"sunset": []
},
"busan/suyeong": {
"outdoor": [
"광안리해변 테마거리",
"광안리해수욕장",
"민락해변공원"
],
"indoor": [
"뮤지엄 원"
],
"sunset": [
"삼익비치수변공원"
]
},
"busan/sasang": {
"outdoor": [],
"indoor": [],
"sunset": []
},
"busan/gijang": {
"outdoor": [
"곰내연밭",
"나사해변(나사리해수욕장)",
"소두방공원"
],
"indoor": [],
"sunset": [
"나사해변(나사리해수욕장)"
]
}
}
+160
View File
@@ -0,0 +1,160 @@
{
"chungbuk/cheongju": {
"outdoor": [
"금강로하스 대청공원 (암석식물원)",
"금강로하스대청공원",
"대청댐 전망대"
],
"indoor": [
"청주시립대청호미술관",
"청주시립미술관"
],
"sunset": []
},
"chungbuk/cheongju/sangdang": {
"outdoor": [
"금강로하스 대청공원 (암석식물원)",
"금강로하스대청공원",
"대청댐 전망대"
],
"indoor": [
"청주시립대청호미술관"
],
"sunset": []
},
"chungbuk/cheongju/seowon": {
"outdoor": [
"상당공원",
"서문풍물야시장&서문시장삼겹살거리",
"솔밭공원(청주)"
],
"indoor": [
"청주시립미술관"
],
"sunset": []
},
"chungbuk/cheongju/heungdeok": {
"outdoor": [
"베어트리파크",
"조천연꽃공원",
"조치원테마거리"
],
"indoor": [],
"sunset": []
},
"chungbuk/cheongju/cheongwon": {
"outdoor": [
"삼일공원",
"수암골 카페거리",
"수암골전망대"
],
"indoor": [
"국립현대미술관 청주",
"네오아트센터"
],
"sunset": []
},
"chungbuk/chungju": {
"outdoor": [
"[충주 풍경길] 종댕이길",
"대가미체육공원",
"목계솔밭(충주)"
],
"indoor": [
"성마루미술관",
"충주아쿠아리움"
],
"sunset": []
},
"chungbuk/jecheon": {
"outdoor": [
"교동민화마을",
"수도산도시숲",
"용추폭포 유리전망대"
],
"indoor": [],
"sunset": []
},
"chungbuk/boeun": {
"outdoor": [
"말티재 전망대(말티고개)",
"상주 맥문동 솔숲",
"속리산 산채비빔밥 거리"
],
"indoor": [
"청목화랑 전통낙화연구소"
],
"sunset": []
},
"chungbuk/okcheon": {
"outdoor": [
"옥천금강수변 친수공원"
],
"indoor": [],
"sunset": []
},
"chungbuk/yeongdong": {
"outdoor": [
"김천물소리생태숲",
"레인보우식물원",
"상춘정"
],
"indoor": [],
"sunset": [
"함벽정"
]
},
"chungbuk/jeungpyeong": {
"outdoor": [
"별천지공원",
"보강천미루나무숲",
"증평 좌구산 명상구름다리"
],
"indoor": [],
"sunset": []
},
"chungbuk/jincheon": {
"outdoor": [
"진천 이팝나무길",
"초평호 미르309 출렁다리",
"화랑공원(진천)"
],
"indoor": [],
"sunset": []
},
"chungbuk/goesan": {
"outdoor": [
"괴산 오작교",
"괴산 올갱이국 거리",
"괴산호"
],
"indoor": [
"충북아쿠아리움"
],
"sunset": []
},
"chungbuk/eumseong": {
"outdoor": [
"봉학골산림욕장",
"설성공원",
"응천공원"
],
"indoor": [],
"sunset": [
"백야둘레길"
]
},
"chungbuk/danyang": {
"outdoor": [
"[청풍호자드락길 5코스] 옥순봉길",
"단양 상상의 거리",
"도담정원"
],
"indoor": [
"단양 다누리아쿠아리움"
],
"sunset": [
"양방산전망대"
]
}
}
+190
View File
@@ -0,0 +1,190 @@
{
"chungnam/cheonan": {
"outdoor": [
"물총새공원",
"아름다운정원화수목",
"천안 병천순대거리"
],
"indoor": [
"갤러리현",
"리각미술관"
],
"sunset": []
},
"chungnam/cheonan/dongnam": {
"outdoor": [
"물총새공원",
"아름다운정원화수목",
"천안 병천순대거리"
],
"indoor": [
"갤러리현",
"리각미술관"
],
"sunset": []
},
"chungnam/cheonan/seobuk": {
"outdoor": [],
"indoor": [],
"sunset": []
},
"chungnam/gongju": {
"outdoor": [
"공주 고마나루",
"나태주 골목길",
"이안숲속"
],
"indoor": [
"아트센터고마",
"임립미술관"
],
"sunset": []
},
"chungnam/boryeong": {
"outdoor": [
"대천해수욕장",
"보령 노을광장",
"보령 무궁화수목원"
],
"indoor": [],
"sunset": [
"독산해수욕장",
"보령 노을광장"
]
},
"chungnam/asan": {
"outdoor": [
"덕암교",
"아산문화공원",
"아산호"
],
"indoor": [
"당림미술관",
"뮤지엄 호두"
],
"sunset": [
"아산만방조제"
]
},
"chungnam/seosan": {
"outdoor": [
"[서산 아라메길] 구도 범머리길",
"벌천포해수욕장",
"쉼이있는정원"
],
"indoor": [],
"sunset": [
"황금산몽돌해변"
]
},
"chungnam/nonsan": {
"outdoor": [
"강경근대거리",
"논산 시민가족공원",
"논산 탑정호 출렁다리"
],
"indoor": [],
"sunset": []
},
"chungnam/gyeryong": {
"outdoor": [
"무궁화학습원"
],
"indoor": [],
"sunset": []
},
"chungnam/dangjin": {
"outdoor": [
"[서산 아라메길] 삼길 나루길",
"계남해변",
"면천읍성 골목길"
],
"indoor": [
"아미미술관",
"여미갤러리"
],
"sunset": [
"마섬포구",
"왜목마을 해수욕장"
]
},
"chungnam/geumsan": {
"outdoor": [
"기러기공원",
"월영산 출렁다리"
],
"indoor": [],
"sunset": [
"대둔산도립공원(금산)"
]
},
"chungnam/buyeo": {
"outdoor": [
"나래공원",
"백제교",
"백마강생활체육공원"
],
"indoor": [],
"sunset": [
"성당포구마을"
]
},
"chungnam/seocheon": {
"outdoor": [
"갈목해변",
"서천식물예술원",
"장항 스카이워크 (기벌포 해전 전망대)"
],
"indoor": [],
"sunset": [
"갈목해변",
"마량포구"
]
},
"chungnam/cheongyang": {
"outdoor": [
"고운식물원",
"광시한우거리",
"천장호"
],
"indoor": [],
"sunset": []
},
"chungnam/hongseong": {
"outdoor": [
"광천생활체육공원",
"그림같은 수목원(그림이 있는 정원)",
"남당노을전망대"
],
"indoor": [],
"sunset": [
"궁리포구",
"남당노을전망대"
]
},
"chungnam/yesan": {
"outdoor": [
"선장포노을공원",
"세계꽃식물원",
"예당호 전망대"
],
"indoor": [],
"sunset": [
"선장포노을공원"
]
},
"chungnam/taean": {
"outdoor": [
"[솔향기길] 4코스",
"간월호 쉼터공원",
"갈음이해수욕장"
],
"indoor": [
"오마이갤러리"
],
"sunset": [
"기지포해수욕장",
"꽃지해수욕장"
]
}
}
+97
View File
@@ -0,0 +1,97 @@
{
"daegu/jung": {
"outdoor": [
"김광석다시그리기길",
"대구 동성로거리",
"대구 진골목"
],
"indoor": [
"대백프라자갤러리",
"동원화랑"
],
"sunset": []
},
"daegu/dong": {
"outdoor": [
"대구 도동 측백나무 숲",
"대구 평화시장 닭똥집 골목",
"망우당공원"
],
"indoor": [
"대구 아쿠아리움"
],
"sunset": []
},
"daegu/seo": {
"outdoor": [
"감삼못공원",
"반고개 무침회 골목",
"성당못"
],
"indoor": [],
"sunset": []
},
"daegu/nam": {
"outdoor": [
"가창 찐빵 골목",
"고산골",
"고산골 메타쉐콰이어길"
],
"indoor": [],
"sunset": []
},
"daegu/buk": {
"outdoor": [
"3·1만세운동길",
"꽃보라동산",
"달성공원"
],
"indoor": [
"경북대학교 미술관"
],
"sunset": []
},
"daegu/suseong": {
"outdoor": [
"율하체육공원"
],
"indoor": [
"대구간송미술관",
"대구미술관"
],
"sunset": []
},
"daegu/dalseo": {
"outdoor": [
"강정고령보",
"대구 세천늪테마정원",
"선사시대로 테마거리"
],
"indoor": [],
"sunset": [
"앞산 해넘이전망대"
]
},
"daegu/dalseong": {
"outdoor": [
"다산 좌학리 은행나무 숲",
"달성노을공원",
"달성보전망대"
],
"indoor": [],
"sunset": [
"달성노을공원",
"달성보전망대"
]
},
"daegu/gunwi": {
"outdoor": [
"개천지와 조성지",
"일연공원"
],
"indoor": [
"안계미술관"
],
"sunset": []
}
}
+51
View File
@@ -0,0 +1,51 @@
{
"daejeon/dong": {
"outdoor": [
"대동하늘공원",
"인쇄거리",
"하늘물빛정원"
],
"indoor": [],
"sunset": []
},
"daejeon/jung": {
"outdoor": [
"대전 치유의 숲",
"대흥동 문화예술의거리",
"보문산큰나무전망대"
],
"indoor": [
"대전아쿠아리움"
],
"sunset": []
},
"daejeon/seo": {
"outdoor": [
"남선공원",
"엑스포다리",
"한밭수목원"
],
"indoor": [
"대전 엑스포 아쿠아리움",
"대전시립미술관"
],
"sunset": []
},
"daejeon/yuseong": {
"outdoor": [
"유림공원",
"유성온천공원"
],
"indoor": [],
"sunset": []
},
"daejeon/daedeok": {
"outdoor": [
"대청호",
"명상정원",
"장동만남공원"
],
"indoor": [],
"sunset": []
}
}
+197
View File
@@ -0,0 +1,197 @@
{
"gangwon/chuncheon": {
"outdoor": [
"강원특별자치도립화목원",
"건봉령승호대",
"구봉산 전망대 카페거리"
],
"indoor": [
"춘천미술관"
],
"sunset": [
"구봉산 전망대 카페거리"
]
},
"gangwon/wonju": {
"outdoor": [
"[원주 소풍길] 1코스 운곡솔바람숲길",
"단관공원",
"동화마을수목원"
],
"indoor": [
"뮤지엄산",
"빙하미술관"
],
"sunset": []
},
"gangwon/gangneung": {
"outdoor": [
"강릉 명주동 거리",
"강릉 솔향수목원",
"강릉 안목해맞이공원"
],
"indoor": [
"강릉시립미술관 교동",
"경포 아쿠아리움"
],
"sunset": [
"강릉항여객터미널"
]
},
"gangwon/donghae": {
"outdoor": [
"감추해변",
"냉천공원",
"도째비골 해랑전망대"
],
"indoor": [],
"sunset": []
},
"gangwon/taebaek": {
"outdoor": [
"구와우마을",
"삼방동 전망대",
"봉화 금강소나무림"
],
"indoor": [],
"sunset": []
},
"gangwon/sokcho": {
"outdoor": [
"교암해변",
"닭전 골목",
"대포항 전망대"
],
"indoor": [
"내설악 백공미술관",
"바우지움 조각미술관"
],
"sunset": [
"영랑호"
]
},
"gangwon/samcheok": {
"outdoor": [
"궁촌해변(궁촌해수욕장)",
"비치조각공원",
"삼척미로정원"
],
"indoor": [],
"sunset": []
},
"gangwon/hongcheon": {
"outdoor": [
"강재구공원",
"무궁화수목원",
"화로구이 골목"
],
"indoor": [],
"sunset": []
},
"gangwon/hoengseong": {
"outdoor": [
"황장목 숲길",
"횡성호"
],
"indoor": [
"미술관 자작나무숲"
],
"sunset": []
},
"gangwon/yeongwol": {
"outdoor": [
"금강공원에코스튜디오",
"한반도지형전망대"
],
"indoor": [
"국제현대미술관",
"제이큐브미술관"
],
"sunset": []
},
"gangwon/pyeongchang": {
"outdoor": [
"[효석문학100리길 4코스] 옛길따라 평창강 가는길",
"고랭길",
"청옥산전망대"
],
"indoor": [
"젊은달 와이파크"
],
"sunset": [
"육백마지기"
]
},
"gangwon/jeongseon": {
"outdoor": [
"로미지안가든",
"병방치 스카이워크"
],
"indoor": [
"진부문화예술창작스튜디오"
],
"sunset": []
},
"gangwon/cheorwon": {
"outdoor": [
"소이산 생태숲 녹색길",
"승리전망대",
"승일교"
],
"indoor": [],
"sunset": []
},
"gangwon/hwacheon": {
"outdoor": [
"비목공원",
"칠성전망대",
"파로호(화천)"
],
"indoor": [
"토속어류생태체험관"
],
"sunset": []
},
"gangwon/yanggu": {
"outdoor": [
"국립DMZ자생식물원",
"소양호(양구)",
"용머리 공원"
],
"indoor": [
"박수근미술관"
],
"sunset": []
},
"gangwon/inje": {
"outdoor": [
"소양호(인제)",
"원대리 자작나무 숲 (속삭이는 자작나무 숲)"
],
"indoor": [
"공립인제내설악미술관",
"목공예 갤러리"
],
"sunset": []
},
"gangwon/goseong": {
"outdoor": [
"가진해변",
"거진등대해맞이공원",
"고성 육송정 홍교"
],
"indoor": [
"진부령미술관"
],
"sunset": []
},
"gangwon/yangyang": {
"outdoor": [
"갯마을해변",
"양리단길",
"현산공원"
],
"indoor": [],
"sunset": []
}
}
+58
View File
@@ -0,0 +1,58 @@
{
"gwangju/dong": {
"outdoor": [
"광주 예술의 거리",
"광주공원",
"사직공원전망타워"
],
"indoor": [
"광주 의재미술관",
"드영미술관"
],
"sunset": [
"서석대"
]
},
"gwangju/seo": {
"outdoor": [
"금남로",
"풍암호수"
],
"indoor": [
"광주미디어아트플랫폼 GMAP",
"하정웅미술관(광주)"
],
"sunset": []
},
"gwangju/nam": {
"outdoor": [
"광주시립수목원",
"나주 은행나무 수목원"
],
"indoor": [],
"sunset": []
},
"gwangju/buk": {
"outdoor": [
"광주시민의숲",
"시리단길",
"쌍암공원"
],
"indoor": [
"광주시립미술관",
"시화문화마을 금봉미술관"
],
"sunset": []
},
"gwangju/gwangsan": {
"outdoor": [
"광주 송정동 떡갈비 골목",
"상무시민공원",
"휴심정"
],
"indoor": [
"동곡미술관"
],
"sunset": []
}
}
+236
View File
@@ -0,0 +1,236 @@
{
"gyeongbuk/pohang": {
"outdoor": [
"구룡포 말목장성탐방로",
"구룡포 일본인 가옥거리",
"구룡포해수욕장"
],
"indoor": [
"포항시립미술관"
],
"sunset": []
},
"gyeongbuk/pohang/nam": {
"outdoor": [
"구룡포 말목장성탐방로",
"구룡포 일본인 가옥거리",
"구룡포해수욕장"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/pohang/buk": {
"outdoor": [
"경상북도수목원",
"덕수공원",
"삼정해수욕장"
],
"indoor": [
"포항시립미술관"
],
"sunset": []
},
"gyeongbuk/gyeongju": {
"outdoor": [
"건천편백나무숲",
"경북천년숲정원",
"경주 금리단길"
],
"indoor": [
"솔거미술관",
"오아르미술관"
],
"sunset": [
"금장대"
]
},
"gyeongbuk/gimcheon": {
"outdoor": [
"부항댐 출렁다리"
],
"indoor": [
"김천시립미술관"
],
"sunset": []
},
"gyeongbuk/andong": {
"outdoor": [
"그라스원",
"안동시장 찜닭골목",
"월영교"
],
"indoor": [
"송강미술관"
],
"sunset": []
},
"gyeongbuk/gumi": {
"outdoor": [
"구미 금리단길",
"구미낙동강체육공원",
"동락신나루"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/yeongju": {
"outdoor": [
"구성공원",
"무섬 외나무다리",
"신라식물원"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/yeongcheon": {
"outdoor": [
"군위 화산산성 전망대",
"영천댐하류공원",
"영천역 광장"
],
"indoor": [
"시안미술관"
],
"sunset": []
},
"gyeongbuk/sangju": {
"outdoor": [
"경천섬(경천섬공원)",
"낙강교",
"의성 낙단보 수변공원"
],
"indoor": [],
"sunset": [
"경천섬(경천섬공원)"
]
},
"gyeongbuk/mungyeong": {
"outdoor": [
"모전공원",
"봉명산 출렁다리",
"뿅뿅다리"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/gyeongsan": {
"outdoor": [
"남매공원",
"망향정",
"자인계정숲(경산 자인의 계정숲)"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/uiseong": {
"outdoor": [
"달빛공원"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/cheongsong": {
"outdoor": [
"목계솔밭(청송)",
"산소카페 청송정원",
"소헌공원"
],
"indoor": [
"군립청송야송미술관"
],
"sunset": []
},
"gyeongbuk/yeongyang": {
"outdoor": [
"금강소나무생태경영림",
"영양 자작나무숲",
"한마음광장"
],
"indoor": [],
"sunset": [
"선바위"
]
},
"gyeongbuk/yeongdeok": {
"outdoor": [
"경정해수욕장",
"등기산스카이워크",
"영덕해맞이공원"
],
"indoor": [],
"sunset": [
"영덕조각공원"
]
},
"gyeongbuk/cheongdo": {
"outdoor": [],
"indoor": [],
"sunset": []
},
"gyeongbuk/goryeong": {
"outdoor": [
"가야산 야생화식물원",
"개경포기념공원",
"고령 신촌숲"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/seongju": {
"outdoor": [
"성주별고을체육공원"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/chilgok": {
"outdoor": [
"가산수피아",
"칠곡보 생태공원",
"칠곡평화전망대"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/yecheon": {
"outdoor": [
"가오실공원",
"만송정 숲",
"안동 장승공원"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/bonghwa": {
"outdoor": [
"국립백두대간수목원",
"범바위 전망대",
"워낭소리공원"
],
"indoor": [],
"sunset": []
},
"gyeongbuk/uljin": {
"outdoor": [
"구산해수욕장",
"연호공원",
"울진은어다리"
],
"indoor": [
"울진아쿠아리움"
],
"sunset": []
},
"gyeongbuk/ulleung": {
"outdoor": [
"남서일몰전망대",
"내수전몽돌해변",
"성인봉 원시림 (울릉도, 독도 국가지질공원)"
],
"indoor": [],
"sunset": [
"남서일몰전망대",
"석포일출일몰전망대"
]
}
}
+602
View File
@@ -0,0 +1,602 @@
{
"gyeonggi/suwon": {
"outdoor": [
"당수체육공원",
"나혜석거리",
"영흥수목원"
],
"indoor": [
"드림아트스페이스",
"아쿠아플라넷 광교"
],
"sunset": [
"일월호수공원"
]
},
"gyeonggi/suwon/jangan": {
"outdoor": [
"노송지대",
"만석거공원",
"왕의 골목여행"
],
"indoor": [
"수원시립만석전시관"
],
"sunset": []
},
"gyeonggi/suwon/gwonseon": {
"outdoor": [
"당수체육공원",
"대부둑공원",
"서호공원"
],
"indoor": [
"드림아트스페이스"
],
"sunset": [
"일월호수공원"
]
},
"gyeonggi/suwon/paldal": {
"outdoor": [
"광교 프라이부르크전망대",
"광교중앙공원",
"수원 공방거리"
],
"indoor": [
"수원시립미술관",
"아쿠아플라넷 광교"
],
"sunset": []
},
"gyeonggi/suwon/yeongtong": {
"outdoor": [
"고렴공원",
"나혜석거리",
"영흥수목원"
],
"indoor": [],
"sunset": []
},
"gyeonggi/seongnam": {
"outdoor": [
"낙생대공원",
"분당 정자동 카페거리",
"남한산성 탐방로"
],
"indoor": [
"나폴레옹갤러리",
"문아트그라운드 뮤지엄"
],
"sunset": []
},
"gyeonggi/seongnam/sujeong": {
"outdoor": [
"남한산성 탐방로",
"단대동 닭죽촌",
"사기막골근린공원"
],
"indoor": [],
"sunset": []
},
"gyeonggi/seongnam/jungwon": {
"outdoor": [
"대원공원",
"신구대학교식물원",
"수진공원"
],
"indoor": [],
"sunset": []
},
"gyeonggi/seongnam/bundang": {
"outdoor": [
"낙생대공원",
"분당 정자동 카페거리",
"능골공원"
],
"indoor": [
"나폴레옹갤러리",
"문아트그라운드 뮤지엄"
],
"sunset": []
},
"gyeonggi/uijeongbu": {
"outdoor": [
"경기도청북부청사역 하부 맨발황톳길",
"마장호수",
"마장호수 출렁다리"
],
"indoor": [
"양주시립민복진미술관"
],
"sunset": []
},
"gyeonggi/anyang": {
"outdoor": [
"가막들공원",
"동편마을 카페거리",
"백운호수"
],
"indoor": [],
"sunset": []
},
"gyeonggi/anyang/manan": {
"outdoor": [
"병목안 시민공원",
"안양중앙시장 곱창골목",
"삼덕공원"
],
"indoor": [],
"sunset": []
},
"gyeonggi/anyang/dongan": {
"outdoor": [
"가막들공원",
"동편마을 카페거리",
"백운호수"
],
"indoor": [],
"sunset": []
},
"gyeonggi/bucheon": {
"outdoor": [
"남부수자원생태공원",
"푸른수목원",
"까치울음식테마마을"
],
"indoor": [
"부천아트벙커B39"
],
"sunset": []
},
"gyeonggi/bucheon/wonmi": {
"outdoor": [
"무릉도원수목원",
"부천 원미공원",
"부천 중앙공원"
],
"indoor": [],
"sunset": []
},
"gyeonggi/bucheon/sosa": {
"outdoor": [
"남부수자원생태공원",
"푸른수목원",
"비둘기공원"
],
"indoor": [],
"sunset": []
},
"gyeonggi/bucheon/ojeong": {
"outdoor": [
"까치울음식테마마을",
"도당공원",
"롯데몰 김포공항점스카이파크"
],
"indoor": [
"부천아트벙커B39"
],
"sunset": []
},
"gyeonggi/gwangmyeong": {
"outdoor": [
"개봉유수지 생태공원",
"광명가구문화의거리",
"도덕산 출렁다리"
],
"indoor": [
"아트센터 예술의 시간"
],
"sunset": []
},
"gyeonggi/pyeongtaek": {
"outdoor": [
"고덕수변공원",
"바람새마을 소풍정원",
"모곡근린공원"
],
"indoor": [],
"sunset": [
"칠곡호수공원"
]
},
"gyeonggi/dongducheon": {
"outdoor": [
"감악산 출렁다리",
"배꼽다리"
],
"indoor": [],
"sunset": []
},
"gyeonggi/ansan": {
"outdoor": [
"바다향기수목원",
"서해안 황금해안길",
"성포예술공원"
],
"indoor": [
"경기도미술관",
"김홍도미술관"
],
"sunset": [
"누에섬 등대전망대",
"송산그린시티전망대"
]
},
"gyeonggi/ansan/sangnok": {
"outdoor": [
"노적봉공원",
"댕이골 전통음식거리",
"반월호수"
],
"indoor": [
"김홍도미술관"
],
"sunset": []
},
"gyeonggi/ansan/danwon": {
"outdoor": [
"바다향기수목원",
"서해안 황금해안길",
"성포예술공원"
],
"indoor": [
"경기도미술관"
],
"sunset": [
"누에섬 등대전망대",
"송산그린시티전망대"
]
},
"gyeonggi/goyang": {
"outdoor": [
"도래울바람물공원",
"행주산성먹거리촌",
"선인장다육식물연구소"
],
"indoor": [
"매직플로우",
"아쿠아플라넷 일산"
],
"sunset": []
},
"gyeonggi/goyang/deogyang": {
"outdoor": [
"도래울바람물공원",
"행주산성먹거리촌",
"성라공원"
],
"indoor": [
"매직플로우"
],
"sunset": []
},
"gyeonggi/goyang/ilsandong": {
"outdoor": [
"밤리단길",
"앤티크거리 보넷길",
"풍동 애니골"
],
"indoor": [
"고양아람누리 아람미술관"
],
"sunset": []
},
"gyeonggi/goyang/ilsanseo": {
"outdoor": [
"고양 피크닉시민공원",
"선인장다육식물연구소",
"일산 대화동 먹자골목"
],
"indoor": [
"갤러리박영",
"아쿠아플라넷 일산"
],
"sunset": []
},
"gyeonggi/gwacheon": {
"outdoor": [
"과천야생화자연학습장",
"렛츠런파크 서울 포니랜드",
"뿌리깊은나무숲"
],
"indoor": [
"가원미술관",
"국립현대미술관 과천"
],
"sunset": []
},
"gyeonggi/guri": {
"outdoor": [
"구리역공원",
"구리타워",
"돌다리 곱창골목"
],
"indoor": [],
"sunset": []
},
"gyeonggi/namyangju": {
"outdoor": [
"물맑음수목원"
],
"indoor": [
"구하우스미술관",
"도자기체험미술관 비즘"
],
"sunset": []
},
"gyeonggi/osan": {
"outdoor": [
"맑음터공원",
"물향기수목원",
"운암뜰 한식거리"
],
"indoor": [
"오산시립미술관"
],
"sunset": []
},
"gyeonggi/siheung": {
"outdoor": [
"미생의 다리",
"산들공원",
"용도수목원"
],
"indoor": [],
"sunset": []
},
"gyeonggi/gunpo": {
"outdoor": [
"매쟁이골",
"산본중앙공원"
],
"indoor": [],
"sunset": []
},
"gyeonggi/uiwang": {
"outdoor": [],
"indoor": [],
"sunset": []
},
"gyeonggi/hanam": {
"outdoor": [
"귀여리 벚꽃길",
"물의 정원",
"양서문화체육공원"
],
"indoor": [
"한강뮤지엄"
],
"sunset": []
},
"gyeonggi/yongin": {
"outdoor": [
"기흥맛깔촌",
"놀이정원풀빛",
"광교산체육공원"
],
"indoor": [
"백남준아트센터",
"알토이미술관"
],
"sunset": []
},
"gyeonggi/yongin/cheoin": {
"outdoor": [
"가실벚꽃길",
"석포숲공원",
"양지파인펫파크"
],
"indoor": [
"벗이미술관"
],
"sunset": []
},
"gyeonggi/yongin/giheung": {
"outdoor": [
"기흥맛깔촌",
"놀이정원풀빛"
],
"indoor": [
"백남준아트센터",
"알토이미술관"
],
"sunset": []
},
"gyeonggi/yongin/suji": {
"outdoor": [
"고기동 오리촌",
"광교산체육공원",
"보정동카페거리"
],
"indoor": [
"뮤지엄그라운드",
"한국미술관"
],
"sunset": []
},
"gyeonggi/paju": {
"outdoor": [
"공릉호",
"도라전망대",
"벽초지수목원"
],
"indoor": [
"93뮤지엄가족미술관",
"갤러리 MOA"
],
"sunset": [
"헤이리무장애노을숲길"
]
},
"gyeonggi/icheon": {
"outdoor": [
"덕평공룡수목원",
"도예촌 쌀밥거리",
"도척그린공원"
],
"indoor": [
"갤러리 더 화",
"이천시립월전미술관"
],
"sunset": []
},
"gyeonggi/anseong": {
"outdoor": [
"금광호수",
"금광호수공원",
"금광호수하늘전망대"
],
"indoor": [
"동아방송예술대학교 DIMA아트센터"
],
"sunset": []
},
"gyeonggi/gimpo": {
"outdoor": [
"갈현체육공원",
"라베니체 마치에비뉴",
"걸포중앙공원"
],
"indoor": [
"김포 아트빌리지",
"보름산미술관"
],
"sunset": []
},
"gyeonggi/hwaseong": {
"outdoor": [
"너른공원",
"궁평리 해수욕장",
"남양호(남양황라)"
],
"indoor": [
"소다미술관",
"엄미술관"
],
"sunset": [
"궁평항",
"매향항선착장"
]
},
"gyeonggi/hwaseong/manse": {
"outdoor": [
"궁평리 해수욕장",
"남양호(남양황라)",
"안중레포츠공원"
],
"indoor": [],
"sunset": [
"궁평항",
"매향항선착장"
]
},
"gyeonggi/hwaseong/hyohaeng": {
"outdoor": [],
"indoor": [
"엄미술관"
],
"sunset": []
},
"gyeonggi/hwaseong/byeongjeom": {
"outdoor": [
"개나리공원",
"구봉산근린공원",
"다람산공원"
],
"indoor": [
"소다미술관"
],
"sunset": []
},
"gyeonggi/hwaseong/dongtan": {
"outdoor": [
"너른공원",
"동학산공원"
],
"indoor": [],
"sunset": []
},
"gyeonggi/gwangju": {
"outdoor": [
"광주 곤지암도자공원",
"율봄식물원",
"중대물빛공원"
],
"indoor": [
"닻미술관",
"영은미술관"
],
"sunset": []
},
"gyeonggi/yangju": {
"outdoor": [
"국립수목원",
"나리농원",
"독바위공원"
],
"indoor": [],
"sunset": []
},
"gyeonggi/pocheon": {
"outdoor": [
"나남수목원",
"포천수원산정상전망대"
],
"indoor": [],
"sunset": []
},
"gyeonggi/yeoju": {
"outdoor": [
"남한강출렁다리",
"달맞이광장",
"황학산수목원"
],
"indoor": [
"C아트뮤지엄(숲속의 미술공원)",
"경기생활도자미술관"
],
"sunset": [
"흥원창"
]
},
"gyeonggi/yeoncheon": {
"outdoor": [
"열쇠전망대",
"임진강 댑싸리정원",
"태풍전망대"
],
"indoor": [
"조각가 박시동 미술관"
],
"sunset": [
"임진강 주상절리"
]
},
"gyeonggi/gapyeong": {
"outdoor": [
"가평베고니아새정원",
"강촌 출렁다리공원",
"청평호반"
],
"indoor": [
"남송미술관",
"노고갤러리"
],
"sunset": []
},
"gyeonggi/yangpyeong": {
"outdoor": [
"개군레포츠공원",
"더그림",
"이포보"
],
"indoor": [
"마나스아트센터",
"양평군립미술관"
],
"sunset": [
"이포보전망대"
]
}
}
+245
View File
@@ -0,0 +1,245 @@
{
"gyeongnam/changwon": {
"outdoor": [
"가포해안변공원",
"광암해수욕장",
"마산 오동동 아구찜거리"
],
"indoor": [
"창원시립마산문신미술관",
"경남도립미술관"
],
"sunset": [
"불모산 노을 전망대"
]
},
"gyeongnam/changwon/uichang": {
"outdoor": [
"금병공원",
"대산플라워랜드",
"명품십리길"
],
"indoor": [
"대산미술관",
"주남아트갤러리"
],
"sunset": []
},
"gyeongnam/changwon/seongsan": {
"outdoor": [
"기업사랑공원",
"안민고개 만남전망대",
"용전숲"
],
"indoor": [
"경남도립미술관",
"클레이아크 김해미술관"
],
"sunset": []
},
"gyeongnam/changwon/masanhappo": {
"outdoor": [
"가포해안변공원",
"광암해수욕장",
"마산 오동동 아구찜거리"
],
"indoor": [
"창원시립마산문신미술관"
],
"sunset": []
},
"gyeongnam/changwon/masanhoewon": {
"outdoor": [
"산호공원(용마공원) 시의거리",
"팔룡산 돌탑공원"
],
"indoor": [],
"sunset": []
},
"gyeongnam/changwon/jinhae": {
"outdoor": [
"거가대교",
"구영해수욕장",
"진해 벚꽃공원"
],
"indoor": [],
"sunset": [
"불모산 노을 전망대"
]
},
"gyeongnam/jinju": {
"outdoor": [
"금호못유원지",
"남가람문화거리",
"선학산전망대"
],
"indoor": [
"와인갤러리",
"진주시립이성자미술관"
],
"sunset": [
"남강댐 노을공원"
]
},
"gyeongnam/tongyeong": {
"outdoor": [
"거제대교",
"달아공원",
"덕동해수욕장"
],
"indoor": [
"전혁림 미술관",
"통영 옻칠미술관"
],
"sunset": [
"평인 노을길"
]
},
"gyeongnam/sacheon": {
"outdoor": [
"그레이스 정원",
"남일대해수욕장",
"모충공원"
],
"indoor": [
"사천미술관",
"아라마루 아쿠아리움"
],
"sunset": [
"실안낙조"
]
},
"gyeongnam/gimhae": {
"outdoor": [
"가야의 거리",
"거북공원",
"글로벌푸드타운"
],
"indoor": [],
"sunset": []
},
"gyeongnam/miryang": {
"outdoor": [
"낙동강철교전망대",
"달빛쌈지공원",
"밀양햇살상권"
],
"indoor": [],
"sunset": [
"낙동강철교전망대"
]
},
"gyeongnam/geoje": {
"outdoor": [
"거제 우제봉전망대",
"거제식물원",
"구조라해수욕장"
],
"indoor": [],
"sunset": [
"노을이 물드는 언덕"
]
},
"gyeongnam/yangsan": {
"outdoor": [
"달무리수변공원",
"서리단길",
"양산천 구름다리"
],
"indoor": [],
"sunset": []
},
"gyeongnam/uiryeong": {
"outdoor": [
"아열대식물원",
"의령구름다리"
],
"indoor": [],
"sunset": []
},
"gyeongnam/haman": {
"outdoor": [
"경상남도수목원",
"남지철교",
"함주공원"
],
"indoor": [
"마산현대미술관"
],
"sunset": [
"함안 악양루"
]
},
"gyeongnam/changnyeong": {
"outdoor": [
"연지못",
"우포출렁다리",
"창녕 만옥정공원"
],
"indoor": [],
"sunset": []
},
"gyeongnam/goseong": {
"outdoor": [
"고성 솔섬",
"고성 장산숲",
"대항해수욕장"
],
"indoor": [],
"sunset": []
},
"gyeongnam/namhae": {
"outdoor": [
"구미동해변",
"남해대교",
"남해토피아랜드"
],
"indoor": [
"바람흔적미술관"
],
"sunset": []
},
"gyeongnam/hadong": {
"outdoor": [
"광양 옥룡사 동백나무 숲",
"금오산전망대",
"정동원길"
],
"indoor": [],
"sunset": []
},
"gyeongnam/sancheong": {
"outdoor": [
"대포숲",
"무릉교",
"송정숲"
],
"indoor": [],
"sunset": []
},
"gyeongnam/hamyang": {
"outdoor": [
"상림공원"
],
"indoor": [],
"sunset": []
},
"gyeongnam/geochang": {
"outdoor": [
"갈계숲",
"거창사건추모공원",
"오도산전망대"
],
"indoor": [],
"sunset": []
},
"gyeongnam/hapcheon": {
"outdoor": [
"일해공원",
"합천 정원테마파크",
"합천호"
],
"indoor": [],
"sunset": []
}
}
+135
View File
@@ -0,0 +1,135 @@
{
"incheon/jemulpo": {
"outdoor": [
"동인천 삼치거리",
"상트페테르부르크광장",
"월미공원 월미전망대"
],
"indoor": [
"우리미술관",
"트릭아트스토리"
],
"sunset": [
"북성포구",
"월미공원 월미전망대"
]
},
"incheon/yeongjong": {
"outdoor": [
"강화 동막해변",
"더스카이184(THE SKY184)",
"세계평화의숲"
],
"indoor": [
"해든뮤지움"
],
"sunset": [
"거잠포해변",
"백운산전망대"
]
},
"incheon/michuhol": {
"outdoor": [
"감중공원",
"물텀벙 특화음식거리",
"수봉공원"
],
"indoor": [],
"sunset": []
},
"incheon/yeonsu": {
"outdoor": [
"G타워 전망대",
"[대부해솔길] 1코스",
"구봉솔숲해수욕장"
],
"indoor": [
"종이미술관"
],
"sunset": [
"구봉도 낙조전망대",
"구봉솔숲해수욕장"
]
},
"incheon/namdong": {
"outdoor": [
"인천대공원",
"인천중앙공원"
],
"indoor": [],
"sunset": []
},
"incheon/bupyeong": {
"outdoor": [
"건지공원",
"부평 해물탕거리",
"원적산공원 은행나무숲"
],
"indoor": [
"플레이 아쿠아리움 부천"
],
"sunset": []
},
"incheon/gyeyang": {
"outdoor": [
"경인아라뱃길 다남공원",
"계산국민체육공원",
"계양공원"
],
"indoor": [],
"sunset": []
},
"incheon/seohae": {
"outdoor": [
"경인아라뱃길 아라타워 전망대",
"노을공원(인천)",
"늘푸른공원"
],
"indoor": [],
"sunset": [
"경인아라뱃길 아라타워 전망대",
"노을공원(인천)"
]
},
"incheon/geomdan": {
"outdoor": [
"경인아라뱃길 검암공원",
"아라마루 전망대",
"경인아라뱃길 시천공원"
],
"indoor": [
"CICA 미술관"
],
"sunset": [
"아라빛섬"
]
},
"incheon/ganghwa": {
"outdoor": [
"강화도제적봉 평화전망대",
"대청도 농여해변",
"마니산 치유의 숲"
],
"indoor": [
"몬스터리움",
"작은미술관 보구곶"
],
"sunset": [
"민머루해변",
"장화리일몰조망지"
]
},
"incheon/ongjin": {
"outdoor": [
"송도랜드마크시티1호수변공원",
"아암도해안공원"
],
"indoor": [
"송암미술관"
],
"sunset": [
"송도랜드마크시티1호수변공원",
"아암도해안공원"
]
}
}
+32
View File
@@ -0,0 +1,32 @@
{
"jeju/jeju": {
"outdoor": [
"검멀레해변",
"금능석물원",
"김녕미로공원"
],
"indoor": [
"김택화 미술관",
"아쿠아플라넷 제주"
],
"sunset": [
"구엄포구",
"금능돌담해변길"
]
},
"jeju/seogwipo": {
"outdoor": [
"가파도 소망전망대",
"고배기동산",
"노리매공원"
],
"indoor": [
"김영갑갤러리두모악",
"서귀포시립기당미술관"
],
"sunset": [
"강정포구",
"구두미포구"
]
}
}
+170
View File
@@ -0,0 +1,170 @@
{
"jeonbuk/jeonju": {
"outdoor": [
"객사길",
"나들목 가족공원",
"한국도로공사 전주수목원"
],
"indoor": [
"교동미술관",
"미술관 솔"
],
"sunset": []
},
"jeonbuk/jeonju/wansan": {
"outdoor": [
"삼천 2동 막걸리골목",
"지사울공원"
],
"indoor": [
"유휴열미술관",
"전북도립미술관"
],
"sunset": []
},
"jeonbuk/jeonju/deokjin": {
"outdoor": [
"객사길",
"나들목 가족공원",
"한국도로공사 전주수목원"
],
"indoor": [
"교동미술관",
"미술관 솔"
],
"sunset": []
},
"jeonbuk/gunsan": {
"outdoor": [
"고군산섬잇길",
"군산 영화의 거리",
"동백대교"
],
"indoor": [
"군산평화박물관",
"장미갤러리"
],
"sunset": [
"만경낙조전망대"
]
},
"jeonbuk/iksan": {
"outdoor": [
"[전북 천리길 익산시 제3길] 웅포 곰개나루길",
"달빛소리 수목원",
"배산체육공원"
],
"indoor": [],
"sunset": []
},
"jeonbuk/jeongeup": {
"outdoor": [
"내장산수목원",
"미르샘 다리",
"우화정(내장산)"
],
"indoor": [
"정읍시립미술관"
],
"sunset": []
},
"jeonbuk/namwon": {
"outdoor": [
"남원 아담원",
"남원 추어탕 거리",
"대정저수지"
],
"indoor": [
"남원시립김병종미술관"
],
"sunset": []
},
"jeonbuk/gimje": {
"outdoor": [
"시민문화체육공원"
],
"indoor": [],
"sunset": []
},
"jeonbuk/wanju": {
"outdoor": [
"고산문화공원",
"덕진공원",
"세병호"
],
"indoor": [
"그림책미술관",
"오스갤러리"
],
"sunset": [
"비비정"
]
},
"jeonbuk/jinan": {
"outdoor": [],
"indoor": [],
"sunset": []
},
"jeonbuk/muju": {
"outdoor": [
"덕유산국립공원 적상전망대",
"용담호"
],
"indoor": [],
"sunset": []
},
"jeonbuk/jangsu": {
"outdoor": [
"장수물빛공원(물빛공원)"
],
"indoor": [],
"sunset": []
},
"jeonbuk/imsil": {
"outdoor": [
"고원화목원",
"국사봉전망대",
"오수의견공원"
],
"indoor": [],
"sunset": []
},
"jeonbuk/sunchang": {
"outdoor": [
"순창 양지천 꽃잔디길",
"순창군 채계산 출렁다리"
],
"indoor": [
"강천예술원",
"섬진강미술관"
],
"sunset": []
},
"jeonbuk/gochang": {
"outdoor": [
"고창읍성 맹종죽림",
"동호해수욕장",
"서해안 바람공원"
],
"indoor": [],
"sunset": [
"동호해수욕장",
"모항해수욕장"
]
},
"jeonbuk/buan": {
"outdoor": [
"격포해수욕장",
"고군산대교",
"내소사 전나무 숲길"
],
"indoor": [
"금구원야외조각미술관",
"휘목아트타운 미술관"
],
"sunset": [
"격포해수욕장",
"고사포해수욕장"
]
}
}
+251
View File
@@ -0,0 +1,251 @@
{
"jeonnam/mokpo": {
"outdoor": [
"갓바위 문화타운",
"김대중대교",
"맨드라미정원"
],
"indoor": [
"못난이미술관",
"무안군 오승우미술관"
],
"sunset": [
"설레미해수욕장"
]
},
"jeonnam/yeosu": {
"outdoor": [
"거북선대교",
"낭도해변",
"낭만포차거리"
],
"indoor": [
"아르떼뮤지엄 여수",
"아쿠아플라넷 여수"
],
"sunset": [
"끝등전망대",
"낭도해변"
]
},
"jeonnam/suncheon": {
"outdoor": [
"가야정원",
"공마당둘레길",
"광양불고기특화거리"
],
"indoor": [
"전남도립미술관"
],
"sunset": [
"와온해변",
"용산전망대"
]
},
"jeonnam/naju": {
"outdoor": [
"나주 구진포 장어거리",
"나주호",
"승촌보교"
],
"indoor": [],
"sunset": []
},
"jeonnam/gwangyang": {
"outdoor": [
"묘도 봉화산 전망공원",
"배알도 섬 정원",
"배알도 수변공원"
],
"indoor": [],
"sunset": []
},
"jeonnam/damyang": {
"outdoor": [
"관방제림",
"담양국수거리",
"국립정원문화원"
],
"indoor": [
"아트센터 대담",
"해동문화예술촌"
],
"sunset": []
},
"jeonnam/gokseong": {
"outdoor": [
"겸면목화공원",
"국립곡성치유의숲",
"동악산 하늘정원"
],
"indoor": [],
"sunset": []
},
"jeonnam/gurye": {
"outdoor": [
"구례수목원",
"대황강출렁다리",
"천개의향나무숲"
],
"indoor": [],
"sunset": []
},
"jeonnam/goheung": {
"outdoor": [
"거금대교",
"거금생태숲",
"고흥 해창만 간척지 공원"
],
"indoor": [
"남포미술관",
"도화헌미술관"
],
"sunset": [
"염포해수욕장",
"중산 일몰전망대"
]
},
"jeonnam/boseong": {
"outdoor": [
"갈멜정원",
"득량역 추억의 거리",
"율포해수욕장(솔밭해변)"
],
"indoor": [],
"sunset": []
},
"jeonnam/hwasun": {
"outdoor": [
"개천사 비자나무숲",
"너릿재공원",
"모후산 생태숲"
],
"indoor": [
"보성군립 백민미술관",
"화순 군립 최상준미술관"
],
"sunset": []
},
"jeonnam/jangheung": {
"outdoor": [
"수문해수욕장",
"장흥 126타워(정남진 전망대)",
"정남진 수목원"
],
"indoor": [],
"sunset": []
},
"jeonnam/gangjin": {
"outdoor": [
"가우도 출렁다리",
"강진 백련사 동백나무 숲",
"사의재저잣거리"
],
"indoor": [],
"sunset": [
"강진만생태공원"
]
},
"jeonnam/haenam": {
"outdoor": [
"땅끝우림정원",
"송평해변",
"포레스트 수목원"
],
"indoor": [],
"sunset": []
},
"jeonnam/yeongam": {
"outdoor": [],
"indoor": [
"영암군립하정웅미술관"
],
"sunset": []
},
"jeonnam/muan": {
"outdoor": [
"느러지전망관람대",
"대광해수욕장",
"무안 물맞이 치유의 숲"
],
"indoor": [],
"sunset": []
},
"jeonnam/hampyeong": {
"outdoor": [
"달맞이공원",
"돌머리해수욕장",
"함평 고막천 석교"
],
"indoor": [
"함평군립미술관"
],
"sunset": [
"안악해변"
]
},
"jeonnam/yeonggwang": {
"outdoor": [
"가마미해수욕장",
"물무산 행복숲",
"백수해안공원"
],
"indoor": [
"잠월미술관"
],
"sunset": [
"가마미해수욕장",
"구시포해수욕장"
]
},
"jeonnam/jangseong": {
"outdoor": [
"옐로우 출렁다리",
"요월정원림",
"장성 상무평화공원"
],
"indoor": [],
"sunset": []
},
"jeonnam/wando": {
"outdoor": [
"가사동백숲해변",
"거문대교",
"미소공원"
],
"indoor": [],
"sunset": [
"망끝전망대",
"사구미해수욕장"
]
},
"jeonnam/jindo": {
"outdoor": [
"가계해수욕장",
"삼도대교",
"철마공원"
],
"indoor": [
"나절로미술관",
"남도전통미술관"
],
"sunset": [
"세방낙조 전망대"
]
},
"jeonnam/sinan": {
"outdoor": [
"고하도 전망대",
"기동 삼거리 벽화",
"노을공원"
],
"indoor": [
"1004섬 수석미술관&수석정원",
"저녁노을미술관"
],
"sunset": [
"고하도 전망대",
"노을공원"
]
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"sejong/sejong": {
"outdoor": [
"고운뜰공원",
"국립세종수목원",
"금강보행교(이응다리)"
],
"indoor": [
"소피아갤러리"
],
"sunset": [
"고운뜰공원",
"청벽산"
]
}
}
+287
View File
@@ -0,0 +1,287 @@
{
"seoul/jongno": {
"outdoor": [
"북촌한옥마을",
"무궁화동산",
"북촌전망대"
],
"indoor": [
"국립현대미술관 서울관",
"PKM갤러리"
],
"sunset": [
"인왕산 무무대 전망대",
"정동전망대"
]
},
"seoul/jung": {
"outdoor": [
"[종로둘레길 3코스] 낙산 코스",
"남산 야외식물원",
"남산서울타워"
],
"indoor": [
"갤러리 스클로",
"두산갤러리"
],
"sunset": []
},
"seoul/yongsan": {
"outdoor": [
"공덕동 족발골목",
"국립중앙박물관 전통염료식물원",
"마포대교"
],
"indoor": [
"갤러리에스피",
"김세중미술관"
],
"sunset": [
"반포한강공원"
]
},
"seoul/seongdong": {
"outdoor": [
"서울숲",
"서울 살곶이 다리",
"성수동 수제화거리"
],
"indoor": [
"성수 갤러리 골목",
"더페이지갤러리"
],
"sunset": []
},
"seoul/gwangjin": {
"outdoor": [
"광진광장공원",
"올림픽대교",
"자양동 양꼬치거리 (중국음식문화거리)"
],
"indoor": [],
"sunset": []
},
"seoul/dongdaemun": {
"outdoor": [
"간데메공원",
"답십리 영화의 거리",
"용두동 쭈꾸미골목"
],
"indoor": [],
"sunset": []
},
"seoul/jungnang": {
"outdoor": [
"노원 불빛정원",
"사가정공원",
"용마산 스카이워크"
],
"indoor": [
"중랑아트센터"
],
"sunset": []
},
"seoul/seongbuk": {
"outdoor": [
"KOCCA콘텐츠문화광장",
"[서울둘레길 19코스] 북한산 성북코스",
"국립산림과학원(홍릉시험림)"
],
"indoor": [
"간송미술관(서울 보화각)",
"성북구립 최만린미술관"
],
"sunset": [
"채석장 전망대"
]
},
"seoul/gangbuk": {
"outdoor": [
"[서울둘레길 20코스] 북한산 강북코스",
"[서울둘레길 21코스] 북한산 도봉코스",
"오동근린공원 유아숲체험장"
],
"indoor": [
"상상톡톡 미술관"
],
"sunset": []
},
"seoul/dobong": {
"outdoor": [
"서울창포원",
"수락산 당고개지구 공원",
"우이령 숲속문화마을(구 우이동 먹거리마을)"
],
"indoor": [],
"sunset": []
},
"seoul/nowon": {
"outdoor": [
"[서울둘레길 3코스] 불암산코스",
"등나무근린공원",
"산들소리"
],
"indoor": [
"서울시립 북서울미술관",
"서울시립 사진미술관"
],
"sunset": []
},
"seoul/eunpyeong": {
"outdoor": [
"[서울둘레길 17코스] 북한산 은평코스",
"응암동 감자국 거리",
"일영허브랜드(숲길정원)"
],
"indoor": [
"가나아트센터",
"갤러리 비앤에스"
],
"sunset": []
},
"seoul/seodaemun": {
"outdoor": [
"연세로",
"이대거리"
],
"indoor": [
"자하미술관"
],
"sunset": []
},
"seoul/mapo": {
"outdoor": [
"경의선숲길",
"망원한강공원",
"경의선책거리"
],
"indoor": [
"대안공간 루프"
],
"sunset": [
"망원한강공원",
"하늘공원"
]
},
"seoul/yangcheon": {
"outdoor": [
"안양천 사계절 테마원",
"양천구 로데오거리",
"양천공원"
],
"indoor": [],
"sunset": []
},
"seoul/gangseo": {
"outdoor": [
"[서울둘레길 15코스] 노을·하늘공원코스",
"강서역사문화거리",
"강서한강공원"
],
"indoor": [
"겸재정선미술관"
],
"sunset": []
},
"seoul/guro": {
"outdoor": [
"[서울둘레길 14코스] 안양천 하류코스",
"거리공원",
"국제음식문화거리(INTERNATIONAL FOOD STREET)"
],
"indoor": [
"갤러리 구루지"
],
"sunset": []
},
"seoul/geumcheon": {
"outdoor": [
"금빛공원",
"금천 폭포공원",
"새빛공원"
],
"indoor": [],
"sunset": []
},
"seoul/yeongdeungpo": {
"outdoor": [
"여의도한강공원",
"당산공원",
"문래동꽃밭정원"
],
"indoor": [
"더현대 서울"
],
"sunset": []
},
"seoul/dongjak": {
"outdoor": [
"노들나루공원",
"노량진컵밥거리",
"보라매공원"
],
"indoor": [
"퐁피두센터 한화"
],
"sunset": []
},
"seoul/gwanak": {
"outdoor": [
"[서울둘레길 11코스] 관악산코스",
"샤로수길",
"[서울둘레길 12코스] 호암산코스"
],
"indoor": [
"서울대학교 미술관"
],
"sunset": []
},
"seoul/seocho": {
"outdoor": [
"[서울둘레길 10코스] 우면산코스",
"몽마르뜨공원",
"우면산 소망탑"
],
"indoor": [
"샘터화랑",
"서울아트나우 갤러리"
],
"sunset": []
},
"seoul/gangnam": {
"outdoor": [
"세로수길",
"신사공원",
"아시아공원"
],
"indoor": [
"K현대미술관",
"코엑스 아쿠아리움"
],
"sunset": []
},
"seoul/songpa": {
"outdoor": [
"석촌호수",
"롯데월드타워 서울스카이",
"송리단길"
],
"indoor": [
"롯데월드 아쿠아리움",
"롯데뮤지엄"
],
"sunset": []
},
"seoul/gangdong": {
"outdoor": [
"광나루한강공원",
"광진교 8번가",
"천호자전거거리"
],
"indoor": [],
"sunset": [
"광나루자전거공원",
"일자산 허브천문공원"
]
}
}
+51
View File
@@ -0,0 +1,51 @@
{
"ulsan/jung": {
"outdoor": [
"달빛야경누리길",
"학성공원",
"함월루"
],
"indoor": [
"울산 팀아쿠아",
"울산시립미술관"
],
"sunset": []
},
"ulsan/nam": {
"outdoor": [
"맨발의 청춘길",
"문화공원(울산)"
],
"indoor": [],
"sunset": []
},
"ulsan/dong": {
"outdoor": [
"대왕암공원",
"대왕암공원 출렁다리",
"솔개해수욕장"
],
"indoor": [
"슬도아트"
],
"sunset": []
},
"ulsan/buk": {
"outdoor": [
"강동몽돌해변 (정자해변)",
"강동사랑길",
"경주 양남 주상절리 전망대"
],
"indoor": [],
"sunset": []
},
"ulsan/ulju": {
"outdoor": [
"문수산전망대",
"온실리움",
"자드락숲"
],
"indoor": [],
"sunset": []
}
}
+5
View File
@@ -1,8 +1,10 @@
import { BrowserRouter, Route, Routes } from 'react-router'
import { BLayout } from './b/BLayout'
import { FoliagePage } from './b/FoliagePage'
import { GakPage } from './b/GakPage'
import { SeasonPage } from './b/SeasonPage'
import { SkyPage } from './b/SkyPage'
import { TalkPage } from './b/TalkPage'
import { TodayPage } from './b/TodayPage'
import { WeekPage } from './b/WeekPage'
@@ -13,10 +15,13 @@ export default function App() {
<Route element={<BLayout />}>
<Route index element={<TodayPage />} />
<Route path="today/:sido/:place" element={<TodayPage />} />
<Route path="tomorrow/:sido/:place" element={<TodayPage />} />
<Route path="gak" element={<GakPage />} />
<Route path="sky" element={<SkyPage />} />
<Route path="week" element={<WeekPage />} />
<Route path="season" element={<SeasonPage />} />
<Route path="foliage" element={<FoliagePage />} />
<Route path="talk" element={<TalkPage />} />
<Route path="*" element={<TodayPage />} />
</Route>
</Routes>
@@ -3,8 +3,8 @@
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
import { client } from '../client.gen';
import { addComment, createCard, deleteComment, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, publishCard, refresh, rejectCard, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen';
import type { AddCommentData, AddCommentError, AddCommentResponse, CreateCardData, CreateCardError, CreateCardResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen';
import { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, createCard, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, publishCard, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from '../sdk.gen';
import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, AuthConfigData, AuthConfigResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, CreateCardData, CreateCardError, CreateCardResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, GetCardImageData, GetCardImageError, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTalkImageData, GetTalkImageError, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetTomorrowGuPageData, GetTomorrowGuPageError, GetTomorrowGuPageResponse, GetTomorrowPageData, GetTomorrowPageError, GetTomorrowPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCardsData, ListCardsError, ListCardsResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListMyTalksData, ListMyTalksError, ListMyTalksResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListPresetsData, ListPresetsResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, PublishCardData, PublishCardError, PublishCardResponse, RefreshData, RefreshError, RefreshResponse, RejectCardData, RejectCardError, RejectCardResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, TalkGroupsData, TalkGroupsError, TalkGroupsResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen';
export type QueryKey<TOptions extends Options> = [
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
@@ -78,7 +78,7 @@ export const nearestRegionOptions = (options: Options<NearestRegionData>) => que
export const getWeatherTodayQueryKey = (options: Options<GetWeatherTodayData>) => createQueryKey('getWeatherToday', options);
/**
* 오늘 3시간 칸 날씨
* 오늘(또는 내일) 3시간 칸 날씨
*/
export const getWeatherTodayOptions = (options: Options<GetWeatherTodayData>) => queryOptions<GetWeatherTodayResponse, GetWeatherTodayError, GetWeatherTodayResponse, ReturnType<typeof getWeatherTodayQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
@@ -379,6 +379,41 @@ export const loginMutation = (options?: Partial<Options<LoginData>>): UseMutatio
return mutationOptions;
};
/**
* 구글 로그인 (처음이면 자동 닉네임으로 가입)
*/
export const googleLoginMutation = (options?: Partial<Options<GoogleLoginData>>): UseMutationOptions<GoogleLoginResponse, GoogleLoginError, Options<GoogleLoginData>> => {
const mutationOptions: UseMutationOptions<GoogleLoginResponse, GoogleLoginError, Options<GoogleLoginData>> = {
mutationFn: async (fnOptions) => {
const { data } = await googleLogin({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const authConfigQueryKey = (options?: Options<AuthConfigData>) => createQueryKey('authConfig', options);
/**
* 로그인 화면 설정 (구글 클라이언트 ID)
*/
export const authConfigOptions = (options?: Options<AuthConfigData>) => queryOptions<AuthConfigResponse, DefaultError, AuthConfigResponse, ReturnType<typeof authConfigQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await authConfig({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: authConfigQueryKey(options)
});
/**
* 토큰 재발급
*/
@@ -466,7 +501,7 @@ export const unlikePostMutation = (options?: Partial<Options<UnlikePostData>>):
};
/**
* 좋아요
* 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likePostMutation = (options?: Partial<Options<LikePostData>>): UseMutationOptions<LikePostResponse, LikePostError, Options<LikePostData>> => {
const mutationOptions: UseMutationOptions<LikePostResponse, LikePostError, Options<LikePostData>> = {
@@ -642,7 +677,7 @@ export const listCommentsInfiniteOptions = (options: Options<ListCommentsData>)
};
/**
* 댓글 쓰기 (60자)
* 댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개)
*/
export const addCommentMutation = (options?: Partial<Options<AddCommentData>>): UseMutationOptions<AddCommentResponse, AddCommentError, Options<AddCommentData>> => {
const mutationOptions: UseMutationOptions<AddCommentResponse, AddCommentError, Options<AddCommentData>> = {
@@ -659,7 +694,7 @@ export const addCommentMutation = (options?: Partial<Options<AddCommentData>>):
};
/**
* 내 댓글 지우기
* 내 댓글 지우기 (로그인 없이 쓴 댓글은 같은 IP 에서)
*/
export const deleteCommentMutation = (options?: Partial<Options<DeleteCommentData>>): UseMutationOptions<DeleteCommentResponse, DeleteCommentError, Options<DeleteCommentData>> => {
const mutationOptions: UseMutationOptions<DeleteCommentResponse, DeleteCommentError, Options<DeleteCommentData>> = {
@@ -693,7 +728,7 @@ export const unlikeCommentMutation = (options?: Partial<Options<UnlikeCommentDat
};
/**
* 댓글 좋아요
* 댓글 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likeCommentMutation = (options?: Partial<Options<LikeCommentData>>): UseMutationOptions<LikeCommentResponse, LikeCommentError, Options<LikeCommentData>> => {
const mutationOptions: UseMutationOptions<LikeCommentResponse, LikeCommentError, Options<LikeCommentData>> = {
@@ -709,6 +744,344 @@ export const likeCommentMutation = (options?: Partial<Options<LikeCommentData>>)
return mutationOptions;
};
export const listMyGakQueryKey = (options?: Options<ListMyGakData>) => createQueryKey('listMyGak', options);
/**
* 내 각 목록 (로그인하지 않았으면 빈 목록)
*/
export const listMyGakOptions = (options?: Options<ListMyGakData>) => queryOptions<ListMyGakResponse, ListMyGakError, ListMyGakResponse, ReturnType<typeof listMyGakQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await listMyGak({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: listMyGakQueryKey(options)
});
/**
* 이름과 날씨 조건으로 내 각 만들기
*/
export const addMyGakMutation = (options?: Partial<Options<AddMyGakData>>): UseMutationOptions<AddMyGakResponse, AddMyGakError, Options<AddMyGakData>> => {
const mutationOptions: UseMutationOptions<AddMyGakResponse, AddMyGakError, Options<AddMyGakData>> = {
mutationFn: async (fnOptions) => {
const { data } = await addMyGak({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const listPresetsQueryKey = (options?: Options<ListPresetsData>) => createQueryKey('listPresets', options);
/**
* 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기)
*/
export const listPresetsOptions = (options?: Options<ListPresetsData>) => queryOptions<ListPresetsResponse, DefaultError, ListPresetsResponse, ReturnType<typeof listPresetsQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await listPresets({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: listPresetsQueryKey(options)
});
/**
* 조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)
*/
export const scoreMyGakMutation = (options?: Partial<Options<ScoreMyGakData>>): UseMutationOptions<ScoreMyGakResponse, ScoreMyGakError, Options<ScoreMyGakData>> => {
const mutationOptions: UseMutationOptions<ScoreMyGakResponse, ScoreMyGakError, Options<ScoreMyGakData>> = {
mutationFn: async (fnOptions) => {
const { data } = await scoreMyGak({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 내 각 지우기
*/
export const deleteMyGakMutation = (options?: Partial<Options<DeleteMyGakData>>): UseMutationOptions<DeleteMyGakResponse, DeleteMyGakError, Options<DeleteMyGakData>> => {
const mutationOptions: UseMutationOptions<DeleteMyGakResponse, DeleteMyGakError, Options<DeleteMyGakData>> = {
mutationFn: async (fnOptions) => {
const { data } = await deleteMyGak({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const talkGroupsQueryKey = (options?: Options<TalkGroupsData>) => createQueryKey('talkGroups', options);
/**
* 오늘 피드 묶음 (동네 사람들 + 주제별, 가까운 동네·덜 지난 글 먼저, 한 사람 한 장)
*/
export const talkGroupsOptions = (options?: Options<TalkGroupsData>) => queryOptions<TalkGroupsResponse, TalkGroupsError, TalkGroupsResponse, ReturnType<typeof talkGroupsQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await talkGroups({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: talkGroupsQueryKey(options)
});
export const listTalksQueryKey = (options?: Options<ListTalksData>) => createQueryKey('listTalks', options);
/**
* 동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기)
*/
export const listTalksOptions = (options?: Options<ListTalksData>) => queryOptions<ListTalksResponse, ListTalksError, ListTalksResponse, ReturnType<typeof listTalksQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await listTalks({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: listTalksQueryKey(options)
});
export const listTalksInfiniteQueryKey = (options?: Options<ListTalksData>): QueryKey<Options<ListTalksData>> => createQueryKey('listTalks', options, true);
/**
* 동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기)
*/
export const listTalksInfiniteOptions = (options?: Options<ListTalksData>) => {
const opts = infiniteQueryOptions<ListTalksResponse, ListTalksError, InfiniteData<ListTalksResponse>, QueryKey<Options<ListTalksData>>, string | null | Pick<QueryKey<Options<ListTalksData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
// @ts-ignore
{
queryFn: async ({ pageParam, queryKey, signal }) => {
// @ts-ignore
const page: Pick<QueryKey<Options<ListTalksData>>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : {
query: {
cursor: pageParam
}
};
const params = createInfiniteParams(queryKey, page);
const { data } = await listTalks({
...options,
...params,
signal,
throwOnError: true
});
return data;
},
queryKey: listTalksInfiniteQueryKey(options)
});
return opts as Omit<typeof opts, 'initialData'>;
};
export const listMyTalksQueryKey = (options?: Options<ListMyTalksData>) => createQueryKey('listMyTalks', options);
/**
* 내가 쓴 글 (최신순)
*/
export const listMyTalksOptions = (options?: Options<ListMyTalksData>) => queryOptions<ListMyTalksResponse, ListMyTalksError, ListMyTalksResponse, ReturnType<typeof listMyTalksQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await listMyTalks({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: listMyTalksQueryKey(options)
});
export const listMyTalksInfiniteQueryKey = (options?: Options<ListMyTalksData>): QueryKey<Options<ListMyTalksData>> => createQueryKey('listMyTalks', options, true);
/**
* 내가 쓴 글 (최신순)
*/
export const listMyTalksInfiniteOptions = (options?: Options<ListMyTalksData>) => {
const opts = infiniteQueryOptions<ListMyTalksResponse, ListMyTalksError, InfiniteData<ListMyTalksResponse>, QueryKey<Options<ListMyTalksData>>, string | null | Pick<QueryKey<Options<ListMyTalksData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
// @ts-ignore
{
queryFn: async ({ pageParam, queryKey, signal }) => {
// @ts-ignore
const page: Pick<QueryKey<Options<ListMyTalksData>>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : {
query: {
cursor: pageParam
}
};
const params = createInfiniteParams(queryKey, page);
const { data } = await listMyTalks({
...options,
...params,
signal,
throwOnError: true
});
return data;
},
queryKey: listMyTalksInfiniteQueryKey(options)
});
return opts as Omit<typeof opts, 'initialData'>;
};
/**
* 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)
*/
export const addTalkMutation = (options?: Partial<Options<AddTalkData>>): UseMutationOptions<AddTalkResponse, AddTalkError, Options<AddTalkData>> => {
const mutationOptions: UseMutationOptions<AddTalkResponse, AddTalkError, Options<AddTalkData>> = {
mutationFn: async (fnOptions) => {
const { data } = await addTalk({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 글에 붙일 사진 올리기 (10MB까지, 위치 정보를 지우고 1080px로 줄여 저장)
*/
export const uploadTalkImageMutation = (options?: Partial<Options<UploadTalkImageData>>): UseMutationOptions<UploadTalkImageResponse, UploadTalkImageError, Options<UploadTalkImageData>> => {
const mutationOptions: UseMutationOptions<UploadTalkImageResponse, UploadTalkImageError, Options<UploadTalkImageData>> = {
mutationFn: async (fnOptions) => {
const { data } = await uploadTalkImage({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const getTalkImageQueryKey = (options: Options<GetTalkImageData>) => createQueryKey('getTalkImage', options);
/**
* 올린 사진
*/
export const getTalkImageOptions = (options: Options<GetTalkImageData>) => queryOptions<unknown, GetTalkImageError, unknown, ReturnType<typeof getTalkImageQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getTalkImage({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getTalkImageQueryKey(options)
});
/**
* 내 이야기 지우기
*/
export const deleteTalkMutation = (options?: Partial<Options<DeleteTalkData>>): UseMutationOptions<DeleteTalkResponse, DeleteTalkError, Options<DeleteTalkData>> => {
const mutationOptions: UseMutationOptions<DeleteTalkResponse, DeleteTalkError, Options<DeleteTalkData>> = {
mutationFn: async (fnOptions) => {
const { data } = await deleteTalk({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 이야기 좋아요 취소
*/
export const unlikeTalkMutation = (options?: Partial<Options<UnlikeTalkData>>): UseMutationOptions<UnlikeTalkResponse, UnlikeTalkError, Options<UnlikeTalkData>> => {
const mutationOptions: UseMutationOptions<UnlikeTalkResponse, UnlikeTalkError, Options<UnlikeTalkData>> = {
mutationFn: async (fnOptions) => {
const { data } = await unlikeTalk({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 이야기 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likeTalkMutation = (options?: Partial<Options<LikeTalkData>>): UseMutationOptions<LikeTalkResponse, LikeTalkError, Options<LikeTalkData>> => {
const mutationOptions: UseMutationOptions<LikeTalkResponse, LikeTalkError, Options<LikeTalkData>> = {
mutationFn: async (fnOptions) => {
const { data } = await likeTalk({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 이야기 신고 (서로 다른 3명이면 숨김)
*/
export const reportTalkMutation = (options?: Partial<Options<ReportTalkData>>): UseMutationOptions<ReportTalkResponse, ReportTalkError, Options<ReportTalkData>> => {
const mutationOptions: UseMutationOptions<ReportTalkResponse, ReportTalkError, Options<ReportTalkData>> = {
mutationFn: async (fnOptions) => {
const { data } = await reportTalk({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
/**
* 이 글 쓴 사람의 글 안 보기
*/
export const blockTalkAuthorMutation = (options?: Partial<Options<BlockTalkAuthorData>>): UseMutationOptions<BlockTalkAuthorResponse, BlockTalkAuthorError, Options<BlockTalkAuthorData>> => {
const mutationOptions: UseMutationOptions<BlockTalkAuthorResponse, BlockTalkAuthorError, Options<BlockTalkAuthorData>> = {
mutationFn: async (fnOptions) => {
const { data } = await blockTalkAuthor({
...options,
...fnOptions,
throwOnError: true
});
return data;
}
};
return mutationOptions;
};
export const getWatchSummaryQueryKey = (options: Options<GetWatchSummaryData>) => createQueryKey('getWatchSummary', options);
/**
@@ -781,6 +1154,60 @@ export const getTodayGuPageOptions = (options: Options<GetTodayGuPageData>) => q
queryKey: getTodayGuPageQueryKey(options)
});
export const getTomorrowPageQueryKey = (options: Options<GetTomorrowPageData>) => createQueryKey('getTomorrowPage', options);
/**
* 지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)
*/
export const getTomorrowPageOptions = (options: Options<GetTomorrowPageData>) => queryOptions<GetTomorrowPageResponse, GetTomorrowPageError, GetTomorrowPageResponse, ReturnType<typeof getTomorrowPageQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getTomorrowPage({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getTomorrowPageQueryKey(options)
});
export const getTomorrowGuPageQueryKey = (options: Options<GetTomorrowGuPageData>) => createQueryKey('getTomorrowGuPage', options);
/**
* 구로 나뉜 시의 구 내일 날씨 페이지
*/
export const getTomorrowGuPageOptions = (options: Options<GetTomorrowGuPageData>) => queryOptions<GetTomorrowGuPageResponse, GetTomorrowGuPageError, GetTomorrowGuPageResponse, ReturnType<typeof getTomorrowGuPageQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getTomorrowGuPage({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: getTomorrowGuPageQueryKey(options)
});
export const listCardsQueryKey = (options?: Options<ListCardsData>) => createQueryKey('listCards', options);
/**
* 만든 카드뉴스 목록 (관리자). 다시 내려받거나 올릴 때
*/
export const listCardsOptions = (options?: Options<ListCardsData>) => queryOptions<ListCardsResponse, ListCardsError, ListCardsResponse, ReturnType<typeof listCardsQueryKey>>({
queryFn: async ({ queryKey, signal }) => {
const { data } = await listCards({
...options,
...queryKey[0],
signal,
throwOnError: true
});
return data;
},
queryKey: listCardsQueryKey(options)
});
/**
* 카드뉴스 저장 (관리자). publish 면 바로 그날 피드에 올린다
*/
+2 -2
View File
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { addComment, createCard, deleteComment, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, publishCard, refresh, rejectCard, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type PublishCardData, type PublishCardError, type PublishCardErrors, type PublishCardResponse, type PublishCardResponses, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type RejectCardData, type RejectCardError, type RejectCardErrors, type RejectCardResponse, type RejectCardResponses, type ReqCardCreate, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResCard, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPostLine truncated
export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, createCard, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, publishCard, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen';
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type LiLine truncated
+155 -7
View File
@@ -1,8 +1,8 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
import { client } from './client.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, CreateCardData, CreateCardErrors, CreateCardResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, CreateCardData, CreateCardErrors, CreateCardResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetCardImageData, GetCardImageErrors, GetCardImageResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetTomorrowGuPageData, GetTomorrowGuPageErrors, GetTomorrowGuPageResponses, GetTomorrowPageData, GetTomorrowPageErrors, GetTomorrowPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCardsData, ListCardsErrors, ListCardsResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListMyTalksData, ListMyTalksErrors, ListMyTalksResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListPresetsData, ListPresetsResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, PublishCardData, PublishCardErrors, PublishCardResponses, RefreshData, RefreshErrors, RefreshResponses, RejectCardData, RejectCardErrors, RejectCardResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, TalkGroupsData, TalkGroupsErrors, TalkGroupsResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -29,7 +29,7 @@ export const listRegions = <ThrowOnError extends boolean = true>(options?: Optio
export const nearestRegion = <ThrowOnError extends boolean = true>(options: Options<NearestRegionData, ThrowOnError>): RequestResult<NearestRegionResponses, NearestRegionErrors, ThrowOnError> => (options.client ?? client).get<NearestRegionResponses, NearestRegionErrors, ThrowOnError>({ url: '/v1/region/nearest', ...options });
/**
* 오늘 3시간 칸 날씨
* 오늘(또는 내일) 3시간 칸 날씨
*/
export const getWeatherToday = <ThrowOnError extends boolean = true>(options: Options<GetWeatherTodayData, ThrowOnError>): RequestResult<GetWeatherTodayResponses, GetWeatherTodayErrors, ThrowOnError> => (options.client ?? client).get<GetWeatherTodayResponses, GetWeatherTodayErrors, ThrowOnError>({ url: '/v1/weather/today', ...options });
@@ -127,6 +127,23 @@ export const login = <ThrowOnError extends boolean = true>(options: Options<Logi
}
});
/**
* 구글 로그인 (처음이면 자동 닉네임으로 가입)
*/
export const googleLogin = <ThrowOnError extends boolean = true>(options: Options<GoogleLoginData, ThrowOnError>): RequestResult<GoogleLoginResponses, GoogleLoginErrors, ThrowOnError> => (options.client ?? client).post<GoogleLoginResponses, GoogleLoginErrors, ThrowOnError>({
url: '/v1/auth/google',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 로그인 화면 설정 (구글 클라이언트 ID)
*/
export const authConfig = <ThrowOnError extends boolean = true>(options?: Options<AuthConfigData, ThrowOnError>): RequestResult<AuthConfigResponses, unknown, ThrowOnError> => (options?.client ?? client).get<AuthConfigResponses, unknown, ThrowOnError>({ url: '/v1/auth/config', ...options });
/**
* 토큰 재발급
*/
@@ -167,7 +184,7 @@ export const updateMe = <ThrowOnError extends boolean = true>(options: Options<U
export const unlikePost = <ThrowOnError extends boolean = true>(options: Options<UnlikePostData, ThrowOnError>): RequestResult<UnlikePostResponses, UnlikePostErrors, ThrowOnError> => (options.client ?? client).delete<UnlikePostResponses, UnlikePostErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/like', ...options });
/**
* 좋아요
* 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likePost = <ThrowOnError extends boolean = true>(options: Options<LikePostData, ThrowOnError>): RequestResult<LikePostResponses, LikePostErrors, ThrowOnError> => (options.client ?? client).post<LikePostResponses, LikePostErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/like', ...options });
@@ -192,7 +209,7 @@ export const listSaved = <ThrowOnError extends boolean = true>(options?: Options
export const listComments = <ThrowOnError extends boolean = true>(options: Options<ListCommentsData, ThrowOnError>): RequestResult<ListCommentsResponses, ListCommentsErrors, ThrowOnError> => (options.client ?? client).get<ListCommentsResponses, ListCommentsErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/comment/list', ...options });
/**
* 댓글 쓰기 (60자)
* 댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개)
*/
export const addComment = <ThrowOnError extends boolean = true>(options: Options<AddCommentData, ThrowOnError>): RequestResult<AddCommentResponses, AddCommentErrors, ThrowOnError> => (options.client ?? client).post<AddCommentResponses, AddCommentErrors, ThrowOnError>({
url: '/v1/reaction/post/{post_id}/comment',
@@ -204,7 +221,7 @@ export const addComment = <ThrowOnError extends boolean = true>(options: Options
});
/**
* 내 댓글 지우기
* 내 댓글 지우기 (로그인 없이 쓴 댓글은 같은 IP 에서)
*/
export const deleteComment = <ThrowOnError extends boolean = true>(options: Options<DeleteCommentData, ThrowOnError>): RequestResult<DeleteCommentResponses, DeleteCommentErrors, ThrowOnError> => (options.client ?? client).delete<DeleteCommentResponses, DeleteCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}', ...options });
@@ -214,10 +231,126 @@ export const deleteComment = <ThrowOnError extends boolean = true>(options: Opti
export const unlikeComment = <ThrowOnError extends boolean = true>(options: Options<UnlikeCommentData, ThrowOnError>): RequestResult<UnlikeCommentResponses, UnlikeCommentErrors, ThrowOnError> => (options.client ?? client).delete<UnlikeCommentResponses, UnlikeCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/like', ...options });
/**
* 댓글 좋아요
* 댓글 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likeComment = <ThrowOnError extends boolean = true>(options: Options<LikeCommentData, ThrowOnError>): RequestResult<LikeCommentResponses, LikeCommentErrors, ThrowOnError> => (options.client ?? client).post<LikeCommentResponses, LikeCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/like', ...options });
/**
* 내 각 목록 (로그인하지 않았으면 빈 목록)
*/
export const listMyGak = <ThrowOnError extends boolean = true>(options?: Options<ListMyGakData, ThrowOnError>): RequestResult<ListMyGakResponses, ListMyGakErrors, ThrowOnError> => (options?.client ?? client).get<ListMyGakResponses, ListMyGakErrors, ThrowOnError>({ url: '/v1/my-gak', ...options });
/**
* 이름과 날씨 조건으로 내 각 만들기
*/
export const addMyGak = <ThrowOnError extends boolean = true>(options: Options<AddMyGakData, ThrowOnError>): RequestResult<AddMyGakResponses, AddMyGakErrors, ThrowOnError> => (options.client ?? client).post<AddMyGakResponses, AddMyGakErrors, ThrowOnError>({
url: '/v1/my-gak',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기)
*/
export const listPresets = <ThrowOnError extends boolean = true>(options?: Options<ListPresetsData, ThrowOnError>): RequestResult<ListPresetsResponses, unknown, ThrowOnError> => (options?.client ?? client).get<ListPresetsResponses, unknown, ThrowOnError>({ url: '/v1/my-gak/presets', ...options });
/**
* 조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)
*/
export const scoreMyGak = <ThrowOnError extends boolean = true>(options: Options<ScoreMyGakData, ThrowOnError>): RequestResult<ScoreMyGakResponses, ScoreMyGakErrors, ThrowOnError> => (options.client ?? client).post<ScoreMyGakResponses, ScoreMyGakErrors, ThrowOnError>({
url: '/v1/my-gak/score',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 내 각 지우기
*/
export const deleteMyGak = <ThrowOnError extends boolean = true>(options: Options<DeleteMyGakData, ThrowOnError>): RequestResult<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError> => (options.client ?? client).delete<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError>({ url: '/v1/my-gak/{my_gak_id}', ...options });
/**
* 오늘 피드 묶음 (동네 사람들 + 주제별, 가까운 동네·덜 지난 글 먼저, 한 사람 한 장)
*/
export const talkGroups = <ThrowOnError extends boolean = true>(options?: Options<TalkGroupsData, ThrowOnError>): RequestResult<TalkGroupsResponses, TalkGroupsErrors, ThrowOnError> => (options?.client ?? client).get<TalkGroupsResponses, TalkGroupsErrors, ThrowOnError>({ url: '/v1/talk/groups', ...options });
/**
* 동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기)
*/
export const listTalks = <ThrowOnError extends boolean = true>(options?: Options<ListTalksData, ThrowOnError>): RequestResult<ListTalksResponses, ListTalksErrors, ThrowOnError> => (options?.client ?? client).get<ListTalksResponses, ListTalksErrors, ThrowOnError>({ url: '/v1/talk/list', ...options });
/**
* 내가 쓴 글 (최신순)
*/
export const listMyTalks = <ThrowOnError extends boolean = true>(options?: Options<ListMyTalksData, ThrowOnError>): RequestResult<ListMyTalksResponses, ListMyTalksErrors, ThrowOnError> => (options?.client ?? client).get<ListMyTalksResponses, ListMyTalksErrors, ThrowOnError>({ url: '/v1/talk/mine', ...options });
/**
* 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)
*/
export const addTalk = <ThrowOnError extends boolean = true>(options: Options<AddTalkData, ThrowOnError>): RequestResult<AddTalkResponses, AddTalkErrors, ThrowOnError> => (options.client ?? client).post<AddTalkResponses, AddTalkErrors, ThrowOnError>({
url: '/v1/talk',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 글에 붙일 사진 올리기 (10MB까지, 위치 정보를 지우고 1080px로 줄여 저장)
*/
export const uploadTalkImage = <ThrowOnError extends boolean = true>(options: Options<UploadTalkImageData, ThrowOnError>): RequestResult<UploadTalkImageResponses, UploadTalkImageErrors, ThrowOnError> => (options.client ?? client).post<UploadTalkImageResponses, UploadTalkImageErrors, ThrowOnError>({
...formDataBodySerializer,
url: '/v1/talk/image',
...options,
headers: {
'Content-Type': null,
...options.headers
}
});
/**
* 올린 사진
*/
export const getTalkImage = <ThrowOnError extends boolean = true>(options: Options<GetTalkImageData, ThrowOnError>): RequestResult<GetTalkImageResponses, GetTalkImageErrors, ThrowOnError> => (options.client ?? client).get<GetTalkImageResponses, GetTalkImageErrors, ThrowOnError>({ url: '/v1/talk/image/{name}', ...options });
/**
* 내 이야기 지우기
*/
export const deleteTalk = <ThrowOnError extends boolean = true>(options: Options<DeleteTalkData, ThrowOnError>): RequestResult<DeleteTalkResponses, DeleteTalkErrors, ThrowOnError> => (options.client ?? client).delete<DeleteTalkResponses, DeleteTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}', ...options });
/**
* 이야기 좋아요 취소
*/
export const unlikeTalk = <ThrowOnError extends boolean = true>(options: Options<UnlikeTalkData, ThrowOnError>): RequestResult<UnlikeTalkResponses, UnlikeTalkErrors, ThrowOnError> => (options.client ?? client).delete<UnlikeTalkResponses, UnlikeTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/like', ...options });
/**
* 이야기 좋아요 (로그인 없으면 IP 당 한 번)
*/
export const likeTalk = <ThrowOnError extends boolean = true>(options: Options<LikeTalkData, ThrowOnError>): RequestResult<LikeTalkResponses, LikeTalkErrors, ThrowOnError> => (options.client ?? client).post<LikeTalkResponses, LikeTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/like', ...options });
/**
* 이야기 신고 (서로 다른 3명이면 숨김)
*/
export const reportTalk = <ThrowOnError extends boolean = true>(options: Options<ReportTalkData, ThrowOnError>): RequestResult<ReportTalkResponses, ReportTalkErrors, ThrowOnError> => (options.client ?? client).post<ReportTalkResponses, ReportTalkErrors, ThrowOnError>({
url: '/v1/talk/{talk_id}/report',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
/**
* 이 글 쓴 사람의 글 안 보기
*/
export const blockTalkAuthor = <ThrowOnError extends boolean = true>(options: Options<BlockTalkAuthorData, ThrowOnError>): RequestResult<BlockTalkAuthorResponses, BlockTalkAuthorErrors, ThrowOnError> => (options.client ?? client).post<BlockTalkAuthorResponses, BlockTalkAuthorErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/block', ...options });
/**
* 워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표
*/
@@ -238,6 +371,21 @@ export const getTodayPage = <ThrowOnError extends boolean = true>(options: Optio
*/
export const getTodayGuPage = <ThrowOnError extends boolean = true>(options: Options<GetTodayGuPageData, ThrowOnError>): RequestResult<GetTodayGuPageResponses, GetTodayGuPageErrors, ThrowOnError> => (options.client ?? client).get<GetTodayGuPageResponses, GetTodayGuPageErrors, ThrowOnError>({ url: '/v1/seo/today/{sido}/{place}/{gu}', ...options });
/**
* 지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)
*/
export const getTomorrowPage = <ThrowOnError extends boolean = true>(options: Options<GetTomorrowPageData, ThrowOnError>): RequestResult<GetTomorrowPageResponses, GetTomorrowPageErrors, ThrowOnError> => (options.client ?? client).get<GetTomorrowPageResponses, GetTomorrowPageErrors, ThrowOnError>({ url: '/v1/seo/tomorrow/{sido}/{place}', ...options });
/**
* 구로 나뉜 시의 구 내일 날씨 페이지
*/
export const getTomorrowGuPage = <ThrowOnError extends boolean = true>(options: Options<GetTomorrowGuPageData, ThrowOnError>): RequestResult<GetTomorrowGuPageResponses, GetTomorrowGuPageErrors, ThrowOnError> => (options.client ?? client).get<GetTomorrowGuPageResponses, GetTomorrowGuPageErrors, ThrowOnError>({ url: '/v1/seo/tomorrow/{sido}/{place}/{gu}', ...options });
/**
* 만든 카드뉴스 목록 (관리자). 다시 내려받거나 올릴 때
*/
export const listCards = <ThrowOnError extends boolean = true>(options?: Options<ListCardsData, ThrowOnError>): RequestResult<ListCardsResponses, ListCardsErrors, ThrowOnError> => (options?.client ?? client).get<ListCardsResponses, ListCardsErrors, ThrowOnError>({ url: '/v1/card', ...options });
/**
* 카드뉴스 저장 (관리자). publish 면 바로 그날 피드에 올린다
*/
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -58,8 +58,8 @@ async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<
const anonymous = await fetch(withToken(retry, null))
if (anonymous.status !== 401) return anonymous
}
// 로그아웃하다 만료된 거면 로그인 창을 띄우지 않는다
if (new URL(request.url).pathname !== '/v1/auth/logout') emitAuthRequired()
// 로그인 창은 사람이 한 동작(글쓰기·댓글 등)에만 띄운다. 화면이 알아서 받는 GET(내 정보 등)이나 로그아웃이 만료로 401이면 조용히 로그아웃 상태로 둔다
if (request.method !== 'GET' && new URL(request.url).pathname !== '/v1/auth/logout') emitAuthRequired()
return response
}
+34 -5
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation } from 'react-router'
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
import { useIsFetching, useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen'
import { cx } from '../lib/utils'
@@ -202,12 +202,41 @@ function FirstLoad() {
)
}
// 페이지마다 마지막 스크롤 위치: 뒤로 가기로 돌아오면 그 자리로
const scrolled = new Map<string, number>()
function Shell() {
const { pathname } = useLocation()
const { pathname, key } = useLocation()
const navType = useNavigationType()
const { kind } = useSky()
useEffect(() => {
window.scrollTo({ top: 0 })
}, [pathname])
const save = () => scrolled.set(key, window.scrollY)
window.addEventListener('scroll', save, { passive: true })
return () => window.removeEventListener('scroll', save)
}, [key])
useEffect(() => {
const top = navType === 'POP' ? scrolled.get(key) : undefined
if (top == null) {
window.scrollTo({ top: 0 })
return
}
// 피드가 다시 그려져 그 높이가 될 때까지 최대 3초 맞추고, 그 사이 사람이 화면을 만지면 멈춘다
let tries = 0
let raf = 0
const stop = () => cancelAnimationFrame(raf)
const go = () => {
window.scrollTo({ top })
if (Math.abs(window.scrollY - top) > 2 && ++tries < 180) raf = requestAnimationFrame(go)
}
go()
window.addEventListener('touchstart', stop, { once: true, passive: true })
window.addEventListener('wheel', stop, { once: true, passive: true })
return () => {
stop()
window.removeEventListener('touchstart', stop)
window.removeEventListener('wheel', stop)
}
}, [pathname, key, navType])
// 지금 보고 있는 탭을 다시 누르면 맨 위로
const toTopIfHere = (to: string) => () => {
if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' })
@@ -232,7 +261,7 @@ function Shell() {
{TABS.map((t) =>
t.key === 'today' ? (
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
<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)')}>
<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/') || pathname.startsWith('/tomorrow/') ? '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]">
<TabIcon name={t.key} className="size-[30px]" />
</span>
+480
View File
@@ -0,0 +1,480 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, STAGE, headline, md, placeLabels, spread, useFoliage, useLabelSize, type Box, type Kind, type Pt, type Spot, type Stage } from './foliage'
import { useSheet } from './sheetContext'
import { FoliageMapShare, FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Chips, Ic, TAP44 } from './ui'
type View = { s: number; tx: number; ty: number }
type Filter = 'all' | Kind
const DOT_R: Record<Stage, number> = { peak: ICON_R, first: 4, before: 3, gone: 3 }
const MAX_ZOOM = 5
const FIT_TOP = 30
const FIT_BOTTOM = 14
// 이름 우선순위(절정 단풍 > 절정 은행 > 첫 단풍 > 나머지)와 그 이름이 나오기 시작하는 배율(처음 화면 대비)
const pri = (m: Spot) => (m.stage === 'peak' ? (m.kind === 'maple' ? 0 : 1) : m.stage === 'first' ? 2 : 3)
const LABEL_FROM = [1, 1.6, 2.5, 3.5]
// 점이 나오기 시작하는 배율: 처음엔 절정 잎만 보여 차분하게
const DOT_FROM: Record<Stage, number> = { peak: 1, first: 1.6, before: 2.5, gone: 2.5 }
const TAP_R = 24
const SHARE_ICON = 'relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-(--ink2) [&_svg]:stroke-[1.9]'
const SHARE_BTN = `${SHARE_ICON} bg-white/80`
const GROUPS: [Stage, string][] = [
['peak', '지금 절정'],
['first', '곧 절정'],
['before', '아직'],
['gone', '절정 지남'],
]
const FILTERS: [Filter, string][] = [
['all', '전체'],
['maple', '단풍'],
['ginkgo', '은행'],
]
// 단계 표시: 절정은 잎, 첫 단풍은 주황 점, 단풍 전·지남은 회색 점(고르면 점을 크게)
const DOT_CLASS: Record<Stage, string> = { peak: '', first: 'bg-[#d9772e]/85', before: 'bg-[#8f8a80]/60', gone: 'bg-[#8f8a80]/60' }
function StageMark({ m, big }: { m: Spot; big?: boolean }) {
if (m.stage === 'peak') return <Ic name={m.kind} className={cx('relative', big ? 'size-8' : 'size-5', LEAF_SHADOW)} />
return <i className={cx('b-keep-bg relative rounded-full', DOT_CLASS[m.stage], big ? 'size-3.5' : m.stage === 'first' ? 'size-[7px]' : 'size-[5px]')} />
}
function Marker({ p, sel }: { p: Pt; sel: boolean }) {
return (
<span className={cx('pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center', sel && 'z-[3]')} style={{ left: p.x, top: p.y }}>
{/* 고른 명소는 속이 빈 고리만: 옆 명소를 가리지 않게 */}
{sel && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<StageMark m={p.m} big={sel && p.m.stage !== 'peak'} />
</span>
)
}
/** 단풍 지도 페이지: 명소 65곳을 지도에서 확대해 보고 목록으로 고른다. 한 손가락은 확대 전엔 페이지 스크롤, 확대 뒤엔 지도 이동 */
export function FoliagePage() {
const navigate = useNavigate()
const [params] = useSearchParams()
const { today, spots } = useFoliage()
const [filter, setFilter] = useState<Filter>('all')
const [sel, setSel] = useState<string | null>(params.get('spot'))
const linked = useRef(params.get('spot'))
const { open } = useSheet()
const [shareSpot, setShareSpot] = useState<Spot | null>(null)
const [shareReq, setShareReq] = useState(0)
const spotShotRef = useRef<HTMLDivElement>(null)
const mapShotRef = useRef<HTMLDivElement>(null)
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.kind === filter), [spots, filter])
const vpRef = useRef<HTMLDivElement>(null)
const [box, setBox] = useState({ W: 0, H: 0 })
const [view, setView] = useState<View>({ s: 1, tx: 0, ty: 0 })
const viewRef = useRef(view)
useLayoutEffect(() => {
viewRef.current = view
}, [view])
const size = useLabelSize(vpRef, spots)
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
const fit = useMemo<View>(() => {
const { W, H } = box
if (!W) return { s: 1, tx: 0, ty: 0 }
const xs = spots.map((m) => m.x)
const ys = spots.map((m) => m.y)
const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)]
// 위쪽은 맨 북쪽 이름표가 잘리지 않게 FIT_TOP 만큼 띄우고, 아래는 제주까지만
const h = H - FIT_TOP - FIT_BOTTOM
const s = Math.min(W / ((x1 - x0 + 0.14) * W), h / ((y1 - y0) * W))
return { s, tx: W / 2 - ((x0 + x1) / 2) * W * s, ty: FIT_TOP + h / 2 - ((y0 + y1) / 2) * W * s }
}, [box, spots])
const clamp = useCallback(
(v: View): View => {
const { W, H } = box
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s))
const w = W * s
// 지도 그림 가장자리가 화면 안쪽으로 너무 들어오지 않게
const tx = Math.min(W * 0.25, Math.max(W * 0.75 - w, v.tx))
const ty = Math.min(H * 0.25, Math.max(H * 0.75 - w, v.ty))
return { s, tx, ty }
},
[box, fit],
)
const anim = useRef(0)
const set = useCallback((v: View) => {
cancelAnimationFrame(anim.current)
setView(v)
}, [])
const animateTo = useCallback(
(to: View) => {
cancelAnimationFrame(anim.current)
const from = viewRef.current
const target = clamp(to)
const start = performance.now()
const step = (now: number) => {
const k = Math.min(1, (now - start) / 280)
const e = 1 - (1 - k) ** 3
setView({ s: from.s + (target.s - from.s) * e, tx: from.tx + (target.tx - from.tx) * e, ty: from.ty + (target.ty - from.ty) * e })
if (k < 1) anim.current = requestAnimationFrame(step)
}
anim.current = requestAnimationFrame(step)
},
[clamp],
)
const zoomAt = useCallback(
(f: number, cx: number, cy: number, smooth = false) => {
const v = viewRef.current
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s * f))
const k = s / v.s
const next = clamp({ s, tx: cx - (cx - v.tx) * k, ty: cy - (cy - v.ty) * k })
if (smooth) animateTo(next)
else set(next)
},
[fit, clamp, animateTo, set],
)
const focus = useCallback(
(m: Spot) => {
const { W, H } = box
const s = Math.max(viewRef.current.s, fit.s * 2.5)
animateTo({ s, tx: W / 2 - m.x * W * s, ty: H * 0.42 - m.y * W * s })
},
[box, fit, animateTo],
)
useLayoutEffect(() => {
const el = vpRef.current
if (!el) return
const ro = new ResizeObserver(() => setBox({ W: el.clientWidth, H: el.clientHeight }))
ro.observe(el)
return () => ro.disconnect()
}, [])
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로
const started = useRef(false)
useEffect(() => {
if (!box.W) return
if (started.current) {
set(clamp(viewRef.current))
return
}
started.current = true
set(fit)
const m = spots.find((s) => s.name === linked.current)
if (m) focus(m)
}, [box, fit, spots, set, clamp, focus])
const pts = useMemo(() => {
const ratio = view.s / fit.s
const visible = shown.filter((m) => m.name === sel || ratio >= DOT_FROM[m.stage] - 0.01)
return spread(visible.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: DOT_R[m.stage] })))
}, [shown, view, box.W, fit.s, sel])
const ptsRef = useRef(pts)
useLayoutEffect(() => {
ptsRef.current = pts
}, [pts])
const labelAt = useMemo(() => {
const ratio = view.s / fit.s
const order = pts.filter((p) => p.m.name === sel || ratio >= LABEL_FROM[pri(p.m)]).sort((a, b) => Number(b.m.name === sel) - Number(a.m.name === sel) || pri(a.m) - pri(b.m))
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }]
return placeLabels(order, pts, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.stage === 'peak' || p.m.name === sel)
}, [pts, size, sel, view.s, fit.s, box])
const provs = useMemo(
() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: view.tx + v.x * box.W * view.s, y: view.ty + v.y * box.W * view.s })), pts, labelBoxes(labelAt, size)),
[view, box.W, pts, labelAt, size],
)
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setSel((cur) => (best && best !== cur ? best : null))
}, [])
// 손가락: 두 손가락은 확대·이동, 한 손가락은 확대했을 때만 지도 이동(아니면 페이지 스크롤), 두 번 누르면 확대
useEffect(() => {
const el = vpRef.current
if (!el) return
let pinch: { d: number; x: number; y: number } | null = null
let one: { x: number; y: number; moved: boolean; scroll: boolean } | null = null
let lastTap = 0
const local = (t: { clientX: number; clientY: number }) => {
const r = el.getBoundingClientRect()
return { x: t.clientX - r.left, y: t.clientY - r.top }
}
const zoomed = () => viewRef.current.s > fit.s * 1.01
const onStart = (e: TouchEvent) => {
if ((e.target as HTMLElement).closest('button')) {
one = null
return
}
cancelAnimationFrame(anim.current)
if (e.touches.length === 2) {
const [a, b] = [local(e.touches[0]), local(e.touches[1])]
pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
one = null
} else if (e.touches.length === 1) {
one = { ...local(e.touches[0]), moved: false, scroll: false }
}
}
const onMove = (e: TouchEvent) => {
if (e.touches.length === 2 && pinch) {
e.preventDefault()
const [a, b] = [local(e.touches[0]), local(e.touches[1])]
const d = Math.hypot(a.x - b.x, a.y - b.y)
const x = (a.x + b.x) / 2
const y = (a.y + b.y) / 2
const v = viewRef.current
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, (v.s * d) / pinch.d))
const k = s / v.s
set(clamp({ s, tx: x - (pinch.x - v.tx) * k, ty: y - (pinch.y - v.ty) * k }))
pinch = { d, x, y }
return
}
if (e.touches.length !== 1 || !one) return
const p = local(e.touches[0])
const first = !one.moved
if (Math.hypot(p.x - one.x, p.y - one.y) > 6) one.moved = true
if (!zoomed() || one.scroll) return
const v = viewRef.current
const next = clamp({ s: v.s, tx: v.tx + p.x - one.x, ty: v.ty + p.y - one.y })
// 첫 움직임이 세로인데 지도가 그쪽 끝에 닿아 더 못 가면 이번 손짓은 페이지 스크롤로 넘긴다
if (first && Math.abs(p.y - one.y) > Math.abs(p.x - one.x) && next.ty === v.ty) {
one.scroll = true
return
}
e.preventDefault()
set(next)
one = { ...p, moved: one.moved, scroll: false }
}
const onEnd = (e: TouchEvent) => {
if (e.touches.length < 2) pinch = null
if (e.touches.length || !one || one.moved) {
if (!e.touches.length) one = null
return
}
e.preventDefault()
const now = Date.now()
if (now - lastTap < 300) {
lastTap = 0
zoomAt(2, one.x, one.y, true)
} else {
lastTap = now
pickAt(one.x, one.y)
}
one = null
}
// 마우스: 끌어서 이동, 누르면 고르기, 두 번 누르면 확대, 트랙패드 오므리기(ctrl+휠)로 확대
let drag: { x: number; y: number; moved: boolean } | null = null
const onDown = (e: PointerEvent) => {
if (e.pointerType !== 'mouse' || (e.target as HTMLElement).closest('button')) return
cancelAnimationFrame(anim.current)
drag = { ...local(e), moved: false }
}
const onPMove = (e: PointerEvent) => {
if (!drag) return
const p = local(e)
if (Math.hypot(p.x - drag.x, p.y - drag.y) > 3) drag.moved = true
const v = viewRef.current
set(clamp({ s: v.s, tx: v.tx + p.x - drag.x, ty: v.ty + p.y - drag.y }))
drag = { ...p, moved: drag.moved }
}
const onUp = () => {
if (drag && !drag.moved) pickAt(drag.x, drag.y)
drag = null
}
const onDbl = (e: MouseEvent) => {
const p = local(e)
zoomAt(2, p.x, p.y, true)
}
const onWheel = (e: WheelEvent) => {
if (!e.ctrlKey) return
e.preventDefault()
const p = local(e)
zoomAt(Math.exp(-e.deltaY * 0.01), p.x, p.y)
}
el.addEventListener('touchstart', onStart, { passive: true })
el.addEventListener('touchmove', onMove, { passive: false })
el.addEventListener('touchend', onEnd, { passive: false })
el.addEventListener('pointerdown', onDown)
window.addEventListener('pointermove', onPMove)
window.addEventListener('pointerup', onUp)
el.addEventListener('dblclick', onDbl)
el.addEventListener('wheel', onWheel, { passive: false })
return () => {
el.removeEventListener('touchstart', onStart)
el.removeEventListener('touchmove', onMove)
el.removeEventListener('touchend', onEnd)
el.removeEventListener('pointerdown', onDown)
window.removeEventListener('pointermove', onPMove)
window.removeEventListener('pointerup', onUp)
el.removeEventListener('dblclick', onDbl)
el.removeEventListener('wheel', onWheel)
}
}, [fit, clamp, set, zoomAt, pickAt])
const chosen = spots.find((m) => m.name === sel)
const pickFromList = (m: Spot) => {
setSel(m.name)
const el = vpRef.current
if (el) window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - 120, behavior: 'smooth' })
focus(m)
}
// 보내기: 공유 창이 이미지(명소 하나면 그 명소 지도 조각, 아니면 전체 지도)와 링크를 같이 보낸다
const share = (m?: Spot) => {
setShareSpot(m ?? null)
setShareReq((n) => n + 1)
}
useEffect(() => {
if (!shareReq) return
const el = shareSpot ? spotShotRef.current : mapShotRef.current
if (el) open({ type: 'share', share: { title: shareSpot ? `${shareSpot.name} 단풍` : '단풍 지도', slides: [el] } })
}, [shareReq, shareSpot, open])
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
const peakSpots = spots.filter((m) => m.stage === 'peak')
const peakCount = peakSpots.length
const ranked = rankNow(spots)
return (
<div className="pb-6">
<div className="flex items-start gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative mt-0.5 grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<div className="min-w-0 flex-1 px-1">
<p className="m-0 flex items-center gap-1 text-[13px] font-extrabold opacity-75">
<Ic name="maple" className="size-4" />
단풍 지도 · {md(today)}
</p>
<h2 className="m-0 mt-0.5 font-jua text-[26px] leading-tight font-normal text-balance">{headline(spots)}</h2>
</div>
<button type="button" onClick={() => share()} aria-label="단풍 지도 보내기" className={cx(SHARE_BTN, 'mt-0.5 shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
<SendIcon />
</button>
</div>
<div ref={vpRef} className="b-keep-bg relative mt-2 h-[min(122vw,calc(100dvh-330px),560px)] min-h-[300px] touch-pan-y overflow-hidden bg-[#fff6ea] select-none">
<img src={MAP_SRC} alt="단풍 지도" draggable={false} className={cx(MAP_IMG, 'max-w-none')} style={{ inset: 'auto', left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{[...pts].sort((a, b) => Number(a.m.stage === 'peak') - Number(b.m.stage === 'peak')).map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 고르기`}
onClick={() => setSel(m.name === sel ? null : m.name)}
className={cx(LABEL, 'cursor-pointer border-0', m.name === sel ? 'z-[3] bg-[#28304a] text-[#ffffff]' : m.stage === 'peak' ? LABEL_INK[m.kind] : 'bg-[#ffffffeb] text-[#5b6075]', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name}
</button>
))}
<div className="absolute top-2.5 right-2.5 z-[4] flex flex-col gap-2">
{(
[
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const
).map(([t, label, f]) => (
<button key={t} type="button" aria-label={label} onClick={() => zoomAt(f, box.W / 2, box.H / 2, true)} className="b-keep-bg grid size-9 cursor-pointer place-items-center rounded-full bg-[#ffffff] text-[20px] font-bold text-[#28304a] shadow-[0_2px_6px_rgb(40_48_74/0.2)]">
{t}
</button>
))}
</div>
</div>
{/* 고른 명소는 범례 자리에: 지도 위를 가리지 않고, 다시 누르거나 빈 곳을 누르면 풀린다 */}
{chosen ? (
<div className="mx-3 mt-2 flex h-[60px] items-center gap-3 rounded-[18px] bg-white px-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<span className="grid size-8 shrink-0 place-items-center">
<StageMark m={chosen} big />
</span>
<div className="min-w-0 flex-1">
<p className="m-0 flex items-center gap-1.5">
<b className="truncate font-jua text-[18px] leading-tight font-normal">{chosen.name}</b>
<span className={cx('shrink-0 rounded-full px-1.5 py-px text-[11px] font-extrabold', chosen.stage === 'peak' ? 'bg-[#ffe3db] text-[#b5321f]' : chosen.stage === 'first' ? 'bg-[#ffe8d2] text-[#a34f12]' : 'bg-(--chip) text-(--ink2)')}>{STAGE[chosen.stage]}</span>
</p>
<p className="m-0 flex gap-1 text-[12px] font-bold text-(--ink3)">
<span className="truncate">{chosen.region}</span>
<span className="shrink-0">· 절정 예상 {md(chosen.peak)}</span>
</p>
</div>
<button type="button" onClick={() => share(chosen)} aria-label={`${chosen.name} 보내기`} className={cx(SHARE_BTN, TAP44)}>
<SendIcon />
</button>
</div>
) : (
<div className="mx-3 mt-2 flex h-[60px] flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="maple" className={cx('size-4', LEAF_SHADOW)} />
단풍 절정
</span>
<span className="flex items-center gap-1">
<Ic name="ginkgo" className={cx('size-4', LEAF_SHADOW)} />
은행 절정
</span>
<span className="flex items-center gap-1">
<i className="b-keep-bg size-[7px] rounded-full bg-[#d9772e]/85" />첫 단풍
</span>
<span className="flex items-center gap-1">
<i className="b-keep-bg size-[5px] rounded-full bg-[#8f8a80]/60" />단풍 전
</span>
</div>
)}
<Chips label="종류" items={FILTERS} value={filter} onChange={setFilter} />
<div className="px-4">
{GROUPS.map(([g, title]) => {
const rows = shown.filter((m) => m.stage === g).sort((a, b) => a.peak.localeCompare(b.peak))
if (!rows.length) return null
return (
<section key={g} aria-label={title} className="pt-5">
<h3 className="m-0 flex items-baseline gap-1.5 px-1 pb-1.5 font-jua text-[19px] font-normal">
{title}
<span className="font-sans text-[13px] font-extrabold text-(--ink3)">{rows.length}곳</span>
</h3>
<ul className="m-0 list-none border-t border-(--line) p-0">
{rows.map((m) => (
<li key={m.name} className={cx('flex items-center border-b border-(--line)', m.name === sel && 'bg-[rgb(255_122_69/0.08)]')}>
<button type="button" onClick={() => pickFromList(m)} aria-current={m.name === sel || undefined} className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 py-2.5 pl-1 text-left">
<span className="grid size-7 shrink-0 place-items-center">
<StageMark m={m} big />
</span>
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-(--ink3)">
{m.region} · {m.own ? '절정 예상' : '가까운 지점 날짜'}
</small>
</span>
<b className={cx('shrink-0 font-jua text-[18px] font-normal tabular-nums', g === 'peak' ? 'text-(--orange)' : 'text-(--ink2)')}>{md(m.peak)}</b>
</button>
<button type="button" onClick={() => share(m)} aria-label={`${m.name} 보내기`} className={cx(SHARE_ICON, 'ml-1', TAP44)}>
<SendIcon />
</button>
</li>
))}
</ul>
</section>
)
})}
<FoliageSpotShare spot={shareSpot} peak={peakSpots} ref={spotShotRef} />
<FoliageMapShare title={headline(spots)} peak={peakSpots} ranked={ranked} ref={mapShotRef} />
<p className="m-0 px-1.5 pt-4 text-[11.5px] leading-relaxed font-semibold text-(--ink3)">
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요{peakCount ? ` · 지금 절정 ${peakCount}곳` : ''}
</p>
</div>
</div>
)
}
+108 -11
View File
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react'
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode, type RefObject } from 'react'
import { createPortal } from 'react-dom'
import { PostType, SlotTone, type GakSlide, type HoursSlide, type ImageSlide, 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 ImageSlide, type PlanSlide, type PostData, type PostReaction, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
import { API_BASE_URL } from '../api/setup'
import { cx } from '../lib/utils'
import { cardBg, clockShort, fall } from './lib'
@@ -8,7 +8,7 @@ import type { SlideBg } from './types'
import { deg } from './weatherText'
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
import { useAuth } from './authContext'
import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { useSheet } from './sheetContext'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { useCarousel } from './carousel'
@@ -30,6 +30,11 @@ const ACCOUNTS: Record<PostType, readonly [string, string]> = {
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
[PostType.MOON]: ['오늘 밤 달', 'moon'],
[PostType.UV]: ['자외선', 'glasses'],
[PostType.HERO]: ['오늘 날씨', 'sun'],
[PostType.TODAY_GAK]: ['오늘의 각', 'rabbit'],
[PostType.FOLIAGE]: ['단풍 지도', 'maple'],
[PostType.EVENTS_BAND]: ['이번 주 가까운 행사', 'fireworks'],
[PostType.SEASON_BAND]: ['이번 주 계절 이야기', 'fallen_leaf'],
[PostType.CARD]: ['날씨각 카드', 'stars'],
}
@@ -55,6 +60,22 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
const DARK = new Set<SlideBg>(['dusk', 'night'])
// 그림 배경이 있는 각(code)과 장 수. 여러 장이면 글마다 돌려 쓴다
const BG_IMAGES: Record<string, number> = { bike: 4, picnic: 1, hiking: 1, camping: 1, stars: 1, walk: 1, hangang: 1 }
const EVENT_BG_N = 4
function bgImage(name: string, n: number, seed: number): CSSProperties {
const file = n > 1 ? `${name}-${'abcd'[seed % n]}` : name
return { backgroundImage: `url(/post-bg/${file}.webp)`, backgroundSize: 'cover', backgroundPosition: 'center' }
}
/** 그림 배경: 각은 각마다, 사진 없는 행사는 행사용. 없으면 색 배경만 */
function slideImage(post: PostData, slide: Slide): CSSProperties | undefined {
if (slide.kind === 'gak') return BG_IMAGES[slide.code] ? bgImage(slide.code, BG_IMAGES[slide.code], post.post_id) : undefined
if (post.post_type === PostType.EVENT && slide.kind === 'rows' && !slide.image) return bgImage('event', EVENT_BG_N, post.post_id)
return undefined
}
function Lines({ text }: { text: string }) {
return text.split('\n').map((t, i) => (
<span key={i}>
@@ -75,14 +96,14 @@ function Big({ children, className }: { children: ReactNode; className?: string
function Pic({ name, className }: { name: string; className?: string }) {
return (
<span className={cx('b-fall pointer-events-none absolute top-[30%] right-3.5 w-[42%]', className)} style={fall('.1s', '5s')}>
<Ic name={name} className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
<Ic name={name} className="b-bob w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
</span>
)
}
const slideBase = 'relative flex h-full w-full shrink-0 flex-col px-5 py-[22px]'
function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
const { open } = useSheet()
if (slide.kind === 'hours') {
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]))
@@ -117,10 +138,17 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
}
if (slide.kind === 'gak')
return (
<div className={cx(slideBase, `b-bg-${bg}`)}>
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
<Big>{slide.line}</Big>
<Pic name={slide.code} />
{slide.say && <p className="relative z-[1] m-0 mt-2.5 w-[56%] rounded-[16px] rounded-tl-[4px] bg-white/80 px-3 py-2 text-[14px] leading-snug font-bold">{slide.say}</p>}
{/* 점수 근거: 비중 큰 조건과 지금 값. 오른쪽 아이콘과 겹치지 않게 왼쪽 반만 */}
{!!slide.rows?.length && (
<div className="relative z-[1] mt-2 w-[56%] rounded-[16px] bg-white/70 px-3 text-[14px] [&_b]:text-[15px] [&>div>div]:py-1.5 [&>div]:mt-0">
<Rows rows={slide.rows} />
</div>
)}
<b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b>
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
@@ -229,7 +257,7 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
</div>
)
return (
<div className={cx(slideBase, `b-bg-${bg}`)}>
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<Eyebrow className={DARK.has(bg) ? 'opacity-85' : undefined}>{slide.eyebrow}</Eyebrow>
<Big className="relative z-[1]">
<Lines text={slide.line} />
@@ -318,7 +346,6 @@ export function PostCardSkel() {
function FullCard({ post }: PostProps) {
const { open } = useSheet()
const { loggedIn } = useAuth()
const liked = !!post.liked
const likeCount = post.like_count
const queryClient = useQueryClient()
@@ -344,7 +371,6 @@ function FullCard({ post }: PostProps) {
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
const setLike = (on: boolean) => {
if (!loggedIn) return open({ type: 'login' })
if (on === liked || like.isPending || unlike.isPending) return
if (on) setPop((p) => p + 1)
setLikeFailed(0)
@@ -369,7 +395,7 @@ function FullCard({ post }: PostProps) {
if ((e.target as HTMLElement).closest('button')) return
const now = Date.now()
if (now - lastTap.current < 320) {
if (liked && loggedIn) setPop((p) => p + 1)
if (liked) setPop((p) => p + 1)
else setLike(true)
}
lastTap.current = now
@@ -407,7 +433,7 @@ function FullCard({ post }: PostProps) {
>
<div ref={trackRef} className="flex h-full">
{post.slides.map((s, i) => (
<SlideView key={i} slide={s} bg={bgs[i]} />
<SlideView key={i} slide={s} bg={bgs[i]} img={slideImage(post, s)} />
))}
</div>
</div>
@@ -463,3 +489,74 @@ function FullCard({ post }: PostProps) {
</article>
)
}
type FrameProps = {
title: string
account: string
avatar: string
caption?: ReactNode
more?: ReactNode
shot?: RefObject<HTMLDivElement | null>
pinned?: { key: PinnedKey; post?: PostReaction | null }
children: ReactNode
}
/** 피드 글과 같은 틀(계정 줄·본문·보내기 줄)에 날씨·각 같은 화면 조각을 담는다. 보내기는 shot(공유용 틀)이 있으면 그것을, 없으면 본문을 이미지로 */
export function PostFrame({ title, account, avatar, caption, more, shot, pinned, children }: FrameProps) {
const { open } = useSheet()
const bodyRef = useRef<HTMLDivElement>(null)
const like = usePinnedLike(pinned?.key ?? 'gak_post', pinned?.post)
const postId = pinned?.post?.post_id
const share = () => {
const el = shot?.current ?? bodyRef.current
if (el) open({ type: 'share', share: { title, slides: [el] } })
}
return (
<article className="mt-3.5 border-y border-(--line) bg-white first:mt-1" aria-label={title}>
<div className="flex items-center gap-2.5 px-3 py-2.5">
<span className="b-ring size-[34px] shrink-0 rounded-full p-0.5">
<i className="grid size-full place-items-center rounded-full bg-white">
<Ic name={avatar} className="w-[22px]" />
</i>
</span>
<span>
<b className="block text-sm leading-tight font-extrabold">날씨각</b>
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span>
</div>
<div ref={bodyRef}>{children}</div>
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
{postId != null && (
<>
<button type="button" onClick={like.toggle} aria-pressed={like.liked} aria-label="좋아요" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
<HeartIcon className={like.liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink)'} />
</button>
<button type="button" onClick={() => open({ type: 'comments', postId })} aria-label="댓글 보기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
<CommentIcon className="fill-none stroke-(--ink) [stroke-linejoin:round]" />
</button>
</>
)}
<button type="button" onClick={share} aria-label="보내기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
</button>
{more && <span className="ml-auto text-[13px] font-bold text-(--ink2)">{more}</span>}
</div>
{postId != null && (
<p className="px-3 py-0.5 text-sm font-extrabold">
{like.failed ? <span className="text-(--heart)" role="alert">좋아요를 반영하지 못했어요. 다시 해 주세요.</span> : `좋아요 ${like.count.toLocaleString()}개`}
</p>
)}
{caption && (
<p className="px-3 pt-0.5 pb-3 text-sm">
<b className="mr-[5px] font-extrabold">날씨각</b>
{caption}
</p>
)}
{postId != null && (
<button type="button" onClick={() => open({ type: 'comments', postId })} className="block cursor-pointer px-3 pb-3 text-sm font-semibold text-(--ink3)">
{pinned?.post?.comment_count ? `댓글 ${pinned.post.comment_count}개 모두 보기` : '첫 댓글 남기기'}
</button>
)}
</article>
)
}
+1 -1
View File
@@ -82,7 +82,7 @@ export function SeasonPage() {
<p className="m-0 text-[13px] font-extrabold opacity-75">이번 주 특집{w.start && w.end ? ` · ${dateRange(w.start, w.end)}` : ''}</p>
<p className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight">{w.headline}</p>
<span className="b-fall pointer-events-none absolute top-[18%] right-3.5 w-[38%]" style={fall('.1s')}>
<Ic name="maple" className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
<Ic name="maple" className="b-bob w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
</span>
{(w.poem_lines ?? []).length > 0 && (
<p className="mt-auto max-w-[72%] pt-3 font-batang text-[22px] leading-[1.7]">
+56 -69
View File
@@ -14,22 +14,26 @@ import {
listCommentsInfiniteOptions,
listCommentsInfiniteQueryKey,
listRegionsOptions,
loginMutation,
meQueryKey,
signupMutation,
unlikeCommentMutation,
updateMeMutation,
} from '../api/client/@tanstack/react-query.gen'
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen'
import { AuthProvider, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '../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 { GoogleButton } from './googleLogin'
import { useInstall, useInstallable } from './install'
import { InstallSheet } from './installBanner'
import { WeatherWhySheet } from './weatherWhy'
import { MixSheet } from './myGak'
import { ownPage, useRegion } from './regionContext'
import { useSky } from './skyContext'
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
import { HeartIcon } from './svg'
import { MyTalks } from './talk'
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
export function SheetProvider({ children }: { children: ReactNode }) {
@@ -72,7 +76,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
)
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요' } as const
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
@@ -96,13 +100,15 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const root = document.documentElement
const before = root.style.overflow
root.style.overflow = 'hidden'
root.classList.add('b-sheet-open')
return () => {
root.style.overflow = before
root.classList.remove('b-sheet-open')
}
}, [isOpen])
const then = state?.type === 'login' ? state.then : undefined
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type]
return (
<dialog
@@ -132,6 +138,9 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />}
{state.type === 'install' && <InstallSheet />}
{state.type === 'weatherWhy' && <WeatherWhySheet d={state.why} />}
</div>
)}
{!state && <RegionLinks />}
@@ -354,7 +363,7 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
</div>
<b className={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b>
</div>
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금은 제철이 아니에요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{now && (
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
@@ -519,14 +528,14 @@ function ShareSheet({ share }: { share: SharePayload }) {
const srcs = useRef<string[]>([])
const [toast, setToast] = useState('')
const image = images[size]
const text = `${share.title} · 날씨각 ${SITE_URL}`
const text = `${share.title} · 날씨각`
// 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다
useEffect(() => {
if (images[size] || failed[size]) return
let alive = true
const today = new Date().toLocaleDateString('ko-KR', { month: 'long', day: 'numeric', weekday: 'long' })
shareImage(share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then(
shareImage(size === 'square' && share.square ? share.square : share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then(
(blob) => {
if (!alive) return
const src = URL.createObjectURL(blob)
@@ -541,21 +550,28 @@ function ShareSheet({ share }: { share: SharePayload }) {
return () => {
alive = false
}
}, [size, images, failed, share.slides, kind, region.name])
}, [size, images, failed, share.slides, share.square, kind, region.name])
useEffect(() => {
const list = srcs.current
return () => list.forEach((s) => URL.revokeObjectURL(s))
}, [])
// 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 공유창이 없으면 이미지를 내려받고 링크를 복사한다
// 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 이미지만 받는 앱이 있어 링크도 복사해 둔다. 공유창이 없으면 이미지를 내려받고 링크를 복사한다
const send = () => {
if (!image) return
const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' })
if (navigator.canShare?.({ files: [file], text })) {
navigator.share({ files: [file], title: share.title, text }).then(
() => {
setToast('보냈어요')
if (navigator.canShare?.({ files: [file], text, url: SITE_URL })) {
const copied = navigator.clipboard?.writeText(SITE_URL).then(
() => true,
(e: unknown) => {
console.error('[share] copy link', e)
return false
},
)
navigator.share({ files: [file], title: share.title, text, url: SITE_URL }).then(
async () => {
setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요')
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
},
(e: unknown) => {
@@ -575,7 +591,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
setToast('이미지를 내려받았어요')
return
}
navigator.clipboard.writeText(text).then(
navigator.clipboard.writeText(`${text} ${SITE_URL}`).then(
() => setToast('이미지를 내려받고 링크를 복사했어요'),
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
)
@@ -614,8 +630,6 @@ const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
const { region } = useRegion()
const { loggedIn } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const [liked, setLiked] = useState(c.liked)
const [count, setCount] = useState(c.like_count)
@@ -626,7 +640,6 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
const [likeFailed, setLikeFailed] = useState(false)
const toggle = () => {
if (!loggedIn) return open({ type: 'login' })
if (like.isPending || unlike.isPending) return
const next = !liked
setLikeFailed(false)
@@ -708,8 +721,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
const { region } = useRegion()
const { open } = useSheet()
const { loggedIn, me } = useAuth()
const { me } = useAuth()
const queryClient = useQueryClient()
const list = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
@@ -724,12 +736,11 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
const submit = (e: FormEvent) => {
e.preventDefault()
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } })
const body = text.trim()
if (!body || add.isPending) return
setAddFailed(false)
add.mutate(
{ path: { post_id: postId }, body: { body } },
{ path: { post_id: postId }, body: { body, region: region.code } },
{
onSuccess: (res) => {
setAddFailed(!res.result?.success)
@@ -783,7 +794,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
</p>
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
<button type="submit" disabled={add.isPending || (loggedIn && !text.trim())} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
<button type="submit" disabled={add.isPending || !text.trim()} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
<Swap labels={['게시', '올리는 중…']} at={add.isPending ? 1 : 0} />
</button>
</form>
@@ -792,79 +803,49 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
}
/* ---------- 로그인 ---------- */
const AUTH_ERRORS: Record<string, string> = {
AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.',
AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.',
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.',
}
function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
const { me } = useAuth()
const [mode, setMode] = useState<'login' | 'signup'>('login')
const [loginId, setLoginId] = useState('')
const [password, setPassword] = useState('')
const [nickname, setNickname] = useState('')
const [error, setError] = useState('')
const login = useMutation(loginMutation())
const signup = useMutation(signupMutation())
const pending = login.isPending || signup.isPending
const done = (res: ResAuth) => {
if (!res.result?.success || !res.access_token) {
setError(AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.')
setError('구글로 로그인하지 못했어요. 다시 해 주세요.')
return
}
setTokens(res.access_token, res.refresh_token ?? null)
track(mode === 'login' ? 'login' : 'sign_up', { method: 'id' })
track('login', { method: 'google' })
onLoggedIn()
}
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
const submit = (e: FormEvent) => {
e.preventDefault()
setError('')
if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: done, onError: fail })
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: done, onError: fail })
}
if (me) return <MeSheet onDone={onDone} />
const field = 'w-full rounded-[14px] border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-3'
return (
<Body>
<form onSubmit={submit} className="flex flex-col gap-2.5">
<p className="text-center text-sm font-semibold text-(--ink2)">좋아요·댓글은 로그인한 뒤에 할 수 있어요.</p>
<div className="grid grid-cols-2 gap-1 rounded-full bg-[#f3f6fb] p-1" role="group" aria-label="로그인 또는 가입">
{(
[
['login', '로그인'],
['signup', '처음이에요'],
] as const
).map(([m, l]) => (
<button key={m} type="button" aria-pressed={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full py-2 text-sm font-extrabold', mode === m ? 'bg-(--ink) text-white' : 'text-(--ink2)')}>
{l}
</button>
))}
</div>
<input value={loginId} onChange={(e) => setLoginId(e.target.value)} autoComplete="username" required minLength={4} maxLength={20} placeholder="아이디" aria-label="아이디" className={field} />
<input value={password} onChange={(e) => setPassword(e.target.value)} type="password" autoComplete={mode === 'login' ? 'current-password' : 'new-password'} required minLength={mode === 'signup' ? 8 : undefined} maxLength={64} placeholder={mode === 'signup' ? '비밀번호 (8자 이상)' : '비밀번호'} aria-label="비밀번호" className={field} />
{mode === 'signup' && <input value={nickname} onChange={(e) => setNickname(e.target.value)} required minLength={2} maxLength={12} placeholder="닉네임 (2~12자)" aria-label="닉네임" className={field} />}
<p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
<div className="flex flex-col gap-2.5">
<p className="text-center text-sm font-semibold text-(--ink2)">글쓰기는 로그인한 뒤에 할 수 있어요.</p>
<GoogleButton
onResult={(res) => {
setError('')
done(res)
}}
onFail={fail}
/>
<p className="m-0 text-center text-[13px] font-bold text-(--heart) empty:hidden" aria-live="polite">
{error}
</p>
<button type="submit" disabled={pending} className="cursor-pointer rounded-[14px] bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
<Swap labels={mode === 'login' ? ['로그인', '로그인 중…'] : ['가입하고 시작하기', '가입하는 중…']} at={pending ? 1 : 0} />
</button>
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
나중에 할게요
</button>
</form>
</div>
</Body>
)
}
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
function MeSheet({ onDone }: { onDone: () => void }) {
const install = useInstall()
const installable = useInstallable()
const { me, logout } = useAuth()
const queryClient = useQueryClient()
const update = useMutation(updateMeMutation())
@@ -898,8 +879,13 @@ function MeSheet({ onDone }: { onDone: () => void }) {
<Body className="flex flex-col gap-3">
<div className="flex flex-col items-center gap-1.5">
<Avatar character={me.character} color={me.color} mood={me.mood} size={64} />
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.login_id}(으)로 로그인했어요</p>
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
</div>
{installable && (
<button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
📲 홈 화면에 추가
</button>
)}
<section aria-label="내 캐릭터">
<h4 className="m-0 mb-2 text-sm font-extrabold">내 캐릭터</h4>
<div className="grid grid-cols-3 gap-2" role="radiogroup" aria-label="캐릭터 고르기">
@@ -972,6 +958,7 @@ function MeSheet({ onDone }: { onDone: () => void }) {
<p className={cx('m-0 min-h-5 text-center text-[13px] font-bold', saving ? 'text-(--ink2)' : 'text-(--heart)')} aria-live="polite">
{saving ? (saving.nickname == null ? '저장 중…' : '') : error}
</p>
<MyTalks />
<button
type="button"
onClick={() => {
+44
View File
@@ -0,0 +1,44 @@
import { useSearchParams } from 'react-router'
import type { TalkTopic } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { TalkCard } from './talk'
import { TOPICS, useTopicTalks } from './talkState'
import { Sec } from './ui'
/** 주제별 사람 글: 위 주제 탭, 아래 글 목록. 피드 묶음의 '전체 보기'가 ?topic= 으로 연다 */
export function TalkPage() {
const [params, setParams] = useSearchParams()
const raw = Number(params.get('topic'))
const topic = TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : undefined
const { talks, loaded, more, loadMore } = useTopicTalks(topic)
const tabs: (readonly [TalkTopic | undefined, string])[] = [[undefined, '전체'], ...TOPICS]
return (
<section aria-label="동네 사람들 글">
<Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" />
<div className="flex flex-wrap gap-1.5 px-4 pb-1" role="tablist" aria-label="글 주제">
{tabs.map(([k, label]) => (
<button
key={label}
type="button"
role="tab"
aria-selected={topic === k}
onClick={() => setParams(k ? { topic: String(k) } : {}, { replace: true })}
className={cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold', topic === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2)')}
>
{label}
</button>
))}
</div>
{loaded && !talks.length && <p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">아직 이 주제 글이 없어요. 오늘 탭에서 첫 글을 써 주세요.</p>}
{talks.map((t) => (
<TalkCard key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
))}
{more && (
<button type="button" onClick={() => loadMore()} className="mx-3 mt-3 w-[calc(100%-1.5rem)] cursor-pointer rounded-[14px] bg-white py-2.5 text-[13.5px] font-extrabold text-(--ink2)">
더 보기
</button>
)}
</section>
)
}
+402 -121
View File
@@ -1,15 +1,37 @@
import { Fragment, useEffect, useState, type ReactNode } from 'react'
import { Link } from 'react-router'
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
import { Link, useLocation } 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 {
PostType,
RainType,
Sky,
TalkTopic,
type BandArticle,
type BandEvent,
type Hero as HeroData,
type PostReaction,
type ResWeatherToday,
type TalkData,
type TopIndex,
type WeatherSlot,
} from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
import { PostCard, PostCardSkel } from './Post'
import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner'
import { MyGakRow } from './myGak'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { FeedComposer, NearTalks, TalkCard, TalkGroup } from './talk'
import { topicName, useTalkGroups } from './talkState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { useSky } from './skyContext'
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
import { DayShareCard, DayShareGrid, GakShareCard, type DayShare } from './shareCards'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
import { deg, slotAt } from './weatherText'
type Mode = 'now' | TimeKind
@@ -24,10 +46,24 @@ const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
}
// 비·눈 줄기: 위치·주기를 엇갈려 고르게
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 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 STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
const STARS = Array.from({ length: 26 }, (_, i) => ({
left: `${(i * 37) % 100}%`,
top: `${(i * 53) % 60}%`,
opacity: 0.4 + ((i * 7) % 6) / 10,
}))
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
const SHOOTS = [
{ top: '6%', left: '80%', '--len': '90px', '--dur': '7s', '--dl': '1.5s' },
@@ -65,20 +101,40 @@ 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' }
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),
...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
post?: PostReaction | null
today?: ResWeatherToday
ranked: TopIndex[]
all: TopIndex[]
feedLoad: Load
todayLoad: Load
}
type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet'
@@ -91,26 +147,67 @@ function weatherOf(slot?: WeatherSlot): Weather {
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 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' },
{ cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' },
{ cls: 'top-[30px] left-[72%] h-7 w-[64px]', d: '.4s', f: '5.4s' },
]
const CLOUD_N: Record<Weather, number> = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3 }
const CLOUD_N: Record<Weather, number> = {
clear: 0,
partly: 2,
cloudy: 3,
rain: 3,
snow: 3,
sleet: 3,
}
function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps) {
const { open } = useSheet()
const like = usePinnedLike('hero_post', post)
const { region } = useRegion()
const tplRef = useRef<HTMLDivElement>(null)
const gridRef = useRef<HTMLDivElement>(null)
// 내일 스위치: 내일 칸 날씨는 켤 때 받고, 시간대는 화면 전체 하늘과 따로 히어로 안에서만 고른다
// 내일 날씨 페이지(/tomorrow/...)로 들어오면 내일이 켜진 채로
const { pathname } = useLocation()
const [tmr, setTmr] = useState(() => pathname.startsWith('/tomorrow/'))
const [tmrKind, setTmrKind] = useState<TimeKind>('day')
const tomorrowQ = useQuery({
...getWeatherTodayOptions({
query: { region: region.code, day: 'tomorrow' },
}),
enabled: tmr,
})
const ahead = hero?.tomorrow
const share = () =>
tplRef.current &&
open({
type: 'share',
share: {
title: `${region.name} ${tmr ? '내일' : '오늘'} 날씨`,
slides: [tplRef.current],
square: gridRef.current ? [gridRef.current] : undefined,
},
})
const { preview, setServerKind, setPreview } = useSky()
const mode: Mode = preview ?? 'now'
const mode: Mode = tmr ? tmrKind : (preview ?? 'now')
const clock = useNow()
const t = kst(clock)
const t = kst(tmr ? new Date(clock.getTime() + 86400000) : clock)
const nowKind = hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)
const kind = mode === 'now' ? nowKind : mode
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind])
const slots = today?.slots ?? []
const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? []
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad
// 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
// 지금은 가장 가까운 3시간 칸(17시면 18시 칸). 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
const slotOf = (k: TimeKind | 'now') => {
@@ -124,22 +221,78 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s)
}
const weather = weatherOf(slotOf(mode))
const slotScore = mode === 'now' ? undefined : hero?.weather_slots?.[SLOT_KEY[mode]]
const score = slotScore ?? hero?.weather_score
const slotTop = mode === 'now' ? undefined : ranked.find((g) => g.active)
const top1 = slotTop ?? hero?.top1
const slotScore = mode === 'now' ? undefined : (tmr ? ahead?.weather_slots : hero?.weather_slots)?.[SLOT_KEY[mode]]
const score = tmr ? slotScore : (slotScore ?? hero?.weather_score)
// 점수 옆 ? 버튼: 보고 있는 시간대(지금이면 지금 구간)의 날씨 점수 근거
const whyKey = mode === 'now' ? SLOT_KEY[nowKind] : SLOT_KEY[mode]
const why = (tmr ? ahead?.weather_why : hero?.weather_why)?.[whyKey]
const whyLabel = tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label
const slotTop = mode === 'now' || tmr ? undefined : ranked.find((g) => g.active)
const top1 = tmr ? ahead?.top1 : (slotTop ?? hero?.top1)
// 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다
const moon = (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null ? { name: hero.moon_name, pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null
const moon =
!tmr && (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null
? {
name: hero.moon_name,
pct: hero.moon_pct,
waning: WANING.includes(hero.moon_name),
}
: null
// 말풍선 머리말은 칸 이름 그대로: 지금은 / 아침은 / 낮은 / 저녁은 / 밤은
const when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label
const bubble = slotTop ? (slotTop.score >= 70 ? `${when}은 ${slotTop.name}!` : `${when}은 쉬어 가요`) : hero ? (hero.bubble ?? '지금은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
const status = hero?.status ?? []
const bubble = tmr
? top1
? top1.score >= 70
? `내일은 ${top1.name}!`
: '내일은 쉬어 가요'
: null
: slotTop
? slotTop.score >= 70
? `${when}은 ${slotTop.name}!`
: `${when}은 쉬어 가요`
: hero
? (hero.bubble ?? '지금은 쉬어 가요')
: failed(feedLoad)
? '앗, 날씨를 못 불러왔어요'
: null
// 내일은 최저·최고 기온과 고른 시간대 습도
const temps = slots.flatMap((x) => (x.temp_c != null ? [x.temp_c] : []))
const humidity = tmr && mode !== 'now' ? slotOf(mode)?.humidity : null
const status = tmr
? [
...(temps.length
? [
{ label: '최저', value: deg(Math.min(...temps)), tone: 'info' },
{ label: '최고', value: deg(Math.max(...temps)), tone: 'info' },
]
: []),
...(humidity != null ? [{ label: '습도', value: `${humidity}%`, tone: 'info' }] : []),
]
: (hero?.status ?? [])
const rain = weather === 'rain' || weather === 'sleet'
const snow = weather === 'snow' || weather === 'sleet'
// 공유 이미지: 아침~밤 네 시간대 모두. 점수는 시간대 점수, 각은 그 시간대 1등
const days: DayShare[] = KINDS.map((k) => {
const isNow = !tmr && k === nowKind
const s = slotOf(isNow ? 'now' : k)
const top = tmr ? ahead?.top1 : atSlot(all, k).find((g) => g.active)
return {
kind: k,
label: PREVIEW[k].label,
now: isNow,
icon: k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)],
temp: s?.temp_c != null ? deg(s.temp_c) : '–',
score: (tmr ? ahead?.weather_slots : hero?.weather_slots)?.[SLOT_KEY[k]] ?? (isNow ? hero?.weather_score : null),
gak: top ? { name: top.name, icon: top.icon } : null,
}
})
// 시안 D4-2: 가운데 해(점수)와 하늘 날씨, 결론 두 줄, 상태 한 줄, 아래 하루 흐름 칸(누르면 그 시간대 하늘로)
return (
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3" data-t={kind} data-sky={weather}>
<DayShareCard days={days} ref={tplRef} />
<DayShareGrid days={days} ref={gridRef} />
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
{STARS.map((s, i) => (
<i key={i} className="absolute size-[3px] rounded-full shadow-[0_0_6px_#fff]" style={s} />
@@ -154,29 +307,109 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
{snow && FLAKES.map((s, i) => <i key={i} className="b-flake" style={s} />)}
</div>
)}
<p className="relative z-[3] m-0 text-[14px] font-bold opacity-80">
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</p>
<div className="relative z-[3] flex items-center justify-between">
<span className="flex items-center gap-2">
<span className="b-strip grid grid-cols-2 rounded-full p-[3px]" role="radiogroup" aria-label="오늘 또는 내일 날씨">
{(
[
[false, '오늘'],
[true, '내일'],
] as const
).map(([v, l]) => (
<button
key={l}
type="button"
role="radio"
aria-checked={tmr === v}
onClick={() => setTmr(v)}
className={cx('cursor-pointer rounded-full px-2.5 py-0.5 font-jua text-[13px]', tmr === v ? 'b-strip-on text-(--orange-deep)' : 'opacity-75')}
>
{l}
</button>
))}
</span>
<span className="text-[13px] font-bold opacity-80">
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</span>
</span>
<span className="flex items-center gap-3 [&_svg]:size-[22px] [&_svg]:stroke-[2]">
{post && (
<>
<button
type="button"
onClick={like.toggle}
aria-pressed={like.liked}
aria-label={like.failed ? '좋아요를 반영하지 못했어요. 다시 눌러 주세요' : '오늘 날씨 좋아요'}
className={cx('relative flex cursor-pointer items-center gap-1 text-[13px] font-extrabold', TAP44, !like.liked && 'opacity-80')}
>
<HeartIcon className={like.liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-current'} />
{like.count > 0 && like.count.toLocaleString()}
</button>
<button
type="button"
onClick={() => open({ type: 'comments', postId: post.post_id })}
aria-label="오늘 날씨 댓글"
className={cx('relative flex cursor-pointer items-center gap-1 text-[13px] font-extrabold opacity-80', TAP44)}
>
<CommentIcon className="fill-none stroke-current [stroke-linejoin:round]" />
{post.comment_count > 0 && post.comment_count.toLocaleString()}
</button>
</>
)}
<button type="button" onClick={share} aria-label="오늘 날씨 보내기" className={cx('relative grid size-7 cursor-pointer place-items-center opacity-80', TAP44)}>
<SendIcon className="fill-none stroke-current [stroke-linecap:round] [stroke-linejoin:round]" />
</button>
</span>
</div>
<div className="relative h-[146px]">
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
<span key={c.cls} className={cx('b-cloud b-fall z-[1]', c.cls)} style={fall(c.d, c.f)} aria-hidden="true" />
))}
<div className="b-sun b-fall absolute top-2 left-1/2 -ml-16 grid aspect-square w-32 place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
{moon && (
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
<path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} />
</svg>
)}
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
<small className="block font-jua text-[12px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}</small>
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
<span key={c.cls} className={cx('b-fall absolute z-[1]', c.cls)} style={fall(c.d, c.f)} aria-hidden="true">
<span className="b-cloud b-bob inset-0" />
</span>
))}
<div className={'b-fall absolute top-2 left-1/2 -ml-16 aspect-square w-32'} style={fall('0s', '5.6s')}>
<div className="b-sun b-bob relative grid size-full place-items-center rounded-full text-center">
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
{moon && (
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
<path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} />
</svg>
)}
{/* 점수 근거가 있으면 해를 눌러도 근거 창: 구석 버튼은 구름에 가려져서 상태 줄 끝으로 옮김 */}
{(() => {
const body = (
<>
<small className="block font-jua text-[12px]">
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</small>
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
</>
)
const cls = cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')
if (!why || score == null) return <span className={cls}>{body}</span>
return (
<button
type="button"
onClick={() => open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } })}
aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`}
className={cx(cls, 'flex cursor-pointer flex-col items-center')}
>
{body}
</button>
)
})()}
</div>
</div>
</div>
<div className="relative z-[3] text-center">
{/* 다 불러온 높이(한 줄 말·날씨 한 줄·상태 두 줄)를 미리 잡아 둔다: 늦게 채워지며 아래 피드가 밀려 내려가지 않게 */}
<div className="relative z-[3] min-h-[103px] text-center">
{top1 ? (
<button type="button" onClick={() => open({ type: 'gak', indexId: top1.index_id })} aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`} className="cursor-pointer font-jua text-[24px] leading-tight">
<button
type="button"
onClick={() => open({ type: 'gak', indexId: top1.index_id })}
aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`}
className="cursor-pointer font-jua text-[24px] leading-tight"
>
{bubble}
</button>
) : (
@@ -188,25 +421,41 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
<p className="m-0 mt-1.5 flex flex-wrap justify-center gap-x-1.5 font-jua text-[14px]">
{status.map((x, i) => (
<Fragment key={x.label}>
{i > 0 && <span className="opacity-30" aria-hidden="true">·</span>}
{i > 0 && (
<span className="opacity-30" aria-hidden="true">
·
</span>
)}
<span className={cx('whitespace-nowrap', x.tone === 'warn' && 'b-warn')}>
<span className={cx(x.tone !== 'warn' && 'opacity-75')}>{x.label}</span> <b className="font-normal">{x.value}</b>
</span>
</Fragment>
))}
{why && score != null && (
<button type="button" onClick={() => open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } })} aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`} className={cx('relative cursor-pointer whitespace-nowrap text-(--orange-deep)', TAP44)}>
· 점수 근거 ›
</button>
)}
</p>
)}
</div>
<div className="b-strip relative z-[3] mt-2.5 grid grid-cols-4 gap-1 rounded-[18px] p-[3px]" role="tablist" aria-label="하루 흐름, 누르면 그 시간대 하늘로">
{KINDS.map((k) => {
const isNow = k === nowKind
const isNow = !tmr && k === nowKind
const s = slotOf(isNow ? 'now' : k)
const on = k === kind
return (
<button key={k} type="button" role="tab" aria-selected={on} onClick={() => setPreview(isNow ? null : k)} className={cx('flex cursor-pointer flex-col items-center rounded-[14px] py-1.5', on && 'b-strip-on')}>
<button
key={k}
type="button"
role="tab"
aria-selected={on}
onClick={() => (tmr ? setTmrKind(k) : setPreview(isNow ? null : k))}
className={cx('flex cursor-pointer flex-col items-center rounded-[14px] py-1.5', on && 'b-strip-on')}
>
<span className={cx('text-[13px] font-bold', on ? 'text-(--orange-deep)' : 'opacity-75')}>{isNow ? '지금' : PREVIEW[k].label}</span>
<Ic name={k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)]} className="my-0.5 h-[22px] w-[22px] object-contain" />
<b className="font-jua text-[15px] font-normal">{heroVal(todayLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</b>
<b className="font-jua text-[15px] font-normal">{heroVal(slotsLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</b>
</button>
)
})}
@@ -227,27 +476,42 @@ function moonPath(pct: number, r: number, lit: boolean) {
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
}
function Stories({ items }: { items: TopIndex[] }) {
function GakCard({ items, post, place, at }: { items: TopIndex[]; post?: PostReaction | null; place: string; at: string }) {
const { open } = useSheet()
const tplRef = useRef<HTMLDivElement>(null)
const top = items.filter((g) => g.active).slice(0, 5)
return (
<Rail label="오늘의 각 순위">
{items.map((g, i) => (
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, 지금 시간대 아님`} className={cx('flex w-[72px] cursor-pointer flex-col items-center gap-1', !g.active && 'opacity-55')}>
<span className={cx('relative size-[68px] rounded-full p-[3px]', !g.active || g.score < 50 ? 'bg-[#d6deea]' : 'b-ring')}>
<i className="grid size-full place-items-center rounded-full border-[3px] border-(--page) bg-(--page)">
<Ic name={g.icon} className="w-[42px]" />
</i>
{i < 3 && g.active && <Ic name={MEDALS[i]} className="absolute -right-1 -bottom-1 w-[25px]" />}
</span>
<b className="font-jua text-[13px] font-normal whitespace-nowrap">{g.name}</b>
{g.active ? (
<em className="font-bagel text-[12.5px] leading-none text-(--orange) not-italic">{g.score}</em>
) : (
<small className="text-[11px] leading-none font-extrabold text-(--ink3)">지금 아님</small>
)}
</button>
))}
</Rail>
<PostFrame
title={`오늘의 각 · ${place}`}
account="오늘의 각"
avatar="rabbit"
more={<Link to="/gak">전체 보기</Link>}
caption="누르면 계산 근거를 보여 줘요"
shot={tplRef}
pinned={{ key: 'gak_post', post }}
>
<GakShareCard items={top} title={`오늘의 각 · ${place} ${at}`} ref={tplRef} />
<div className="b-band-2 px-4 pt-3.5 pb-3">
<p className="m-0 font-jua text-[19px]">
오늘의 각 · {place} {at}
</p>
<ol className="m-0 mt-2 grid list-none gap-1.5 p-0">
{top.map((g, i) => (
<li key={g.index_id}>
<button type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} className="flex w-full cursor-pointer items-center gap-2.5 rounded-[18px] bg-white px-3 py-2 text-left shadow-[inset_0_-4px_0_var(--shade)]">
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="w-[24px] shrink-0" /> : <span className="w-[24px] shrink-0 text-center font-jua text-(--ink3)">{i + 1}</span>}
<Ic name={g.icon} className="w-[34px] shrink-0" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[16px] leading-tight font-normal">{g.name}</b>
{g.summary && <small className="block truncate text-xs font-semibold text-(--ink2)">{g.summary}</small>}
</span>
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
</button>
</li>
))}
</ol>
</div>
</PostFrame>
)
}
@@ -260,39 +524,21 @@ function PostsSkel() {
)
}
const STORY_SKELS = Array.from({ length: 6 }, (_, i) => i)
/** Stories 와 같은 칸(68px 동그라미 + 이름 + 점수)을 6개 */
function StoriesSkel() {
/** 띠도 포스트 틀에 담아 좋아요·댓글·보내기를 단다 (post 는 서버의 띠 자리) */
function Band({ tone, title, sub, to, avatar, post, pinKey, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; avatar: string; post?: PostReaction | null; pinKey: PinnedKey; children: ReactNode }) {
return (
<SkelRail>
{STORY_SKELS.map((i) => (
<span key={i} className="flex w-[72px] flex-col items-center gap-1">
<Skel shape className="size-[68px] rounded-full" />
<b className="font-jua text-[13px] font-normal">
<Skel className="w-12" />
</b>
<em className="font-bagel text-[12.5px] leading-none not-italic">
<Skel className="w-6" />
</em>
</span>
))}
</SkelRail>
<PostFrame title={title} account={title} avatar={avatar} pinned={{ key: pinKey, post }}>
<section className={cx('pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
<Sec title={title} sub={sub} more={{ to }} className="pt-0" />
{children}
</section>
</PostFrame>
)
}
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
function EventsBand({ events, post }: { events: BandEvent[]; post?: PostReaction | null }) {
return (
<section className={cx('mt-3.5 pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
<Sec title={title} sub={sub} more={{ to }} className="pt-0" />
{children}
</section>
)
}
function EventsBand({ events }: { events: BandEvent[] }) {
return (
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week">
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week" avatar="fireworks" post={post} pinKey="events_post">
<Rail>
{events.map((e, i) => (
<Link key={e.event_id} to="/week" className="w-[200px] overflow-hidden rounded-[22px] bg-white shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
@@ -309,29 +555,10 @@ function EventsBand({ events }: { events: BandEvent[] }) {
)
}
function TopBand({ items, sub }: { items: TopIndex[]; sub: string }) {
function SeasonBand({ news, post }: { news: BandArticle[]; post?: PostReaction | null }) {
const { open } = useSheet()
return (
<Band tone={2} title="지금 뜨는 각 TOP 5" sub={sub} to="/gak">
<Rail>
{items.slice(0, 5).map((g, i) => (
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} className="relative flex w-[138px] cursor-pointer flex-col items-start gap-1 rounded-[22px] bg-white p-3 text-left shadow-[inset_0_-5px_0_var(--shade)]">
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="absolute top-2 left-2 w-[26px]" /> : <span className="absolute top-2.5 left-3 font-jua text-(--ink3)">{i + 1}위</span>}
<Ic name={g.icon} className="w-[58px] self-center" />
<b className="font-jua text-base font-normal">{g.name}</b>
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
{g.summary && <small className="text-xs font-semibold text-(--ink2)">{g.summary}</small>}
</button>
))}
</Rail>
</Band>
)
}
function SeasonBand({ news }: { news: BandArticle[] }) {
const { open } = useSheet()
return (
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season">
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season" avatar="fallen_leaf" post={post} pinKey="season_post">
<Rail>
{news.map((a) => (
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="w-[200px] cursor-pointer overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
@@ -352,6 +579,7 @@ export function TodayPage() {
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
const { preview } = useSky()
const { open } = useSheet()
const f = feed.data
const posts = f?.posts ?? []
const stories = atSlot(f?.stories ?? [], preview)
@@ -359,25 +587,72 @@ export function TodayPage() {
const bands = f?.bands
const nowAt = f?.hero?.now_at
const load = loadOf(feed)
const [mine, setMine] = useState<TalkData[]>([])
// 사람 글은 묶음으로: '동네 사람들'은 오늘의 각 아래, 주제 묶음은 같은 주제 포스트 아래. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고
const talkGroups = useTalkGroups()
const groupOf = (topic: number) => (talkGroups.groups.get(topic) ?? []).filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
const group = (topic: number) => {
const talks = groupOf(topic)
return talks.length ? <TalkGroup key={`talk-${topic}`} title={topicName(topic)} topic={topic} talks={talks} /> : null
}
// 비·눈이 오거나 2시간 안에 올 때만 비·눈 묶음을 히어로 바로 아래로
const at = nowAt ? Date.parse(nowAt) : 0
const nowSlot = (today.data?.slots ?? []).filter((x) => x.temp_c != null).reduce<WeatherSlot | undefined>((a, b) => (!a || Math.abs(Date.parse(b.at) - at) < Math.abs(Date.parse(a.at) - at) ? b : a), undefined)
const raining = ['rain', 'snow', 'sleet'].includes(weatherOf(nowSlot)) || !!f?.hero?.will_rain_2h
const sunsetAt = posts.findIndex((p) => p.post_type === PostType.SUNSET)
useEffect(() => {
window.scrollTo({ top: 0 })
}, [region.code])
// 친구가 보낸 내 각 링크(/?my=...)로 들어오면 내 동네 기준으로 보여 준다
useEffect(() => {
const url = new URL(window.location.href)
const code = url.searchParams.get('my')
if (!code) return
url.searchParams.delete('my')
window.history.replaceState(window.history.state, '', url)
const g = fromShare(code)
if (g) open({ type: 'mix', shared: g })
}, [open])
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
[6, bands?.top5?.length ? <TopBand key="top5" items={sloted ? stories.filter((g) => g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} post={f?.events_post} /> : null],
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} post={f?.season_post} /> : null],
]
// 사람 글 묶음은 포스트 사이사이에 하나씩: 묶음·띠·단풍 카드가 이미 붙는 자리와 바로 앞 자리는 건너뛰어 가로 목록이 연달아 나오지 않게
const spreadTopics = [TalkTopic.OUTFIT, ...(raining ? [] : [TalkTopic.RAIN]), ...(sunsetAt < 0 ? [TalkTopic.SKY] : []), ...(posts.length < 2 ? [TalkTopic.FOLIAGE] : [])].filter((tp) => groupOf(tp).length)
const taken = new Set([1, sunsetAt, ...bandAt.map(([at]) => at - 1)])
const spreadAt = new Map<number, ReactNode>()
let spreadN = 0
for (let i = 0; i < posts.length && spreadN < spreadTopics.length; i++) {
if (taken.has(i) || spreadAt.has(i - 1)) continue
spreadAt.set(i, group(spreadTopics[spreadN++]))
}
const spreadLeft = spreadTopics.slice(spreadN).map((tp) => group(tp))
return (
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} className="inset-x-3 top-3 bottom-1" />}
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} />
<FeedComposer onPosted={(t) => setMine((m) => [t, ...m])} />
{mine.map((t) => (
<TalkCard key={t.talk_id} t={t} onGone={() => setMine((m) => m.filter((x) => x.talk_id !== t.talk_id))} />
))}
{raining && group(TalkTopic.RAIN)}
<MyGakRow />
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
) : load === 'loading' ? (
<PostCardSkel />
) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
)}
<NearTalks talks={groupOf(0)} loaded={talkGroups.loaded} />
<InstallBanner />
<div>
{load === 'loading' && <PostsSkel />}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
@@ -387,9 +662,15 @@ export function TodayPage() {
{posts.map((p, i) => (
<Fragment key={p.post_id}>
<PostCard post={p} />
{i === sunsetAt && group(TalkTopic.SKY)}
{i === 1 && <FoliageCard post={f?.foliage_post} />}
{i === 1 && group(TalkTopic.FOLIAGE)}
{bandAt.find(([at]) => at === i + 1)?.[1]}
{spreadAt.get(i)}
</Fragment>
))}
{/* 글이 모자라 끼울 자리가 없던 묶음은 맨 뒤에 */}
{feed.isSuccess && spreadLeft}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
</div>
</section>
+20 -9
View File
@@ -22,11 +22,12 @@
outline-offset: 2px;
}
/* 하늘에서 떨어진 뒤 둥둥 */
/* 하늘에서 떨어진 뒤(.b-fall) 둥둥(.b-bob, 그 안쪽 요소). 한 요소에 transform 애니메이션 둘이 겹치면 GPU로 못 넘겨 매 프레임 메인 스레드가 일한다 */
.b-fall {
animation:
b-drop 1.05s cubic-bezier(0.22, 0.9, 0.3, 1) var(--d, 0s) both,
b-float var(--f, 4.8s) ease-in-out calc(var(--d, 0s) + 1.05s) infinite;
animation: b-drop 1.05s cubic-bezier(0.22, 0.9, 0.3, 1) var(--d, 0s) backwards;
}
.b-bob {
animation: b-float var(--f, 4.8s) ease-in-out calc(var(--d, 0s) + 1.05s) infinite;
}
@keyframes b-drop {
0% {
@@ -53,7 +54,7 @@
transform: translateY(0);
}
50% {
transform: translateY(calc(var(--amp, 9px) * -1)) rotate(var(--tilt, 1.2deg));
transform: translateY(-9px) rotate(1.2deg);
}
}
@@ -509,6 +510,9 @@
border-radius: 50%;
background: #fff;
box-shadow: 0 0 6px rgb(255 255 255 / 0.8);
}
/* 별은 밤에만 보이니 반짝임·별똥별도 밤에만 돌린다 (낮에 안 보이는 채로 돌면 매 프레임 일을 한다) */
.b-skybg[data-t='night'] .b-skystars i {
animation: b-twinkle var(--tw, 5s) ease-in-out infinite;
animation-delay: var(--dl, 0s);
}
@@ -523,8 +527,14 @@
border-radius: 2px;
background: linear-gradient(90deg, rgb(255 255 255 / 0), #fff);
opacity: 0;
}
:is(.b-skybg, .b-hero)[data-t='night'] .b-shoot {
animation: b-shoot var(--dur, 8s) ease-in var(--dl, 0s) infinite;
}
/* 아래 창이 열려 있는 동안 뒤 화면 움직임은 멈춘다 (창이 버벅이지 않게) */
html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot, .b-stars i) {
animation-play-state: paused !important;
}
@keyframes b-shoot {
0%, 86% { opacity: 0; transform: rotate(-24deg) translateX(0); }
89% { opacity: 1; }
@@ -543,13 +553,13 @@
}
}
/* 위·아래 바는 반투명으로 하늘이 비치게 */
/* 위 바는 반투명으로 하늘이 비치게, 아래 탭 바는 홈 바 자리까지 글이 비치지 않게 불투명 */
.b-topbg {
background: rgb(255 255 255 / 0.18);
transition: background 1.4s ease;
}
.b-tabbar {
background: rgb(255 255 255 / 0.6);
background: #f7faff;
overflow: visible;
border-color: rgb(255 255 255 / 0.4);
}
@@ -557,7 +567,7 @@
background: rgb(14 20 51 / 0.35);
}
.b-app[data-t='night'] .b-tabbar {
background: rgb(18 24 60 / 0.62);
background: #121838;
border-color: rgb(255 255 255 / 0.08);
}
@@ -601,7 +611,8 @@
.b-app[data-t='night'] .bg-\(--ink\) .text-\[\#ffb3c4\] {
color: #ffd0dc;
}
.b-app[data-t='night'] .text-\[\#28304a\] {
/* b-keep-bg(밤에도 밝은 바탕 그대로) 안은 글자도 그대로 */
.b-app[data-t='night'] .text-\[\#28304a\]:not(.b-keep-bg, .b-keep-bg *) {
color: var(--ink);
}
.b-app[data-t='night'] :is(.text-\[\#1f9d62\], .text-\[\#1f7a4f\]) {
+213
View File
@@ -0,0 +1,213 @@
import { useLayoutEffect, useMemo, useState, type RefObject } from 'react'
import data from '../../seo/foliage_2026.json'
import { kst } from './lib'
export type Kind = 'maple' | 'ginkgo'
export type Stage = 'before' | 'first' | 'peak' | 'gone'
type Raw = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string }
/** x·y 는 지도 그림 안 위치(0~1), own 은 산림청 예측 지점 자기 날짜인지(아니면 가까운 지점에서 빌린 날짜) */
export type Spot = Omit<Raw, 'basis' | 'lat' | 'lon'> & { stage: Stage; d: number; x: number; y: number; own: boolean }
// 지도 그림(public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값
const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 }
export const MAP_SRC = '/foliage/korea-map.webp'
// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 PEAK_AFTER 일 뒤까지 절정으로 본다
const FIRST_DAYS = 14
const PEAK_DAYS = 3
const PEAK_AFTER = 7
export const STAGE: Record<Stage, string> = { before: '단풍 전', first: '첫 단풍', peak: '절정', gone: '절정 지남' }
export const KIND: Record<Kind, string> = { maple: '단풍', ginkgo: '은행' }
const DAY = 86_400_000
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
function stage(peak: string, today: string): Stage {
const d = days(today, peak)
if (d < -PEAK_AFTER) return 'gone'
if (d <= PEAK_DAYS) return 'peak'
return d <= FIRST_DAYS ? 'first' : 'before'
}
const toXY = (lat: number, lon: number) => ({ x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size })
// 지도 위 시·도 이름 자리(위경도). 서울·경기는 겹치지 않게 경기를 북쪽으로 조금 올림
export const PROVINCES = (
[
['서울', 37.56, 126.98],
['경기', 37.95, 127.05],
['강원', 37.65, 128.35],
['충북', 36.8, 127.75],
['충남', 36.45, 126.85],
['전북', 35.72, 127.1],
['전남', 34.85, 126.9],
['경북', 36.3, 128.75],
['경남', 35.3, 128.2],
['제주', 33.38, 126.55],
] as const
).map(([name, lat, lon]) => ({ name, ...toXY(lat, lon) }))
export const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
const province = (m: Spot) => m.region.split(' ')[0].split('·')
/** 오늘(한국 시각) 기준 명소 65곳과 단계. 단풍철이 아니면 inSeason 이 false */
export function useFoliage() {
const [today] = useState(() => {
const t = kst(new Date())
return `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}`
})
return useMemo(() => {
const spots: Spot[] = (data.spots as Raw[]).map(({ basis, lat, lon, ...m }) => ({
...m,
stage: stage(m.peak, today),
d: days(today, m.peak),
...toXY(lat, lon),
own: basis.startsWith('산림청'),
}))
// 가장 이른 명소가 첫 단풍에 들 때부터 가장 늦은 명소의 절정이 끝날 때까지
const peaks = spots.map((m) => m.peak).sort()
const inSeason = days(peaks[0], today) >= -FIRST_DAYS && days(peaks[peaks.length - 1], today) <= PEAK_AFTER
return { today, spots, inSeason }
}, [today])
}
/** 절정 명소가 많은 시·도 3곳, 절정이 없으면 가장 먼저 올 절정, 다 지났으면 지는 중 */
export function headline(spots: Spot[]) {
const peak = spots.filter((m) => m.stage === 'peak')
if (peak.length) {
const count = new Map<string, number>()
for (const p of peak.flatMap(province)) count.set(p, (count.get(p) ?? 0) + 1)
return `지금 절정: ${[...count].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([p]) => p).join('·')}`
}
if (spots.some((m) => m.stage === 'gone')) return '올해 단풍이 지고 있어요'
const first = spots.reduce((a, b) => (b.peak < a.peak ? b : a))
return `첫 절정은 ${province(first)[0]}, ${md(first.peak)}쯤`
}
/** 지금 가기 좋은 순: 절정인 곳 중 절정 예상일이 오늘과 가까운 순, 같으면 자기 예측 날짜 먼저, 그다음 이름 순 */
export const rankNow = (spots: Spot[]) =>
spots.filter((m) => m.stage === 'peak').sort((a, b) => Math.abs(a.d) - Math.abs(b.d) || Number(b.own) - Number(a.own) || a.name.localeCompare(b.name))
/** 시·도 이름 자리(명소 이름표를 먼저 놓은 뒤): 원래 자리가 잎·점·이름표에 덮이면 둘레를 돌며 가장 가까운 빈자리로 옮긴다(최대 반경 R, 바다 쪽도 됨) */
export function placeProvinces(provs: { name: string; x: number; y: number }[], pts: Pt[], labels: Box[] = [], R = 90) {
// 앞에서 놓은 시·도 이름도 피한다(서울·경기처럼 붙은 곳)
const placed: Box[] = []
const free = (x: number, y: number) =>
pts.every((p) => Math.abs(p.x - x) > p.r + 17 || Math.abs(p.y - y) > p.r + 10) && [...labels, ...placed].every((b) => !overlaps(provinceBox(x, y), b))
return provs.map((v) => {
const at = pick(v)
placed.push(provinceBox(at.x, at.y))
return at
})
function pick(v: { name: string; x: number; y: number }) {
if (free(v.x, v.y)) return v
for (let d = 5; d <= R; d += 5)
for (let a = 0; a < 24; a++) {
const x = v.x + Math.cos((a / 24) * 2 * Math.PI) * d
const y = v.y + Math.sin((a / 24) * 2 * Math.PI) * d
if (free(x, y)) return { ...v, x, y }
}
return v
}
}
export function provinceBox(x: number, y: number): Box {
return { l: x - 16, t: y - 9, r: x + 16, b: y + 9 }
}
/** placeLabels 결과를 상자로: 시·도 이름이 피해 갈 자리 */
export const labelBoxes = (at: Record<string, { left: number; top: number }>, size: Record<string, { w: number; h: number }>) =>
Object.entries(at).map(([n, a]) => ({ l: a.left, t: a.top, r: a.left + (size[n]?.w ?? 0), b: a.top + (size[n]?.h ?? 0) }))
export type Pt = { m: Spot; x: number; y: number; r: number }
const LABEL_GAP = 4
export type Box = { l: number; t: number; r: number; b: number }
const overlaps = (a: Box, b: Box) => a.l < b.r && b.l < a.r && a.t < b.b && b.t < a.b
/** 화면 위 점끼리 겹치면 서로 밀어 떼어 놓는다 (pts 를 고쳐서 돌려줌) */
export function spread(pts: Pt[], gap = 1.5) {
for (let it = 0; it < 60; it++) {
let moved = false
for (let i = 0; i < pts.length; i++)
for (let j = i + 1; j < pts.length; j++) {
const a = pts[i]
const b = pts[j]
let dx = b.x - a.x
let dy = b.y - a.y
let d = Math.hypot(dx, dy)
const need = a.r + b.r + gap
if (d >= need) continue
if (d < 0.01) [dx, dy, d] = [Math.cos(i + j), Math.sin(i + j), 1]
const push = (need - d) / 2
a.x -= (dx / d) * push
a.y -= (dy / d) * push
b.x += (dx / d) * push
b.y += (dy / d) * push
moved = true
}
if (!moved) break
}
return pts
}
/** 이름표를 점 오른쪽·왼쪽 순으로 놓아 보고(잎과 짝이 헷갈리지 않게 옆 먼저), 점·다른 이름표·막힌 칸과 겹치거나 영역 밖이면 그 이름은 뺀다. 앞 순서가 먼저 자리를 잡는다 */
export function placeLabels(order: Pt[], all: Pt[], size: Record<string, { w: number; h: number }>, area: Box, blocked: Box[] = [], vertical: (p: Pt) => boolean = () => false) {
const dots = all.map((p) => ({ name: p.m.name, box: { l: p.x - p.r, t: p.y - p.r, r: p.x + p.r, b: p.y + p.r } }))
const taken = [...blocked.map((box) => ({ name: '', box })), ...dots]
const out: Record<string, { left: number; top: number }> = {}
for (const p of order) {
const s = size[p.m.name]
if (!s || p.x < area.l || p.x > area.r || p.y < area.t || p.y > area.b) continue
// 옆 자리가 없을 때 vertical 인 명소(절정)만 위·아래도 써 본다
const tries = [
[p.r + 2, -s.h / 2],
[-s.w - p.r - 2, -s.h / 2],
...(vertical(p) ? [[-s.w / 2, -s.h - p.r - 1], [-s.w / 2, p.r + 1]] : []),
]
for (const [dx, dy] of tries) {
const r = { l: p.x + dx, t: p.y + dy, r: p.x + dx + s.w, b: p.y + dy + s.h }
if (r.l < area.l || r.t < area.t || r.r > area.r || r.b > area.b) continue
// 이름표끼리는 LABEL_GAP 만큼 띄워 손가락으로 옆 이름을 잘못 누르지 않게
const pad = { l: r.l - LABEL_GAP, t: r.t - LABEL_GAP, r: r.r + LABEL_GAP, b: r.b + LABEL_GAP }
if (taken.some((o) => o.name !== p.m.name && overlaps(o.name ? r : pad, o.box))) continue
// 위·아래 자리는 이름표에서 가장 가까운 표시가 자기 것일 때만: 아니면 다른 점의 이름처럼 읽힌다
const cx = (r.l + r.r) / 2
const cy = (r.t + r.b) / 2
const mine = Math.hypot(cx - p.x, cy - p.y)
if (dy !== -s.h / 2 && all.some((q) => q.m.name !== p.m.name && Math.hypot(cx - q.x, cy - q.y) < mine)) continue
taken.push({ name: '', box: r })
out[p.m.name] = { left: r.l, top: r.t }
break
}
}
return out
}
/** 이름표 크기를 재 둔다: host 안 data-label 이 붙은 요소의 폭·높이 (host 크기가 바뀌면 다시) */
export function useLabelSize(host: RefObject<HTMLElement | null>, key: unknown) {
const [size, setSize] = useState<Record<string, { w: number; h: number }>>({})
useLayoutEffect(() => {
const el = host.current
if (!el) return
const ro = new ResizeObserver(() => {
const out: Record<string, { w: number; h: number }> = {}
el.querySelectorAll<HTMLElement>('[data-label]').forEach((l) => {
out[l.dataset.label ?? ''] = { w: l.offsetWidth, h: l.offsetHeight }
})
setSize(out)
})
ro.observe(el)
return () => ro.disconnect()
}, [host, key])
return size
}
export const LEAF_SHADOW = 'drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.45)]'
// 밤 화면에서도 지도는 밝은 종이 그대로라 이름표도 흰 바탕 그대로(b-keep-bg)
export const LABEL = "b-keep-bg absolute rounded-[7px] before:absolute before:-inset-x-1 before:-inset-y-2 before:content-[''] px-[5px] py-px text-[11.5px] leading-[1.35] font-extrabold whitespace-nowrap shadow-[0_1px_3px_rgb(40_48_74/0.18)]"
export const LABEL_INK: Record<Kind, string> = { maple: 'bg-[#ffffffeb] text-[#b5321f]', ginkgo: 'bg-[#ffffffeb] text-[#8a6508]' }
// 지도 그림 색을 빼서 단풍 아이콘이 묻히지 않게
export const MAP_IMG = 'pointer-events-none absolute inset-0 size-full select-none mix-blend-multiply brightness-[1.08] saturate-[.3]'
export const ICON_R = 10
// 시·도 이름: 지도에 옅게 깔리는 글자
// 어두운 산 무늬 위에서도 읽히게 종이색 테두리를 두른다
export const PROVINCE = 'pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 font-jua text-[13px] leading-none whitespace-nowrap text-[#5c4a36]/85 [text-shadow:0_0_2px_#fff6ea,0_0_4px_#fff6ea,0_0_6px_#fff6ea]'
+160
View File
@@ -0,0 +1,160 @@
import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useNavigate } from 'react-router'
import { cx } from '../lib/utils'
import type { PostReaction } from '../api/client/types.gen'
import { useCarousel } from './carousel'
import { headline, ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, spread, useFoliage, useLabelSize } from './foliage'
import { PostFrame } from './Post'
import { useSheet } from './sheetContext'
import { FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Ic } from './ui'
const TAP_R = 24
const RANK_N = 7
/** 피드의 단풍 지도 카드: 1장은 지금 절정인 곳만 잎 아이콘으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위. '지도 크게 보기'로 단풍 지도 페이지 */
export function FoliageCard({ post }: { post?: PostReaction | null }) {
const navigate = useNavigate()
const { today, spots, inSeason } = useFoliage()
const peak = useMemo(() => spots.filter((m) => m.stage === 'peak').sort((a, b) => Number(a.kind === 'ginkgo') - Number(b.kind === 'ginkgo') || a.y - b.y), [spots])
const mapRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(mapRef, peak)
const [W, setW] = useState(0)
const [picked, setPicked] = useState<string | null>(null)
const { open } = useSheet()
const spotShotRef = useRef<HTMLDivElement>(null)
const { ref: sliderRef, index } = useCarousel({ align: 'start' })
useLayoutEffect(() => {
const el = mapRef.current
if (!el) return
const ro = new ResizeObserver(() => setW(el.clientWidth))
ro.observe(el)
return () => ro.disconnect()
}, [inSeason])
const pts = useMemo(() => spread(peak.map((m) => ({ m, x: m.x * W, y: m.y * W, r: ICON_R }))), [peak, W])
const labelAt = useMemo(() => placeLabels(pts, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true), [pts, size, W])
const provs = useMemo(() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: v.x * W, y: v.y * W })), pts, labelBoxes(labelAt, size)), [pts, W, labelAt, size])
if (!inSeason) return null
const go = (name?: string) => navigate(name ? `/foliage?spot=${encodeURIComponent(name)}` : '/foliage')
const toggle = (name: string) => setPicked(name === picked ? null : name)
// 잎이 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 명소를 고른다
const tapMap = (e: MouseEvent<HTMLDivElement>) => {
const r = e.currentTarget.getBoundingClientRect()
let best: string | null = null
let bestD = TAP_R
for (const p of pts) {
const d = Math.hypot(p.x - (e.clientX - r.left), p.y - (e.clientY - r.top))
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setPicked(best && best !== picked ? best : null)
}
const sel = peak.find((m) => m.name === picked)
// 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로
const ranked = rankNow(spots).slice(0, RANK_N)
return (
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" pinned={{ key: 'foliage_post', post }} caption={peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined}>
<div className="b-keep-bg relative bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 text-[13px] font-extrabold opacity-75">단풍 지도 · {md(today)}</p>
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">{headline(spots)}</p>
<div className="relative mt-1">
<span data-noshot aria-hidden="true" className="absolute top-0 right-0 z-[4] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white">
{index + 1}/2
</span>
<div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
<div className="flex">
<div className="min-w-0 shrink-0 grow-0 basis-full">
<div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={MAP_IMG} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{pts.map((p) => (
<span key={p.m.name} className="pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center" style={{ left: p.x, top: p.y }}>
{p.m.name === picked && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<Ic name={p.m.kind} className={cx('relative size-5', LEAF_SHADOW)} />
</span>
))}
{peak.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 정보 보기`}
onClick={(e) => {
e.stopPropagation()
toggle(m.name)
}}
className={cx(LABEL, LABEL_INK[m.kind], 'cursor-pointer border-0', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name}
</button>
))}
</div>
{/* 고른 명소 정보는 지도 밖, 범례 자리에: 지도 위 잎을 가리지 않게 */}
{sel ? (
<div className="b-keep-bg mt-2 flex items-center gap-3 rounded-[16px] bg-[#ffffff] px-3 py-2.5 shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
<Ic name={sel.kind} className="size-8 shrink-0" />
<div className="min-w-0 flex-1">
<b className="block truncate font-jua text-[18px] leading-tight font-normal">{sel.name}</b>
<span className="flex gap-1 text-[12px] font-bold text-[#6b7189]">
<span className="shrink-0">{sel.region.split(' ')[0]}</span>
<span className="shrink-0">· 절정 예상 {md(sel.peak)}</span>
</span>
</div>
<button type="button" onClick={() => sel && open({ type: 'share', share: { title: `${sel.name} 단풍`, slides: spotShotRef.current ? [spotShotRef.current] : [] } })} aria-label={`${sel.name} 보내기`} className="relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-[#28304a] [&_svg]:stroke-[1.9]">
<SendIcon />
</button>
<button type="button" onClick={() => go(sel.name)} className="b-keep-bg shrink-0 cursor-pointer rounded-full bg-[#28304a] px-3 py-1.5 text-[12.5px] font-extrabold text-[#ffffff]">
지도에서 보기 ›
</button>
</div>
) : (
<span className="mt-2 flex h-[52px] items-center gap-3 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="maple" className="size-4" />
단풍 절정
</span>
<span className="flex items-center gap-1">
<Ic name="ginkgo" className="size-4" />
은행 절정
</span>
</span>
)}
</div>
<div className="flex min-w-0 shrink-0 grow-0 basis-full flex-col pl-1">
<p className="m-0 font-jua text-[20px] leading-tight">지금 가기 좋은 곳</p>
<p className="m-0 mt-0.5 text-[12px] font-bold text-[#6b7189]">절정 예상일이 오늘과 가까운 순서예요</p>
<ol className="m-0 mt-2 flex flex-1 list-none flex-col justify-between p-0">
{ranked.map((m, i) => (
<li key={m.name}>
<button type="button" onClick={() => go(m.name)} className="flex w-full cursor-pointer items-center gap-2.5 border-0 bg-transparent py-1.5 text-left">
<b className={cx('w-6 shrink-0 text-center font-jua text-[22px] font-normal', i < 3 ? 'text-[#b5321f]' : 'text-[#9a8f80]')}>{i + 1}</b>
<Ic name={m.kind} className={cx('size-7 shrink-0', LEAF_SHADOW)} />
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-[#6b7189]">{m.region}</small>
</span>
<span className="shrink-0 text-[14px] font-extrabold tabular-nums">{md(m.peak)}</span>
</button>
</li>
))}
</ol>
</div>
</div>
</div>
</div>
<FoliageSpotShare spot={sel ?? null} peak={peak} ref={spotShotRef} />
<button type="button" onClick={() => go()} className="b-keep-bg mt-2 w-full cursor-pointer rounded-full bg-[#ffffff] py-2 text-[14px] font-extrabold text-[#28304a] shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
지도 크게 보기 ›
</button>
</div>
</PostFrame>
)
}
+82
View File
@@ -0,0 +1,82 @@
import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { authConfigOptions, googleLoginMutation } from '../api/client/@tanstack/react-query.gen'
import type { ResAuth } from '../api/client/types.gen'
type GoogleId = {
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 로그인 창을 처음 열 때 한 번만 받는다 */
function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id
const login = useMutation(googleLoginMutation())
const box = useRef<HTMLDivElement>(null)
const [broken, setBroken] = useState(false)
const { mutate } = login
// 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다
const cb = useRef({ onResult, onFail })
useEffect(() => {
cb.current = { onResult, onFail }
}, [onResult, onFail])
useEffect(() => {
if (!clientId || !box.current) return
let alive = true
loadGoogle().then(
(g) => {
if (!alive || !box.current) return
g.initialize({
client_id: clientId,
ux_mode: 'popup',
callback: (r) => {
if (!r.credential) return cb.current.onFail()
mutate({ body: { credential: r.credential } }, { onSuccess: (res) => cb.current.onResult(res), onError: () => cb.current.onFail() })
},
})
g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth })
},
(e: unknown) => {
console.error('[google] script', e)
if (alive) setBroken(true)
},
)
return () => {
alive = false
}
}, [clientId, mutate])
if (!clientId) return null
return (
<div className="flex flex-col gap-2">
<div ref={box} className="flex min-h-[44px] justify-center" aria-busy={login.isPending} />
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
</div>
)
}
+104
View File
@@ -0,0 +1,104 @@
import { useSyncExternalStore } from 'react'
import { track } from '../lib/analytics'
import { useSheet } from './sheetContext'
type InstallPromptEvent = Event & { prompt: () => Promise<void>; userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }> }
const DISMISS_KEY = 'nalssigak.b.installDismissed'
const DISMISS_DAYS = 14
// 안드로이드 Chrome 은 설치할 수 있을 때 이 이벤트를 한 번 준다. 앱이 뜨기 전에 올 수 있어 모듈을 불러올 때 바로 받아 둔다
let deferred: InstallPromptEvent | null = null
const listeners = new Set<() => void>()
const notify = () => listeners.forEach((cb) => cb())
if (typeof window !== 'undefined') {
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault()
deferred = e as InstallPromptEvent
notify()
})
window.addEventListener('appinstalled', () => {
deferred = null
track('install_done', {})
notify()
})
}
export type Platform = 'standalone' | 'inapp' | 'ios' | 'android' | 'other'
/** 지금 이 기기에서 홈 화면 추가를 어떻게 안내할지 */
export function platform(): Platform {
const ua = navigator.userAgent
if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) return 'standalone'
if (/KAKAOTALK|Instagram|FBAN|FBAV|NAVER\(inapp|; wv\)|Line\//i.test(ua)) return 'inapp'
if (/iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return 'ios'
if (/Android/.test(ua)) return 'android'
return 'other'
}
const onPhone = () => ['ios', 'android', 'inapp'].includes(platform())
/** 설치를 권할 곳: 휴대폰 브라우저, 그리고 설치창을 띄울 수 있는 PC 브라우저(Chrome·Edge). PC Safari·Firefox 와 이미 설치해 연 화면은 뺀다 */
export function useInstallable() {
const canPrompt = useCanPrompt()
return platform() !== 'standalone' && (onPhone() || canPrompt)
}
/** 설치창을 바로 띄울 수 있는지 (안드로이드 Chrome 등) */
export function useCanPrompt() {
return useSyncExternalStore(
(cb) => {
listeners.add(cb)
return () => listeners.delete(cb)
},
() => deferred != null,
)
}
/** 설치창을 띄운다. 띄웠으면 true */
export async function promptInstall(): Promise<boolean> {
if (!deferred) return false
const e = deferred
deferred = null
notify()
try {
await e.prompt()
} catch (err) {
// 이미 한 번 띄웠거나 브라우저가 막으면 안내 창으로 넘긴다
console.warn('[install] prompt', err)
return false
}
const { outcome } = await e.userChoice
track('install_choice', { outcome })
return true
}
export function dismissed(): boolean {
try {
const at = Number(localStorage.getItem(DISMISS_KEY))
return at > 0 && Date.now() - at < DISMISS_DAYS * 86_400_000
} catch {
// 저장소를 못 쓰는 브라우저에선 이번 방문 동안만 보인다
return false
}
}
export function dismiss() {
try {
localStorage.setItem(DISMISS_KEY, String(Date.now()))
} catch (e) {
console.warn('[install] 닫은 시각을 저장하지 못함', e)
}
}
/** 홈 화면에 추가: 설치창을 띄울 수 있으면 띄우고, 아니면 기기별 안내 창을 연다 */
export function useInstall() {
const { open } = useSheet()
const canPrompt = useCanPrompt()
return async (from: 'banner' | 'menu') => {
const shown = canPrompt && (await promptInstall())
track('install_click', { from, method: shown ? 'prompt' : 'guide' })
if (!shown) open({ type: 'install' })
}
}
+130
View File
@@ -0,0 +1,130 @@
import { useEffect, useState, type ReactNode } from 'react'
import { track } from '../lib/analytics'
import { dismiss, dismissed, platform, promptInstall, useCanPrompt, useInstall, useInstallable } from './install'
const SITE = 'https://weather.o2o.kr'
/** 오늘 탭의 작은 설치 카드. 오늘의 각까지 본 뒤 자리에 놓고, 설치할 수 있는 곳(휴대폰, PC Chrome·Edge)에서만 보인다. 닫으면 2주 숨긴다 */
export function InstallBanner() {
const install = useInstall()
const installable = useInstallable()
const [closed, setClosed] = useState(dismissed)
const hidden = !installable || closed
useEffect(() => {
if (!hidden) track('install_banner_view', {})
}, [hidden])
if (hidden) return null
return (
<aside aria-label="홈 화면에 추가" className="mx-3 mt-3.5 flex items-center gap-3 rounded-[22px] bg-white p-3.5 shadow-[inset_0_-5px_0_var(--shade)]">
<img src="/app/icon-192.png" alt="" className="size-12 shrink-0 rounded-[14px]" />
<div className="min-w-0 flex-1">
<p className="m-0 font-jua text-[16.5px] leading-snug">내일도 우산각·빨래각, 바로 확인하세요</p>
<p className="m-0 mt-0.5 text-[12.5px] font-semibold text-(--ink2)">날씨각을 홈 화면에 추가하고 한 번에 열어보세요.</p>
<div className="mt-2 flex gap-1.5">
<button type="button" onClick={() => install('banner')} className="cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">
📲 홈 화면에 추가
</button>
<button
type="button"
onClick={() => {
dismiss()
setClosed(true)
}}
className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2)"
>
닫기
</button>
</div>
</div>
</aside>
)
}
function Steps({ items }: { items: ReactNode[] }) {
return (
<ol className="m-0 flex list-none flex-col gap-2 p-0">
{items.map((t, i) => (
<li key={i} className="flex items-start gap-2.5 rounded-2xl bg-[#f3f6fb] px-3.5 py-3 text-[14.5px] font-bold">
<b className="grid size-6 shrink-0 place-items-center rounded-full bg-(--orange) font-jua text-[14px] font-normal text-white">{i + 1}</b>
<span>{t}</span>
</li>
))}
</ol>
)
}
// 사파리 아래 가운데 공유 버튼과 공유 목록의 '홈 화면에 추가' 모양 그대로
const ShareGlyph = () => (
<svg viewBox="0 0 24 24" className="mx-0.5 inline size-[22px] -translate-y-0.5 fill-none stroke-[#2f7cf6] stroke-2 [stroke-linecap:round] [stroke-linejoin:round]" aria-label="공유 버튼">
<path d="M12 3v12M8 7l4-4 4 4M6 11H5v10h14V11h-1" />
</svg>
)
const AddGlyph = () => (
<svg viewBox="0 0 24 24" className="mx-0.5 inline size-[22px] -translate-y-0.5 fill-none stroke-(--ink) stroke-2 [stroke-linecap:round]" aria-hidden="true">
<rect x="4" y="4" width="16" height="16" rx="4" />
<path d="M12 8v8M8 12h8" />
</svg>
)
/** 설치창을 띄울 수 없는 기기의 안내. 안드로이드는 열어 둔 사이 크롬이 설치를 허락하면 바로 설치 버튼으로 바뀐다 */
export function InstallSheet() {
const p = platform()
const canPrompt = useCanPrompt()
const [copied, setCopied] = useState(false)
const copy = () =>
navigator.clipboard.writeText(SITE).then(
() => setCopied(true),
(e: unknown) => console.error('[install] copy', e),
)
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
{p === 'standalone' && <p className="m-0 text-[15px] font-bold">이미 홈 화면에서 열었어요. 다음에도 아이콘을 눌러 바로 여세요.</p>}
{p === 'ios' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">아이폰은 Safari에서 이렇게 추가해요.</p>
<Steps
items={[
<>화면 아래 <ShareGlyph /> 공유 버튼을 눌러요. 안 보이면 오른쪽 아래 ··· 를 누른 뒤 공유</>,
<>목록을 올려 <AddGlyph /> 홈 화면에 추가를 눌러요</>,
"오른쪽 위 '추가'를 누르면 끝이에요",
]}
/>
</>
)}
{p === 'android' && canPrompt && (
<button type="button" onClick={() => void promptInstall()} className="w-full cursor-pointer rounded-full bg-(--orange) py-3 font-jua text-[17px] text-white">
📲 지금 설치하기
</button>
)}
{p === 'android' && !canPrompt && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">지금 브라우저에선 설치창을 바로 띄울 수 없어요. 메뉴에서 추가해 주세요.</p>
<Steps items={['오른쪽 위 ⋮ 메뉴를 눌러요', "'홈 화면에 추가' 또는 '앱 설치'를 눌러요", "'추가' 또는 '설치'를 누르면 끝이에요"]} />
</>
)}
{p === 'inapp' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">카카오톡 같은 앱 안에서는 홈 화면에 추가할 수 없어요. Safari나 Chrome에서 열어 주세요.</p>
<Steps items={["오른쪽 위 ⋮ 또는 공유 버튼에서 '다른 브라우저로 열기'를 눌러요", '안 보이면 아래 주소를 복사해 Safari·Chrome에 붙여 넣어요', "열린 화면에서 '홈 화면에 추가'를 눌러요"]} />
</>
)}
{p === 'other' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">휴대폰에서 열면 홈 화면에 추가할 수 있어요.</p>
<Steps items={['휴대폰 Safari(아이폰)나 Chrome(갤럭시)에서 아래 주소를 열어요', "공유 버튼이나 ⋮ 메뉴에서 '홈 화면에 추가'를 눌러요"]} />
</>
)}
{(p === 'inapp' || p === 'other') && (
<div className="mt-3 flex items-center gap-2 rounded-2xl border border-(--line) px-3.5 py-2.5">
<span className="min-w-0 flex-1 truncate text-[14.5px] font-bold select-all">{SITE}</span>
<button type="button" onClick={copy} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
{copied ? '복사함' : '주소 복사'}
</button>
</div>
)}
</div>
)
}
+2 -2
View File
@@ -1,6 +1,6 @@
import type { CSSProperties } from 'react'
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', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental', 'ginkgo'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
@@ -39,7 +39,7 @@ export const MOODS = [
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') => ({ '--d': d, '--f': f }) as CSSProperties
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const
+235
View File
@@ -0,0 +1,235 @@
import { useState, type ReactNode } from 'react'
import type { MyGakPreset, MyGakRule, MyGakScore } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Ic, Rail, Sec } from './ui'
const SLOT_WORD = Object.fromEntries(SLOTS) as Record<Slot, string>
function Score({ s, big }: { s?: MyGakScore; big?: boolean }) {
const v = s?.score
return (
<em className={cx('ml-auto font-bagel leading-none not-italic', big ? 'text-[36px]' : 'text-[28px]', v == null || v < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>
{v ?? '–'}
</em>
)
}
function Reasons({ s }: { s?: MyGakScore }) {
if (!s?.slot) return <p className="m-0 text-[12.5px] font-semibold text-(--ink3)">예보를 불러오는 중이에요</p>
return (
<p className="m-0 text-[12.5px] leading-snug font-semibold text-(--ink2)">
<b className="mr-1 text-(--ink)">{SLOT_WORD[s.slot as Slot]}</b>
{s.reasons?.join(' · ')}
</p>
)
}
/** 오늘 탭의 내 각 줄: 내가 정한 조건으로 매긴 오늘 점수 */
export function MyGakRow() {
const { open } = useSheet()
const { items, remove } = useMyGak()
const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? []
const [copied, setCopied] = useState<number | null>(null)
const send = (g: MyGak, i: number) => {
const url = shareUrl(g)
if (navigator.share) {
navigator.share({ title: `${g.name} · 날씨각`, url }).catch((e: unknown) => {
if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[myGak] share', e)
})
return
}
navigator.clipboard.writeText(url).then(
() => setCopied(i),
(e: unknown) => console.error('[myGak] copy', e),
)
}
return (
<>
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
<Rail label="내 각">
{items.map((g, i) => (
<div key={g.id ?? 'local'} className="flex w-[220px] flex-col gap-1.5 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<div className="flex items-center gap-1">
<b className="font-jua text-[17px] leading-tight font-normal">{g.name}</b>
<Score s={scores[i]} />
</div>
<Reasons s={scores[i]} />
<div className="mt-auto flex gap-1.5 pt-0.5">
<button type="button" onClick={() => send(g, i)} className="cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
{copied === i ? '링크 복사함' : '친구에게 보내기'}
</button>
<button type="button" onClick={() => remove(g)} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[12.5px] font-extrabold text-(--ink2)">
지우기
</button>
</div>
</div>
))}
<button type="button" onClick={() => open({ type: 'mix' })} className="flex w-[120px] cursor-pointer flex-col items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-(--line) p-3 font-jua text-[15px] text-(--ink2)">
<span className="text-[26px] leading-none">+</span>
내 각 만들기
</button>
</Rail>
</>
)
}
function Row({ label, on, onToggle, children }: { label: string; on: boolean; onToggle: () => void; children: ReactNode }) {
return (
<div className={cx('flex min-h-[44px] flex-wrap items-center gap-2 border-b border-(--line) py-2', !on && 'opacity-60')}>
<label className="flex w-[84px] cursor-pointer items-center gap-1.5 text-[14px] font-extrabold">
<input type="checkbox" checked={on} onChange={onToggle} className="size-4 accent-(--orange)" />
{label}
</label>
{on ? <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5 text-[13.5px] font-bold">{children}</div> : <span className="text-[13px] font-semibold text-(--ink3)">상관없음</span>}
</div>
)
}
function Num({ value, onChange, min, max, label }: { value: number; onChange: (v: number) => void; min: number; max: number; label: string }) {
return (
<input
type="number"
inputMode="numeric"
aria-label={label}
value={value}
min={min}
max={max}
onChange={(e) => {
const v = Number(e.target.value)
if (e.target.value !== '' && Number.isFinite(v)) onChange(Math.min(max, Math.max(min, v)))
}}
className="w-[58px] rounded-xl bg-[#f3f6fb] px-2 py-1.5 text-center tabular-nums"
/>
)
}
function Choice<T extends string>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<span className="flex gap-1" role="radiogroup" aria-label={label}>
{options.map(([k, word]) => (
<button key={k} type="button" role="radio" aria-checked={value === k} onClick={() => onChange(k)} className={cx('cursor-pointer rounded-full px-3 py-1.5', value === k ? 'bg-(--orange) text-white' : 'bg-[#eef4fc]')}>
{word}
</button>
))}
</span>
)
}
type Filled<T> = { [K in keyof T]-?: NonNullable<T[K]> }
const DEFAULT_RULE: Filled<MyGakRule> = { temp: [15, 25], rain: 'dry', wind_max: 4, air: 'normal', humidity: [30, 60], slots: ['morning', 'day', 'evening', 'night'] }
type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity'
const condsOf = (r: MyGakRule): Record<Cond, boolean> => ({ temp: !!r.temp, rain: !!r.rain, wind_max: r.wind_max != null, air: !!r.air, humidity: !!r.humidity })
/** 있는 각을 골라 그 각 조건으로 채운다 */
function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) {
const items = usePresets().data ?? []
if (!items.length) return null
return (
<div className="mb-3">
<span className="font-jua text-[19px]">있는 각에서 불러오기</span>
<div className="-mx-4">
<Rail label="있는 각에서 불러오기">
{items.map((p) => (
<button
key={p.code}
type="button"
aria-pressed={picked === p.code}
onClick={() => onPick(p)}
className={cx('flex w-[68px] cursor-pointer flex-col items-center gap-1 rounded-2xl px-1 py-2 text-[12px] leading-tight font-extrabold', picked === p.code ? 'bg-(--orange) text-white' : 'bg-[#f3f6fb] text-(--ink2)')}
>
<Ic name={p.icon} className="size-9" />
<span className="w-full truncate">{p.name}</span>
</button>
))}
</Rail>
</div>
</div>
)
}
/** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */
export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) {
const { region } = useRegion()
const { create, pending, failed } = useMyGak()
const [name, setName] = useState(shared?.name ?? '')
const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE)
const [on, setOn] = useState<Record<Cond, boolean>>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false })
const [picked, setPicked] = useState<string | null>(null)
const pick = (p: MyGakPreset) => {
setPicked(p.code)
setName(p.name)
setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE)
setOn(condsOf(p.rule))
}
const set = <K extends keyof typeof vals>(k: K, v: (typeof vals)[K]) => setVals((x) => ({ ...x, [k]: v }))
const toggle = (k: Cond) => setOn((x) => ({ ...x, [k]: !x[k] }))
const rule: MyGakRule = { slots: vals.slots, ...(Object.fromEntries((Object.keys(on) as Cond[]).filter((k) => on[k]).map((k) => [k, vals[k]])) as Partial<MyGakRule>) }
const valid = Object.values(on).some(Boolean) && vals.slots.length > 0 && (!on.temp || vals.temp[0] < vals.temp[1]) && (!on.humidity || vals.humidity[0] < vals.humidity[1])
const score = useMyGakScores(valid ? [rule] : []).data?.scores?.[0]
const title = gakName(name) || '이름 없는 각'
const toggleSlot = (s: Slot) => set('slots', vals.slots.includes(s) ? vals.slots.filter((x) => x !== s) : SLOTS.map(([k]) => k).filter((k) => k === s || vals.slots.includes(k)))
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
{shared ? (
<p className="m-0 text-[13px] font-bold text-(--ink2)">친구가 보낸 각이에요. {region.name} 기준 점수예요</p>
) : (
<>
<PresetPicker picked={picked} onPick={pick} />
<label className="block">
<span className="font-jua text-[19px]">이름</span>
<input value={name} onChange={(e) => setName(e.target.value)} maxLength={11} placeholder="소맥, 야독, 새우깡" className="mt-1.5 w-full rounded-2xl bg-[#f3f6fb] px-3.5 py-2.5 text-[15px]" />
</label>
</>
)}
<fieldset disabled={!!shared} className="m-0 mt-3 border-0 p-0">
<legend className="font-jua text-[19px]">조건</legend>
<Row label="기온" on={on.temp} onToggle={() => toggle('temp')}>
<Num label="최저 기온" value={vals.temp[0]} min={-20} max={40} onChange={(v) => set('temp', [v, vals.temp[1]])} />~
<Num label="최고 기온" value={vals.temp[1]} min={-20} max={40} onChange={(v) => set('temp', [vals.temp[0], v])} />° 체감
</Row>
<Row label="비" on={on.rain} onToggle={() => toggle('rain')}>
<Choice label="비" value={vals.rain} onChange={(v) => set('rain', v)} options={[['dry', '안 와야'], ['wet', '와야']]} />
</Row>
<Row label="바람" on={on.wind_max} onToggle={() => toggle('wind_max')}>
초속 <Num label="바람 상한" value={vals.wind_max} min={1} max={20} onChange={(v) => set('wind_max', v)} />m 이하
</Row>
<Row label="미세먼지" on={on.air} onToggle={() => toggle('air')}>
<Choice label="미세먼지" value={vals.air} onChange={(v) => set('air', v)} options={[['good', '좋음만'], ['normal', '보통까지']]} />
</Row>
<Row label="습도" on={on.humidity} onToggle={() => toggle('humidity')}>
<Num label="최저 습도" value={vals.humidity[0]} min={0} max={100} onChange={(v) => set('humidity', [v, vals.humidity[1]])} />~
<Num label="최고 습도" value={vals.humidity[1]} min={0} max={100} onChange={(v) => set('humidity', [vals.humidity[0], v])} />%
</Row>
<div className="flex flex-wrap items-center gap-1.5 py-2.5 text-[13.5px] font-bold">
<span className="w-[84px] text-[14px] font-extrabold">시간대</span>
{SLOTS.map(([k, word]) => (
<button key={k} type="button" aria-pressed={vals.slots.includes(k)} onClick={() => toggleSlot(k)} className={cx('cursor-pointer rounded-full px-3 py-1.5', vals.slots.includes(k) ? 'bg-(--orange) text-white' : 'bg-[#eef4fc]')}>
{word}
</button>
))}
</div>
</fieldset>
<div className="mt-2 flex flex-col gap-1.5 rounded-[20px] bg-[#f3f6fb] p-3.5">
<div className="flex items-center">
<b className="font-jua text-[20px] font-normal">{title}</b>
<Score s={valid ? score : undefined} big />
</div>
{valid ? <Reasons s={score} /> : <p className="m-0 text-[12.5px] font-semibold text-(--ink3)">조건과 시간대를 하나 이상 골라요</p>}
</div>
{failed && <p className="mt-2 mb-0 text-xs font-bold text-(--heart)">저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요</p>}
<button
type="button"
disabled={!valid || !gakName(name) || pending}
onClick={() => create({ name, rule }, onDone)}
className="mt-3.5 w-full cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[17px] text-white disabled:cursor-default disabled:opacity-45"
>
{shared ? '내 각으로 가져오기' : '내 각으로 저장'}
</button>
</div>
)
}
+137
View File
@@ -0,0 +1,137 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useSyncExternalStore } from 'react'
import { SITE_URL } from '../api/setup'
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '../api/client/@tanstack/react-query.gen'
import { scoreMyGak } from '../api/client/sdk.gen'
import type { MyGakRule, MyGakScore } from '../api/client/types.gen'
import { useAuth } from './authContext'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
const KEY = 'nalssigak.b.myRule'
export type Slot = 'morning' | 'day' | 'evening' | 'night'
export const SLOTS: [Slot, string][] = [
['morning', '아침'],
['day', '낮'],
['evening', '저녁'],
['night', '밤'],
]
/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) */
export type MyGak = { id?: number; name: string; rule: MyGakRule }
function readLocal(): MyGak | null {
try {
const raw = localStorage.getItem(KEY)
return raw ? (JSON.parse(raw) as MyGak) : null
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
return null
}
}
// 시트와 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
let local = readLocal()
const listeners = new Set<() => void>()
const subscribe = (cb: () => void) => {
listeners.add(cb)
return () => listeners.delete(cb)
}
function setLocal(g: MyGak | null) {
local = g
listeners.forEach((cb) => cb())
try {
if (g) localStorage.setItem(KEY, JSON.stringify(g))
else localStorage.removeItem(KEY)
} catch (e) {
console.warn('[myGak] 기기에 저장하지 못함', e)
}
}
/** 이름 끝에 '각'을 붙인다 (서버와 같은 규칙) */
export const gakName = (name: string) => {
const n = name.trim().replace(/\s+/g, ' ')
return n && !n.endsWith('각') ? `${n}각` : n
}
/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 */
export function shareUrl(g: MyGak) {
const json = JSON.stringify({ n: g.name, r: g.rule })
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)))
return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`
}
export function fromShare(code: string): MyGak | null {
try {
const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/'))
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; r?: unknown }
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, rule: v.r as MyGakRule } : null
} catch (e) {
console.warn('[myGak] 받은 링크를 읽지 못함', e)
return null
}
}
/** 조건들의 우리 동네 오늘 점수. 조건이 같으면 캐시를 같이 쓴다 */
export function useMyGakScores(rules: MyGakRule[]) {
const { region } = useRegion()
return useQuery({
queryKey: ['myGakScore', region.code, rules],
enabled: rules.length > 0,
staleTime: 5 * 60_000,
queryFn: async (): Promise<{ nowSlot?: Slot | null; scores: MyGakScore[] }> => {
const { data } = await scoreMyGak({ body: { region_code: region.code, rules } })
if (!data.result?.success) throw new Error(data.result?.desc ?? 'score')
return { nowSlot: data.now_slot, scores: data.scores ?? [] }
},
})
}
/** 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기) */
export function usePresets() {
return useQuery({ ...listPresetsOptions(), staleTime: Infinity, select: (d) => d.items ?? [] })
}
export function useMyGak() {
const { loggedIn } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const q = useQuery({ ...listMyGakOptions(), enabled: loggedIn })
const saved = useSyncExternalStore(subscribe, () => local)
const refresh = () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() })
const add = useMutation({ ...addMyGakMutation(), onSuccess: refresh })
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: refresh })
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
const { mutate } = add
useEffect(() => {
if (!loggedIn || !saved) return
mutate({ body: { name: saved.name, rule: saved.rule } }, { onSuccess: () => setLocal(null) })
}, [loggedIn, saved, mutate])
const items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, rule: g.rule })) : saved ? [saved] : []
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
const create = (g: MyGak, onDone?: () => void) => {
const item = { name: gakName(g.name), rule: g.rule }
if (loggedIn) {
add.mutate({ body: item }, { onSuccess: (res) => res.result?.success && onDone?.() })
return
}
if (saved) {
open({ type: 'login' })
return
}
setLocal(item)
onDone?.()
}
const remove = (g: MyGak) => {
if (g.id != null) return del.mutate({ path: { my_gak_id: g.id } })
setLocal(null)
}
return { items, create, remove, pending: add.isPending, failed: add.data?.result?.success === false }
}
+38
View File
@@ -0,0 +1,38 @@
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
import type { PostReaction, ResFeed } from '../api/client/types.gen'
export type PinnedKey = 'hero_post' | 'gak_post' | 'foliage_post' | 'events_post' | 'season_post'
/** 히어로·오늘의 각·단풍 지도·띠처럼 포스트 틀이 아닌 카드의 좋아요. 화면을 먼저 바꾸고 실패하면 되돌린다 */
export function usePinnedLike(key: PinnedKey, r?: PostReaction | null) {
const queryClient = useQueryClient()
const like = useMutation(likePostMutation())
const unlike = useMutation(unlikePostMutation())
const [failed, setFailed] = useState(false)
const liked = !!r?.liked
const count = r?.like_count ?? 0
const patch = (values: Partial<PostReaction>) =>
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
feed?.[key] && feed[key].post_id === r?.post_id ? { ...feed, [key]: { ...feed[key], ...values } } : feed,
)
const toggle = () => {
if (!r || like.isPending || unlike.isPending) return
const on = !liked
setFailed(false)
patch({ liked: on, like_count: count + (on ? 1 : -1) })
const revert = () => {
patch({ liked, like_count: count })
setFailed(true)
}
;(on ? like : unlike).mutate(
{ path: { post_id: r.post_id } },
{
onSuccess: (res) => (res.result?.success ? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) }) : revert()),
onError: revert,
},
)
}
return { liked, count, failed, toggle }
}
+6 -4
View File
@@ -10,9 +10,9 @@ const KEY = 'nalssigak.b.region'
type RegionPage = (typeof regionPages)[number]
/** /today/gyeonggi/seongnam, /today/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
/** /today/gyeonggi/seongnam, /tomorrow/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
function pageOf(pathname: string): RegionPage | undefined {
const path = pathname.match(/^\/today\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
const path = pathname.match(/^\/(?:today|tomorrow)\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
return path ? regionPages.find((p) => p.path === path) : undefined
}
@@ -45,9 +45,11 @@ export function RegionProvider({ children }: { children: ReactNode }) {
const navigate = useNavigate()
const page = pageOf(pathname)
const pageRef = useRef(page)
const dayRef = useRef(pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today')
useEffect(() => {
pageRef.current = page
}, [page])
dayRef.current = pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today'
}, [page, pathname])
const [stored] = useState(readStored)
const [landing] = useState(page)
const [chosen, setRegionState] = useState<RegionData>(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION)))
@@ -61,7 +63,7 @@ export function RegionProvider({ children }: { children: ReactNode }) {
setRegionState(r)
writeStored(r)
const next = ownPage(r.code)
if (pageRef.current && next && next !== pageRef.current) navigate(`/today/${next.path}`)
if (pageRef.current && next && next !== pageRef.current) navigate(`/${dayRef.current}/${next.path}`)
}, [navigate])
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음)
+187
View File
@@ -0,0 +1,187 @@
import type { Ref } from 'react'
import { createPortal } from 'react-dom'
import { cx } from '../lib/utils'
import type { TopIndex } from '../api/client/types.gen'
import { LEAF_SHADOW, MAP_IMG, MAP_SRC, md, PROVINCE, PROVINCES, STAGE, type Spot } from './foliage'
import { MEDALS, type TimeKind } from './lib'
import { Ic } from './ui'
/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
function Offscreen({ children }: { children: React.ReactNode }) {
return createPortal(
<div aria-hidden="true" className="pointer-events-none fixed top-0 -left-[10000px] w-[380px]">
{children}
</div>,
document.body,
)
}
export type DayShare = {
kind: TimeKind
label: string
now: boolean
icon: string
temp: string
score?: number | null
gak?: { name: string; icon: string } | null
}
function DayLabel({ d, size }: { d: DayShare; size: string }) {
return (
<span className={cx('flex items-center gap-1.5 font-jua leading-none', size)}>
{d.label}
{d.now && <small className="rounded-full bg-[#ff7a45] px-2 py-0.5 font-sans text-[13px] font-extrabold text-white">지금</small>}
</span>
)
}
/** 히어로 공유: 아침·낮·저녁·밤 네 줄. 줄마다 그 시간대 하늘에 날씨·기온, 날씨 점수, 그 시간 1등 각. 로고·지역·날짜는 공유 틀이 그린다 */
export function DayShareCard({ days, ref }: { days: DayShare[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col">
{days.map((d) => (
<div key={d.kind} className="b-hero grid flex-1 grid-cols-[96px_1fr_auto] items-center gap-3 px-4" data-t={d.kind}>
<span className="flex flex-col gap-1.5">
<DayLabel d={d} size="text-[28px]" />
<span className="flex items-center gap-1 font-jua text-[22px] leading-none">
<Ic name={d.icon} className="h-7 w-7 object-contain" />
{d.temp}
</span>
</span>
<span className="flex min-w-0 items-center gap-2">
{d.gak && <Ic name={d.gak.icon} className="w-10 shrink-0" />}
<b className="font-jua text-[24px] leading-tight font-normal break-keep">{d.gak?.name ?? '쉬어 가요'}</b>
</span>
<span className="text-right">
<b className="block font-bagel text-[62px] leading-[0.9] font-normal">{d.score ?? '–'}</b>
<small className="text-[13px] font-bold opacity-75">날씨 점수</small>
</span>
</div>
))}
</div>
</Offscreen>
)
}
/** 1:1 공유용: 같은 내용을 2×2 칸으로 */
export function DayShareGrid({ days, ref }: { days: DayShare[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="grid aspect-square grid-cols-2 grid-rows-2">
{days.map((d) => (
<div key={d.kind} className="b-hero flex flex-col justify-between p-4" data-t={d.kind}>
<span className="flex items-center justify-between">
<DayLabel d={d} size="text-[26px]" />
<span className="flex items-center gap-1 font-jua text-[20px] leading-none">
<Ic name={d.icon} className="h-7 w-7 object-contain" />
{d.temp}
</span>
</span>
<span>
<b className="block font-bagel text-[64px] leading-[0.9] font-normal">{d.score ?? '–'}</b>
<small className="text-[12px] font-bold opacity-75">날씨 점수</small>
</span>
<span className="flex min-w-0 items-center gap-1.5">
{d.gak && <Ic name={d.gak.icon} className="w-8 shrink-0" />}
<b className="truncate font-jua text-[21px] font-normal">{d.gak?.name ?? '쉬어 가요'}</b>
</span>
</div>
))}
</div>
</Offscreen>
)
}
export function GakShareCard({ items, title, ref }: { items: TopIndex[]; title: string; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="b-band-2 flex aspect-[4/5] flex-col bg-white px-5 pt-5 pb-4">
<p className="m-0 font-jua text-[22px]">{title}</p>
<ol className="m-0 mt-3 grid list-none gap-2 p-0">
{items.map((g, i) => (
<li key={g.index_id} className="flex items-center gap-2.5 rounded-[18px] bg-white px-3 py-2.5 shadow-[inset_0_-4px_0_var(--shade)]">
{i < 3 ? <Ic name={MEDALS[i]} className="w-[24px] shrink-0" /> : <span className="w-[24px] shrink-0 text-center font-jua text-(--ink3)">{i + 1}</span>}
<Ic name={g.icon} className="w-[36px] shrink-0" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[17px] leading-tight font-normal">{g.name}</b>
{g.summary && <small className="block truncate text-xs font-semibold text-(--ink2)">{g.summary}</small>}
</span>
<em className="font-bagel text-[24px] leading-none text-(--orange) not-italic">{g.score}</em>
</li>
))}
</ol>
</div>
</Offscreen>
)
}
/** 단풍 명소 하나 공유: 그 명소를 가운데 둔 지도 조각(둘레 시·도 이름과 다른 절정 잎) 위에 큰 잎, 아래에 이름·지역·절정 예상일 */
export function FoliageSpotShare({ spot, peak, ref }: { spot: Spot | null; peak: Spot[]; ref: Ref<HTMLDivElement> }) {
if (!spot) return null
const near = peak.filter((m) => m.name !== spot.name)
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col bg-[#fff6ea] text-[#28304a]">
<div className="relative flex-1 overflow-hidden">
{/* 명소가 가운데 오게 지도 그림을 3배로 키워 옮긴다 */}
<div className="absolute top-1/2 left-1/2 aspect-square w-[220%] bg-[#fff6ea]" style={{ transform: `translate(-${spot.x * 100}%, -${spot.y * 100}%)` }}>
<img src={MAP_SRC} alt="" className={MAP_IMG} />
{PROVINCES.map((v) => (
<span key={v.name} className={cx(PROVINCE, 'text-[15px]')} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
{v.name}
</span>
))}
{near.map((m) => (
<Ic key={m.name} name={m.kind} className={cx('absolute size-5 -translate-x-1/2 -translate-y-1/2', LEAF_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.y * 100}%` }} />
))}
</div>
<span className="absolute top-1/2 left-1/2 grid size-[92px] -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full border-[3px] border-[#28304a] bg-[#ffffff99]">
<Ic name={spot.kind} className={cx('w-[60px]', LEAF_SHADOW)} />
</span>
</div>
<div className="px-5 pt-3 pb-4">
<p className="m-0 flex items-center gap-2">
<b className="font-jua text-[34px] leading-tight font-normal">{spot.name}</b>
<span className={cx('rounded-full px-2 py-0.5 text-[14px] font-extrabold', spot.stage === 'peak' ? 'bg-[#ffe3db] text-[#b5321f]' : 'bg-[#efe6d8] text-[#5b6075]')}>{STAGE[spot.stage]}</span>
</p>
<p className="m-0 mt-0.5 text-[15px] font-bold text-[#6b7189]">{spot.region}</p>
<p className="m-0 mt-2 font-jua text-[22px]">절정 예상 {md(spot.peak)}</p>
</div>
</div>
</Offscreen>
)
}
/** 단풍 지도 전체 공유: 지금 절정 제목, 절정 잎만 찍힌 지도, 가기 좋은 곳 1~3위 */
export function FoliageMapShare({ title, peak, ranked, ref }: { title: string; peak: Spot[]; ranked: Spot[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 font-jua text-[24px] leading-tight">{title}</p>
<div className="relative mx-auto mt-1 aspect-square w-[78%] bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={MAP_IMG} />
{PROVINCES.map((v) => (
<span key={v.name} className={PROVINCE} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
{v.name}
</span>
))}
{peak.map((m) => (
<Ic key={m.name} name={m.kind} className={cx('absolute size-4 -translate-x-1/2 -translate-y-1/2', LEAF_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.y * 100}%` }} />
))}
</div>
<ol className="m-0 mt-auto grid list-none gap-1.5 p-0">
{ranked.slice(0, 3).map((m, i) => (
<li key={m.name} className="flex items-center gap-2.5 rounded-[14px] bg-[#ffffff] px-3 py-1.5">
<Ic name={MEDALS[i]} className="w-[22px] shrink-0" />
<Ic name={m.kind} className="w-[22px] shrink-0" />
<b className="min-w-0 flex-1 truncate font-jua text-[17px] font-normal">{m.name}</b>
<span className="shrink-0 text-[13px] font-bold text-[#6b7189]">{m.region.split(' ')[0]}</span>
<span className="shrink-0 font-jua text-[16px] text-[#b5321f]">{md(m.peak)}</span>
</li>
))}
</ol>
</div>
</Offscreen>
)
}
+7 -1
View File
@@ -1,5 +1,8 @@
import type { MyGak } from './myGakState'
import type { WeatherWhyPayload } from './weatherWhy'
import { createContext, use } from 'react'
export type SharePayload = { title: string; slides: HTMLElement[] }
/** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides) */
export type SharePayload = { title: string; slides: HTMLElement[]; square?: HTMLElement[] }
type CommentsState = { type: 'comments'; postId: number; draft?: string }
@@ -12,6 +15,9 @@ export type SheetState =
| { type: 'login'; then?: CommentsState }
| { type: 'me' }
| { type: 'region' }
| { type: 'mix'; shared?: MyGak }
| { type: 'install' }
| { type: 'weatherWhy'; why: WeatherWhyPayload }
| null
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
+2 -1
View File
@@ -35,7 +35,7 @@ export function PinIcon({ className }: P) {
)
}
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' }) {
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' | 'talk' }) {
return (
<svg viewBox="0 0 24 24" {...line} className={className} aria-hidden="true">
{name === 'today' && <path d="M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />}
@@ -55,6 +55,7 @@ export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky'
<circle cx="12" cy="15" r="1.6" />
</>
)}
{name === 'talk' && <path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.5 4v-4h0A1.5 1.5 0 0 1 4 14.5zM8 8.5h8M8 12h5" />}
{name === 'season' && <path d="M12 6.5C10 5 7 4.5 3.5 5v14c3.5-.5 6.5 0 8.5 1.5 2-1.5 5-2 8.5-1.5V5C17 4.5 14 5 12 6.5zM12 6.5v14" />}
</svg>
)
+373
View File
@@ -0,0 +1,373 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from 'react'
import { Link } from 'react-router'
import {
addTalkMutation,
blockTalkAuthorMutation,
deleteTalkMutation,
likeTalkMutation,
reportTalkMutation,
unlikeTalkMutation,
} from '../api/client/@tanstack/react-query.gen'
import { uploadTalkImage } from '../api/client/sdk.gen'
import { TalkReport, TalkTopic, type TalkData } from '../api/client/types.gen'
import { API_BASE_URL } from '../api/setup'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, kst } from './lib'
import { useRegion } from './regionContext'
import { topicName, TOPICS, useMyTalks } from './talkState'
import { useSheet } from './sheetContext'
import { HeartIcon } from './svg'
import { Avatar, Rail, TAP44 } from './ui'
const BODY_MAX = 100
const PHOTO_MAX = 10 * 1024 * 1024
// 서버 ErrorType 이름 → 안내
const WRITE_ERRORS: Record<string, string> = {
LINK_NOT_ALLOWED: '링크나 전화번호는 쓸 수 없어요.',
DAILY_LIMIT: '오늘은 더 쓸 수 없어요. 하루 5개까지예요.',
INVALID_INPUT: '100자 안으로 써 주세요.',
}
// 글이 이보다 적으면 '동네 사람들' 묶음 대신 첫 글 쓰기 카드
const GROUP_MIN = 3
const COMPOSE_ID = 'talk-compose'
const REASONS = [
[TalkReport.ABUSE, '욕설·비하'],
[TalkReport.SPAM, '광고·도배'],
[TalkReport.PRIVACY, '개인정보 노출'],
[TalkReport.ETC, '기타'],
] as const
/** 쓴 시각을 시간대로만: 정확한 시각은 동선이 드러나서 뭉갠다 */
function slotWord(iso: string) {
const h = kst(iso).h
return h < 6 ? '새벽' : h < 10 ? '아침' : h < 17 ? '낮' : h < 21 ? '저녁' : '밤'
}
function useRefreshTalks() {
const queryClient = useQueryClient()
return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks', 'talkGroups'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') })
}
function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
const { region } = useRegion()
const { loggedIn, me } = useAuth()
const { open } = useSheet()
const refresh = useRefreshTalks()
const add = useMutation(addTalkMutation())
const [text, setText] = useState('')
const [topic, setTopic] = useState<TalkTopic>(TalkTopic.LOCAL)
const [error, setError] = useState<string | null>(null)
const [photo, setPhoto] = useState<{ file: File; src: string } | null>(null)
const [uploading, setUploading] = useState(false)
const fileRef = useRef<HTMLInputElement>(null)
const busy = add.isPending || uploading
useEffect(() => {
if (!photo) return
return () => URL.revokeObjectURL(photo.src)
}, [photo])
const pick = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
e.target.value = ''
if (!file) return
if (file.size > PHOTO_MAX) return setError('사진은 10MB까지 올릴 수 있어요.')
setError(null)
setPhoto({ file, src: URL.createObjectURL(file) })
}
// 사진이 있으면 먼저 올려 주소를 받고, 그 주소를 글에 붙인다
const upload = async (): Promise<string | undefined> => {
if (!photo) return undefined
setUploading(true)
try {
const { data } = await uploadTalkImage({ body: { file: photo.file } })
if (!data.result?.success || !data.image) throw new Error(data.result?.desc ?? 'upload')
return data.image
} finally {
setUploading(false)
}
}
const submit = (e: FormEvent) => {
e.preventDefault()
if (!loggedIn) return open({ type: 'login' })
const body = text.trim()
if (!body || busy) return
setError(null)
upload().then(
(image) =>
add.mutate(
{ body: { region_code: region.code, body, image, topic } },
{
onSuccess: (res) => {
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
setText('')
setPhoto(null)
setTopic(TalkTopic.LOCAL)
refresh()
if (res.talk) onDone?.(res.talk)
},
onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
},
),
(e: unknown) => {
console.error('[talk] photo upload', e)
setError('사진을 올리지 못했어요. 사진 파일인지 확인해 주세요.')
},
)
}
return (
<form onSubmit={submit} className="mx-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<textarea
id={COMPOSE_ID}
value={text}
onChange={(e) => setText(e.target.value)}
onFocus={() => !loggedIn && open({ type: 'login' })}
readOnly={busy}
maxLength={BODY_MAX}
rows={2}
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
aria-label="동네 이야기 쓰기"
className="w-full resize-none rounded-2xl bg-[#f3f6fb] px-3 py-2.5 text-[14.5px]"
/>
{photo && (
<div className="relative mt-2 w-[96px]">
<img src={photo.src} alt="올릴 사진" className="aspect-[4/5] w-full rounded-xl object-cover" />
<button type="button" onClick={() => setPhoto(null)} aria-label="사진 빼기" className="absolute -top-1.5 -right-1.5 grid size-6 cursor-pointer place-items-center rounded-full bg-(--ink) text-[13px] font-extrabold text-white">
×
</button>
</div>
)}
<div className="mt-2 flex flex-wrap gap-1.5" role="radiogroup" aria-label="글 주제">
{TOPICS.map(([k, label]) => (
<button
key={k}
type="button"
role="radio"
aria-checked={topic === k}
onClick={() => setTopic(k)}
className={cx('cursor-pointer rounded-full px-2.5 py-1 text-[12.5px] font-extrabold', topic === k ? 'bg-(--ink) text-white' : 'bg-[#f3f6fb] text-(--ink2)')}
>
{label}
</button>
))}
</div>
<input ref={fileRef} type="file" accept="image/*" onChange={pick} hidden />
<div className="mt-1.5 flex items-center gap-2 text-xs font-bold text-(--ink3)">
<button type="button" onClick={() => (loggedIn ? fileRef.current?.click() : open({ type: 'login' }))} disabled={busy} className="shrink-0 cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2) disabled:opacity-40">
사진
</button>
<span className="min-w-0 truncate">{me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}</span>
<span className="ml-auto tabular-nums">
{text.length}/{BODY_MAX}
</span>
<button type="submit" disabled={busy || (loggedIn && !text.trim())} className="shrink-0 cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white disabled:opacity-40">
{busy ? '올리는 중…' : '올리기'}
</button>
</div>
{error && (
<p className="mt-1 mb-0 text-xs font-bold text-(--heart)" role="alert">
{error}
</p>
)}
</form>
)
}
/** onGone: 내 글을 지웠을 때. 목록을 다시 받아도 빠지지 않는 곳(방금 쓴 글)에서 직접 뺀다 */
function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; compact?: boolean }) {
const { loggedIn } = useAuth()
const { open } = useSheet()
const refresh = useRefreshTalks()
const [liked, setLiked] = useState(t.liked)
const [count, setCount] = useState(t.like_count)
const [menu, setMenu] = useState<'closed' | 'open' | 'report' | 'done'>('closed')
const like = useMutation(likeTalkMutation())
const unlike = useMutation(unlikeTalkMutation())
const remove = useMutation(deleteTalkMutation())
const report = useMutation(reportTalkMutation())
const block = useMutation(blockTalkAuthorMutation())
const [failed, setFailed] = useState(false)
const toggle = () => {
if (like.isPending || unlike.isPending) return
const next = !liked
setLiked(next)
setCount((n) => n + (next ? 1 : -1))
;(next ? like : unlike).mutate(
{ path: { talk_id: t.talk_id } },
{
onSuccess: (res) => {
if (res.result?.success && res.like_count != null) return setCount(res.like_count)
setLiked(!next)
setCount(t.like_count)
},
onError: () => {
setLiked(!next)
setCount(t.like_count)
},
},
)
}
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
const after = {
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true)
setMenu('done')
refresh()
},
onError: () => setFailed(true),
}
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }))
const src = t.image?.startsWith('/v1/') ? API_BASE_URL + t.image : (t.image ?? undefined)
return (
<div className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 border-b border-(--line) py-2.5 last:border-b-0">
<Avatar character={t.character} color={t.color} mood={t.mood} />
<div className="min-w-0">
<small className="block text-xs font-bold text-(--ink3)">
<b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b>
{[t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ')}
</small>
{t.image && compact && <img src={src} alt="" loading="lazy" className="float-right mt-1 ml-2 size-12 rounded-xl bg-[#eef4fc] object-cover" />}
<p className={cx('m-0 mt-0.5 text-[14.5px] break-words whitespace-pre-wrap', compact && 'line-clamp-2')}>{t.body}</p>
{t.image && !compact && <img src={src} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
{ago(t.created_at)} · 좋아요 {count}개 ·{' '}
<button type="button" onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
{t.mine ? '내 글' : '더보기'}
</button>
</small>
{menu !== 'closed' && (
<div className="mt-1.5 flex flex-wrap gap-1.5 text-[12.5px] font-extrabold" role="group" aria-label="글 메뉴">
{menu === 'done' ? (
<span className="text-[#1f9d62]">처리했어요</span>
) : t.mine ? (
<button type="button" onClick={() => remove.mutate({ path: { talk_id: t.talk_id } }, { ...after, onSuccess: (res) => (after.onSuccess(res), res.result?.success && onGone?.()) })} disabled={remove.isPending} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
지우기
</button>
) : menu === 'report' ? (
REASONS.map(([reason, label]) => (
<button key={reason} type="button" onClick={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after)} disabled={report.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
{label}
</button>
))
) : (
<>
<button type="button" onClick={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after))} disabled={block.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
이 사람 글 안 보기
</button>
<button type="button" onClick={() => guard(() => setMenu('report'))} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
신고하기
</button>
</>
)}
{failed && (
<span className="text-(--heart)" role="alert">
못 했어요. 다시 해 주세요
</span>
)}
</div>
)}
</div>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
</button>
</div>
)
}
/** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */
/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 방금 올린 글은 바로 아래에 보인다 (피드 사이 글은 새로 받을 때 섞인다) */
export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void }) {
return (
<div className="mt-3.5">
<Composer onDone={onPosted} />
</div>
)
}
/** 피드에 끼우는 글 한 장 */
export function TalkCard({ t, onGone }: { t: TalkData; onGone?: () => void }) {
return (
<article className="mt-3.5 border-y border-(--line) bg-white px-3" aria-label={`${t.nickname}의 글`}>
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} onGone={onGone} />
</article>
)
}
/** 오늘 피드의 사람 글 묶음: 옆으로 넘기는 카드, 끝에 그 주제 전체 보기 */
export function TalkGroup({ title, topic, talks }: { title: string; topic?: number; talks: TalkData[] }) {
return (
<section aria-label={title} className="mt-3.5">
<div className="flex items-end justify-between px-4">
<h2 className="m-0 font-jua text-[19px] font-normal">{title}</h2>
<Link to={topic ? `/talk?topic=${topic}` : '/talk'} className="text-[13px] font-bold text-(--ink2)">
전체 보기
</Link>
</div>
<Rail label={title}>
{talks.map((t) => (
<article key={`${t.talk_id}:${t.liked}:${t.like_count}`} className="w-[78%] max-w-[320px] rounded-[20px] bg-white px-3 shadow-[inset_0_-4px_0_var(--shade)]" aria-label={`${t.nickname}의 글`}>
<TalkRow t={t} compact />
</article>
))}
</Rail>
</section>
)
}
/** '동네 사람들' 글이 적을 때 묶음 대신: 위 쓰기 칸으로 데려간다 */
export function FirstTalkCard() {
const { region } = useRegion()
const place = region.name.split(' ').at(-1)
const go = () => {
const el = document.getElementById(COMPOSE_ID)
el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
el?.focus({ preventScroll: true })
}
return (
<button type="button" onClick={go} className="mx-3 mt-3.5 flex w-[calc(100%-1.5rem)] cursor-pointer items-center gap-3 rounded-[22px] bg-white p-3.5 text-left shadow-[inset_0_-5px_0_var(--shade)]">
<span className="font-jua text-[16.5px] leading-snug">
지금 {place} 하늘 어때요?
<small className="block font-sans text-[12.5px] font-semibold text-(--ink2)">첫 이야기를 남겨 주세요</small>
</span>
<span className="ml-auto shrink-0 rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">쓰기</span>
</button>
)
}
/** '동네 사람들' 자리: 글이 GROUP_MIN 개 이상이면 묶음, 아니면 첫 글 쓰기 */
export function NearTalks({ talks, loaded }: { talks: TalkData[]; loaded: boolean }) {
if (!loaded) return null
return talks.length >= GROUP_MIN ? <TalkGroup title="동네 사람들" talks={talks} /> : <FirstTalkCard />
}
/** 내 정보 창의 내가 쓴 글 */
export function MyTalks() {
const { talks, loaded, more, loadMore } = useMyTalks()
if (!loaded) return null
return (
<section aria-label="내 글">
<h4 className="m-0 mb-1 text-sm font-extrabold">내 글</h4>
{talks.length ? (
talks.map((t) => <TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />)
) : (
<p className="m-0 text-[13px] font-semibold text-(--ink3)">아직 쓴 글이 없어요</p>
)}
{more && (
<button type="button" onClick={() => loadMore()} className="mt-1 w-full cursor-pointer rounded-[14px] bg-[#f3f6fb] py-2.5 text-[13.5px] font-extrabold text-(--ink2)">
더 보기
</button>
)}
</section>
)
}
+53
View File
@@ -0,0 +1,53 @@
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions, talkGroupsOptions } from '../api/client/@tanstack/react-query.gen'
import { TalkTopic, type TalkData } from '../api/client/types.gen'
import { useRegion } from './regionContext'
// 글 주제와 피드 묶음 이름
export const TOPICS = [
[TalkTopic.LOCAL, '동네 이야기'],
[TalkTopic.SKY, '하늘·노을'],
[TalkTopic.RAIN, '비·눈'],
[TalkTopic.FOLIAGE, '단풍·꽃'],
[TalkTopic.OUTFIT, '오늘 옷차림'],
] as const
export const topicName = (t?: number) => TOPICS.find(([k]) => k === t)?.[1] ?? '동네 이야기'
/** 오늘 피드 묶음: 0 은 '동네 사람들', 나머지는 주제별(3장 이상일 때만 옴) */
export function useTalkGroups() {
const { region } = useRegion()
const q = useQuery(talkGroupsOptions({ query: { region: region.code } }))
const groups = new Map<number, TalkData[]>((q.data?.groups ?? []).map((g) => [g.topic, g.talks ?? []]))
return { groups, loaded: q.isSuccess }
}
/** 주제별 글 페이지 목록 (topic 없으면 전체) */
export function useTopicTalks(topic?: TalkTopic) {
const { region } = useRegion()
const list = useInfiniteQuery({
...listTalksInfiniteOptions({ query: { region: region.code, ...(topic ? { topic } : {}) } }),
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
})
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
loaded: list.isSuccess,
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
}
}
/** 내가 쓴 글 (최신순) */
export function useMyTalks() {
const list = useInfiniteQuery({
...listMyTalksInfiniteOptions(),
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
})
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
loaded: list.isSuccess,
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
}
}
+88
View File
@@ -0,0 +1,88 @@
import type { WeatherWhy } from '../api/client/types.gen'
import { cx } from '../lib/utils'
/** status: 히어로 상태 줄 그대로 (단계 이름, 실제 값) */
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[]; status?: { label: string; value: string; tone?: string; detail?: string | null }[] }
// 조건마다 같은 색을 막대 칸과 아래 줄 점에 같이 써서 이어 보이게
const COLOR: Record<string, string> = {
기온: '#ff7a45',
비: '#4f97e3',
햇볕: '#ffb02e',
바람: '#5fb8b0',
습도: '#8e8cf0',
미세먼지: '#b59a86',
}
const colorOf = (label: string) => COLOR[label] ?? '#9aa3b8'
// 상태 줄 항목마다 단계를 나누는 기준 (backend/services/hero_stats.py 와 같은 값)
const RULE: Record<string, string> = {
습도: '30% 아래는 건조, 60% 넘으면 습함이에요',
불쾌지수: '68 아래는 쾌적, 75부터 불쾌예요',
자외선: '3 아래는 낮음, 6부터 높음이에요',
미세먼지: '에어코리아 기준 등급이에요',
}
/** 날씨 점수 근거: 비중만큼 나눈 막대(채운 만큼 얻은 점수)와 조건별 지금 값 */
export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) {
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-4 pb-[18px]">
<p className="m-0 flex items-baseline gap-2">
<b className="font-bagel text-[44px] leading-none font-normal">{d.score}</b>
<span className="font-jua text-[17px] text-(--ink2)">{d.label} 날씨 점수</span>
</p>
<div className="mt-3 flex h-7 gap-[3px] overflow-hidden rounded-[10px]" role="img" aria-label={d.why.map((w) => `${w.label} 비중 ${w.weight}% 중 ${w.score}점`).join(', ')}>
{d.why.map((w) => (
<span key={w.label} className="relative h-full bg-[#eef2f8]" style={{ width: `${w.weight}%` }}>
<span className="absolute inset-y-0 left-0" style={{ width: `${w.score}%`, background: colorOf(w.label) }} />
</span>
))}
</div>
<p className="m-0 mt-1.5 text-[12.5px] font-semibold text-(--ink3)">칸 넓이는 비중, 채운 만큼이 얻은 점수예요</p>
<ul className="m-0 mt-3 flex list-none flex-col gap-1.5 p-0">
{d.why.map((w) => (
<li key={w.label} className="flex items-center gap-3 rounded-2xl bg-[#f5f8fc] px-3.5 py-2.5">
<i className="size-3 shrink-0 rounded-full" style={{ background: colorOf(w.label) }} aria-hidden="true" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[16px] leading-tight font-normal">
{w.label} <small className="font-sans text-[12px] font-bold text-(--ink3)">비중 {w.weight}%</small>
</b>
<small className="block text-[13px] font-semibold text-(--ink2)">{w.note}</small>
</span>
<b className="font-jua text-[20px] font-normal tabular-nums">{w.score}</b>
</li>
))}
</ul>
{d.status && d.status.length > 0 && (
<>
<h4 className="m-0 mt-5 font-jua text-[17px] font-normal">지금 상태</h4>
<ul className="m-0 mt-2 flex list-none flex-col gap-1.5 p-0">
{d.status.map((s) => (
<li key={s.label} className="flex items-center gap-3 rounded-2xl bg-[#f5f8fc] px-3.5 py-2.5">
<span className="min-w-0 flex-1">
<b className="block font-jua text-[16px] leading-tight font-normal">{s.label}</b>
{RULE[s.label] && <small className="block text-[12.5px] font-semibold text-(--ink3)">{RULE[s.label]}</small>}
</span>
<span className="shrink-0 text-right">
<b className={cx('block font-jua text-[18px] leading-tight font-normal', s.tone === 'warn' && 'b-warn')}>{s.value}</b>
{s.detail?.split(' · ').map((x) => (
<small key={x} className="block text-[12px] font-bold whitespace-nowrap text-(--ink2) tabular-nums">
{x}
</small>
))}
</span>
</li>
))}
</ul>
</>
)}
<p className="m-0 mt-3 text-[13px] leading-relaxed font-semibold text-(--ink2)">
조건마다 점수를 매겨 비중대로 합쳐요. 유난히 아쉬운 조건이 있으면 조금 더 깎고, 모든 조건이 완벽할 때만 만점이 나와요.
</p>
</div>
)
}
+6 -1
View File
@@ -3,9 +3,14 @@ type Events = {
view_gak: { index_id: number; gak_name: string; score: number; rank: number }
select_content: { content_type: 'article'; item_id: number; category: string }
share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string }
login: { method: 'id' }
login: { method: 'id' | 'google' }
sign_up: { method: 'id' }
region_change: { region_name: string; method: 'list' | 'location' }
install_banner_view: Record<string, never>
install_click: { from: 'banner' | 'menu'; method: 'prompt' | 'guide' }
install_choice: { outcome: 'accepted' | 'dismissed' }
install_done: Record<string, never>
app_launch: { mode: 'standalone' }
}
declare global {
+8
View File
@@ -4,6 +4,8 @@ import { createRoot } from 'react-dom/client'
import './index.css'
import './api/setup'
import App from './App.tsx'
import './b/install'
import { track } from './lib/analytics'
// iOS는 user-scalable=no를 무시해서 두 손가락 확대를 직접 막는다
for (const type of ['gesturestart', 'gesturechange']) document.addEventListener(type, (e) => e.preventDefault(), { passive: false })
@@ -13,6 +15,12 @@ const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, refetchOnWindowFocus: false, placeholderData: keepPreviousData } },
})
// 홈 화면 설치 조건(서비스 워커)과, 홈 화면 아이콘으로 연 횟수
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').catch((e: unknown) => console.error('[sw] register', e))
}
if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) track('app_launch', { mode: 'standalone' })
createRoot(document.getElementById('root')!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
+153 -3
View File
@@ -1,4 +1,4 @@
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'
@@ -6,10 +6,22 @@ import { defineConfig, type Plugin } from 'vite'
type Gak = { name: string; description: string }
type RegionPage = { path: string; name: string; main: string; regions: { code: string; name: string }[] }
type Faq = { q: string; a: string }
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 regionPages: RegionPage[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/region.json'), 'utf8'))
const faqGroups: { category: string; items: Faq[] }[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/faq.json'), 'utf8'))
/** 지역별 장소: 시도마다 한 파일 seo/region_faq/seoul.json (backend/scripts/gen_region_faq.py 가 만든다) */
const regionFaqDir = resolve(import.meta.dirname, 'seo/region_faq')
const regionPlaces: Record<string, { outdoor: string[]; indoor: string[]; sunset: string[] }> = Object.assign(
{},
...readdirSync(regionFaqDir)
.filter((f) => f.endsWith('.json'))
.map((f) => JSON.parse(readFileSync(resolve(regionFaqDir, f), 'utf8'))),
)
const faqList = (items: Faq[]) => items.map((f) => `<h3>${f.q}</h3><p>${f.a}</p>`).join('')
/** 검색 로봇이 처음 받는 페이지별 HTML. 바뀌지 않는 소개 글만 넣고, 날씨 값은 앱이 뜬 뒤 불러온다 */
const PAGES: { path: string; title: string; description: string; body: string; code?: string; keywords?: string }[] = [
@@ -57,18 +69,150 @@ for (const r of regionPages) {
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(', ')
// 지역 이름이 든 질문: 답은 매일 바뀌지 않는 말만 (오늘 값은 서버가 h1 아래에 채운다)
const faq: Faq[] = [
{ q: `${bare} 오늘 날씨 어때요?`, a: `이 페이지 맨 위에 ${r.name}의 오늘 최저·최고 기온, 강수확률, 지금 기온과 하늘 상태가 나와요. 기상청 예보가 나올 때마다 하루 8번, 미세먼지는 매시간 새로 반영해요.` },
{ q: `${bare} 오늘 뭐 하기 좋아요?`, a: `${r.name}의 오늘 날씨로 세차, 빨래, 러닝, 피크닉 같은 ${gaks.length}가지 일을 점수 매겨 아침, 낮, 저녁, 밤마다 1위를 알려 드려요. 이 페이지의 오늘 각 순위에서 바로 확인하세요.` },
{ q: `${bare} 비 오는 날 뭐 할까요?`, a: `${head}에 비가 오면 우산각·파전각·막걸리각·넷플릭스각 점수가 올라가요. 빨래는 실내 건조로 돌리고 세차는 비가 그친 뒤 이틀쯤 미루는 게 좋아요.` },
{ q: `${bare} 세차·빨래하기 좋은 날은 언제예요?`, a: `세차각은 ${head}의 이틀 뒤까지 비 소식을 함께 봐서 비 걱정 없는 날 점수가 높아요. 빨래각은 낮 9~16시에 해가 잘 들고 바람이 적당하고 덜 습할수록 높아요.` },
{ q: `${bare} 노을은 몇 시에 봐요?`, a: `이 페이지에 ${r.name}의 오늘 해 지는 시각이 나와요. 노을은 보통 해 진 뒤 10~20분이 가장 붉고, 노을 탭에서 얼마나 물들지와 가까운 노을 명소를 볼 수 있어요.` },
]
PAGES.push({
path: `today/${r.path}`,
code: r.main,
keywords,
title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[isGu ? 1 : 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>${bare} 날씨, 오늘 ${head}에서는 뭐 하기 좋을까요? ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.</p>${parts}<p>세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.</p><p><a href="/tomorrow/${r.path}">${r.name} 내일 날씨 보기</a></p><h2>${r.name} 날씨 자주 묻는 질문</h2>${faqList(faq)}<p><a href="/faq/${sido}">${r.name.split(' ')[0]} 지역별 날씨 자주 묻는 질문</a> · <a href="/faq">날씨별로 뭐 하면 좋을까?</a></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 tomorrowKeywords = [...new Set([`${bare} 내일 날씨`, `${head} 내일 날씨`, `${r.name} 내일 날씨`, ...guNames.flatMap((g) => [`${g} 내일 날씨`, `${bareName(g)} 내일 날씨`]), '날씨각'])].join(', ')
PAGES.push({
path: `tomorrow/${r.path}`,
code: r.main,
keywords: tomorrowKeywords,
title: `${head} 내일 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[isGu ? 1 : 0]}` : ''} | 날씨각`,
description: `내일 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 미리 알려 드려요.`,
body: `<h1>${r.name} 내일 날씨, 뭐 할까?</h1><p>${bare} 내일 날씨, 내일 ${head}에서는 뭐 하기 좋을까요? ${r.name}의 기상청 예보로 내일 하기 좋은 일을 아침, 낮, 저녁, 밤마다 점수로 미리 알려 드려요.</p><p>내일 최저·최고 기온과 강수확률, 해 지는 시각을 하루 8번 새 예보로 바꿔 드려요.</p><p><a href="/today/${r.path}">${r.name} 오늘 날씨 보기</a></p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 내일 날씨</h2><ul>${near.map((o) => `<li><a href="/tomorrow/${o.path}">${o.name} 내일 날씨</a></li>`).join('')}</ul>` : ''}`,
})
}
const attr = (s: string) => s.replace(/&/g, '&amp;').replace(/"/g, '&quot;')
// 시도별로 지역을 모은다 (seoul → 서울). 구로 나뉜 시의 구도 모두 (수원시 장안구): 시 바로 뒤에 둔다
const sidoPages = new Map<string, { name: string; regions: RegionPage[] }>()
for (const r of regionPages.filter((o) => o.path.split('/').length === 2).flatMap((c) => [c, ...regionPages.filter((o) => o.path.startsWith(`${c.path}/`))])) {
const slug = r.path.split('/')[0]
const s = sidoPages.get(slug) ?? { name: r.name.split(' ')[0], regions: [] }
s.regions.push(r)
sidoPages.set(slug, s)
}
/** 질문에 쓰는 이름: 군산, 강남, 수원 장안구 */
const shortName = (r: RegionPage) => {
const parts = r.name.split(' ').slice(1)
return parts.length === 2 ? `${bareName(parts[0])} ${parts[1]}` : bareName(headName(r.name))
}
const shortCounts = new Map<string, number>()
for (const r of regionPages) shortCounts.set(shortName(r), (shortCounts.get(shortName(r)) ?? 0) + 1)
/** 중구·동구처럼 여러 시도에 있으면 서울 중구 */
const askName = (r: RegionPage) => (shortCounts.get(shortName(r))! > 1 ? `${r.name.split(' ')[0]} ${shortName(r)}` : shortName(r))
function regionFaq(r: RegionPage): Faq[] {
const name = askName(r)
const { outdoor = [], indoor = [], sunset = [] } = regionPlaces[r.path] ?? {}
const where = [
outdoor.length ? `맑은 날엔 ${outdoor.join('·')}처럼 바깥 나들이가 좋아요.` : '맑은 날엔 가까운 공원에서 산책이나 피크닉이 좋아요.',
indoor.length ? `비 오는 날엔 ${indoor.join('·')} 같은 실내 장소를 추천해요.` : '비 오는 날엔 실내 전시나 카페처럼 비를 피할 수 있는 곳이 좋아요.',
sunset.length ? `노을은 ${sunset.join('·')}에서 보기 좋아요.` : '',
]
return [
{ q: `${name} 오늘 날씨 어때요?`, a: `${r.name}의 오늘 최저·최고 기온, 강수확률, 지금 기온은 날씨각 ${name} 오늘 날씨 페이지에서 볼 수 있어요. 기상청 예보가 나올 때마다 하루 8번 새로 반영하고, 그 날씨로 세차·빨래·러닝 같은 ${gaks.length}가지 일을 아침·낮·저녁·밤마다 점수로 알려 드려요.` },
{ q: `${name} 날씨별로 어디 가면 좋아요?`, a: `${where.filter(Boolean).join(' ')} 날씨각 주말 탭에서 ${name} 날씨에 맞는 나들이 장소와 가까운 행사를 볼 수 있어요.` },
]
}
/** FAQ 정적 페이지 한 장: 앱(SPA)을 거치지 않아 사람도 로봇과 같은 글을 본다. 그래서 FAQPage 구조화 데이터는 FAQ 페이지에만 넣는다 */
function faqHtml(site: string, p: { path: string; title: string; description: string; keywords: string; body: string; items: Faq[] }): string {
const url = `${site}/${p.path}`
const ld = {
'@context': 'https://schema.org',
'@type': 'FAQPage',
mainEntity: p.items.map((f) => ({ '@type': 'Question', name: f.q, acceptedAnswer: { '@type': 'Answer', text: f.a } })),
}
return `<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${p.title}</title>
<meta name="description" content="${attr(p.description)}" />
<meta name="keywords" content="${attr(p.keywords)}" />
<link rel="canonical" href="${url}" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="날씨각" />
<meta property="og:title" content="${attr(p.title)}" />
<meta property="og:description" content="${attr(p.description)}" />
<meta property="og:url" content="${url}" />
<meta property="og:image" content="${site}/og.png" />
<meta property="og:locale" content="ko_KR" />
<script type="application/ld+json">${JSON.stringify(ld).replace(/</g, '\u003c')}</script>
<style>
body { margin: 0; padding: 32px 20px 64px; font: 15px/1.7 -apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Malgun Gothic", sans-serif; color: #28304a; background: #f1f8ff; }
main { max-width: 720px; margin: 0 auto; }
h1 { font-size: 26px; margin: 0 0 8px; }
h2 { font-size: 20px; margin: 40px 0 8px; }
h3 { font-size: 16px; margin: 24px 0 4px; }
p { margin: 0 0 8px; }
a { color: #2d5bd7; }
.sidos a { display: inline-block; margin: 0 12px 4px 0; }
</style>
</head>
<body>
<main>
${p.body}
<p><a href="/">날씨각 처음으로</a> · <a href="/gak">오늘의 각</a> · <a href="/sky">오늘 노을</a> · <a href="/week">주말·행사</a></p>
</main>
</body>
</html>
`
}
/** /faq (날씨별 추천·각 기준·이용 안내) 와 시도마다 /faq/seoul (지역별 질문) */
function faqPages(site: string): { path: string; html: string }[] {
const sidoLinks = `<p class="sidos">${[...sidoPages].map(([slug, s]) => `<a href="/faq/${slug}">${s.name} 날씨</a>`).join(' ')}</p>`
const main = faqHtml(site, {
path: 'faq',
title: '날씨별로 뭐 하면 좋을까? 자주 묻는 질문 | 날씨각',
description: '비 오는 날, 맑은 날, 미세먼지 나쁜 날 뭐 하면 좋을까요? 세차·빨래·러닝·캠핑하기 좋은 날씨와 지역별 오늘 날씨 보는 법을 날씨각이 알려 드려요.',
keywords: '비 오는 날 뭐하지, 맑은 날 뭐하지, 미세먼지 나쁜 날, 세차하기 좋은 날씨, 빨래 잘 마르는 날씨, 러닝하기 좋은 날씨, 캠핑하기 좋은 날씨, 등산하기 좋은 날씨, 노을 예쁜 날, 오늘 날씨, 지역별 날씨, 날씨각',
items: faqGroups.flatMap((g) => g.items),
body: `<h1>날씨별로 뭐 하면 좋을까?</h1>
<p>비 오는 날, 맑은 날, 미세먼지 나쁜 날 하기 좋은 일과 세차·빨래·러닝하기 좋은 날씨를 정리했어요. 우리 동네 오늘 점수는 <a href="/">날씨각</a>에서 바로 볼 수 있어요.</p>
${faqGroups.map((g) => `<h2>${g.category}</h2>${faqList(g.items)}`).join('\n')}
<h2>지역별 날씨 자주 묻는 질문</h2>
<p>군산 날씨, 강남 날씨처럼 전국 시·군·구마다 오늘 날씨와 날씨에 맞는 나들이 장소를 따로 알려 드려요.</p>
${sidoLinks}`,
})
const sidos = [...sidoPages].map(([slug, s]) => {
const names = s.regions.map(askName)
return faqHtml(site, {
path: `faq/${slug}`,
title: `${s.name} 지역별 날씨, 뭐 할까? 자주 묻는 질문 | 날씨각`,
description: `${names.slice(0, 5).join('·')} 등 ${s.name} ${s.regions.length}개 지역의 오늘 날씨 보는 법과 맑은 날·비 오는 날 가기 좋은 곳, 노을 명소를 날씨각이 알려 드려요.`,
keywords: [...names.map((n) => `${n} 날씨`), `${s.name} 날씨`, '날씨각'].join(', '),
items: s.regions.flatMap(regionFaq),
body: `<h1>${s.name} 지역별 날씨 자주 묻는 질문</h1>
<p>${s.name} 시·군·구마다 오늘 날씨 보는 법과 날씨에 맞는 나들이 장소를 정리했어요. 날씨별로 뭐 하면 좋을지는 <a href="/faq">자주 묻는 질문</a>에서 볼 수 있어요.</p>
${s.regions.map((r) => `<h2>${r.name.split(' ').slice(1).join(' ') || r.name} 날씨</h2>${regionFaq(r).map((f, i) => `<h3>${f.q}</h3><p>${attr(f.a)}${i === 0 ? ` <a href="/today/${r.path}">${askName(r)} 오늘 날씨 보기</a>` : ''}</p>`).join('')}`).join('\n')}
<h2>다른 시도 날씨</h2>
${sidoLinks}`,
})
})
return [{ path: 'faq', html: main }, ...[...sidoPages.keys()].map((slug, i) => ({ path: `faq/${slug}`, html: sidos[i] }))]
}
function seoPages(): Plugin {
let outDir = 'dist'
return {
@@ -96,8 +240,14 @@ function seoPages(): Plugin {
mkdirSync(dirname(file), { recursive: true })
writeFileSync(file, html)
}
const faqs = faqPages(site)
for (const f of faqs) {
const file = resolve(outDir, `${f.path}.html`)
mkdirSync(dirname(file), { recursive: true })
writeFileSync(file, f.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>`)
const urls = ['', ...faqs.map((f) => f.path), ...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`)
},
}