Compare commits

...
Author SHA1 Message Date
minaChoi aef8b4a022 fix: 로그인 창에 남은 '또는 아이디로' 구분선과 '아이디로 로그인해 주세요' 안내 빼기, 빈 오류 칸 여백 줄이기 2026-10-21 17:24:02 +09:00
minaChoi cc06d1fa6d docs: 10/21 배포 — 댓글 표 운영 DB 반영 확인 2026-10-21 17:13:34 +09:00
minaChoi 93e041bb91 feat: 10/21 회의 반영 — 공유 링크·로그인 없이 댓글·구글 로그인만, 히어로·오늘의 각 좋아요·댓글, 히어로 오늘/내일 스위치, 단풍 지도 65곳·3단계
- 공유: 이미지와 함께 고정 URL을 넘기고 링크도 클립보드에 복사
- 로그인 창은 구글만, 댓글은 로그인 없이 '동네 익명'(링크·전화번호 막기, IP당 하루 20개, 같은 IP만 지우기)
- 히어로·오늘의 각 카드에 좋아요·댓글 (PostType HERO·TODAY_GAK)
- 히어로 오늘/내일 스위치: 내일 구간별 날씨 점수·기온·최저최고·습도·1위 각, /v1/weather/today?day=tomorrow
- 단풍 지도: 단풍 그림 지도, 단풍 전·첫 단풍·절정, 단풍잎·은행잎, 명소 65곳(산림청 예측 + 가까운 지점 날짜)
- 하단 탭 바 불투명 (홈 바 자리로 글이 비치지 않게)
- 사람 글 동네 우선 정렬·내 글 목록, 내 각 '있는 각에서 불러오기'
- 댓글 표 user_id NULL 허용·ip_hash·region_name (운영 DB ALTER 필요)
2026-10-21 17:10:29 +09:00
minaChoi 14f24d1ab0 fix: 로그인 등 아래 창이 버벅이던 문제 — 해·구름 떨어짐과 둥둥을 다른 요소로 나눠 GPU로 넘기고(둘이 겹쳐 매 프레임 메인 스레드 작업), 낮엔 안 보이는 별 애니메이션 멈춤, 창이 열린 동안 뒤 화면 움직임 정지 2026-10-21 16:16:26 +09:00
minaChoi bfbf6da101 fix: 로그인이 만료된 채로 들어오면 로그인 창이 저절로 떠 화면이 막히던 문제 — 로그인 창은 사람이 한 동작(GET 아닌 요청)의 401에만 2026-10-21 14:55:31 +09:00
minaChoi dff03f6b28 fix: 홈 화면에 추가 — 설치창 호출이 실패해도 안내 창으로 넘어가게, 아이폰 안내에 공유·추가 버튼 모양 그림, 안드로이드는 안내를 연 사이 설치가 가능해지면 바로 '지금 설치하기' 버튼 2026-10-21 14:21:55 +09:00
minaChoi b5ad97585d fix: 내 각 가로 목록을 다른 캐러셀처럼 Embla(Rail)로 2026-10-21 13:59:06 +09:00
minaChoi ad5d1876ca fix: 히어로 공유 이미지 글자·아이콘·점수를 크게 — 시간대 이름 아래 날씨·기온, 각 이름 24px, 점수 62px 2026-10-21 13:58:31 +09:00
minaChoi b7d4df4d7a feat: 히어로 날씨 점수 옆 ? 버튼 — 누르면 비중 막대(칸 넓이=비중, 채운 만큼=얻은 점수)와 조건별 지금 값으로 점수 근거를 보여 주는 창 2026-10-21 13:55:15 +09:00
minaChoi 8f95519cb6 feat: 날씨 점수를 깐깐하게(96→92, 100점은 모든 조건이 완벽할 때만, 낮은 점수도 8/9로) — 히어로에 구간별 점수 근거(조건·비중·조건 점수·지금 값) weather_why 2026-10-21 13:55:15 +09:00
minaChoi b5c280ca3c feat: 히어로 공유 이미지를 하루 띠로 — 아침·낮·저녁·밤 네 줄(그 시간대 하늘·날씨·기온·날씨 점수·1등 각, 지금 표시), 1:1은 2×2 칸 2026-10-21 13:33:54 +09:00
minaChoi 8b487b7030 fix: 단풍 지도 산 이름을 눌러도 산 정보가 뜨게 2026-10-21 11:54:29 +09:00
minaChoi f182e46e87 fix: 단풍 지도를 남한만(백령도·제주·울릉·독도 포함) 정사각형 그림으로, 점마다 산 이름 표시(붙은 곳은 이름 방향 조정) 2026-10-21 11:44:10 +09:00
63 changed files with 2303 additions and 414 deletions

No files matched your search

+37 -2
View File
@@ -34,14 +34,41 @@
| [ ] | 단풍 지도·단풍 포스트, 새 각 — 야구각 문장(숫자 뺌)만 반영. 농구·배구·제철 수산물각 초안은 보류(scratchpad `new_gak_draft.json`) | 10/20 회의 | `backend/seed/index_definition.json`, `backend/seed/article.json` |
| [x] | 불쾌지수 항상 표시 | 10/20 회의 결정 (10/8도 결정) | `backend/services/hero_stats.py:70` |
| [x] | 나만의 각을 '이름+조건(기온·비·바람·미세먼지·습도·시간대 수치) 저장'으로 바꿈 — 섞기 방식 대체, 점수는 서버가 그 동네 예보로 계산(조건에서 멀수록 깎기), 받은 링크에 조건을 담아 친구 동네 점수로. 피드에 올려 좋아요는 아직 | 10/20 회의 결정 (조합 방식 대체) | `frontend/src/b/myGak.tsx` |
| [ ] | 비로그인 좋아요·댓글·공유 허용, 포스팅만 로그인. 중복 막기는 IP 기준(사용자 결정 10/20). 댓글 로그인 여부 확인 필요 | 10/20 회의 결정 | `backend/router/v1/reaction/reaction.py` |
| [ ] | 구글·토스 로그인, 앱인토스 정산 계좌 오류 토스 문의 | 10/20 회의 결정 | `backend/router/v1/auth/account.py` |
| [x] | 비로그인 좋아요·댓글·공유 허용, 포스팅만 로그인. 중복 막기는 IP 기준(사용자 결정 10/20). 댓글도 로그인 없이(10/21 회의 결정) — 아래 10/21 행으로 이어짐 | 10/20 회의 결정 | `backend/router/v1/reaction/reaction.py` |
| [ ] | 구글·토스 로그인, 앱인토스 정산 계좌 오류 토스 문의 — 구글 로그인 됨(`4e9b0ba`), 토스 문의 보냄(답변 대기). 남은 것은 아래 10/21 행 | 10/20 회의 결정 | `backend/router/v1/auth/account.py` |
| [ ] | 사람 글 사진 올리기 — 보여 주기(talk.image)는 됨, 올리기는 패키지 설치 확인 후(python-multipart·Pillow, 위치 정보 지우기) | 10/20 회의 결정 | `backend/router/v1/talk/talk.py`, `frontend/src/b/talk.tsx` |
| [ ] | 날씨 타로·오늘 날씨 코디 기획 (옷차림 [보류] 행과 합침). 타로는 운세 주제별 귀여운 각 이름으로 — 예: 애정 날씨 타로 → '다툼구름각' (사용자 10/21) | 10/20 회의 | |
| [ ] | **[결정 필요]** 피드 각 카드에서 빨래각 같은 평이한 각 빼기 — 피드 각 3개는 전체 순위로 골라 빨래각(priority 1)이 들어감. priority를 낮추면 히어로·각 탭 순위도 바뀜. priority 조정 vs 피드에선 is_fun 각 먼저 | 피드 순서 작업 중 발견 | `backend/seed/index_definition.json`, `backend/services/feed_service.py` |
| [ ] | 오늘의 각 카드 순위와 점수 순서가 다름(1위 83점, 2위 97점) — 순위에 중요도를 섞어서. 카드로 보이니 어색함 | 카드화 중 발견 | `backend/services/index_service.py` |
| [ ] | AdSense 게재 — 피드 포스트 사이 인피드 광고(포스트 틀, '광고' 표시, 몇 개마다 넣을지 결정). 게시자 ID(ca-pub-…) 받은 뒤 진행, `public/ads.txt`·`privacy.html` 광고 쿠키 고지·`docs/콘텐츠_설계서.md:11` '광고 없음' 수정 같이 | 사용자 결정 10/21, ID 없음 (https://adsense.google.com/start/) | `frontend/index.html`, `frontend/src/b/TodayPage.tsx` |
| [ ] | 테스트 실패 2건: `test_feed.py::test_feed_assembles_hero_stories_posts_and_bands`(각 57개, 기대 40 — 커밋 전 각 추가 영향), `test_weather_today.py:60`(날짜 따라 18시 아이콘 moon) | 피드 순서 작업 중 발견 | `backend/tests/` |
## 10/21 회의 (`docs/meetings/2026-10-21.md`)
| 상태 | 할 일 | 이유 | 관련 파일 |
|---|---|---|---|
| [x] | 공유에 링크 반드시 포함 — 공유창에 고정 URL을 url 칸으로 넘기고 링크도 클립보드에 복사(이미지만 받는 앱 대비) (금일 핵심) | 10/21 회의 결정 | `frontend/src/b/Sheets.tsx:564` |
| [x] | 히어로는 지금 형태 유지 + 좋아요·댓글 추가 (공유는 원래 있음). 서버에 히어로용 포스트(PostType.HERO)를 날마다 시도별로 만듦 | 10/21 회의 결정 | `frontend/src/b/TodayPage.tsx`, `backend/services/feed_service.py` |
| [x] | 오늘의 각부터 모든 카드에 좋아요·댓글·공유 — 오늘의 각 카드에 붙임(PostType.TODAY_GAK). 단풍 지도 카드는 아직 보내기만 (금일 핵심) | 10/21 회의 결정 | `frontend/src/b/TodayPage.tsx`, `backend/services/reaction_service.py` |
| [x] | 로그인은 포스팅할 때만, 댓글은 로그인 없이 — 이름 '마포구 익명'(사용자 결정 10/21), 링크·전화번호 막기, IP당 하루 20개, 지우기는 같은 IP (금일 핵심) | 10/21 회의 결정 | `backend/router/v1/reaction/reaction.py` |
| [x] | 웹 로그인 구글로 통일 — 로그인 창에서 아이디·비밀번호 칸 뺌. 서버 `/v1/auth/signup`·`/login`은 테스트 6개 파일이 계정 만들 때 써서 남김 (금일 핵심) | 10/21 회의 결정 | `frontend/src/b/Sheets.tsx`, `backend/router/v1/auth/account.py:25` |
| [ ] | 모바일에서 창이 닫히지 않는 오류 — 어느 창인지 확인 필요 (금일 핵심) | 10/21 회의 | `frontend/src/b/Sheets.tsx` |
| [x] | '내일 날씨' — 별도 카드 대신 히어로에 오늘/내일 스위치(사용자 결정 10/21). 내일은 시간대별 날씨 점수·기온, 최저·최고, 습도, 내일 1위 각 | 10/21 회의 결정 | `frontend/src/b/TodayPage.tsx` |
| [ ] | 넣을 수 있는 지역은 모두 날씨 페이지 추가 (지금 274개) | 10/21 회의 결정 | `backend/seed/region.csv` |
| [x] | 단풍 지도 UI 수정 — 단풍 그림 지도(Codex), 카카오처럼 단계 3개(단풍 전·첫 단풍·절정)와 단풍잎·은행잎 아이콘, 명소 65곳(단풍 39·은행 26) | 10/21 회의 후속, 사용자 10/21 | `frontend/src/b/foliageMap.tsx`, `frontend/seo/foliage_2026.json` |
| [ ] | 단풍 지도 '첫 단풍'은 절정 14일 전부터로 추정(발표에 시작일 없음). 예측 지점이 아닌 명소 32곳은 가장 가까운 예측 지점 날짜를 빌림(예: 남산공원·창덕궁 ← 수리산). 실제 관측과 다를 수 있음 | 사용자 결정 10/21 | `frontend/seo/foliage_2026.json` |
| [ ] | 토스 미니앱 최신 버전 재등록 — 웹이 바뀌면 자동 반영 안 됨 | 10/21 회의 | |
| [ ] | 유튜브 숏폼 자동화 진행 방안 협의 (김성경, 10/22) | 10/21 회의 | |
| [ ] | 인스타 운영 관리자 페이지(자동 게시 전 승인 메일) + 초기 이야기형 피드(각 100개·빨래각·소맥각·점수 산정법) | 10/21 회의 | |
| [ ] | 레이어 공유 아이디어 — 사용자 사진 위에 날씨각 정보를 얹어 공유(캐시워크식), 앱 기능으로 | 10/21 회의 (황 본부장 의견, 대표 방향) | |
| [ ] | iOS 개발자 계정 — 소장에게 기존 계정 확인, 어려우면 회사 계정 새로 만들기. 안드로이드 앱 계속 준비 | 10/21 회의 결정 | |
| [ ] | 앱인토스 정산 계좌 법인 계좌로 등록(대표) 후 토스 로그인 연동 가입 | 10/21 회의 결정 | |
| [ ] | '○○구 내일 날씨' 검색 태깅 — 스위치 뒤 내용은 눌러야 보여 구글이 읽는지 공식 문서로 확인 필요. 구 페이지(SEO)에 내일 기온·습도 넣는 안과 비교 | 10/21 회의 결정 | `backend/router/v1/seo/` |
| [x] | **운영 DB 반영(10/21 배포 때 init.sql로 적용 확인)** — 댓글 표 `user_id` NULL 허용, `ip_hash`·`region_name` 칸, `idx_comment_ip` (init.sql에 추가, 로컬만 적용). 배포 전에 운영에 ALTER 실행 (운영 영향, 확인 받고) | 익명 댓글 | `backend/postgres-init/init.sql` |
| [ ] | **[결정 필요]** 새 화면 문구 검토: '보냈어요. 링크도 복사해 뒀어요', '글쓰기는 로그인한 뒤에 할 수 있어요.', '오늘'/'내일', '내일 낮 날씨 점수', '내일은 ○○각!'/'내일은 쉬어 가요', '최저'/'최고'/'습도', 익명 이름 '마포구 익명', 단풍 지도 '단풍 전'/'첫 단풍'/'절정'/'단풍'/'은행', '가까운 예측 지점 날짜예요', '지금 절정 ○곳: … 외' | 화면 문구 규칙 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/Sheets.tsx` |
| [ ] | 익명 댓글이 링크·하루 제한에 걸려도 '댓글을 올리지 못했어요'만 나옴 — 이유별 안내 | 익명 댓글 작업 중 발견 | `frontend/src/b/Sheets.tsx` |
| [ ] | 매일 대표에게 진행 보고 (미완료 포함) | 10/21 회의 결정 | |
## 진행 순서
결정이 필요 없는 것부터, 사용자 눈에 틀린 정보가 보이는 것 → 기능 → 다듬기 순.
@@ -193,3 +220,11 @@
| [ ] | **[결정 필요]** 기존 각과 겹침 — 센치↔감성노래, 게임↔넷플릭스·집콕, 곱슬머리↔화장붕괴, 효도↔트로트, 셀카↔사진산책. 둘 다 둘지 합칠지 | 새 각 추가 중 발견 (10/20) | `backend/seed/index_definition.json` |
| [ ] | 감사각은 '어제보다 날씨가 크게 바뀐 날'을 못 봄 — 지금은 덥거나 춥거나 비 오면 높음. 전날 대비 기온 변화 요소를 계산에 넣을지 | 새 각 추가 중 발견 (10/20) | `backend/services/calc/index_calc.py` |
| [ ] | 테스트 2개가 날짜·시각에 따라 깨짐 — `test_feed` 스토리 수 40 고정(10월엔 계절 각이 늘어 다름, 각 추가 전 42·후 57), `test_weather_today` 7번째 칸이 시각에 따라 노을/달 | 새 각 추가 중 테스트에서 발견 (10/20) | `backend/tests/test_feed.py:64`, `backend/tests/test_weather_today.py` |
| [x] | 내 각 만들기 '있는 각에서 불러오기' 문구 검토 — 그대로 쓰기로 확정 (10/21) | 각 불러오기 카로셀 추가 (10/21) | `frontend/src/b/myGak.tsx` |
| [ ] | 내 각 만들기 숫자 칸이 좁아 세 자리(습도 100)가 잘림 — 불러온 각에 100이 자주 나옴 | 각 불러오기 카로셀 확인 중 발견 (10/21) | `frontend/src/b/myGak.tsx` `Num` |
| [ ] | 불러온 각 점수가 공식 각과 다름 — 더울수록·멀수록·바람 셀수록·요일 같은 규칙은 내 각 조건으로 비슷하게만 옮기거나 뺌(파티·게임·감사각은 비 조건만 남음) | 각 불러오기 카로셀 추가 (10/21) | `backend/services/calc/my_gak_calc.py` `preset` |
| [x] | 피드에 사람 글이 6개까지만 보임 — 20개를 받고 운영 포스트 3개마다 1개씩만 끼움(포스트 18개 → 6개). 나머지 14개와 다음 페이지는 안 보임 | 피드 정렬 점검 (10/21) | `frontend/src/b/TodayPage.tsx:419`, `frontend/src/b/talkState.ts` |
| [x] | 방금 쓴 글을 지워도 글쓰기 칸 아래에 남음 — 화면에만 들고 있는 내 글 목록(`mine`)에서 빼지 않음 | 피드 정렬 점검 (10/21) | `frontend/src/b/TodayPage.tsx:366`, `frontend/src/b/talk.tsx:201` |
| [x] | 내가 쓴 글 모아 보기 없음 → 내 정보 창에 '내 글' 목록(10/21) — 새로고침하면 위 고정이 풀리고 전국 최신순에 섞여 6개 안에 못 들면 못 찾음. 내 정보 창에 '내 글' 목록을 둘지 | 피드 정렬 점검 (10/21) | `backend/crud/talk_crud.py`, `frontend/src/b/Sheets.tsx:870` |
| [x] | 사람 글 정렬이 전국 최신순뿐 → 같은 시도 글 12시간 앞당김, 같은 사람 연속 금지(10/21) — 우리 동네 글 우선 없음, 한 사람이 하루 5개 쓰면 피드 사람 글 칸을 거의 다 차지함 | 피드 정렬 점검 (10/21) | `backend/crud/talk_crud.py:27` |
| [ ] | **[결정 필요]** 내 글 문구 검토 — '내 글', '아직 쓴 글이 없어요', '더 보기'를 확인받지 않고 넣음 | 피드 정렬 개선 (10/21) | `frontend/src/b/talk.tsx` `MyTalks` |
+3 -1
View File
@@ -357,7 +357,9 @@ class Comment(Base):
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
post_id: Mapped[int] = mapped_column(BigInteger)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
user_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), nullable=True)
ip_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
body: Mapped[str] = mapped_column(String(60))
like_count: Mapped[int] = mapped_column(Integer, default=0)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+2
View File
@@ -145,6 +145,8 @@ class PostType(CodeEnum):
DAY_TRIP = 13 # 당일치기: 1~2시간 거리 후보 도시 중 주말 날씨 1위 + 그곳 행사
MOON = 14 # 오늘 밤 달 (보름·삭이면 그 이야기)
UV = 15 # 오늘 낮 자외선 (아침·낮, '보통' 이상인 날만)
HERO = 16 # 히어로(오늘 날씨)의 좋아요·댓글 자리. 피드 목록엔 안 나온다
TODAY_GAK = 17 # 오늘의 각 카드의 좋아요·댓글 자리. 피드 목록엔 안 나온다
class EventKind(CodeEnum):
+13 -7
View File
@@ -1,7 +1,8 @@
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import delete, select, update
from sqlalchemy import delete, func, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
@@ -51,8 +52,9 @@ class ReactionCRUD:
stmt = stmt.where(Post.post_id < cursor)
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
async def comments(self, s: AsyncSession, post_id: int, cursor: Optional[int], limit: int) -> list[tuple[Comment, str, str, str, Optional[str]]]:
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).join(User, User.user_id == Comment.user_id).where(Comment.post_id == post_id, Comment.deleted.is_(False))
async def comments(self, s: AsyncSession, post_id: int, cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다."""
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(Comment.post_id == post_id, Comment.deleted.is_(False))
if cursor is not None:
stmt = stmt.where(Comment.comment_id > cursor)
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
@@ -65,16 +67,20 @@ class ReactionCRUD:
stmt = select(CommentLikeAnon.comment_id).where(CommentLikeAnon.ip_hash == ip_hash, CommentLikeAnon.comment_id.in_(comment_ids))
return set((await s.scalars(stmt)).all())
async def add_comment(self, s: AsyncSession, post_id: int, user_id: uuid.UUID, body: str) -> Comment:
c = Comment(post_id=post_id, user_id=user_id, body=body)
async def add_comment(self, s: AsyncSession, post_id: int, who: Liker, body: str, region_name: Optional[str]) -> Comment:
c = Comment(post_id=post_id, user_id=who.user_id, body=body) if who.user_id is not None else Comment(post_id=post_id, ip_hash=who.ip_hash, region_name=region_name, body=body)
s.add(c)
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + 1))
await s.flush()
return c
async def delete_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID) -> bool:
async def anon_comments_since(self, s: AsyncSession, ip_hash: str, since: datetime) -> int:
return await s.scalar(select(func.count()).select_from(Comment).where(Comment.user_id.is_(None), Comment.ip_hash == ip_hash, Comment.created_at >= since))
async def delete_comment(self, s: AsyncSession, comment_id: int, who: Liker) -> bool:
owner = Comment.user_id == who.user_id if who.user_id is not None else (Comment.user_id.is_(None) & (Comment.ip_hash == who.ip_hash))
res = await s.execute(
update(Comment).where(Comment.comment_id == comment_id, Comment.user_id == user_id, Comment.deleted.is_(False))
update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False))
.values(deleted=True).returning(Comment.post_id)
)
post_id = res.scalar()
+17 -4
View File
@@ -2,7 +2,7 @@ import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import delete, func, select, update
from sqlalchemy import BigInteger, case, cast, delete, func, select, tuple_, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
@@ -12,16 +12,29 @@ from crud.reaction_crud import toggle_like_row
class TalkCRUD:
async def page(self, s: AsyncSession, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Talk, User, Optional[str]]]:
"""최신 글부터. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다."""
async def page(
self, s: AsyncSession, viewer: Optional[uuid.UUID], sido: Optional[str], boost_sec: int, cursor: Optional[tuple[int, int]], limit: int
) -> list[tuple[Talk, User, Optional[str], int]]:
"""최신 글부터. 보는 사람과 같은 시도 글은 boost_sec 만큼 늦게 쓴 것처럼 앞에 둔다. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다.
cursor 는 앞 페이지 마지막 글의 (정렬 키, talk_id)."""
key = cast(func.floor(func.extract("epoch", Talk.created_at)), BigInteger)
if sido:
key = key + case((func.left(Talk.region_code, 2) == sido, boost_sec), else_=0)
stmt = (
select(Talk, User, Region.short_name)
select(Talk, User, Region.short_name, key)
.join(User, User.user_id == Talk.user_id)
.outerjoin(Region, Region.code == Talk.region_code)
.where(Talk.deleted.is_(False), Talk.hidden.is_(False), User.deleted.is_(False))
)
if viewer is not None:
stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)))
if cursor is not None:
stmt = stmt.where(tuple_(key, Talk.talk_id) < tuple_(*cursor))
return list((await s.execute(stmt.order_by(key.desc(), Talk.talk_id.desc()).limit(limit))).all())
async def mine(self, s: AsyncSession, user_id: uuid.UUID, cursor: Optional[int], limit: int) -> list[tuple[Talk, Optional[str]]]:
"""내가 쓴 글, 최신부터. 신고로 숨겨진 글도 쓴 사람에겐 보인다."""
stmt = select(Talk, Region.short_name).outerjoin(Region, Region.code == Talk.region_code).where(Talk.user_id == user_id, Talk.deleted.is_(False))
if cursor is not None:
stmt = stmt.where(Talk.talk_id < cursor)
return list((await s.execute(stmt.order_by(Talk.talk_id.desc()).limit(limit))).all())
+5
View File
@@ -237,6 +237,11 @@ CREATE TABLE IF NOT EXISTS public.comment (
deleted BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX IF NOT EXISTS idx_comment_post ON public.comment (post_id, created_at) WHERE deleted = FALSE;
-- 로그인 없이 쓴 댓글은 user_id 가 비고 IP 해시와 쓸 때의 동네 이름('마포구 익명'으로 보임)을 남긴다
ALTER TABLE public.comment ALTER COLUMN user_id DROP NOT NULL;
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS ip_hash VARCHAR(64) NULL;
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS region_name VARCHAR(20) NULL;
CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL;
-- 댓글 신고 (보류)
-- ALTER TABLE public.comment ADD COLUMN report_count INTEGER NOT NULL DEFAULT 0;
+5 -1
View File
@@ -22,11 +22,15 @@ async def get_feed(
err, feed = await service.feed(region)
if err is not ErrorType.SUCCESS:
return Res_Feed(result=error_info(err))
ids = [p.post_id for p in feed.posts]
pinned = [x for x in (feed.hero_post, feed.gak_post) if x is not None]
ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned]
counts = await reactions.counts(ids)
liked, saved = await reactions.marks(user, ids)
# 캐시된 피드는 모두에게 같으니, 로그인 안 한 사람의 좋아요 표시는 캐시 밖에서 IP 해시로 덧붙인다
anon_liked = await reactions.anon_liked(who.ip_hash, ids) if user is None else set()
for x in pinned:
x.like_count, x.comment_count = counts.get(x.post_id, (x.like_count, x.comment_count))
x.liked = x.post_id in (liked if user is not None else anon_liked)
for p in feed.posts:
p.like_count, p.comment_count = counts.get(p.post_id, (p.like_count, p.comment_count))
if user is not None:
+27
View File
@@ -136,6 +136,14 @@ class PostData(WebPacketProtocol):
saved: Optional[bool] = None
class PostReaction(WebPacketProtocol):
"""포스트 틀이 아닌 카드(히어로·오늘의 각)에 붙는 좋아요·댓글."""
post_id: int
like_count: int
comment_count: int
liked: Optional[bool] = None
class TopIndex(WebPacketProtocol):
index_id: int
code: str
@@ -156,6 +164,21 @@ class HeroStat(WebPacketProtocol):
tone: Literal["normal", "warn", "rain"] = Field(description="normal=기본, warn=조심(노랑), rain=비(파랑)")
class WeatherWhy(WebPacketProtocol):
label: str
weight: int = Field(description="비중 % (합 100)")
score: int = Field(description="이 조건 점수 0~100")
note: str = Field(description="지금 값 (예: 체감 19°, 편한 범위 18~24° 안)")
class HeroTomorrow(WebPacketProtocol):
"""히어로 '내일' 스위치. 3시간 칸 날씨는 /v1/weather/today?day=tomorrow 로 따로 받는다."""
day: date
weather_slots: dict[str, int] = Field(default_factory=dict, description="내일 구간별 날씨 점수 {morning·day·evening·night: 점수}")
weather_why: dict[str, list[WeatherWhy]] = Field(default_factory=dict, description="내일 구간별 날씨 점수 근거")
top1: Optional[TopIndex] = Field(default=None, description="내일 하루 점수로 1위인 각. score·summary 는 내일 값")
class Hero(WebPacketProtocol):
now_at: datetime
sky_mode: Literal["morning", "day", "sunset", "night"]
@@ -168,12 +191,14 @@ class Hero(WebPacketProtocol):
will_rain_2h: Optional[bool] = None
weather_score: Optional[int] = None
weather_slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}")
weather_why: dict[str, list[WeatherWhy]] = Field(default_factory=dict, description="구간별 날씨 점수 근거(조건·비중·조건 점수·지금 값). 키는 weather_slots 와 같다")
top1: Optional[TopIndex] = None
bubble: Optional[str] = None
moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달")
moon_pct: Optional[int] = Field(default=None, description="달에서 빛나는 면의 비율 0~100 (모양 그림용, 밝기 아님)")
stats: list[HeroStat] = Field(default_factory=list, description="히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저")
status: list[HeroStat] = Field(default_factory=list, description="히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)")
tomorrow: Optional[HeroTomorrow] = None
class BandEvent(WebPacketProtocol):
@@ -207,6 +232,8 @@ class Res_Feed(Res_WebPacketProtocol):
hero: Optional[Hero] = None
stories: list[TopIndex] = []
posts: list[PostData] = []
hero_post: Optional[PostReaction] = None
gak_post: Optional[PostReaction] = None
bands: Optional[Bands] = None
+9 -1
View File
@@ -7,7 +7,7 @@ from common.database.model.models import MyGak, User
from common.enums import ErrorType
from common.models.errors import error_info
from common.models.gmodel import Res_WebPacketProtocol
from router.v1.my_gak.protocol import MyGakData, MyGakRule, MyGakScore, Req_MyGak, Req_MyGakScore, Res_MyGak, Res_MyGakList, Res_MyGakScore
from router.v1.my_gak.protocol import MyGakData, MyGakPreset, MyGakRule, MyGakScore, Req_MyGak, Req_MyGakScore, Res_MyGak, Res_MyGakList, Res_MyGakPresets, Res_MyGakScore
from services.my_gak_service import MyGakService
router = APIRouter(prefix="/v1/my-gak", tags=["my-gak"])
@@ -33,6 +33,14 @@ async def add_my_gak(req: Req_MyGak, user: User = Depends(current_user), service
return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g))
@router.get("/presets", response_model=Res_MyGakPresets, response_model_exclude_none=True, summary="공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기)")
async def list_presets(service: MyGakService = Depends()) -> Res_MyGakPresets:
err, items = await service.presets()
if err is not ErrorType.SUCCESS:
return Res_MyGakPresets(result=error_info(err))
return Res_MyGakPresets(items=[MyGakPreset(**x) for x in items])
@router.post("/score", response_model=Res_MyGakScore, response_model_exclude_none=True, summary="조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)")
async def score_my_gak(req: Req_MyGakScore, service: MyGakService = Depends()) -> Res_MyGakScore:
err, got = await service.score(req.region_code, [r.model_dump(exclude_none=True) for r in req.rules])
+11
View File
@@ -37,6 +37,17 @@ class Req_MyGak(Req_WebPacketProtocol):
rule: MyGakRule
class MyGakPreset(WebPacketProtocol):
code: str
name: str
icon: str
rule: MyGakRule = Field(description="공식 각을 내 각 조건으로 비슷하게 옮긴 값. 점수는 공식 각과 다를 수 있음")
class Res_MyGakPresets(Res_WebPacketProtocol):
items: list[MyGakPreset] = []
class Res_MyGakList(Res_WebPacketProtocol):
items: list[MyGakData] = Field(default=[], description="내 각. 로그인하지 않았으면 비어 있음")
+3
View File
@@ -1,6 +1,8 @@
from datetime import date, datetime
from typing import Optional
from pydantic import Field
from common.enums import PostType
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
@@ -46,6 +48,7 @@ class Res_CommentList(Res_WebPacketProtocol):
class Req_Comment(Req_WebPacketProtocol):
body: str
region: Optional[str] = Field(None, description="로그인 없이 쓸 때 보고 있는 동네 코드. 이름이 '마포구 익명'으로 보인다")
class Res_Comment(Res_WebPacketProtocol):
+8 -6
View File
@@ -69,15 +69,17 @@ async def list_comments(
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자)")
async def add_comment(post_id: int = Path(...), req: Req_Comment = ..., user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_Comment:
err, v = await service.add_comment(post_id, user, req.body)
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개)")
async def add_comment(
post_id: int = Path(...), req: Req_Comment = ..., user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: ReactionService = Depends(),
) -> Res_Comment:
err, v = await service.add_comment(post_id, user, who, req.body, req.region)
return Res_Comment(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_Comment(comment=_comment(v))
@router.delete("/comment/{comment_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 댓글 지우기")
async def delete_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
return Res_WebPacketProtocol(result=error_info(await service.delete_comment(comment_id, user)))
@router.delete("/comment/{comment_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 댓글 지우기 (로그인 없이 쓴 댓글은 같은 IP 에서)")
async def delete_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
return Res_WebPacketProtocol(result=error_info(await service.delete_comment(comment_id, who)))
async def _clike(comment_id: int, who: Liker, on: bool, service: ReactionService) -> Res_CommentLike:
+16
View File
@@ -23,3 +23,19 @@ async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = P
if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
@router.get("/tomorrow/{sido}/{place}", response_class=HTMLResponse, summary="지역 내일 날씨 페이지: 정적 HTML 에 내일 예보를 채운다 (nginx 가 /tomorrow/... 를 넘김)")
async def get_tomorrow_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
err, html = await service.page(f"tomorrow/{sido}/{place}")
if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
@router.get("/tomorrow/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 내일 날씨 페이지")
async def get_tomorrow_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), gu: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
err, html = await service.page(f"tomorrow/{sido}/{place}/{gu}")
if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
+1 -1
View File
@@ -35,7 +35,7 @@ class Req_TalkReport(Req_WebPacketProtocol):
class Res_TalkList(Res_WebPacketProtocol):
talks: list[TalkData] = []
next_cursor: Optional[int] = None
next_cursor: Optional[str] = Field(None, description="다음 페이지를 받을 때 그대로 cursor 로 보낸다")
class Res_Talk(Res_WebPacketProtocol):
+19 -6
View File
@@ -14,7 +14,7 @@ from common.models.gmodel import Res_WebPacketProtocol
from common.utils.kma_time import KST
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData
from services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save
from services.talk_service import PAGE, TalkService, TalkView
from services.talk_service import TalkService, TalkView
router = APIRouter(prefix="/v1/talk", tags=["talk"])
@@ -27,15 +27,28 @@ def _data(v: TalkView) -> TalkData:
)
@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국, 최신순, 로그인 없이 보기)")
@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국 최신순, 보는 동네와 같은 시도 글은 앞으로, 같은 사람 글은 띄움, 로그인 없이 보기)")
async def list_talks(
cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: TalkService = Depends()
region: Optional[str] = Query(None, min_length=10, max_length=10, description="보는 사람의 구 행정코드"),
cursor: Optional[str] = Query(None, max_length=40),
user: Optional[User] = Depends(optional_user),
who: Liker = Depends(liker),
service: TalkService = Depends(),
) -> Res_TalkList:
err, views = await service.page(user, who.ip_hash, cursor)
err, views, nxt = await service.page(user, who.ip_hash, region, cursor)
if err is not ErrorType.SUCCESS:
return Res_TalkList(result=error_info(err))
talks = [_data(v) for v in views]
return Res_TalkList(talks=talks, next_cursor=talks[-1].talk_id if len(talks) == PAGE else None)
return Res_TalkList(talks=[_data(v) for v in views], next_cursor=nxt)
@router.get("/mine", response_model=Res_TalkList, response_model_exclude_none=True, summary="내가 쓴 글 (최신순)")
async def list_my_talks(cursor: Optional[str] = Query(None, max_length=20), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_TalkList:
if cursor is not None and not cursor.isdigit():
return Res_TalkList(result=error_info(ErrorType.INVALID_INPUT))
err, views, nxt = await service.mine(user, int(cursor) if cursor else None)
if err is not ErrorType.SUCCESS:
return Res_TalkList(result=error_info(err))
return Res_TalkList(talks=[_data(v) for v in views], next_cursor=str(nxt) if nxt else None)
@router.post("", response_model=Res_Talk, response_model_exclude_none=True, summary="동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)")
+1
View File
@@ -13,6 +13,7 @@ class WeatherSlot(WebPacketProtocol):
sky: Optional[Sky] = None
rain_type: Optional[RainType] = None
rain_prob: Optional[int] = None
humidity: Optional[int] = None
icon: str
tone: SlotTone
note: str
+11 -5
View File
@@ -1,8 +1,11 @@
from datetime import timedelta
from typing import Literal
from fastapi import APIRouter, Depends, Query
from common.enums import AirGrade, ErrorType, RainType, Sky
from common.models.errors import error_info
from common.utils.kma_time import KST
from common.utils.kma_time import KST, now_kst
from router.v1.weather.protocol import (
AirData,
CommuteData,
@@ -24,13 +27,16 @@ def _to_slot(s: Slot) -> WeatherSlot:
data = WeatherSlot(at=s.at, label=f"{s.at.astimezone(KST).hour}시", icon=s.icon, tone=s.tone, note=s.note)
if s.row is not None:
data.temp_c, data.feels_c = float(s.row.temp_c), float(s.row.feels_c)
data.sky, data.rain_type, data.rain_prob = Sky(s.row.sky), RainType(s.row.rain_type), s.row.rain_prob
data.sky, data.rain_type, data.rain_prob, data.humidity = Sky(s.row.sky), RainType(s.row.rain_type), s.row.rain_prob, s.row.humidity
return data
@router.get("/today", response_model=Res_WeatherToday, response_model_exclude_none=True, summary="오늘 3시간 칸 날씨")
async def get_weather_today(region: str = Query(..., description="구 행정코드"), service: WeatherService = Depends()) -> Res_WeatherToday:
err, today = await service.today(region)
@router.get("/today", response_model=Res_WeatherToday, response_model_exclude_none=True, summary="오늘(또는 내일) 3시간 칸 날씨")
async def get_weather_today(
region: str = Query(..., description="구 행정코드"), day: Literal["today", "tomorrow"] = Query("today", description="tomorrow 면 내일 칸"),
service: WeatherService = Depends(),
) -> Res_WeatherToday:
err, today = await service.today(region, now_kst().date() + timedelta(days=1) if day == "tomorrow" else None)
if err is not ErrorType.SUCCESS:
return Res_WeatherToday(result=error_info(err))
return Res_WeatherToday(
+66
View File
@@ -50,3 +50,69 @@ def definition(rule: MyRule) -> SimpleNamespace:
zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}] if rule.rain == "dry" else [],
windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
)
# 공식 각을 내 각 조건으로 옮길 때 쓰는 대표 시각(해 뜨고 지는 시각은 계절마다 달라 가운데 값으로)
_SUNRISE_HOUR, _SUNSET_HOUR = 6, 18
_TEMP_MIN, _TEMP_MAX = -20, 40
def _slot_of_hour(h: int) -> str:
h %= 24
if NIGHT_END_HOUR <= h < 11:
return "morning"
if 11 <= h < _SUNSET_HOUR - 2:
return "day"
if _SUNSET_HOUR - 2 <= h < _SUNSET_HOUR + 1:
return "evening"
return "night"
def _window_slots(windows: list[dict]) -> list[str]:
hours: set[int] = set()
for w in windows:
if "around" in w:
mid = _SUNRISE_HOUR if w["around"] == "sunrise" else _SUNSET_HOUR
hours.update(range(mid - w["hours"], mid + w["hours"]))
else:
hours.update(range(w["from"], w["to"]))
got = {_slot_of_hour(h) for h in hours}
return [s for s in SLOTS if s in got]
def _preset_temp(r: dict) -> Optional[list[float]]:
off = r.get("offset", 0)
t = r["type"]
if t == "range":
lo, hi = r["lo"] - off, r["hi"] - off
elif t == "higher":
lo, hi = r["full"] - off, _TEMP_MAX
elif t == "lower":
lo, hi = _TEMP_MIN, r["full"] - off
else:
return None # 범위에서 멀수록 좋은 규칙은 범위 하나로 옮길 수 없다
lo, hi = max(_TEMP_MIN, lo), min(_TEMP_MAX, hi)
return [_n(lo), _n(hi)] if lo < hi else None
_PRESET_HUMIDITY = {"higher": [60, 100], "lower": [0, 60]}
def preset(defn) -> dict:
"""공식 각을 내 각 조건(MyGakRule 모양)으로 비슷하게 옮긴다. 비중 0인 요소와 옮길 수 없는 규칙은 뺀다."""
r = defn.factor_rules
out: dict = {"slots": _window_slots(defn.windows) or list(SLOTS)}
if defn.weight_temp and (temp := _preset_temp(r["temp"])):
out["temp"] = temp
if defn.weight_rain:
out["rain"] = r["rain"]["dir"]
wind = r.get("wind", {})
if defn.weight_wind and wind.get("type") in ("calm", "moderate"):
out["wind_max"] = _n(max(1, wind["ok"])) if wind["type"] == "calm" else 5
air = r.get("air")
if defn.weight_air and not (air and air["full"] > air["zero"]):
out["air"] = "normal"
hum = r.get("humidity", {})
if defn.weight_humidity and hum.get("type") in ("range", "higher", "lower"):
out["humidity"] = [hum["lo"], hum["hi"]] if hum["type"] == "range" else _PRESET_HUMIDITY[hum["type"]]
return out
+36 -11
View File
@@ -11,7 +11,7 @@ from redis.exceptions import RedisError
from common.cache.lock import redis_lock
from common.cache.redis_client import REDIS
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Article, OpenMeteoHourly, Post, Region, WeatherHourly
from common.database.model.models import Article, IndexScore, OpenMeteoHourly, Post, Region, WeatherHourly
from common.enums import AirGrade, ArticleCategory, ErrorType, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType
from common.logger import LOG
from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, next_vilage_available, now_kst
@@ -21,8 +21,8 @@ from crud.region_crud import RegionCRUD
from crud.season_crud import SeasonCRUD
from crud.weather_crud import WeatherCRUD
from router.v1.feed.protocol import (
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HourCell, HoursSlide, PostData, Res_Feed, Row, RowsSlide, SunsetSlide,
PlanSlide, PlanStep, TopIndex, WeekDay, WeekGak, WeekSlide,
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HeroTomorrow, HourCell, HoursSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide,
PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide,
)
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
from services.air_service import pm10_grade, pm25_grade
@@ -63,7 +63,11 @@ LINEUP = [
(18, PostType.DAY_TRIP, RefType.NONE, None),
(19, PostType.MOON, RefType.NONE, None),
(20, PostType.UV, RefType.NONE, None),
(21, PostType.HERO, RefType.NONE, None),
(22, PostType.TODAY_GAK, RefType.NONE, None),
]
# 피드 목록 대신 히어로·오늘의 각 카드에 좋아요·댓글만 붙는 자리
_PINNED = {PostType.HERO: "hero_post", PostType.TODAY_GAK: "gak_post"}
# 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다.
NATIONAL_SCOPE = "00"
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON})
@@ -237,6 +241,28 @@ def _by_position(posts: list[Post]) -> list[Post]:
return list(out.values())
def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]:
"""내일 하루 점수로 1위인 각과 그 점수 (점수 × 중요도)."""
best = None
for i in board.items:
s = next((x for x in i.trend if x.score_date == day), None)
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
best = (i, s)
return best
def _hero_tomorrow(day: date, board: IndexBoard) -> HeroTomorrow:
best = _tomorrow_best(board, day)
top1 = None
if best is not None:
d, s = best[0].definition, best[1]
top1 = TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=s.score, rank=1, summary=s.summary)
return HeroTomorrow(
day=day, weather_slots=board.tomorrow_slots, top1=top1,
weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.tomorrow_why.items()},
)
def _top(i: IndexItem) -> TopIndex:
d = i.definition
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active,
@@ -369,8 +395,10 @@ class FeedService:
gak = sorted(board.ranked[:3], key=lambda i: _gak_key(i, now.hour)) if board else []
cards = []
pinned = {_PINNED[PostType(p.post_type)]: PostReaction(post_id=p.post_id, like_count=p.like_count, comment_count=p.comment_count)
for p in posts or [] if PostType(p.post_type) in _PINNED}
for p in posts or []:
if PostType(p.post_type) is PostType.GAK:
if PostType(p.post_type) is PostType.GAK or PostType(p.post_type) in _PINNED:
continue
data = self._render(p, ctx)
if data is not None:
@@ -384,7 +412,7 @@ class FeedService:
feed = Res_Feed(
region_code=region.code, region_name=region.name, slot=slot,
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])),
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"),
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"), **pinned,
bands=Bands(
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]],
@@ -443,10 +471,12 @@ class FeedService:
discomfort=cur.discomfort_index if cur else None, discomfort_label=discomfort_label(cur.discomfort_index) if cur else None,
rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None,
weather_score=board.weather_score if board else None, weather_slots=board.weather_slots if board else {},
weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.weather_why.items()} if board else {},
top1=_top(top) if top else None, bubble=bubble,
moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None,
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)],
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_status(x_in)],
tomorrow=_hero_tomorrow(now.date() + timedelta(days=1), board) if board else None,
)
@staticmethod
@@ -688,13 +718,8 @@ class FeedService:
return PostData(**base, title=plan.title, icon=icon, caption=caption, slides=slides, share_messages=[share])
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
tomorrow = c.now.date() + timedelta(days=1)
rows = [Row(label=x.label, value=x.text) for x in c.now_w.commute]
best = None
for i in c.board.items if c.board else []:
s = next((x for x in i.trend if x.score_date == tomorrow), None)
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
best = (i, s)
best = _tomorrow_best(c.board, c.now.date() + timedelta(days=1)) if c.board else None
if best is not None:
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
caption = _temp_change(c.today, c.tomorrow) or "출근 전에 한 번 더 확인해 주세요."
+41 -6
View File
@@ -40,6 +40,26 @@ WEATHER_SCORE_DEF = SimpleNamespace(
},
zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
)
WEATHER_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "sun": "햇볕"}
def strict_weather(raw: int) -> int:
"""날씨 점수는 높을수록 깐깐하게: 90점까지는 8/9, 그 위는 두 배로 깎아 100점은 모든 조건이 완벽할 때만 (96 → 92)."""
return round(raw * 8 / 9) if raw <= 90 else round(80 + (raw - 90) * 2)
@dataclass
class WeatherWhy:
label: str
weight: int
score: int
note: str
def weather_why(r: Result) -> list[WeatherWhy]:
"""날씨 점수를 이룬 조건들. 비중 큰 것부터."""
axes = sorted((a for a in WEATHER_AXIS_NAME if getattr(WEATHER_SCORE_DEF, f"weight_{a}")), key=lambda a: -getattr(WEATHER_SCORE_DEF, f"weight_{a}"))
return [WeatherWhy(label=WEATHER_AXIS_NAME[a], weight=getattr(WEATHER_SCORE_DEF, f"weight_{a}"), score=r.factors[a], note=r.notes.get(a, "")) for a in axes]
SEASONS = ("겨울", "봄", "여름", "가을")
@@ -83,6 +103,9 @@ class IndexBoard:
weather_score: Optional[int]
items: list[IndexItem]
weather_slots: dict[str, int] = field(default_factory=dict)
weather_why: dict[str, list[WeatherWhy]] = field(default_factory=dict)
tomorrow_slots: dict[str, int] = field(default_factory=dict) # 내일 아침·낮·저녁·밤 날씨 점수
tomorrow_why: dict[str, list[WeatherWhy]] = field(default_factory=dict)
@property
def ranked(self) -> list[IndexItem]:
@@ -187,7 +210,7 @@ def shown_slot(key: str) -> str:
return "night" if key == EARLY else key
def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
def _shown_parts(parts: dict, cur: str) -> dict:
"""구간 점수를 아침·낮·저녁·밤 순으로. 0~5시면 밤은 전날 밤 구간을 쓴다."""
shown = {shown_slot(k): v for k, v in parts.items() if k != ("night" if cur == EARLY else EARLY)}
return {k: shown[k] for k in SLOTS if k in shown}
@@ -305,10 +328,12 @@ class IndexService:
if region is None:
return ErrorType.NOT_FOUND, None
now = now_kst()
err, weather_parts = await self.ensure(region, now)
err, weather_days = await self.ensure(region, now)
if err is not ErrorType.SUCCESS:
return err, None
today = now.date()
weather_parts = weather_days[today]
tomorrow_parts = weather_days.get(today + timedelta(days=1), {})
cur = current_slot(now, sun_times(today, float(region.lat), float(region.lon)).sunset_at)
slots = slot_days(today)
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
@@ -362,7 +387,11 @@ class IndexService:
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key], active=False, in_season=False,
))
return ErrorType.SUCCESS, IndexBoard(
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
region=region, day=today, weather_score=weather_parts[cur].score if cur in weather_parts else None, items=items,
weather_slots=_shown_parts({k: r.score for k, r in weather_parts.items()}, cur),
weather_why=_shown_parts({k: weather_why(r) for k, r in weather_parts.items()}, cur),
tomorrow_slots=_shown_parts({k: r.score for k, r in tomorrow_parts.items()}, ""),
tomorrow_why=_shown_parts({k: weather_why(r) for k, r in tomorrow_parts.items()}, ""),
)
async def custom(self, region_code: str, defns: list) -> tuple[ErrorType, Optional[tuple[str, list[dict[str, Result]]]]]:
@@ -395,8 +424,8 @@ class IndexService:
out.append({shown_slot(k): r for k, r in parts.items() if k != ("night" if cur == EARLY else EARLY)})
return ErrorType.SUCCESS, (shown_slot(cur), out)
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[date, dict[str, Result]]]]:
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘·내일 구간별 날씨 점수도 같이 낸다."""
_, _, _, warnings, ultra = await asyncio.gather(
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
self.warning_service.for_region(region, now), ultra_hours(region, now, wait=True),
@@ -426,7 +455,13 @@ class IndexService:
)
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx)
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()}
tomorrow = today + timedelta(days=1)
tomorrow_ctx = Context(day=tomorrow, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, tomorrow), **base_ctx)
tomorrow_sunset = sun_times(tomorrow, float(region.lat), float(region.lon)).sunset_at
weather_parts = {
today: {k: replace(r, score=strict_weather(r.score)) for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()},
tomorrow: {k: replace(r, score=strict_weather(r.score)) for k, r in slot_results(WEATHER_SCORE_DEF, tomorrow, region, by_at, by_om, tomorrow_ctx, tomorrow_sunset).items()},
}
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
inputs_at = max(issued, air.measured_at) if air else issued
+7 -1
View File
@@ -8,7 +8,7 @@ from common.database.model.models import MyGak, User
from common.enums import ErrorType
from crud.my_gak_crud import MyGakCRUD
from services.calc.day_slot import SLOTS
from services.calc.my_gak_calc import MyRule, axes, definition
from services.calc.my_gak_calc import MyRule, axes, definition, preset
from services.index_service import IndexService
# 한 사람이 만들 수 있는 내 각 수
@@ -57,6 +57,12 @@ class MyGakService:
return err
return ErrorType.SUCCESS if found else ErrorType.NOT_FOUND
async def presets(self) -> tuple[ErrorType, list[dict]]:
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.crud.definitions(s))
if err is not ErrorType.SUCCESS:
return err, []
return err, [{"code": d.code, "name": d.name, "icon": d.icon, "rule": preset(d)} for d in defs]
async def score(self, region_code: str, rules: list[dict]) -> tuple[ErrorType, Optional[tuple[str, list[dict]]]]:
"""조건마다 그 동네 오늘 시간대별 점수. 지금 시간대를 골랐으면 그 점수, 아니면 고른 시간대 중 가장 좋은 점수."""
mine = [my_rule(r) for r in rules]
+42 -11
View File
@@ -8,10 +8,16 @@ from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Comment, Post, User
from common.enums import ErrorType
from common.liker import Liker
from common.utils.kma_time import kst_midnight, now_kst
from crud.feed_crud import FeedCRUD
from crud.reaction_crud import ReactionCRUD
from crud.region_crud import RegionCRUD
from services.talk_service import _LINK, _PHONE
COMMENT_MAX = 60
# 로그인 없이 IP 하나가 하루에 쓸 수 있는 댓글 수
ANON_DAILY_MAX = 20
ANON_CHARACTER, ANON_COLOR = "rabbit", "orange"
PAGE = 20
@@ -33,8 +39,8 @@ class SavedView:
class ReactionService:
def __init__(self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD)) -> None:
self.crud, self.feed = crud, feed
def __init__(self, crud: ReactionCRUD = Depends(ReactionCRUD), feed: FeedCRUD = Depends(FeedCRUD), regions: RegionCRUD = Depends(RegionCRUD)) -> None:
self.crud, self.feed, self.regions = crud, feed, regions
async def _post_exists(self, post_id: int) -> ErrorType:
err, post = await DB_SESSION_MNG.execute_lambda(lambda s: self.feed.get(s, post_id))
@@ -78,6 +84,13 @@ class ReactionService:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.saved_posts(s, user.user_id, cursor, PAGE))
return err, [SavedView(post=p, saved_at=ps.created_at) for p, ps in rows or []]
@staticmethod
def _view(c: Comment, nickname: Optional[str], character: Optional[str], color: Optional[str], mood: Optional[str], liked: bool, who: Liker) -> CommentView:
if c.user_id is None:
mine = who.user_id is None and c.ip_hash == who.ip_hash
return CommentView(comment=c, nickname=f"{c.region_name} 익명" if c.region_name else "익명", character=ANON_CHARACTER, color=ANON_COLOR, mood=None, liked=liked, mine=mine)
return CommentView(comment=c, nickname=nickname or "", character=character or ANON_CHARACTER, color=color or ANON_COLOR, mood=mood, liked=liked, mine=c.user_id == who.user_id)
async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, cursor, PAGE))
if err is not ErrorType.SUCCESS:
@@ -88,23 +101,41 @@ class ReactionService:
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked_comments(s, user.user_id, ids))
elif rows:
_, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked_comments(s, ip_hash, ids))
return ErrorType.SUCCESS, [
CommentView(comment=c, nickname=n, character=ch, color=co, mood=mo, liked=c.comment_id in (liked or set()), mine=user is not None and c.user_id == user.user_id)
for c, n, ch, co, mo in rows
]
who = Liker(user_id=user.user_id if user else None, ip_hash=ip_hash)
return ErrorType.SUCCESS, [self._view(c, n, ch, co, mo, c.comment_id in (liked or set()), who) for c, n, ch, co, mo in rows]
async def add_comment(self, post_id: int, user: User, body: str) -> tuple[ErrorType, Optional[CommentView]]:
async def add_comment(self, post_id: int, user: Optional[User], who: Liker, body: str, region_code: Optional[str] = None) -> tuple[ErrorType, Optional[CommentView]]:
"""로그인 없이도 쓴다. 그때는 링크·전화번호를 막고 IP 하나에 하루 ANON_DAILY_MAX 개까지, 이름은 쓸 때 동네로 '마포구 익명'."""
body = body.strip()
if not body or len(body) > COMMENT_MAX:
return ErrorType.INVALID_INPUT, None
err = await self._post_exists(post_id)
if err is not ErrorType.SUCCESS:
return err, None
err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, post_id, user.user_id, body))
return err, (CommentView(comment=c, nickname=user.nickname, character=user.character, color=user.color, mood=user.mood, liked=False, mine=True) if c else None)
region_name = None
if user is None:
if _LINK.search(body) or _PHONE.search(body):
return ErrorType.LINK_NOT_ALLOWED, None
today = kst_midnight(now_kst().date())
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_comments_since(s, who.ip_hash, today))
if err is not ErrorType.SUCCESS:
return err, None
if n >= ANON_DAILY_MAX:
return ErrorType.DAILY_LIMIT, None
if region_code:
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
if err is not ErrorType.SUCCESS:
return err, None
region_name = region.short_name if region else None
err, c = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add_comment(s, post_id, who, body, region_name))
if c is None:
return err, None
if user is None:
return err, self._view(c, None, None, None, None, False, who)
return err, self._view(c, user.nickname, user.character, user.color, user.mood, False, who)
async def delete_comment(self, comment_id: int, user: User) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, user.user_id))
async def delete_comment(self, comment_id: int, who: Liker) -> ErrorType:
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete_comment(s, comment_id, who))
if err is not ErrorType.SUCCESS:
return err
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
+24 -9
View File
@@ -21,7 +21,7 @@ from services.feed_service import FeedService
_CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"')
_NAME = re.compile(r"<h1>(.+?) 오늘 날씨")
_NAME = re.compile(r"<h1>(.+?) (?:오늘|내일) 날씨")
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
@@ -61,15 +61,27 @@ def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[da
return " ".join(parts)
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
line = today_line(feed, rows, sunset_at)
def tomorrow_line(rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
"""내일 페이지 한 줄: 내일 하루 예보와 해 지는 시각."""
parts = [day_summary(rows)] if rows else []
if parts and sunset_at:
parts.append(f"해 지는 시각 {_clock(sunset_at)}.")
return " ".join(parts)
def _put(template: str, line: str, extra: str = "") -> str:
"""설명 메타와 본문 h1 바로 아래에 한 줄을 넣는다."""
if not line:
return template
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{extra}", html, count=1)
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
top = feed.bands.top5 if feed.bands else []
ranks = f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{ranks}", html, count=1)
return _put(template, today_line(feed, rows, sunset_at), ranks)
class SeoService:
@@ -98,9 +110,12 @@ class SeoService:
LOG.error(f"[seo] feed {code}: {err}")
return ErrorType.SUCCESS, template
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code))
today = now_kst().date()
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at if region else None
start = kst_midnight(today)
ahead = path.startswith("tomorrow/")
day = now_kst().date() + timedelta(days=1 if ahead else 0)
sunset_at = sun_times(day, float(region.lat), float(region.lon)).sunset_at if region else None
start = kst_midnight(day)
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
if ahead:
return ErrorType.SUCCESS, _put(template, tomorrow_line(rows or [], sunset_at))
name = _NAME.search(template)
return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
+49 -13
View File
@@ -20,6 +20,8 @@ DAILY_MAX = 5
# 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다
HIDE_AT = 3
PAGE = 20
# 보는 사람과 같은 시도에서 쓴 글은 이만큼 늦게 쓴 글처럼 앞에 둔다
LOCAL_BOOST = timedelta(hours=12)
# 링크(http, www, 도메인 꼴)와 전화번호(010-1234-5678, 01012345678, 02-123-4567)
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b", re.I)
@@ -38,6 +40,22 @@ def weather_line(row: Optional[WeatherHourly]) -> Optional[str]:
return f"{round(float(row.temp_c))}° {word}".strip()
def spread_authors(views: list["TalkView"]) -> list["TalkView"]:
"""같은 사람 글이 붙으면 뒤에서 다른 사람 글을 당겨 끼운다."""
out = list(views)
for i in range(1, len(out)):
if out[i].author.user_id == out[i - 1].author.user_id:
j = next((k for k in range(i + 1, len(out)) if out[k].author.user_id != out[i - 1].author.user_id), None)
if j is not None:
out.insert(i, out.pop(j))
return out
def parse_cursor(cursor: str) -> Optional[tuple[int, int]]:
key, _, talk_id = cursor.partition("_")
return (int(key), int(talk_id)) if key.lstrip("-").isdigit() and talk_id.isdigit() else None
@dataclass
class TalkView:
talk: Talk
@@ -51,21 +69,39 @@ class TalkService:
def __init__(self, crud: TalkCRUD = Depends(TalkCRUD), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)) -> None:
self.crud, self.regions, self.weather = crud, regions, weather
async def page(self, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[TalkView]]:
async def page(self, user: Optional[User], ip_hash: str, region_code: Optional[str], cursor: Optional[str]) -> tuple[ErrorType, list[TalkView], Optional[str]]:
"""한 페이지와 다음 페이지 cursor. 같은 사람 글은 페이지 안에서 떨어뜨린다."""
after = parse_cursor(cursor) if cursor else None
if cursor and after is None:
return ErrorType.INVALID_INPUT, [], None
viewer = user.user_id if user else None
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, cursor, PAGE))
sido = region_code[:2] if region_code else None
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, sido, int(LOCAL_BOOST.total_seconds()), after, PAGE))
if err is not ErrorType.SUCCESS:
return err, []
liked: set[int] = set()
if rows:
ids = [t.talk_id for t, *_ in rows]
if user is not None:
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, ids))
else:
err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked(s, ip_hash, ids))
if err is not ErrorType.SUCCESS:
return err, []
return ErrorType.SUCCESS, [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name in rows]
return err, [], None
err, liked = await self._liked(user, ip_hash, [t.talk_id for t, *_ in rows])
if err is not ErrorType.SUCCESS:
return err, [], None
views = [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name, _ in rows]
last = rows[-1] if len(rows) == PAGE else None
return ErrorType.SUCCESS, spread_authors(views), f"{last[3]}_{last[0].talk_id}" if last else None
async def mine(self, user: User, cursor: Optional[int]) -> tuple[ErrorType, list[TalkView], Optional[int]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.mine(s, user.user_id, cursor, PAGE))
if err is not ErrorType.SUCCESS:
return err, [], None
err, liked = await self._liked(user, "", [t.talk_id for t, _ in rows])
if err is not ErrorType.SUCCESS:
return err, [], None
views = [TalkView(talk=t, author=user, region_name=name, liked=t.talk_id in liked, mine=True) for t, name in rows]
return ErrorType.SUCCESS, views, rows[-1][0].talk_id if len(rows) == PAGE else None
async def _liked(self, user: Optional[User], ip_hash: str, ids: list[int]) -> tuple[ErrorType, set[int]]:
if not ids:
return ErrorType.SUCCESS, set()
if user is not None:
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, ids))
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.anon_liked(s, ip_hash, ids))
async def _weather_now(self, region_code: str) -> Optional[str]:
"""지금 시각에 가장 가까운 예보 한 칸. 못 읽으면 날씨 없이 쓴다."""
+62
View File
@@ -85,3 +85,65 @@ async def test_anon_talk_like():
assert next(x for x in talks if x["talk_id"] == talk_id)["liked"] is False
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
@pytest.mark.anyio
async def test_anon_comment_shows_region_and_only_same_ip_deletes(offline):
async with client() as c:
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
url = f"/v1/reaction/post/{post_id}/comment"
made = (await c.post(url, headers=IP_A, json={"body": " 우산 챙겨요 ", "region": REGION})).json()["comment"]
assert made["body"] == "우산 챙겨요" and made["nickname"] == "마포구 익명" and made["mine"] is True
assert (await c.post(url, headers=IP_A, json={"body": "www.example.com 보세요"})).json()["result"]["desc"] == "LINK_NOT_ALLOWED"
no_region = (await c.post(url, headers=IP_A, json={"body": "안녕"})).json()["comment"]
assert no_region["nickname"] == "익명"
listed = (await c.get(f"{url}/list", headers=IP_B)).json()["comments"]
assert [(x["nickname"], x["mine"]) for x in listed] == [("마포구 익명", False), ("익명", False)]
assert next(x for x in (await c.get(f"{url}/list", headers=IP_A)).json()["comments"] if x["comment_id"] == made["comment_id"])["mine"] is True
h = await _login(c, "anon_cmt_01")
delete = f"/v1/reaction/comment/{made['comment_id']}"
assert (await c.delete(delete, headers=IP_B)).json()["result"]["desc"] == "NOT_FOUND"
assert (await c.delete(delete, headers={**h, **IP_A})).json()["result"]["desc"] == "NOT_FOUND"
assert (await c.delete(delete, headers=IP_A)).json()["result"]["success"] is True
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
assert next(x for x in feed["posts"] if x["post_id"] == post_id)["comment_count"] == 1
@pytest.mark.anyio
async def test_anon_comment_daily_limit_per_ip(offline):
async with client() as c:
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
url = f"/v1/reaction/post/{post_id}/comment"
ip = {"X-Forwarded-For": "203.0.113.40"}
for i in range(20):
assert (await c.post(url, headers=ip, json={"body": f"댓글{i}"})).json()["result"]["success"] is True
assert (await c.post(url, headers=ip, json={"body": "하나 더"})).json()["result"]["desc"] == "DAILY_LIMIT"
assert (await c.post(url, headers=IP_B, json={"body": "다른 사람"})).json()["result"]["success"] is True
h = await _login(c, "anon_cmt_02")
assert (await c.post(url, headers={**h, **ip}, json={"body": "로그인하면 따로"})).json()["result"]["success"] is True
@pytest.mark.anyio
async def test_hero_and_today_gak_take_likes_and_comments(offline):
async with client() as c:
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
hero, gak = feed["hero_post"]["post_id"], feed["gak_post"]["post_id"]
assert hero != gak and {hero, gak}.isdisjoint(p["post_id"] for p in feed["posts"])
assert (await c.post(f"/v1/reaction/post/{hero}/like", headers=IP_A)).json()["like_count"] == 1
assert (await c.post(f"/v1/reaction/post/{gak}/comment", headers=IP_A, json={"body": "좋다"})).json()["result"]["success"] is True
mine = (await c.get("/v1/feed", params={"region": REGION}, headers=IP_A)).json()
assert mine["hero_post"] == {"post_id": hero, "like_count": 1, "comment_count": 0, "liked": True}
assert mine["gak_post"] == {"post_id": gak, "like_count": 0, "comment_count": 1, "liked": False}
assert (await c.get("/v1/feed", params={"region": REGION}, headers=IP_B)).json()["hero_post"]["liked"] is False
@pytest.mark.anyio
async def test_hero_tomorrow_and_tomorrow_slots(offline):
async with client() as c:
hero = (await c.get("/v1/feed", params={"region": REGION})).json()["hero"]
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
assert res["day"] == hero["tomorrow"]["day"]
+3 -2
View File
@@ -50,11 +50,12 @@ async def test_signup_rejects_bad_input():
@pytest.mark.anyio
async def test_comment_requires_login_and_reactions_update_feed(offline):
async def test_comment_without_login_is_anonymous_and_reactions_update_feed(offline):
async with client() as c:
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
post_id = feed["posts"][0]["post_id"]
assert (await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "안녕"})).status_code == 401
anon = (await c.post(f"/v1/reaction/post/{feed['posts'][1]['post_id']}/comment", json={"body": "안녕"})).json()
assert anon["result"]["success"] is True and anon["comment"]["nickname"] == "익명"
token = (await _signup(c))["access_token"]
h = {"Authorization": f"Bearer {token}"}
+7 -4
View File
@@ -14,9 +14,12 @@ from common.utils.kma_time import kst_midnight, now_kst
from crud.region_crud import RegionCRUD
from crud.weather_crud import WeatherCRUD
from router.router import app
from services.calc.index_calc import rank_score
from services.calc.index_calc import AXES, Result, rank_score
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, season_of, slot_days, slot_label, windows_for
_RESULT_50 = Result(score=50, factors={a: 50 for a in AXES}, notes={}, zero_reason=None, summary="")
_WEATHER_50 = {k: _RESULT_50 for k in ("morning", "day", "evening", "night", "early")}
REGION = "1141000000"
@@ -142,7 +145,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))]
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): _WEATHER_50})))
_, board = await service.board(REGION)
view = [(i.definition.code, i.active, i.in_season, i.season) for i in board.items]
# 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만
@@ -162,7 +165,7 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): _WEATHER_50})))
err, board = await service.board(REGION)
assert err is ErrorType.SUCCESS
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
@@ -179,7 +182,7 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)]
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {k: 50 for k in every})))
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): {k: _RESULT_50 for k in every}})))
monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"]))
_, board = await service.board(REGION)
ranks = {i.definition.code: i.slot_ranks for i in board.items}
+23
View File
@@ -340,3 +340,26 @@ def test_umbrella_lost_needs_rain_that_stopped():
assert evaluate(defn, [[_h(13), _h(14)]], after_rain).score >= 80
assert evaluate(defn, [[_h(13), _h(14)]], CTX).zero_reason == "앞서 내린 비가 없어 0점"
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
def test_weather_score_is_strict_near_top():
"""좋은 날(96)도 92 수준, 100점은 모든 조건이 완벽할 때만. 낮은 점수도 조금씩 내려간다."""
from services.index_service import strict_weather
assert strict_weather(100) == 100
assert strict_weather(96) == 92
assert strict_weather(99) < 100
assert strict_weather(75) < 75
scores = [strict_weather(s) for s in range(101)]
assert scores == sorted(scores)
def test_weather_why_lists_every_condition_heaviest_first():
from services.index_service import WEATHER_SCORE_DEF, weather_why
ctx = Context(day=date(2026, 10, 2), is_holiday=False, pm25=12, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
r = evaluate(WEATHER_SCORE_DEF, [[_h(h, feels=19.0, prob=0, wind=2.0, hum=55, sunshine_ratio=0.9) for h in range(9, 22)]], ctx)
why = weather_why(r)
assert [w.label for w in why] == ["기온", "비", "햇볕", "바람", "습도", "미세먼지"]
assert sum(w.weight for w in why) == 100
assert why[0].note.startswith("체감 19°")
+34 -1
View File
@@ -1,12 +1,16 @@
import json
import os
from datetime import date
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
from common.enums import RainType, Sky
from router.router import app
from router.v1.my_gak.protocol import MyGakRule
from services.calc.index_calc import Context, Hour, evaluate
from services.calc.my_gak_calc import MyRule, axes, definition
from services.calc.my_gak_calc import MyRule, axes, definition, preset
from services.my_gak_service import MAX_PER_USER, gak_name
RULE = {"temp": [15, 25], "rain": "dry", "slots": ["evening", "night"]}
@@ -84,3 +88,32 @@ async def test_rejects_bad_rules():
assert (await bad({"temp": [25, 15]})).status_code == 422
assert (await bad({"temp": [15, 25], "slots": []})).status_code == 422
assert (await bad({"humidity": [10, 120]})).status_code == 422
def _defn(rules: dict, windows: list[dict], **weights) -> SimpleNamespace:
w = {"temp": 30, "rain": 30, "wind": 0, "humidity": 0, "air": 0} | weights
return SimpleNamespace(factor_rules=rules, windows=windows, **{f"weight_{k}": v for k, v in w.items()})
def test_preset_copies_rules_that_fit_and_drops_the_rest():
base = {"rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 3, "limit": 10}, "humidity": {"type": "range", "lo": 30, "hi": 60}}
p = preset(_defn(base | {"temp": {"type": "range", "lo": 18, "hi": 24}}, [{"from": 18, "to": 24}], wind=15, humidity=10, air=10))
assert p == {"slots": ["evening", "night"], "temp": [18, 24], "rain": "dry", "wind_max": 3, "air": "normal", "humidity": [30, 60]}
# 더울수록·추울수록은 만점 기온부터 끝까지, 산 정상 보정은 되돌린다
assert preset(_defn(base | {"temp": {"type": "higher", "zero": 16, "full": 27}}, [{"from": 9, "to": 11}]))["temp"] == [27, 40]
assert preset(_defn(base | {"temp": {"type": "lower", "zero": 10, "full": -5}}, [{"from": 9, "to": 11}]))["temp"] == [-20, -5]
assert preset(_defn(base | {"temp": {"type": "range", "lo": 10, "hi": 20, "offset": -4}}, [{"from": 9, "to": 11}]))["temp"] == [14, 24]
# 범위에서 멀수록 좋은 기온, 탁할수록 좋은 미세먼지, 비중 0인 바람은 옮기지 않는다
p = preset(_defn(base | {"temp": {"type": "away", "lo": 15, "hi": 24}, "air": {"zero": 15, "full": 75}}, [{"around": "sunset", "hours": 1}], air=20))
assert p == {"slots": ["evening"], "rain": "dry"}
@pytest.mark.anyio
async def test_presets_cover_every_gak_with_valid_rules():
async with client() as c:
body = (await c.get("/v1/my-gak/presets")).json()
with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), "seed", "index_definition.json"), encoding="utf-8") as f:
seed = json.load(f)
assert [x["code"] for x in body["items"]] == [x["code"] for x in sorted(seed, key=lambda x: x["sort_order"])]
for x in body["items"]:
MyGakRule(**x["rule"])
+23 -1
View File
@@ -7,7 +7,7 @@ from common.utils.kma_time import KST
from common.database.model.models import WeatherHourly
from router.router import app
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
from services.seo_service import SeoService, day_summary, fill, today_line
from services.seo_service import SeoService, day_summary, fill, today_line, tomorrow_line
REGION = "1114000000"
TEMPLATE = (
@@ -76,3 +76,25 @@ async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
page = await client.get("/v1/seo/today/gyeonggi/seongnam/bundang")
assert page.status_code == 200 and "지금 20°" in page.text
def test_tomorrow_line_has_day_and_sunset():
line = tomorrow_line([_hour(12, 19.5, prob=10)], datetime(2026, 10, 15, 17, 51, tzinfo=KST))
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 해 지는 시각 오후 5시 51분."
assert tomorrow_line([], datetime(2026, 10, 15, 17, 51, tzinfo=KST)) == ""
@pytest.mark.anyio
async def test_tomorrow_page_fills_tomorrow_forecast(offline, monkeypatch):
tmpl = TEMPLATE.replace("오늘 날씨", "내일 날씨")
async def template(self, path):
return tmpl if path == "tomorrow/gyeonggi/seongnam/bundang" else None
monkeypatch.setattr(SeoService, "template", template)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
page = await client.get("/v1/seo/tomorrow/gyeonggi/seongnam/bundang")
missing = await client.get("/v1/seo/tomorrow/seoul/nowhere")
assert page.status_code == 200 and "<h1>서울 중구 내일 날씨, 뭐 할까?</h1><p>최저 " in page.text
assert "지금 " not in page.text and "<ol>" not in page.text
assert missing.status_code == 404
+59 -3
View File
@@ -1,10 +1,13 @@
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
from router.router import app
from services.talk_service import DAILY_MAX, HIDE_AT, weather_line
from services.talk_service import DAILY_MAX, HIDE_AT, parse_cursor, spread_authors, weather_line
REGION = "1144000000"
BUSAN = "2611000000"
def client():
@@ -16,8 +19,8 @@ async def _login(c, login_id: str) -> dict:
return {"Authorization": f"Bearer {body['access_token']}"}
async def _write(c, h, body="망원동 하늘 진짜 맑아요"):
return (await c.post("/v1/talk", json={"region_code": REGION, "body": body}, headers=h)).json()
async def _write(c, h, body="망원동 하늘 진짜 맑아요", region=REGION):
return (await c.post("/v1/talk", json={"region_code": region, "body": body}, headers=h)).json()
@pytest.mark.anyio
@@ -87,3 +90,56 @@ def test_weather_line():
assert weather_line(Row()) == "18° 맑음"
assert weather_line(Wet()) == "12° 비"
assert weather_line(None) is None
def _ids(body: dict) -> list[int]:
return [x["talk_id"] for x in body["talks"]]
@pytest.mark.anyio
async def test_same_sido_talks_come_first_for_that_viewer():
async with client() as c:
busan = (await _write(c, await _login(c, "talk_bs1"), "광안리 바람 시원해요", BUSAN))["talk"]["talk_id"]
seoul = (await _write(c, await _login(c, "talk_se1"), "망원동 비 그쳤어요"))["talk"]["talk_id"]
nation = _ids((await c.get("/v1/talk/list")).json())
local = _ids((await c.get("/v1/talk/list", params={"region": BUSAN})).json())
assert nation.index(seoul) < nation.index(busan)
assert local.index(busan) < local.index(seoul)
@pytest.mark.anyio
async def test_pages_follow_cursor_without_repeats():
async with client() as c:
mine = []
for i in range(5):
h = await _login(c, f"talk_pg{i}")
for j in range(DAILY_MAX):
mine.append((await _write(c, h, f"페이지 글 {i}-{j}", BUSAN if j % 2 else REGION))["talk"]["talk_id"])
seen, cursor = [], None
while True:
body = (await c.get("/v1/talk/list", params={"region": BUSAN} | ({"cursor": cursor} if cursor else {}))).json()
seen += _ids(body)
cursor = body.get("next_cursor")
if not cursor:
break
assert (await c.get("/v1/talk/list", params={"cursor": "abc"})).json()["result"]["desc"] == "INVALID_INPUT"
assert len(seen) == len(set(seen)) and set(mine) <= set(seen)
@pytest.mark.anyio
async def test_mine_lists_only_my_talks_newest_first():
async with client() as c:
assert (await c.get("/v1/talk/mine")).status_code == 401
h = await _login(c, "talk_mine")
ids = [(await _write(c, h, f"내 글 {i}"))["talk"]["talk_id"] for i in range(3)]
await _write(c, await _login(c, "talk_notmine"), "남의 글")
await c.delete(f"/v1/talk/{ids[0]}", headers=h)
body = (await c.get("/v1/talk/mine", headers=h)).json()
assert _ids(body) == [ids[2], ids[1]] and all(x["mine"] for x in body["talks"])
def test_spread_authors_and_cursor():
v = lambda who: SimpleNamespace(author=SimpleNamespace(user_id=who)) # noqa: E731
assert [x.author.user_id for x in spread_authors([v("a"), v("a"), v("a"), v("b"), v("c")])] == ["a", "b", "a", "c", "a"]
assert parse_cursor("1760000000_42") == (1760000000, 42)
assert parse_cursor("12") is None and parse_cursor("x_1") is None
+68
View File
@@ -0,0 +1,68 @@
# 2026-10-21(수) 회의 — 날씨각
주제: '내일 날씨' 검색 공략, 공유·로그인 정리, 앱·위젯 확장 준비
참석: 대표, 황 본부장, 최미나
## 금일 핵심 업무 (최미나)
1. 공유 링크·좋아요·댓글·로그인 수정분 배포
2. '내일 날씨' 카드 추가 및 태깅 테스트
## 진행 관리
- 미완료 항목을 포함해 진행 상황을 매일 대표에게 보고 (결정)
- 전일 회의 내용은 병렬로 반영 중이고, 일부는 로컬에만 반영된 상태
## 설치·토스 미니앱
- 토스 미니앱은 라이브 상태이고 홈 화면 바로가기를 추가할 수 있음
- 토스 밖 웹에서도 홈 화면 바로가기를 쉽게 추가하게 (방향) — 이미 반영됨(`e5716c0`, `dff03f6`)
- 미니앱은 웹 업데이트가 자동 반영되지 않음. 웹이 바뀔 때마다 다시 올려야 하고, 지금 토스 바로가기는 이전 버전
## 공유·좋아요·로그인
- 공유하면 이미지는 가지만 링크가 빠짐 → 공유에 링크를 반드시 포함 (결정). 지금은 이미지와 함께 링크를 공유 text에 실어 보냄(`frontend/src/b/Sheets.tsx:564`)
- 히어로는 포스트 형태로 바꾸지 않고 지금 형태를 유지하며, 공유·좋아요를 추가 (결정)
- 오늘의 각부터 모든 카드에 좋아요·댓글·공유 (결정)
- 로그인은 포스팅할 때만 요청하고, 댓글을 쓸 때는 띄우지 않음 (결정) — 10/20 '확인 필요'였던 댓글 로그인 여부가 이로써 정해짐
- 웹 로그인은 구글로 통일하고 일반 로그인은 제거 (결정) — 구글 로그인은 있음(`4e9b0ba`), 아이디·비밀번호 로그인·가입은 남아 있음(`backend/router/v1/auth/account.py:25`, `:31`)
- 의견(황 본부장): 공유 이미지는 각마다 달라도 링크는 날씨각 고정 URL 하나로 하면 개발이 쉬움
- 의견(황 본부장): 통이미지 공유는 몇 번 하다 그만둠. 캐시워크처럼 사용자 사진 위에 날씨각 정보 레이어를 얹어 '내 콘텐츠'로 공유하게 해야 함 → 앱 기능으로 넣는 방향(대표), 구현 아이디어 검토
- 모바일에서 창이 닫히지 않는 오류 → 수정 예정
## 검색 노출
- 구별 페이지로 '분당구 오늘 날씨' 구글 2위 확인. 넣을 수 있는 지역은 모두 추가 (결정)
- 구글 트렌드상 '내일 날씨'가 '오늘 날씨'보다 검색량이 압도적으로 많음
- 메인 타임라인(나의 각 아래)에 '내일 날씨' 카드를 넣고 '○○구 내일 날씨'로 검색 등록되게 태깅. 별도 페이지는 만들지 않음 (결정). 결정 사항 요약에는 '히어로에 추가'로 적혀 있어 위치는 확인 필요
- 구글에 등록되려면 페이지에 실제 내일 기온·습도가 있어야 함
- 스테이머뭄은 중복 사이트를 내리고 하나만 남겨 다시 상위 노출됨
- 김성경 FAQ 반영 완료
## 홍보·제휴
- 유튜브 숏폼 자동화: 수석이 방향을 제시함. 10/22 김성경과 협의 후 진행
- 인스타 운영 자동화 관리자 페이지 제작 중. 자동 게시 전 담당자에게 승인 메일을 보내고, 승인·수정 후 게시
- 날씨 타로는 날마다 주제를 바꿈(회사 생활 등). 코디는 20·30·40대 이상 연령대별로 색 등을 바꿔 자동 게시
- 인스타 초기 피드는 이야기형('각이 100개 있어요', 빨래각·소맥각 소개, 날씨 점수 산정법)으로 하고 이후 자동화 피드로 전환 (방향)
- 캐시워크 미팅(10/21 17시, 황 본부장): 날씨각 URL 전달. 1단계 제휴 목적은 날씨각을 위젯으로 플랫폼에 넣고 '더 보기'로 유입시키는 것
## 위젯·앱
- 의견(대표): 위젯은 그 자체로 정보를 줌. 통신사(KT 등)가 날씨각 위젯을 기본 탑재하면 포털처럼 쓸 수 있음
- 위젯을 제공하려면 앱이 필요함. 기존 날씨 위젯과는 각 콘텐츠로 차별화
- 안드로이드 앱은 계속 준비하고 iOS도 함께 출시 추진 (결정)
- iOS 개발자 계정은 이전 담당자 개인 계정으로 보이고 비밀번호를 모름 → 소장에게 확인 요청, 어려우면 회사 계정으로 새로 만듦
- 의견(대표·황 본부장): 필사·하루 한 구절 같은 루틴형 위젯도 수요가 있음
## 앱인토스 정산 계좌
- 토스에 계좌 오류 화면을 보내 문의했고 답변 대기 중. 개인이 아니라 법인(주식회사 AI O2O) 계좌로 등록해야 함
- 조수현 부장이 법인 통장 사본을 대표에게 전달 → 대표가 등록 → 토스 로그인 연동 가입 (결정)
## 담당·기한
| 할 일 | 담당 | 기한 | 보고 |
|---|---|---|---|
| 공유 링크 포함, 전 카드 좋아요·댓글·공유, 로그인 수정, 모바일 창 닫힘 오류 수정 후 배포 | 최미나 | 미정 | 대표 데일리 보고 |
| '내일 날씨' 카드 추가, 지역별 태깅 테스트 | 최미나 | 미정 | 대표 데일리 보고 |
| 전 지역 날씨 페이지 추가 | 최미나 | 미정 | 대표 데일리 보고 |
| 단풍 지도 UI 수정 | 최미나 | 미정 | 대표 공유 |
| 토스 미니앱 최신 버전 재등록 | 최미나 | 미정 | 황 본부장 공유 |
| 유튜브 숏폼 자동화 진행 방안 협의 | 김성경·최미나 | 10/22 | 대표 보고 |
| 인스타 운영 관리자 페이지, 초기 피드 | 최미나 | 미정 | 대표 보고 |
| 레이어 공유 방식 아이디어 | 최미나 | 미정 | 황 본부장 공유 |
| iOS 개발자 계정 확인(소장) 또는 회사 계정 새로 만들기 | 최미나 | 미정 | 대표 보고 |
| 법인 통장 사본 전달, 앱인토스 계좌 등록, 토스 로그인 가입 | 조수현(사본)·대표(등록)·최미나(가입) | 10/21 | 대표 확인 |
| 캐시워크 미팅 | 황 본부장 | 10/21 17:00 | 대표 공유 |
+2 -2
View File
@@ -37,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;
Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

+471 -28
View File
@@ -1,218 +1,661 @@
{
"source": "산림청·국립수목원·국립산림과학원 「2026년 한반도 단풍절정 예측지도」(2026.9.22 보도자료, 단풍나무류 지도)",
"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% 이상이 물든 때(지도 기준: 단풍나무류 단풍 50% 이상). 산별 시작일은 발표에 없어 start는 null",
"basis": "절정: 그 수종 잎의 50% 이상이 물든 때. 첫 단풍: 발표에 시작일이 없어 절정 14일 전부터로 추정. 예측 지점이 아닌 명소는 basis에 적은 가장 가까운 예측 지점 날짜를 씀",
"license": "공공누리 제1유형(출처표시) — 정책브리핑 게재본은 '텍스트에 한하여' 1유형, 사진·이미지는 저작권자 허락 필요(지도 이미지 자체 재사용은 확인 필요)",
"coord_source": "한국관광공사 TourAPI(KorService2 searchKeyword2) 관광지 좌표 mapy/mapx; 산마다 쓴 지점명은 coord_point(정상이 아닌 국립공원·탐방 지점일 수 있음)",
"coord_source": "한국관광공사 TourAPI(KorService2 searchKeyword2) 좌표; 소리봉(포천)은 광릉숲길 좌표로 근사(가까운 지점 계산용, 지도엔 안 나옴)",
"updated": "2026-10-21",
"mountains": [
"spots": [
{
"name": "설악산",
"kind": "maple",
"region": "강원 속초·양양·인제",
"lat": 38.119,
"lon": 128.465,
"start": null,
"peak": "2026-10-20",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "설악산 대청봉"
},
{
"name": "점봉산",
"kind": "maple",
"region": "강원 인제·양양",
"lat": 38.036,
"lon": 128.471,
"start": null,
"peak": "2026-10-21",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "점봉산 곰배령"
},
{
"name": "광덕산",
"kind": "maple",
"region": "강원 화천·경기 포천",
"lat": 38.115,
"lon": 127.439,
"start": null,
"peak": "2026-10-22",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "광덕산(화천)"
},
{
"name": "화악산",
"kind": "maple",
"region": "강원 화천·경기 가평",
"lat": 38.048,
"lon": 127.522,
"start": null,
"peak": "2026-10-20",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "화악산"
},
{
"name": "축령산",
"kind": "maple",
"region": "경기 남양주·가평",
"lat": 37.753,
"lon": 127.309,
"start": null,
"peak": "2026-10-26",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "축령산"
},
{
"name": "용문산",
"kind": "maple",
"region": "경기 양평",
"lat": 37.551,
"lon": 127.569,
"start": null,
"peak": "2026-10-23",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "용문산"
},
{
"name": "수리산",
"kind": "maple",
"region": "경기 군포·안양·안산",
"lat": 37.348,
"lon": 126.901,
"start": null,
"peak": "2026-11-02",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "수리산도립공원"
},
{
"name": "가야산(충남)",
"kind": "maple",
"region": "충남 서산·예산",
"lat": 36.704,
"lon": 126.609,
"start": null,
"peak": "2026-10-31",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "가야산(서산)"
},
{
"name": "소백산",
"kind": "maple",
"region": "충북 단양·경북 영주",
"lat": 36.935,
"lon": 128.457,
"start": null,
"peak": "2026-10-20",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "소백산 천문대"
},
{
"name": "속리산",
"kind": "maple",
"region": "충북 보은·경북 상주",
"lat": 36.517,
"lon": 127.817,
"start": null,
"peak": "2026-10-28",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "속리산국립공원(충북)"
},
{
"name": "계룡산",
"kind": "maple",
"region": "충남 공주·계룡, 대전",
"lat": 36.357,
"lon": 127.232,
"start": null,
"peak": "2026-11-01",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "계룡산국립공원"
},
{
"name": "주왕산",
"kind": "maple",
"region": "경북 청송",
"lat": 36.394,
"lon": 129.142,
"start": null,
"peak": "2026-10-26",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "주왕산국립공원"
},
{
"name": "팔공산",
"kind": "maple",
"region": "대구·경북",
"lat": 35.99,
"lon": 128.696,
"start": null,
"peak": "2026-10-30",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "팔공산국립공원(동화사지구)"
},
{
"name": "가야산(경북)",
"kind": "maple",
"region": "경북 성주·경남 합천",
"lat": 35.8,
"lon": 128.142,
"start": null,
"peak": "2026-10-28",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "가야산국립공원(백운동 지구)"
},
{
"name": "금원산",
"kind": "maple",
"region": "경남 거창",
"lat": 35.731,
"lon": 127.761,
"start": null,
"peak": "2026-10-25",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "금원산"
},
{
"name": "지리산",
"kind": "maple",
"region": "경남·전남·전북",
"lat": 35.304,
"lon": 127.749,
"start": null,
"peak": "2026-10-27",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "지리산 천왕봉"
},
{
"name": "변산반도",
"kind": "maple",
"region": "전북 부안",
"lat": 35.642,
"lon": 126.58,
"start": null,
"peak": "2026-11-04",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "변산반도국립공원"
},
{
"name": "내장산",
"kind": "maple",
"region": "전북 정읍·전남 장성",
"lat": 35.471,
"lon": 126.867,
"start": null,
"peak": "2026-11-04",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "내장산국립공원"
},
{
"name": "월출산",
"kind": "maple",
"region": "전남 영암·강진",
"lat": 34.775,
"lon": 126.722,
"start": null,
"peak": "2026-11-09",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "월출산국립공원"
},
{
"name": "두륜산",
"kind": "maple",
"region": "전남 해남",
"lat": 34.49,
"lon": 126.616,
"start": null,
"peak": "2026-11-11",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "두륜산도립공원"
},
{
"name": "상왕봉",
"kind": "maple",
"region": "전남 완도",
"lat": 34.348,
"lon": 126.693,
"start": null,
"peak": "2026-11-11",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "상왕산"
},
{
"name": "교래곶자왈",
"kind": "maple",
"region": "제주 제주시 조천",
"lat": 33.442,
"lon": 126.667,
"start": null,
"peak": "2026-11-02",
"basis": "산림청 예측(단풍나무류)",
"coord_point": "제주 교래자연휴양림"
},
{
"name": "한라산(1100도로)",
"kind": "maple",
"region": "제주",
"lat": 33.358,
"lon": 126.463,
"start": null,
"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": "보석사"
}
]
}
}
+1
View File
@@ -13,6 +13,7 @@ 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 />} />
@@ -3,8 +3,8 @@
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
import { client } from '../client.gen';
import { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, 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, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, 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, 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, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, UploadTalkImageData, UploadTalkImageError, UploadTalkImageResponse } from '../types.gen';
import { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, 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, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, GetArticleData, GetArticleError, GetArticleResponse, 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, 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, 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, RefreshData, RefreshError, RefreshResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, ScoreMyGakData, ScoreMyGakError, ScoreMyGakResponse, SignupData, SignupError, SignupResponse, 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 }) => {
@@ -677,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>> = {
@@ -694,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>> = {
@@ -779,6 +779,24 @@ export const addMyGakMutation = (options?: Partial<Options<AddMyGakData>>): UseM
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)
});
/**
* 조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)
*/
@@ -816,7 +834,7 @@ export const deleteMyGakMutation = (options?: Partial<Options<DeleteMyGakData>>)
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 }) => {
@@ -834,10 +852,10 @@ export const listTalksOptions = (options?: Options<ListTalksData>) => queryOptio
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>>, number | null | Pick<QueryKey<Options<ListTalksData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
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 }) => {
@@ -861,6 +879,54 @@ export const listTalksInfiniteOptions = (options?: Options<ListTalksData>) => {
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개)
*/
+2 -2
View File
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, 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 ClientOptions, type CommentData, type CommuteData, Confidence, 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 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 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 HourCell, type HoursSlide, type HttpValidationError, 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 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 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 ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, 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, Line truncated
export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, 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 ClientOptions, type CommentData, type CommuteData, Confidence, 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 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 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, 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 ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListMyTalksData, type ListMyTalksError, type ListMyTalksErrors, type ListMyTalksResponse, type ListMyTalksResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListPresetsData, type ListPresetsResponse, type ListPresetsResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, type LoginData, type LoginError, type LoginErrors, type LogLine truncated
+15 -5
View File
@@ -2,7 +2,7 @@
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
import { client } from './client.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, 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, 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, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } from './types.gen';
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, 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, 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, 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, RefreshData, RefreshErrors, RefreshResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, 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 });
@@ -209,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',
@@ -221,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 });
@@ -252,6 +252,11 @@ export const addMyGak = <ThrowOnError extends boolean = true>(options: Options<A
}
});
/**
* 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기)
*/
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 });
/**
* 조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)
*/
@@ -270,10 +275,15 @@ export const scoreMyGak = <ThrowOnError extends boolean = true>(options: Options
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 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개)
*/
+219 -3
View File
@@ -625,6 +625,14 @@ export type Hero = {
weather_slots?: {
[key: string]: number;
};
/**
* Weather Why
*
* 구간별 날씨 점수 근거(조건·비중·조건 점수·지금 값). 키는 weather_slots 와 같다
*/
weather_why?: {
[key: string]: Array<WeatherWhy>;
};
top1?: TopIndex | null;
/**
* Bubble
@@ -654,6 +662,7 @@ export type Hero = {
* 히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)
*/
status?: Array<HeroStat>;
tomorrow?: HeroTomorrow | null;
};
/**
@@ -680,6 +689,38 @@ export type HeroStat = {
tone: 'normal' | 'warn' | 'rain';
};
/**
* HeroTomorrow
*
* 히어로 '내일' 스위치. 3시간 칸 날씨는 /v1/weather/today?day=tomorrow 로 따로 받는다.
*/
export type HeroTomorrow = {
/**
* Day
*/
day: string;
/**
* Weather Slots
*
* 내일 구간별 날씨 점수 {morning·day·evening·night: 점수}
*/
weather_slots?: {
[key: string]: number;
};
/**
* Weather Why
*
* 내일 구간별 날씨 점수 근거
*/
weather_why?: {
[key: string]: Array<WeatherWhy>;
};
/**
* 내일 하루 점수로 1위인 각. score·summary 는 내일 값
*/
top1?: TopIndex | null;
};
/**
* HourCell
*/
@@ -867,6 +908,28 @@ export type MyGakData = {
rule: MyGakRule;
};
/**
* MyGakPreset
*/
export type MyGakPreset = {
/**
* Code
*/
code: string;
/**
* Name
*/
name: string;
/**
* Icon
*/
icon: string;
/**
* 공식 각을 내 각 조건으로 비슷하게 옮긴 값. 점수는 공식 각과 다를 수 있음
*/
rule: MyGakRule;
};
/**
* MyGakRule
*/
@@ -1120,6 +1183,30 @@ export type PostData = {
saved?: boolean | null;
};
/**
* PostReaction
*
* 포스트 틀이 아닌 카드(히어로·오늘의 각)에 붙는 좋아요·댓글.
*/
export type PostReaction = {
/**
* Post Id
*/
post_id: number;
/**
* Like Count
*/
like_count: number;
/**
* Comment Count
*/
comment_count: number;
/**
* Liked
*/
liked?: boolean | null;
};
/**
* PostType
*/
@@ -1183,7 +1270,15 @@ export const PostType = {
/**
* UV
*/
UV: 15
UV: 15,
/**
* HERO
*/
HERO: 16,
/**
* TODAY_GAK
*/
TODAY_GAK: 17
} as const;
/**
@@ -1320,6 +1415,12 @@ export type ReqComment = {
* Body
*/
body: string;
/**
* Region
*
* 로그인 없이 쓸 때 보고 있는 동네 코드. 이름이 '마포구 익명'으로 보인다
*/
region?: string | null;
};
/**
@@ -1617,6 +1718,8 @@ export type ResFeed = {
* Posts
*/
posts?: Array<PostData>;
hero_post?: PostReaction | null;
gak_post?: PostReaction | null;
bands?: Bands | null;
};
@@ -1766,6 +1869,21 @@ export type ResMyGakList = {
items?: Array<MyGakData>;
};
/**
* Res_MyGakPresets
*/
export type ResMyGakPresets = {
result?: ErrorInfo;
/**
* Msg
*/
msg?: string | null;
/**
* Items
*/
items?: Array<MyGakPreset>;
};
/**
* Res_MyGakScore
*/
@@ -2073,8 +2191,10 @@ export type ResTalkList = {
talks?: Array<TalkData>;
/**
* Next Cursor
*
* 다음 페이지를 받을 때 그대로 cursor 로 보낸다
*/
next_cursor?: number | null;
next_cursor?: string | null;
};
/**
@@ -3141,6 +3261,10 @@ export type WeatherSlot = {
* Rain Prob
*/
rain_prob?: number | null;
/**
* Humidity
*/
humidity?: number | null;
/**
* Icon
*/
@@ -3152,6 +3276,34 @@ export type WeatherSlot = {
note: string;
};
/**
* WeatherWhy
*/
export type WeatherWhy = {
/**
* Label
*/
label: string;
/**
* Weight
*
* 비중 % (합 100)
*/
weight: number;
/**
* Score
*
* 이 조건 점수 0~100
*/
score: number;
/**
* Note
*
* 지금 값 (예: 체감 19°, 편한 범위 18~24° 안)
*/
note: string;
};
/**
* WeekDay
*/
@@ -3382,6 +3534,12 @@ export type GetWeatherTodayData = {
* 구 행정코드
*/
region: string;
/**
* Day
*
* tomorrow 면 내일 칸
*/
day?: 'today' | 'tomorrow';
};
url: '/v1/weather/today';
};
@@ -4470,6 +4628,22 @@ export type AddMyGakResponses = {
export type AddMyGakResponse = AddMyGakResponses[keyof AddMyGakResponses];
export type ListPresetsData = {
body?: never;
path?: never;
query?: never;
url: '/v1/my-gak/presets';
};
export type ListPresetsResponses = {
/**
* Successful Response
*/
200: ResMyGakPresets;
};
export type ListPresetsResponse = ListPresetsResponses[keyof ListPresetsResponses];
export type ScoreMyGakData = {
body: ReqMyGakScore;
path?: never;
@@ -4541,10 +4715,16 @@ export type ListTalksData = {
};
path?: never;
query?: {
/**
* Region
*
* 보는 사람의 구 행정코드
*/
region?: string | null;
/**
* Cursor
*/
cursor?: number | null;
cursor?: string | null;
};
url: '/v1/talk/list';
};
@@ -4567,6 +4747,42 @@ export type ListTalksResponses = {
export type ListTalksResponse = ListTalksResponses[keyof ListTalksResponses];
export type ListMyTalksData = {
body?: never;
headers?: {
/**
* Authorization
*/
authorization?: string | null;
};
path?: never;
query?: {
/**
* Cursor
*/
cursor?: string | null;
};
url: '/v1/talk/mine';
};
export type ListMyTalksErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type ListMyTalksError = ListMyTalksErrors[keyof ListMyTalksErrors];
export type ListMyTalksResponses = {
/**
* Successful Response
*/
200: ResTalkList;
};
export type ListMyTalksResponse = ListMyTalksResponses[keyof ListMyTalksResponses];
export type AddTalkData = {
body: ReqTalk;
headers?: {
+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
}
+1 -1
View File
@@ -232,7 +232,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>
+38 -4
View File
@@ -1,12 +1,13 @@
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 PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type PostReaction, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, clockShort, fall } from './lib'
import type { SlideBg } from './types'
import { deg } from './weatherText'
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { useSheet } from './sheetContext'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { useCarousel } from './carousel'
@@ -28,6 +29,8 @@ const ACCOUNTS: Record<PostType, readonly [string, string]> = {
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
[PostType.MOON]: ['오늘 밤 달', 'moon'],
[PostType.UV]: ['자외선', 'glasses'],
[PostType.HERO]: ['오늘 날씨', 'sun'],
[PostType.TODAY_GAK]: ['오늘의 각', 'rabbit'],
}
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide
@@ -87,7 +90,7 @@ 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>
)
}
@@ -478,12 +481,23 @@ function FullCard({ post }: PostProps) {
)
}
type FrameProps = { title: string; account: string; avatar: string; caption?: ReactNode; more?: ReactNode; shot?: RefObject<HTMLDivElement | null>; children: ReactNode }
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, children }: FrameProps) {
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] } })
@@ -503,17 +517,37 @@ export function PostFrame({ title, account, avatar, caption, more, shot, childre
</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]">
+40 -64
View File
@@ -14,9 +14,7 @@ import {
listCommentsInfiniteOptions,
listCommentsInfiniteQueryKey,
listRegionsOptions,
loginMutation,
meQueryKey,
signupMutation,
unlikeCommentMutation,
updateMeMutation,
} from '../api/client/@tanstack/react-query.gen'
@@ -28,12 +26,14 @@ import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateR
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 }) {
@@ -76,7 +76,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
)
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가' } 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 }) {
@@ -100,8 +100,10 @@ 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])
@@ -138,6 +140,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{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 />}
@@ -525,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)
@@ -547,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) => {
@@ -581,7 +591,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
setToast('이미지를 내려받았어요')
return
}
navigator.clipboard.writeText(text).then(
navigator.clipboard.writeText(`${text} ${SITE_URL}`).then(
() => setToast('이미지를 내려받고 링크를 복사했어요'),
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
)
@@ -711,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 } }),
@@ -727,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)
@@ -786,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>
@@ -795,74 +803,41 @@ 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, method: 'id' | 'google' = 'id') => {
const done = (res: ResAuth) => {
if (!res.result?.success || !res.access_token) {
setError(method === 'google' ? '구글로 로그인하지 못했어요. 다시 해 주세요.' : (AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.'))
setError('구글로 로그인하지 못했어요. 다시 해 주세요.')
return
}
setTokens(res.access_token, res.refresh_token ?? null)
track(method === 'google' ? 'login' : mode === 'login' ? 'login' : 'sign_up', { method })
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: (res) => done(res), onError: fail })
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: (res) => done(res), 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>
<GoogleButton onResult={(res) => done(res, 'google')} onFail={fail} />
<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>
)
}
@@ -983,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={() => {
+303 -71
View File
@@ -1,8 +1,19 @@
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
import { Link } from 'react-router'
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 TalkData, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
import {
RainType,
Sky,
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 { FoliageCard } from './foliageMap'
@@ -10,13 +21,14 @@ import { InstallBanner } from './installBanner'
import { MyGakRow } from './myGak'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike } from './pinnedLike'
import { FeedComposer, TalkCard } from './talk'
import { useFeedTalks } from './talkState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { useSky } from './skyContext'
import { GakShareCard, HeroShareCard, type HeroShare } from './shareCards'
import { SendIcon } from './svg'
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'
@@ -32,10 +44,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' },
@@ -73,7 +99,12 @@ 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[] {
@@ -81,12 +112,27 @@ function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
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'
@@ -99,29 +145,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 share = () => tplRef.current && open({ type: 'share', share: { title: `${region.name} 오늘 날씨`, slides: [tplRef.current] } })
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') => {
@@ -135,39 +219,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'
const shareData: HeroShare = {
kind,
sky: weather,
date: `${t.mo}월 ${t.d}일 ${WEEKDAYS[t.wd]}요일`,
place: region.name,
label: `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`,
score,
bubble,
summary: top1?.summary,
status: status.map((x) => ({ label: x.label, value: x.value, warn: x.tone === 'warn' })),
slots: KINDS.map((k) => {
const s = slotOf(k === nowKind ? 'now' : k)
return { label: k === nowKind ? '지금' : PREVIEW[k].label, icon: k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)], temp: s?.temp_c != null ? deg(s.temp_c) : '–', on: k === kind }
}),
}
// 공유 이미지: 아침~밤 네 시간대 모두. 점수는 시간대 점수, 각은 그 시간대 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}>
<HeroShareCard d={shareData} ref={tplRef} />
<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} />
@@ -183,33 +306,108 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
</div>
)}
<div className="relative z-[3] flex items-center justify-between">
<p className="m-0 text-[14px] font-bold opacity-80">
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</p>
<button type="button" onClick={share} aria-label="오늘 날씨 보내기" className={cx('relative grid size-7 cursor-pointer place-items-center opacity-80 [&_svg]:size-[22px] [&_svg]:stroke-[2]', TAP44)}>
<SendIcon className="fill-none stroke-current [stroke-linecap:round] [stroke-linejoin:round]" />
</button>
<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>
)}
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
<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>
</span>
{why && score != null && (
<button
type="button"
onClick={() =>
open({
type: 'weatherWhy',
why: { label: whyLabel, score, why },
})
}
aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`}
className={cx(
'absolute right-0 bottom-1 z-[2] grid size-7 cursor-pointer place-items-center rounded-full bg-white font-jua text-[16px] text-(--orange-deep) shadow-[0_2px_6px_rgb(40_48_74/0.25)]',
TAP44,
)}
>
?
</button>
)}
</div>
</div>
</div>
<div className="relative z-[3] 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>
) : (
@@ -221,7 +419,11 @@ 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>
@@ -232,14 +434,21 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
</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>
)
})}
@@ -260,12 +469,20 @@ function moonPath(pct: number, r: number, lit: boolean) {
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
}
function GakCard({ items, place, at }: { items: TopIndex[]; place: string; at: string }) {
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 (
<PostFrame title={`오늘의 각 · ${place}`} account="오늘의 각" avatar="rabbit" more={<Link to="/gak">전체 보기</Link>} caption="누르면 계산 근거를 보여 줘요" shot={tplRef}>
<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]">
@@ -347,6 +564,8 @@ function SeasonBand({ news }: { news: BandArticle[] }) {
)
}
const TALK_EVERY = 3
export function TodayPage() {
const { region } = useRegion()
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
@@ -361,8 +580,19 @@ export function TodayPage() {
const nowAt = f?.hero?.now_at
const load = loadOf(feed)
const [mine, setMine] = useState<TalkData[]>([])
// 사람들이 쓴 글은 운영 포스트 3개마다 하나씩. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고
const talks = useFeedTalks().filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
// 사람들이 쓴 글은 4·7·10번째 포스트 뒤에 하나씩(3번째 뒤 행사 띠와 안 붙게), 남은 글은 피드 끝에. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고
const feedTalks = useFeedTalks()
const talks = feedTalks.talks.filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
const between = Math.max(0, Math.floor((posts.length - 1) / TALK_EVERY))
const moreRef = useRef<HTMLDivElement>(null)
const { more, loadMore } = feedTalks
useEffect(() => {
const el = moreRef.current
if (!el || !more) return
const io = new IntersectionObserver((es) => es.some((e) => e.isIntersecting) && loadMore(), { rootMargin: '600px' })
io.observe(el)
return () => io.disconnect()
}, [more, loadMore])
useEffect(() => {
window.scrollTo({ top: 0 })
@@ -388,15 +618,15 @@ export function TodayPage() {
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)} />
<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} />
<TalkCard key={t.talk_id} t={t} onGone={() => setMine((m) => m.filter((x) => x.talk_id !== t.talk_id))} />
))}
<MyGakRow />
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
<GakCard items={stories} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
<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 />
) : (
@@ -413,11 +643,13 @@ export function TodayPage() {
<Fragment key={p.post_id}>
<PostCard post={p} />
{i === 1 && <FoliageCard />}
{(i + 1) % 3 === 0 && talks[(i + 1) / 3 - 1] && <TalkCard t={talks[(i + 1) / 3 - 1]} />}
{i > 0 && i % TALK_EVERY === 0 && talks[i / TALK_EVERY - 1] && <TalkCard t={talks[i / TALK_EVERY - 1]} />}
{bandAt.find(([at]) => at === i + 1)?.[1]}
</Fragment>
))}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
{load !== 'loading' && talks.slice(between).map((t) => <TalkCard key={t.talk_id} t={t} />)}
<div ref={moreRef} aria-hidden />
</div>
</section>
)
+18 -8
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);
}
+53 -39
View File
@@ -3,37 +3,42 @@ import data from '../../seo/foliage_2026.json'
import { cx } from '../lib/utils'
import { kst } from './lib'
import { PostFrame } from './Post'
import { Ic } from './ui'
type Mountain = { name: string; region: string; lat: number; lon: number; peak: string }
type Stage = 'peak' | 'soon' | 'before' | 'after'
type Kind = 'maple' | 'ginkgo'
type Spot = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string }
type Stage = 'before' | 'first' | 'peak'
// 지도 그림(public/foliage/korea-map.webp, 1024×1536)의 위경도 → 그림 위 위치. generated-images/foliage-map/korea_outline.json 과 같은 값
const MAP = { lon0: 124.0, lon1: 132.2, lat0: 33.0, lat1: 43.1, w: 900, h: 1407, scale: 1.09168, ox: 20.74, cw: 1024, ch: 1536 }
const PEAK_DAYS = 3 // 절정일 앞뒤 이만큼은 '지금 절정'
const SOON_DAYS = 7
// 지도 그림(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 }
// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 절정으로 본다
const FIRST_DAYS = 14
const PEAK_DAYS = 3
const SEASON = { from: '09-20', to: '11-25' }
const SEOUL = { lat: 37.566, lon: 126.978 }
const STAGE: Record<Stage, { label: string; dot: string }> = {
peak: { label: '지금 절정', dot: 'bg-[#ff5a36]' },
soon: { label: '곧 절정', dot: 'bg-[#ffb02e]' },
before: { label: '아직', dot: 'bg-[#7cc47a]' },
after: { label: '절정 지남', dot: 'bg-[#b9a69a]' },
const STAGE: Record<Stage, { label: string; icon: string }> = {
before: { label: '단풍 전', icon: 'size-3 opacity-60 grayscale' },
first: { label: '첫 단풍', icon: 'size-3.5' },
peak: { label: '절정', icon: 'size-[18px]' },
}
const KIND: Record<Kind, { label: string; icon: string }> = {
maple: { label: '단풍', icon: 'maple' },
ginkgo: { label: '은행', icon: 'ginkgo' },
}
const pos = (m: Mountain) => ({
left: `${((MAP.ox + ((m.lon - MAP.lon0) / (MAP.lon1 - MAP.lon0)) * MAP.w * MAP.scale) / MAP.cw) * 100}%`,
top: `${((((MAP.lat1 - m.lat) / (MAP.lat1 - MAP.lat0)) * MAP.h * MAP.scale) / MAP.ch) * 100}%`,
const pos = (m: Spot) => ({
left: `${((MAP.ox + (m.lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size) * 100}%`,
top: `${((MAP.oy + (MAP.lat1 - m.lat) * MAP.s) / MAP.size) * 100}%`,
})
const DAY = 86_400_000
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
function stage(m: Mountain, today: string): Stage {
function stage(m: Spot, today: string): Stage {
const d = days(today, m.peak)
if (Math.abs(d) <= PEAK_DAYS) return 'peak'
if (d < 0) return 'after'
return d <= SOON_DAYS ? 'soon' : 'before'
if (d <= PEAK_DAYS) return 'peak'
return d <= FIRST_DAYS ? 'first' : 'before'
}
const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
@@ -46,48 +51,57 @@ export function FoliageCard() {
const [picked, setPicked] = useState<string | null>(null)
const mmdd = today.slice(5)
if (mmdd < SEASON.from || mmdd > SEASON.to) return null
const mountains = (data.mountains as unknown as Mountain[]).map((m) => ({ ...m, stage: stage(m, today) }))
const peakNow = mountains.filter((m) => m.stage === 'peak').map((m) => m.name)
// 발표 지도에 서울 안 산은 없어 서울 시청에서 가장 가까운 산으로
const seoul = mountains.reduce((a, b) => (Math.hypot(b.lat - SEOUL.lat, b.lon - SEOUL.lon) < Math.hypot(a.lat - SEOUL.lat, a.lon - SEOUL.lon) ? b : a))
const sel = mountains.find((m) => m.name === picked)
const spots = (data.spots as Spot[]).map((m) => ({ ...m, stage: stage(m, today) }))
const peakNow = spots.filter((m) => m.stage === 'peak').map((m) => m.name)
// 발표 지도에 서울 안 산은 없어 서울 시청에서 가장 가까운 단풍 예측 산으로
const forecast = spots.filter((m) => m.kind === 'maple' && m.basis.startsWith('산림청'))
const seoul = forecast.reduce((a, b) => (Math.hypot(b.lat - SEOUL.lat, b.lon - SEOUL.lon) < Math.hypot(a.lat - SEOUL.lat, a.lon - SEOUL.lon) ? b : a))
const sel = spots.find((m) => m.name === picked)
return (
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peakNow.length ? `지금 절정: ${peakNow.join(' · ')}` : undefined}>
<div className="relative bg-[#e6f2ff] px-4 pt-4 pb-3">
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peakNow.length ? `지금 절정 ${peakNow.length}곳: ${peakNow.slice(0, 5).join(' · ')}${peakNow.length > 5 ? ' 외' : ''}` : undefined}>
<div className="relative bg-[#fff6ea] px-4 pt-4 pb-3">
<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">서울 근교 {seoul.name} 절정 예상 {md(seoul.peak)}</p>
<div className="relative mx-auto mt-2 aspect-[2/3] w-[86%]">
<img src="/foliage/korea-map.webp" alt="한반도 지도" className="absolute inset-0 size-full" />
{mountains.map((m) => (
<div className="relative mx-auto mt-1 aspect-square w-full">
<img src="/foliage/korea-map.webp" alt="단풍 지도" className="absolute inset-0 size-full" />
{spots.map((m) => (
<button
key={m.name}
type="button"
onClick={() => setPicked(m.name === picked ? null : m.name)}
aria-label={`${m.name} ${STAGE[m.stage].label}, 절정 예상 ${md(m.peak)}`}
className="absolute -translate-x-1/2 -translate-y-1/2 cursor-pointer p-1.5"
aria-label={`${m.name} ${KIND[m.kind].label} ${STAGE[m.stage].label}, 절정 예상 ${md(m.peak)}`}
className={cx('absolute grid -translate-x-1/2 -translate-y-1/2 cursor-pointer place-items-center p-0.5', m.name === picked && 'z-[2] scale-150')}
style={pos(m)}
>
<i className={cx('block size-3.5 rounded-full border-2 border-white shadow-[0_1px_4px_rgb(40_48_74/0.35)]', STAGE[m.stage].dot, m.name === picked && 'size-5')} />
<Ic name={KIND[m.kind].icon} className={cx('drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.4)]', STAGE[m.stage].icon)} />
</button>
))}
{sel && (
<p className="absolute right-0 bottom-0 m-0 rounded-[14px] bg-white/90 px-3 py-2 text-[13px] font-bold shadow-[0_4px_12px_rgb(40_48_74/0.15)]">
<p className="absolute right-0 bottom-0 z-[3] m-0 max-w-[75%] rounded-[14px] bg-white/95 px-3 py-2 text-[13px] font-bold shadow-[0_4px_12px_rgb(40_48_74/0.15)]">
<b className="font-jua text-[16px] font-normal">{sel.name}</b> {sel.region}
<br />
{STAGE[sel.stage].label} · 절정 예상 {md(sel.peak)}
{KIND[sel.kind].label} {STAGE[sel.stage].label} · 절정 예상 {md(sel.peak)}
{!sel.basis.startsWith('산림청') && <small className="block text-[11px] font-semibold text-(--ink3)">가까운 예측 지점 날짜예요</small>}
</p>
)}
</div>
<div className="mt-2 flex flex-wrap justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
{(Object.keys(STAGE) as Stage[]).map((s) => (
<span key={s} className="flex items-center gap-1">
<i className={cx('size-2.5 rounded-full', STAGE[s].dot)} />
{STAGE[s].label}
<div className="mt-2 flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
{(Object.keys(KIND) as Kind[]).map((k) => (
<span key={k} className="flex items-center gap-1">
<Ic name={KIND[k].icon} className="size-4" />
{KIND[k].label}
</span>
))}
<span className="opacity-30" aria-hidden="true">|</span>
{(Object.keys(STAGE) as Stage[]).map((st) => (
<span key={st} className="flex items-center gap-1">
<Ic name="maple" className={cx('size-4', STAGE[st].icon)} />
{STAGE[st].label}
</span>
))}
</div>
<p className="m-0 mt-1.5 text-center text-[11px] font-semibold text-(--ink3)">
출처: 산림청 2026 단풍절정 예측 · 단풍나무 잎 절반이 물든 때 기준
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요
</p>
</div>
</PostFrame>
+1 -2
View File
@@ -76,8 +76,7 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
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>}
<p className="m-0 flex items-center gap-2 text-[12.5px] font-bold text-(--ink3) before:h-px before:flex-1 before:bg-(--line) after:h-px after:flex-1 after:bg-(--line)">또는 아이디로</p>
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
</div>
)
}
+7 -1
View File
@@ -62,7 +62,13 @@ export async function promptInstall(): Promise<boolean> {
const e = deferred
deferred = null
notify()
await e.prompt()
try {
await e.prompt()
} catch (err) {
// 이미 한 번 띄웠거나 브라우저가 막으면 안내 창으로 넘긴다
console.warn('[install] prompt', err)
return false
}
const { outcome } = await e.userChoice
track('install_choice', { outcome })
return true
+32 -7
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'
import { useEffect, useState, type ReactNode } from 'react'
import { track } from '../lib/analytics'
import { dismiss, dismissed, platform, useInstall, useInstallable } from './install'
import { dismiss, dismissed, platform, promptInstall, useCanPrompt, useInstall, useInstallable } from './install'
const SITE = 'https://weather.o2o.kr'
@@ -42,11 +42,11 @@ export function InstallBanner() {
)
}
function Steps({ items }: { items: string[] }) {
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={t} className="flex items-start gap-2.5 rounded-2xl bg-[#f3f6fb] px-3.5 py-3 text-[14.5px] font-bold">
<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>
@@ -55,9 +55,23 @@ function Steps({ items }: { items: string[] }) {
)
}
/** 설치창을 띄울 수 없는 기기의 안내 */
// 사파리 아래 가운데 공유 버튼과 공유 목록의 '홈 화면에 추가' 모양 그대로
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(
@@ -71,10 +85,21 @@ export function InstallSheet() {
{p === 'ios' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">아이폰은 Safari에서 이렇게 추가해요.</p>
<Steps items={['아래쪽 가운데 공유 버튼(네모에 위쪽 화살표)을 눌러요', "목록을 올려 '홈 화면에 추가'를 눌러요", "오른쪽 위 '추가'를 누르면 끝이에요"]} />
<Steps
items={[
<>화면 아래 <ShareGlyph /> 공유 버튼을 눌러요. 안 보이면 오른쪽 아래 ··· 를 누른 뒤 공유</>,
<>목록을 올려 <AddGlyph /> 홈 화면에 추가를 눌러요</>,
"오른쪽 위 '추가'를 누르면 끝이에요",
]}
/>
</>
)}
{p === 'android' && (
{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={['오른쪽 위 ⋮ 메뉴를 눌러요', "'홈 화면에 추가' 또는 '앱 설치'를 눌러요", "'추가' 또는 '설치'를 누르면 끝이에요"]} />
+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', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental'])
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
+51 -14
View File
@@ -1,10 +1,10 @@
import { useState, type ReactNode } from 'react'
import type { MyGakRule, MyGakScore } from '../api/client/types.gen'
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 } from './myGakState'
import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Sec } from './ui'
import { Ic, Rail, Sec } from './ui'
const SLOT_WORD = Object.fromEntries(SLOTS) as Record<Slot, string>
@@ -49,9 +49,9 @@ export function MyGakRow() {
return (
<>
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
<div className="flex snap-x gap-2 overflow-x-auto px-3 pb-1 [scrollbar-width:none]">
<Rail label="내 각">
{items.map((g, i) => (
<div key={g.id ?? 'local'} className="flex w-[220px] shrink-0 snap-start flex-col gap-1.5 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<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]} />
@@ -67,11 +67,11 @@ export function MyGakRow() {
</div>
</div>
))}
<button type="button" onClick={() => open({ type: 'mix' })} className="flex w-[120px] shrink-0 cursor-pointer snap-start flex-col items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-(--line) p-3 font-jua text-[15px] text-(--ink2)">
<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>
</div>
</Rail>
</>
)
}
@@ -122,15 +122,49 @@ 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 ? { temp: !!shared.rule.temp, rain: !!shared.rule.rain, wind_max: shared.rule.wind_max != null, air: !!shared.rule.air, humidity: !!shared.rule.humidity } : { temp: true, rain: true, wind_max: false, air: false, humidity: false },
)
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>) }
@@ -144,10 +178,13 @@ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => voi
{shared ? (
<p className="m-0 text-[13px] font-bold text-(--ink2)">친구가 보낸 각이에요. {region.name} 기준 점수예요</p>
) : (
<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>
<>
<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>
+6 -1
View File
@@ -1,7 +1,7 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useSyncExternalStore } from 'react'
import { SITE_URL } from '../api/setup'
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey } from '../api/client/@tanstack/react-query.gen'
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'
@@ -89,6 +89,11 @@ export function useMyGakScores(rules: MyGakRule[]) {
})
}
/** 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기) */
export function usePresets() {
return useQuery({ ...listPresetsOptions(), staleTime: Infinity, select: (d) => d.items ?? [] })
}
export function useMyGak() {
const { loggedIn } = useAuth()
const { open } = useSheet()
+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'
/** 히어로·오늘의 각처럼 포스트 틀이 아닌 카드의 좋아요. 화면을 먼저 바꾸고 실패하면 되돌린다 */
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 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음)
+66 -38
View File
@@ -1,8 +1,8 @@
import type { Ref } from 'react'
import { createPortal } from 'react-dom'
import type { TopIndex } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { MEDALS } from './lib'
import type { TopIndex } from '../api/client/types.gen'
import { MEDALS, type TimeKind } from './lib'
import { Ic } from './ui'
/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
@@ -15,50 +15,78 @@ function Offscreen({ children }: { children: React.ReactNode }) {
)
}
export type HeroShare = {
kind: string
sky: string
date: string
place: string
export type DayShare = {
kind: TimeKind
label: string
now: boolean
icon: string
temp: string
score?: number | null
bubble?: string | null
summary?: string | null
status: { label: string; value: string; warn: boolean }[]
slots: { label: string; icon: string; temp: string; on: boolean }[]
gak?: { name: string; icon: string } | null
}
export function HeroShareCard({ d, ref }: { d: HeroShare; ref: Ref<HTMLDivElement> }) {
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="b-hero relative flex aspect-[4/5] flex-col overflow-hidden px-5 pt-5 pb-4 text-center" data-t={d.kind} data-sky={d.sky}>
<p className="m-0 text-left text-[14px] font-bold opacity-80">
{d.date} · {d.place}
</p>
<div className="b-sun mx-auto mt-5 grid aspect-square w-36 place-items-center rounded-full">
<span>
<small className="block font-jua text-[13px]">{d.label}</small>
<b className="block font-bagel text-[58px] leading-[0.95] font-normal">{d.score ?? '–'}</b>
</span>
</div>
<p className="m-0 mt-4 font-jua text-[26px] leading-tight">{d.bubble}</p>
{d.summary && <p className="m-0 mt-1 text-[15px] font-bold opacity-80">{d.summary}</p>}
<p className="m-0 mt-2 flex flex-wrap justify-center gap-x-2 font-jua text-[14px]">
{d.status.map((x) => (
<span key={x.label} className={cx('whitespace-nowrap', x.warn && 'b-warn')}>
<span className="opacity-75">{x.label}</span> {x.value}
<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>
))}
</p>
<div className="b-strip mt-auto grid grid-cols-4 gap-1 rounded-[18px] p-[3px]">
{d.slots.map((s) => (
<span key={s.label} className={cx('flex flex-col items-center rounded-[14px] py-1.5', s.on && 'b-strip-on')}>
<span className="text-[13px] font-bold opacity-80">{s.label}</span>
<Ic name={s.icon} className="my-0.5 h-[22px] w-[22px] object-contain" />
<b className="font-jua text-[15px] font-normal">{s.temp}</b>
<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>
))}
</div>
<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>
)
+4 -1
View File
@@ -1,6 +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 }
@@ -15,6 +17,7 @@ export type SheetState =
| { type: 'region' }
| { type: 'mix'; shared?: MyGak }
| { type: 'install' }
| { type: 'weatherWhy'; why: WeatherWhyPayload }
| null
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
+28 -5
View File
@@ -15,6 +15,7 @@ import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, kst } from './lib'
import { useRegion } from './regionContext'
import { useMyTalks } from './talkState'
import { useSheet } from './sheetContext'
import { HeartIcon } from './svg'
import { Avatar, TAP44 } from './ui'
@@ -44,7 +45,7 @@ function slotWord(iso: string) {
function useRefreshTalks() {
const queryClient = useQueryClient()
return () => queryClient.invalidateQueries({ queryKey: [{ _id: 'listTalks' }] })
return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') })
}
function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
@@ -158,7 +159,8 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
)
}
function TalkRow({ t }: { t: TalkData }) {
/** onGone: 내 글을 지웠을 때. 목록을 다시 받아도 빠지지 않는 곳(방금 쓴 글)에서 직접 뺀다 */
function TalkRow({ t, onGone }: { t: TalkData; onGone?: () => void }) {
const { loggedIn } = useAuth()
const { open } = useSheet()
const refresh = useRefreshTalks()
@@ -225,7 +227,7 @@ function TalkRow({ t }: { t: TalkData }) {
{menu === 'done' ? (
<span className="text-[#1f9d62]">처리했어요</span>
) : t.mine ? (
<button type="button" onClick={() => remove.mutate({ path: { talk_id: t.talk_id } }, after)} disabled={remove.isPending} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
<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' ? (
@@ -270,10 +272,31 @@ export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void })
}
/** 피드에 끼우는 글 한 장 */
export function TalkCard({ t }: { t: TalkData }) {
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} />
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} onGone={onGone} />
</article>
)
}
/** 내 정보 창의 내가 쓴 글 */
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>
)
}
+25 -4
View File
@@ -1,12 +1,33 @@
import { useInfiniteQuery } from '@tanstack/react-query'
import { listTalksInfiniteOptions } from '../api/client/@tanstack/react-query.gen'
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions } from '../api/client/@tanstack/react-query.gen'
import { useRegion } from './regionContext'
/** 사람들이 쓴 글. 오늘 피드에 운영 포스트 사이사이 섞는다 */
/** 사람들이 쓴 글. 오늘 피드에 운영 포스트 사이사이 섞고, 남은 글은 피드 끝에 이어 붙인다 */
export function useFeedTalks() {
const { region } = useRegion()
const list = useInfiniteQuery({
...listTalksInfiniteOptions(),
...listTalksInfiniteOptions({ query: { region: region.code } }),
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
})
return list.data?.pages.flatMap((p) => p.talks ?? []) ?? []
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
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,
}
}
+54
View File
@@ -0,0 +1,54 @@
import type { WeatherWhy } from '../api/client/types.gen'
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[] }
// 조건마다 같은 색을 막대 칸과 아래 줄 점에 같이 써서 이어 보이게
const COLOR: Record<string, string> = {
기온: '#ff7a45',
비: '#4f97e3',
햇볕: '#ffb02e',
바람: '#5fb8b0',
습도: '#8e8cf0',
미세먼지: '#b59a86',
}
const colorOf = (label: string) => COLOR[label] ?? '#9aa3b8'
/** 날씨 점수 근거: 비중만큼 나눈 막대(채운 만큼 얻은 점수)와 조건별 지금 값 */
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>
<p className="m-0 mt-3 text-[13px] leading-relaxed font-semibold text-(--ink2)">
조건마다 점수를 매겨 비중대로 합쳐요. 유난히 아쉬운 조건이 있으면 조금 더 깎고, 모든 조건이 완벽할 때만 만점이 나와요.
</p>
</div>
)
}
+11 -1
View File
@@ -83,7 +83,17 @@ for (const r of regionPages) {
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><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>` : ''}`,
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>` : ''}`,
})
}