Compare commits

..
Author SHA1 Message Date
minaChoi cc5ecd7bbf Merge remote-tracking branch 'origin/main' into feat/apps-in-toss 2026-10-27 20:03:38 +09:00
minaChoi 7f5441a512 Merge branch 'feat/youtube-shorts' — 사파리 쇼츠 시작 영상 2026-10-27 20:03:27 +09:00
minaChoi 694ea85ed3 fix: 아이폰 사파리에서 쇼츠를 누르면 첫 영상부터 열리던 문제 — 시작 영상으로 옮긴 뒤 한 번 더 맞추고, 옮기기 전엔 보이는 칸 변화를 무시 2026-10-27 20:03:27 +09:00
minaChoi 597017bd37 Merge remote-tracking branch 'origin/main' into feat/apps-in-toss 2026-10-27 19:56:17 +09:00
minaChoi ef61a5bf73 Merge branch 'feat/youtube-shorts' — 쇼츠 멈춤 없앰 2026-10-27 19:56:06 +09:00
minaChoi 74805aa829 fix: 쇼츠에서 멈춤 명령을 없앰 — 앞뒤 영상은 소리 없이 계속 틀어 두고 넘어오면 처음부터, 톡 누르면 릴스처럼 소리 켜기·끄기 (멈췄다 틀면 유튜브가 재생·멈춤 버튼을 띄워서) 2026-10-27 19:56:06 +09:00
minaChoi 89221535ba Merge remote-tracking branch 'origin/main' into feat/apps-in-toss 2026-10-27 19:45:52 +09:00
minaChoi 5f79df1973 Merge branch 'feat/youtube-shorts' — 쇼츠 줄 재생 버튼 숨김 2026-10-27 19:45:41 +09:00
minaChoi 942b652e56 fix: 오늘 화면 쇼츠 줄 첫 카드도 재생이 시작된 뒤에만 영상을 보임 — 자동재생이 막히면 유튜브 재생 버튼 대신 표지 2026-10-27 19:45:41 +09:00
minaChoi 8ccdf22882 Merge remote-tracking branch 'origin/main' into feat/apps-in-toss 2026-10-27 19:30:27 +09:00
minaChoi e962304107 chore: 쇼츠 빈 줄 정리 2026-10-27 19:30:27 +09:00
minaChoi f24e790bd7 Merge branch 'feat/youtube-shorts' — 쇼츠 토스판과 같은 코드 2026-10-27 19:30:15 +09:00
minaChoi d38cfc7229 fix: 쇼츠 코드를 토스판과 같게 — 토스도 앞뒤 미리 받기·소리 없이 자동재생, 재생 신호가 안 오는 토스만 1초 뒤 영상을 보임 (웹 동작은 그대로) 2026-10-27 19:30:15 +09:00
minaChoi 8191881f6a fix: 토스판 쇼츠를 웹과 같이 — 소리 없이 자동재생·재생 버튼 없음·앞뒤 미리 받기·손가락으로 넘기기·소리 켜기 버튼, 재생 신호가 안 오는 토스만 1초 뒤 영상을 보임 2026-10-27 19:27:00 +09:00
minaChoi 7ffeecbb4f fix: 토스판 쇼츠도 릴스처럼 다음 영상을 미리 받아 둠 — 다음 영상은 멈춘 채 띄워 두고 넘어오면 재생, 지난 영상은 내려 소리가 겹치지 않게 2026-10-27 19:22:26 +09:00
minaChoi 4875ea4333 Merge remote-tracking branch 'origin/main' into feat/apps-in-toss
# Conflicts:
#	frontend/src/b/BLayout.tsx
#	frontend/src/b/Shorts.tsx
#	frontend/src/b/talk.tsx
2026-10-27 19:08:51 +09:00
minaChoi b346af7fef Merge branch 'feat/youtube-shorts' — 단풍 지도 포스트 맨 앞 2026-10-27 19:05:34 +09:00
minaChoi 340b30cc8b fix: 단풍 지도를 피드 맨 위가 아니라 포스트 맨 앞으로 — 쇼츠·글쓰기·오늘의 각은 원래 자리 2026-10-27 19:05:33 +09:00
minaChoi fd67c2b45f Merge branch 'feat/youtube-shorts' — 내 각 개편, 이야기 내 글·무한 스크롤, 공유 이미지 얇은 띠, 행사 주소 2026-10-27 18:55:43 +09:00
minaChoi ffe6153148 feat: 내 각 아이콘·상세, 이야기 내 글·무한 스크롤, 공유 이미지 얇은 띠, 행사 주소 수집
- 내 각: 아이콘 고르기(my_gak.icon), 카드는 아이콘·점수·아쉬운 조건만, 눌러서 상세(시간대·조건별 점수), 공유는 공통 공유 창
- 이야기: 오늘 쓴 내 글 묶음, '내 글' 칩·탭, 무한 스크롤, 사진 카메라 버튼, 지우기 확인, ⋯ 메뉴 하트 옆, 글 시간 서버 계산(1일 전)
- 공유 이미지: 1:1·4:5 는 아래 얇은 띠 한 줄로 카드를 크게
- 행사: 수집 때 주소 저장(event.address), 행사 포스트에 장소·주소·기간
- 히어로 말풍선 '오늘 낮은 / 내일 낮은', 내일을 볼 때 배경도 따라감, 달 보름 순간이 낮이면 뜨는 시각으로
- 단풍 지도 피드 맨 위, 행사·계절 띠 포스트 틀 되돌림, 쇼츠 홈 버튼 가림·닫기 버튼, 하단 여백, 회색 글자 대비
- 토스 앱에선 쇼츠 플레이어를 하나만 띄움
2026-10-27 18:55:42 +09:00
minaChoi 3a249c509d Merge branch 'feat/youtube-shorts' — 각 포스트 오늘·내일·주말 점수, 밤 화면 포스트 색, 동네 글 묶음 1개부터 (1557ba4)
겹친 곳: 히어로 아이콘 간격은 main 방식(버튼 좌우 5px) 하나로, 달 포스트는 밤하늘·행사는 사진 있을 때만 밤하늘, 토스에선 첫 이야기 카드 숨김 유지
2026-10-27 16:26:31 +09:00
minaChoi 55edc037fb Merge branch 'revert/write-login-once' — 쓰기 버튼 로그인 창 누를 때마다 2026-10-27 15:48:37 +09:00
minaChoi a17cef201d fix: 쓰기 버튼 로그인 창을 다시 누를 때마다 띄우기 — '한 번만 띄우고 안내 흔들기'(0bc8ca0)를 되돌림 2026-10-27 15:47:14 +09:00
minaChoi 0414160520 Merge branch 'fix/write-login-once' — 쓰기 버튼 로그인 창은 한 번만 2026-10-27 15:41:58 +09:00
minaChoi 0bc8ca02a4 fix: 쓰기 버튼(쓰기 칸·사진·올리기·첫 이야기 카드)으로 뜨는 로그인 창은 이번 방문에 한 번만 — 닫은 뒤엔 '로그인하면 쓸 수 있어요'만 흔들어 알림 2026-10-27 15:41:57 +09:00
minaChoi 1557ba42c4 fix: 각 포스트·밤 화면·히어로 아이콘·동네 글 묶음 손봄
- 각 포스트: 각마다 같던 근거 표·요약 줄을 빼고 오늘·내일·주말 점수 칸(각 상세와 같은 값), 작은 화면에서 점수·그림 줄임
- 밤 화면에서도 포스트 본문은 낮 색 그대로, 어두운 각 배경(캠핑·별보기·산책)과 행사 밤하늘 배경 뺌
- 히어로 좋아요·댓글·보내기 간격·높이 맞춤
- 동네 사람들 묶음을 글 1개부터 보이게 (3개 미만이면 자기 글도 안 보이던 문제)
- QA 체크리스트에 쇼츠·각 포스트 결과, TODO 에 쇼츠 공유 링크 빈 화면
2026-10-27 15:20:35 +09:00
minaChoi 9af3407546 Merge branch 'fix/sheet-slide' — 아래 창 열기·닫기 애니메이션 2026-10-27 15:08:40 +09:00
minaChoi 117de90c3e fix: 아래 창(로그인 등)이 열리고 닫힐 때 버벅여 보이던 것 — 반투명으로 40px만 올라와 뒤 탭 바가 비쳤고 닫힐 땐 툭 사라지며 쓰기 칸 테두리가 번쩍였음, 불투명하게 아래에서 끝까지 올라오고 내려가며 닫히게 2026-10-27 15:08:40 +09:00
minaChoi be60551f49 Merge branch 'fix/composer-login-no-keyboard' — 로그인 전 쓰기 칸은 키보드 없이 로그인 창 2026-10-27 14:55:46 +09:00
minaChoi dcf2fe5a53 fix: 로그인 안 한 채 쓰기 칸을 누르면 로그인 창이 버벅이던 것 — 칸에 포커스가 가며 키보드가 떴다 내려갔음, 로그인 전엔 읽기 전용으로 두고 누르면 로그인 창 2026-10-27 14:55:46 +09:00
minaChoi 132301dc28 Merge branch 'fix/google-button-skeleton' — 로그인 창 구글 버튼 스켈레톤 2026-10-27 14:49:42 +09:00
minaChoi dd133c9d52 fix: 로그인 창 구글 버튼 자리에 스켈레톤 — 빈칸에 버튼이 늦게 툭 튀어나와 버벅이는 것처럼 보이던 것, 다 그려지면 부드럽게 바꿔 보임 2026-10-27 14:49:41 +09:00
minaChoi 5459b97ba0 Merge branch 'fix/foliage-card-slide2' — 단풍 카드 2번째 장 가림, 히어로 아이콘 간격, 로그인 창 첫 열기 버벅임, 토스 글 종류 필터 되돌림 2026-10-27 14:40:33 +09:00
minaChoi 1908433e46 fix: 토스에서 가리던 글 종류(카드뉴스 등) 다시 보이게 — 토스 번들이 업데이트돼 d3d872b 필터를 되돌림 2026-10-27 14:40:33 +09:00
minaChoi 7dcd6c6a4c fix: 로그인 창을 처음 열 때 버벅이던 것 줄임 — 구글 로그인 스크립트는 한가할 때 미리 받고, 구글 버튼과 뒤 화면 멈추기는 창이 다 올라온 뒤에 2026-10-27 14:39:41 +09:00
minaChoi 7d84226105 fix: 히어로 하트·댓글·보내기 간격이 숫자가 붙으면 어긋나던 문제 — 버튼마다 좌우 여백을 같게 2026-10-27 14:39:41 +09:00
minaChoi c45940c358 fix: 피드 단풍 지도 카드 2번째 장(지금 가기 좋은 곳) 왼쪽이 가려지던 문제 — 가운데 맞추려 민 지도가 옆 장을 덮었음, 1번째 장 밖은 자름 2026-10-27 14:29:34 +09:00
minaChoi 09e8b4734a Merge branch 'feat/app-moon-bot' — 앱 히어로·달 포스트 실제 달 모양, 캐릭터 댓글 표시 2026-10-27 14:05:03 +09:00
minaChoi a87f245547 feat: 앱도 웹과 같이 — 히어로·달 포스트를 오늘 밤 실제 달 모양으로(저녁엔 노을빛, 어두운 달이면 흰 점수), 캐릭터 댓글에 '날씨각' 표시·신고 메뉴 없음 2026-10-27 14:05:03 +09:00
minaChoi 197fafdc02 Merge branch 'fix/login-sheet-loop' — 로그인 안 한 채 쓰기 칸 누르면 로그인 창이 닫혀도 다시 열리던 문제 2026-10-27 13:25:43 +09:00
minaChoi 77cfb04808 feat: 토스판 첫 실행 인트로 다시 넣음 (51e0c06 되돌림) — 토스 로그인을 다시 켜서 검수 의견대로 로그인 전에 서비스 소개 2026-10-27 08:30:54 +09:00
minaChoi 9dc7a52383 feat: 토스판 토스 로그인 다시 켬 (0144a64 되돌림) — 로그인 버튼·글쓰기 칸·글 더보기, 두 번째 내 각 저장 때 로그인 창 2026-10-27 08:30:41 +09:00
minaChoi 130f14e96a fix: 토스판 쇼츠를 열거나 넘길 때 검은 플레이어가 깜빡임 — 재생 상태가 안 오므로 플레이어 문서가 뜨고 1초 뒤까지 표지로 가렸다가 서서히 띄움 2026-10-26 16:41:15 +09:00
minaChoi b240ecb180 fix: 토스판 쇼츠는 유튜브 기본 플레이어로 자동재생 — 토스 웹뷰엔 플레이어 재생 상태가 안 와서 숨기기·명령·재생 아이콘을 쓰지 않고, 소리 켠 채 재생(막히면 유튜브 재생 버튼), 넘기기는 이전·다음 버튼. 웹은 그대로 2026-10-26 16:33:50 +09:00
minaChoi 21bfa2a3ff fix: 토스판 쇼츠는 유튜브 기본 플레이어로 — 토스 웹뷰엔 재생 상태가 안 와서 자동재생·숨기기 대신 재생 버튼을 처음부터 보이고, 카드는 표지와 재생 아이콘, 쇼츠 페이지에 이전·다음 버튼 2026-10-26 16:24:45 +09:00
minaChoi 61023d090e fix: 쇼츠 재생 아이콘을 플레이어가 보낸 재생 상태로만 판단 — 늦은 자동재생과 누르기가 겹쳐도 어긋나지 않게, 카드 아이콘은 플레이어 위에, 넘기기 판은 재생 명령이 막힌 때만 치움 2026-10-26 16:18:09 +09:00
minaChoi 2fd6fcbd06 fix: 쇼츠 재생 멈춤 표시를 effect 안 setState 없이 2026-10-26 16:12:02 +09:00
minaChoi acb6c4d717 fix: 쇼츠가 저절로 재생되지 않으면(토스 웹뷰) 2초 뒤 플레이어를 보이고 재생 아이콘을 띄워 직접 눌러 재생 2026-10-26 16:11:49 +09:00
minaChoi 81b17f057f fix: 토스판 쇼츠 재생 — 웹뷰 기본값(자동재생·화면 안 재생 막음)을 풀어 줌 2026-10-26 16:03:54 +09:00
minaChoi 51e0c06f2d fix: 토스판 첫 실행 인트로 뺌 — 토스 로그인을 뺐으니 로그인 전 소개 화면이 필요 없음 2026-10-26 15:52:06 +09:00
minaChoi 0a84f34729 Merge remote-tracking branch 'origin/main' into feat/apps-in-toss 2026-10-26 15:46:15 +09:00
minaChoi 2627dd2685 Merge remote-tracking branch 'origin/main' into feat/apps-in-toss 2026-10-26 15:33:39 +09:00
50 changed files with 1085 additions and 422 deletions

No files matched your search

+2
View File
@@ -62,6 +62,7 @@
| [ ] | 오늘 화면 쇼츠 줄 — YouTube Data API 키(`YOUTUBE_API_KEY`) 발급해 운영 .env 에 넣기. 없으면 `youtube_shorts`(영상 ID 3개 고정)만 나와 새 쇼츠가 자동으로 안 붙음 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 채널 RSS가 404라 키 없이 채널 목록을 못 받음 | `backend/config/settings.py`, `backend/services/shorts_service.py` | | [ ] | 오늘 화면 쇼츠 줄 — YouTube Data API 키(`YOUTUBE_API_KEY`) 발급해 운영 .env 에 넣기. 없으면 `youtube_shorts`(영상 ID 3개 고정)만 나와 새 쇼츠가 자동으로 안 붙음 (https://console.cloud.google.com/apis/library/youtube.googleapis.com) | 채널 RSS가 404라 키 없이 채널 목록을 못 받음 | `backend/config/settings.py`, `backend/services/shorts_service.py` |
| [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` | | [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` |
| [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` | | [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` |
| [ ] | 쇼츠 API 실패·빈 목록일 때 공유 링크로 들어오면 남색 빈 화면만 보임 — 그 영상 ID 하나라도 띄우거나 × 버튼·안내 문구 보이기 | 10/27 QA 실패 (`items` 가 비면 빈 div 만 그림) | `frontend/src/b/Shorts.tsx` |
| [ ] | 쇼츠 자동재생 아이폰 사파리 실기기 확인 — 소리 꺼도 자동재생을 막는다는 보고 있음 | 헤드리스 크롬에서만 확인 | `frontend/src/b/Shorts.tsx` | | [ ] | 쇼츠 자동재생 아이폰 사파리 실기기 확인 — 소리 꺼도 자동재생을 막는다는 보고 있음 | 헤드리스 크롬에서만 확인 | `frontend/src/b/Shorts.tsx` |
| [x] | 단풍 명소 `남이섬`이 두 번 들어감(절정 10-25·10-27) — 10-27(화목원) 쪽 지움, 67곳 | 10/27 전체 점검 | `frontend/seo/foliage_2026.json` | | [x] | 단풍 명소 `남이섬`이 두 번 들어감(절정 10-25·10-27) — 10-27(화목원) 쪽 지움, 67곳 | 10/27 전체 점검 | `frontend/seo/foliage_2026.json` |
| [x] | 날짜 따라 깨지던 테스트 2개 — 노을 칸은 그날 해 지는 시각으로, 방위각은 한 해 범위(240~300°)로 확인 | 10/27 전체 점검 | `backend/tests/test_weather_today.py`, `backend/tests/test_sky_api.py` | | [x] | 날짜 따라 깨지던 테스트 2개 — 노을 칸은 그날 해 지는 시각으로, 방위각은 한 해 범위(240~300°)로 확인 | 10/27 전체 점검 | `backend/tests/test_weather_today.py`, `backend/tests/test_sky_api.py` |
@@ -240,6 +241,7 @@
| [ ] | 토스 로그인 문구 검토 — '토스로 로그인', '토스로 로그인했어요', '토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.', 기본 닉네임 '토스1234'(userKey 끝 4자리), 로그인 창 '날씨각 로그인'·'로그인하면 동네 이야기를 쓰고 내 각을 저장할 수 있어요', 인트로 '오늘 날씨에 맞는 일을 점수로 알려 줘요'·'세차·빨래·러닝 각 점수'·'오늘 노을이 예쁜 시간'·'이번 주말 가까운 행사'·'시작하기'(10/24) | 토스 로그인 구현(10/14) | `frontend/src/b/Sheets.tsx`, `backend/services/auth_service.py` | | [ ] | 토스 로그인 문구 검토 — '토스로 로그인', '토스로 로그인했어요', '토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.', 기본 닉네임 '토스1234'(userKey 끝 4자리), 로그인 창 '날씨각 로그인'·'로그인하면 동네 이야기를 쓰고 내 각을 저장할 수 있어요', 인트로 '오늘 날씨에 맞는 일을 점수로 알려 줘요'·'세차·빨래·러닝 각 점수'·'오늘 노을이 예쁜 시간'·'이번 주말 가까운 행사'·'시작하기'(10/24) | 토스 로그인 구현(10/14) | `frontend/src/b/Sheets.tsx`, `backend/services/auth_service.py` |
| [ ] | 토스판 첫 실행에 인트로와 위치 권한 창이 같이 뜸 — 위치 권한은 앱이 뜨자마자 물어서 인트로 위에 겹칠 수 있음. '시작하기' 뒤로 미룰지 토스 앱에서 확인 | 인트로 추가 (10/24) | `frontend/src/b/region.tsx`, `frontend/src/b/tossIntro.tsx` | | [ ] | 토스판 첫 실행에 인트로와 위치 권한 창이 같이 뜸 — 위치 권한은 앱이 뜨자마자 물어서 인트로 위에 겹칠 수 있음. '시작하기' 뒤로 미룰지 토스 앱에서 확인 | 인트로 추가 (10/24) | `frontend/src/b/region.tsx`, `frontend/src/b/tossIntro.tsx` |
| [ ] | 메뉴의 '로그인하면 좋아요·댓글을 쓸 수 있어요' — 좋아요·댓글은 로그인 없이 됨(10/21 결정)이라 문구가 틀림 | 인트로 추가 중 발견 (10/24) | `frontend/src/b/Sheets.tsx:1117` | | [ ] | 메뉴의 '로그인하면 좋아요·댓글을 쓸 수 있어요' — 좋아요·댓글은 로그인 없이 됨(10/21 결정)이라 문구가 틀림 | 인트로 추가 중 발견 (10/24) | `frontend/src/b/Sheets.tsx:1117` |
| [ ] | 토스 웹뷰에서 유튜브 플레이어가 보내는 재생 상태(postMessage)가 페이지에 오지 않음 — 원인 미확인(origin 불일치? 토스 브리지?). 그래서 토스판 쇼츠는 숨기기·명령 없이 유튜브 기본 플레이어 사용. 원인 찾으면 웹과 같은 UI로 합칠 수 있음 | 토스판 쇼츠 재생 안 됨 (10/26) | `frontend/src/b/Shorts.tsx` |
| [ ] | 댓글 신고·차단 — 앱인토스 필수 아님(신고·차단 필수는 채팅·만남·중고거래만, 서비스 오픈 정책·서비스별 주의사항). 만들지 않기로 함(10/14). 검수에서 요청이 오면 만든다 | 토스 로그인 구현(10/14) | | | [ ] | 댓글 신고·차단 — 앱인토스 필수 아님(신고·차단 필수는 채팅·만남·중고거래만, 서비스 오픈 정책·서비스별 주의사항). 만들지 않기로 함(10/14). 검수에서 요청이 오면 만든다 | 토스 로그인 구현(10/14) | |
| [x] | 각 늘리기 53→68 — 리서치로 고른 8개(한강·놀이공원·데이트·곱슬머리·보일러·선크림·모기·테니스) + 감성 7개(효도·감사·선물·파티·게임·셀카·센치), 아이콘 15개(Codex) | 사용자 요청 (10/20, 리서치 https://claude.ai/artifact/3ZQbtGKRLVZViRRC5voBzY) | `backend/seed/index_definition.json`, `frontend/public/icons/`, `frontend/src/b/lib.ts` | | [x] | 각 늘리기 53→68 — 리서치로 고른 8개(한강·놀이공원·데이트·곱슬머리·보일러·선크림·모기·테니스) + 감성 7개(효도·감사·선물·파티·게임·셀카·센치), 아이콘 15개(Codex) | 사용자 요청 (10/20, 리서치 https://claude.ai/artifact/3ZQbtGKRLVZViRRC5voBzY) | `backend/seed/index_definition.json`, `frontend/public/icons/`, `frontend/src/b/lib.ts` |
| [ ] | **[결정 필요]** 한강각·놀이공원각이 강·놀이공원 없는 동네에도 나옴 — 각을 지역별로 가려 보여 주는 기능이 없음(한강밤바람각도 같음). 서울·한강 인접 구만 보일지 | 새 각 추가 중 발견 (10/20) | `backend/seed/index_definition.json`, `backend/services/index_service.py` | | [ ] | **[결정 필요]** 한강각·놀이공원각이 강·놀이공원 없는 동네에도 나옴 — 각을 지역별로 가려 보여 주는 기능이 없음(한강밤바람각도 같음). 서울·한강 인접 구만 보일지 | 새 각 추가 중 발견 (10/20) | `backend/seed/index_definition.json`, `backend/services/index_service.py` |
+2
View File
@@ -246,6 +246,7 @@ class Event(Base):
area: Mapped[Optional[str]] = mapped_column(String(20), nullable=True) area: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
name: Mapped[str] = mapped_column(String(60)) name: Mapped[str] = mapped_column(String(60))
place_name: Mapped[str] = mapped_column(String(60)) place_name: Mapped[str] = mapped_column(String(60))
address: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
icon: Mapped[str] = mapped_column(String(30), default="fireworks") icon: Mapped[str] = mapped_column(String(30), default="fireworks")
start_date: Mapped[date] = mapped_column(Date) start_date: Mapped[date] = mapped_column(Date)
end_date: Mapped[date] = mapped_column(Date) end_date: Mapped[date] = mapped_column(Date)
@@ -447,6 +448,7 @@ class MyGak(Base):
my_gak_id: Mapped[int] = mapped_column(BigInteger, primary_key=True) my_gak_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True)) user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
name: Mapped[str] = mapped_column(String(12)) name: Mapped[str] = mapped_column(String(12))
icon: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
rule: Mapped[dict] = mapped_column(JSONB) rule: Mapped[dict] = mapped_column(JSONB)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+3 -2
View File
@@ -1,4 +1,5 @@
import uuid import uuid
from typing import Optional
from sqlalchemy import delete, func, select from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
@@ -13,8 +14,8 @@ class MyGakCRUD:
async def count(self, s: AsyncSession, user_id: uuid.UUID) -> int: async def count(self, s: AsyncSession, user_id: uuid.UUID) -> int:
return await s.scalar(select(func.count()).select_from(MyGak).where(MyGak.user_id == user_id)) return await s.scalar(select(func.count()).select_from(MyGak).where(MyGak.user_id == user_id))
async def add(self, s: AsyncSession, user_id: uuid.UUID, name: str, rule: dict) -> MyGak: async def add(self, s: AsyncSession, user_id: uuid.UUID, name: str, rule: dict, icon: Optional[str] = None) -> MyGak:
row = MyGak(user_id=user_id, name=name, rule=rule) row = MyGak(user_id=user_id, name=name, rule=rule, icon=icon)
s.add(row) s.add(row)
await s.flush() await s.flush()
return row return row
+3 -2
View File
@@ -48,11 +48,12 @@ class WeekCRUD:
if not rows: if not rows:
return return
# 출처마다 이름에 "<" 같은 HTML 문자가 섞여 와서, 넣기 전에 푼다 # 출처마다 이름에 "<" 같은 HTML 문자가 섞여 와서, 넣기 전에 푼다
rows = [{**r, "name": plain(r["name"]), "place_name": plain(r["place_name"])} for r in rows] # 주소는 출처마다 있거나 없어서, 없는 행도 칸을 맞춰 넣는다
rows = [{**r, "name": plain(r["name"]), "place_name": plain(r["place_name"]), "address": r.get("address")} for r in rows]
stmt = insert(Event).values(rows) stmt = insert(Event).values(rows)
await s.execute(stmt.on_conflict_do_update( await s.execute(stmt.on_conflict_do_update(
index_elements=["source_id"], index_elements=["source_id"],
set_={k: stmt.excluded[k] for k in ("name", "place_name", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon", "kind", "icon")}, set_={k: stmt.excluded[k] for k in ("name", "place_name", "address", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon", "kind", "icon")},
)) ))
async def replace_manual_events(self, s: AsyncSession, rows: list[dict]) -> None: async def replace_manual_events(self, s: AsyncSession, rows: list[dict]) -> None:
+2
View File
@@ -316,6 +316,7 @@ CREATE TABLE IF NOT EXISTS public.my_gak (
created_at TIMESTAMPTZ NOT NULL DEFAULT now() created_at TIMESTAMPTZ NOT NULL DEFAULT now()
); );
CREATE INDEX IF NOT EXISTS ix_my_gak_user ON public.my_gak (user_id); CREATE INDEX IF NOT EXISTS ix_my_gak_user ON public.my_gak (user_id);
ALTER TABLE public.my_gak ADD COLUMN IF NOT EXISTS icon VARCHAR(32) NULL; -- 고른 아이콘 (각 아이콘 이름, 없으면 기본)
-- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다 -- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다
CREATE TABLE IF NOT EXISTS public.talk ( CREATE TABLE IF NOT EXISTS public.talk (
@@ -465,6 +466,7 @@ ALTER TABLE public.event ADD COLUMN IF NOT EXISTS image_url VARCHAR(500) NULL;
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lat NUMERIC(8,5) NULL; ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lat NUMERIC(8,5) NULL;
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lon NUMERIC(8,5) NULL; ALTER TABLE public.event ADD COLUMN IF NOT EXISTS lon NUMERIC(8,5) NULL;
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS kind SMALLINT NOT NULL DEFAULT 1; ALTER TABLE public.event ADD COLUMN IF NOT EXISTS kind SMALLINT NOT NULL DEFAULT 1;
ALTER TABLE public.event ADD COLUMN IF NOT EXISTS address VARCHAR(120) NULL; -- 도로명 주소 (출처에 있을 때만)
-- 공휴일 (주말·행사 탭의 "개천절"). -- 공휴일 (주말·행사 탭의 "개천절").
CREATE TABLE IF NOT EXISTS public.holiday ( CREATE TABLE IF NOT EXISTS public.holiday (
+2 -13
View File
@@ -1,10 +1,10 @@
from typing import Optional from typing import Optional
from fastapi import APIRouter, Depends, Path, Query, Request from fastapi import APIRouter, Depends, Path, Query
from common.auth import optional_user from common.auth import optional_user
from common.database.model.models import User from common.database.model.models import User
from common.enums import ErrorType, PostType from common.enums import ErrorType
from common.liker import Liker, liker from common.liker import Liker, liker
from common.models.errors import error_info from common.models.errors import error_info
from router.v1.feed.protocol import Res_Feed, Res_Post from router.v1.feed.protocol import Res_Feed, Res_Post
@@ -13,26 +13,15 @@ from services.reaction_service import ReactionService
router = APIRouter(prefix="/v1/feed", tags=["feed"]) router = APIRouter(prefix="/v1/feed", tags=["feed"])
# 토스에 올라간 10/13 번들은 UV 까지만 알아서, 그 뒤에 생긴 글 종류(카드뉴스 등)가 오면 흰 화면이 된다
TOSS_KNOWN_MAX = PostType.UV.value
def _from_toss(request: Request) -> bool:
ref = request.headers.get("origin") or request.headers.get("referer") or ""
return "AppsInToss" in request.headers.get("user-agent", "") or ".tossmini.com" in ref
@router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠") @router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠")
async def get_feed( async def get_feed(
request: Request,
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
service: FeedService = Depends(), reactions: ReactionService = Depends(), service: FeedService = Depends(), reactions: ReactionService = Depends(),
) -> Res_Feed: ) -> Res_Feed:
err, feed = await service.feed(region) err, feed = await service.feed(region)
if err is not ErrorType.SUCCESS: if err is not ErrorType.SUCCESS:
return Res_Feed(result=error_info(err)) return Res_Feed(result=error_info(err))
if _from_toss(request):
feed = feed.model_copy(update={"posts": [p for p in feed.posts if p.post_type.value <= TOSS_KNOWN_MAX]})
pinned = [x for x in (feed.hero_post, feed.gak_post, feed.foliage_post, feed.events_post, feed.season_post) if x is not None] pinned = [x for x in (feed.hero_post, feed.gak_post, feed.foliage_post, feed.events_post, feed.season_post) if x is not None]
ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned] ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned]
counts = await reactions.counts(ids) counts = await reactions.counts(ids)
+2 -1
View File
@@ -5,6 +5,7 @@ from pydantic import Field
from common.enums import PostType, SkySituation, SlotTone from common.enums import PostType, SkySituation, SlotTone
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
from router.v1.index.protocol import TrendPoint
class Row(WebPacketProtocol): class Row(WebPacketProtocol):
@@ -51,8 +52,8 @@ class GakSlide(WebPacketProtocol):
score: int score: int
line: str line: str
summary: str summary: str
rows: list[Row] = Field(default=[], description="점수 근거: 비중 큰 날씨 조건부터 네 개와 지금 값 (기온 · 체감 18°)")
say: Optional[str] = Field(default=None, description="점수 구간 설명 문장 (seed sentences)") say: Optional[str] = Field(default=None, description="점수 구간 설명 문장 (seed sentences)")
trend: list[TrendPoint] = Field(default=[], description="오늘 · 내일 · 이번 주말 점수 (각 상세 날짜 칸과 같은 값)")
class Cut(WebPacketProtocol): class Cut(WebPacketProtocol):
+2 -2
View File
@@ -14,7 +14,7 @@ router = APIRouter(prefix="/v1/my-gak", tags=["my-gak"])
def _data(g: MyGak) -> MyGakData: def _data(g: MyGak) -> MyGakData:
return MyGakData(my_gak_id=g.my_gak_id, name=g.name, rule=MyGakRule(**g.rule)) return MyGakData(my_gak_id=g.my_gak_id, name=g.name, icon=g.icon, rule=MyGakRule(**g.rule))
@router.get("", response_model=Res_MyGakList, response_model_exclude_none=True, summary="내 각 목록 (로그인하지 않았으면 빈 목록)") @router.get("", response_model=Res_MyGakList, response_model_exclude_none=True, summary="내 각 목록 (로그인하지 않았으면 빈 목록)")
@@ -29,7 +29,7 @@ async def list_my_gak(user: Optional[User] = Depends(optional_user), service: My
@router.post("", response_model=Res_MyGak, response_model_exclude_none=True, summary="이름과 날씨 조건으로 내 각 만들기") @router.post("", response_model=Res_MyGak, response_model_exclude_none=True, summary="이름과 날씨 조건으로 내 각 만들기")
async def add_my_gak(req: Req_MyGak, user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_MyGak: async def add_my_gak(req: Req_MyGak, user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_MyGak:
err, g = await service.add(user, req.name, req.rule.model_dump(exclude_none=True)) err, g = await service.add(user, req.name, req.rule.model_dump(exclude_none=True), req.icon)
return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g)) return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g))
+3
View File
@@ -29,11 +29,13 @@ class MyGakRule(WebPacketProtocol):
class MyGakData(WebPacketProtocol): class MyGakData(WebPacketProtocol):
my_gak_id: int my_gak_id: int
name: str name: str
icon: Optional[str] = Field(None, description="고른 아이콘 (각 아이콘 이름)")
rule: MyGakRule rule: MyGakRule
class Req_MyGak(Req_WebPacketProtocol): class Req_MyGak(Req_WebPacketProtocol):
name: str = Field(min_length=1, max_length=12, description="내 각 이름 (끝에 '각'이 없으면 붙인다)") name: str = Field(min_length=1, max_length=12, description="내 각 이름 (끝에 '각'이 없으면 붙인다)")
icon: Optional[str] = Field(None, pattern=r"^[a-z_]{1,32}$", description="고른 아이콘 (각 아이콘 이름)")
rule: MyGakRule rule: MyGakRule
@@ -66,6 +68,7 @@ class MyGakScore(WebPacketProtocol):
slot: Optional[Slot] = Field(None, description="score 가 어느 시간대 점수인지") slot: Optional[Slot] = Field(None, description="score 가 어느 시간대 점수인지")
slots: dict[str, int] = Field(default={}, description="고른 시간대별 점수 (아침·낮·저녁·밤 순)") slots: dict[str, int] = Field(default={}, description="고른 시간대별 점수 (아침·낮·저녁·밤 순)")
reasons: list[str] = Field(default=[], description="score 근거: 조건마다 그 시간대 실제 값") reasons: list[str] = Field(default=[], description="score 근거: 조건마다 그 시간대 실제 값")
factors: dict[str, int] = Field(default={}, description="조건별 점수 0~100 (temp·rain·wind·air·humidity, reasons 와 같은 순서)")
class Res_MyGakScore(Res_WebPacketProtocol): class Res_MyGakScore(Res_WebPacketProtocol):
+1
View File
@@ -22,6 +22,7 @@ class TalkData(WebPacketProtocol):
liked: bool liked: bool
mine: bool mine: bool
created_at: datetime created_at: datetime
ago: str = Field(description="쓴 지 얼마나 됐는지 (방금 · 12분 전 · 3시간 전 · 1일 전 · 2주 전)")
class Req_Talk(Req_WebPacketProtocol): class Req_Talk(Req_WebPacketProtocol):
+3 -2
View File
@@ -11,10 +11,10 @@ from common.enums import ErrorType, TalkTopic
from common.liker import Liker, liker from common.liker import Liker, liker
from common.models.errors import error_info from common.models.errors import error_info
from common.models.gmodel import Res_WebPacketProtocol from common.models.gmodel import Res_WebPacketProtocol
from common.utils.kma_time import KST from common.utils.kma_time import KST, now_kst
from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkGroups, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData, TalkGroup from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkGroups, Res_TalkImage, Res_TalkLike, Res_TalkList, TalkData, TalkGroup
from services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save from services.talk_image import MAX_BYTES, URL_PREFIX, file_of, save
from services.talk_service import TalkService, TalkView from services.talk_service import TalkService, TalkView, ago_text
router = APIRouter(prefix="/v1/talk", tags=["talk"]) router = APIRouter(prefix="/v1/talk", tags=["talk"])
@@ -24,6 +24,7 @@ def _data(v: TalkView) -> TalkData:
return TalkData( return TalkData(
talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather, talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather,
body=t.body, image=t.image, topic=TalkTopic(t.topic), like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST), body=t.body, image=t.image, topic=TalkTopic(t.topic), like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST),
ago=ago_text(t.created_at, now_kst()),
) )
+3 -2
View File
@@ -106,7 +106,8 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
if start is None or end is None or end < since: if start is None or end is None or end < since:
return None return None
loc = ld.get("location") or {} loc = ld.get("location") or {}
sido = sido_of((loc.get("address") or {}).get("streetAddress", "")) address = html.unescape((loc.get("address") or {}).get("streetAddress") or "").strip()
sido = sido_of(address)
if sido is None: if sido is None:
return None return None
geo = loc.get("geo") or {} geo = loc.get("geo") or {}
@@ -115,7 +116,7 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
kind = EventKind.CONCERT kind = EventKind.CONCERT
return { return {
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": name[:60], "source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": name[:60],
"place_name": place[:60], "start_date": start, "end_date": end, "is_confirmed": True, "place_name": place[:60], "address": address[:120] or None, "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": POPUP_URL.format(id=popup_id), "image_url": None, "source_url": POPUP_URL.format(id=popup_id), "image_url": None,
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": kind, "icon": EVENT_ICON[kind], "lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": kind, "icon": EVENT_ICON[kind],
} }
+1 -1
View File
@@ -59,7 +59,7 @@ def parse_seoul_festivals(items: list[dict]) -> list[dict]:
continue continue
rows.append({ rows.append({
"source_id": f"{SOURCE_PREFIX}{it['cultcode']}", "sido_code": SEOUL, "name": name[:60], "source_id": f"{SOURCE_PREFIX}{it['cultcode']}", "sido_code": SEOUL, "name": name[:60],
"place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True, "place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "address": html.unescape(it.get("addr") or "")[:120] or None, "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": VIEW_URL.format(code=it["cultcode"]), "source_url": VIEW_URL.format(code=it["cultcode"]),
"image_url": IMAGE_URL.format(id=it["atchFileId"]) if it.get("atchFileId") else None, "image_url": IMAGE_URL.format(id=it["atchFileId"]) if it.get("atchFileId") else None,
# 이 목록은 xCoord 가 위도, yCoord 가 경도다 # 이 목록은 xCoord 가 위도, yCoord 가 경도다
+1 -1
View File
@@ -35,7 +35,7 @@ def parse_festivals(items: list[dict], sido_code: str) -> list[dict]:
continue continue
rows.append({ rows.append({
"source_id": str(it["contentid"]), "sido_code": sido_code, "name": it.get("title", "")[:60], "source_id": str(it["contentid"]), "sido_code": sido_code, "name": it.get("title", "")[:60],
"place_name": (it.get("addr1") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True, "place_name": (it.get("addr1") or "")[:60], "address": (it.get("addr1") or "")[:120] or None, "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": None, "image_url": (it.get("firstimage") or "").replace("http://", "https://", 1) or None, "source_url": None, "image_url": (it.get("firstimage") or "").replace("http://", "https://", 1) or None,
"lat": _coord(it.get("mapy")), "lon": _coord(it.get("mapx")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL], "lat": _coord(it.get("mapy")), "lon": _coord(it.get("mapx")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL],
}) })
+15 -31
View File
@@ -1,6 +1,5 @@
import asyncio import asyncio
import random import random
import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date, datetime, time, timedelta from datetime import date, datetime, time, timedelta
from typing import Optional from typing import Optional
@@ -25,6 +24,7 @@ from router.v1.feed.protocol import (
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HeroTomorrow, HourCell, HoursSlide, ImageSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide, BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HeroTomorrow, HourCell, HoursSlide, ImageSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide,
PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide, PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide,
) )
from router.v1.index.protocol import TrendPoint
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
from services.air_service import pm10_grade, pm25_grade from services.air_service import pm10_grade, pm25_grade
from services.bot_comment import fill_bot_comments from services.bot_comment import fill_bot_comments
@@ -34,7 +34,7 @@ from services.calc.moon import MoonNight, nearest, night, view_line
from services.calc.sky_score import GRADE_LABEL, sky_title from services.calc.sky_score import GRADE_LABEL, sky_title
from services.calc.sun import sun_times from services.calc.sun import sun_times
from services.hero_stats import UV_HIGH, HeroInput, discomfort_label, hero_stats, hero_status, uv_label, uv_level from services.hero_stats import UV_HIGH, HeroInput, discomfort_label, hero_stats, hero_status, uv_label, uv_level
from services.index_service import IndexBoard, IndexItem, IndexService from services.index_service import IndexBoard, IndexItem, IndexService, slot_label
from services.now_service import NowService, NowWeather from services.now_service import NowService, NowWeather
from services.season_service import SeasonService from services.season_service import SeasonService
from services.sky_service import SkyService, SkyView, day_verdict from services.sky_service import SkyService, SkyView, day_verdict
@@ -425,7 +425,7 @@ class FeedService:
cards.append(data) cards.append(data)
gak_posts = sorted((p for p in posts or [] if PostType(p.post_type) is PostType.GAK), key=lambda p: p.index_rank or 0) gak_posts = sorted((p for p in posts or [] if PostType(p.post_type) is PostType.GAK), key=lambda p: p.index_rank or 0)
for p, item in zip(gak_posts, gak): for p, item in zip(gak_posts, gak):
cards.append(self._gak(p, item)) cards.append(self._gak(p, item, board.day))
has_warning = bool(now_w and now_w.warnings) has_warning = bool(now_w and now_w.warnings)
# 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만) # 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만)
items = [i for i in board.items if i.in_season] if board else [] items = [i for i in board.items if i.in_season] if board else []
@@ -504,10 +504,11 @@ class FeedService:
return dict(post_id=p.post_id, post_type=PostType(p.post_type), like_count=p.like_count, comment_count=p.comment_count, return dict(post_id=p.post_id, post_type=PostType(p.post_type), like_count=p.like_count, comment_count=p.comment_count,
published_at=p.published_at.astimezone(KST)) published_at=p.published_at.astimezone(KST))
def _gak(self, p: Post, i: IndexItem) -> PostData: def _gak(self, p: Post, i: IndexItem, today: date) -> PostData:
d = i.definition d = i.definition
return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i), return PostData(**self._base(p), title=f"{d.name} {i.score.score}점", icon=d.icon, caption=_gak_caption(i),
slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary, rows=gak_rows(i), say=_band_sentence(d.sentences, i.score.score))], slides=[GakSlide(kind="gak", index_id=d.index_id, code=d.code, name=d.name, rank=i.rank, score=i.score.score, line=d.description, summary=i.score.summary, say=_band_sentence(d.sentences, i.score.score),
trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend])],
share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"]) share_messages=[f"오늘 {d.name} 어때? {d.name} {i.score.score}점이래"])
def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]: def _render(self, p: Post, c: "_Ctx") -> Optional[PostData]:
@@ -541,7 +542,11 @@ class FeedService:
if len(soon) < rank: if len(soon) < rank:
return None return None
e = soon[rank - 1] e = soon[rank - 1]
rows = ([Row(label="장소", value=e.event.place_name, place=e.event.place_name)] if e.event.place_name else []) + [Row(label="기간", value=day_range(e.event.start_date, e.event.end_date))] ev = e.event
# 장소 이름이 행사 이름과 같으면(출처에 장소가 비어 이름이 들어간 것) 빼고, 주소는 눌러서 지도로
rows = ([Row(label="장소", value=ev.place_name, place=ev.address or ev.place_name)] if ev.place_name and ev.place_name != ev.name else [])
rows += [Row(label="주소", value=ev.address, place=ev.address)] if ev.address and ev.address != ev.place_name else []
rows += [Row(label="기간", value=day_range(ev.start_date, ev.end_date))]
caption = _event_caption(e) caption = _event_caption(e)
return PostData(**base, title=e.event.name, icon=e.event.icon, caption=caption, return PostData(**base, title=e.event.name, icon=e.event.icon, caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=f"가까운 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows, image=e.event.image_url, image_credit=image_credit(e.event))], slides=[RowsSlide(kind="rows", eyebrow=f"가까운 행사 · {e.status_label}", line=e.event.name, icon=e.event.icon, rows=rows, image=e.event.image_url, image_credit=image_credit(e.event))],
@@ -608,7 +613,10 @@ class FeedService:
share_messages=[f"오늘 밤은 {name}이래 🌙"]) share_messages=[f"오늘 밤은 {name}이래 🌙"])
when = f"{'내일 ' if at.date() > tonight.date() else ''}{at:%H:%M}" when = f"{'내일 ' if at.date() > tonight.date() else ''}{at:%H:%M}"
if is_full: if is_full:
line = f"오늘 밤 보름달,\n{when}에 가장 둥글어요" # 가장 둥근 순간이 낮(달이 안 보일 때)이면 그 시각 대신 뜨는 시각을 알려 준다
daytime = 6 <= at.hour < 17
line = (f"오늘 밤 보름달,\n{when}에 가장 둥글어요" if not daytime
else f"오늘 밤 보름달,\n{_clock_word(m.rise_at)}에 떠요" if m.rise_at else "오늘 밤 보름달,\n저녁부터 밤새 떠 있어요")
caption = "구름 사이로 잠깐씩 보일 수 있어요." if view.startswith("흐려서") else "소원 빌기 딱 좋은 밤이에요 🌕" caption = "구름 사이로 잠깐씩 보일 수 있어요." if view.startswith("흐려서") else "소원 빌기 딱 좋은 밤이에요 🌕"
return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption, return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", moon_pct=100, moon_waxing=False, rows=[Row(label="보이는지", value=view), *rows])], slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", moon_pct=100, moon_waxing=False, rows=[Row(label="보이는지", value=view), *rows])],
@@ -779,30 +787,6 @@ def _band_sentence(sentences: Optional[dict], score: int) -> Optional[str]:
return sentences[str(lo)] if lo is not None else None return sentences[str(lo)] if lo is not None else None
# 각 포스트에 보일 근거 줄 이름. 시간(요일·노을 점수)은 계산 방식 설명이라 뺀다
_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "uv": "자외선", "sun": "햇볕", "view": "시야"}
_NOTE_HEAD = {"wind": "바람 ", "humidity": "습도 ", "air": "초미세먼지 "}
def gak_rows(i: IndexItem, n: int = 4) -> list[Row]:
"""비중이 큰 조건부터 n개와 지금 값. 점수에 안 쓰는 조건도 n개가 될 때까지 지금 날씨로 채운다. 값은 계산 근거 문구의 첫 마디 (체감 18°, 확률 20%, 초속 3m)."""
d, notes = i.definition, i.score.notes or {}
weighted = sorted((a for a in _AXIS_NAME if getattr(d, f"weight_{a}", 0) and notes.get(a)), key=lambda a: -getattr(d, f"weight_{a}"))
axes = weighted + [a for a in ("temp", "rain", "wind", "air", "humidity") if a not in weighted and notes.get(a)]
rows = []
for a in axes[:n]:
head, _, tail = notes[a].partition(", ")
prob = re.search(r"확률 \d+%", notes[a]) if a == "rain" else None
if prob:
value = prob.group(0)
elif a == "air" and tail:
value = tail
else:
value = head.removeprefix(_NOTE_HEAD.get(a, ""))
rows.append(Row(label=_AXIS_NAME[a], value=value))
return rows
def _gak_caption(i: IndexItem) -> str: def _gak_caption(i: IndexItem) -> str:
"""슬라이드에 없는 내일 점수(없으면 하기 좋은 시간). 점수 구간 설명 문장은 슬라이드에 있다.""" """슬라이드에 없는 내일 점수(없으면 하기 좋은 시간). 점수 구간 설명 문장은 슬라이드에 있다."""
nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None) nxt = next((x for x in i.trend if x.score_date > i.score.score_date), None)
+3 -2
View File
@@ -40,7 +40,7 @@ class MyGakService:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.of_user(s, user.user_id)) err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.of_user(s, user.user_id))
return err, rows or [] return err, rows or []
async def add(self, user: User, name: str, rule: dict) -> tuple[ErrorType, Optional[MyGak]]: async def add(self, user: User, name: str, rule: dict, icon: Optional[str] = None) -> tuple[ErrorType, Optional[MyGak]]:
name = gak_name(name) name = gak_name(name)
if name is None: if name is None:
return ErrorType.INVALID_INPUT, None return ErrorType.INVALID_INPUT, None
@@ -49,7 +49,7 @@ class MyGakService:
return err, None return err, None
if n >= MAX_PER_USER: if n >= MAX_PER_USER:
return ErrorType.INVALID_INPUT, None return ErrorType.INVALID_INPUT, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule)) return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule, icon))
async def delete(self, user: User, my_gak_id: int) -> ErrorType: async def delete(self, user: User, my_gak_id: int) -> ErrorType:
err, found = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, user.user_id, my_gak_id)) err, found = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, user.user_id, my_gak_id))
@@ -79,5 +79,6 @@ class MyGakService:
"score": res.score if res else None, "slot": key if res else None, "score": res.score if res else None, "slot": key if res else None,
"slots": {k: v.score for k, v in picked.items()}, "slots": {k: v.score for k, v in picked.items()},
"reasons": [res.notes[a] for a in axes(r) if res.notes.get(a)] if res else [], "reasons": [res.notes[a] for a in axes(r) if res.notes.get(a)] if res else [],
"factors": {a: res.factors[a] for a in axes(r) if res.notes.get(a) and a in res.factors} if res else {},
}) })
return ErrorType.SUCCESS, (now_slot, out) return ErrorType.SUCCESS, (now_slot, out)
+14
View File
@@ -66,6 +66,20 @@ def group_age(t: Talk, region_code: Optional[str], now: datetime) -> float:
return age - near - LIKE_H * math.log2(1 + t.like_count) return age - near - LIKE_H * math.log2(1 + t.like_count)
def ago_text(at: datetime, now: datetime) -> str:
"""글 시간: 방금 · N분 전 · N시간 전 · N일 전 · N주 전 (하루가 넘으면 시간 대신 날로)"""
minutes = max(0, int((now - at).total_seconds() // 60))
if minutes < 5:
return "방금"
if minutes < 60:
return f"{minutes}분 전"
hours = minutes // 60
if hours < 24:
return f"{hours}시간 전"
days = hours // 24
return f"{days}일 전" if days < 7 else f"{days // 7}주 전"
def pick_group(views: list["TalkView"], region_code: Optional[str], now: datetime) -> list["TalkView"]: def pick_group(views: list["TalkView"], region_code: Optional[str], now: datetime) -> list["TalkView"]:
"""한 사람 한 장, 최대 GROUP_MAX 장. 첫 장은 신고 받은 적 없는 글""" """한 사람 한 장, 최대 GROUP_MAX 장. 첫 장은 신고 받은 적 없는 글"""
out: list[TalkView] = [] out: list[TalkView] = []
-15
View File
@@ -416,18 +416,3 @@ def test_uv_post_only_when_moderate_or_higher():
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
assert FeedService._uv_post(None, base, ctx([])) is None assert FeedService._uv_post(None, base, ctx([])) is None
def test_gak_rows_shows_heaviest_conditions_with_short_values():
from types import SimpleNamespace
from services.feed_service import gak_rows
d = SimpleNamespace(weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=0, weight_air=15, weight_uv=0, weight_sun=0, weight_view=0, weight_time=20)
notes = {"temp": "체감 18°, 편한 범위 15~25° 안", "rain": "비 확률 20%", "wind": "바람 초속 3.1m", "air": "초미세먼지 16㎍/㎥, 좋음", "time": "수요일"}
item = SimpleNamespace(definition=d, score=SimpleNamespace(notes=notes))
assert [(r.label, r.value) for r in gak_rows(item, 3)] == [("기온", "체감 18°"), ("비", "확률 20%"), ("미세먼지", "좋음")]
# 점수에 안 쓰는 조건은 뒤에 지금 날씨로 채운다
d.weight_wind = 0
assert [r.label for r in gak_rows(item)] == ["기온", "비", "미세먼지", "바람"]
item.score.notes = {**notes, "rain": "비 소식, 내일까지 비 확률 70%"}
assert gak_rows(item)[1].value == "확률 70%"
-18
View File
@@ -1,18 +0,0 @@
from starlette.requests import Request
from common.enums import PostType
from router.v1.feed.feed import TOSS_KNOWN_MAX, _from_toss
def _req(headers: dict) -> Request:
return Request({"type": "http", "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()]})
def test_from_toss_by_referer_or_user_agent():
assert _from_toss(_req({"referer": "https://nalssigak.apps.tossmini.com/"}))
assert _from_toss(_req({"user-agent": "Mozilla/5.0 ... AppsInToss TossApp/5.282.1"}))
assert not _from_toss(_req({"referer": "https://weather.o2o.kr/", "user-agent": "Mozilla/5.0 Safari"}))
def test_card_is_hidden_from_old_toss_bundle():
assert PostType.CARD.value > TOSS_KNOWN_MAX >= PostType.UV.value
+2 -1
View File
@@ -34,7 +34,8 @@ def _moon_post(now: datetime):
def test_moon_post_every_night_with_full_and_new_moon_stories(): def test_moon_post_every_night_with_full_and_new_moon_stories():
full = _moon_post(datetime(2025, 10, 7, 20, 0, tzinfo=KST)) # 보름 10.07 12:47 full = _moon_post(datetime(2025, 10, 7, 20, 0, tzinfo=KST)) # 보름 10.07 12:47
assert full.title == "오늘 밤 보름달" and "12:4" in full.slides[0].line # 가장 둥근 순간(12:47)이 낮이라 그 시각 대신 뜨는 시각·밤새 떠 있음을 말한다
assert full.title == "오늘 밤 보름달" and "12:4" not in full.slides[0].line and ("떠요" in full.slides[0].line or "밤새" in full.slides[0].line)
new = _moon_post(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) # 삭 04.09 03:21, 자정 넘긴 새벽에도 그 밤 new = _moon_post(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) # 삭 04.09 03:21, 자정 넘긴 새벽에도 그 밤
assert new.title == "오늘 밤 달 없는 밤" assert new.title == "오늘 밤 달 없는 밤"
plain = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)) # 보름 사흘 전 plain = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)) # 보름 사흘 전
+5
View File
@@ -72,6 +72,11 @@ async def test_add_list_delete_and_limits():
item = (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE}, headers=h)).json()["item"] item = (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE}, headers=h)).json()["item"]
assert item["name"] == "소맥각" and item["rule"]["temp"] == [15, 25] and item["rule"]["slots"] == ["evening", "night"] assert item["name"] == "소맥각" and item["rule"]["temp"] == [15, 25] and item["rule"]["slots"] == ["evening", "night"]
assert [g["my_gak_id"] for g in (await c.get("/v1/my-gak", headers=h)).json()["items"]] == [item["my_gak_id"]] assert [g["my_gak_id"] for g in (await c.get("/v1/my-gak", headers=h)).json()["items"]] == [item["my_gak_id"]]
# 고른 아이콘을 저장하고, 아이콘 이름 꼴이 아니면 받지 않는다
picnic = (await c.post("/v1/my-gak", json={"name": "피크닉", "icon": "picnic", "rule": RULE}, headers=h)).json()["item"]
assert picnic["icon"] == "picnic"
assert (await c.post("/v1/my-gak", json={"name": "피크닉", "icon": "../x", "rule": RULE}, headers=h)).status_code == 422
await c.delete(f"/v1/my-gak/{picnic['my_gak_id']}", headers=h)
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["success"] is True assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["success"] is True
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["desc"] == "NOT_FOUND" assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["desc"] == "NOT_FOUND"
for i in range(MAX_PER_USER): for i in range(MAX_PER_USER):
+1 -1
View File
@@ -22,7 +22,7 @@ def _page(popup_id: int, kind: str, start: str, end: str, address: str = "서울
def test_parse_popup_maps_store(): def test_parse_popup_maps_store():
row = parse_popup(_page(501, "STORE", "2026-10-02", "2026-10-11"), 501, date(2026, 10, 1)) row = parse_popup(_page(501, "STORE", "2026-10-02", "2026-10-11"), 501, date(2026, 10, 1))
assert row == { assert row == {
"source_id": "popga:501", "sido_code": "11", "name": "테스트 팝업 & 굿즈", "place_name": "테스트 빌딩 1F", "source_id": "popga:501", "sido_code": "11", "name": "테스트 팝업 & 굿즈", "place_name": "테스트 빌딩 1F", "address": "서울 성동구 테스트로 1",
"start_date": date(2026, 10, 2), "end_date": date(2026, 10, 11), "is_confirmed": True, "start_date": date(2026, 10, 2), "end_date": date(2026, 10, 11), "is_confirmed": True,
"source_url": "https://popga.co.kr/popup/501", "image_url": None, "lat": 37.54461, "lon": 127.05575, "kind": EventKind.POPUP, "icon": "popup", "source_url": "https://popga.co.kr/popup/501", "image_url": None, "lat": 37.54461, "lon": 127.05575, "kind": EventKind.POPUP, "icon": "popup",
} }
+14
View File
@@ -191,3 +191,17 @@ def test_pick_group_orders_near_fresh_first_one_per_person_clean_first():
assert [v.talk.talk_id for v in pick_group([far, same_sido, same_gu, old_popular, again], REGION, now)] == [5, 2, 1, 4] assert [v.talk.talk_id for v in pick_group([far, same_sido, same_gu, old_popular, again], REGION, now)] == [5, 2, 1, 4]
reported = _view(6, "e", REGION, 0, reports=1) reported = _view(6, "e", REGION, 0, reports=1)
assert pick_group([reported, far], REGION, now)[0].talk.talk_id == 1 assert pick_group([reported, far], REGION, now)[0].talk.talk_id == 1
def test_ago_text_switches_to_days_after_a_day():
from datetime import datetime, timedelta
from services.talk_service import ago_text
now = datetime(2026, 10, 27, 18, 0)
assert ago_text(now - timedelta(minutes=2), now) == "방금"
assert ago_text(now - timedelta(minutes=12), now) == "12분 전"
assert ago_text(now - timedelta(hours=23, minutes=59), now) == "23시간 전"
assert ago_text(now - timedelta(hours=24), now) == "1일 전"
assert ago_text(now - timedelta(hours=140), now) == "5일 전"
assert ago_text(now - timedelta(days=15), now) == "2주 전"
+26
View File
@@ -152,3 +152,29 @@
- [ ] 작은 버튼이 잘 눌리는지: 포스트 하트·댓글·보내기, 댓글 하트, 시트 × - [ ] 작은 버튼이 잘 눌리는지: 포스트 하트·댓글·보내기, 댓글 하트, 시트 ×
- [ ] 댓글 입력칸을 누르면 키보드 위로 입력칸·게시 버튼이 보인다 (확인) - [ ] 댓글 입력칸을 누르면 키보드 위로 입력칸·게시 버튼이 보인다 (확인)
- [ ] 로그인 시트 비밀번호 칸·버튼, 지역 검색 목록이 키보드에 가려지지 않는다 (확인) - [ ] 로그인 시트 비밀번호 칸·버튼, 지역 검색 목록이 키보드에 가려지지 않는다 (확인)
## 17. 오늘 탭: 쇼츠 줄·쇼츠 페이지
10/27 헤드리스 크롬(iPhone 13·SE·데스크톱 1280)으로 자동 점검한 결과. `[x]` 통과, `[ ]` 실패·미확인.
- [x] 히어로 바로 아래 세로 카드 줄(3개), 제목 줄 없음
- [x] 줄이 화면에 보이면 첫 카드만 소리 없이 재생, 화면 밖으로 나가면 플레이어를 내림
- [x] 카드 누름 → `/shorts/영상ID`, 영상이 헤더·버튼 줄과 하단 탭 사이에 9:16으로 맞고, 앞뒤 영상까지 3개만 띄움
- [x] 쇼츠 페이지에선 뒤 페이지가 스크롤되지 않고, 닫으면 다시 스크롤됨
- [x] '소리 켜기' 누름 → '소리 끄기'로 바뀜
- [x] 위아래로 넘기면 주소가 그 영상으로 바뀜(뒤로 가기 기록은 안 쌓임 → 뒤로 가기 한 번에 오늘 화면)
- [x] 영상 탭 → 일시정지, 다시 탭 → 재생 (모바일·마우스 둘 다)
- [x] × · Esc · 하단 탭 누름 → 쇼츠 페이지를 닫고 이동
- [x] 공유 링크로 바로 들어오면 그 영상부터, 닫으면 오늘 화면으로(뒤로 가기에 남지 않음)
- [x] 목록에 없는 영상 ID 링크 → 그 영상을 맨 앞에 붙여 보임 / `/shorts`(ID 없음) → 첫 영상부터 / 새로고침해도 그대로
- [x] 마우스로 20px 끌면 제자리, 30px 넘게 끌면 다음·이전, 첫 영상에서 아래로 끌면 그대로
- [x] 마우스 휠·키보드 ↓로도 넘어감
- [x] 쇼츠 API 실패·빈 목록 → 오늘 화면에서 줄이 통째로 숨음
- [ ] **실패** 쇼츠 API 실패·빈 목록일 때 공유 링크(`/shorts/영상ID`)로 들어오면 남색 빈 화면만 계속 보임. 영상·× 버튼·안내 문구 없음(하단 탭으로만 나갈 수 있음)
- [ ] 미확인: 밤 테마에서 쇼츠 카드 그림·영상이 남색 판에 가려지지 않는지 (자동 캡처가 다른 곳을 찍음, 눈으로 확인 필요)
- [ ] 미확인: 아이폰 사파리 실기기 자동재생, 손가락으로 위아래 넘길 때 한 장씩 딱 멈추는지 (헤드리스는 터치 스크롤 재현 불가)
## 18. 각 포스트 카드
- [x] 아이폰 13·SE에서 점수·각 이름·'계산 근거 보기' 버튼이 카드 밖으로 잘리지 않는다 (10/27 근거 표·요약 줄 뺀 뒤, SE는 점수 글씨를 작게)
- [x] 카드마다 같은 내용이 반복되지 않는다: 기온·비·바람·미세먼지 표와 '오전 10시 13°, 바람 조금' 줄 없음, 말풍선 문장은 각마다 다름
+2
View File
@@ -6,5 +6,7 @@ export default defineConfig({
brand: { primaryColor: '#ff7a45' }, brand: { primaryColor: '#ff7a45' },
permissions: [{ name: 'geolocation', access: 'access' }], permissions: [{ name: 'geolocation', access: 'access' }],
navigationBar: { withBackButton: true, withHomeButton: true }, navigationBar: { withBackButton: true, withHomeButton: true },
// 기본값은 자동재생·화면 안 재생을 막아 쇼츠(유튜브)가 재생되지 않는다
webView: { allowsInlineMediaPlayback: true, mediaPlaybackRequiresUserAction: false },
webBundleDir: 'dist-toss', webBundleDir: 'dist-toss',
}) })
+14 -5
View File
@@ -1,14 +1,14 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react' import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router' import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
import { useIsFetching, useQuery } from '@tanstack/react-query' import { useIsFetching, useQuery, useQueryClient } from '@tanstack/react-query'
import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { authConfigOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib' import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
import './b.css' import './b.css'
import { AuthProvider } from './auth' import { AuthProvider } from './auth'
import { RegionProvider } from './region' import { RegionProvider } from './region'
import { useAuth } from './authContext' import { useAuth } from './authContext'
import { preloadGoogle } from './googleScript'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { SheetProvider } from './Sheets' import { SheetProvider } from './Sheets'
@@ -47,7 +47,16 @@ function TopBar() {
const { region, locateStatus } = useRegion() const { region, locateStatus } = useRegion()
const { open } = useSheet() const { open } = useSheet()
const { me, mePending } = useAuth() const { me, mePending } = useAuth()
const queryClient = useQueryClient()
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to)) const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
const loggedOut = !mePending && !me
// 로그인 창을 처음 열 때 버벅이지 않게 구글 로그인 준비물을 미리 받아 둔다
useEffect(() => {
if (!loggedOut) return
void queryClient.prefetchQuery({ ...authConfigOptions(), staleTime: Infinity })
return preloadGoogle()
}, [loggedOut, queryClient])
return ( return (
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]"> <header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
@@ -62,7 +71,7 @@ function TopBar() {
<PinIcon className="size-3.5 shrink-0" /> <PinIcon className="size-3.5 shrink-0" />
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : <span className="truncate whitespace-nowrap"><span className="max-[399px]:hidden">{region.name}</span><span className="min-[400px]:hidden">{region.name.split(' ').at(-1)}</span></span>} {locateStatus === 'locating' ? <Skel className="w-[72px]" /> : <span className="truncate whitespace-nowrap"><span className="max-[399px]:hidden">{region.name}</span><span className="min-[400px]:hidden">{region.name.split(' ').at(-1)}</span></span>}
</button> </button>
{IS_TOSS ? null : mePending ? ( {mePending ? (
<Skel shape className="size-9 shrink-0 rounded-full" /> <Skel shape className="size-9 shrink-0 rounded-full" />
) : me ? ( ) : me ? (
<button type="button" onClick={() => open({ type: 'me' })} aria-label={`내 정보, ${me.nickname}`} className="shrink-0 cursor-pointer rounded-full shadow-[0_6px_12px_rgb(40_48_74/0.12)]"> <button type="button" onClick={() => open({ type: 'me' })} aria-label={`내 정보, ${me.nickname}`} className="shrink-0 cursor-pointer rounded-full shadow-[0_6px_12px_rgb(40_48_74/0.12)]">
@@ -254,7 +263,7 @@ function Shell() {
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */} {/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" /> <div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" /> <div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(70px+env(safe-area-inset-bottom,0px))]"> <div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(104px+env(safe-area-inset-bottom,0px))]">
<TopBar /> <TopBar />
<main className="relative z-[1]"> <main className="relative z-[1]">
<Outlet /> <Outlet />
+26 -16
View File
@@ -53,7 +53,8 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter' if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter'
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length] if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length]
if (slide.kind === 'image') return 'sky' if (slide.kind === 'image') return 'sky'
if (post.post_type === PostType.EVENT || post.post_type === PostType.MOON) return 'night' if (post.post_type === PostType.MOON) return 'night'
if (post.post_type === PostType.EVENT) return slide.image ? 'night' : 'peach'
if (post.post_type === PostType.TIP) return 'sky' if (post.post_type === PostType.TIP) return 'sky'
if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac' if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac'
if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint' if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint'
@@ -63,18 +64,16 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
const DARK = new Set<SlideBg>(['dusk', 'night']) const DARK = new Set<SlideBg>(['dusk', 'night'])
// 그림 배경이 있는 각(code)과 장 수. 여러 장이면 글마다 돌려 쓴다 // 그림 배경이 있는 각(code)과 장 수. 여러 장이면 글마다 돌려 쓴다
const BG_IMAGES: Record<string, number> = { bike: 4, picnic: 1, hiking: 1, camping: 1, stars: 1, walk: 1, hangang: 1 } const BG_IMAGES: Record<string, number> = { bike: 4, picnic: 1, hiking: 1, hangang: 1 }
const EVENT_BG_N = 4
function bgImage(name: string, n: number, seed: number): CSSProperties { function bgImage(name: string, n: number, seed: number): CSSProperties {
const file = n > 1 ? `${name}-${'abcd'[seed % n]}` : name const file = n > 1 ? `${name}-${'abcd'[seed % n]}` : name
return { backgroundImage: `url(/post-bg/${file}.webp)`, backgroundSize: 'cover', backgroundPosition: 'center' } return { backgroundImage: `url(/post-bg/${file}.webp)`, backgroundSize: 'cover', backgroundPosition: 'center' }
} }
/** 그림 배경: 각은 각마다, 사진 없는 행사는 행사용. 없으면 색 배경만 */ /** 그림 배경: 각은 각마다. 없으면 색 배경만 */
function slideImage(post: PostData, slide: Slide): CSSProperties | undefined { function slideImage(post: PostData, slide: Slide): CSSProperties | undefined {
if (slide.kind === 'gak') return BG_IMAGES[slide.code] ? bgImage(slide.code, BG_IMAGES[slide.code], post.post_id) : undefined if (slide.kind === 'gak') return BG_IMAGES[slide.code] ? bgImage(slide.code, BG_IMAGES[slide.code], post.post_id) : undefined
if (post.post_type === PostType.EVENT && slide.kind === 'rows' && !slide.image) return bgImage('event', EVENT_BG_N, post.post_id)
return undefined return undefined
} }
@@ -164,17 +163,28 @@ function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSPro
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}> <div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow> <Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
<Big>{slide.line}</Big> <Big>{slide.line}</Big>
<Pic name={slide.code} /> <Pic name={slide.code} className="[@media(max-height:700px)]:top-[26%] [@media(max-height:700px)]:w-[34%]" />
{slide.say && <p className="relative z-[1] m-0 mt-2.5 w-[56%] rounded-[16px] rounded-tl-[4px] bg-white/80 px-3 py-2 text-[14px] leading-snug font-bold">{slide.say}</p>} {slide.say && <p className="relative z-[1] m-0 mt-2.5 w-[56%] rounded-[16px] rounded-tl-[4px] bg-white/80 px-3 py-2 text-[14px] leading-snug font-bold">{slide.say}</p>}
{/* 점수 근거: 비중 큰 조건과 지금 값. 오른쪽 아이콘과 겹치지 않게 왼쪽 반만 */} {/* 오른쪽 아래 빈 곳에 오늘·내일·주말 점수 (각 상세 날짜 칸과 같은 값) */}
{!!slide.rows?.length && ( <div className="relative z-[1] mt-auto flex items-end justify-between gap-3">
<div className="relative z-[1] mt-2 w-[56%] rounded-[16px] bg-white/70 px-3 text-[14px] [&_b]:text-[15px] [&>div>div]:py-1.5 [&>div]:mt-0"> <div>
<Rows rows={slide.rows} /> <b className="block font-bagel text-[82px] leading-[0.9] font-normal text-(--orange) [@media(max-height:700px)]:text-[64px]">{slide.score}</b>
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
</div> </div>
)} {!!slide.trend?.length && (
<b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b> <div className="grid w-[46%] grid-cols-2 gap-1.5">
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p> {slide.trend.map((t) => (
<Eyebrow className="mt-1">{slide.summary}</Eyebrow> <div key={t.day} className="rounded-xl bg-white/80 px-1 py-1.5 text-center">
<small className="block text-[11px] font-extrabold whitespace-nowrap text-(--ink2)">
{t.label}
{t.estimated && ' 예상'}
</small>
<b className="block font-bagel text-lg leading-tight font-normal text-(--orange)">{t.score}</b>
</div>
))}
</div>
)}
</div>
<button type="button" onClick={() => open({ type: 'gak', indexId: slide.index_id })} className="mt-3 cursor-pointer self-start rounded-full bg-(--orange) px-4 py-[9px] font-jua text-[15px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)]"> <button type="button" onClick={() => open({ type: 'gak', indexId: slide.index_id })} className="mt-3 cursor-pointer self-start rounded-full bg-(--orange) px-4 py-[9px] font-jua text-[15px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)]">
계산 근거 보기 계산 근거 보기
</button> </button>
@@ -438,7 +448,7 @@ function FullCard({ post }: PostProps) {
<small className="text-xs font-semibold text-(--ink2)">{account}</small> <small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span> </span>
</div> </div>
<div className="relative aspect-[4/5] overflow-hidden" onClick={onTap}> <div className="b-day relative aspect-[4/5] overflow-hidden" onClick={onTap}>
{n > 1 && ( {n > 1 && (
<span data-noshot className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white" aria-hidden="true"> <span data-noshot className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white" aria-hidden="true">
{index + 1}/{n} {index + 1}/{n}
@@ -548,7 +558,7 @@ export function PostFrame({ title, account, avatar, caption, more, shot, pinned,
<small className="text-xs font-semibold text-(--ink2)">{account}</small> <small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span> </span>
</div> </div>
<div ref={bodyRef}>{children}</div> <div ref={bodyRef} className="b-day">{children}</div>
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]"> <div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
{postId != null && ( {postId != null && (
<> <>
+98 -35
View File
@@ -20,6 +20,7 @@ import {
listRegionsOptions, listRegionsOptions,
meQueryKey, meQueryKey,
reportCommentMutation, reportCommentMutation,
tossMutation,
unblockMutation, unblockMutation,
unlikeCommentMutation, unlikeCommentMutation,
updateMeMutation, updateMeMutation,
@@ -27,15 +28,15 @@ import {
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen' } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { AuthProvider, ReportReason, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '@nalssigak/shared/api/client/types.gen' import { AuthProvider, ReportReason, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics' import { track } from '../lib/analytics'
import { IS_TOSS, tossShare } from '../lib/platform' import { IS_TOSS, tossLogin, tossShare } from '../lib/platform'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { useAuth } from './authContext' import { useAuth } from './authContext'
import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib' import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib'
import { GoogleButton } from './googleLogin' import { GoogleButton } from './googleLogin'
import { useInstall, useInstallable } from './install' import { useInstall, useInstallable } from './install'
import { InstallSheet } from './installBanner' import { InstallSheet } from './installBanner'
import { ARTICLE_CAT } from './lib' import { ARTICLE_CAT, SHEET_CLOSE_MS, SHEET_OPEN_MS } from './lib'
import { MixSheet } from './myGak' import { MixSheet, MyGakSheet } from './myGak'
import { ownPage, useRegion } from './regionContext' import { ownPage, useRegion } from './regionContext'
import { WeatherWhySheet } from './weatherWhy' import { WeatherWhySheet } from './weatherWhy'
import { useSky } from './skyContext' import { useSky } from './skyContext'
@@ -95,11 +96,25 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const [gakTitle, setGakTitle] = useState('') const [gakTitle, setGakTitle] = useState('')
const [articleTitle, setArticleTitle] = useState('') const [articleTitle, setArticleTitle] = useState('')
// 닫히는 동안에도 내려가는 창에 내용이 남아 있게, 마지막으로 연 창을 들고 있는다
const [shown, setShown] = useState<SheetState>(state)
if (state && state !== shown) setShown(state)
const closing = !state && shown != null
useEffect(() => { useEffect(() => {
const el = ref.current const el = ref.current
if (!el) return if (!el) return
if (state && !el.open) el.showModal() if (state) {
if (!state && el.open) el.close() if (!el.open) el.showModal()
return
}
if (!el.open) return
// 내려가는 애니메이션이 끝난 뒤에 실제로 닫는다
const t = setTimeout(() => {
el.close()
setShown(null)
}, SHEET_CLOSE_MS)
return () => clearTimeout(t)
}, [state]) }, [state])
// 창이 열려 있는 동안 뒤 페이지는 스크롤되지 않게 잠근다 // 창이 열려 있는 동안 뒤 페이지는 스크롤되지 않게 잠근다
@@ -109,15 +124,17 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const root = document.documentElement const root = document.documentElement
const before = root.style.overflow const before = root.style.overflow
root.style.overflow = 'hidden' root.style.overflow = 'hidden'
root.classList.add('b-sheet-open') // 뒤 화면 움직임 멈추기는 페이지 전체 스타일을 다시 계산하게 해서, 창이 다 올라온 뒤에 한다
const pause = setTimeout(() => root.classList.add('b-sheet-open'), SHEET_OPEN_MS)
return () => { return () => {
clearTimeout(pause)
root.style.overflow = before root.style.overflow = before
root.classList.remove('b-sheet-open') root.classList.remove('b-sheet-open')
} }
}, [isOpen]) }, [isOpen])
const then = state?.type === 'login' ? state.then : undefined const then = shown?.type === 'login' ? shown.then : undefined
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type] const title = !shown ? '' : shown.type === 'gak' ? gakTitle : shown.type === 'article' ? articleTitle || TITLES.article : shown.type === 'mix' ? (shown.shared ? '받은 각' : '내 각 만들기') : shown.type === 'myGak' ? '내 각' : TITLES[shown.type]
return ( return (
<dialog <dialog
@@ -125,12 +142,17 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
aria-label={title} aria-label={title}
data-t={kind} data-t={kind}
onClose={onClose} onClose={onClose}
// ESC 도 바로 닫지 않고 내려가며 닫히게
onCancel={(e) => {
e.preventDefault()
onClose()
}}
onClick={(e) => { onClick={(e) => {
if (e.target === e.currentTarget) onClose() if (e.target === e.currentTarget) onClose()
}} }}
className="b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)" className={cx('b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)', closing && 'b-sheet-closing')}
> >
{state && ( {shown && (
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white pb-[env(safe-area-inset-bottom,0px)]"> <div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white pb-[env(safe-area-inset-bottom,0px)]">
<div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center"> <div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center">
<div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-(--line)" aria-hidden="true" /> <div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-(--line)" aria-hidden="true" />
@@ -139,21 +161,22 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
× ×
</button> </button>
</div> </div>
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />} {shown.type === 'gak' && <GakSheet indexId={shown.indexId} onTitle={setGakTitle} />}
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />} {shown.type === 'article' && <ArticleSheet articleId={shown.articleId} onTitle={setArticleTitle} />}
{state.type === 'seasonWeek' && <SeasonWeekSheet />} {shown.type === 'seasonWeek' && <SeasonWeekSheet />}
{state.type === 'share' && <ShareSheet share={state.share} />} {shown.type === 'share' && <ShareSheet share={shown.share} />}
{state.type === 'comments' && <CommentsSheet postId={state.postId} draft={state.draft} />} {shown.type === 'comments' && <CommentsSheet postId={shown.postId} draft={shown.draft} />}
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />} {shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{state.type === 'me' && <MeSheet onDone={onClose} />} {shown.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />} {shown.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />} {shown.type === 'mix' && <MixSheet shared={shown.shared} onDone={onClose} />}
{state.type === 'install' && <InstallSheet />} {shown.type === 'myGak' && <MyGakSheet gak={shown.gak} shot={shown.shot} onDone={onClose} />}
{state.type === 'weatherWhy' && <WeatherWhySheet d={state.why} />} {shown.type === 'install' && <InstallSheet />}
{state.type === 'talk' && <TalkSheet talk={state.talk} />} {shown.type === 'weatherWhy' && <WeatherWhySheet d={shown.why} />}
{shown.type === 'talk' && <TalkSheet talk={shown.talk} />}
</div> </div>
)} )}
{!state && <RegionLinks />} {!shown && <RegionLinks />}
</dialog> </dialog>
) )
} }
@@ -539,6 +562,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
const [toast, setToast] = useState('') const [toast, setToast] = useState('')
const image = images[size] const image = images[size]
const text = `${share.title} · 날씨각` const text = `${share.title} · 날씨각`
const url = share.url ?? SITE_URL
// 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다 // 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다
useEffect(() => { useEffect(() => {
@@ -584,15 +608,15 @@ function ShareSheet({ share }: { share: SharePayload }) {
) )
return return
} }
if (navigator.canShare?.({ files: [file], text, url: SITE_URL })) { if (navigator.canShare?.({ files: [file], text, url })) {
const copied = navigator.clipboard?.writeText(SITE_URL).then( const copied = navigator.clipboard?.writeText(url).then(
() => true, () => true,
(e: unknown) => { (e: unknown) => {
console.error('[share] copy link', e) console.error('[share] copy link', e)
return false return false
}, },
) )
navigator.share({ files: [file], title: share.title, text, url: SITE_URL }).then( navigator.share({ files: [file], title: share.title, text, url }).then(
async () => { async () => {
setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요') setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요')
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio }) track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
@@ -614,7 +638,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
setToast('이미지를 내려받았어요') setToast('이미지를 내려받았어요')
return return
} }
navigator.clipboard.writeText(`${text} ${SITE_URL}`).then( navigator.clipboard.writeText(`${text} ${url}`).then(
() => setToast('이미지를 내려받고 링크를 복사했어요'), () => setToast('이미지를 내려받고 링크를 복사했어요'),
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'), () => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
) )
@@ -970,7 +994,7 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.') const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
if (me) return <MeSheet onDone={onDone} /> if (me) return <MeSheet onDone={onDone} />
if (IS_TOSS) return <TossNoLoginSheet onDone={onDone} /> if (IS_TOSS) return <TossLoginSheet onDone={onDone} onLoggedIn={onLoggedIn} />
return ( return (
<Body> <Body>
@@ -994,13 +1018,52 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
) )
} }
/** 토스판은 로그인이 없다. 로그인이 필요한 곳(두 번째 내 각)에서 안내만 한다 */ /** 앱인토스는 토스 로그인만 쓸 수 있다 */
function TossNoLoginSheet({ onDone }: { onDone: () => void }) { function TossLoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
const [error, setError] = useState('')
const [opening, setOpening] = useState(false)
const toss = useMutation(tossMutation())
const pending = opening || toss.isPending
const start = async () => {
setError('')
setOpening(true)
let code: Awaited<ReturnType<typeof tossLogin>>
try {
code = await tossLogin()
} catch (e) {
console.error('[login] toss', e)
setError('토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.')
return
} finally {
setOpening(false)
}
toss.mutate(
{ body: { authorization_code: code.authorizationCode, referrer: code.referrer } },
{
onSuccess: (res) => {
if (!res.result?.success || !res.access_token) return setError('토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.')
setTokens(res.access_token, res.refresh_token ?? null)
track('login', { method: 'toss' })
onLoggedIn()
},
onError: () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.'),
},
)
}
return ( return (
<Body className="flex flex-col gap-2.5"> <Body className="flex flex-col gap-2.5">
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">토스에서는 내 각을 하나만 만들 수 있어요. 지금 각을 지우고 새로 만들어 주세요.</p> <h3 className="m-0 text-center font-jua text-xl font-normal">날씨각 로그인</h3>
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)]"> <p className="m-0 text-center text-sm font-semibold text-(--ink2)">로그인하면 동네 이야기를 쓰고 내 각을 저장할 수 있어요</p>
알겠어요 <p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
{error}
</p>
<button type="button" onClick={start} 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={['토스로 로그인', '로그인 중…']} at={pending ? 1 : 0} />
</button>
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
나중에 할게요
</button> </button>
</Body> </Body>
) )
@@ -1297,12 +1360,12 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
</li> </li>
))} ))}
</ul> </ul>
{!IS_TOSS && <p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)"> <p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)">
{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'} {me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'}
<button type="button" onClick={me ? logout : () => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--rain)"> <button type="button" onClick={me ? logout : () => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--rain)">
{me ? '로그아웃' : '로그인'} {me ? '로그아웃' : '로그인'}
</button> </button>
</p>} </p>
</Body> </Body>
) )
} }
+77 -29
View File
@@ -3,7 +3,9 @@ import { type CSSProperties, type PointerEvent as ReactPointerEvent, useEffect,
import { Link, useNavigate, useParams } from 'react-router' import { Link, useNavigate, useParams } from 'react-router'
import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ShortItem } from '@nalssigak/shared/api/client' import type { ShortItem } from '@nalssigak/shared/api/client'
import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { CloseIcon } from './svg'
import { Rail, Skel, SkelRail, TAP44 } from './ui' import { Rail, Skel, SkelRail, TAP44 } from './ui'
// 유튜브는 플레이어가 200×200 이상이어야 해서, 카드 안 미리보기는 200px 너비로 띄우고 줄여 보인다. // 유튜브는 플레이어가 200×200 이상이어야 해서, 카드 안 미리보기는 200px 너비로 띄우고 줄여 보인다.
@@ -15,13 +17,18 @@ const SCALE = (CARD_W / PLAYER_W) * 1.4
// 쇼츠 페이지의 영상 칸: 위 헤더(54px)·버튼 줄(48px)과 아래 탭 바(--shorts-tab) 사이 높이와 화면 너비 안에 9:16으로 맞춘다 // 쇼츠 페이지의 영상 칸: 위 헤더(54px)·버튼 줄(48px)과 아래 탭 바(--shorts-tab) 사이 높이와 화면 너비 안에 9:16으로 맞춘다
const FIT = { width: 'min(100vw, calc((100dvh - env(safe-area-inset-top, 0px) - 54px - 48px - var(--shorts-tab, 0px)) * 9 / 16))', aspectRatio: '9 / 16' } const FIT = { width: 'min(100vw, calc((100dvh - env(safe-area-inset-top, 0px) - 54px - 48px - var(--shorts-tab, 0px)) * 9 / 16))', aspectRatio: '9 / 16' }
/** 아래 탭 바 높이 (기기마다 안전 영역이 달라 실제로 잰다) */ /** 아래 탭 바가 가리는 높이: 탭 바 위로 솟은 가운데 홈 동그라미까지 (기기마다 안전 영역이 달라 실제로 잰다) */
function useTabBarHeight() { function useTabBarHeight() {
const [h, setH] = useState(0) const [h, setH] = useState(0)
useLayoutEffect(() => { useLayoutEffect(() => {
const nav = document.querySelector<HTMLElement>('nav.b-tabbar') const nav = document.querySelector<HTMLElement>('nav.b-tabbar')
if (!nav) return if (!nav) return
const ro = new ResizeObserver(() => setH(nav.offsetHeight)) const measure = () => {
const bar = nav.getBoundingClientRect()
const bump = nav.querySelector('.b-tab-main > *')?.getBoundingClientRect().top ?? bar.top
setH(Math.round(bar.bottom - Math.min(bar.top, bump)))
}
const ro = new ResizeObserver(measure)
ro.observe(nav) ro.observe(nav)
return () => ro.disconnect() return () => ro.disconnect()
}, []) }, [])
@@ -30,6 +37,11 @@ function useTabBarHeight() {
const YT_ORIGIN = 'https://www.youtube-nocookie.com' const YT_ORIGIN = 'https://www.youtube-nocookie.com'
// 토스 웹뷰에는 플레이어가 보내는 재생 상태가 오지 않는다. 그래서 토스는 첫 장면이 나왔는지를 시간으로 보고 표지를 걷는다 (나머지는 웹과 같다)
const PLAIN = IS_TOSS
// 토스는 재생 상태가 안 오므로, 플레이어 문서가 뜨고 이만큼 지나면 첫 장면이 나왔다고 보고 표지를 걷는다 (그 전엔 플레이어의 검은 화면 대신 표지)
const PLAIN_SHOW_MS = 1000
function embed(id: string) { function embed(id: string) {
const q = new URLSearchParams({ const q = new URLSearchParams({
autoplay: '1', mute: '1', playsinline: '1', loop: '1', playlist: id, controls: '0', rel: '0', modestbranding: '1', autoplay: '1', mute: '1', playsinline: '1', loop: '1', playlist: id, controls: '0', rel: '0', modestbranding: '1',
@@ -38,7 +50,7 @@ function embed(id: string) {
return `${YT_ORIGIN}/embed/${id}?${q}` return `${YT_ORIGIN}/embed/${id}?${q}`
} }
type Func = 'playVideo' | 'pauseVideo' | 'seekTo' | 'mute' | 'unMute' type Func = 'playVideo' | 'seekTo' | 'mute' | 'unMute'
/** 이미 띄운 플레이어에 명령 (IFrame API 메시지) */ /** 이미 띄운 플레이어에 명령 (IFrame API 메시지) */
function command(frame: HTMLIFrameElement | null | undefined, func: Func, args: unknown[] = []) { function command(frame: HTMLIFrameElement | null | undefined, func: Func, args: unknown[] = []) {
@@ -85,7 +97,8 @@ export function ShortsRail() {
<section ref={ref} aria-label="날씨각 쇼츠"> <section ref={ref} aria-label="날씨각 쇼츠">
<Rail label="쇼츠 목록"> <Rail label="쇼츠 목록">
{items.map((s, i) => ( {items.map((s, i) => (
<ShortCard key={s.id} s={s} playing={i === 0 && visible} /> // 토스 앱 웹뷰는 유튜브 플레이어가 무거워, 줄에선 표지만 보이고 누르면 재생
<ShortCard key={s.id} s={s} playing={!IS_TOSS && i === 0 && visible} />
))} ))}
</Rail> </Rail>
</section> </section>
@@ -93,16 +106,35 @@ export function ShortsRail() {
} }
function ShortCard({ s, playing }: { s: ShortItem; playing: boolean }) { function ShortCard({ s, playing }: { s: ShortItem; playing: boolean }) {
// 재생이 시작된 뒤에만 플레이어를 보인다: 자동재생이 막히면(아이폰 절전 등) 유튜브 재생 버튼 대신 표지 그대로
const [started, setStarted] = useState(false)
const frame = useRef<HTMLIFrameElement>(null)
useEffect(() => {
if (!playing) return
const onMessage = (e: MessageEvent) => {
if (e.origin !== YT_ORIGIN || typeof e.data !== 'string' || e.source !== frame.current?.contentWindow) return
try {
if ((JSON.parse(e.data) as { info?: { playerState?: number } }).info?.playerState === PLAYING) setStarted(true)
} catch {
return
}
}
window.addEventListener('message', onMessage)
return () => window.removeEventListener('message', onMessage)
}, [playing])
return ( return (
<Link to={`/shorts/${s.id}`} aria-label={`${s.title} 보기`} className="relative block aspect-[9/16] w-[120px] cursor-pointer overflow-hidden rounded-xl bg-[#1d2233] p-0 text-left text-white"> <Link to={`/shorts/${s.id}`} aria-label={`${s.title} 보기`} className="relative block aspect-[9/16] w-[120px] cursor-pointer overflow-hidden rounded-xl bg-[#1d2233] p-0 text-left text-white">
<img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" loading="lazy" className="absolute inset-0 size-full object-cover" /> <img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" loading="lazy" className="absolute inset-0 size-full object-cover" />
{playing && ( {playing && (
<iframe <iframe
ref={frame}
src={embed(s.id)} src={embed(s.id)}
title={s.title} title={s.title}
allow="autoplay; encrypted-media; picture-in-picture" allow="autoplay; encrypted-media; picture-in-picture"
tabIndex={-1} tabIndex={-1}
className="pointer-events-none absolute top-1/2 left-1/2 border-0" // 재생 상태를 받으려면 플레이어에 먼저 '듣고 있다'고 알린다
onLoad={(e) => e.currentTarget.contentWindow?.postMessage(JSON.stringify({ event: 'listening', id: s.id }), YT_ORIGIN)}
className={cx('pointer-events-none absolute top-1/2 left-1/2 border-0 transition-opacity duration-200', !started && 'opacity-0')}
style={{ width: PLAYER_W, height: (PLAYER_W * 16) / 9, transform: `translate(-50%, -50%) scale(${SCALE})` }} style={{ width: PLAYER_W, height: (PLAYER_W * 16) / 9, transform: `translate(-50%, -50%) scale(${SCALE})` }}
/> />
)} )}
@@ -139,22 +171,37 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
const tabH = useTabBarHeight() const tabH = useTabBarHeight()
// 첫 장면을 받은 플레이어. 그 전엔 플레이어의 검은 화면 대신 표지를 보인다 // 첫 장면을 받은 플레이어. 그 전엔 플레이어의 검은 화면 대신 표지를 보인다
const [ready, setReady] = useState<ReadonlySet<number>>(new Set()) const [ready, setReady] = useState<ReadonlySet<number>>(new Set())
// 토스: 표지를 걷은 플레이어들. 다음 영상도 미리 띄워 두므로 여럿
const [plainShown, setPlainShown] = useState<ReadonlySet<number>>(new Set())
const plainTimers = useRef(new Set<number>())
useEffect(() => {
const timers = plainTimers.current
return () => timers.forEach((t) => window.clearTimeout(t))
}, [])
const frames = useRef(new Map<number, HTMLIFrameElement>()) const frames = useRef(new Map<number, HTMLIFrameElement>())
const atRef = useRef(start) const atRef = useRef(start)
const soundRef = useRef(false) const soundRef = useRef(false)
// 누르기로 멈춘 상태. 다른 영상으로 넘어가면 다시 재생 중으로
const paused = useRef(false)
// 처음 한 번: 시작 영상으로 맞추고, 뒤 페이지 스크롤을 잠근다 // 처음 한 번: 시작 영상으로 맞추고, 뒤 페이지 스크롤을 잠근다
const startRef = useRef(start) const startRef = useRef(start)
useEffect(() => { // 시작 영상으로 옮기기 전엔 보이는 칸이 바뀐 것으로 치지 않는다 (사파리는 처음 그릴 때 맨 위 칸이 먼저 보여 첫 영상으로 바뀌던 것)
// scrollIntoView 는 바깥 칸까지 굴려 버튼 줄이 헤더 밑으로 숨으므로 목록만 옮긴다 const placed = useRef(false)
useLayoutEffect(() => {
// scrollIntoView 는 바깥 칸까지 굴려 버튼 줄이 헤더 밑으로 숨으므로 목록만 옮긴다. 사파리는 첫 그림 전에 옮긴 값을 되돌려 한 번 더
const box = list.current const box = list.current
if (box) box.scrollTop = box.clientHeight * startRef.current const place = () => {
if (box) box.scrollTop = box.clientHeight * startRef.current
}
place()
const raf = requestAnimationFrame(() => {
place()
placed.current = true
})
const root = document.documentElement const root = document.documentElement
const before = root.style.overflow const before = root.style.overflow
root.style.overflow = 'hidden' root.style.overflow = 'hidden'
return () => { return () => {
cancelAnimationFrame(raf)
root.style.overflow = before root.style.overflow = before
} }
}, []) }, [])
@@ -170,6 +217,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
if (!box) return if (!box) return
const io = new IntersectionObserver( const io = new IntersectionObserver(
(entries) => { (entries) => {
if (!placed.current) return
for (const e of entries) if (e.isIntersecting) setAt(Number((e.target as HTMLElement).dataset.i)) for (const e of entries) if (e.isIntersecting) setAt(Number((e.target as HTMLElement).dataset.i))
}, },
{ root: box, threshold: 0.6 }, { root: box, threshold: 0.6 },
@@ -178,7 +226,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
return () => io.disconnect() return () => io.disconnect()
}, []) }, [])
// 미리 띄운 영상이 재생되기 시작하면(첫 장면을 받음) 보이는 영상이 아닐 때 멈추고 처음으로 // 플레이어가 재생을 시작하면(첫 장면을 받음) 보이게 한다. 앞뒤 영상은 멈추지 않는다: 멈췄다 다시 틀면 유튜브가 재생·멈춤 버튼을 영상 위에 띄운다
useEffect(() => { useEffect(() => {
const onMessage = (e: MessageEvent) => { const onMessage = (e: MessageEvent) => {
if (e.origin !== YT_ORIGIN || typeof e.data !== 'string') return if (e.origin !== YT_ORIGIN || typeof e.data !== 'string') return
@@ -192,9 +240,6 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
for (const [i, f] of frames.current) { for (const [i, f] of frames.current) {
if (f.contentWindow !== e.source) continue if (f.contentWindow !== e.source) continue
setReady((r) => (r.has(i) ? r : new Set(r).add(i))) setReady((r) => (r.has(i) ? r : new Set(r).add(i)))
if (i === atRef.current) continue
command(f, 'pauseVideo')
command(f, 'seekTo', [0, true])
} }
} }
window.addEventListener('message', onMessage) window.addEventListener('message', onMessage)
@@ -205,27 +250,21 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
useEffect(() => { useEffect(() => {
if (atRef.current !== at) moved(items[at]) if (atRef.current !== at) moved(items[at])
atRef.current = at atRef.current = at
paused.current = false // 앞뒤 영상은 소리 없이 계속 돌고 있으니, 넘어온 영상만 처음부터 다시 틀고 소리를 맞춘다 (멈춤 명령은 쓰지 않는다)
for (const [i, f] of frames.current) { for (const [i, f] of frames.current) {
if (i === at) { if (i === at) {
command(f, 'seekTo', [0, true])
command(f, soundRef.current ? 'unMute' : 'mute') command(f, soundRef.current ? 'unMute' : 'mute')
command(f, 'playVideo') command(f, 'playVideo')
} else { } else command(f, 'mute')
command(f, 'pauseVideo')
command(f, 'mute')
}
} }
}, [at, items]) }, [at, items])
// 마우스로도 끌어 넘긴다: 영상 위는 유튜브 iframe 이 마우스를 가져가서, 그 위에 투명한 판을 깔고 끈 만큼 목록을 옮긴다. // 마우스로도 끌어 넘긴다: 영상 위는 유튜브 iframe 이 마우스를 가져가서, 그 위에 투명한 판을 깔고 끈 만큼 목록을 옮긴다.
// 손가락은 브라우저 스크롤에 맡기고, 끌지 않고 누르기만 하면 재생·일시정지 // 손가락은 브라우저 스크롤에 맡기고, 끌지 않고 누르기만 하면 릴스처럼 소리 켜기·끄기 (멈추면 유튜브 버튼이 떠서)
const drag = useRef<{ y: number; top: number; moved: boolean } | null>(null) const drag = useRef<{ y: number; top: number; moved: boolean } | null>(null)
const lastPointer = useRef('') const lastPointer = useRef('')
const [dragging, setDragging] = useState(false) const [dragging, setDragging] = useState(false)
const togglePause = () => {
paused.current = !paused.current
command(frames.current.get(atRef.current), paused.current ? 'pauseVideo' : 'playVideo')
}
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => { const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
lastPointer.current = e.pointerType lastPointer.current = e.pointerType
const box = list.current const box = list.current
@@ -248,7 +287,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
drag.current = null drag.current = null
setDragging(false) setDragging(false)
if (!d || !box) return if (!d || !box) return
if (!d.moved) return togglePause() if (!d.moved) return toggleSound()
// 30px 만 끌어도 다음·이전 영상으로, 그보다 덜 끌면 제자리로 // 30px 만 끌어도 다음·이전 영상으로, 그보다 덜 끌면 제자리로
const h = box.clientHeight const h = box.clientHeight
const dy = e.clientY - d.y const dy = e.clientY - d.y
@@ -282,8 +321,9 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
/> />
<div className="absolute inset-0 bg-black/35" aria-hidden="true" /> <div className="absolute inset-0 bg-black/35" aria-hidden="true" />
<div className="relative mx-auto flex h-12 w-full max-w-[440px] shrink-0 items-center justify-between px-3"> <div className="relative mx-auto flex h-12 w-full max-w-[440px] shrink-0 items-center justify-between px-3">
<button type="button" onClick={onClose} aria-label="닫기" className={cx('relative grid size-9 cursor-pointer place-items-center rounded-full bg-white/15 text-xl text-white', TAP44)}> {/* 글자 '×'는 글꼴마다 아래로 처져 그림으로 */}
× <button type="button" onClick={onClose} aria-label="닫기" className={cx('relative grid size-9 cursor-pointer place-items-center rounded-full bg-white/15 text-white', TAP44)}>
<CloseIcon className="size-[18px]" />
</button> </button>
<button type="button" onClick={toggleSound} aria-pressed={sound} className="h-9 cursor-pointer rounded-full bg-white/15 px-3.5 text-[13px] font-bold text-white"> <button type="button" onClick={toggleSound} aria-pressed={sound} className="h-9 cursor-pointer rounded-full bg-white/15 px-3.5 text-[13px] font-bold text-white">
{sound ? '소리 끄기' : '소리 켜기'} {sound ? '소리 끄기' : '소리 켜기'}
@@ -294,6 +334,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
<div key={s.id} data-i={i} className="relative grid h-full snap-start place-items-center"> <div key={s.id} data-i={i} className="relative grid h-full snap-start place-items-center">
<div className="relative" style={FIT}> <div className="relative" style={FIT}>
<img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" className="absolute inset-0 size-full object-cover" /> <img src={`https://i.ytimg.com/vi/${s.id}/hqdefault.jpg`} alt="" className="absolute inset-0 size-full object-cover" />
{/* 릴스처럼 앞뒤 영상을 소리 없이 미리 받아 둔다 */}
{Math.abs(i - at) <= 1 && ( {Math.abs(i - at) <= 1 && (
<iframe <iframe
ref={(f) => { ref={(f) => {
@@ -305,6 +346,13 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
allow="autoplay; encrypted-media; picture-in-picture" allow="autoplay; encrypted-media; picture-in-picture"
// 재생 상태를 받으려면 플레이어에 먼저 '듣고 있다'고 알린다 // 재생 상태를 받으려면 플레이어에 먼저 '듣고 있다'고 알린다
onLoad={(e) => { onLoad={(e) => {
if (PLAIN) {
const t = window.setTimeout(() => {
plainTimers.current.delete(t)
setPlainShown((r) => (r.has(i) ? r : new Set(r).add(i)))
}, PLAIN_SHOW_MS)
plainTimers.current.add(t)
}
e.currentTarget.contentWindow?.postMessage(JSON.stringify({ event: 'listening', id: s.id }), YT_ORIGIN) e.currentTarget.contentWindow?.postMessage(JSON.stringify({ event: 'listening', id: s.id }), YT_ORIGIN)
// 앞뒤 밖으로 밀려나 내려갔다 다시 뜬 플레이어는 첫 장면을 새로 받을 때까지 다시 숨긴다 // 앞뒤 밖으로 밀려나 내려갔다 다시 뜬 플레이어는 첫 장면을 새로 받을 때까지 다시 숨긴다
setReady((r) => { setReady((r) => {
@@ -314,7 +362,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
return next return next
}) })
}} }}
className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', !ready.has(i) && 'opacity-0')} className={cx('absolute inset-0 size-full border-0 transition-opacity duration-200', (PLAIN ? !plainShown.has(i) : !ready.has(i)) && 'opacity-0')}
/> />
)} )}
<div <div
@@ -326,7 +374,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
drag.current = null drag.current = null
setDragging(false) setDragging(false)
}} }}
onClick={() => lastPointer.current !== 'mouse' && togglePause()} onClick={() => lastPointer.current !== 'mouse' && toggleSound()}
className={cx('absolute inset-0 touch-pan-y select-none', dragging ? 'cursor-grabbing' : 'cursor-grab')} className={cx('absolute inset-0 touch-pan-y select-none', dragging ? 'cursor-grabbing' : 'cursor-grab')}
/> />
</div> </div>
+58 -26
View File
@@ -1,44 +1,76 @@
import { useEffect, useEffectEvent, useRef } from 'react'
import { useSearchParams } from 'react-router' import { useSearchParams } from 'react-router'
import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen' import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { TalkCard } from './talk' import { useAuth } from './authContext'
import { TOPICS, useTopicTalks } from './talkState' import { useSheet } from './sheetContext'
import { Sec } from './ui' import { FeedComposer, TalkCard } from './talk'
import { TOPICS, useMyTalks, useTopicTalks } from './talkState'
import { Rail, Sec } from './ui'
/** 주제별 사람 글: 위 주제 탭, 아래 글 목록. 피드 묶음의 '전체 보기'가 ?topic= 으로 연다 */ type Tab = TalkTopic | 'all' | 'mine'
/** 목록 끝이 화면 아래 600px 안에 들어오면 다음 쪽을 받는다 (글이 많아도 버튼 없이 이어서) */
function MoreOnScroll({ onMore }: { onMore: () => void }) {
const ref = useRef<HTMLDivElement>(null)
const more = useEffectEvent(onMore)
useEffect(() => {
const el = ref.current
if (!el) return
const io = new IntersectionObserver(([e]) => e.isIntersecting && more(), { rootMargin: '0px 0px 600px 0px' })
io.observe(el)
return () => io.disconnect()
}, [])
return <div ref={ref} className="h-px" aria-hidden="true" />
}
/** 주제별 사람 글: 위 주제 탭(한 줄 가로로 밀기, 끝에 '내 글'), 아래 글 목록. 피드 묶음의 '전체 보기'가 ?topic= · ?mine=1 로 연다 */
export function TalkPage() { export function TalkPage() {
const [params, setParams] = useSearchParams() const [params, setParams] = useSearchParams()
const { loggedIn } = useAuth()
const { open } = useSheet()
const raw = Number(params.get('topic')) const raw = Number(params.get('topic'))
const topic = TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : undefined const tab: Tab = params.get('mine') ? 'mine' : TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : 'all'
const { talks, loaded, more, loadMore } = useTopicTalks(topic) const topicList = useTopicTalks(tab === 'all' || tab === 'mine' ? undefined : tab)
const tabs: (readonly [TalkTopic | undefined, string])[] = [[undefined, '전체'], ...TOPICS] const mineList = useMyTalks(tab === 'mine' && loggedIn)
const { talks, loaded, more, loadMore } = tab === 'mine' ? mineList : topicList
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...TOPICS, ['mine', '내 글']]
const go = (k: Tab) => setParams(k === 'mine' ? { mine: '1' } : k === 'all' ? {} : { topic: String(k) }, { replace: true })
return ( return (
<section aria-label="동네 사람들 글"> <section aria-label="동네 사람들 글">
<Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" /> <Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" />
<div className="flex flex-wrap gap-1.5 px-4 pb-1" role="tablist" aria-label="글 주제"> <div role="tablist" aria-label="글 주제">
{tabs.map(([k, label]) => ( <Rail className="gap-1.5 pt-0">
<button {tabs.map(([k, label]) => (
key={label} <button
type="button" key={label}
role="tab" type="button"
aria-selected={topic === k} role="tab"
onClick={() => setParams(k ? { topic: String(k) } : {}, { replace: true })} aria-selected={tab === k}
className={cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold', topic === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2)')} onClick={() => go(k)}
> className={cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold whitespace-nowrap', tab === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2)')}
{label} >
</button> {label}
))} </button>
))}
</Rail>
</div> </div>
{loaded && !talks.length && <p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">아직 이 주제 글이 없어요. 오늘 탭에서 첫 글을 써 주세요.</p>} <FeedComposer />
{tab === 'mine' && !loggedIn ? (
<p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">
로그인하면 내가 쓴 글을 모아 볼 수 있어요.{' '}
<button type="button" onClick={() => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--orange)">
로그인
</button>
</p>
) : (
loaded && !talks.length && <p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">{tab === 'mine' ? '아직 쓴 글이 없어요. 위 칸에서 첫 글을 써 주세요.' : '아직 이 주제 글이 없어요. 위 칸에서 첫 글을 써 주세요.'}</p>
)}
{talks.map((t) => ( {talks.map((t) => (
<TalkCard key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} /> <TalkCard key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
))} ))}
{more && ( {more && <MoreOnScroll onMore={() => loadMore()} />}
<button type="button" onClick={() => loadMore()} className="mx-3 mt-3 w-[calc(100%-1.5rem)] cursor-pointer rounded-[14px] bg-white py-2.5 text-[13.5px] font-extrabold text-(--ink2)">
더 보기
</button>
)}
</section> </section>
) )
} }
+44 -34
View File
@@ -12,23 +12,23 @@ import {
type Hero as HeroData, type Hero as HeroData,
type PostReaction, type PostReaction,
type ResWeatherToday, type ResWeatherToday,
type TalkData,
type TopIndex, type TopIndex,
type WeatherSlot, type WeatherSlot,
} from '@nalssigak/shared/api/client/types.gen' } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib' import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
import { fall } from './lib' import { fall } from './lib'
import { useAuth } from './authContext'
import { FoliageCard } from './foliageMap' import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner' import { InstallBanner } from './installBanner'
import { MoonArt } from './moon' import { MoonArt } from './moon'
import { MyGakRow } from './myGak' import { MyGakRow } from './myGak'
import { fromShare } from './myGakState' import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post' import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike, type PinnedKey } from './pinnedLike' import { usePinnedLike } from './pinnedLike'
import { ShortsRail } from './Shorts' import { ShortsRail } from './Shorts'
import { FeedComposer, NearTalks, TalkCard, TalkGroup } from './talk' import { FeedComposer, NearTalks, TalkGroup } from './talk'
import { topicName, useTalkGroups } from './talkState' import { topicName, useTalkGroups, useTodayMyTalks } from './talkState'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { useSky } from './skyContext' import { useSky } from './skyContext'
@@ -159,8 +159,8 @@ const WEATHER_ICON: Record<Weather, string> = {
sleet: 'snow', sleet: 'snow',
} }
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋 // 구름 수: 구름 많음 둘, 흐림·비·눈 셋
// 히어로 오른쪽 위 좋아요·댓글·보내기: 셋 다 같은 32px 칸에 아이콘 가운데, 수는 아이콘 옆 // 히어로 오른쪽 위 좋아요·댓글·보내기: 아이콘마다 좌우 여백을 같게, 숫자가 붙어도 아이콘 사이 간격이 그대로
const HERO_ACT = 'relative flex h-8 min-w-8 cursor-pointer items-center justify-center gap-1 text-[13px] font-extrabold' const HERO_ACT = 'relative flex h-8 cursor-pointer items-center justify-center gap-1 px-[5px] text-[13px] leading-none font-extrabold tabular-nums'
const CLOUDS = [ const CLOUDS = [
{ cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' }, { cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' },
{ cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' }, { cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' },
@@ -211,6 +211,10 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
const kind = mode === 'now' ? nowKind : mode const kind = mode === 'now' ? nowKind : mode
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다 // 화면 전체 하늘 배경도 같은 시간대로 맞춘다
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind]) useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind])
// 내일을 볼 땐 배경·글자색도 내일 고른 칸을 따른다 (오늘 밤을 고른 채 내일 낮을 보면 낮 하늘에 흰 글자가 되던 것)
useEffect(() => {
if (tmr) setPreview(tmrKind)
}, [tmr, tmrKind, setPreview])
const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? [] const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? []
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad
// 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸 // 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
@@ -243,13 +247,14 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
waning: WANING.includes(hero.moon_name), waning: WANING.includes(hero.moon_name),
} }
: null : null
// 말풍선 머리말은 칸 이름 그대로: 지금은 / 아침은 / 낮은 / 저녁은 / 밤은 // 말풍선 머리말: 지금은 / 오늘 낮은 / 내일은 / 내일 낮은 (어느 날 어느 칸인지 같이)
const when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label const when = mode === 'now' || mode === nowKind ? '지금' : `오늘 ${PREVIEW[mode].label}`
const tmrWhen = mode === 'now' ? '내일' : `내일 ${PREVIEW[mode].label}`
const bubble = tmr const bubble = tmr
? top1 ? top1
? top1.score >= 70 ? top1.score >= 70
? `내일은 ${top1.name}!` ? `${tmrWhen}은 ${top1.name}!`
: '내일은 쉬어 가요' : `${tmrWhen}은 쉬어 가요`
: null : null
: slotTop : slotTop
? slotTop.score >= 70 ? slotTop.score >= 70
@@ -326,7 +331,11 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
type="button" type="button"
role="radio" role="radio"
aria-checked={tmr === v} aria-checked={tmr === v}
onClick={() => setTmr(v)} onClick={() => {
// 내일로 넘어갈 땐 지금 보던 시간대 그대로 시작해 배경이 튀지 않게
if (v && !tmr) setTmrKind(kind)
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')} 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} {l}
@@ -516,21 +525,18 @@ function PostsSkel() {
) )
} }
/** 띠도 포스트 틀에 담아 좋아요·댓글·보내기를 단다 (post 는 서버의 띠 자리) */ function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
function Band({ tone, title, sub, to, avatar, post, pinKey, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; avatar: string; post?: PostReaction | null; pinKey: PinnedKey; children: ReactNode }) {
return ( return (
<PostFrame title={title} account={title} avatar={avatar} pinned={{ key: pinKey, post }}> <section className={cx('mt-3.5 pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
<section className={cx('pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}> <Sec title={title} sub={sub} more={{ to }} className="pt-0" />
<Sec title={title} sub={sub} more={{ to }} className="pt-0" /> {children}
{children} </section>
</section>
</PostFrame>
) )
} }
function EventsBand({ events, post }: { events: BandEvent[]; post?: PostReaction | null }) { function EventsBand({ events }: { events: BandEvent[] }) {
return ( return (
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week" avatar="fireworks" post={post} pinKey="events_post"> <Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week">
<Rail> <Rail>
{events.map((e, i) => ( {events.map((e, i) => (
<Link key={e.event_id} to="/week" className="w-[200px] overflow-hidden rounded-[22px] bg-white shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]"> <Link key={e.event_id} to="/week" className="w-[200px] overflow-hidden rounded-[22px] bg-white shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
@@ -547,10 +553,10 @@ function EventsBand({ events, post }: { events: BandEvent[]; post?: PostReaction
) )
} }
function SeasonBand({ news, post }: { news: BandArticle[]; post?: PostReaction | null }) { function SeasonBand({ news }: { news: BandArticle[] }) {
const { open } = useSheet() const { open } = useSheet()
return ( return (
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season" avatar="fallen_leaf" post={post} pinKey="season_post"> <Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season">
<Rail> <Rail>
{news.map((a) => ( {news.map((a) => (
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="w-[200px] cursor-pointer overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]"> <button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="w-[200px] cursor-pointer overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
@@ -579,8 +585,9 @@ export function TodayPage() {
const bands = f?.bands const bands = f?.bands
const nowAt = f?.hero?.now_at const nowAt = f?.hero?.now_at
const load = loadOf(feed) const load = loadOf(feed)
const [mine, setMine] = useState<TalkData[]>([]) // 사람 글은 묶음으로: '동네 사람들'은 오늘의 각 아래, 주제 묶음은 같은 주제 포스트 아래. 오늘 쓴 내 글은 글쓰기 칸 아래 '오늘 내 글'에 따로 있으니 빼고
// 사람 글은 묶음으로: '동네 사람들'은 오늘의 각 아래, 주제 묶음은 같은 주제 포스트 아래. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고 const { loggedIn } = useAuth()
const mine = useTodayMyTalks(loggedIn)
const talkGroups = useTalkGroups() const talkGroups = useTalkGroups()
const groupOf = (topic: number) => (talkGroups.groups.get(topic) ?? []).filter((t) => !mine.some((m) => m.talk_id === t.talk_id)) const groupOf = (topic: number) => (talkGroups.groups.get(topic) ?? []).filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
const group = (topic: number) => { const group = (topic: number) => {
@@ -610,12 +617,12 @@ export function TodayPage() {
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다 // 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [ const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} post={f?.events_post} /> : null], [3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} post={f?.season_post} /> : null], [9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
] ]
// 사람 글 묶음은 포스트 사이사이에 하나씩: 묶음·띠·단풍 카드가 이미 붙는 자리와 바로 앞 자리는 건너뛰어 가로 목록이 연달아 나오지 않게 // 사람 글 묶음은 포스트 사이사이에 하나씩: 묶음·띠·단풍 카드가 이미 붙는 자리와 바로 앞 자리는 건너뛰어 가로 목록이 연달아 나오지 않게
const spreadTopics = [TalkTopic.OUTFIT, ...(raining ? [] : [TalkTopic.RAIN]), ...(sunsetAt < 0 ? [TalkTopic.SKY] : []), ...(posts.length < 2 ? [TalkTopic.FOLIAGE] : [])].filter((tp) => groupOf(tp).length) const spreadTopics = [TalkTopic.OUTFIT, ...(raining ? [] : [TalkTopic.RAIN]), ...(sunsetAt < 0 ? [TalkTopic.SKY] : [])].filter((tp) => groupOf(tp).length)
const taken = new Set([1, sunsetAt, ...bandAt.map(([at]) => at - 1)]) const taken = new Set([1, sunsetAt, ...bandAt.map(([at]) => at - 1)])
const spreadAt = new Map<number, ReactNode>() const spreadAt = new Map<number, ReactNode>()
let spreadN = 0 let spreadN = 0
@@ -630,10 +637,8 @@ export function TodayPage() {
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}> <section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.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)} />
<ShortsRail /> <ShortsRail />
<FeedComposer onPosted={(t) => setMine((m) => [t, ...m])} /> <FeedComposer />
{mine.map((t) => ( {mine.length > 0 && <TalkGroup title="오늘 내 글" talks={mine} href="/talk?mine=1" />}
<TalkCard key={t.talk_id} t={t} onGone={() => setMine((m) => m.filter((x) => x.talk_id !== t.talk_id))} />
))}
{raining && group(TalkTopic.RAIN)} {raining && group(TalkTopic.RAIN)}
<MyGakRow /> <MyGakRow />
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */} {/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
@@ -652,12 +657,17 @@ export function TodayPage() {
{load !== 'loading' && !posts.length && ( {load !== 'loading' && !posts.length && (
<StateBox load="ready" empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'} hold={<PostsSkel />} className="inset-x-3 top-3.5 bottom-auto" /> <StateBox load="ready" empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'} hold={<PostsSkel />} className="inset-x-3 top-3.5 bottom-auto" />
)} )}
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에, 단풍 이야기 묶음은 바로 아래 */}
{load !== 'loading' && posts.length > 0 && (
<>
<FoliageCard />
{group(TalkTopic.FOLIAGE)}
</>
)}
{posts.map((p, i) => ( {posts.map((p, i) => (
<Fragment key={p.post_id}> <Fragment key={p.post_id}>
<PostCard post={p} /> <PostCard post={p} />
{i === sunsetAt && group(TalkTopic.SKY)} {i === sunsetAt && group(TalkTopic.SKY)}
{i === 1 && <FoliageCard post={f?.foliage_post} />}
{i === 1 && group(TalkTopic.FOLIAGE)}
{bandAt.find(([at]) => at === i + 1)?.[1]} {bandAt.find(([at]) => at === i + 1)?.[1]}
{spreadAt.get(i)} {spreadAt.get(i)}
</Fragment> </Fragment>
+67 -27
View File
@@ -2,7 +2,7 @@
.b-app { .b-app {
--ink: #28304a; --ink: #28304a;
--ink2: #5a6380; --ink2: #5a6380;
--ink3: #8a92aa; --ink3: #6b738c;
--line: #e6ecf4; --line: #e6ecf4;
--page: #f7fbff; --page: #f7fbff;
--outer: #dfeaf6; --outer: #dfeaf6;
@@ -120,13 +120,37 @@
} }
} }
/* 아래 창은 불투명한 채로 화면 아래에서 끝까지 올라오고, 닫힐 땐 다시 내려간다 (반투명으로 올라오면 뒤 탭 바가 비쳐 깜빡여 보였다) */
.b-sheet { .b-sheet {
animation: b-up 0.26s cubic-bezier(0.2, 0.9, 0.3, 1); animation: b-up 0.28s cubic-bezier(0.2, 0.9, 0.3, 1);
}
.b-sheet-dialog[open]::backdrop {
animation: b-fade-in 0.2s ease-out;
}
.b-sheet-closing .b-sheet {
animation: b-down 0.2s ease-in forwards;
}
.b-sheet-closing::backdrop {
animation: b-fade-out 0.2s ease-in forwards;
} }
@keyframes b-up { @keyframes b-up {
from { from {
transform: translateY(40px); transform: translateY(100%);
opacity: 0.4; }
}
@keyframes b-down {
to {
transform: translateY(100%);
}
}
@keyframes b-fade-in {
from {
opacity: 0;
}
}
@keyframes b-fade-out {
to {
opacity: 0;
} }
} }
@@ -150,11 +174,13 @@
.b-fall, .b-fall,
.b-heart-pop, .b-heart-pop,
.b-like-bit, .b-like-bit,
.b-sheet { .b-sheet,
.b-sheet-dialog[open]::backdrop {
animation: none !important; animation: none !important;
} }
.b-heart-pop, .b-heart-pop,
.b-like-bit { .b-like-bit,
.b-sheet-closing .b-sheet {
opacity: 0; opacity: 0;
} }
} }
@@ -594,72 +620,86 @@ html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot,
.b-app[data-t='night'] .b-tabbar { .b-app[data-t='night'] .b-tabbar {
--ink: #fff; --ink: #fff;
} }
.b-app[data-t='night'] .bg-white { .b-app[data-t='night'] .bg-white:not(.b-day, .b-day *) {
background-color: var(--card); background-color: var(--card);
} }
.b-app[data-t='night'] [class*='bg-white/'] { .b-app[data-t='night'] [class*='bg-white/']:not(.b-day, .b-day *) {
background-color: rgb(34 42 92 / 0.85); background-color: rgb(34 42 92 / 0.85);
} }
.b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']):not(.b-keep-bg) { .b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']):not(.b-keep-bg, .b-day, .b-day *) {
background: var(--chip); background: var(--chip);
} }
.b-app[data-t='night'] [class*='border-[#dfe5ee]'] { .b-app[data-t='night'] [class*='border-[#dfe5ee]']:not(.b-day, .b-day *) {
border-color: rgb(255 255 255 / 0.12); border-color: rgb(255 255 255 / 0.12);
} }
.b-app[data-t='night'] [class*='rgb(217_229_244'] { .b-app[data-t='night'] [class*='rgb(217_229_244']:not(.b-day, .b-day *) {
box-shadow: inset 0 -5px 0 var(--shade); box-shadow: inset 0 -5px 0 var(--shade);
} }
.b-app[data-t='night'] .bg-\(--ink\) { .b-app[data-t='night'] .bg-\(--ink\):not(.b-day, .b-day *) {
background-color: #4b56b5; background-color: #4b56b5;
color: #fff; color: #fff;
} }
.b-app[data-t='night'] .bg-\(--ink\) .text-\[\#ffb3c4\] { .b-app[data-t='night'] .bg-\(--ink\) .text-\[\#ffb3c4\]:not(.b-day, .b-day *) {
color: #ffd0dc; color: #ffd0dc;
} }
/* b-keep-bg(밤에도 밝은 바탕 그대로) 안은 글자도 그대로 */ /* b-keep-bg(밤에도 밝은 바탕 그대로) 안은 글자도 그대로 */
.b-app[data-t='night'] .text-\[\#28304a\]:not(.b-keep-bg, .b-keep-bg *) { .b-app[data-t='night'] .text-\[\#28304a\]:not(.b-keep-bg, .b-keep-bg *, .b-day, .b-day *) {
color: var(--ink); color: var(--ink);
} }
.b-app[data-t='night'] :is(.text-\[\#1f9d62\], .text-\[\#1f7a4f\]) { .b-app[data-t='night'] :is(.text-\[\#1f9d62\], .text-\[\#1f7a4f\]):not(.b-day, .b-day *) {
color: #4fd39a; color: #4fd39a;
} }
.b-app[data-t='night'] .text-\[\#d6457a\] { .b-app[data-t='night'] .text-\[\#d6457a\]:not(.b-day, .b-day *) {
color: #ff8db5; color: #ff8db5;
} }
.b-app[data-t='night'] .text-\[\#c2471b\] { .b-app[data-t='night'] .text-\[\#c2471b\]:not(.b-day, .b-day *) {
color: #ffab85; color: #ffab85;
} }
.b-app[data-t='night'] .bg-\[\#dff5ea\] { .b-app[data-t='night'] .bg-\[\#dff5ea\]:not(.b-day, .b-day *) {
background: rgb(79 211 154 / 0.16); background: rgb(79 211 154 / 0.16);
} }
.b-app[data-t='night'] .bg-\[\#ffe8dc\] { .b-app[data-t='night'] .bg-\[\#ffe8dc\]:not(.b-day, .b-day *) {
background: rgb(255 138 87 / 0.16); background: rgb(255 138 87 / 0.16);
} }
.b-app[data-t='night'] .b-bg-sky { .b-app[data-t='night'] .b-bg-sky:not(.b-day, .b-day *) {
background: linear-gradient(180deg, #2a4384, #1f2c62); background: linear-gradient(180deg, #2a4384, #1f2c62);
} }
.b-app[data-t='night'] .b-bg-butter { .b-app[data-t='night'] .b-bg-butter:not(.b-day, .b-day *) {
background: linear-gradient(180deg, #4d4128, #2c2a3e); background: linear-gradient(180deg, #4d4128, #2c2a3e);
} }
.b-app[data-t='night'] .b-bg-peach { .b-app[data-t='night'] .b-bg-peach:not(.b-day, .b-day *) {
background: linear-gradient(180deg, #553632, #2e2840); background: linear-gradient(180deg, #553632, #2e2840);
} }
.b-app[data-t='night'] .b-bg-mint { .b-app[data-t='night'] .b-bg-mint:not(.b-day, .b-day *) {
background: linear-gradient(180deg, #1f4a45, #1d2d4a); background: linear-gradient(180deg, #1f4a45, #1d2d4a);
} }
.b-app[data-t='night'] .b-bg-lilac { .b-app[data-t='night'] .b-bg-lilac:not(.b-day, .b-day *) {
background: linear-gradient(180deg, #3d3480, #262a5e); background: linear-gradient(180deg, #3d3480, #262a5e);
} }
.b-app[data-t='night'] .b-band-1 { .b-app[data-t='night'] .b-band-1:not(.b-day, .b-day *) {
background: linear-gradient(180deg, rgb(255 160 110 / 0.12), rgb(255 255 255 / 0)); background: linear-gradient(180deg, rgb(255 160 110 / 0.12), rgb(255 255 255 / 0));
} }
.b-app[data-t='night'] .b-band-2 { .b-app[data-t='night'] .b-band-2:not(.b-day, .b-day *) {
background: linear-gradient(180deg, rgb(255 214 110 / 0.12), rgb(255 255 255 / 0)); background: linear-gradient(180deg, rgb(255 214 110 / 0.12), rgb(255 255 255 / 0));
} }
.b-app[data-t='night'] .b-band-3 { .b-app[data-t='night'] .b-band-3:not(.b-day, .b-day *) {
background: linear-gradient(180deg, rgb(110 230 180 / 0.12), rgb(255 255 255 / 0)); background: linear-gradient(180deg, rgb(110 230 180 / 0.12), rgb(255 255 255 / 0));
} }
/* 밤에도 포스트 카드 본문은 낮 색 그대로 (어두운 카드가 줄줄이 이어지지 않게). 위 밤 덮어쓰기는 이 안을 뺀다 */
.b-app[data-t='night'] .b-day {
--ink: #28304a;
--ink2: #5a6380;
--ink3: #6b738c;
--line: #e6ecf4;
--shade: #d9e5f4;
--orange: #ff7a45;
--heart: #ff3b5c;
--skel: color-mix(in oklab, currentColor 13%, transparent);
color: var(--ink);
color-scheme: light;
}
.b-app[data-t='night'] img[data-dark] { .b-app[data-t='night'] img[data-dark] {
filter: drop-shadow(0 0 1px rgb(255 255 255 / 0.9)) drop-shadow(0 0 6px rgb(255 255 255 / 0.3)); filter: drop-shadow(0 0 1px rgb(255 255 255 / 0.9)) drop-shadow(0 0 6px rgb(255 255 255 / 0.3));
} }
+4 -4
View File
@@ -1,7 +1,6 @@
import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react' import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useNavigate } from 'react-router' import { useNavigate } from 'react-router'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen'
import { useCarousel } from './carousel' import { useCarousel } from './carousel'
import { headline, ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, spread, useFoliage, useLabelSize } from './foliage' import { headline, ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, spread, useFoliage, useLabelSize } from './foliage'
import { PostFrame } from './Post' import { PostFrame } from './Post'
@@ -14,7 +13,7 @@ const TAP_R = 24
const RANK_N = 7 const RANK_N = 7
/** 피드의 단풍 지도 카드: 1장은 지금 절정인 곳만 잎 아이콘으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위. '지도 크게 보기'로 단풍 지도 페이지 */ /** 피드의 단풍 지도 카드: 1장은 지금 절정인 곳만 잎 아이콘으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위. '지도 크게 보기'로 단풍 지도 페이지 */
export function FoliageCard({ post }: { post?: PostReaction | null }) { export function FoliageCard() {
const navigate = useNavigate() const navigate = useNavigate()
const { today, spots, inSeason } = useFoliage() const { today, spots, inSeason } = useFoliage()
const peak = useMemo(() => spots.filter((m) => m.stage === 'peak').sort((a, b) => Number(a.kind === 'ginkgo') - Number(b.kind === 'ginkgo') || a.y - b.y), [spots]) const peak = useMemo(() => spots.filter((m) => m.stage === 'peak').sort((a, b) => Number(a.kind === 'ginkgo') - Number(b.kind === 'ginkgo') || a.y - b.y), [spots])
@@ -56,7 +55,7 @@ export function FoliageCard({ post }: { post?: PostReaction | null }) {
// 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로 // 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로
const ranked = rankNow(spots).slice(0, RANK_N) const ranked = rankNow(spots).slice(0, RANK_N)
return ( return (
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" pinned={{ key: 'foliage_post', post }} caption={peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined}> <PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined}>
<div className="b-keep-bg relative bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]"> <div className="b-keep-bg relative bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 text-[13px] font-extrabold opacity-75">단풍 지도 · {md(today)}</p> <p className="m-0 text-[13px] font-extrabold opacity-75">단풍 지도 · {md(today)}</p>
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">{headline(spots)}</p> <p className="m-0 mt-1 font-jua text-[24px] leading-tight">{headline(spots)}</p>
@@ -66,7 +65,8 @@ export function FoliageCard({ post }: { post?: PostReaction | null }) {
</span> </span>
<div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요"> <div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
<div className="flex"> <div className="flex">
<div className="min-w-0 shrink-0 grow-0 basis-full"> {/* 밀어 낸 지도가 옆 장(가기 좋은 곳)을 덮지 않게 이 장 밖은 자른다 */}
<div className="min-w-0 shrink-0 grow-0 basis-full overflow-hidden">
{/* 지도 그림은 땅이 왼쪽에 치우쳐 있어 오른쪽(빈 바다)으로 밀어 가운데에 맞춘다 */} {/* 지도 그림은 땅이 왼쪽에 치우쳐 있어 오른쪽(빈 바다)으로 밀어 가운데에 맞춘다 */}
<div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full translate-x-[7%] bg-[#fff6ea]"> <div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full translate-x-[7%] bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={MAP_IMG} /> <img src={MAP_SRC} alt="" className={MAP_IMG} />
+20 -34
View File
@@ -2,43 +2,20 @@ import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen' import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
type GoogleId = { import { loadGoogle } from './googleScript'
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void import { SHEET_OPEN_MS } from './lib'
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void import { Skel } from './ui'
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 로그인 창을 처음 열 때 한 번만 받는다 */
function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */ /** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) { export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id const config = useQuery({ ...authConfigOptions(), staleTime: Infinity })
const clientId = config.data?.google_client_id
const login = useMutation(googleLoginMutation()) const login = useMutation(googleLoginMutation())
const box = useRef<HTMLDivElement>(null) const box = useRef<HTMLDivElement>(null)
const [broken, setBroken] = useState(false) const [broken, setBroken] = useState(false)
// 구글 버튼(iframe)이 다 그려지기 전엔 같은 크기의 스켈레톤을 보여 준다. 빈칸에 버튼이 툭 튀어나오면 버벅이는 것처럼 보여서
const [ready, setReady] = useState(false)
const { mutate } = login const { mutate } = login
// 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다 // 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다
const cb = useRef({ onResult, onFail }) const cb = useRef({ onResult, onFail })
@@ -49,8 +26,10 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
useEffect(() => { useEffect(() => {
if (!clientId || !box.current) return if (!clientId || !box.current) return
let alive = true let alive = true
loadGoogle().then( // 버튼(iframe)을 만드는 일이 무거워, 로그인 창이 다 올라온 뒤에 만든다. 자리는 min-h 로 잡아 둬서 밀리지 않는다
(g) => { const wait = new Promise((r) => setTimeout(r, SHEET_OPEN_MS))
Promise.all([loadGoogle(), wait]).then(
([g]) => {
if (!alive || !box.current) return if (!alive || !box.current) return
g.initialize({ g.initialize({
client_id: clientId, client_id: clientId,
@@ -61,6 +40,9 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
}, },
}) })
g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth }) g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth })
const frame = box.current.querySelector('iframe')
if (frame) frame.addEventListener('load', () => alive && setReady(true), { once: true })
else setReady(true)
}, },
(e: unknown) => { (e: unknown) => {
console.error('[google] script', e) console.error('[google] script', e)
@@ -72,10 +54,14 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
} }
}, [clientId, mutate]) }, [clientId, mutate])
if (config.isPending) return <Skel shape className="mx-auto h-[44px] w-full max-w-[400px] rounded-full" />
if (!clientId) return null if (!clientId) return null
return ( return (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<div ref={box} className="flex min-h-[44px] justify-center" aria-busy={login.isPending} /> <div className="relative">
{!ready && !broken && <Skel shape className="absolute inset-x-0 top-0 mx-auto h-[44px] w-full max-w-[400px] rounded-full" />}
<div ref={box} className={cx('flex min-h-[44px] justify-center transition-opacity duration-200', ready ? 'opacity-100' : 'opacity-0')} aria-busy={login.isPending || !ready} />
</div>
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>} {broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
</div> </div>
) )
+40
View File
@@ -0,0 +1,40 @@
export type GoogleId = {
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 한 번만 받는다. 실패하면 다음에 다시 받는다 */
export function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
/** 로그인 안 한 사람은 화면이 한가할 때 스크립트를 미리 받아 둔다. 로그인 창이 올라오는 도중에 스크립트를 실행하느라 화면이 멈추지 않게. 돌려준 함수로 취소 */
export function preloadGoogle(): () => void {
const run = () => void loadGoogle().catch((e: unknown) => console.error('[google] preload', e))
if ('requestIdleCallback' in window) {
const id = requestIdleCallback(run, { timeout: 4000 })
return () => cancelIdleCallback(id)
}
const id = setTimeout(run, 2500)
return () => clearTimeout(id)
}
+5
View File
@@ -14,3 +14,8 @@ export function iconSrc(name: string) {
export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: [ARTICLE_LABEL[1], 'text-[#1f9d62]'], 2: [ARTICLE_LABEL[2], 'text-[#7a5cd6]'], 3: [ARTICLE_LABEL[3], 'text-(--orange)'] } export const ARTICLE_CAT: Record<number, [string, string]> = { 1: [ARTICLE_LABEL[1], 'text-[#1f9d62]'], 2: [ARTICLE_LABEL[2], 'text-[#7a5cd6]'], 3: [ARTICLE_LABEL[3], 'text-(--orange)'] }
/** 아래 창이 다 올라오는 시간(.b-sheet 0.26s). 무거운 일은 이 뒤로 미뤄 올라오는 동안 버벅이지 않게 */
export const SHEET_OPEN_MS = 280
/** 아래 창이 내려가며 닫히는 시간(.b-sheet-closing 0.2s). 이 뒤에 실제로 닫는다 */
export const SHEET_CLOSE_MS = 200
+173 -37
View File
@@ -1,7 +1,8 @@
import { useState, type ReactNode } from 'react' import { useRef, useState, type ReactNode } from 'react'
import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen' import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState' import { gakName, MY_GAK_ICON, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
import { MyGakShareCard } from './shareCards'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { Ic, Rail, Sec } from './ui' import { Ic, Rail, Sec } from './ui'
@@ -27,55 +28,160 @@ function Reasons({ s }: { s?: MyGakScore }) {
) )
} }
/** 오늘 탭의 내 각 줄: 내가 정한 조건으로 매긴 오늘 점수 */ // 조건 이름. 점수 응답의 factors 와 reasons 는 같은 순서다
const AXIS_NAME: Record<string, string> = { temp: '기온', rain: '비', wind: '바람', air: '미세먼지', humidity: '습도' }
// 조건 점수가 이보다 낮으면 '아쉬운 조건'으로 카드에 칩을 단다
const SHORT = 70
/** 조건마다 이름·점수·실제 값 (실제 값은 근거 문구의 첫 마디: 체감 15°) */
function conditions(s?: MyGakScore) {
const notes = s?.reasons ?? []
return Object.entries(s?.factors ?? {}).map(([axis, value], i) => ({ axis, label: AXIS_NAME[axis] ?? axis, value, note: notes[i] ?? '', short: (notes[i] ?? '').split(', ')[0] }))
}
/** 오늘 탭의 내 각 줄: 카드엔 아이콘·이름·점수·아쉬운 조건만, 누르면 상세 창 */
export function MyGakRow() { export function MyGakRow() {
const { open } = useSheet() const { open } = useSheet()
const { items, remove } = useMyGak() const { items } = useMyGak()
const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? [] const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? []
const [copied, setCopied] = useState<number | null>(null) const shots = useRef<(HTMLDivElement | null)[]>([])
const send = (g: MyGak, i: number) => {
const url = shareUrl(g)
if (navigator.share) {
navigator.share({ title: `${g.name} · 날씨각`, url }).catch((e: unknown) => {
if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[myGak] share', e)
})
return
}
navigator.clipboard.writeText(url).then(
() => setCopied(i),
(e: unknown) => console.error('[myGak] copy', e),
)
}
return ( return (
<> <>
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" /> <Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
<Rail label="내 각"> <Rail label="내 각">
{items.map((g, i) => ( {items.map((g, i) => {
<div key={g.id ?? 'local'} className="flex w-[220px] flex-col gap-1.5 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]"> const s = scores[i]
<div className="flex items-center gap-1"> const miss = conditions(s).filter((c) => c.value < SHORT).slice(0, 2)
<b className="font-jua text-[17px] leading-tight font-normal">{g.name}</b> return (
<Score s={scores[i]} /> <button
</div> key={g.id ?? 'local'}
<Reasons s={scores[i]} /> type="button"
<div className="mt-auto flex gap-1.5 pt-0.5"> onClick={() => open({ type: 'myGak', gak: g, shot: shots.current[i] })}
<button type="button" onClick={() => send(g, i)} className="cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white"> aria-label={`${g.name} ${s?.score ?? ''}점 자세히`}
{copied === i ? '링크 복사함' : '친구에게 보내기'} className="flex w-[200px] cursor-pointer flex-col gap-2 rounded-[22px] bg-white p-3 text-left shadow-[inset_0_-5px_0_var(--shade)]"
</button> >
<button type="button" onClick={() => remove(g)} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[12.5px] font-extrabold text-(--ink2)"> <span className="flex w-full items-start justify-between">
지우기 <Ic name={g.icon ?? MY_GAK_ICON} className="size-10" />
</button> <Score s={s} big />
</div> </span>
</div> <span>
))} <b className="block font-jua text-[17px] leading-tight font-normal">{g.name}</b>
<small className="text-xs font-bold text-(--ink3)">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준` : '예보를 불러오는 중이에요'}</small>
</span>
{s?.slot && (
<span className="flex flex-wrap gap-1 text-[11.5px] font-extrabold">
{miss.length ? (
miss.map((c) => (
<span key={c.axis} className="rounded-full bg-[#ffe8dc] px-2 py-0.5 text-[#c2471b]">
{c.short}
</span>
))
) : (
<span className="rounded-full bg-[#dff5ea] px-2 py-0.5 text-[#1f7a4f]">조건 다 맞아요</span>
)}
</span>
)}
</button>
)
})}
<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)"> <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> <span className="text-[26px] leading-none">+</span>
내 각 만들기 내 각 만들기
</button> </button>
</Rail> </Rail>
{items.map((g, i) => (
<MyGakShareCard
key={g.id ?? 'local'}
name={g.name}
icon={g.icon ?? MY_GAK_ICON}
score={scores[i]?.score}
slot={scores[i]?.slot ? SLOT_WORD[scores[i].slot as Slot] : undefined}
rows={conditions(scores[i])}
ref={(el) => {
shots.current[i] = el
}}
/>
))}
</> </>
) )
} }
/** 내 각 상세: 시간대별 점수, 조건별 점수와 실제 값, 공유하기(다른 포스트와 같은 공유 창)·지우기 */
export function MyGakSheet({ gak, shot, onDone }: { gak: MyGak; shot?: HTMLElement | null; onDone: () => void }) {
const { open } = useSheet()
const { remove } = useMyGak()
const s = useMyGakScores([gak.rule]).data?.scores?.[0]
const [confirm, setConfirm] = useState(false)
const rows = conditions(s)
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
<div className="flex items-center gap-3">
<Ic name={gak.icon ?? MY_GAK_ICON} className="size-14" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[22px] leading-tight font-normal">{gak.name}</b>
<small className="text-[12.5px] font-bold text-(--ink3)">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준 점수` : '예보를 불러오는 중이에요'}</small>
</span>
<Score s={s} big />
</div>
<div className="mt-3 grid grid-cols-4 gap-1.5" aria-label="시간대별 점수">
{SLOTS.map(([k, word]) => {
const v = s?.slots?.[k]
return (
<div key={k} className={cx('rounded-2xl px-1 py-2 text-center', s?.slot === k ? 'bg-[#fff4ec]' : 'bg-[#f3f6fb]')}>
<small className="block text-xs font-extrabold text-(--ink2)">{word}</small>
<b className={cx('block font-bagel text-xl font-normal', v != null ? 'text-(--orange)' : 'text-(--ink3)')}>{v ?? '–'}</b>
</div>
)
})}
</div>
<div className="mt-3.5 flex flex-col gap-2.5">
{rows.map((c) => (
<div key={c.axis} className="grid grid-cols-[64px_1fr_32px] items-center gap-x-2.5 text-[13.5px] font-bold">
<span>{c.label}</span>
<i className="block h-[9px] overflow-hidden rounded-full bg-[#e3eaf4]">
<s className="b-keep-bg block h-full bg-[linear-gradient(90deg,#ffc86e,var(--orange))]" style={{ width: `${c.value}%` }} />
</i>
<em className="text-right text-xs text-(--ink2) not-italic tabular-nums">{c.value}</em>
<p className="col-start-2 col-end-4 m-0 -mt-0.5 text-[12.5px] font-semibold text-(--ink2)">{c.note}</p>
</div>
))}
</div>
<div className="mt-4 flex gap-2">
<button
type="button"
onClick={() => open({ type: 'share', share: { title: gak.name, slides: shot ? [shot] : [], url: shareUrl(gak) } })}
disabled={!shot}
className="flex-1 cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[16px] text-white disabled:opacity-45"
>
공유하기
</button>
{confirm ? (
<>
<button
type="button"
onClick={() => {
remove(gak)
onDone()
}}
className="cursor-pointer rounded-2xl bg-[#fdecec] px-4 py-3 font-jua text-[16px] text-(--heart)"
>
지우기
</button>
<button type="button" onClick={() => setConfirm(false)} className="cursor-pointer rounded-2xl bg-[#eef4fc] px-4 py-3 font-jua text-[16px] text-(--ink2)">
취소
</button>
</>
) : (
<button type="button" onClick={() => setConfirm(true)} className="cursor-pointer rounded-2xl bg-[#eef4fc] px-4 py-3 font-jua text-[16px] text-(--ink2)">
지우기
</button>
)}
</div>
{confirm && <p className="mt-1.5 mb-0 text-right text-[12.5px] font-bold text-(--ink2)">지울까요?</p>}
</div>
)
}
function Row({ label, on, onToggle, children }: { label: string; on: boolean; onToggle: () => void; children: ReactNode }) { function Row({ label, on, onToggle, children }: { label: string; on: boolean; onToggle: () => void; children: ReactNode }) {
return ( return (
<div className={cx('flex min-h-[44px] flex-wrap items-center gap-2 border-b border-(--line) py-2', !on && 'opacity-60')}> <div className={cx('flex min-h-[44px] flex-wrap items-center gap-2 border-b border-(--line) py-2', !on && 'opacity-60')}>
@@ -124,6 +230,32 @@ 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 }) 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 IconPicker({ value, onPick }: { value: string; onPick: (icon: string) => void }) {
const icons = [...new Set([MY_GAK_ICON, ...(usePresets().data ?? []).map((p) => p.icon)])]
return (
<div className="mt-3">
<span className="font-jua text-[19px]">아이콘</span>
<div className="-mx-4">
<Rail label="아이콘" className="gap-1.5">
{icons.map((icon) => (
<button
key={icon}
type="button"
aria-pressed={value === icon}
aria-label={`아이콘 ${icon}`}
onClick={() => onPick(icon)}
className={cx('grid size-12 cursor-pointer place-items-center rounded-2xl', value === icon ? 'bg-(--orange) ring-2 ring-(--orange)' : 'bg-[#f3f6fb]')}
>
<Ic name={icon} className="size-8" />
</button>
))}
</Rail>
</div>
</div>
)
}
/** 있는 각을 골라 그 각 조건으로 채운다 */ /** 있는 각을 골라 그 각 조건으로 채운다 */
function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) { function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) {
const items = usePresets().data ?? [] const items = usePresets().data ?? []
@@ -159,9 +291,11 @@ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => voi
const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE) const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE)
const [on, setOn] = useState<Record<Cond, boolean>>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false }) const [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 [picked, setPicked] = useState<string | null>(null)
const [icon, setIcon] = useState(shared?.icon ?? MY_GAK_ICON)
const pick = (p: MyGakPreset) => { const pick = (p: MyGakPreset) => {
setPicked(p.code) setPicked(p.code)
setName(p.name) setName(p.name)
setIcon(p.icon)
setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE) setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE)
setOn(condsOf(p.rule)) setOn(condsOf(p.rule))
} }
@@ -184,6 +318,7 @@ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => voi
<span className="font-jua text-[19px]">이름</span> <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]" /> <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> </label>
<IconPicker value={icon} onPick={setIcon} />
</> </>
)} )}
<fieldset disabled={!!shared} className="m-0 mt-3 border-0 p-0"> <fieldset disabled={!!shared} className="m-0 mt-3 border-0 p-0">
@@ -215,7 +350,8 @@ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => voi
</div> </div>
</fieldset> </fieldset>
<div className="mt-2 flex flex-col gap-1.5 rounded-[20px] bg-[#f3f6fb] p-3.5"> <div className="mt-2 flex flex-col gap-1.5 rounded-[20px] bg-[#f3f6fb] p-3.5">
<div className="flex items-center"> <div className="flex items-center gap-2">
<Ic name={icon} className="size-8" />
<b className="font-jua text-[20px] font-normal">{title}</b> <b className="font-jua text-[20px] font-normal">{title}</b>
<Score s={valid ? score : undefined} big /> <Score s={valid ? score : undefined} big />
</div> </div>
@@ -225,7 +361,7 @@ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => voi
<button <button
type="button" type="button"
disabled={!valid || !gakName(name) || pending} disabled={!valid || !gakName(name) || pending}
onClick={() => create({ name, rule }, onDone)} onClick={() => create({ name, icon, rule }, onDone)}
className="mt-3.5 w-full cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[17px] text-white disabled:cursor-default disabled:opacity-45" className="mt-3.5 w-full cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[17px] text-white disabled:cursor-default disabled:opacity-45"
> >
{shared ? '내 각으로 가져오기' : '내 각으로 저장'} {shared ? '내 각으로 가져오기' : '내 각으로 저장'}
+11 -7
View File
@@ -19,7 +19,10 @@ export const SLOTS: [Slot, string][] = [
] ]
/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) */ /** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) */
export type MyGak = { id?: number; name: string; rule: MyGakRule } export type MyGak = { id?: number; name: string; icon?: string | null; rule: MyGakRule }
/** 아이콘을 안 골랐을 때 */
export const MY_GAK_ICON = 'rabbit'
function readLocal(): MyGak | null { function readLocal(): MyGak | null {
try { try {
@@ -58,7 +61,7 @@ export const gakName = (name: string) => {
/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 */ /** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 */
export function shareUrl(g: MyGak) { export function shareUrl(g: MyGak) {
const json = JSON.stringify({ n: g.name, r: g.rule }) const json = JSON.stringify({ n: g.name, i: g.icon ?? undefined, r: g.rule })
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json))) const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)))
return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}` return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`
} }
@@ -66,8 +69,9 @@ export function shareUrl(g: MyGak) {
export function fromShare(code: string): MyGak | null { export function fromShare(code: string): MyGak | null {
try { try {
const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/')) const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/'))
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; r?: unknown } const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; i?: unknown; r?: unknown }
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, rule: v.r as MyGakRule } : null const icon = typeof v.i === 'string' && /^[a-z_]{1,32}$/.test(v.i) ? v.i : null
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, icon, rule: v.r as MyGakRule } : null
} catch (e) { } catch (e) {
console.warn('[myGak] 받은 링크를 읽지 못함', e) console.warn('[myGak] 받은 링크를 읽지 못함', e)
return null return null
@@ -108,14 +112,14 @@ export function useMyGak() {
const { mutate } = add const { mutate } = add
useEffect(() => { useEffect(() => {
if (!loggedIn || !saved) return if (!loggedIn || !saved) return
mutate({ body: { name: saved.name, rule: saved.rule } }, { onSuccess: () => setLocal(null) }) mutate({ body: { name: saved.name, icon: saved.icon, rule: saved.rule } }, { onSuccess: () => setLocal(null) })
}, [loggedIn, saved, mutate]) }, [loggedIn, saved, mutate])
const items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, rule: g.rule })) : saved ? [saved] : [] const items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, icon: g.icon, rule: g.rule })) : saved ? [saved] : []
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */ /** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
const create = (g: MyGak, onDone?: () => void) => { const create = (g: MyGak, onDone?: () => void) => {
const item = { name: gakName(g.name), rule: g.rule } const item = { name: gakName(g.name), icon: g.icon, rule: g.rule }
if (loggedIn) { if (loggedIn) {
add.mutate({ body: item }, { onSuccess: (res) => res.result?.success && onDone?.() }) add.mutate({ body: item }, { onSuccess: (res) => res.result?.success && onDone?.() })
return return
+29
View File
@@ -185,3 +185,32 @@ export function FoliageMapShare({ title, peak, ranked, ref }: { title: string; p
</Offscreen> </Offscreen>
) )
} }
/** 내 각 공유: 아이콘·이름·점수, 조건마다 막대와 실제 값. 로고·지역·날짜는 공유 틀이 그린다 */
export function MyGakShareCard({ name, icon, score, slot, rows, ref }: { name: string; icon: string; score?: number | null; slot?: string; rows: { axis: string; label: string; value: number; note: string }[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="b-band-1 flex aspect-[4/5] flex-col bg-white px-5 pt-5 pb-4 text-[#28304a]">
<p className="m-0 text-[13px] font-extrabold opacity-75">내 각{slot ? ` · ${slot} 기준` : ''}</p>
<div className="mt-2 flex items-center gap-3">
<Ic name={icon} className="w-[64px] shrink-0" />
<b className="min-w-0 flex-1 font-jua text-[28px] leading-tight font-normal">{name}</b>
<em className="font-bagel text-[52px] leading-none text-[#ff7a45] not-italic">{score ?? '–'}</em>
</div>
<ul className="m-0 mt-4 grid list-none gap-2.5 p-0">
{rows.map((r) => (
<li key={r.axis} className="rounded-[18px] bg-white px-3 py-2.5 shadow-[inset_0_-4px_0_#d9e5f4]">
<span className="flex items-center gap-2 text-[14px] font-extrabold">
{r.label}
<i className="block h-[8px] flex-1 overflow-hidden rounded-full bg-[#e3eaf4]">
<s className="block h-full bg-[linear-gradient(90deg,#ffc86e,#ff7a45)]" style={{ width: `${r.value}%` }} />
</i>
</span>
<small className="mt-0.5 block text-[12.5px] font-semibold text-[#5a6380]">{r.note}</small>
</li>
))}
</ul>
</div>
</Offscreen>
)
}
+3 -2
View File
@@ -2,8 +2,8 @@ import type { MyGak } from './myGakState'
import type { TalkData } from '@nalssigak/shared/api/client/types.gen' import type { TalkData } from '@nalssigak/shared/api/client/types.gen'
import type { WeatherWhyPayload } from './weatherWhy' import type { WeatherWhyPayload } from './weatherWhy'
import { createContext, use } from 'react' import { createContext, use } from 'react'
/** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides) */ /** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides). url: 같이 보낼 링크 (없으면 사이트 주소) */
export type SharePayload = { title: string; slides: HTMLElement[]; square?: HTMLElement[] } export type SharePayload = { title: string; slides: HTMLElement[]; square?: HTMLElement[]; url?: string }
type CommentsState = { type: 'comments'; postId: number; draft?: string } type CommentsState = { type: 'comments'; postId: number; draft?: string }
@@ -17,6 +17,7 @@ export type SheetState =
| { type: 'me' } | { type: 'me' }
| { type: 'region' } | { type: 'region' }
| { type: 'mix'; shared?: MyGak } | { type: 'mix'; shared?: MyGak }
| { type: 'myGak'; gak: MyGak; shot?: HTMLElement | null }
| { type: 'install' } | { type: 'install' }
| { type: 'weatherWhy'; why: WeatherWhyPayload } | { type: 'weatherWhy'; why: WeatherWhyPayload }
| { type: 'talk'; talk: TalkData } | { type: 'talk'; talk: TalkData }
+44 -15
View File
@@ -2,7 +2,9 @@ import { domToCanvas } from 'modern-screenshot'
import { API_BASE_URL } from '../api/setup' import { API_BASE_URL } from '../api/setup'
const W = 1080 const W = 1080
const SIDE = 60 const SIDE = 24
// 1:1·4:5 아래 띠 높이: 날씨각 · 동네·날짜 · 주소 한 줄
const FOOT = 84
// 시간대별 배경 (화면 하늘 배경과 같은 색) // 시간대별 배경 (화면 하늘 배경과 같은 색)
const SKY: Record<string, [string, string, string]> = { const SKY: Record<string, [string, string, string]> = {
@@ -12,11 +14,14 @@ const SKY: Record<string, [string, string, string]> = {
night: ['#0e1433', '#1b2356', '#2a2e6e'], night: ['#0e1433', '#1b2356', '#2a2e6e'],
} }
/** 공유 이미지 크기. 위: 로고·지역 날짜, 가운데: 카드, 아래: 주소 */ /**
* 공유 이미지 크기. 9:16 은 위 로고·지역 날짜, 가운데 카드, 아래 주소 알약.
* 1:1·4:5(strip)는 카드를 크게 두고 아래 얇은 띠 한 줄(날씨각 · 지역 날짜 · 주소)만
*/
export const SHARE_SIZES = { export const SHARE_SIZES = {
story: { ratio: '9:16', w: 9, hr: 16, h: 1920, logoY: 250, logoPx: 96, subY: 325, subPx: 40, pillY: 1760, pillH: 100, labelPx: 34, hostPx: 46 }, story: { ratio: '9:16', w: 9, hr: 16, h: 1920, strip: false, logoY: 250, logoPx: 96, subY: 325, subPx: 40, pillY: 1760, pillH: 100, labelPx: 34, hostPx: 46 },
feed: { ratio: '4:5', w: 4, hr: 5, h: 1350, logoY: 140, logoPx: 76, subY: 200, subPx: 34, pillY: 1250, pillH: 84, labelPx: 30, hostPx: 40 }, feed: { ratio: '4:5', w: 4, hr: 5, h: 1350, strip: true, logoY: 0, logoPx: 40, subY: 0, subPx: 26, pillY: 0, pillH: 0, labelPx: 0, hostPx: 32 },
square: { ratio: '1:1', w: 1, hr: 1, h: 1080, logoY: 115, logoPx: 64, subY: 168, subPx: 30, pillY: 990, pillH: 80, labelPx: 28, hostPx: 38 }, square: { ratio: '1:1', w: 1, hr: 1, h: 1080, strip: true, logoY: 0, logoPx: 40, subY: 0, subPx: 26, pillY: 0, pillH: 0, labelPx: 0, hostPx: 32 },
} as const } as const
export type ShareSize = keyof typeof SHARE_SIZES export type ShareSize = keyof typeof SHARE_SIZES
@@ -113,7 +118,7 @@ type Box = { x: number; y: number; w: number; h: number }
function place(n: number, aspect: number, top: number, bottom: number): Box[] { function place(n: number, aspect: number, top: number, bottom: number): Box[] {
const room = bottom - top const room = bottom - top
if (n === 1) { if (n === 1) {
const w = Math.min(W - SIDE * 3, room / aspect) const w = Math.min(W - SIDE * 2, room / aspect)
const h = w * aspect const h = w * aspect
return [{ x: (W - w) / 2, y: top + (room - h) / 2, w, h }] return [{ x: (W - w) / 2, y: top + (room - h) / 2, w, h }]
} }
@@ -152,11 +157,11 @@ export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize;
document.fonts.load(LOGO(z.hostPx), opts.host), document.fonts.load(LOGO(z.hostPx), opts.host),
document.fonts.load(LOGO(36), '12'), document.fonts.load(LOGO(36), '12'),
document.fonts.load(SANS(z.subPx), opts.sub), document.fonts.load(SANS(z.subPx), opts.sub),
document.fonts.load(SANS(z.labelPx), PILL_LABEL), ...(z.strip ? [] : [document.fonts.load(SANS(z.labelPx), PILL_LABEL)]),
]) ])
const css = await fontCss(cards.map((c) => c.textContent ?? '').join('')) const css = await fontCss(cards.map((c) => c.textContent ?? '').join(''))
const aspect = cards[0].offsetHeight / cards[0].offsetWidth const aspect = cards[0].offsetHeight / cards[0].offsetWidth
const boxes = place(cards.length, aspect, z.subY + 60, z.pillY - z.pillH / 2 - 50) const boxes = z.strip ? place(cards.length, aspect, SIDE, z.h - FOOT) : place(cards.length, aspect, z.subY + 60, z.pillY - z.pillH / 2 - 50)
const shots = await Promise.all(cards.map((c, i) => domToCanvas(c, { scale: boxes[i].w / c.offsetWidth, filter: keep, font: css ? { cssText: css } : false, fetchFn: viaProxy }))) const shots = await Promise.all(cards.map((c, i) => domToCanvas(c, { scale: boxes[i].w / c.offsetWidth, filter: keep, font: css ? { cssText: css } : false, fetchFn: viaProxy })))
const canvas = document.createElement('canvas') const canvas = document.createElement('canvas')
@@ -173,13 +178,15 @@ export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize;
ctx.fillStyle = bg ctx.fillStyle = bg
ctx.fillRect(0, 0, W, z.h) ctx.fillRect(0, 0, W, z.h)
ctx.textAlign = 'center' if (!z.strip) {
ctx.fillStyle = '#ff7a45' ctx.textAlign = 'center'
ctx.font = LOGO(z.logoPx) ctx.fillStyle = '#ff7a45'
ctx.fillText('날씨각', W / 2, z.logoY) ctx.font = LOGO(z.logoPx)
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380' ctx.fillText('날씨각', W / 2, z.logoY)
ctx.font = SANS(z.subPx) ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
ctx.fillText(opts.sub, W / 2, z.subY, W - SIDE * 2) ctx.font = SANS(z.subPx)
ctx.fillText(opts.sub, W / 2, z.subY, W - SIDE * 2)
}
const r = 40 * (boxes[0].w / 900) const r = 40 * (boxes[0].w / 900)
shots.forEach((shot, i) => { shots.forEach((shot, i) => {
@@ -200,6 +207,28 @@ export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize;
}) })
if (shots.length > 1) boxes.forEach((b, i) => badge(ctx, b.x + 6, b.y + 6, i + 1)) if (shots.length > 1) boxes.forEach((b, i) => badge(ctx, b.x + 6, b.y + 6, i + 1))
if (z.strip) {
// 아래 띠: 왼쪽 [날씨각 지역 · 날짜], 오른쪽 주소. 카드 양 끝에 맞춘다
const left = Math.min(...boxes.map((b) => b.x))
const right = Math.max(...boxes.map((b) => b.x + b.w))
const y = z.h - FOOT / 2 + 2
ctx.textBaseline = 'middle'
ctx.textAlign = 'left'
ctx.fillStyle = '#ff7a45'
ctx.font = LOGO(z.logoPx)
ctx.fillText('날씨각', left, y)
const logoW = ctx.measureText('날씨각').width
ctx.font = LOGO(z.hostPx)
const hostW = ctx.measureText(opts.host).width
ctx.textAlign = 'right'
ctx.fillText(opts.host, right, y)
ctx.textAlign = 'left'
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
ctx.font = SANS(z.subPx)
ctx.fillText(opts.sub, left + logoW + 16, y, Math.max(0, right - hostW - 24 - (left + logoW + 16)))
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png'))
}
// 주소 알약: [오늘 내 동네 각 보기 host] // 주소 알약: [오늘 내 동네 각 보기 host]
ctx.font = SANS(z.labelPx) ctx.font = SANS(z.labelPx)
const lw = ctx.measureText(PILL_LABEL).width const lw = ctx.measureText(PILL_LABEL).width
+18 -1
View File
@@ -5,7 +5,7 @@ const line = { fill: 'none', stroke: 'currentColor', strokeLinecap: 'round', str
// 좋아요·댓글·보내기 세 아이콘이 나란히 놓일 때 크기가 같아 보이게: 하트는 원래 그림이 작아 10% 키우고(보이는 칸을 좁힘), 보내기는 커서 5% 줄인다 // 좋아요·댓글·보내기 세 아이콘이 나란히 놓일 때 크기가 같아 보이게: 하트는 원래 그림이 작아 10% 키우고(보이는 칸을 좁힘), 보내기는 커서 5% 줄인다
export function HeartIcon({ className }: P) { export function HeartIcon({ className }: P) {
return ( return (
<svg viewBox="1.1 2.75 21.8 21.8" className={className} aria-hidden="true"> <svg viewBox="1.1 1.95 21.8 21.8" className={className} aria-hidden="true">
<path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" /> <path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" />
</svg> </svg>
) )
@@ -27,6 +27,23 @@ export function SendIcon({ className }: P) {
) )
} }
export function CloseIcon({ className }: P) {
return (
<svg viewBox="0 0 24 24" {...line} strokeWidth="2.4" className={className} aria-hidden="true">
<path d="M6 6l12 12M18 6 6 18" />
</svg>
)
}
export function CameraIcon({ className }: P) {
return (
<svg viewBox="0 0 24 24" {...line} strokeWidth="2" className={className} aria-hidden="true">
<path d="M4 8.5A1.5 1.5 0 0 1 5.5 7h2.2l1.5-2h5.6l1.5 2h2.2A1.5 1.5 0 0 1 20 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 17.5z" />
<circle cx="12" cy="13" r="3.5" />
</svg>
)
}
export function PinIcon({ className }: P) { export function PinIcon({ className }: P) {
return ( return (
<svg viewBox="0 0 24 24" {...line} strokeWidth="2.2" className={className} aria-hidden="true"> <svg viewBox="0 0 24 24" {...line} strokeWidth="2.2" className={className} aria-hidden="true">
+58 -36
View File
@@ -12,14 +12,13 @@ import {
import { uploadTalkImage } from '@nalssigak/shared/api/client/sdk.gen' import { uploadTalkImage } from '@nalssigak/shared/api/client/sdk.gen'
import { TalkReport, TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen' import { TalkReport, TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen'
import { API_BASE_URL } from '../api/setup' import { API_BASE_URL } from '../api/setup'
import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { useAuth } from './authContext' import { useAuth } from './authContext'
import { ago, kst } from '@nalssigak/shared/lib' import { kst } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { topicName, TOPICS, useMyTalks } from './talkState' import { topicName, TOPICS, useMyTalks } from './talkState'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { HeartIcon } from './svg' import { CameraIcon, HeartIcon } from './svg'
import { Avatar, Rail, TAP44 } from './ui' import { Avatar, Rail, TAP44 } from './ui'
const BODY_MAX = 100 const BODY_MAX = 100
@@ -32,8 +31,6 @@ const WRITE_ERRORS: Record<string, string> = {
INVALID_INPUT: '100자 안으로 써 주세요.', INVALID_INPUT: '100자 안으로 써 주세요.',
} }
// 글이 이보다 적으면 '동네 사람들' 묶음 대신 첫 글 쓰기 카드
const GROUP_MIN = 3
const COMPOSE_ID = 'talk-compose' const COMPOSE_ID = 'talk-compose'
const REASONS = [ const REASONS = [
@@ -130,13 +127,19 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
id={COMPOSE_ID} id={COMPOSE_ID}
value={text} value={text}
onChange={(e) => setText(e.target.value)} onChange={(e) => setText(e.target.value)}
onFocus={(e) => { // 로그인 전엔 읽기 전용이라 눌러도 키보드가 안 올라온다 (키보드가 떴다 내려가며 로그인 창이 버벅이던 것). 누르거나 Enter 면 로그인 창
onClick={(e) => {
if (loggedIn) return if (loggedIn) return
// 로그인 창(<dialog>)은 닫힐 때 포커스를 이 칸으로 돌려놓아 다시 열리므로, 열기 전에 포커스를 뺀다 // 창이 닫힐 때 포커스가 이 칸으로 돌아와 테두리가 번쩍이지 않게
e.currentTarget.blur() e.currentTarget.blur()
open({ type: 'login' }) open({ type: 'login' })
}} }}
readOnly={busy} onKeyDown={(e) => {
if (loggedIn || (e.key !== 'Enter' && e.key !== ' ')) return
e.preventDefault()
open({ type: 'login' })
}}
readOnly={busy || !loggedIn}
maxLength={BODY_MAX} maxLength={BODY_MAX}
rows={2} rows={2}
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`} placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
@@ -167,8 +170,9 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
</div> </div>
<input ref={fileRef} type="file" accept="image/*" onChange={pick} hidden /> <input ref={fileRef} type="file" accept="image/*" onChange={pick} hidden />
<div className="mt-1.5 flex items-center gap-2 text-xs font-bold text-(--ink3)"> <div className="mt-1.5 flex items-center gap-2 text-xs font-bold text-(--ink3)">
<button type="button" onClick={() => (loggedIn ? fileRef.current?.click() : open({ type: 'login' }))} disabled={busy} className="shrink-0 cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2) disabled:opacity-40"> {/* 주제 칩과 헷갈리지 않게 글자 대신 카메라 아이콘 */}
사진 <button type="button" onClick={() => (loggedIn ? fileRef.current?.click() : open({ type: 'login' }))} disabled={busy} aria-label="사진 붙이기" className={cx('relative grid size-8 shrink-0 cursor-pointer place-items-center rounded-full bg-[#eef4fc] text-(--ink2) disabled:opacity-40', TAP44)}>
<CameraIcon className="size-[18px]" />
</button> </button>
<span className="min-w-0 truncate">{me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}</span> <span className="min-w-0 truncate">{me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}</span>
<span className="ml-auto tabular-nums"> <span className="ml-auto tabular-nums">
@@ -194,7 +198,7 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
const refresh = useRefreshTalks() const refresh = useRefreshTalks()
const [liked, setLiked] = useState(t.liked) const [liked, setLiked] = useState(t.liked)
const [count, setCount] = useState(t.like_count) const [count, setCount] = useState(t.like_count)
const [menu, setMenu] = useState<'closed' | 'open' | 'report' | 'done'>('closed') const [menu, setMenu] = useState<'closed' | 'open' | 'confirm' | 'report' | 'done'>('closed')
const like = useMutation(likeTalkMutation()) const like = useMutation(likeTalkMutation())
const unlike = useMutation(unlikeTalkMutation()) const unlike = useMutation(unlikeTalkMutation())
const remove = useMutation(deleteTalkMutation()) const remove = useMutation(deleteTalkMutation())
@@ -236,7 +240,7 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
const src = t.image?.startsWith('/v1/') ? API_BASE_URL + t.image : (t.image ?? undefined) const src = t.image?.startsWith('/v1/') ? API_BASE_URL + t.image : (t.image ?? undefined)
return ( return (
<div className={cx('grid grid-cols-[34px_1fr_24px] gap-2.5 border-b border-(--line) py-2.5 last:border-b-0', compact ? 'h-full w-full items-stretch' : 'items-start')}> <div className={cx('grid grid-cols-[34px_1fr_auto] gap-2.5 border-b border-(--line) py-2.5 last:border-b-0', compact ? 'h-full w-full items-stretch' : 'items-start')}>
<span className="self-start"> <span className="self-start">
<Avatar character={t.character} color={t.color} mood={t.mood} /> <Avatar character={t.character} color={t.color} mood={t.mood} />
</span> </span>
@@ -244,6 +248,7 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
<div className={cx('min-w-0', compact && 'flex flex-col')}> <div className={cx('min-w-0', compact && 'flex flex-col')}>
<small className={cx('block text-xs font-bold text-(--ink3)', compact && 'truncate')}> <small className={cx('block text-xs font-bold text-(--ink3)', compact && 'truncate')}>
<b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b> <b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b>
{t.mine && <span className="mr-1 rounded-full bg-[#ffe8dc] px-1.5 py-px text-[11px] font-extrabold text-[#c2471b]">내 글</span>}
{[t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ')} {[t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ')}
</small> </small>
{/* 묶음 안 작은 카드는 글이 잘리니, 누르면 창에서 글 전체·큰 사진을 본다 */} {/* 묶음 안 작은 카드는 글이 잘리니, 누르면 창에서 글 전체·큰 사진을 본다 */}
@@ -257,22 +262,24 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
)} )}
{t.image && !compact && <img src={src} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />} {t.image && !compact && <img src={src} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
<small className={cx('block text-xs font-bold text-(--ink3)', compact ? 'mt-auto pt-1.5' : 'mt-0.5')}> <small className={cx('block text-xs font-bold text-(--ink3)', compact ? 'mt-auto pt-1.5' : 'mt-0.5')}>
{ago(t.created_at)} · 좋아요 {count}개 {t.ago} · 좋아요 {count}개
{!IS_TOSS && (
<>
{' · '}
<button type="button" onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
{t.mine ? '내 글' : '더보기'}
</button>
</>
)}
</small> </small>
{menu !== 'closed' && ( {menu !== 'closed' && (
<div className="mt-1.5 flex flex-wrap gap-1.5 text-[12.5px] font-extrabold" role="group" aria-label="글 메뉴"> <div className="mt-1.5 flex flex-wrap gap-1.5 text-[12.5px] font-extrabold" role="group" aria-label="글 메뉴">
{menu === 'done' ? ( {menu === 'done' ? (
<span className="text-[#1f9d62]">처리했어요</span> <span className="text-[#1f9d62]">처리했어요</span>
) : t.mine && menu === 'confirm' ? (
<>
<span className="self-center text-(--ink2)">지울까요?</span>
<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>
<button type="button" onClick={() => setMenu('closed')} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
취소
</button>
</>
) : t.mine ? ( ) : t.mine ? (
<button type="button" onClick={() => remove.mutate({ path: { talk_id: t.talk_id } }, { ...after, onSuccess: (res) => (after.onSuccess(res), res.result?.success && onGone?.()) })} disabled={remove.isPending} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)"> <button type="button" onClick={() => setMenu('confirm')} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
지우기 지우기
</button> </button>
) : menu === 'report' ? ( ) : menu === 'report' ? (
@@ -299,25 +306,36 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
</div> </div>
)} )}
</div> </div>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="좋아요" className={cx('relative cursor-pointer self-start pt-1', TAP44)}> {/* 글 메뉴(⋯)는 하트 옆 오른쪽 위에: 아래 줄 끝에 두면 말줄임표처럼 읽힌다 */}
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} /> <span className="flex items-start gap-4 self-start">
</button> <button
type="button"
onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')}
aria-expanded={menu !== 'closed'}
aria-label="글 메뉴"
className={cx('relative cursor-pointer pt-0.5 text-[15px] leading-none font-extrabold tracking-[1px] text-(--ink3)', TAP44)}
>
⋯
</button>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
</button>
</span>
</div> </div>
) )
} }
/** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */ /** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */
/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 방금 올린 글은 바로 아래에 보인다 (피드 사이 글은 새로 받을 때 섞인다) */ /** 피드 위 쓰는 칸. 늘 펼쳐 두고, 오늘 쓴 내 글은 바로 아래 '오늘 내 글' 묶음에 보인다 */
export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void }) { export function FeedComposer() {
if (IS_TOSS) return null
return ( return (
<div className="mt-3.5"> <div className="mt-3.5">
<Composer onDone={onPosted} /> <Composer />
</div> </div>
) )
} }
/** 묶음에서 누른 글 하나를 창으로: 글 전체·큰 사진·좋아요·더보기 */ /** 묶음에서 누른 글 하나를 창으로: 글 전체·큰 사진·좋아요·글 메뉴 */
export function TalkSheet({ talk }: { talk: TalkData }) { export function TalkSheet({ talk }: { talk: TalkData }) {
return ( return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pb-[18px]"> <div className="flex-1 overflow-auto overscroll-contain px-4 pb-[18px]">
@@ -329,19 +347,20 @@ export function TalkSheet({ talk }: { talk: TalkData }) {
/** 피드에 끼우는 글 한 장 */ /** 피드에 끼우는 글 한 장 */
export function TalkCard({ t, onGone }: { t: TalkData; onGone?: () => void }) { export function TalkCard({ t, onGone }: { t: TalkData; onGone?: () => void }) {
return ( return (
<article className="mt-3.5 border-y border-(--line) bg-white px-3" aria-label={`${t.nickname}의 글`}> <article className="mx-3 mt-3 rounded-[20px] bg-white px-3 shadow-[inset_0_-4px_0_var(--shade)]" aria-label={`${t.nickname}의 글`}>
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} onGone={onGone} /> <TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} onGone={onGone} />
</article> </article>
) )
} }
/** 오늘 피드의 사람 글 묶음: 옆으로 넘기는 카드, 끝에 그 주제 전체 보기 */ /** 오늘 피드의 사람 글 묶음: 옆으로 넘기는 카드, 끝에 그 주제 전체 보기 */
export function TalkGroup({ title, topic, talks }: { title: string; topic?: number; talks: TalkData[] }) { /** href: 오른쪽 위 '전체 보기'가 여는 곳 (없으면 이야기 탭의 그 주제) */
export function TalkGroup({ title, topic, talks, href }: { title: string; topic?: number; talks: TalkData[]; href?: string }) {
return ( return (
<section aria-label={title} className="mt-3.5"> <section aria-label={title} className="mt-3.5">
<div className="flex items-end justify-between px-4"> <div className="flex items-end justify-between px-4">
<h2 className="m-0 font-jua text-[19px] font-normal">{title}</h2> <h2 className="m-0 font-jua text-[19px] font-normal">{title}</h2>
<Link to={topic ? `/talk?topic=${topic}` : '/talk'} className="text-[13px] font-bold text-(--ink2)"> <Link to={href ?? (topic ? `/talk?topic=${topic}` : '/talk')} className="text-[13px] font-bold text-(--ink2)">
전체 보기 전체 보기
</Link> </Link>
</div> </div>
@@ -360,7 +379,10 @@ export function TalkGroup({ title, topic, talks }: { title: string; topic?: numb
export function FirstTalkCard() { export function FirstTalkCard() {
const { region } = useRegion() const { region } = useRegion()
const place = region.name.split(' ').at(-1) const place = region.name.split(' ').at(-1)
const { loggedIn } = useAuth()
const { open } = useSheet()
const go = () => { const go = () => {
if (!loggedIn) return open({ type: 'login' })
const el = document.getElementById(COMPOSE_ID) const el = document.getElementById(COMPOSE_ID)
el?.scrollIntoView({ behavior: 'smooth', block: 'center' }) el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
el?.focus({ preventScroll: true }) el?.focus({ preventScroll: true })
@@ -376,11 +398,11 @@ export function FirstTalkCard() {
) )
} }
/** '동네 사람들' 자리: 글이 GROUP_MIN 개 이상이면 묶음, 아니면 첫 글 쓰기 */ /** '동네 사람들' 자리: 글이 하나라도 있으면 묶음, 없으면 첫 글 쓰기 */
export function NearTalks({ talks, loaded }: { talks: TalkData[]; loaded: boolean }) { export function NearTalks({ talks, loaded }: { talks: TalkData[]; loaded: boolean }) {
if (!loaded) return null if (!loaded) return null
if (talks.length >= GROUP_MIN) return <TalkGroup title="동네 사람들" talks={talks} /> if (talks.length) return <TalkGroup title="동네 사람들" talks={talks} />
return IS_TOSS ? null : <FirstTalkCard /> return <FirstTalkCard />
} }
/** 내 정보 창의 내가 쓴 글 */ /** 내 정보 창의 내가 쓴 글 */
+16 -2
View File
@@ -1,6 +1,8 @@
import { useInfiniteQuery, useQuery } from '@tanstack/react-query' import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions, talkGroupsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { useState } from 'react'
import { listMyTalksInfiniteOptions, listMyTalksOptions, listTalksInfiniteOptions, talkGroupsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen' import { TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen'
import { kst } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
// 글 주제와 피드 묶음 이름 // 글 주제와 피드 묶음 이름
@@ -37,10 +39,22 @@ export function useTopicTalks(topic?: TalkTopic) {
} }
} }
/** 오늘(한국 날짜) 쓴 내 글, 최신순. 로그인했을 때만 받는다 */
export function useTodayMyTalks(loggedIn: boolean) {
const q = useQuery({ ...listMyTalksOptions(), enabled: loggedIn })
// 오늘 날짜는 화면을 연 때 기준으로 한 번만
const [now] = useState(() => kst(new Date()))
return (q.data?.talks ?? []).filter((t) => {
const d = kst(t.created_at)
return d.y === now.y && d.mo === now.mo && d.d === now.d
})
}
/** 내가 쓴 글 (최신순) */ /** 내가 쓴 글 (최신순) */
export function useMyTalks() { export function useMyTalks(enabled = true) {
const list = useInfiniteQuery({ const list = useInfiniteQuery({
...listMyTalksInfiniteOptions(), ...listMyTalksInfiniteOptions(),
enabled,
initialPageParam: {}, initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined, getNextPageParam: (last) => last.next_cursor ?? undefined,
}) })
+79
View File
@@ -0,0 +1,79 @@
import { moonPath } from '@nalssigak/shared/lib/today';
import { useId } from 'react';
import Svg, { Circle, ClipPath, Defs, Ellipse, FeGaussianBlur, Filter, G, Path, RadialGradient, Stop } from 'react-native-svg';
// 앞면 바다(어두운 무늬) 자리: [x, y, 가로 반지름, 세로 반지름]. 실제 달 앞면 배치를 대강 따른다 (웹 frontend/src/b/moon.tsx 와 같다)
const MARIA: [number, number, number, number][] = [
[-0.32, -0.36, 0.3, 0.26],
[0.12, -0.36, 0.17, 0.15],
[0.3, -0.06, 0.2, 0.17],
[-0.56, 0.06, 0.26, 0.42],
[0.66, -0.26, 0.1, 0.12],
[0.52, 0.22, 0.13, 0.15],
[-0.14, 0.44, 0.18, 0.13],
[-0.46, 0.5, 0.1, 0.09],
];
// 작은 크레이터: [x, y, 반지름]
const CRATERS: [number, number, number][] = [
[0.1, 0.72, 0.07],
[0.42, 0.52, 0.05],
[-0.66, -0.5, 0.05],
[0.62, 0.52, 0.04],
[-0.2, 0.08, 0.04],
];
// 저녁(노을)엔 노을빛이 도는 달, 밤엔 하얀 달
const TONES = {
night: { body: ['#fffcf2', '#f6ebcb', '#e0cc98'], shade: '#1a2050' },
dusk: { body: ['#fff8ee', '#ffe2cc', '#f2b9a2'], shade: '#4a2a63' },
};
/** 오늘 밤 실제 모양대로 그린 달. pct 는 빛나는 면의 비율 0~100, 기우는 달은 왼쪽이 밝다. 빛 번짐까지 그려서 달 지름은 size 의 2/3 */
export function MoonArt({ pct, waxing, tone = 'night', size }: { pct: number; waxing: boolean; tone?: keyof typeof TONES; size: number }) {
const id = useId().replace(/[^a-zA-Z0-9]/g, '');
const t = TONES[tone];
const k = pct / 100;
const full = pct >= 99;
const hidden = pct <= 1;
return (
<Svg viewBox="-1.5 -1.5 3 3" width={size} height={size} pointerEvents="none">
<Defs>
<RadialGradient id={`${id}glow`} cx="0" cy="0" r="1.5" gradientUnits="userSpaceOnUse">
<Stop offset="0.6" stopColor="#fff4cf" stopOpacity={0.55} />
<Stop offset="0.8" stopColor="#ffe9a8" stopOpacity={0.16} />
<Stop offset="1" stopColor="#ffe9a8" stopOpacity={0} />
</RadialGradient>
<RadialGradient id={`${id}body`} cx="-0.2" cy="-0.28" r="1.44" gradientUnits="userSpaceOnUse">
<Stop offset="0" stopColor={t.body[0]} />
<Stop offset="0.6" stopColor={t.body[1]} />
<Stop offset="1" stopColor={t.body[2]} />
</RadialGradient>
<RadialGradient id={`${id}limb`} cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse">
<Stop offset="0.72" stopColor="#8a6f3c" stopOpacity={0} />
<Stop offset="1" stopColor="#8a6f3c" stopOpacity={0.28} />
</RadialGradient>
<ClipPath id={`${id}disc`}>
<Circle r="1" />
</ClipPath>
<Filter id={`${id}soft`} x="-0.2" y="-0.2" width="1.4" height="1.4">
<FeGaussianBlur stdDeviation="0.035" />
</Filter>
</Defs>
{!hidden && <Circle r="1.5" fill={`url(#${id}glow)`} opacity={full ? 1 : 0.12 + 0.8 * k} />}
<G clipPath={`url(#${id}disc)`}>
<Circle r="1" fill={`url(#${id}body)`} />
<G filter={`url(#${id}soft)`} fill="#c4b287" opacity={0.55}>
{MARIA.map(([x, y, rx, ry]) => (
<Ellipse key={`${x},${y}`} cx={x} cy={y} rx={rx} ry={ry} />
))}
</G>
{CRATERS.map(([x, y, r]) => (
<Circle key={`${x},${y}`} cx={x} cy={y} r={r} fill="#efe2bd" stroke="#cdbb8c" strokeWidth={0.018} opacity={0.8} />
))}
<Circle r="1" fill={`url(#${id}limb)`} />
{/* 안 보이는 쪽: 흐릿한 경계로 덮고, 땅빛(지구조) 정도만 비치게 */}
{!full && <Path d={moonPath(pct, 1.04, false)} fill={t.shade} opacity={0.94} filter={`url(#${id}soft)`} transform={waxing ? undefined : 'scale(-1,1)'} />}
</G>
{hidden && <Circle r="1" fill="none" stroke="#fff" strokeOpacity={0.18} strokeWidth={0.025} />}
</Svg>
);
}
+27 -3
View File
@@ -5,11 +5,12 @@ import type { SlideBg } from '@nalssigak/shared/lib/types';
import { deg } from '@nalssigak/shared/lib/weatherText'; import { deg } from '@nalssigak/shared/lib/weatherText';
import { Image } from 'expo-image'; import { Image } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient'; import { LinearGradient } from 'expo-linear-gradient';
import type { ReactNode } from 'react'; import { useState, type ReactNode } from 'react';
import { Pressable, StyleSheet, View } from 'react-native'; import { Pressable, StyleSheet, View } from 'react-native';
import { Text } from '@/components/text'; import { Text } from '@/components/text';
import Svg, { Polygon } from 'react-native-svg'; import Svg, { Polygon } from 'react-native-svg';
import { MoonArt } from '@/components/moon';
import { Credit, Ic, Rows, Thumb } from '@/components/ui'; import { Credit, Ic, Rows, Thumb } from '@/components/ui';
import { CARD_BG } from '@/lib/colors'; import { CARD_BG } from '@/lib/colors';
import { useSheet } from '@/lib/sheet'; import { useSheet } from '@/lib/sheet';
@@ -54,7 +55,7 @@ export function slideBg(post: PostData, slide: Slide): SlideBg {
if (slide.kind === 'week') return 'mint'; if (slide.kind === 'week') return 'mint';
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter'; if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter';
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length]; if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length];
if (post.post_type === PostType.EVENT) return 'night'; if (post.post_type === PostType.EVENT || post.post_type === PostType.MOON) return 'night';
if (post.post_type === PostType.TIP) return 'sky'; if (post.post_type === PostType.TIP) return 'sky';
if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac'; if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac';
if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint'; if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint';
@@ -86,6 +87,28 @@ function Pic({ name, widthPct = 42 }: { name: string; widthPct?: number }) {
); );
} }
// 달 포스트 밤하늘 별: [left %, top %, 크기]
const STARS: [number, number, number][] = [
[8, 34, 2], [18, 52, 1.5], [30, 40, 2.5], [44, 30, 1.5], [52, 58, 2], [62, 22, 1.5], [90, 18, 2], [94, 44, 1.5], [12, 70, 1.5], [38, 66, 2], [76, 74, 1.5], [86, 64, 2], [24, 12, 1.5], [70, 10, 2.5],
];
/** 달 포스트 그림: 아이콘 대신 오늘 밤 실제 모양의 달과 별 */
function MoonPic({ pct, waxing }: { pct: number; waxing: boolean }) {
const [w, setW] = useState(0);
return (
<View pointerEvents="none" style={StyleSheet.absoluteFill} onLayout={(e) => setW(e.nativeEvent.layout.width)}>
{STARS.map(([x, y, s]) => (
<View key={`${x},${y}`} className="absolute rounded-full bg-white opacity-80" style={{ left: `${x}%`, top: `${y}%`, width: s, height: s }} />
))}
{w > 0 && (
<View className="absolute top-[22%] right-0">
<MoonArt pct={pct} waxing={waxing} size={w * 0.6} />
</View>
)}
</View>
);
}
export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) { export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
const { open } = useSheet(); const { open } = useSheet();
const { kind } = useSky(); const { kind } = useSky();
@@ -246,13 +269,14 @@ export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
); );
return ( return (
<Base colors={colors}> <Base colors={colors}>
{slide.moon_pct != null && <MoonPic pct={slide.moon_pct} waxing={!!slide.moon_waxing} />}
<Eyebrow light={light} className={light ? 'opacity-85' : undefined}> <Eyebrow light={light} className={light ? 'opacity-85' : undefined}>
{slide.eyebrow} {slide.eyebrow}
</Eyebrow> </Eyebrow>
<Big light={light} className="z-[1]"> <Big light={light} className="z-[1]">
{slide.line} {slide.line}
</Big> </Big>
<Pic name={slide.icon} widthPct={36} /> {slide.moon_pct == null && <Pic name={slide.icon} widthPct={36} />}
<Rows rows={slide.rows ?? []} dark={light} /> <Rows rows={slide.rows ?? []} dark={light} />
</Base> </Base>
); );
+7 -1
View File
@@ -200,6 +200,11 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
<View className="flex-1"> <View className="flex-1">
<Text className="text-sm text-ink"> <Text className="text-sm text-ink">
<Text className="font-extrabold">{c.nickname} </Text> <Text className="font-extrabold">{c.nickname} </Text>
{c.official && (
<>
<Text className="bg-orange text-[10.5px] font-extrabold text-white">{' 날씨각 '}</Text>{' '}
</>
)}
{c.body} {c.body}
</Text> </Text>
<View className="mt-0.5 flex-row flex-wrap items-center"> <View className="mt-0.5 flex-row flex-wrap items-center">
@@ -214,7 +219,8 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
</> </>
)} )}
</Text> </Text>
{!c.mine && <CommentMenu c={c} postId={postId} onNotice={onNotice} />} {/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
{!c.mine && !c.official && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
</View> </View>
</View> </View>
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="댓글 좋아요" className="pt-1"> <Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="댓글 좋아요" className="pt-1">
+19 -7
View File
@@ -1,15 +1,16 @@
import type { Hero as HeroData, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen'; import type { Hero as HeroData, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { kindOfHour, kst, type Load, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'; import { kindOfHour, kst, type Load, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib';
import { KINDS, moonPath, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today'; import { KINDS, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today';
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText'; import { deg, slotAt } from '@nalssigak/shared/lib/weatherText';
import { useEffect, useState, type ReactNode } from 'react'; import { useEffect, useState, type ReactNode } from 'react';
import { Pressable, View, type DimensionValue, type ViewStyle } from 'react-native'; import { Pressable, View, type DimensionValue, type ViewStyle } from 'react-native';
import { Text } from '@/components/text'; import { Text } from '@/components/text';
import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated'; import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
import { LinearGradient } from 'expo-linear-gradient'; import { LinearGradient } from 'expo-linear-gradient';
import Svg, { Defs, Path, RadialGradient, Rect, Stop } from 'react-native-svg'; import Svg, { Defs, RadialGradient, Rect, Stop } from 'react-native-svg';
import { Fall } from '@/components/fall'; import { Fall } from '@/components/fall';
import { MoonArt } from '@/components/moon';
import { Shoot, type ShootSpec } from '@/components/sky-bg'; import { Shoot, type ShootSpec } from '@/components/sky-bg';
import { Ic, Skel } from '@/components/ui'; import { Ic, Skel } from '@/components/ui';
import { useSheet } from '@/lib/sheet'; import { useSheet } from '@/lib/sheet';
@@ -140,6 +141,12 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
const snow = weather === 'snow' || weather === 'sleet'; const snow = weather === 'snow' || weather === 'sleet';
const orb = ORB[kind === 'sunset' ? 'sunset' : kind === 'night' ? 'night' : 'sun']; const orb = ORB[kind === 'sunset' ? 'sunset' : kind === 'night' ? 'night' : 'sun'];
const text = dark ? 'text-white' : 'text-[#28304a]'; const text = dark ? 'text-white' : 'text-[#28304a]';
// 가운데가 밝은 달이면 진한 글씨에 흰 번짐, 가운데가 어두운 달(초승·그믐·삭)이면 흰 글씨
const orbText: { color: string; textShadowColor?: string; textShadowRadius?: number } = !moon
? { color: orb.text }
: moon.pct >= 50
? { color: orb.text, textShadowColor: '#fff', textShadowRadius: 8 }
: { color: '#fff', textShadowColor: 'rgba(10,14,40,0.6)', textShadowRadius: 8 };
return ( return (
<View className="mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3"> <View className="mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3">
@@ -157,7 +164,13 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
</Text> </Text>
<View className="h-[146px] items-center"> <View className="h-[146px] items-center">
<Fall d={0} f={5600} amp={8}> <Fall d={0} f={5600} amp={8}>
<View className="mt-2 size-32 items-center justify-center" style={{ boxShadow: `0 20px 40px ${kind === 'night' ? 'rgb(190 180 255 / 0.35)' : kind === 'sunset' ? 'rgb(255 150 110 / 0.4)' : 'rgb(240 106 58 / 0.32)'}`, borderRadius: 64 }}> <View className="mt-2 size-32 items-center justify-center" style={moon ? undefined : { boxShadow: `0 20px 40px ${kind === 'night' ? 'rgb(190 180 255 / 0.35)' : kind === 'sunset' ? 'rgb(255 150 110 / 0.4)' : 'rgb(240 106 58 / 0.32)'}`, borderRadius: 64 }}>
{/* 저녁·밤엔 오늘 밤 실제 모양의 달 (빛 번짐까지 그려서 공보다 크게) */}
{moon ? (
<View pointerEvents="none" style={{ position: 'absolute', top: -32, left: -32 }}>
<MoonArt pct={moon.pct} waxing={!moon.waning} tone={kind === 'sunset' ? 'dusk' : 'night'} size={192} />
</View>
) : (
<Svg viewBox="-1 -1 2 2" width={128} height={128} style={{ position: 'absolute' }}> <Svg viewBox="-1 -1 2 2" width={128} height={128} style={{ position: 'absolute' }}>
<Defs> <Defs>
<RadialGradient id="orb" cx="-0.32" cy="-0.4" r="1.4" gradientUnits="userSpaceOnUse"> <RadialGradient id="orb" cx="-0.32" cy="-0.4" r="1.4" gradientUnits="userSpaceOnUse">
@@ -168,13 +181,12 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
</RadialGradient> </RadialGradient>
</Defs> </Defs>
<Rect x="-1" y="-1" width="2" height="2" rx="1" fill="url(#orb)" opacity={gray ? 0.85 : 1} /> <Rect x="-1" y="-1" width="2" height="2" rx="1" fill="url(#orb)" opacity={gray ? 0.85 : 1} />
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
{moon && <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> </Svg>
<Text className="font-jua text-[12px]" style={{ color: orb.text }}> )}
<Text className="font-jua text-[12px]" style={orbText}>
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`} {failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</Text> </Text>
<Text className="font-bagel text-[52px] leading-[52px]" style={{ color: orb.text }}> <Text className="font-bagel text-[52px] leading-[52px]" style={orbText}>
{heroVal(feedLoad, score, 'w-[84px] h-10')} {heroVal(feedLoad, score, 'w-[84px] h-10')}
</Text> </Text>
</View> </View>
+32 -6
View File
@@ -646,18 +646,18 @@ export type GakSlide = {
* Summary * Summary
*/ */
summary: string; summary: string;
/**
* Rows
*
* 점수 근거: 비중 큰 날씨 조건부터 네 개와 지금 값 (기온 · 체감 18°)
*/
rows?: Array<Row>;
/** /**
* Say * Say
* *
* 점수 구간 설명 문장 (seed sentences) * 점수 구간 설명 문장 (seed sentences)
*/ */
say?: string | null; say?: string | null;
/**
* Trend
*
* 오늘 · 내일 · 이번 주말 점수 (각 상세 날짜 칸과 같은 값)
*/
trend?: Array<TrendPoint>;
}; };
/** /**
@@ -1036,6 +1036,12 @@ export type MyGakData = {
* Name * Name
*/ */
name: string; name: string;
/**
* Icon
*
* 고른 아이콘 (각 아이콘 이름)
*/
icon?: string | null;
rule: MyGakRule; rule: MyGakRule;
}; };
@@ -1139,6 +1145,14 @@ export type MyGakScore = {
* score 근거: 조건마다 그 시간대 실제 값 * score 근거: 조건마다 그 시간대 실제 값
*/ */
reasons?: Array<string>; reasons?: Array<string>;
/**
* Factors
*
* 조건별 점수 0~100 (temp·rain·wind·air·humidity, reasons 와 같은 순서)
*/
factors?: {
[key: string]: number;
};
}; };
/** /**
@@ -1713,6 +1727,12 @@ export type ReqMyGak = {
* 내 각 이름 (끝에 '각'이 없으면 붙인다) * 내 각 이름 (끝에 '각'이 없으면 붙인다)
*/ */
name: string; name: string;
/**
* Icon
*
* 고른 아이콘 (각 아이콘 이름)
*/
icon?: string | null;
rule: MyGakRule; rule: MyGakRule;
}; };
@@ -3377,6 +3397,12 @@ export type TalkData = {
* Created At * Created At
*/ */
created_at: string; created_at: string;
/**
* Ago
*
* 쓴 지 얼마나 됐는지 (방금 · 12분 전 · 3시간 전 · 1일 전 · 2주 전)
*/
ago: string;
}; };
/** /**
+4 -1
View File
@@ -75,7 +75,10 @@ export function ago(iso: string | null | undefined, now = Date.now()) {
const min = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000)) const min = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000))
if (min < 5) return '방금' if (min < 5) return '방금'
if (min < 60) return `${min}분 전` if (min < 60) return `${min}분 전`
return `${Math.floor(min / 60)}시간 전` const h = Math.floor(min / 60)
if (h < 24) return `${h}시간 전`
const d = Math.floor(h / 24)
return d < 7 ? `${d}일 전` : `${Math.floor(d / 7)}주 전`
} }
/** 날짜 칸 이름: 오늘 · 내일 · "토 10.4" */ /** 날짜 칸 이름: 오늘 · 내일 · "토 10.4" */