Merge branch 'react-native' into release/1026-merge
# Conflicts: # backend/common/enums.py # backend/router/v1/auth/account.py # frontend/.dockerignore # frontend/package-lock.json # frontend/package.json # frontend/public/terms.html # frontend/src/api/client/index.ts # frontend/src/b/BLayout.tsx # frontend/src/b/Sheets.tsx # shared/api/client/@tanstack/react-query.gen.ts # shared/api/client/sdk.gen.ts # shared/api/client/types.gen.ts
This commit is contained in:
commit
5d18fa51fa
148 files changed
+21940
-4532
No files matched your search
@@ -0,0 +1,14 @@
|
|||||||
|
# 저장소 루트를 빌드 대상으로 쓰는 건 frontend 이미지뿐이라 frontend·shared·루트 package 파일만 넘긴다
|
||||||
|
*
|
||||||
|
!package.json
|
||||||
|
!package-lock.json
|
||||||
|
!frontend
|
||||||
|
!shared
|
||||||
|
!mobile/package.json
|
||||||
|
**/node_modules
|
||||||
|
**/dist
|
||||||
|
**/*.log
|
||||||
|
**/.DS_Store
|
||||||
|
**/dist-toss
|
||||||
|
**/*.ait
|
||||||
|
**/.env.toss
|
||||||
@@ -4,6 +4,9 @@
|
|||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
|
|
||||||
|
# npm workspaces 의존성 (frontend·mobile·shared 가 루트 하나를 같이 쓴다)
|
||||||
|
node_modules/
|
||||||
|
|
||||||
# Python 바이트코드/캐시
|
# Python 바이트코드/캐시
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
|
|||||||
@@ -298,3 +298,47 @@
|
|||||||
| [ ] | `npm run card`가 크롬 멈춤에 시간 제한이 없음 — 10/24 소개 카드 7번 장에서 헤드리스 크롬이 75분 멈춰 있었음(`--virtual-time-budget`만으론 안 끝남). `execFileSync`에 `timeout`(예: 60초) 주고 실패 시 그 장만 재시도 | 10/24 렌더 중 발견 | `admin/scripts/card.mjs` |
|
| [ ] | `npm run card`가 크롬 멈춤에 시간 제한이 없음 — 10/24 소개 카드 7번 장에서 헤드리스 크롬이 75분 멈춰 있었음(`--virtual-time-budget`만으론 안 끝남). `execFileSync`에 `timeout`(예: 60초) 주고 실패 시 그 장만 재시도 | 10/24 렌더 중 발견 | `admin/scripts/card.mjs` |
|
||||||
| [x] | 10/25 건강·운동 타로(킹서버 카드 7→포스트 3960, 인스타 https://www.instagram.com/p/De5iLg4AS_M/)·꾸안꾸 코디는 처음 올린 카드 8→포스트 3961(인스타 De58VfXINy0)이 40대~ 옷이 20-30대와 같아 숨기고, 40대~ 옷을 새로 써서 카드 9→포스트 3962(인스타 De5-8gboL-c)로 재게시했으나 40대 여자 그림에 롱가디건이 끼고 전체가 여름 옷으로 보여 다시 숨김. 일교차 8도 이상이면 겉옷을 5번째 옷으로 넣게 고쳐 카드 10→포스트 3963(인스타 De6B2gwIMXF)으로 올렸으나 그림 배치와 이름표 자리가 어긋나 숨김. 프롬프트에 옷 자리를 적고 다시 그려 카드 11→포스트 3964, 인스타 https://www.instagram.com/p/De6JRIkoKbT/ 로 최종 게시. 07:52 예약(세션 크론)이 세션 종료로 안 돌아 09:46 수동 실행. 코디는 사용자 결정으로 사람 구분을 20-30대·40대~ 4장으로 바꿈(f30·m30 그림 파일 8장은 남아 있으나 미사용). 새 그림 8장(러닝각·자전거각·warm 꾸안꾸 6) | 사용자 요청 (10/24) | `admin/image-prompts/ootd.json`, `admin/scripts/card.mjs` |
|
| [x] | 10/25 건강·운동 타로(킹서버 카드 7→포스트 3960, 인스타 https://www.instagram.com/p/De5iLg4AS_M/)·꾸안꾸 코디는 처음 올린 카드 8→포스트 3961(인스타 De58VfXINy0)이 40대~ 옷이 20-30대와 같아 숨기고, 40대~ 옷을 새로 써서 카드 9→포스트 3962(인스타 De5-8gboL-c)로 재게시했으나 40대 여자 그림에 롱가디건이 끼고 전체가 여름 옷으로 보여 다시 숨김. 일교차 8도 이상이면 겉옷을 5번째 옷으로 넣게 고쳐 카드 10→포스트 3963(인스타 De6B2gwIMXF)으로 올렸으나 그림 배치와 이름표 자리가 어긋나 숨김. 프롬프트에 옷 자리를 적고 다시 그려 카드 11→포스트 3964, 인스타 https://www.instagram.com/p/De6JRIkoKbT/ 로 최종 게시. 07:52 예약(세션 크론)이 세션 종료로 안 돌아 09:46 수동 실행. 코디는 사용자 결정으로 사람 구분을 20-30대·40대~ 4장으로 바꿈(f30·m30 그림 파일 8장은 남아 있으나 미사용). 새 그림 8장(러닝각·자전거각·warm 꾸안꾸 6) | 사용자 요청 (10/24) | `admin/image-prompts/ootd.json`, `admin/scripts/card.mjs` |
|
||||||
|
|
||||||
|
## 앱(React Native) 마이그레이션
|
||||||
|
|
||||||
|
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| [x] | 1단계: 웹·앱 공통 코드 `shared/`(`@nalssigak/shared`) 분리, 루트 npm workspaces, 웹 Docker 빌드 대상을 루트로 | 앱과 API 클라이언트·로직 공유 | `package.json`, `shared/`, `frontend/Dockerfile`, `compose.yaml`, `.dockerignore` |
|
||||||
|
| [x] | 2단계: 앱에 react-query·Uniwind 설정 + Metro가 `react`를 `mobile/node_modules`(19.2.3) 것만 쓰게 설정 — 루트에는 웹용 react 19.3.0이 있고 RN 렌더러는 19.2.3에서만 돌아감 | 앱 시작 준비 | `mobile/metro.config.js`, `mobile/src/app/_layout.tsx`, `mobile/src/lib/query-client.ts` |
|
||||||
|
| [x] | 앱 토큰 저장소 `expo-secure-store`로 `configureApi` 연결, API 주소는 `EXPO_PUBLIC_API_BASE_URL` | 웹은 localStorage | `mobile/src/lib/api.ts`, `mobile/.env.example` |
|
||||||
|
| [x] | 안드로이드 에뮬레이터(Expo Go)에서 확인: 오늘 화면 실데이터, 위치 권한 창, 탭 이동, 각 근거 시트 | | `mobile/` |
|
||||||
|
| [x] | 안드로이드 개발 빌드에서 가입·로그인(아바타 표시)·좋아요·이미지 공유·위치로 지역 찾기 확인 | | `mobile/` |
|
||||||
|
| [ ] | 안드로이드 댓글 쓰기·내 정보 바꾸기·로그아웃 확인 | 아직 안 눌러 봄 | `mobile/src/components/sheets/` |
|
||||||
|
| [x] | 출시 빌드 설정: `eas.json`(production 은 운영 API·사이트 주소, 빌드 번호 자동 증가), iOS 수출 규정 암호화 없음, 안드로이드 권한은 대략 위치만(정밀 위치·저장소·다른 앱 위에 그리기 뺌) | | `mobile/eas.json`, `mobile/app.json` |
|
||||||
|
| [ ] | 출시 빌드 전 준비(사용자): Apple Developer·Google Play Console·Expo 계정, 스토어 스크린샷·설명·데이터 안전 양식 | 서명·제출에 필요 | |
|
||||||
|
| [x] | 회원 탈퇴(스토어 심사 필수): `DELETE /v1/auth/me` — 계정·댓글·좋아요·저장 모두 삭제, 게시물·댓글 수 맞춤. 웹·앱 내 정보 시트 '탈퇴하기'(한 번 더 확인) | Apple 5.1.1(v), Google Play 계정 삭제 정책 | `backend/crud/user_crud.py`, `backend/services/auth_service.py`, `frontend/src/b/Sheets.tsx`, `mobile/src/components/sheets/me.tsx` |
|
||||||
|
| [ ] | 운영 배포 때 탈퇴 API 같이 나감 — 배포 전 웹 내 정보 시트 '탈퇴하기' 화면 확인 (앱은 안드로이드에서 확인, 웹은 빌드·린트만) | | `frontend/src/b/Sheets.tsx` |
|
||||||
|
| [ ] | 백엔드 테스트 3개가 날짜 때문에 실패 (10/19): `test_feed`(제철 각 수 42≠40), `test_watch`, `test_weather_today`(10월 하순 18시가 일몰 뒤라 'sunset' 아이콘 아님) — 탈퇴 작업과 무관 | 기대값을 날짜에 안 묶이게 고쳐야 함 | `backend/tests/` |
|
||||||
|
| [ ] | Xcode 설치 후 iOS 시뮬레이터에서 전체 확인 | | `mobile/` |
|
||||||
|
| [x] | 안드로이드 개발 빌드(`expo run:android`) 설치 확인: 홈 화면 해 아이콘·'날씨각' 이름, 실데이터 화면 | | `mobile/` |
|
||||||
|
| [x] | 앱 ID: 안드로이드 패키지 `kr.o2o.nalssigak` — Play Console 기존 '날씨각'(Wear OS 트랙에 워치 앱 있음)에 휴대전화 앱으로 추가하려면 패키지명이 같아야 함. iOS 번들 ID는 미정 | 스토어에 올리면 못 바꿈 | `mobile/app.json` |
|
||||||
|
| [x] | Play 제출: 휴대전화 versionCode 1000부터 (10/23 `app.json` versionCode 1000, 로컬 빌드)(워치가 1 사용) — `eas login` 후 `eas build:version:set -p android` | 같은 앱 안에서 versionCode 겹치면 안 됨 | `mobile/eas.json` |
|
||||||
|
| [x] | Play 제출: 워치 앱과 같은 업로드 키 (10/23 로컬 빌드로 서명 확인, SHA-1 D3:51…44:79. 비밀번호는 ~/.gradle/gradle.properties `NALSSIGAK_UPLOAD_*`)(.jks)를 `eas credentials -p android`로 등록 (사용자: 키 파일·비밀번호 준비, 분실 시 Play Console에서 업로드 키 재설정) | EAS는 안 넣으면 새 키를 만듦 | |
|
||||||
|
| [ ] | 출시 aab 서명 설정이 생성 폴더 `mobile/android/app/build.gradle`에만 있음 — `expo prebuild --clean` 하면 지워지니 다시 넣거나 config plugin으로 옮기기 | `android/`는 gitignore·재생성 | `mobile/android/app/build.gradle` |
|
||||||
|
| [ ] | 앱 구글 로그인 기기 확인: 네이티브 다시 빌드 → 구글 계정 로그인된 에뮬레이터(Play 서비스 이미지)에서 구글로 계속하기 | 새 네이티브 모듈이라 지금 설치된 개발 빌드엔 없음. Android 클라이언트(개발·Play SHA-1)는 콘솔에 등록됨 | `mobile/src/components/sheets/google.tsx` |
|
||||||
|
| [ ] | 운영 서버 `.env`에 `GOOGLE_CLIENT_ID`(웹 클라이언트 ID) 넣고 구글 로그인 백엔드 배포 | 비어 있으면 `/v1/auth/config`가 ID를 안 줘서 앱·웹 구글 버튼이 숨음 | `backend/config/settings.py` |
|
||||||
|
| [ ] | Play 제출(사용자): 휴대전화 스크린샷 2장+, 개인정보처리방침 URL, 계정 삭제 URL(웹 '탈퇴하기' 운영 배포 후), 데이터 보안 양식(대략 위치·계정 정보·댓글), 콘텐츠 등급, 앱 액세스용 심사 테스트 계정. 개인 계정(2023.11 이후)이면 비공개 테스트 12명·14일 | | |
|
||||||
|
| [x] | Play UGC 정책(댓글): 처음 댓글 쓸 때 이용약관 동의(`POST /v1/auth/terms`), 남의 댓글 ⋯ → 신고(이유 4가지, 신고한 사람에겐 바로 숨김, 3건이면 모두에게 숨김) / 이 사람 차단, 내 정보 '차단한 사람'·풀기, 운영 조치 `scripts/moderate.py`(숨김·되살림·정지), 탈퇴 때 신고·차단도 삭제 | Play 'User Generated Content' 정책 | `backend/`, `frontend/src/b/Sheets.tsx`, `frontend/public/terms.html`, `mobile/src/components/sheets/` |
|
||||||
|
| [ ] | 운영 DB 반영: `init.sql`의 `users.terms_agreed_at`, `comment.report_count`·`is_hidden`, `comment_report`, `user_block` (ALTER·CREATE IF NOT EXISTS) — 코드 배포 전에 먼저 | 새 코드가 이 칼럼을 읽음 | `backend/postgres-init/init.sql` |
|
||||||
|
| [ ] | **[검토 필요]** 이용약관 초안 문구 검토 | 법무 문구라 확인 필요 | `frontend/public/terms.html` |
|
||||||
|
| [ ] | 개인정보처리방침에 휴대전화 앱·댓글·신고·차단 기록 추가 (지금은 웹·워치 앱만 적혀 있음) | Play 데이터 보안 양식과 맞아야 함 | `frontend/public/privacy.html` |
|
||||||
|
| [x] | 앱 신고·차단·약관 화면 안드로이드 확인: ⋯ 메뉴, 차단 확인·안내·목록에서 빠짐, 약관 동의 후 바로 게시, 내 정보 '차단한 사람' 풀기 (신고 흐름은 백엔드 테스트로만). 새 패키지 `kr.o2o.nalssigak` 개발 빌드로 다시 설치함 | | `mobile/` |
|
||||||
|
| [ ] | 오늘 날씨 칸(3시·6시 등)이 '?' — 백엔드가 며칠 꺼져 있다 켜지면 최신 발표(예: 8시, 9시부터 예보)만 받아 새벽 칸 행이 없음. 0시 재수신(`_midnight_missing`)은 0시에 묵은 값이 있으면 안 돎. 운영은 늘 켜져 있어 드묾 — 고칠 땐 오늘 칸 중 비거나 묵은 칸이 있으면 다시 받기 | 10/19 로컬(9811)에서 확인, 앱·웹 버그 아님 | `backend/services/weather_service.py` (`today`, `ensure_vilage`, `_midnight_missing`) |
|
||||||
|
| [x] | 앱 아이콘 3D 해 그림(600px 원본)으로: iOS 1024, 안드로이드 적응형(앞·뒤·단색), 스플래시. Expo Go 에선 안 보이고 개발 빌드부터 보임. 스토어용으로는 1024px 이상 원본이 있으면 더 선명 | | `mobile/assets/images/` |
|
||||||
|
| [x] | 3단계-1: 탭 5개 구조·위 막대·하늘 배경·밤 테마(Uniwind dark), Today 히어로·각 순위·행사/TOP5/계절 띠 | | `mobile/src/app/`, `mobile/src/components/` |
|
||||||
|
| [x] | Today 게시물 카드(슬라이드 7종·넘기기·좋아요·댓글·텍스트 공유), 3·6·9번째 글 뒤 띠 | | `mobile/src/components/post/`, `mobile/src/app/index.tsx` |
|
||||||
|
| [x] | 시트 7종(각 근거·읽을거리·댓글·이번 주 특집·로그인/가입·내 정보·지역 고르기)을 RN `Modal`로, 위 막대 로그인/아바타 | 새 패키지 없이 | `mobile/src/components/sheets/`, `mobile/src/components/top-bar.tsx` |
|
||||||
|
| [x] | 고른 지역 저장 (SecureStore) | | `mobile/src/lib/region.tsx` |
|
||||||
|
| [x] | 위치로 지역 찾기(`expo-location`): 처음 켠 사람은 가장 가까운 구로, 지역 시트 '지금 위치로 찾기' | 웹과 같게 | `mobile/src/lib/region.tsx`, `mobile/src/components/sheets/region.tsx` |
|
||||||
|
| [x] | 움직임: 해·구름 떨어지기/둥둥, 비·눈, 스켈레톤 깜빡임, 첫 로딩 덮개, 하늘색 서서히 바뀜, 밤 별 반짝임 ('동작 줄이기' 켜면 멈춤) | | `mobile/src/components/today/hero.tsx`, `first-load.tsx`, `sky-bg.tsx` |
|
||||||
|
| [x] | 나머지 탭(각·노을·주말·행사·계절·상식) 옮기기 | | `mobile/src/app/`, `mobile/src/components/{gak,sky,week,season}/` |
|
||||||
|
| [x] | 이미지로 공유(`react-native-view-shot` + `expo-sharing`): 게시물은 보고 있는 슬라이드, 주말은 고른 날 추천 카드 | 웹 스토리 이미지(머리말·주소 붙인 9:16)와는 다름 | `mobile/src/lib/share-image.ts` |
|
||||||
|
| [x] | 웹과 다른 작은 것들 맞춤: 좋아요 튀는 하트·토스트, 밤 별똥별, 단풍잎 떨어짐, 시 구절 고운바탕, 실패·빈 안내 높이 유지(hold), 시트 배경은 제자리 페이드 | | `mobile/src/` |
|
||||||
|
| [ ] | 공유 이미지를 웹처럼 9:16 스토리(머리말·사이트 주소)로 — 지금은 화면 그대로 찍음. 좋아요 효과는 카드 안에만 뜸(RN에 portal 없음) | 남은 차이 | `mobile/src/lib/share-image.ts`, `mobile/src/components/post/` |
|
||||||
|
| [x] | `mobile/` 템플릿 예제 화면·`.vscode`·`LICENSE`·README 지움, `AGENTS.md`·`.claude`는 둠 | 사용자 결정 | `mobile/` |
|
||||||
|
| [ ] | `frontend-dev` 개발 컨테이너 실제로 띄워 확인 (이미지 빌드만 확인, 5173이 사용 중이라 실행은 못 함) | 볼륨 경로 바뀜 | `compose.yaml` |
|
||||||
|
| [ ] | 운영 서버가 git pull 뒤 루트 `package-lock.json`으로 빌드되는지 배포 때 확인 | 빌드 대상이 `./frontend` → `.` | `deploy.sh`, `compose.yaml` |
|
||||||
@@ -360,6 +360,7 @@ class User(Base):
|
|||||||
color: Mapped[str] = mapped_column(String(20), default="orange")
|
color: Mapped[str] = mapped_column(String(20), default="orange")
|
||||||
mood: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
mood: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||||
status: Mapped[int] = mapped_column(SmallInteger, default=1)
|
status: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||||
|
terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
|
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||||
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())
|
||||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||||
@@ -400,10 +401,29 @@ class Comment(Base):
|
|||||||
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||||
body: Mapped[str] = mapped_column(String(60))
|
body: Mapped[str] = mapped_column(String(60))
|
||||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||||
|
report_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||||
|
is_hidden: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||||
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())
|
||||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||||
|
|
||||||
|
|
||||||
|
class CommentReport(Base):
|
||||||
|
__tablename__ = "comment_report"
|
||||||
|
|
||||||
|
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||||
|
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||||
|
reason: Mapped[int] = mapped_column(SmallInteger)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
|
||||||
|
|
||||||
|
class UserBlock(Base):
|
||||||
|
__tablename__ = "user_block"
|
||||||
|
|
||||||
|
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||||
|
blocked_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
|
||||||
|
|
||||||
class CommentLike(Base):
|
class CommentLike(Base):
|
||||||
__tablename__ = "comment_like"
|
__tablename__ = "comment_like"
|
||||||
|
|
||||||
@@ -472,9 +492,3 @@ class TalkReport(Base):
|
|||||||
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())
|
||||||
|
|
||||||
|
|
||||||
class UserBlock(Base):
|
|
||||||
__tablename__ = "user_block"
|
|
||||||
|
|
||||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
|
||||||
blocked_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
@@ -25,6 +25,7 @@ class ErrorType(Enum):
|
|||||||
AUTH_FAILED = 4002
|
AUTH_FAILED = 4002
|
||||||
AUTH_DUPLICATE_ID = 4003
|
AUTH_DUPLICATE_ID = 4003
|
||||||
AUTH_TOKEN_INVALID = 4004
|
AUTH_TOKEN_INVALID = 4004
|
||||||
|
TERMS_REQUIRED = 4005
|
||||||
|
|
||||||
|
|
||||||
class Sky(CodeEnum):
|
class Sky(CodeEnum):
|
||||||
@@ -192,3 +193,10 @@ class AuthProvider(CodeEnum):
|
|||||||
LOCAL = 1
|
LOCAL = 1
|
||||||
GOOGLE = 2
|
GOOGLE = 2
|
||||||
TOSS = 3
|
TOSS = 3
|
||||||
|
|
||||||
|
|
||||||
|
class ReportReason(CodeEnum):
|
||||||
|
ABUSE = 1
|
||||||
|
AD = 2
|
||||||
|
PRIVACY = 3
|
||||||
|
OTHER = 4
|
||||||
@@ -2,13 +2,15 @@ import uuid
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from sqlalchemy import delete, func, select, update
|
from sqlalchemy import delete, func, or_, select, update
|
||||||
from sqlalchemy.dialects.postgresql import insert
|
from sqlalchemy.dialects.postgresql import insert
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, Post, PostLike, PostLikeAnon, PostSave, User
|
from common.database.model.models import Comment, CommentLike, CommentLikeAnon, CommentReport, Post, PostLike, PostLikeAnon, PostSave, User, UserBlock
|
||||||
from common.liker import Liker
|
from common.liker import Liker
|
||||||
|
|
||||||
|
HIDE_AT = 3 # 신고가 이만큼 쌓이면 모두에게서 숨긴다
|
||||||
|
|
||||||
|
|
||||||
async def toggle_like_row(s: AsyncSession, who: Liker, member: type, anon: type, id_name: str, id_value: int, on: bool) -> bool:
|
async def toggle_like_row(s: AsyncSession, who: Liker, member: type, anon: type, id_name: str, id_value: int, on: bool) -> bool:
|
||||||
"""로그인했으면 member 표에 user_id 로, 아니면 anon 표에 ip_hash 로 넣거나 지운다. 실제로 바뀌었으면 True."""
|
"""로그인했으면 member 표에 user_id 로, 아니면 anon 표에 ip_hash 로 넣거나 지운다. 실제로 바뀌었으면 True."""
|
||||||
@@ -52,9 +54,16 @@ class ReactionCRUD:
|
|||||||
stmt = stmt.where(Post.post_id < cursor)
|
stmt = stmt.where(Post.post_id < cursor)
|
||||||
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
|
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
|
||||||
|
|
||||||
async def comments(self, s: AsyncSession, post_id: int, cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
|
async def comments(self, s: AsyncSession, post_id: int, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Comment, Optional[str], Optional[str], Optional[str], Optional[str]]]:
|
||||||
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다."""
|
"""로그인 없이 쓴 댓글은 User 칸이 모두 None 이다. 숨긴 댓글은 빼고, 보는 사람이 신고한 댓글·차단한 사람의 댓글도 뺀다."""
|
||||||
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(Comment.post_id == post_id, Comment.deleted.is_(False))
|
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).outerjoin(User, User.user_id == Comment.user_id).where(
|
||||||
|
Comment.post_id == post_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)
|
||||||
|
)
|
||||||
|
if viewer is not None:
|
||||||
|
stmt = stmt.where(
|
||||||
|
Comment.comment_id.not_in(select(CommentReport.comment_id).where(CommentReport.user_id == viewer)),
|
||||||
|
or_(Comment.user_id.is_(None), Comment.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer))),
|
||||||
|
)
|
||||||
if cursor is not None:
|
if cursor is not None:
|
||||||
stmt = stmt.where(Comment.comment_id > cursor)
|
stmt = stmt.where(Comment.comment_id > cursor)
|
||||||
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
|
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
|
||||||
@@ -81,18 +90,61 @@ class ReactionCRUD:
|
|||||||
owner = Comment.user_id == who.user_id if who.user_id is not None else (Comment.user_id.is_(None) & (Comment.ip_hash == who.ip_hash))
|
owner = Comment.user_id == who.user_id if who.user_id is not None else (Comment.user_id.is_(None) & (Comment.ip_hash == who.ip_hash))
|
||||||
res = await s.execute(
|
res = await s.execute(
|
||||||
update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False))
|
update(Comment).where(Comment.comment_id == comment_id, owner, Comment.deleted.is_(False))
|
||||||
.values(deleted=True).returning(Comment.post_id)
|
.values(deleted=True).returning(Comment.post_id, Comment.is_hidden)
|
||||||
)
|
)
|
||||||
post_id = res.scalar()
|
row = res.first()
|
||||||
if post_id is None:
|
if row is None:
|
||||||
return False
|
return False
|
||||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
|
# 숨긴 댓글은 이미 댓글 수에서 빠져 있다
|
||||||
|
if not row.is_hidden:
|
||||||
|
await s.execute(update(Post).where(Post.post_id == row.post_id).values(comment_count=Post.comment_count - 1))
|
||||||
return True
|
return True
|
||||||
|
|
||||||
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, who: Liker, on: bool) -> Optional[int]:
|
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, who: Liker, on: bool) -> Optional[int]:
|
||||||
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False)))
|
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))
|
||||||
if exists is None:
|
if exists is None:
|
||||||
return None
|
return None
|
||||||
if await toggle_like_row(s, who, CommentLike, CommentLikeAnon, "comment_id", comment_id, on):
|
if await toggle_like_row(s, who, CommentLike, CommentLikeAnon, "comment_id", comment_id, on):
|
||||||
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1)))
|
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1)))
|
||||||
return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id))
|
return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id))
|
||||||
|
|
||||||
|
async def comment_author(self, s: AsyncSession, comment_id: int):
|
||||||
|
"""지금 보이는 댓글이면 (comment_id, user_id) 행, 없으면 None. 로그인 없이 쓴 댓글은 user_id 가 None."""
|
||||||
|
return (await s.execute(select(Comment.comment_id, Comment.user_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))).first()
|
||||||
|
|
||||||
|
async def report_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, reason: int) -> None:
|
||||||
|
"""같은 사람이 두 번 신고해도 한 번만 센다. HIDE_AT 건이 되면 숨기고 댓글 수에서 뺀다."""
|
||||||
|
res = await s.execute(insert(CommentReport).values(comment_id=comment_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(CommentReport.comment_id))
|
||||||
|
if res.first() is None:
|
||||||
|
return
|
||||||
|
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(report_count=Comment.report_count + 1))
|
||||||
|
res = await s.execute(
|
||||||
|
update(Comment).where(Comment.comment_id == comment_id, Comment.report_count >= HIDE_AT, Comment.is_hidden.is_(False), Comment.deleted.is_(False))
|
||||||
|
.values(is_hidden=True).returning(Comment.post_id)
|
||||||
|
)
|
||||||
|
post_id = res.scalar()
|
||||||
|
if post_id is not None:
|
||||||
|
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
|
||||||
|
|
||||||
|
async def set_hidden(self, s: AsyncSession, comment_id: int, hidden: bool) -> bool:
|
||||||
|
"""운영자가 댓글을 숨기거나 되살린다. 실제로 바뀌었을 때만 댓글 수를 고친다."""
|
||||||
|
res = await s.execute(
|
||||||
|
update(Comment).where(Comment.comment_id == comment_id, Comment.is_hidden.is_(not hidden), Comment.deleted.is_(False))
|
||||||
|
.values(is_hidden=hidden).returning(Comment.post_id)
|
||||||
|
)
|
||||||
|
post_id = res.scalar()
|
||||||
|
if post_id is None:
|
||||||
|
return False
|
||||||
|
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + (-1 if hidden else 1)))
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None:
|
||||||
|
await s.execute(insert(UserBlock).values(user_id=user_id, blocked_id=blocked_id).on_conflict_do_nothing())
|
||||||
|
|
||||||
|
async def unblock(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> bool:
|
||||||
|
res = await s.execute(delete(UserBlock).where(UserBlock.user_id == user_id, UserBlock.blocked_id == blocked_id).returning(UserBlock.blocked_id))
|
||||||
|
return res.first() is not None
|
||||||
|
|
||||||
|
async def blocked(self, s: AsyncSession, user_id: uuid.UUID) -> list[User]:
|
||||||
|
stmt = select(User).join(UserBlock, UserBlock.blocked_id == User.user_id).where(UserBlock.user_id == user_id).order_by(UserBlock.created_at.desc())
|
||||||
|
return list((await s.scalars(stmt)).all())
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
import uuid
|
import uuid
|
||||||
|
from collections import Counter
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import delete, select, update
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from common.database.model.models import User
|
from common.database.model.models import Comment, CommentLike, CommentReport, Post, PostLike, PostSave, User, UserBlock
|
||||||
|
|
||||||
|
|
||||||
class UserCRUD:
|
class UserCRUD:
|
||||||
@@ -46,3 +47,29 @@ class UserCRUD:
|
|||||||
user.updated_at = datetime.now(timezone.utc)
|
user.updated_at = datetime.now(timezone.utc)
|
||||||
await s.flush()
|
await s.flush()
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
async def agree_terms(self, s: AsyncSession, user_id: uuid.UUID) -> None:
|
||||||
|
await s.execute(update(User).where(User.user_id == user_id, User.terms_agreed_at.is_(None)).values(terms_agreed_at=datetime.now(timezone.utc)))
|
||||||
|
|
||||||
|
async def withdraw(self, s: AsyncSession, user_id: uuid.UUID) -> None:
|
||||||
|
"""계정과 그 사람이 남긴 좋아요·저장·댓글·신고·차단을 모두 지우고, 게시물·댓글에 쌓인 수를 그만큼 줄인다."""
|
||||||
|
liked_posts = (await s.scalars(delete(PostLike).where(PostLike.user_id == user_id).returning(PostLike.post_id))).all()
|
||||||
|
if liked_posts:
|
||||||
|
await s.execute(update(Post).where(Post.post_id.in_(liked_posts)).values(like_count=Post.like_count - 1))
|
||||||
|
liked_comments = (await s.scalars(delete(CommentLike).where(CommentLike.user_id == user_id).returning(CommentLike.comment_id))).all()
|
||||||
|
if liked_comments:
|
||||||
|
await s.execute(update(Comment).where(Comment.comment_id.in_(liked_comments)).values(like_count=Comment.like_count - 1))
|
||||||
|
await s.execute(delete(PostSave).where(PostSave.user_id == user_id))
|
||||||
|
reported = (await s.scalars(delete(CommentReport).where(CommentReport.user_id == user_id).returning(CommentReport.comment_id))).all()
|
||||||
|
if reported:
|
||||||
|
await s.execute(update(Comment).where(Comment.comment_id.in_(reported)).values(report_count=Comment.report_count - 1))
|
||||||
|
await s.execute(delete(UserBlock).where((UserBlock.user_id == user_id) | (UserBlock.blocked_id == user_id)))
|
||||||
|
mine = (await s.execute(delete(Comment).where(Comment.user_id == user_id).returning(Comment.comment_id, Comment.post_id, Comment.deleted, Comment.is_hidden))).all()
|
||||||
|
if mine:
|
||||||
|
ids = [c for c, _, _, _ in mine]
|
||||||
|
await s.execute(delete(CommentLike).where(CommentLike.comment_id.in_(ids)))
|
||||||
|
await s.execute(delete(CommentReport).where(CommentReport.comment_id.in_(ids)))
|
||||||
|
# 이미 지웠거나 숨긴 댓글은 댓글 수에서 빠져 있다
|
||||||
|
for post_id, n in Counter(p for _, p, deleted, hidden in mine if not deleted and not hidden).items():
|
||||||
|
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - n))
|
||||||
|
await s.execute(delete(User).where(User.user_id == user_id))
|
||||||
@@ -218,6 +218,7 @@ CREATE TABLE IF NOT EXISTS public.users (
|
|||||||
color VARCHAR(20) NOT NULL DEFAULT 'orange', -- 프로필 배경색: orange·blue·green·purple·pink·brown
|
color VARCHAR(20) NOT NULL DEFAULT 'orange', -- 프로필 배경색: orange·blue·green·purple·pink·brown
|
||||||
mood VARCHAR(20) NULL, -- 오늘 기분: clear·partly·cloudy·rain·thunder·snow·fog·rainbow. NULL = 안 고름
|
mood VARCHAR(20) NULL, -- 오늘 기분: clear·partly·cloudy·rain·thunder·snow·fog·rainbow. NULL = 안 고름
|
||||||
status SMALLINT NOT NULL DEFAULT 1, -- UserStatus: 1=정상 2=정지
|
status SMALLINT NOT NULL DEFAULT 1, -- UserStatus: 1=정상 2=정지
|
||||||
|
terms_agreed_at TIMESTAMPTZ NULL, -- 이용약관 동의 시각. NULL 이면 댓글을 못 쓴다
|
||||||
token_version SMALLINT NOT NULL DEFAULT 1, -- 올리면 이전 refresh 토큰이 모두 무효
|
token_version SMALLINT NOT NULL DEFAULT 1, -- 올리면 이전 refresh 토큰이 모두 무효
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
@@ -266,16 +267,28 @@ ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS ip_hash VARCHAR(64) NULL;
|
|||||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS region_name VARCHAR(20) NULL;
|
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS region_name VARCHAR(20) NULL;
|
||||||
CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL;
|
CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL;
|
||||||
|
|
||||||
-- 댓글 신고 (보류)
|
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS terms_agreed_at TIMESTAMPTZ NULL;
|
||||||
-- ALTER TABLE public.comment ADD COLUMN report_count INTEGER NOT NULL DEFAULT 0;
|
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS report_count INTEGER NOT NULL DEFAULT 0;
|
||||||
-- ALTER TABLE public.comment ADD COLUMN is_hidden BOOLEAN NOT NULL DEFAULT FALSE;
|
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS is_hidden BOOLEAN NOT NULL DEFAULT FALSE; -- 신고 3건이면 숨김. 숨긴 댓글은 댓글 수에서 빠진다
|
||||||
-- CREATE TABLE IF NOT EXISTS public.comment_report (
|
|
||||||
-- comment_id BIGINT NOT NULL,
|
-- 댓글 신고. 신고한 사람에게는 그 댓글이 바로 안 보인다
|
||||||
-- user_id UUID NOT NULL,
|
CREATE TABLE IF NOT EXISTS public.comment_report (
|
||||||
-- reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
comment_id BIGINT NOT NULL,
|
||||||
-- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
user_id UUID NOT NULL,
|
||||||
-- PRIMARY KEY (comment_id, user_id)
|
reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
||||||
-- );
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (comment_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_comment_report_user ON public.comment_report (user_id);
|
||||||
|
|
||||||
|
-- 사용자 차단. 차단한 사람의 댓글·동네 이야기 글이 내게 안 보인다
|
||||||
|
CREATE TABLE IF NOT EXISTS public.user_block (
|
||||||
|
user_id UUID NOT NULL, -- 차단한 사람
|
||||||
|
blocked_id UUID NOT NULL, -- 차단당한 사람
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (user_id, blocked_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_block_blocked ON public.user_block (blocked_id);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS public.comment_like (
|
CREATE TABLE IF NOT EXISTS public.comment_like (
|
||||||
comment_id BIGINT NOT NULL,
|
comment_id BIGINT NOT NULL,
|
||||||
@@ -343,14 +356,6 @@ CREATE TABLE IF NOT EXISTS public.talk_report (
|
|||||||
PRIMARY KEY (talk_id, user_id)
|
PRIMARY KEY (talk_id, user_id)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- 이 사람 글 안 보기
|
|
||||||
CREATE TABLE IF NOT EXISTS public.user_block (
|
|
||||||
user_id UUID NOT NULL,
|
|
||||||
blocked_id UUID NOT NULL,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
PRIMARY KEY (user_id, blocked_id)
|
|
||||||
);
|
|
||||||
|
|
||||||
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
-- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다)
|
||||||
|
|
||||||
-- 구 목록.
|
-- 구 목록.
|
||||||
|
|||||||
@@ -11,14 +11,14 @@ from common.enums import AuthProvider, ErrorType
|
|||||||
from common.logger import LOG
|
from common.logger import LOG
|
||||||
from common.models.errors import error_info
|
from common.models.errors import error_info
|
||||||
from config.settings import settings
|
from config.settings import settings
|
||||||
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_TossLogin, Req_TossUnlink, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me, Res_TossUnlink
|
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_TossLogin, Req_TossUnlink, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me, Res_TossUnlink, Res_Withdraw
|
||||||
from services.auth_service import AuthService
|
from services.auth_service import AuthService
|
||||||
|
|
||||||
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
||||||
|
|
||||||
|
|
||||||
def _me(u: User) -> Me:
|
def _me(u: User) -> Me:
|
||||||
return Me(login_id=u.login_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, provider=AuthProvider(u.provider))
|
return Me(login_id=u.login_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, provider=AuthProvider(u.provider), terms_agreed=u.terms_agreed_at is not None)
|
||||||
|
|
||||||
|
|
||||||
def _auth(err: ErrorType, user, service: AuthService) -> Res_Auth:
|
def _auth(err: ErrorType, user, service: AuthService) -> Res_Auth:
|
||||||
@@ -100,3 +100,17 @@ async def update_me(req: Req_UpdateMe, user: User = Depends(current_user), servi
|
|||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return Res_Me(result=error_info(err))
|
return Res_Me(result=error_info(err))
|
||||||
return Res_Me(me=_me(updated))
|
return Res_Me(me=_me(updated))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/terms", response_model=Res_Me, response_model_exclude_none=True, summary="이용약관 동의 (댓글 쓰기 전에 한 번)")
|
||||||
|
async def agree_terms(user: User = Depends(current_user), service: AuthService = Depends()) -> Res_Me:
|
||||||
|
err, updated = await service.agree_terms(user)
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
return Res_Me(result=error_info(err))
|
||||||
|
return Res_Me(me=_me(updated))
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/me", response_model=Res_Withdraw, response_model_exclude_none=True, summary="탈퇴 (계정과 남긴 댓글·좋아요를 모두 지운다)")
|
||||||
|
async def withdraw(user: User = Depends(current_user), service: AuthService = Depends()) -> Res_Withdraw:
|
||||||
|
err = await service.withdraw(user)
|
||||||
|
return Res_Withdraw() if err is ErrorType.SUCCESS else Res_Withdraw(result=error_info(err))
|
||||||
@@ -48,6 +48,7 @@ class Me(WebPacketProtocol):
|
|||||||
color: str
|
color: str
|
||||||
mood: Optional[str] = None
|
mood: Optional[str] = None
|
||||||
provider: AuthProvider
|
provider: AuthProvider
|
||||||
|
terms_agreed: bool = False
|
||||||
|
|
||||||
|
|
||||||
class Res_Auth(Res_WebPacketProtocol):
|
class Res_Auth(Res_WebPacketProtocol):
|
||||||
@@ -64,6 +65,10 @@ class Res_Logout(Res_WebPacketProtocol):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Res_Withdraw(Res_WebPacketProtocol):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Res_Me(Res_WebPacketProtocol):
|
class Res_Me(Res_WebPacketProtocol):
|
||||||
me: Optional[Me] = None
|
me: Optional[Me] = None
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
|
import uuid
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from pydantic import Field
|
from pydantic import Field
|
||||||
|
|
||||||
from common.enums import PostType
|
from common.enums import PostType, ReportReason
|
||||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||||
|
|
||||||
|
|
||||||
@@ -58,3 +59,18 @@ class Res_Comment(Res_WebPacketProtocol):
|
|||||||
class Res_CommentLike(Res_WebPacketProtocol):
|
class Res_CommentLike(Res_WebPacketProtocol):
|
||||||
liked: Optional[bool] = None
|
liked: Optional[bool] = None
|
||||||
like_count: Optional[int] = None
|
like_count: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Req_Report(Req_WebPacketProtocol):
|
||||||
|
reason: ReportReason
|
||||||
|
|
||||||
|
|
||||||
|
class BlockedUser(WebPacketProtocol):
|
||||||
|
user_id: uuid.UUID
|
||||||
|
nickname: str
|
||||||
|
character: str
|
||||||
|
color: str
|
||||||
|
|
||||||
|
|
||||||
|
class Res_BlockedList(Res_WebPacketProtocol):
|
||||||
|
users: list[BlockedUser] = []
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import uuid
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Path, Query
|
from fastapi import APIRouter, Depends, Path, Query
|
||||||
@@ -10,7 +11,8 @@ 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
|
||||||
from router.v1.reaction.protocol import (
|
from router.v1.reaction.protocol import (
|
||||||
CommentData, Req_Comment, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave, Res_SavedList, SavedPost,
|
BlockedUser, CommentData, Req_Comment, Req_Report, Res_BlockedList, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave,
|
||||||
|
Res_SavedList, SavedPost,
|
||||||
)
|
)
|
||||||
from services.reaction_service import PAGE, CommentView, ReactionService
|
from services.reaction_service import PAGE, CommentView, ReactionService
|
||||||
|
|
||||||
@@ -69,7 +71,7 @@ async def list_comments(
|
|||||||
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
|
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개)")
|
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 로그인 없으면 '동네 익명'으로 IP 당 하루 20개, 로그인했는데 이용약관 동의 전이면 TERMS_REQUIRED)")
|
||||||
async def add_comment(
|
async def add_comment(
|
||||||
post_id: int = Path(...), req: Req_Comment = ..., user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: ReactionService = Depends(),
|
post_id: int = Path(...), req: Req_Comment = ..., user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), service: ReactionService = Depends(),
|
||||||
) -> Res_Comment:
|
) -> Res_Comment:
|
||||||
@@ -95,3 +97,26 @@ async def like_comment(comment_id: int = Path(...), who: Liker = Depends(liker),
|
|||||||
@router.delete("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 취소")
|
@router.delete("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 취소")
|
||||||
async def unlike_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_CommentLike:
|
async def unlike_comment(comment_id: int = Path(...), who: Liker = Depends(liker), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||||
return await _clike(comment_id, who, False, service)
|
return await _clike(comment_id, who, False, service)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/comment/{comment_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="남의 댓글 신고 (신고한 사람에겐 바로 안 보이고, 3건이면 모두에게 숨김)")
|
||||||
|
async def report_comment(comment_id: int = Path(...), req: Req_Report = ..., user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||||
|
return Res_WebPacketProtocol(result=error_info(await service.report_comment(comment_id, user, req.reason)))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/comment/{comment_id}/block", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이 댓글 쓴 사람 차단 (그 사람 댓글이 내게 안 보임)")
|
||||||
|
async def block_author(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||||
|
return Res_WebPacketProtocol(result=error_info(await service.block_author(comment_id, user)))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/block/list", response_model=Res_BlockedList, response_model_exclude_none=True, summary="내가 차단한 사람")
|
||||||
|
async def list_blocked(user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_BlockedList:
|
||||||
|
err, users = await service.blocked(user)
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
return Res_BlockedList(result=error_info(err))
|
||||||
|
return Res_BlockedList(users=[BlockedUser(user_id=u.user_id, nickname=u.nickname, character=u.character, color=u.color) for u in users])
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/block/{user_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="차단 풀기")
|
||||||
|
async def unblock(user_id: uuid.UUID = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||||
|
return Res_WebPacketProtocol(result=error_info(await service.unblock(user, user_id)))
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""운영자용 댓글·사용자 조치.
|
||||||
|
|
||||||
|
python scripts/moderate.py reports 신고 받은 댓글 (많은 순 30개)
|
||||||
|
python scripts/moderate.py hide <comment_id> 댓글 숨김
|
||||||
|
python scripts/moderate.py show <comment_id> 숨긴 댓글 되살림
|
||||||
|
python scripts/moderate.py suspend <login_id> 이용 정지 (로그인·토큰 막힘)
|
||||||
|
python scripts/moderate.py resume <login_id> 정지 풀기
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
from sqlalchemy import select, update # noqa: E402
|
||||||
|
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
|
||||||
|
from common.database.model.models import Comment, User # noqa: E402
|
||||||
|
from common.enums import ErrorType # noqa: E402
|
||||||
|
from crud.reaction_crud import ReactionCRUD # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
async def _reports(s):
|
||||||
|
stmt = (
|
||||||
|
select(Comment.comment_id, Comment.report_count, Comment.is_hidden, User.login_id, Comment.body)
|
||||||
|
.join(User, User.user_id == Comment.user_id)
|
||||||
|
.where(Comment.report_count > 0, Comment.deleted.is_(False))
|
||||||
|
.order_by(Comment.report_count.desc(), Comment.comment_id.desc())
|
||||||
|
.limit(30)
|
||||||
|
)
|
||||||
|
return (await s.execute(stmt)).all()
|
||||||
|
|
||||||
|
|
||||||
|
async def _set_status(s, login_id: str, status: int) -> bool:
|
||||||
|
res = await s.execute(
|
||||||
|
update(User).where(User.login_id == login_id, User.deleted.is_(False)).values(status=status, token_version=User.token_version + 1).returning(User.user_id)
|
||||||
|
)
|
||||||
|
return res.first() is not None
|
||||||
|
|
||||||
|
|
||||||
|
async def main(argv: list[str]) -> int:
|
||||||
|
if len(argv) < 1 or argv[0] not in {"reports", "hide", "show", "suspend", "resume"} or (argv[0] != "reports" and len(argv) != 2):
|
||||||
|
print(__doc__)
|
||||||
|
return 2
|
||||||
|
cmd = argv[0]
|
||||||
|
if cmd == "reports":
|
||||||
|
err, rows = await DB_SESSION_MNG.execute_lambda(_reports)
|
||||||
|
for comment_id, count, hidden, login_id, body in rows or []:
|
||||||
|
print(f"{comment_id}\t신고 {count}\t{'숨김' if hidden else '보임'}\t{login_id}\t{body}")
|
||||||
|
elif cmd in {"hide", "show"}:
|
||||||
|
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: ReactionCRUD().set_hidden(s, int(argv[1]), cmd == "hide"))
|
||||||
|
print("바뀜" if ok else "그대로 (없는 댓글이거나 이미 그 상태)")
|
||||||
|
else:
|
||||||
|
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: _set_status(s, argv[1], 2 if cmd == "suspend" else 1))
|
||||||
|
print("바뀜" if ok else "없는 아이디")
|
||||||
|
await DB_SESSION_MNG.stop()
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
print(err.name)
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(asyncio.run(main(sys.argv[1:])))
|
||||||
@@ -127,6 +127,16 @@ class AuthService:
|
|||||||
"""이 사용자의 모든 기기 토큰을 무효로 만든다."""
|
"""이 사용자의 모든 기기 토큰을 무효로 만든다."""
|
||||||
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.update(s, user.user_id, {"token_version": user.token_version + 1})])
|
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.update(s, user.user_id, {"token_version": user.token_version + 1})])
|
||||||
|
|
||||||
|
async def agree_terms(self, user: User) -> tuple[ErrorType, Optional[User]]:
|
||||||
|
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.agree_terms(s, user.user_id)])
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
return err, None
|
||||||
|
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, user.user_id))
|
||||||
|
|
||||||
|
async def withdraw(self, user: User) -> ErrorType:
|
||||||
|
"""탈퇴: 계정과 남긴 댓글·좋아요를 한 번에 지운다. 계정이 없어지니 가진 토큰도 바로 못 쓴다."""
|
||||||
|
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.withdraw(s, user.user_id)])
|
||||||
|
|
||||||
async def update_me(self, user: User, nickname: Optional[str], character: Optional[str], color: Optional[str] = None, mood: Optional[str] = None) -> tuple[ErrorType, Optional[User]]:
|
async def update_me(self, user: User, nickname: Optional[str], character: Optional[str], color: Optional[str] = None, mood: Optional[str] = None) -> tuple[ErrorType, Optional[User]]:
|
||||||
"""닉네임·캐릭터·배경색·기분 중 보낸 것만 바꾼다. 기분을 빈 문자열로 보내면 지운다."""
|
"""닉네임·캐릭터·배경색·기분 중 보낸 것만 바꾼다. 기분을 빈 문자열로 보내면 지운다."""
|
||||||
values: dict = {}
|
values: dict = {}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import uuid
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
@@ -6,7 +7,7 @@ from fastapi import Depends
|
|||||||
|
|
||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import Comment, Post, User
|
from common.database.model.models import Comment, Post, User
|
||||||
from common.enums import ErrorType
|
from common.enums import ErrorType, ReportReason
|
||||||
from common.liker import Liker
|
from common.liker import Liker
|
||||||
from common.utils.kma_time import kst_midnight, now_kst
|
from common.utils.kma_time import kst_midnight, now_kst
|
||||||
from crud.feed_crud import FeedCRUD
|
from crud.feed_crud import FeedCRUD
|
||||||
@@ -92,7 +93,7 @@ class ReactionService:
|
|||||||
return CommentView(comment=c, nickname=nickname or "", character=character or ANON_CHARACTER, color=color or ANON_COLOR, mood=mood, liked=liked, mine=c.user_id == who.user_id)
|
return CommentView(comment=c, nickname=nickname or "", character=character or ANON_CHARACTER, color=color or ANON_COLOR, mood=mood, liked=liked, mine=c.user_id == who.user_id)
|
||||||
|
|
||||||
async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
|
async def comments(self, post_id: int, user: Optional[User], ip_hash: str, cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
|
||||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, cursor, PAGE))
|
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, user.user_id if user else None, cursor, PAGE))
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err, []
|
return err, []
|
||||||
liked: set[int] = set()
|
liked: set[int] = set()
|
||||||
@@ -109,6 +110,8 @@ class ReactionService:
|
|||||||
body = body.strip()
|
body = body.strip()
|
||||||
if not body or len(body) > COMMENT_MAX:
|
if not body or len(body) > COMMENT_MAX:
|
||||||
return ErrorType.INVALID_INPUT, None
|
return ErrorType.INVALID_INPUT, None
|
||||||
|
if user is not None and user.terms_agreed_at is None:
|
||||||
|
return ErrorType.TERMS_REQUIRED, None
|
||||||
err = await self._post_exists(post_id)
|
err = await self._post_exists(post_id)
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err, None
|
return err, None
|
||||||
@@ -145,3 +148,37 @@ class ReactionService:
|
|||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
return err, None
|
return err, None
|
||||||
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
|
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
|
||||||
|
|
||||||
|
async def _others_comment(self, comment_id: int, user: User) -> tuple[ErrorType, Optional[uuid.UUID]]:
|
||||||
|
"""남이 쓴, 지금 보이는 댓글의 작성자. 내 댓글이면 INVALID_INPUT, 로그인 없이 쓴 댓글이면 작성자는 None."""
|
||||||
|
err, author = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comment_author(s, comment_id))
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
return err, None
|
||||||
|
if author is None:
|
||||||
|
return ErrorType.NOT_FOUND, None
|
||||||
|
return (ErrorType.INVALID_INPUT, None) if author.user_id == user.user_id else (ErrorType.SUCCESS, author.user_id)
|
||||||
|
|
||||||
|
async def report_comment(self, comment_id: int, user: User, reason: ReportReason) -> ErrorType:
|
||||||
|
err, _ = await self._others_comment(comment_id, user)
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
return err
|
||||||
|
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.report_comment(s, comment_id, user.user_id, reason.value)])
|
||||||
|
|
||||||
|
async def block_author(self, comment_id: int, user: User) -> ErrorType:
|
||||||
|
err, author = await self._others_comment(comment_id, user)
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
return err
|
||||||
|
# 로그인 없이 쓴 댓글은 차단할 사람이 없어 신고만 받는다
|
||||||
|
if author is None:
|
||||||
|
return ErrorType.INVALID_INPUT
|
||||||
|
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.block(s, user.user_id, author)])
|
||||||
|
|
||||||
|
async def unblock(self, user: User, blocked_id: uuid.UUID) -> ErrorType:
|
||||||
|
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.unblock(s, user.user_id, blocked_id))
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
return err
|
||||||
|
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
|
||||||
|
|
||||||
|
async def blocked(self, user: User) -> tuple[ErrorType, list[User]]:
|
||||||
|
err, users = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.blocked(s, user.user_id))
|
||||||
|
return err, users or []
|
||||||
@@ -43,7 +43,7 @@ def anyio_backend():
|
|||||||
|
|
||||||
_VOLATILE = (
|
_VOLATILE = (
|
||||||
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
||||||
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
|
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "comment_report", "user_block", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,9 @@ def client():
|
|||||||
|
|
||||||
async def _login(c, login_id: str) -> dict:
|
async def _login(c, login_id: str) -> dict:
|
||||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
h = {"Authorization": f"Bearer {body['access_token']}"}
|
||||||
|
await c.post("/v1/auth/terms", headers=h) # 로그인한 사람은 약관에 동의해야 댓글을 쓴다
|
||||||
|
return h
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
@@ -147,3 +149,26 @@ async def test_hero_tomorrow_and_tomorrow_slots(offline):
|
|||||||
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
|
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
|
||||||
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
|
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
|
||||||
assert res["day"] == hero["tomorrow"]["day"]
|
assert res["day"] == hero["tomorrow"]["day"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_anon_comment_can_be_reported_not_blocked(offline):
|
||||||
|
"""로그인 없이 쓴 댓글도 신고는 되고(신고한 사람에겐 숨김), 차단할 사람이 없어 차단은 안 된다. 다른 사람을 차단해도 익명 댓글은 그대로 보인다."""
|
||||||
|
async with client() as c:
|
||||||
|
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||||
|
url = f"/v1/reaction/post/{post_id}/comment"
|
||||||
|
listing = f"{url}/list"
|
||||||
|
anon_id = (await c.post(url, headers=IP_A, json={"body": "익명 댓글"})).json()["comment"]["comment_id"]
|
||||||
|
writer = await _login(c, "anon_mod_01")
|
||||||
|
writer_id = (await c.post(url, headers=writer, json={"body": "회원 댓글"})).json()["comment"]["comment_id"]
|
||||||
|
viewer = await _login(c, "anon_mod_02")
|
||||||
|
|
||||||
|
blocked = (await c.post(f"/v1/reaction/comment/{writer_id}/block", headers=viewer)).json()
|
||||||
|
assert blocked["result"]["success"] is True
|
||||||
|
ids = [x["comment_id"] for x in (await c.get(listing, headers=viewer)).json()["comments"]]
|
||||||
|
assert anon_id in ids and writer_id not in ids
|
||||||
|
|
||||||
|
assert (await c.post(f"/v1/reaction/comment/{anon_id}/block", headers=viewer)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||||
|
assert (await c.post(f"/v1/reaction/comment/{anon_id}/report", headers=viewer, json={"reason": 1})).json()["result"]["success"] is True
|
||||||
|
assert anon_id not in [x["comment_id"] for x in (await c.get(listing, headers=viewer)).json()["comments"]]
|
||||||
|
assert anon_id in [x["comment_id"] for x in (await c.get(listing, headers=IP_B)).json()["comments"]]
|
||||||
@@ -10,8 +10,12 @@ def client():
|
|||||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||||
|
|
||||||
|
|
||||||
async def _signup(c, login_id="mina_01", nickname="망원동주민"):
|
async def _signup(c, login_id="mina_01", nickname="망원동주민", agree=True):
|
||||||
return (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
|
"""가입하고, 댓글을 쓸 수 있게 이용약관에도 동의한다 (agree=False 면 안 함)."""
|
||||||
|
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
|
||||||
|
if agree and body.get("access_token"):
|
||||||
|
await c.post("/v1/auth/terms", headers={"Authorization": f"Bearer {body['access_token']}"})
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
@@ -122,3 +126,118 @@ async def test_logout_invalidates_access_and_refresh_tokens():
|
|||||||
assert (await c.post("/v1/auth/refresh", json={"refresh_token": body["refresh_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID"
|
assert (await c.post("/v1/auth/refresh", json={"refresh_token": body["refresh_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID"
|
||||||
again = (await c.post("/v1/auth/login", json={"login_id": "mina_out", "password": "password1"})).json()
|
again = (await c.post("/v1/auth/login", json={"login_id": "mina_out", "password": "password1"})).json()
|
||||||
assert (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {again['access_token']}"})).status_code == 200
|
assert (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {again['access_token']}"})).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_withdraw_deletes_account_and_reactions(offline):
|
||||||
|
async with client() as c:
|
||||||
|
body = await _signup(c, login_id="mina_bye")
|
||||||
|
h = {"Authorization": f"Bearer {body['access_token']}"}
|
||||||
|
other = {"Authorization": f"Bearer {(await _signup(c, 'other_bye', '남는사람'))['access_token']}"}
|
||||||
|
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||||
|
await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)
|
||||||
|
await c.post(f"/v1/reaction/post/{post_id}/save", headers=h)
|
||||||
|
mine = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": "곧 떠나요"})).json()["comment"]
|
||||||
|
kept = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=other, json={"body": "남아요"})).json()["comment"]
|
||||||
|
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/like", headers=h)
|
||||||
|
await c.post(f"/v1/reaction/comment/{mine['comment_id']}/like", headers=other)
|
||||||
|
|
||||||
|
assert (await c.delete("/v1/auth/me")).status_code == 401
|
||||||
|
assert (await c.delete("/v1/auth/me", headers=h)).json()["result"]["success"] is True
|
||||||
|
|
||||||
|
assert (await c.get("/v1/auth/me", headers=h)).status_code == 401
|
||||||
|
assert (await c.post("/v1/auth/refresh", json={"refresh_token": body["refresh_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID"
|
||||||
|
assert (await c.post("/v1/auth/login", json={"login_id": "mina_bye", "password": "password1"})).json()["result"]["desc"] == "AUTH_FAILED"
|
||||||
|
comments = (await c.get(f"/v1/reaction/post/{post_id}/comment/list")).json()["comments"]
|
||||||
|
assert [x["body"] for x in comments] == ["남아요"] and comments[0]["like_count"] == 0
|
||||||
|
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||||
|
assert p["like_count"] == 0 and p["comment_count"] == 1
|
||||||
|
# 같은 아이디로 다시 가입할 수 있다
|
||||||
|
assert (await _signup(c, login_id="mina_bye"))["result"]["success"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def _h(body):
|
||||||
|
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
async def _comment(c, post_id, h, text):
|
||||||
|
return (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": text})).json()
|
||||||
|
|
||||||
|
|
||||||
|
async def _bodies(c, post_id, h=None):
|
||||||
|
return [x["body"] for x in (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers=h or {})).json()["comments"]]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_comment_needs_terms_agreement(offline):
|
||||||
|
async with client() as c:
|
||||||
|
h = _h(await _signup(c, agree=False))
|
||||||
|
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||||
|
assert (await c.get("/v1/auth/me", headers=h)).json()["me"]["terms_agreed"] is False
|
||||||
|
assert (await _comment(c, post_id, h, "안녕"))["result"]["desc"] == "TERMS_REQUIRED"
|
||||||
|
assert (await c.post("/v1/auth/terms", headers=h)).json()["me"]["terms_agreed"] is True
|
||||||
|
assert (await _comment(c, post_id, h, "안녕"))["comment"]["body"] == "안녕"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_report_hides_for_reporter_then_for_all_at_three(offline):
|
||||||
|
async with client() as c:
|
||||||
|
writer = _h(await _signup(c, "writer_1", "쓴사람"))
|
||||||
|
r = [_h(await _signup(c, f"reporter_{i}", f"신고자{i}")) for i in range(3)]
|
||||||
|
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||||
|
bad = (await _comment(c, post_id, writer, "광고입니다"))["comment"]
|
||||||
|
url = f"/v1/reaction/comment/{bad['comment_id']}/report"
|
||||||
|
|
||||||
|
assert (await c.post(url, headers=writer, json={"reason": 2})).json()["result"]["desc"] == "INVALID_INPUT"
|
||||||
|
assert (await c.post(url, headers=r[0], json={"reason": 9})).status_code == 422
|
||||||
|
assert (await c.post(url, headers=r[0], json={"reason": 2})).json()["result"]["success"] is True
|
||||||
|
assert (await c.post(url, headers=r[0], json={"reason": 2})).json()["result"]["success"] is True # 두 번 신고해도 한 번
|
||||||
|
assert await _bodies(c, post_id, r[0]) == [] and await _bodies(c, post_id, r[1]) == ["광고입니다"]
|
||||||
|
|
||||||
|
await c.post(url, headers=r[1], json={"reason": 1})
|
||||||
|
assert await _bodies(c, post_id) == ["광고입니다"]
|
||||||
|
await c.post(url, headers=r[2], json={"reason": 1})
|
||||||
|
assert await _bodies(c, post_id) == [] and await _bodies(c, post_id, writer) == []
|
||||||
|
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||||
|
assert p["comment_count"] == 0
|
||||||
|
# 숨긴 댓글을 지워도 댓글 수가 한 번 더 줄지 않는다
|
||||||
|
assert (await c.delete(f"/v1/reaction/comment/{bad['comment_id']}", headers=writer)).json()["result"]["success"] is True
|
||||||
|
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||||
|
assert p["comment_count"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_block_hides_author_comments_and_can_be_undone(offline):
|
||||||
|
async with client() as c:
|
||||||
|
me = _h(await _signup(c))
|
||||||
|
other = _h(await _signup(c, "rude_1", "무례한"))
|
||||||
|
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||||
|
rude = (await _comment(c, post_id, other, "흥"))["comment"]
|
||||||
|
mine = (await _comment(c, post_id, me, "좋아요"))["comment"]
|
||||||
|
|
||||||
|
assert (await c.post(f"/v1/reaction/comment/{mine['comment_id']}/block", headers=me)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||||
|
assert (await c.post(f"/v1/reaction/comment/{rude['comment_id']}/block")).status_code == 401
|
||||||
|
assert (await c.post(f"/v1/reaction/comment/{rude['comment_id']}/block", headers=me)).json()["result"]["success"] is True
|
||||||
|
assert await _bodies(c, post_id, me) == ["좋아요"] and await _bodies(c, post_id) == ["흥", "좋아요"]
|
||||||
|
|
||||||
|
blocked = (await c.get("/v1/reaction/block/list", headers=me)).json()["users"]
|
||||||
|
assert [u["nickname"] for u in blocked] == ["무례한"]
|
||||||
|
assert (await c.delete(f"/v1/reaction/block/{blocked[0]['user_id']}", headers=me)).json()["result"]["success"] is True
|
||||||
|
assert (await c.delete(f"/v1/reaction/block/{blocked[0]['user_id']}", headers=me)).json()["result"]["desc"] == "NOT_FOUND"
|
||||||
|
assert await _bodies(c, post_id, me) == ["흥", "좋아요"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_withdraw_removes_reports_and_blocks(offline):
|
||||||
|
async with client() as c:
|
||||||
|
leaver = _h(await _signup(c, "leaver_1", "떠날사람"))
|
||||||
|
stay = _h(await _signup(c, "stay_1", "남는사람"))
|
||||||
|
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||||
|
kept = (await _comment(c, post_id, stay, "남아요"))["comment"]
|
||||||
|
gone = (await _comment(c, post_id, leaver, "떠나요"))["comment"]
|
||||||
|
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/report", headers=leaver, json={"reason": 4})
|
||||||
|
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/block", headers=leaver)
|
||||||
|
await c.post(f"/v1/reaction/comment/{gone['comment_id']}/block", headers=stay)
|
||||||
|
assert (await c.delete("/v1/auth/me", headers=leaver)).json()["result"]["success"] is True
|
||||||
|
assert (await c.get("/v1/reaction/block/list", headers=stay)).json()["users"] == []
|
||||||
|
assert await _bodies(c, post_id, stay) == ["남아요"]
|
||||||
@@ -84,6 +84,7 @@ async def test_like_in_one_sido_not_seen_in_another(offline):
|
|||||||
async with client() as c:
|
async with client() as c:
|
||||||
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
||||||
h = {"Authorization": f"Bearer {token}"}
|
h = {"Authorization": f"Bearer {token}"}
|
||||||
|
await c.post("/v1/auth/terms", headers=h)
|
||||||
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
|
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
|
||||||
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
|
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
|
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
|
||||||
|
|||||||
+7
-3
@@ -4,7 +4,8 @@ services:
|
|||||||
# 운영형: docker compose up --build → http://localhost:8080
|
# 운영형: docker compose up --build → http://localhost:8080
|
||||||
frontend:
|
frontend:
|
||||||
build:
|
build:
|
||||||
context: ./frontend
|
context: .
|
||||||
|
dockerfile: frontend/Dockerfile
|
||||||
target: prod
|
target: prod
|
||||||
args:
|
args:
|
||||||
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
|
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
|
||||||
@@ -19,13 +20,16 @@ services:
|
|||||||
frontend-dev:
|
frontend-dev:
|
||||||
profiles: ["dev"]
|
profiles: ["dev"]
|
||||||
build:
|
build:
|
||||||
context: ./frontend
|
context: .
|
||||||
|
dockerfile: frontend/Dockerfile
|
||||||
target: dev
|
target: dev
|
||||||
ports:
|
ports:
|
||||||
- "5173:5173"
|
- "5173:5173"
|
||||||
volumes:
|
volumes:
|
||||||
- ./frontend:/app
|
- ./frontend:/app/frontend
|
||||||
|
- ./shared:/app/shared
|
||||||
- /app/node_modules
|
- /app/node_modules
|
||||||
|
- /app/frontend/node_modules
|
||||||
environment:
|
environment:
|
||||||
- CHOKIDAR_USEPOLLING=true
|
- CHOKIDAR_USEPOLLING=true
|
||||||
- VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr}
|
- VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr}
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
node_modules
|
|
||||||
dist
|
|
||||||
.git
|
|
||||||
*.log
|
|
||||||
.DS_Store
|
|
||||||
Dockerfile
|
|
||||||
.dockerignore
|
|
||||||
dist-toss
|
|
||||||
*.ait
|
|
||||||
.env.toss
|
|
||||||
+13
-5
@@ -2,13 +2,19 @@
|
|||||||
|
|
||||||
# ---- deps: package.json이 바뀔 때만 다시 설치 ----
|
# ---- deps: package.json이 바뀔 때만 다시 설치 ----
|
||||||
FROM node:24-alpine AS deps
|
FROM node:24-alpine AS deps
|
||||||
|
# 빌드 대상은 저장소 루트(npm workspaces). 웹에 필요한 frontend·shared 만 설치한다
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
RUN npm ci
|
COPY frontend/package.json frontend/
|
||||||
|
COPY shared/package.json shared/
|
||||||
|
COPY mobile/package.json mobile/
|
||||||
|
RUN npm ci -w frontend -w shared
|
||||||
|
|
||||||
# ---- dev: 코드 수정이 바로 반영되는 개발 서버 ----
|
# ---- dev: 코드 수정이 바로 반영되는 개발 서버 ----
|
||||||
FROM deps AS dev
|
FROM deps AS dev
|
||||||
COPY . .
|
COPY shared shared
|
||||||
|
COPY frontend frontend
|
||||||
|
WORKDIR /app/frontend
|
||||||
EXPOSE 5173
|
EXPOSE 5173
|
||||||
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
|
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
|
||||||
|
|
||||||
@@ -18,12 +24,14 @@ ARG VITE_API_BASE_URL=""
|
|||||||
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
||||||
ARG VITE_SITE_URL=""
|
ARG VITE_SITE_URL=""
|
||||||
ENV VITE_SITE_URL=$VITE_SITE_URL
|
ENV VITE_SITE_URL=$VITE_SITE_URL
|
||||||
COPY . .
|
COPY shared shared
|
||||||
|
COPY frontend frontend
|
||||||
|
WORKDIR /app/frontend
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# ---- prod: nginx로 정적 파일 제공 ----
|
# ---- prod: nginx로 정적 파일 제공 ----
|
||||||
FROM nginx:1.29-alpine AS prod
|
FROM nginx:1.29-alpine AS prod
|
||||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
COPY --from=build /app/dist /usr/share/nginx/html
|
COPY --from=build /app/frontend/dist /usr/share/nginx/html
|
||||||
EXPOSE 80
|
EXPOSE 80
|
||||||
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
|
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
|
||||||
@@ -2,7 +2,7 @@ import { defineConfig } from '@hey-api/openapi-ts'
|
|||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json',
|
input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json',
|
||||||
output: 'src/api/client',
|
output: '../shared/api/client',
|
||||||
parser: {
|
parser: {
|
||||||
patch: {
|
patch: {
|
||||||
// FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation
|
// FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation
|
||||||
|
|||||||
Generated
-4110
File diff suppressed because it is too large.
Load diff
@@ -13,6 +13,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@apps-in-toss/web-framework": "3.8.0",
|
"@apps-in-toss/web-framework": "3.8.0",
|
||||||
|
"@nalssigak/shared": "*",
|
||||||
"@tailwindcss/vite": "^4.3.3",
|
"@tailwindcss/vite": "^4.3.3",
|
||||||
"@tanstack/react-query": "^5.104.0",
|
"@tanstack/react-query": "^5.104.0",
|
||||||
"embla-carousel-react": "^8.6.0",
|
"embla-carousel-react": "^8.6.0",
|
||||||
|
|||||||
+30
-60
@@ -10,83 +10,53 @@
|
|||||||
main { max-width: 720px; margin: 0 auto; }
|
main { max-width: 720px; margin: 0 auto; }
|
||||||
h1 { font-size: 26px; margin: 0 0 4px; }
|
h1 { font-size: 26px; margin: 0 0 4px; }
|
||||||
h2 { font-size: 18px; margin: 32px 0 8px; }
|
h2 { font-size: 18px; margin: 32px 0 8px; }
|
||||||
ul { padding-left: 20px; }
|
|
||||||
.muted { color: #5a6380; }
|
.muted { color: #5a6380; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main>
|
<main>
|
||||||
<h1>이용약관</h1>
|
<h1>이용약관</h1>
|
||||||
<p class="muted">시행일: 2026년 10월 14일</p>
|
<p class="muted">시행일: 2026년 10월 20일</p>
|
||||||
|
|
||||||
<p>이 약관은 AIO2O(이하 "회사")가 제공하는 날씨각 서비스의 이용 조건과 절차, 회사와 이용자의 권리·의무를 정합니다.</p>
|
<p>이 약관은 AIO2O(이하 "회사")가 운영하는 날씨각 웹·앱 서비스(이하 "서비스")를 이용하는 조건을 정합니다. 댓글을 쓰려면 이 약관에 동의해야 합니다.</p>
|
||||||
|
|
||||||
<h2>1. 용어</h2>
|
<h2>1. 서비스</h2>
|
||||||
|
<p>서비스는 지역별 날씨, 하늘·노을 예보, 생활 지수, 주변 행사 같은 정보를 제공합니다. 날씨 정보는 기상청 등 외부 자료를 바탕으로 한 예보이며 실제 날씨와 다를 수 있습니다.</p>
|
||||||
|
|
||||||
|
<h2>2. 계정</h2>
|
||||||
|
<p>웹·앱에서는 아이디·비밀번호나 구글 계정으로, 토스 앱 안의 미니앱에서는 토스 로그인으로 회원이 됩니다.</p>
|
||||||
|
<p>회원은 자신의 계정을 직접 관리해야 하며, 다른 사람에게 빌려주거나 넘길 수 없습니다. 회원은 언제든지 내 정보에서 탈퇴할 수 있고, 탈퇴하면 계정과 남긴 댓글·좋아요·저장·신고·차단 기록이 모두 지워집니다.</p>
|
||||||
|
|
||||||
|
<h2>3. 댓글에 쓰면 안 되는 내용</h2>
|
||||||
|
<p>아래 내용은 댓글로 쓸 수 없습니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li>서비스: 회사가 웹(weather.o2o.kr), 토스 앱 안의 미니앱(이하 "토스 미니앱"), Wear OS 워치 앱으로 제공하는 날씨각과 그에 딸린 날씨·각 점수·노을·주말·행사·계절 정보, 좋아요·댓글·저장 기능</li>
|
<li>욕설, 비하, 혐오, 따돌림, 위협</li>
|
||||||
<li>이용자: 서비스를 이용하는 모든 사람</li>
|
<li>광고, 홍보, 같은 내용 반복 게시</li>
|
||||||
<li>회원: 웹에서 아이디·비밀번호로 가입했거나, 토스 미니앱에서 토스 로그인으로 로그인한 이용자</li>
|
<li>전화번호·주소 등 자신이나 다른 사람의 개인정보</li>
|
||||||
<li>게시물: 회원이 서비스에 올린 댓글</li>
|
<li>음란하거나 폭력적인 내용, 불법 행위를 부추기는 내용</li>
|
||||||
|
<li>다른 사람의 권리(저작권·초상권·명예 등)를 침해하는 내용</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<h2>2. 약관의 효력과 변경</h2>
|
<h2>4. 신고·차단과 조치</h2>
|
||||||
<p>이 약관은 서비스 화면에 게시해 효력이 생깁니다. 회사는 관련 법령을 어기지 않는 범위에서 약관을 바꿀 수 있으며, 바꿀 때는 시행 7일 전(이용자에게 불리한 변경은 30일 전)부터 서비스 안에서 알립니다.</p>
|
<p>회원은 댓글마다 신고하거나 그 댓글을 쓴 사람을 차단할 수 있습니다. 신고한 댓글과 차단한 사람의 댓글은 본인에게 더는 보이지 않습니다. 신고가 여러 건 쌓인 댓글은 자동으로 숨겨지고, 회사가 확인해 3항을 어긴 댓글은 숨기거나 지우며, 반복해서 어긴 회원은 서비스 이용을 제한할 수 있습니다. 조치에 이의가 있으면 아래 연락처로 알려 주세요.</p>
|
||||||
<p>바뀐 약관에 동의하지 않으면 이용을 그만두고 탈퇴할 수 있습니다. 알린 시행일 뒤에도 계속 이용하면 바뀐 약관에 동의한 것으로 봅니다.</p>
|
|
||||||
|
|
||||||
<h2>3. 회원가입과 로그인</h2>
|
<h2>5. 게시물의 권리와 책임</h2>
|
||||||
<p>웹에서는 아이디, 비밀번호, 닉네임을 입력하고 가입합니다. 토스 미니앱에서는 토스 로그인에 동의하면 회원이 됩니다. 가입하거나 토스 로그인을 하면 이 약관과 <a href="/privacy">개인정보처리방침</a>에 동의한 것으로 봅니다.</p>
|
<p>댓글의 권리와 책임은 작성한 회원에게 있습니다. 회사는 서비스 화면에 댓글을 보여 주는 범위에서만 이를 사용합니다.</p>
|
||||||
<p>만 14세 미만은 회원이 될 수 없습니다. 다른 사람의 정보를 쓰거나 다른 사람을 사칭하는 닉네임을 쓸 수 없습니다.</p>
|
|
||||||
|
|
||||||
<h2>4. 서비스 이용</h2>
|
<h2>6. 서비스 변경·중단</h2>
|
||||||
<p>날씨와 각 점수, 노을, 주말·행사, 계절 정보는 로그인 없이 무료로 볼 수 있습니다. 좋아요, 댓글, 저장은 로그인한 뒤에 쓸 수 있습니다.</p>
|
<p>회사는 운영상 필요하면 서비스 내용을 바꾸거나 중단할 수 있으며, 중요한 변경은 미리 서비스 안에 알립니다.</p>
|
||||||
<p>회사는 운영상·기술상 필요에 따라 서비스의 내용을 바꾸거나 일부 또는 전부를 중단할 수 있으며, 중요한 변경이나 중단은 미리 알립니다. 다만 미리 알릴 수 없는 사정이 있으면 나중에 알릴 수 있습니다.</p>
|
|
||||||
|
|
||||||
<h2>5. 날씨 정보와 면책</h2>
|
<h2>7. 책임의 한계</h2>
|
||||||
<p>서비스의 날씨, 미세먼지, 각 점수, 노을 판정, 주말 순위, 행사 정보는 공공 데이터와 외부 예보를 바탕으로 회사가 계산하거나 정리한 참고 정보입니다. 예보는 실제 날씨와 다를 수 있고, 외부 제공처의 사정으로 늦거나 빠질 수 있습니다.</p>
|
<p>회사는 예보와 실제 날씨의 차이, 회원 사이의 다툼, 회원이 쓴 댓글로 생긴 손해에 대해 회사의 고의나 중대한 과실이 없으면 책임지지 않습니다.</p>
|
||||||
<p>회사는 이 정보의 정확성이나 이 정보를 근거로 한 결정의 결과를 보증하지 않습니다. 야외 활동, 여행, 행사 참석 같은 결정은 이용자 스스로 판단하며, 기상특보나 행사 일정은 기상청과 각 주최 측의 공식 안내를 함께 확인해 주세요.</p>
|
|
||||||
<p>회사의 고의나 중대한 과실로 생긴 손해는 이 면책에서 제외합니다.</p>
|
|
||||||
|
|
||||||
<h2>6. 게시물(댓글)</h2>
|
<h2>8. 개인정보</h2>
|
||||||
<p>게시물에 대한 책임은 그 게시물을 쓴 회원에게 있습니다. 다음 게시물은 쓸 수 없습니다.</p>
|
<p>개인정보 처리는 <a href="/privacy.html">개인정보처리방침</a>을 따릅니다.</p>
|
||||||
<ul>
|
|
||||||
<li>욕설, 비방, 혐오, 음란한 내용</li>
|
|
||||||
<li>다른 사람의 개인정보(이름, 연락처, 주소 등)를 드러내는 내용</li>
|
|
||||||
<li>광고, 홍보, 같은 내용을 되풀이하는 도배</li>
|
|
||||||
<li>다른 사람의 저작권 등 권리를 침해하거나 법령을 어기는 내용</li>
|
|
||||||
</ul>
|
|
||||||
<p>회사는 위에 해당하거나 권리자의 요청이 있는 게시물을 미리 알리지 않고 지우거나 보이지 않게 할 수 있습니다. 문제가 있는 게시물은 <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a>로 알려 주세요. 회원은 자신의 댓글을 언제든 직접 지울 수 있습니다.</p>
|
|
||||||
<p>게시물의 저작권은 쓴 회원에게 있습니다. 회원은 회사가 서비스 안에 그 게시물을 보여 주는 데 필요한 범위에서 이용하도록 허락합니다.</p>
|
|
||||||
|
|
||||||
<h2>7. 회원의 의무와 이용 제한</h2>
|
<h2>9. 문의</h2>
|
||||||
<p>회원은 자신의 계정을 스스로 관리해야 하며, 다른 사람에게 빌려주거나 넘길 수 없습니다.</p>
|
<p>운영자: AIO2O<br />이메일: <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a></p>
|
||||||
<p>자동화된 수단으로 정보를 대량으로 가져가거나, 서비스 운영을 방해하거나, 이 약관을 어기면 회사는 해당 게시물을 지우고 서비스 이용을 제한할 수 있습니다.</p>
|
|
||||||
|
|
||||||
<h2>8. 회원 탈퇴</h2>
|
<h2>10. 약관 변경</h2>
|
||||||
<p>회원은 언제든 <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a>로 탈퇴를 요청할 수 있고, 회사는 지체 없이 처리합니다. 토스 미니앱 회원은 토스 앱에서 날씨각과의 연결을 끊을 수도 있습니다. 탈퇴하면 회원 정보, 댓글, 좋아요, 저장한 포스트를 <a href="/privacy">개인정보처리방침</a>에 따라 파기하며 되살릴 수 없습니다.</p>
|
<p>이 약관이 바뀌면 시행 7일 전부터 이 페이지에 알립니다.</p>
|
||||||
|
|
||||||
<h2>9. 책임의 한계</h2>
|
|
||||||
<p>회사는 천재지변, 정전, 외부 데이터 제공처의 장애처럼 회사가 통제할 수 없는 사유나 이용자의 잘못으로 생긴 서비스 장애에 대해서는 책임지지 않습니다. 회원끼리 또는 회원과 제3자 사이에 게시물로 생긴 분쟁에 대해서도 같습니다.</p>
|
|
||||||
|
|
||||||
<h2>10. 분쟁 해결</h2>
|
|
||||||
<p>이 약관과 서비스 이용에는 대한민국 법을 적용합니다. 서비스 이용과 관련해 분쟁이 생기면 회사와 이용자는 먼저 성실히 협의하고, 소송이 필요하면 민사소송법에 따른 관할 법원에 제기합니다.</p>
|
|
||||||
|
|
||||||
<h2>11. 데이터 출처</h2>
|
|
||||||
<p>서비스는 다음 기관과 제공처의 데이터를 사용합니다. 공공 데이터는 공공데이터포털(data.go.kr)을 통해 받으며 각 기관의 이용 조건을 따릅니다.</p>
|
|
||||||
<ul>
|
|
||||||
<li>기상청: 단기·초단기·중기 예보, 기상특보</li>
|
|
||||||
<li>한국환경공단 에어코리아: 대기오염 실시간 측정 정보</li>
|
|
||||||
<li>한국천문연구원: 공휴일·24절기, 해 뜨고 지는 시각</li>
|
|
||||||
<li>한국관광공사: 축제·행사, 명소 정보와 사진 (ⓒ한국관광공사)</li>
|
|
||||||
<li>한국문화정보원: 공연·전시 정보와 사진 (ⓒ한국문화정보원)</li>
|
|
||||||
<li>Open-Meteo: 구름 등 기상 예보 (CC BY 4.0)</li>
|
|
||||||
<li>팝가: 팝업스토어 정보</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<h2>12. 운영자 정보</h2>
|
|
||||||
<p>상호: AIO2O<br />문의: <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a></p>
|
|
||||||
|
|
||||||
<h2>부칙</h2>
|
|
||||||
<p>이 약관은 2026년 10월 14일부터 시행합니다.</p>
|
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
// This file is auto-generated by @hey-api/openapi-ts
|
|
||||||
|
|
||||||
export { addComment, addMyGak, addTalk, authConfig, blockTalkAuthor, createCard, createReel, deleteComment, deleteMyGak, deleteTalk, getArticle, getCardImage, getFeed, getImage, getIndex, getPost, getReelCover, getReelVideo, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getTomorrowGuPage, getTomorrowPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listCards, listComments, listEvents, listIndices, listMyGak, listMyTalks, listPlaces, listPresets, listReels, listRegions, listSaved, listShorts, listTalks, login, logout, me, nearestRegion, type Options, publishCard, publishInstagram, publishInstagram2, refresh, rejectCard, reportTalk, savePost, scoreMyGak, signup, talkGroups, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen';
|
|
||||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type CardItem, CardStatus, type ClientOptions, type CommentData, type CommuteData, Confidence, type CreateCardData, type CreateCardError, type CreateCardErrors, type CreateCardResponse, type CreateCardResponses, type CreateReelData, type CreateReelError, type CreateReelErrors, type CreateReelResponse, type CreateReelResponses, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetCardImageData, type GetCardImageError, type GetCardImageErrors, type GetCardImageResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetReelCoverData, type GetReelCoverError, type GetReelCoverErrors, type GetReelCoverResponses, type GetReelVideoData, type GetReelVideoError, type GetReelVideoErrors, type GetReelVideoResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetTomorrowGuPageData, type GetTomorrowGuPageError, type GetTomorrowGuPageErrors, type GetTomorrowGuPageResponse, type GetTomorrowGuPageResponses, type GetTomorrowPageData, type GetTomorrowPageError, type GetTomorrowPageErrors, type GetTomorrowPageResponse, type GetTomorrowPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HeroTomorrow, type HourCell, type HoursSlide, type HttpValidationError, type ImageSlide, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCardsData, type ListCardsError, type ListCardsErrors, type ListCardsResponse, type ListCardsResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsRespoLine truncated
|
|
||||||
@@ -1,72 +1,14 @@
|
|||||||
import { client } from './client/client.gen'
|
import { configureApi } from '@nalssigak/shared/api/setup'
|
||||||
import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokens } from './auth'
|
|
||||||
|
|
||||||
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
||||||
export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '')
|
export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '')
|
||||||
|
|
||||||
type Refresh = 'ok' | 'rejected' | 'unreachable'
|
// 사파리 프라이빗 모드 등에서는 localStorage 를 읽는 것만으로 에러가 나서 쓸 때마다 꺼낸다
|
||||||
|
configureApi({
|
||||||
// 401이 한꺼번에 와도 갱신은 한 번만
|
baseUrl: API_BASE_URL,
|
||||||
let refreshing: Promise<Refresh> | null = null
|
storage: {
|
||||||
|
getItem: (key) => localStorage.getItem(key),
|
||||||
/** 서버가 거절하면 'rejected', 네트워크 오류·5xx 면 'unreachable' (이때는 토큰을 지우지 않는다) */
|
setItem: (key, value) => localStorage.setItem(key, value),
|
||||||
function refreshTokens(): Promise<Refresh> {
|
removeItem: (key) => localStorage.removeItem(key),
|
||||||
refreshing ??= (async (): Promise<Refresh> => {
|
},
|
||||||
const token = getRefreshToken()
|
|
||||||
if (!token) return 'rejected'
|
|
||||||
const res = await fetch(`${API_BASE_URL}/v1/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: token }) })
|
|
||||||
if (res.status >= 500) return 'unreachable'
|
|
||||||
const body = res.ok ? await res.json() : null
|
|
||||||
if (!body?.result?.success || !body.access_token) return 'rejected'
|
|
||||||
setTokens(body.access_token, body.refresh_token ?? token)
|
|
||||||
return 'ok'
|
|
||||||
})()
|
|
||||||
.catch((): Refresh => 'unreachable')
|
|
||||||
.finally(() => {
|
|
||||||
refreshing = null
|
|
||||||
})
|
|
||||||
return refreshing
|
|
||||||
}
|
|
||||||
|
|
||||||
const NO_REFRESH = ['/v1/auth/login', '/v1/auth/signup', '/v1/auth/refresh']
|
|
||||||
|
|
||||||
/** 같은 요청을 토큰만 바꿔(null 이면 빼고) 다시 보낼 수 있게 복사한다 */
|
|
||||||
function withToken(request: Request, token: string | null) {
|
|
||||||
const copy = request.clone()
|
|
||||||
if (token) copy.headers.set('Authorization', `Bearer ${token}`)
|
|
||||||
else copy.headers.delete('Authorization')
|
|
||||||
return copy
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 401이면 토큰을 한 번 갱신해 같은 요청을 다시 보낸다.
|
|
||||||
* 갱신이 거절되면 토큰을 지우고, 로그인 없이 되는 요청은 그냥 다시 보내고, 로그인이 꼭 필요한 요청만 로그인 창을 띄운다.
|
|
||||||
*/
|
|
||||||
async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
|
||||||
const request = input instanceof Request && !init ? input : new Request(input, init)
|
|
||||||
const retry = request.clone()
|
|
||||||
const response = await fetch(request)
|
|
||||||
if (response.status !== 401 || NO_REFRESH.includes(new URL(request.url).pathname)) return response
|
|
||||||
if (request.headers.has('Authorization')) {
|
|
||||||
const result = await refreshTokens()
|
|
||||||
if (result === 'unreachable') return response
|
|
||||||
if (result === 'ok') {
|
|
||||||
const again = await fetch(withToken(retry, getAccessToken()))
|
|
||||||
if (again.status !== 401) return again
|
|
||||||
}
|
|
||||||
if (getAccessToken()) clearTokens()
|
|
||||||
const anonymous = await fetch(withToken(retry, null))
|
|
||||||
if (anonymous.status !== 401) return anonymous
|
|
||||||
}
|
|
||||||
// 로그인 창은 사람이 한 동작(글쓰기·댓글 등)에만 띄운다. 화면이 알아서 받는 GET(내 정보 등)이나 로그아웃이 만료로 401이면 조용히 로그아웃 상태로 둔다
|
|
||||||
if (request.method !== 'GET' && new URL(request.url).pathname !== '/v1/auth/logout') emitAuthRequired()
|
|
||||||
return response
|
|
||||||
}
|
|
||||||
|
|
||||||
client.setConfig({ baseUrl: API_BASE_URL, throwOnError: true, fetch: authFetch })
|
|
||||||
|
|
||||||
client.interceptors.request.use((request) => {
|
|
||||||
const token = getAccessToken()
|
|
||||||
if (token) request.headers.set('Authorization', `Bearer ${token}`)
|
|
||||||
return request
|
|
||||||
})
|
})
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
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 } from '@tanstack/react-query'
|
||||||
import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { IS_TOSS } from '../lib/platform'
|
import { IS_TOSS } from '../lib/platform'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { kindOfHour, kst, seasonOf, type TimeKind } from './lib'
|
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
|
||||||
import './b.css'
|
import './b.css'
|
||||||
import { AuthProvider } from './auth'
|
import { AuthProvider } from './auth'
|
||||||
import { RegionProvider } from './region'
|
import { RegionProvider } from './region'
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen'
|
import { listArticlesOptions, listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { ArticleCategory, IndexCategory } from '../api/client/types.gen'
|
import { ArticleCategory, IndexCategory } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { kst, loadOf, MEDALS, seasonOf } from './lib'
|
import { kst, loadOf, MEDALS, seasonOf } from '@nalssigak/shared/lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
|
import { Chips, Ic, Sec, Skel, StateBox } from './ui'
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode, type RefObject } from 'react'
|
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode, type RefObject } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
import { PostType, SlotTone, type GakSlide, type HoursSlide, type ImageSlide, type PlanSlide, type PostData, type PostReaction, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
|
import { PostType, SlotTone, type GakSlide, type HoursSlide, type ImageSlide, type PlanSlide, type PostData, type PostReaction, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { API_BASE_URL } from '../api/setup'
|
import { API_BASE_URL } from '../api/setup'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, clockShort, fall } from './lib'
|
import { cardBg, clockShort } from '@nalssigak/shared/lib'
|
||||||
import type { SlideBg } from './types'
|
import { fall } from './lib'
|
||||||
import { deg } from './weatherText'
|
import type { SlideBg } from '@nalssigak/shared/lib/types'
|
||||||
|
import { deg } from '@nalssigak/shared/lib/weatherText'
|
||||||
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
||||||
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
|
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { usePinnedLike, type PinnedKey } from './pinnedLike'
|
import { usePinnedLike, type PinnedKey } from './pinnedLike'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getSeasonWeekOptions, listArticlesOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getSeasonWeekOptions, listArticlesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { ArticleCategory } from '../api/client/types.gen'
|
import { ArticleCategory } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { ARTICLE_CAT, cardBg, dateRange, fall, loadOf, shortDay } from './lib'
|
import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
|
||||||
|
import { ARTICLE_CAT, fall } from './lib'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
|
import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
|
||||||
|
|
||||||
|
|||||||
+250
-28
@@ -1,10 +1,12 @@
|
|||||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
||||||
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||||
import regionPages from '../../seo/region.json'
|
import regionPages from '../../seo/region.json'
|
||||||
import { setTokens, subscribeAuth } from '../api/auth'
|
import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
|
||||||
import { SITE_URL } from '../api/setup'
|
import { SITE_URL } from '../api/setup'
|
||||||
import {
|
import {
|
||||||
addCommentMutation,
|
addCommentMutation,
|
||||||
|
agreeTermsMutation,
|
||||||
|
blockAuthorMutation,
|
||||||
deleteCommentMutation,
|
deleteCommentMutation,
|
||||||
getArticleOptions,
|
getArticleOptions,
|
||||||
getFeedQueryKey,
|
getFeedQueryKey,
|
||||||
@@ -12,24 +14,30 @@ import {
|
|||||||
getSeasonWeekOptions,
|
getSeasonWeekOptions,
|
||||||
likeCommentMutation,
|
likeCommentMutation,
|
||||||
listCommentsInfiniteOptions,
|
listCommentsInfiniteOptions,
|
||||||
|
listBlockedOptions,
|
||||||
|
listBlockedQueryKey,
|
||||||
listCommentsInfiniteQueryKey,
|
listCommentsInfiniteQueryKey,
|
||||||
listRegionsOptions,
|
listRegionsOptions,
|
||||||
meQueryKey,
|
meQueryKey,
|
||||||
|
reportCommentMutation,
|
||||||
|
unblockMutation,
|
||||||
unlikeCommentMutation,
|
unlikeCommentMutation,
|
||||||
updateMeMutation,
|
updateMeMutation,
|
||||||
} from '../api/client/@tanstack/react-query.gen'
|
withdrawMutation,
|
||||||
import { AuthProvider, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '../api/client/types.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 { track } from '../lib/analytics'
|
import { track } from '../lib/analytics'
|
||||||
import { IS_TOSS, tossShare } from '../lib/platform'
|
import { IS_TOSS, tossShare } from '../lib/platform'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { useAuth } from './authContext'
|
import { useAuth } from './authContext'
|
||||||
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
|
import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib'
|
||||||
import { 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 { WeatherWhySheet } from './weatherWhy'
|
import { ARTICLE_CAT } from './lib'
|
||||||
import { MixSheet } from './myGak'
|
import { MixSheet } from './myGak'
|
||||||
import { ownPage, useRegion } from './regionContext'
|
import { ownPage, useRegion } from './regionContext'
|
||||||
|
import { WeatherWhySheet } from './weatherWhy'
|
||||||
import { useSky } from './skyContext'
|
import { useSky } from './skyContext'
|
||||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||||
@@ -642,8 +650,88 @@ function ShareSheet({ share }: { share: SharePayload }) {
|
|||||||
/* ---------- 댓글 ---------- */
|
/* ---------- 댓글 ---------- */
|
||||||
const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND
|
const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND
|
||||||
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
|
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
|
||||||
|
const REPORT_REASONS = [
|
||||||
|
[ReportReason.ABUSE, '욕설·비하'],
|
||||||
|
[ReportReason.AD, '광고'],
|
||||||
|
[ReportReason.PRIVACY, '개인정보 노출'],
|
||||||
|
[ReportReason.OTHER, '기타'],
|
||||||
|
] as const
|
||||||
|
const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments'
|
||||||
|
|
||||||
function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
|
||||||
|
function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
|
||||||
|
const { loggedIn } = useAuth()
|
||||||
|
const { open } = useSheet()
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [step, setStep] = useState<'closed' | 'menu' | 'report' | 'block'>('closed')
|
||||||
|
const [failed, setFailed] = useState(false)
|
||||||
|
const report = useMutation(reportCommentMutation())
|
||||||
|
const block = useMutation(blockAuthorMutation())
|
||||||
|
const pending = report.isPending || block.isPending
|
||||||
|
|
||||||
|
const finish = (notice: string) => ({
|
||||||
|
onSuccess: (res: { result?: { success?: boolean } }) => {
|
||||||
|
if (!res.result?.success) return setFailed(true)
|
||||||
|
setStep('closed')
|
||||||
|
onNotice(notice)
|
||||||
|
queryClient.invalidateQueries({ predicate: isCommentList })
|
||||||
|
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() })
|
||||||
|
},
|
||||||
|
onError: () => setFailed(true),
|
||||||
|
})
|
||||||
|
const go = (next: typeof step) => {
|
||||||
|
setFailed(false)
|
||||||
|
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', postId } })
|
||||||
|
setStep(next)
|
||||||
|
}
|
||||||
|
const btn = 'cursor-pointer rounded-[12px] bg-[#f3f6fb] px-3 py-2 text-[13px] font-extrabold text-(--ink) disabled:opacity-50'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button type="button" onClick={() => go(step === 'closed' ? 'menu' : 'closed')} aria-expanded={step !== 'closed'} aria-label="댓글 메뉴" className="ml-1.5 cursor-pointer px-1 font-extrabold text-(--ink3)">
|
||||||
|
⋯
|
||||||
|
</button>
|
||||||
|
{step !== 'closed' && (
|
||||||
|
<span className="mt-2 flex flex-wrap items-center gap-1.5" role="group" aria-label="댓글 메뉴">
|
||||||
|
{step === 'menu' && (
|
||||||
|
<>
|
||||||
|
<button type="button" className={btn} onClick={() => go('report')}>
|
||||||
|
신고하기
|
||||||
|
</button>
|
||||||
|
<button type="button" className={btn} onClick={() => go('block')}>
|
||||||
|
이 사람 차단하기
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{step === 'report' &&
|
||||||
|
REPORT_REASONS.map(([reason, label]) => (
|
||||||
|
<button key={reason} type="button" disabled={pending} className={btn} onClick={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.'))}>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{step === 'block' && (
|
||||||
|
<>
|
||||||
|
<span className="w-full text-[13px] font-bold text-(--ink)">{c.nickname}님 댓글을 더는 안 볼까요?</span>
|
||||||
|
<button type="button" disabled={pending} className={cx(btn, 'bg-(--heart) text-white')} onClick={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.'))}>
|
||||||
|
차단하기
|
||||||
|
</button>
|
||||||
|
<button type="button" disabled={pending} className={btn} onClick={() => go('closed')}>
|
||||||
|
취소
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{failed && (
|
||||||
|
<span className="w-full text-[13px] font-bold text-(--heart)" role="alert">
|
||||||
|
잠시 뒤에 다시 해 주세요.
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
|
||||||
const { region } = useRegion()
|
const { region } = useRegion()
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const [liked, setLiked] = useState(c.liked)
|
const [liked, setLiked] = useState(c.liked)
|
||||||
@@ -725,6 +813,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
|||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
{!c.mine && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
|
||||||
</small>
|
</small>
|
||||||
</div>
|
</div>
|
||||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
|
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
|
||||||
@@ -744,13 +833,21 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
|||||||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
||||||
})
|
})
|
||||||
const add = useMutation(addCommentMutation())
|
const add = useMutation(addCommentMutation())
|
||||||
|
const agree = useMutation(agreeTermsMutation())
|
||||||
const [addFailed, setAddFailed] = useState(false)
|
const [addFailed, setAddFailed] = useState(false)
|
||||||
|
const [askTerms, setAskTerms] = useState(false)
|
||||||
|
const [notice, setNotice] = useState('')
|
||||||
const [text, setText] = useState(draft ?? '')
|
const [text, setText] = useState(draft ?? '')
|
||||||
const inputRef = useRef<HTMLInputElement>(null)
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
||||||
|
|
||||||
const submit = (e: FormEvent) => {
|
useEffect(() => {
|
||||||
e.preventDefault()
|
if (!notice) return
|
||||||
|
const t = setTimeout(() => setNotice(''), 3000)
|
||||||
|
return () => clearTimeout(t)
|
||||||
|
}, [notice])
|
||||||
|
|
||||||
|
const send = () => {
|
||||||
const body = text.trim()
|
const body = text.trim()
|
||||||
if (!body || add.isPending) return
|
if (!body || add.isPending) return
|
||||||
setAddFailed(false)
|
setAddFailed(false)
|
||||||
@@ -758,6 +855,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
|||||||
{ path: { post_id: postId }, body: { body, region: region.code } },
|
{ path: { post_id: postId }, body: { body, region: region.code } },
|
||||||
{
|
{
|
||||||
onSuccess: (res) => {
|
onSuccess: (res) => {
|
||||||
|
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true)
|
||||||
setAddFailed(!res.result?.success)
|
setAddFailed(!res.result?.success)
|
||||||
if (!res.result?.success) return
|
if (!res.result?.success) return
|
||||||
setText('')
|
setText('')
|
||||||
@@ -769,13 +867,35 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 로그인했으면 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
|
||||||
|
const submit = (e: FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
if (me && !me.terms_agreed) return setAskTerms(true)
|
||||||
|
send()
|
||||||
|
}
|
||||||
|
const agreeAndSend = () => {
|
||||||
|
setAddFailed(false)
|
||||||
|
agree.mutate(
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
onSuccess: (res) => {
|
||||||
|
if (!res.result?.success) return setAddFailed(true)
|
||||||
|
queryClient.setQueryData(meQueryKey(), res)
|
||||||
|
setAskTerms(false)
|
||||||
|
send()
|
||||||
|
},
|
||||||
|
onError: () => setAddFailed(true),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Body>
|
<Body>
|
||||||
{comments.length ? (
|
{comments.length ? (
|
||||||
<>
|
<>
|
||||||
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
|
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
|
||||||
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} />)}
|
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} onNotice={setNotice} />)}
|
||||||
{list.hasNextPage && (
|
{list.hasNextPage && (
|
||||||
<button type="button" onClick={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 w-full cursor-pointer text-center text-sm font-bold text-(--ink3) disabled:opacity-50">
|
<button type="button" onClick={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 w-full cursor-pointer text-center text-sm font-bold text-(--ink3) disabled:opacity-50">
|
||||||
{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}
|
{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}
|
||||||
@@ -788,24 +908,38 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
|||||||
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} className="inset-0" />
|
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} className="inset-0" />
|
||||||
)}
|
)}
|
||||||
</Body>
|
</Body>
|
||||||
<div className="flex justify-around pt-1 text-[22px]" role="group" aria-label="빠른 이모지">
|
{askTerms ? (
|
||||||
{EMOJIS.map((e) => (
|
<div className="mx-3 flex flex-col gap-2 rounded-[16px] bg-[#f3f6fb] p-3" role="dialog" aria-label="이용약관 동의">
|
||||||
<button
|
<p className="m-0 text-[13px] font-bold text-(--ink)">댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요.</p>
|
||||||
key={e}
|
<div className="flex gap-2">
|
||||||
type="button"
|
<a href="/terms.html" target="_blank" rel="noopener" className="flex-1 rounded-[12px] bg-white p-2.5 text-center text-[13px] font-extrabold text-(--ink)">
|
||||||
disabled={add.isPending}
|
이용약관 보기
|
||||||
className="cursor-pointer disabled:opacity-40"
|
</a>
|
||||||
onClick={() => {
|
<button type="button" onClick={agreeAndSend} disabled={agree.isPending || add.isPending} className="flex-1 cursor-pointer rounded-[12px] bg-(--orange) p-2.5 text-[13px] font-extrabold text-white disabled:opacity-60">
|
||||||
setText((t) => (t + e).slice(0, 60))
|
동의하고 쓰기
|
||||||
inputRef.current?.focus()
|
</button>
|
||||||
}}
|
</div>
|
||||||
>
|
</div>
|
||||||
{e}
|
) : (
|
||||||
</button>
|
<div className="flex justify-around pt-1 text-[22px]" role="group" aria-label="빠른 이모지">
|
||||||
))}
|
{EMOJIS.map((e) => (
|
||||||
</div>
|
<button
|
||||||
<p className="h-4 px-4 text-center text-xs leading-4 font-bold text-(--heart)" role="alert">
|
key={e}
|
||||||
{addFailed && '댓글을 올리지 못했어요. 다시 해 주세요.'}
|
type="button"
|
||||||
|
disabled={add.isPending}
|
||||||
|
className="cursor-pointer disabled:opacity-40"
|
||||||
|
onClick={() => {
|
||||||
|
setText((t) => (t + e).slice(0, 60))
|
||||||
|
inputRef.current?.focus()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{e}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<p className={cx('h-4 px-4 text-center text-xs leading-4 font-bold', addFailed ? 'text-(--heart)' : 'text-(--ink2)')} role="alert">
|
||||||
|
{addFailed ? '댓글을 올리지 못했어요. 다시 해 주세요.' : notice}
|
||||||
</p>
|
</p>
|
||||||
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
|
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
|
||||||
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||||
@@ -870,7 +1004,93 @@ function TossNoLoginSheet({ onDone }: { onDone: () => void }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
|
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃·탈퇴 ---------- */
|
||||||
|
/** 탈퇴: 한 번 더 묻고 지운다. 계정이 없어지니 이 기기 토큰도 지운다 */
|
||||||
|
function Withdraw({ onDone }: { onDone: () => void }) {
|
||||||
|
const withdraw = useMutation(withdrawMutation())
|
||||||
|
const [asking, setAsking] = useState(false)
|
||||||
|
const [failed, setFailed] = useState(false)
|
||||||
|
if (!asking)
|
||||||
|
return (
|
||||||
|
<button type="button" onClick={() => setAsking(true)} className="cursor-pointer self-center p-1 text-[13px] font-semibold text-(--ink3)">
|
||||||
|
탈퇴하기
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
const run = () => {
|
||||||
|
setFailed(false)
|
||||||
|
withdraw.mutate(
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
onSuccess: (res) => {
|
||||||
|
if (!res.result?.success) return setFailed(true)
|
||||||
|
clearTokens()
|
||||||
|
onDone()
|
||||||
|
},
|
||||||
|
onError: () => setFailed(true),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-2.5 rounded-[18px] bg-[#fff1f3] p-3.5" role="alert">
|
||||||
|
<p className="m-0 text-center text-sm font-bold text-(--ink)">
|
||||||
|
탈퇴하면 계정과 남긴 댓글·좋아요가
|
||||||
|
<br />
|
||||||
|
모두 지워져요. 되돌릴 수 없어요.
|
||||||
|
</p>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button type="button" onClick={() => setAsking(false)} disabled={withdraw.isPending} className="flex-1 cursor-pointer rounded-[14px] bg-white p-3 text-sm font-extrabold text-(--ink)">
|
||||||
|
그만둘게요
|
||||||
|
</button>
|
||||||
|
<button type="button" onClick={run} disabled={withdraw.isPending} className="flex-1 cursor-pointer rounded-[14px] bg-(--heart) p-3 text-sm font-extrabold text-white disabled:opacity-60">
|
||||||
|
탈퇴할게요
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{failed && <p className="m-0 text-center text-[13px] font-bold text-(--heart)">탈퇴하지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 차단한 사람: 있을 때만 보이고, 풀면 그 사람 댓글이 다시 보인다 */
|
||||||
|
function Blocked() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const list = useQuery(listBlockedOptions())
|
||||||
|
const unblock = useMutation(unblockMutation())
|
||||||
|
const [failed, setFailed] = useState(false)
|
||||||
|
const users = list.data?.users ?? []
|
||||||
|
if (!users.length) return null
|
||||||
|
const release = (user_id: string) => {
|
||||||
|
setFailed(false)
|
||||||
|
unblock.mutate(
|
||||||
|
{ path: { user_id } },
|
||||||
|
{
|
||||||
|
onSuccess: (res) => {
|
||||||
|
if (!res.result?.success) return setFailed(true)
|
||||||
|
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() })
|
||||||
|
queryClient.invalidateQueries({ predicate: isCommentList })
|
||||||
|
},
|
||||||
|
onError: () => setFailed(true),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<section aria-label="차단한 사람">
|
||||||
|
<h4 className="m-0 mb-2 text-sm font-extrabold">차단한 사람</h4>
|
||||||
|
<ul className="m-0 flex list-none flex-col gap-2 p-0">
|
||||||
|
{users.map((u) => (
|
||||||
|
<li key={u.user_id} className="flex items-center gap-2.5">
|
||||||
|
<Avatar character={u.character} color={u.color} />
|
||||||
|
<span className="flex-1 text-sm font-bold">{u.nickname}</span>
|
||||||
|
<button type="button" onClick={() => release(u.user_id)} disabled={unblock.isPending} className="cursor-pointer rounded-[12px] bg-[#f3f6fb] px-3 py-2 text-[13px] font-extrabold text-(--ink) disabled:opacity-50">
|
||||||
|
풀기
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
{failed && <p className="m-0 mt-1.5 text-[13px] font-bold text-(--heart)">잠시 뒤에 다시 해 주세요.</p>}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function MeSheet({ onDone }: { onDone: () => void }) {
|
function MeSheet({ onDone }: { onDone: () => void }) {
|
||||||
const install = useInstall()
|
const install = useInstall()
|
||||||
const installable = useInstallable()
|
const installable = useInstallable()
|
||||||
@@ -997,6 +1217,8 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
|||||||
>
|
>
|
||||||
로그아웃
|
로그아웃
|
||||||
</button>
|
</button>
|
||||||
|
<Blocked />
|
||||||
|
<Withdraw onDone={onDone} />
|
||||||
</Body>
|
</Body>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { useState, type ReactNode } from 'react'
|
import { useState, type ReactNode } from 'react'
|
||||||
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getSkyOptions, getSkyRankingOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import type { BestTime, SkyPlanData } from '../api/client/types.gen'
|
import type { BestTime, SkyPlanData } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { clockShort, loadOf } from './lib'
|
import { clockShort, loadOf } from '@nalssigak/shared/lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { MapLink, Sec, Skel, StateBox } from './ui'
|
import { MapLink, Sec, Skel, StateBox } from './ui'
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useSearchParams } from 'react-router'
|
import { useSearchParams } from 'react-router'
|
||||||
import type { TalkTopic } from '../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 { TalkCard } from './talk'
|
||||||
import { TOPICS, useTopicTalks } from './talkState'
|
import { TOPICS, useTopicTalks } from './talkState'
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
|
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
|
||||||
import { Link, useLocation } from 'react-router'
|
import { Link, useLocation } from 'react-router'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import {
|
import {
|
||||||
PostType,
|
PostType,
|
||||||
RainType,
|
RainType,
|
||||||
@@ -15,9 +15,10 @@ import {
|
|||||||
type TalkData,
|
type TalkData,
|
||||||
type TopIndex,
|
type TopIndex,
|
||||||
type WeatherSlot,
|
type WeatherSlot,
|
||||||
} from '../api/client/types.gen'
|
} from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
|
import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
|
||||||
|
import { fall } from './lib'
|
||||||
import { FoliageCard } from './foliageMap'
|
import { FoliageCard } from './foliageMap'
|
||||||
import { InstallBanner } from './installBanner'
|
import { InstallBanner } from './installBanner'
|
||||||
import { MyGakRow } from './myGak'
|
import { MyGakRow } from './myGak'
|
||||||
@@ -33,7 +34,7 @@ import { useSky } from './skyContext'
|
|||||||
import { DayShareCard, DayShareGrid, GakShareCard, type DayShare } from './shareCards'
|
import { DayShareCard, DayShareGrid, GakShareCard, type DayShare } from './shareCards'
|
||||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||||
import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
|
import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
|
||||||
import { deg, slotAt } from './weatherText'
|
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText'
|
||||||
|
|
||||||
type Mode = 'now' | TimeKind
|
type Mode = 'now' | TimeKind
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { useRef, useState, type ReactNode } from 'react'
|
import { useRef, useState, type ReactNode } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { cardBg, dateRange, loadOf, shortDay } from './lib'
|
import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||||
|
|||||||
+13
-4
@@ -1,8 +1,8 @@
|
|||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
|
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
|
||||||
import { clearTokens, getAccessToken, subscribeAuth } from '../api/auth'
|
import { clearTokens, getAccessToken, subscribeAuth } from '@nalssigak/shared/api/auth'
|
||||||
import { meOptions } from '../api/client/@tanstack/react-query.gen'
|
import { meOptions, meQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { logout as logoutOnServer } from '../api/client/sdk.gen'
|
import { logout as logoutOnServer } from '@nalssigak/shared/api/client/sdk.gen'
|
||||||
import { AuthContext } from './authContext'
|
import { AuthContext } from './authContext'
|
||||||
|
|
||||||
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
|
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
|
||||||
@@ -18,7 +18,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
const me = useQuery({ ...meOptions(), enabled: !!token })
|
const me = useQuery({ ...meOptions(), enabled: !!token })
|
||||||
|
|
||||||
// 로그인·로그아웃하면 좋아요 여부가 달라지니 받아 둔 데이터를 다시 받는다
|
// 로그인·로그아웃하면 좋아요 여부가 달라지니 받아 둔 데이터를 다시 받는다
|
||||||
useEffect(() => subscribeAuth((reason) => reason === 'change' && queryClient.invalidateQueries()), [queryClient])
|
// 로그아웃·탈퇴 땐 내 정보 캐시를 먼저 버린다. 남겨 두면 다시 받다가 401 이 나서 로그인 창이 뜬다
|
||||||
|
useEffect(
|
||||||
|
() =>
|
||||||
|
subscribeAuth((reason) => {
|
||||||
|
if (reason !== 'change') return
|
||||||
|
if (!getAccessToken()) queryClient.removeQueries({ queryKey: meQueryKey() })
|
||||||
|
void queryClient.invalidateQueries()
|
||||||
|
}),
|
||||||
|
[queryClient],
|
||||||
|
)
|
||||||
|
|
||||||
const mePending = !!token && me.isPending
|
const mePending = !!token && me.isPending
|
||||||
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, mePending, logout }), [token, me.data, mePending])
|
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, mePending, logout }), [token, me.data, mePending])
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createContext, use } from 'react'
|
import { createContext, use } from 'react'
|
||||||
import type { Me } from '../api/client/types.gen'
|
import type { Me } from '@nalssigak/shared/api/client/types.gen'
|
||||||
|
|
||||||
/** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */
|
/** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */
|
||||||
export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void }
|
export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void }
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useLayoutEffect, useMemo, useState, type RefObject } from 'react'
|
import { useLayoutEffect, useMemo, useState, type RefObject } from 'react'
|
||||||
import data from '../../seo/foliage_2026.json'
|
import data from '../../seo/foliage_2026.json'
|
||||||
import { kst } from './lib'
|
import { kst } from '@nalssigak/shared/lib'
|
||||||
|
|
||||||
export type Kind = 'maple' | 'ginkgo'
|
export type Kind = 'maple' | 'ginkgo'
|
||||||
export type Stage = 'before' | 'first' | 'peak' | 'gone'
|
export type Stage = 'before' | 'first' | 'peak' | 'gone'
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
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 '../api/client/types.gen'
|
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'
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useMutation, useQuery } from '@tanstack/react-query'
|
import { useMutation, useQuery } from '@tanstack/react-query'
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { authConfigOptions, googleLoginMutation } from '../api/client/@tanstack/react-query.gen'
|
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import type { ResAuth } from '../api/client/types.gen'
|
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'
|
||||||
|
|
||||||
type GoogleId = {
|
type GoogleId = {
|
||||||
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
|
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
|
||||||
|
|||||||
+2
-131
@@ -1,4 +1,5 @@
|
|||||||
import type { CSSProperties } from 'react'
|
import type { CSSProperties } from 'react'
|
||||||
|
import { ARTICLE_LABEL } from '@nalssigak/shared/lib'
|
||||||
|
|
||||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental', 'ginkgo'])
|
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental', 'ginkgo'])
|
||||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
||||||
@@ -10,136 +11,6 @@ export function iconSrc(name: string) {
|
|||||||
return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png`
|
return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png`
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MEDALS = ['gold', 'silver', 'bronze'] as const
|
|
||||||
|
|
||||||
/** 고를 수 있는 프로필 캐릭터 (백엔드 CHARACTERS 와 같아야 한다) */
|
|
||||||
export const CHARACTERS = [
|
|
||||||
['rabbit', '토끼'],
|
|
||||||
['bear', '곰'],
|
|
||||||
['dog', '강아지'],
|
|
||||||
['sun', '해님'],
|
|
||||||
['moon', '달님'],
|
|
||||||
['cloud', '구름'],
|
|
||||||
] as const
|
|
||||||
|
|
||||||
/** 프로필 배경색 (백엔드 COLORS 와 같아야 한다) */
|
|
||||||
export const AVATAR_COLORS: Record<string, string> = { orange: '#ff8e4e', blue: '#4f97e3', green: '#1f9d62', purple: '#7a5cd6', pink: '#d6457a', brown: '#a8643a' }
|
|
||||||
|
|
||||||
/** 오늘 기분 (백엔드 MOODS 와 같아야 한다) */
|
|
||||||
export const MOODS = [
|
|
||||||
['clear', '☀️', '맑음'],
|
|
||||||
['partly', '⛅', '구름 조금'],
|
|
||||||
['cloudy', '☁️', '흐림'],
|
|
||||||
['rain', '🌧️', '비'],
|
|
||||||
['thunder', '⚡', '번개'],
|
|
||||||
['snow', '❄️', '눈'],
|
|
||||||
['fog', '🌫️', '안개'],
|
|
||||||
['rainbow', '🌈', '무지개'],
|
|
||||||
] as const
|
|
||||||
|
|
||||||
export const moodEmoji = (mood?: string | null) => MOODS.find(([k]) => k === mood)?.[1]
|
|
||||||
|
|
||||||
export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties
|
export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties
|
||||||
|
|
||||||
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const
|
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: [ARTICLE_LABEL[1], 'text-[#1f9d62]'], 2: [ARTICLE_LABEL[2], 'text-[#7a5cd6]'], 3: [ARTICLE_LABEL[3], 'text-(--orange)'] }
|
||||||
|
|
||||||
// 달(1~12) → 계절 이름과 아이콘. 봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2 (서버 각 제철 기준과 같다)
|
|
||||||
const SEASONS: [string, string][] = [['겨울', 'snow'], ['봄', 'garden'], ['여름', 'sun'], ['가을', 'maple']]
|
|
||||||
export const seasonOf = (month: number) => SEASONS[Math.floor((month % 12) / 3)]
|
|
||||||
|
|
||||||
const KST = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Seoul', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23', weekday: 'short' })
|
|
||||||
const WD_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
|
||||||
|
|
||||||
/** 한국 시각으로 쪼개기 (브라우저 시간대와 상관없이) */
|
|
||||||
export function kst(input: string | Date) {
|
|
||||||
const parts = Object.fromEntries(KST.formatToParts(typeof input === 'string' ? new Date(input) : input).map((p) => [p.type, p.value]))
|
|
||||||
return { y: +parts.year, mo: +parts.month, d: +parts.day, h: +parts.hour, mi: +parts.minute, wd: WD_EN.indexOf(parts.weekday) }
|
|
||||||
}
|
|
||||||
|
|
||||||
const h12 = (h: number) => h % 12 || 12
|
|
||||||
|
|
||||||
/** 18:25 → "18:25" (포스트·플랜과 같은 24시간제) */
|
|
||||||
export function clockShort(iso: string) {
|
|
||||||
const t = kst(iso)
|
|
||||||
return `${t.h}:${String(t.mi).padStart(2, '0')}`
|
|
||||||
}
|
|
||||||
|
|
||||||
const COMPASS = ['북', '북북동', '북동', '동북동', '동', '동남동', '남동', '남남동', '남', '남남서', '남서', '서남서', '서', '서북서', '북서', '북북서']
|
|
||||||
|
|
||||||
/** 방위각 → 16방위 이름. 263 → "서" */
|
|
||||||
/** 네이버 지도에서 장소 이름(또는 주소)으로 찾기 */
|
|
||||||
export const naverMap = (query: string) => `https://map.naver.com/p/search/${encodeURIComponent(query)}`
|
|
||||||
|
|
||||||
export const compass = (deg: number) => COMPASS[Math.round(deg / 22.5) % 16]
|
|
||||||
|
|
||||||
/** 18:30 → "6시 반", 18:25 → "6시 25분" */
|
|
||||||
export function timeWords(iso: string) {
|
|
||||||
const t = kst(iso)
|
|
||||||
return `${h12(t.h)}시${t.mi === 0 ? '' : t.mi === 30 ? ' 반' : ` ${t.mi}분`}`
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 발표 시각 → "방금" · "12분 전" · "3시간 전" */
|
|
||||||
export function ago(iso: string | null | undefined, now = Date.now()) {
|
|
||||||
if (!iso) return '오늘'
|
|
||||||
const min = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000))
|
|
||||||
if (min < 5) return '방금'
|
|
||||||
if (min < 60) return `${min}분 전`
|
|
||||||
return `${Math.floor(min / 60)}시간 전`
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 날짜 칸 이름: 오늘 · 내일 · "토 10.4" */
|
|
||||||
export function dayLabel(date: string, index: number) {
|
|
||||||
if (index === 0) return '오늘'
|
|
||||||
if (index === 1) return '내일'
|
|
||||||
const [, m, d] = date.split('-').map(Number)
|
|
||||||
const wd = new Date(`${date}T12:00:00+09:00`).getUTCDay()
|
|
||||||
return `${WEEKDAYS[wd]} ${m}.${d}`
|
|
||||||
}
|
|
||||||
|
|
||||||
export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
|
|
||||||
|
|
||||||
// 서울 월별 대략 일몰 시각(시). 서버 값(/v1/feed hero.sky_mode)이 없을 때만 쓴다
|
|
||||||
const SUNSET_HOUR = [17.7, 18.2, 18.6, 19.1, 19.5, 19.9, 19.9, 19.5, 18.9, 18.2, 17.6, 17.3]
|
|
||||||
|
|
||||||
/** 피드와 같은 시간대: 아침 05–11 · 낮 11–일몰 2시간 전 · 저녁(sunset) 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05 */
|
|
||||||
export function kindOfHour(h: number, month = new Date().getMonth() + 1, minute = 0): TimeKind {
|
|
||||||
const at = h + minute / 60
|
|
||||||
const sunset = SUNSET_HOUR[month - 1]
|
|
||||||
if (at >= 5 && at < 11) return 'morning'
|
|
||||||
if (at >= 11 && at < sunset + 1) return at < sunset - 2 ? 'day' : 'sunset'
|
|
||||||
return 'night'
|
|
||||||
}
|
|
||||||
|
|
||||||
/** "서울 마포구" → "서울" */
|
|
||||||
export const sidoOf = (regionName: string) => regionName.split(' ')[0]
|
|
||||||
|
|
||||||
/** 2026-10-02 ~ 2026-10-11 → "10.2 ~ 10.11", 하루짜리는 "10.3" */
|
|
||||||
export function dateRange(start: string, end: string) {
|
|
||||||
return start === end ? shortDay(start) : `${shortDay(start)} ~ ${shortDay(end)}`
|
|
||||||
}
|
|
||||||
|
|
||||||
const CARD_BG = ['night', 'butter', 'lilac', 'mint', 'peach', 'sky'] as const
|
|
||||||
const ICON_BG: Record<string, (typeof CARD_BG)[number] | 'dusk'> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', fireworks: 'night', popup: 'peach', exhibition: 'lilac', concert: 'night', sheaf: 'butter', rain: 'sky', calendar: 'sky', bulb: 'lilac', maple: 'peach', snow: 'sky', thermo: 'sky', umbrella: 'lilac' }
|
|
||||||
|
|
||||||
/** API에 배경색이 없어 아이콘·순서로 카드 배경을 고른다 */
|
|
||||||
export function cardBg(icon: string, index: number) {
|
|
||||||
return ICON_BG[icon] && icon !== 'calendar' ? ICON_BG[icon] : CARD_BG[index % CARD_BG.length]
|
|
||||||
}
|
|
||||||
|
|
||||||
/** "2026-09-23" → "9.23" */
|
|
||||||
export const shortDay = (day: string) => day.split('-').slice(1).map(Number).join('.')
|
|
||||||
|
|
||||||
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: ['계절 소식', 'text-[#1f9d62]'], 2: ['날씨 상식', 'text-[#7a5cd6]'], 3: ['각 원리', 'text-(--orange)'] }
|
|
||||||
|
|
||||||
/** 읽을거리 한 줄 정보: "계절 소식 · 3분" */
|
|
||||||
export const articleMeta = (a: { category: number; read_minutes: number }) => `${ARTICLE_CAT[a.category]?.[0] ?? '읽을거리'} · ${a.read_minutes}분`
|
|
||||||
|
|
||||||
export type Load = 'loading' | 'error' | 'retrying' | 'ready'
|
|
||||||
type QueryLike = { data?: unknown; isPending: boolean; isError: boolean; isFetching: boolean; errorUpdateCount: number }
|
|
||||||
|
|
||||||
/** 데이터가 있으면 ready. 실패 뒤 다시 받는 중(retrying)은 처음 불러오기(loading)와 구분한다 */
|
|
||||||
export function loadOf(q: QueryLike): Load {
|
|
||||||
if (q.data !== undefined) return 'ready'
|
|
||||||
if (q.isError) return q.isFetching ? 'retrying' : 'error'
|
|
||||||
return q.isFetching && q.errorUpdateCount > 0 ? 'retrying' : 'loading'
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, type ReactNode } from 'react'
|
import { useState, type ReactNode } from 'react'
|
||||||
import type { MyGakPreset, MyGakRule, MyGakScore } from '../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, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useEffect, useSyncExternalStore } from 'react'
|
import { useEffect, useSyncExternalStore } from 'react'
|
||||||
import { SITE_URL } from '../api/setup'
|
import { SITE_URL } from '../api/setup'
|
||||||
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '../api/client/@tanstack/react-query.gen'
|
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { scoreMyGak } from '../api/client/sdk.gen'
|
import { scoreMyGak } from '@nalssigak/shared/api/client/sdk.gen'
|
||||||
import type { MyGakRule, MyGakScore } from '../api/client/types.gen'
|
import type { MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { useAuth } from './authContext'
|
import { useAuth } from './authContext'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
|
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import type { PostReaction, ResFeed } from '../api/client/types.gen'
|
import type { PostReaction, ResFeed } from '@nalssigak/shared/api/client/types.gen'
|
||||||
|
|
||||||
export type PinnedKey = 'hero_post' | 'gak_post' | 'foliage_post' | 'events_post' | 'season_post'
|
export type PinnedKey = 'hero_post' | 'gak_post' | 'foliage_post' | 'events_post' | 'season_post'
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||||
import { useLocation, useNavigate } from 'react-router'
|
import { useLocation, useNavigate } from 'react-router'
|
||||||
import regionPages from '../../seo/region.json'
|
import regionPages from '../../seo/region.json'
|
||||||
import { nearestRegion } from '../api/client/sdk.gen'
|
import { nearestRegion } from '@nalssigak/shared/api/client/sdk.gen'
|
||||||
import type { RegionData } from '../api/client/types.gen'
|
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { track } from '../lib/analytics'
|
import { track } from '../lib/analytics'
|
||||||
import { IS_TOSS, tossLocation } from '../lib/platform'
|
import { IS_TOSS, tossLocation } from '../lib/platform'
|
||||||
import { DEFAULT_REGION, ownPage, RegionContext, type LocateStatus } from './regionContext'
|
import { DEFAULT_REGION, ownPage, RegionContext, type LocateStatus } from './regionContext'
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import { createContext, use } from 'react'
|
import { createContext, use } from 'react'
|
||||||
|
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import regionPages from '../../seo/region.json'
|
import regionPages from '../../seo/region.json'
|
||||||
import type { RegionData } from '../api/client/types.gen'
|
|
||||||
|
|
||||||
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
||||||
|
|
||||||
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus }
|
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus }
|
||||||
|
|
||||||
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 }
|
export { DEFAULT_REGION } from '@nalssigak/shared/lib'
|
||||||
|
|
||||||
/** 구 하나만 보여 주는 지역 페이지: 일반 시군구, 또는 구로 나뉜 시의 구 페이지 */
|
/** 구 하나만 보여 주는 지역 페이지: 일반 시군구, 또는 구로 나뉜 시의 구 페이지 */
|
||||||
export const ownPage = (code: string) => regionPages.find((p) => p.regions.length === 1 && p.regions[0].code === code)
|
export const ownPage = (code: string) => regionPages.find((p) => p.regions.length === 1 && p.regions[0].code === code)
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import type { Ref } from 'react'
|
import type { Ref } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import type { TopIndex } from '../api/client/types.gen'
|
import type { TopIndex } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { LEAF_SHADOW, MAP_IMG, MAP_SRC, md, PROVINCE, PROVINCES, STAGE, type Spot } from './foliage'
|
import { LEAF_SHADOW, MAP_IMG, MAP_SRC, md, PROVINCE, PROVINCES, STAGE, type Spot } from './foliage'
|
||||||
import { MEDALS, type TimeKind } from './lib'
|
import { MEDALS, type TimeKind } from '@nalssigak/shared/lib'
|
||||||
import { Ic } from './ui'
|
import { Ic } from './ui'
|
||||||
|
|
||||||
/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
|
/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { MyGak } from './myGakState'
|
import type { MyGak } from './myGakState'
|
||||||
import type { TalkData } from '../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) */
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createContext, use } from 'react'
|
import { createContext, use } from 'react'
|
||||||
import type { TimeKind } from './lib'
|
import type { TimeKind } from '@nalssigak/shared/lib'
|
||||||
|
|
||||||
/** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼으로 고른 값은 탭을 옮겨도 유지된다 */
|
/** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼으로 고른 값은 탭을 옮겨도 유지된다 */
|
||||||
export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }
|
export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }
|
||||||
|
|||||||
@@ -8,14 +8,14 @@ import {
|
|||||||
likeTalkMutation,
|
likeTalkMutation,
|
||||||
reportTalkMutation,
|
reportTalkMutation,
|
||||||
unlikeTalkMutation,
|
unlikeTalkMutation,
|
||||||
} from '../api/client/@tanstack/react-query.gen'
|
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { uploadTalkImage } from '../api/client/sdk.gen'
|
import { uploadTalkImage } from '@nalssigak/shared/api/client/sdk.gen'
|
||||||
import { TalkReport, TalkTopic, type TalkData } from '../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 { 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 './lib'
|
import { ago, 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'
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
|
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
|
||||||
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions, talkGroupsOptions } from '../api/client/@tanstack/react-query.gen'
|
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions, talkGroupsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
import { TalkTopic, type TalkData } from '../api/client/types.gen'
|
import { TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { useRegion } from './regionContext'
|
import { useRegion } from './regionContext'
|
||||||
|
|
||||||
// 글 주제와 피드 묶음 이름
|
// 글 주제와 피드 묶음 이름
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ import { Link } from 'react-router'
|
|||||||
import { IS_TOSS } from '../lib/platform'
|
import { IS_TOSS } from '../lib/platform'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
import { useCarousel, type Carousel } from './carousel'
|
import { useCarousel, type Carousel } from './carousel'
|
||||||
import { AVATAR_COLORS, iconSrc, moodEmoji, naverMap, type Load } from './lib'
|
import { AVATAR_COLORS, moodEmoji, naverMap, type Load } from '@nalssigak/shared/lib'
|
||||||
|
import { iconSrc } from './lib'
|
||||||
|
|
||||||
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
|
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { WeatherWhy } from '../api/client/types.gen'
|
import type { WeatherWhy } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import { cx } from '../lib/utils'
|
import { cx } from '../lib/utils'
|
||||||
|
|
||||||
/** status: 히어로 상태 줄 그대로 (단계 이름, 실제 값) */
|
/** status: 히어로 상태 줄 그대로 (단계 이름, 실제 값) */
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"enabledPlugins": {
|
||||||
|
"expo@claude-plugins-official": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# 앱이 부를 API 주소. 실기기에서는 localhost 대신 PC의 내부 IP (예: http://192.168.0.10:9810)
|
||||||
|
EXPO_PUBLIC_API_BASE_URL=http://localhost:9810
|
||||||
|
# 사진 경로(/season/..)를 붙일 사이트 주소
|
||||||
|
EXPO_PUBLIC_SITE_URL=https://weather.o2o.kr
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
|
||||||
|
|
||||||
|
# dependencies
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# Expo
|
||||||
|
.expo/
|
||||||
|
dist/
|
||||||
|
web-build/
|
||||||
|
expo-env.d.ts
|
||||||
|
|
||||||
|
# Native
|
||||||
|
.kotlin/
|
||||||
|
*.orig.*
|
||||||
|
*.jks
|
||||||
|
*.p8
|
||||||
|
*.p12
|
||||||
|
*.key
|
||||||
|
*.mobileprovision
|
||||||
|
|
||||||
|
# Metro
|
||||||
|
.metro-health-check*
|
||||||
|
|
||||||
|
# debug
|
||||||
|
npm-debug.*
|
||||||
|
yarn-debug.*
|
||||||
|
yarn-error.*
|
||||||
|
|
||||||
|
# macOS
|
||||||
|
.DS_Store
|
||||||
|
*.pem
|
||||||
|
|
||||||
|
# local env files
|
||||||
|
.env*.local
|
||||||
|
|
||||||
|
# typescript
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
example
|
||||||
|
|
||||||
|
# generated native folders
|
||||||
|
/ios
|
||||||
|
/android
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
This is an Expo/React Native mobile application. Prioritize mobile-first patterns, performance, and cross-platform compatibility.
|
||||||
|
|
||||||
|
## Expo has changed — do not trust your training data
|
||||||
|
|
||||||
|
Expo ships breaking changes every SDK release. APIs you remember are likely renamed, moved, or removed. Before writing any code that touches an Expo, EAS, or React Native API:
|
||||||
|
|
||||||
|
1. Read the major version of the `expo` package in `package.json`.
|
||||||
|
2. Fetch the matching versioned docs: `https://docs.expo.dev/versions/v<major>.0.0/`
|
||||||
|
3. For anything else, fetch https://docs.expo.dev/llms.txt — an index of all Expo docs with corrections to common LLM misconceptions. Follow its links to the specific page you need; never answer from memory.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
Use `bunx` instead of `npx` if the project uses bun (`bun.lock` present).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx expo install <package> # ALWAYS use instead of npm/yarn/pnpm/bun add — resolves SDK-compatible versions
|
||||||
|
npx expo start # start the dev server
|
||||||
|
npx expo lint # lint
|
||||||
|
npx tsc --noEmit # typecheck
|
||||||
|
npx expo-doctor # diagnose dependency and config issues
|
||||||
|
npx expo install --fix # fix incompatible package versions
|
||||||
|
```
|
||||||
|
|
||||||
|
Run lint and typecheck before declaring any task done.
|
||||||
|
|
||||||
|
## Navigation & Routing
|
||||||
|
|
||||||
|
- Use **Expo Router** for all navigation. Routes live in `src/app/` — every file there is a screen, `_layout.tsx` files define navigators. Keep non-route code (components, hooks, utils) outside `src/app/`.
|
||||||
|
- Import `Link`, `router`, and `useLocalSearchParams` from `expo-router`.
|
||||||
|
- Docs: https://docs.expo.dev/router/introduction.md
|
||||||
|
|
||||||
|
## Building with EAS
|
||||||
|
|
||||||
|
Use EAS to build, sign, and submit the app in the cloud (`eas build`, `eas submit`) and to ship over-the-air updates (`eas update`) — no local Xcode or Android Studio required. Run EAS CLI as `bunx eas-cli <command>` in Bun projects, or `npx eas-cli@latest <command>` otherwise; substitute that for bare `eas` in docs examples.
|
||||||
|
Docs: https://docs.expo.dev/eas/index.md
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- If `ios/` and `android/` directories do not exist, they are generated (Continuous Native Generation). Never create or edit them by hand — configure native behavior in `app.json` and config plugins.
|
||||||
|
- Expo Go only includes its bundled native modules. After adding a library with native code, the app needs a development build: `npx expo run:ios|android` locally, or `eas build --profile development`.
|
||||||
|
- Prefer recommended Expo modules over third-party libraries, and check your available skills before adding dependencies. Docs: https://docs.expo.dev/versions/latest/index.md
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
{
|
||||||
|
"expo": {
|
||||||
|
"name": "날씨각",
|
||||||
|
"slug": "nalssigak",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"orientation": "portrait",
|
||||||
|
"icon": "./assets/images/icon.png",
|
||||||
|
"scheme": "nalssigak",
|
||||||
|
"userInterfaceStyle": "automatic",
|
||||||
|
"ios": {
|
||||||
|
"icon": "./assets/images/icon.png",
|
||||||
|
"infoPlist": {
|
||||||
|
"ITSAppUsesNonExemptEncryption": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"android": {
|
||||||
|
"versionCode": 1000,
|
||||||
|
"adaptiveIcon": {
|
||||||
|
"backgroundColor": "#bbeafd",
|
||||||
|
"foregroundImage": "./assets/images/android-icon-foreground.png",
|
||||||
|
"backgroundImage": "./assets/images/android-icon-background.png",
|
||||||
|
"monochromeImage": "./assets/images/android-icon-monochrome.png"
|
||||||
|
},
|
||||||
|
"predictiveBackGestureEnabled": false,
|
||||||
|
"permissions": [
|
||||||
|
"android.permission.ACCESS_COARSE_LOCATION"
|
||||||
|
],
|
||||||
|
"package": "kr.o2o.nalssigak",
|
||||||
|
"blockedPermissions": [
|
||||||
|
"android.permission.ACCESS_FINE_LOCATION",
|
||||||
|
"android.permission.SYSTEM_ALERT_WINDOW",
|
||||||
|
"android.permission.READ_EXTERNAL_STORAGE",
|
||||||
|
"android.permission.WRITE_EXTERNAL_STORAGE"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"web": {
|
||||||
|
"output": "static",
|
||||||
|
"favicon": "./assets/images/favicon.png"
|
||||||
|
},
|
||||||
|
"plugins": [
|
||||||
|
"expo-router",
|
||||||
|
[
|
||||||
|
"expo-splash-screen",
|
||||||
|
{
|
||||||
|
"backgroundColor": "#bbeafd",
|
||||||
|
"image": "./assets/images/splash-icon.png",
|
||||||
|
"imageWidth": 200
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"expo-secure-store",
|
||||||
|
"expo-sharing",
|
||||||
|
[
|
||||||
|
"expo-location",
|
||||||
|
{
|
||||||
|
"locationWhenInUsePermission": "가장 가까운 동네 날씨를 보여 드리려고 위치를 써요."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"@react-native-google-signin/google-signin"
|
||||||
|
],
|
||||||
|
"experiments": {
|
||||||
|
"typedRoutes": true,
|
||||||
|
"reactCompiler": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 1.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 107 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.3 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 705 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 207 KiB |
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"cli": {
|
||||||
|
"version": ">= 16.0.0",
|
||||||
|
"appVersionSource": "remote"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"development": {
|
||||||
|
"developmentClient": true,
|
||||||
|
"distribution": "internal"
|
||||||
|
},
|
||||||
|
"preview": {
|
||||||
|
"distribution": "internal",
|
||||||
|
"env": {
|
||||||
|
"EXPO_PUBLIC_API_BASE_URL": "https://weather.o2o.kr",
|
||||||
|
"EXPO_PUBLIC_SITE_URL": "https://weather.o2o.kr"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"production": {
|
||||||
|
"autoIncrement": true,
|
||||||
|
"env": {
|
||||||
|
"EXPO_PUBLIC_API_BASE_URL": "https://weather.o2o.kr",
|
||||||
|
"EXPO_PUBLIC_SITE_URL": "https://weather.o2o.kr"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"submit": {
|
||||||
|
"production": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
// https://docs.expo.dev/guides/using-eslint/
|
||||||
|
const { defineConfig } = require('eslint/config');
|
||||||
|
const expoConfig = require("eslint-config-expo/flat");
|
||||||
|
|
||||||
|
module.exports = defineConfig([
|
||||||
|
expoConfig,
|
||||||
|
{
|
||||||
|
ignores: ["dist/*"],
|
||||||
|
}
|
||||||
|
]);
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
const path = require('path');
|
||||||
|
const { getDefaultConfig } = require('expo/metro-config');
|
||||||
|
const { withUniwindConfig } = require('uniwind/metro');
|
||||||
|
|
||||||
|
const config = getDefaultConfig(__dirname);
|
||||||
|
|
||||||
|
// 루트 node_modules 에는 웹용 react 가 따로 있어, RN 렌더러와 맞는 앱의 react 만 쓰게 고정한다
|
||||||
|
const PINNED = ['react', 'react-dom'];
|
||||||
|
const resolveRequest = config.resolver.resolveRequest;
|
||||||
|
config.resolver.resolveRequest = (context, moduleName, platform) => {
|
||||||
|
const pinned = PINNED.find((name) => moduleName === name || moduleName.startsWith(`${name}/`));
|
||||||
|
const next = pinned ? { ...context, originModulePath: path.join(__dirname, 'package.json') } : context;
|
||||||
|
return (resolveRequest ?? context.resolveRequest)(next, moduleName, platform);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = withUniwindConfig(config, {
|
||||||
|
cssEntryFile: './src/global.css',
|
||||||
|
dtsFile: './src/uniwind-types.d.ts',
|
||||||
|
});
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
{
|
||||||
|
"name": "mobile",
|
||||||
|
"main": "expo-router/entry",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@expo-google-fonts/bagel-fat-one": "^0.4.0",
|
||||||
|
"@expo-google-fonts/gowun-batang": "^0.4.1",
|
||||||
|
"@expo-google-fonts/jua": "^0.4.1",
|
||||||
|
"@expo/ui": "~57.0.23",
|
||||||
|
"@nalssigak/shared": "*",
|
||||||
|
"@react-native-google-signin/google-signin": "^16.1.5",
|
||||||
|
"@tanstack/react-query": "^5.104.2",
|
||||||
|
"expo": "~57.0.28",
|
||||||
|
"expo-constants": "~57.0.21",
|
||||||
|
"expo-device": "~57.0.2",
|
||||||
|
"expo-font": "~57.0.4",
|
||||||
|
"expo-glass-effect": "~57.0.4",
|
||||||
|
"expo-image": "~57.0.5",
|
||||||
|
"expo-linear-gradient": "~57.0.2",
|
||||||
|
"expo-linking": "~57.0.12",
|
||||||
|
"expo-location": "~57.0.21",
|
||||||
|
"expo-router": "~57.0.26",
|
||||||
|
"expo-secure-store": "~57.0.4",
|
||||||
|
"expo-sharing": "~57.0.23",
|
||||||
|
"expo-splash-screen": "~57.0.10",
|
||||||
|
"expo-status-bar": "~57.0.1",
|
||||||
|
"expo-symbols": "~57.0.3",
|
||||||
|
"expo-system-ui": "~57.0.4",
|
||||||
|
"expo-web-browser": "~57.0.3",
|
||||||
|
"react": "19.2.3",
|
||||||
|
"react-dom": "19.2.3",
|
||||||
|
"react-native": "0.86.3",
|
||||||
|
"react-native-gesture-handler": "~2.32.0",
|
||||||
|
"react-native-reanimated": "4.5.1",
|
||||||
|
"react-native-safe-area-context": "~5.7.0",
|
||||||
|
"react-native-screens": "~4.26.0",
|
||||||
|
"react-native-svg": "15.15.4",
|
||||||
|
"react-native-view-shot": "5.1.0",
|
||||||
|
"react-native-web": "~0.21.0",
|
||||||
|
"react-native-worklets": "0.10.1",
|
||||||
|
"tailwindcss": "^4.3.3",
|
||||||
|
"uniwind": "^1.12.2"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/react": "~19.2.2",
|
||||||
|
"eslint": "^9.0.0",
|
||||||
|
"eslint-config-expo": "~57.0.2",
|
||||||
|
"typescript": "~6.0.3"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"start": "expo start",
|
||||||
|
"android": "expo run:android",
|
||||||
|
"ios": "expo run:ios",
|
||||||
|
"web": "expo start --web",
|
||||||
|
"lint": "expo lint"
|
||||||
|
},
|
||||||
|
"private": true
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import '@/lib/api';
|
||||||
|
import { BagelFatOne_400Regular } from '@expo-google-fonts/bagel-fat-one';
|
||||||
|
import { GowunBatang_400Regular } from '@expo-google-fonts/gowun-batang';
|
||||||
|
import { Jua_400Regular, useFonts } from '@expo-google-fonts/jua';
|
||||||
|
import { QueryClientProvider } from '@tanstack/react-query';
|
||||||
|
import { Tabs } from 'expo-router/tabs';
|
||||||
|
import * as SplashScreen from 'expo-splash-screen';
|
||||||
|
import { StatusBar } from 'expo-status-bar';
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
import { View } from 'react-native';
|
||||||
|
|
||||||
|
import '@/global.css';
|
||||||
|
import { SkyBg } from '@/components/sky-bg';
|
||||||
|
import { TabBar } from '@/components/tab-bar';
|
||||||
|
import { FirstLoad } from '@/components/first-load';
|
||||||
|
import { SheetProvider } from '@/components/sheets';
|
||||||
|
import { TopBar } from '@/components/top-bar';
|
||||||
|
import { AuthProvider } from '@/lib/auth';
|
||||||
|
import { queryClient } from '@/lib/query-client';
|
||||||
|
import { RegionProvider } from '@/lib/region';
|
||||||
|
import { SkyProvider, useSky } from '@/lib/sky';
|
||||||
|
|
||||||
|
SplashScreen.preventAutoHideAsync();
|
||||||
|
|
||||||
|
function Shell() {
|
||||||
|
const { kind } = useSky();
|
||||||
|
return (
|
||||||
|
<View className="flex-1">
|
||||||
|
<SkyBg />
|
||||||
|
<StatusBar style={kind === 'night' ? 'light' : 'dark'} />
|
||||||
|
<Tabs initialRouteName="index" tabBar={(props) => <TabBar {...props} />} screenOptions={{ header: () => <TopBar />, sceneStyle: { backgroundColor: 'transparent' } }}>
|
||||||
|
{/* 메인인 오늘 탭을 가운데에 */}
|
||||||
|
<Tabs.Screen name="sky" />
|
||||||
|
<Tabs.Screen name="gak" />
|
||||||
|
<Tabs.Screen name="index" />
|
||||||
|
<Tabs.Screen name="week" />
|
||||||
|
<Tabs.Screen name="season" />
|
||||||
|
</Tabs>
|
||||||
|
<FirstLoad />
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function RootLayout() {
|
||||||
|
const [loaded, error] = useFonts({ Jua_400Regular, BagelFatOne_400Regular, GowunBatang_400Regular });
|
||||||
|
useEffect(() => {
|
||||||
|
if (loaded || error) SplashScreen.hideAsync();
|
||||||
|
}, [loaded, error]);
|
||||||
|
if (!loaded && !error) return null;
|
||||||
|
return (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<SkyProvider>
|
||||||
|
<AuthProvider>
|
||||||
|
<RegionProvider>
|
||||||
|
<SheetProvider>
|
||||||
|
<Shell />
|
||||||
|
</SheetProvider>
|
||||||
|
</RegionProvider>
|
||||||
|
</AuthProvider>
|
||||||
|
</SkyProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { listArticlesOptions, listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import { ArticleCategory, IndexCategory } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { kst, loadOf, seasonOf } from '@nalssigak/shared/lib';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Pressable, RefreshControl, ScrollView, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
|
||||||
|
import { GakGrid, GridSkel } from '@/components/gak/grid';
|
||||||
|
import { Podium, PodiumSkel } from '@/components/gak/podium';
|
||||||
|
import { Chips, Ic, Sec, StateBox } from '@/components/ui';
|
||||||
|
import { useRegion } from '@/lib/region';
|
||||||
|
import { useSheet } from '@/lib/sheet';
|
||||||
|
|
||||||
|
type Cat = 'all' | 'out' | 'food' | 'home' | 'life' | 'core';
|
||||||
|
|
||||||
|
// 마지막 칩은 지금 계절의 제철 각 (예: 가을 각)
|
||||||
|
const CATS: readonly (readonly [Cat, string])[] = [
|
||||||
|
['all', '전체'],
|
||||||
|
['out', '밖에서 놀기'],
|
||||||
|
['food', '먹고 마시기'],
|
||||||
|
['home', '집안일'],
|
||||||
|
['life', '생활 고민'],
|
||||||
|
['core', `${seasonOf(kst(new Date()).mo)[0]} 각`],
|
||||||
|
];
|
||||||
|
|
||||||
|
const CAT_PARAM: Partial<Record<Cat, IndexCategory>> = { out: IndexCategory.OUTSIDE, food: IndexCategory.FOOD, home: IndexCategory.HOME, life: IndexCategory.LIFE };
|
||||||
|
|
||||||
|
export default function GakScreen() {
|
||||||
|
const { region } = useRegion();
|
||||||
|
const { open } = useSheet();
|
||||||
|
const [cat, setCat] = useState<Cat>('all');
|
||||||
|
const q = useQuery(listIndicesOptions({ query: { region: region.code, category: CAT_PARAM[cat], core: cat === 'core' ? true : undefined } }));
|
||||||
|
const articles = useQuery(listArticlesOptions({ query: { category: ArticleCategory.GAK } }));
|
||||||
|
const top = q.data?.top3 ?? [];
|
||||||
|
const items = q.data?.items ?? [];
|
||||||
|
const day = q.data?.day?.split('-').map(Number);
|
||||||
|
const load = loadOf(q);
|
||||||
|
const howto = articles.data?.articles?.find((a) => a.code === 'howgak');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={q.isRefetching && !q.isPlaceholderData} onRefresh={() => q.refetch()} />}>
|
||||||
|
<Sec title="오늘 1~3위" sub={`${day ? `${day[1]}월 ${day[2]}일 기준 · ` : ''}${region.name}`} />
|
||||||
|
{top.length === 3 ? <Podium top={top} dim={q.isPlaceholderData} /> : load === 'loading' ? <PodiumSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="오늘 1~3위를 아직 못 정했어요." hold={<PodiumSkel />} />}
|
||||||
|
<Chips items={CATS} value={cat} onChange={setCat} />
|
||||||
|
{load === 'loading' ? (
|
||||||
|
<GridSkel />
|
||||||
|
) : !items.length ? (
|
||||||
|
// 실패 안내·다시 시도는 위 받침대 자리에 한 번만
|
||||||
|
<StateBox load="ready" empty={load === 'ready' ? '이 분야는 오늘 계산된 각이 없어요.' : '각 목록을 불러오지 못했어요.'} hold={<GridSkel />} boxClassName="inset-3" />
|
||||||
|
) : (
|
||||||
|
<GakGrid items={items} dim={q.isPlaceholderData} />
|
||||||
|
)}
|
||||||
|
{howto && load !== 'loading' && (
|
||||||
|
<Pressable onPress={() => open({ type: 'article', articleId: howto.article_id })} className="mx-3 mt-1.5 flex-row items-center gap-3 rounded-[22px] bg-[#ece7ff] p-3.5">
|
||||||
|
<Ic name="bulb" size={44} />
|
||||||
|
<View className="flex-1">
|
||||||
|
<Text className="font-jua text-[17px] text-[#28304a]">각 점수는 어떻게 매길까?</Text>
|
||||||
|
<Text className="text-[12.5px] font-semibold text-[#5a6380]">기온·비·바람·습도·공기·시간대 6가지로 계산해요</Text>
|
||||||
|
</View>
|
||||||
|
</Pressable>
|
||||||
|
)}
|
||||||
|
</ScrollView>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import { kst, loadOf } from '@nalssigak/shared/lib';
|
||||||
|
import { atSlot, PREVIEW } from '@nalssigak/shared/lib/today';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { Fragment, type ReactNode } from 'react';
|
||||||
|
import { RefreshControl, ScrollView } from 'react-native';
|
||||||
|
|
||||||
|
import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card';
|
||||||
|
import { Hero } from '@/components/today/hero';
|
||||||
|
import { EventsBand, SeasonBand, Stories, StoriesSkel, TopBand } from '@/components/today/rails';
|
||||||
|
import { Sec, StateBox } from '@/components/ui';
|
||||||
|
import { useRegion } from '@/lib/region';
|
||||||
|
import { useSky } from '@/lib/sky';
|
||||||
|
|
||||||
|
export default function TodayScreen() {
|
||||||
|
const { region } = useRegion();
|
||||||
|
const feed = useQuery(getFeedOptions({ query: { region: region.code } }));
|
||||||
|
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }));
|
||||||
|
const { preview } = useSky();
|
||||||
|
const f = feed.data;
|
||||||
|
const posts = (f?.posts ?? []).filter(isAppPost);
|
||||||
|
const stories = atSlot(f?.stories ?? [], preview);
|
||||||
|
const sloted = preview != null && stories !== f?.stories;
|
||||||
|
const bands = f?.bands;
|
||||||
|
const nowAt = f?.hero?.now_at;
|
||||||
|
const load = loadOf(feed);
|
||||||
|
const refresh = () => Promise.all([feed.refetch(), today.refetch()]);
|
||||||
|
|
||||||
|
// 웹처럼 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
|
||||||
|
const bandAt: [number, ReactNode][] = [
|
||||||
|
[3, bands?.events?.length ? <EventsBand events={bands.events} /> : null],
|
||||||
|
[6, bands?.top5?.length ? <TopBand items={sloted ? stories.filter((g) => g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
|
||||||
|
[9, bands?.season?.length ? <SeasonBand news={bands.season} /> : null],
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
// 지역마다 새로 그려 넘긴 슬라이드 위치가 남지 않게 한다
|
||||||
|
<ScrollView key={region.code} contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={feed.isRefetching && !feed.isPlaceholderData} onRefresh={refresh} />} style={{ opacity: feed.isPlaceholderData ? 0.6 : 1 }}>
|
||||||
|
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
|
||||||
|
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more="/gak" />
|
||||||
|
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} boxClassName="inset-x-3 top-3 bottom-1" />}
|
||||||
|
{load === 'loading' && (
|
||||||
|
<>
|
||||||
|
<PostCardSkel />
|
||||||
|
<PostCardSkel />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다. 다시 시도는 위 각 줄에 한 번만 */}
|
||||||
|
{load !== 'loading' && !posts.length && (
|
||||||
|
<StateBox
|
||||||
|
load="ready"
|
||||||
|
empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'}
|
||||||
|
hold={
|
||||||
|
<>
|
||||||
|
<PostCardSkel />
|
||||||
|
<PostCardSkel />
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
boxClassName="inset-x-3 top-3.5"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{posts.map((p, i) => (
|
||||||
|
<Fragment key={p.post_id}>
|
||||||
|
<PostCard post={p} />
|
||||||
|
{bandAt.find(([at]) => at === i + 1)?.[1]}
|
||||||
|
</Fragment>
|
||||||
|
))}
|
||||||
|
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
|
||||||
|
</ScrollView>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { getSeasonWeekOptions, listArticlesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import { ArticleCategory } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { loadOf } from '@nalssigak/shared/lib';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { RefreshControl, ScrollView, View } from 'react-native';
|
||||||
|
|
||||||
|
import { ArticleRow, HeadSkel, RowsSkel, SeasonHead } from '@/components/season/parts';
|
||||||
|
import { Chips, StateBox } from '@/components/ui';
|
||||||
|
import { useSheet } from '@/lib/sheet';
|
||||||
|
|
||||||
|
const CATS = [
|
||||||
|
['all', '전체'],
|
||||||
|
['season', '계절 소식'],
|
||||||
|
['tip', '날씨 상식'],
|
||||||
|
['gak', '각 원리'],
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const CAT_PARAM = { season: ArticleCategory.SEASON, tip: ArticleCategory.TIP, gak: ArticleCategory.GAK } as const;
|
||||||
|
|
||||||
|
export default function SeasonScreen() {
|
||||||
|
const { open } = useSheet();
|
||||||
|
const [cat, setCat] = useState<(typeof CATS)[number][0]>('all');
|
||||||
|
const week = useQuery(getSeasonWeekOptions());
|
||||||
|
const arts = useQuery(listArticlesOptions(cat === 'all' ? undefined : { query: { category: CAT_PARAM[cat] } }));
|
||||||
|
const w = week.data;
|
||||||
|
const list = arts.data?.articles ?? [];
|
||||||
|
const weekLoad = loadOf(week);
|
||||||
|
const artLoad = loadOf(arts);
|
||||||
|
const refresh = () => Promise.all([week.refetch(), arts.refetch()]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={(week.isRefetching || arts.isRefetching) && !arts.isPlaceholderData} onRefresh={refresh} />}>
|
||||||
|
{w?.headline ? <SeasonHead week={w} onPress={() => open({ type: 'seasonWeek' })} /> : weekLoad === 'loading' ? <HeadSkel /> : <StateBox load={weekLoad} onRetry={() => week.refetch()} empty="이번 주 특집이 아직 없어요." hold={<HeadSkel />} />}
|
||||||
|
<Chips items={CATS} value={cat} onChange={setCat} />
|
||||||
|
<View className="mt-1.5" style={{ opacity: arts.isPlaceholderData ? 0.6 : 1 }}>
|
||||||
|
{artLoad === 'loading' && <RowsSkel />}
|
||||||
|
{artLoad !== 'loading' && !list.length && <StateBox load={artLoad} onRetry={() => arts.refetch()} empty="읽을거리가 아직 없어요." hold={<RowsSkel />} boxClassName="inset-3" />}
|
||||||
|
{list.map((a) => (
|
||||||
|
<ArticleRow key={a.article_id} article={a} onPress={() => open({ type: 'article', articleId: a.article_id })} />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
</ScrollView>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import { getSkyOptions, getSkyRankingOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import { loadOf } from '@nalssigak/shared/lib';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { RefreshControl, ScrollView, View } from 'react-native';
|
||||||
|
|
||||||
|
import { DayTiles, Li, LiSkel, ScoreHelp, SkyHero, Timeline } from '@/components/sky/parts';
|
||||||
|
import { Sec, Skel, StateBox } from '@/components/ui';
|
||||||
|
import { useRegion } from '@/lib/region';
|
||||||
|
|
||||||
|
const THREE = [0, 1, 2];
|
||||||
|
const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i);
|
||||||
|
|
||||||
|
/** 히어로 글자 자리 (실패·빈 안내를 같은 높이로 띄우려고) */
|
||||||
|
function HeroHold() {
|
||||||
|
return (
|
||||||
|
<View>
|
||||||
|
<Skel className="h-7 w-[230px]" />
|
||||||
|
<Skel className="mt-2 w-[180px]" />
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LiSkels({ n }: { n: number[] }) {
|
||||||
|
return (
|
||||||
|
<View className="mx-3 mt-1.5">
|
||||||
|
{n.map((i) => (
|
||||||
|
<LiSkel key={i} last={i === n.length - 1} />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SkyScreen() {
|
||||||
|
const { region } = useRegion();
|
||||||
|
const sky = useQuery(getSkyOptions({ query: { region: region.code } }));
|
||||||
|
const ranking = useQuery(getSkyRankingOptions());
|
||||||
|
const load = loadOf(sky);
|
||||||
|
const rankLoad = loadOf(ranking);
|
||||||
|
const plans = sky.data?.plans ?? [];
|
||||||
|
const [picked, setPicked] = useState<string>();
|
||||||
|
// 타일을 누르면 그날, 아니면 다음에 오는 날
|
||||||
|
const plan = plans.find((p) => p.day === picked) ?? sky.data?.plan ?? undefined;
|
||||||
|
const spots = (sky.data?.spots ?? []).slice(0, 3);
|
||||||
|
const items = (ranking.data?.items ?? []).slice(0, 8);
|
||||||
|
const rise = plan?.kind === 'sunrise';
|
||||||
|
const refresh = () => Promise.all([sky.refetch(), ranking.refetch()]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={sky.isRefetching && !sky.isPlaceholderData} onRefresh={refresh} />} style={{ opacity: sky.isPlaceholderData ? 0.6 : 1 }}>
|
||||||
|
{plan || load === 'loading' ? (
|
||||||
|
<SkyHero plan={plan} />
|
||||||
|
) : (
|
||||||
|
<SkyHero>
|
||||||
|
<StateBox load={load} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." hold={<HeroHold />} boxClassName="inset-x-0 top-1.5 bottom-0" />
|
||||||
|
</SkyHero>
|
||||||
|
)}
|
||||||
|
{plans.length > 1 && <DayTiles plans={plans} day={plan?.day} onPick={setPicked} />}
|
||||||
|
{plan && <ScoreHelp plan={plan} />}
|
||||||
|
<Sec title="언제 보면 좋을까" />
|
||||||
|
{plan?.timeline?.length || load === 'loading' ? <Timeline rows={plan?.timeline} kind={plan?.kind} /> : <StateBox load="ready" empty={load === 'ready' ? '노을 시간 정보가 없어요.' : '노을 시간을 불러오지 못했어요.'} hold={<Timeline />} />}
|
||||||
|
{!rise && <Sec title="가까운 노을 명소" sub="가까운 순 · 방향은 내 동네에서 본 쪽" />}
|
||||||
|
{rise ? null : spots.length ? (
|
||||||
|
<View className="mx-3 mt-1.5">
|
||||||
|
{spots.map((p, i) => (
|
||||||
|
<Li key={p.no} no={p.no} title={p.name} sub={p.direction ? `${p.direction}쪽` : null} right={`${p.distance_km}km`} place={p.name} last={i === 2} />
|
||||||
|
))}
|
||||||
|
{/* 3곳이 안 되면 빈 줄로 높이를 지켜 아래 순위가 밀리지 않게 */}
|
||||||
|
{THREE.slice(spots.length).map((i) => (
|
||||||
|
<LiSkel key={`ghost-${i}`} ghost last={i === 2} />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
) : load === 'loading' ? (
|
||||||
|
<View className="mx-3 mt-1.5">
|
||||||
|
{THREE.map((i) => (
|
||||||
|
<LiSkel key={i} last={i === 2} />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
) : (
|
||||||
|
// 실패 안내·다시 시도는 위 히어로에 한 번만
|
||||||
|
<StateBox load="ready" empty={load === 'ready' ? '근처에 등록된 노을 명소가 없어요.' : '명소 정보를 불러오지 못했어요.'} hold={<LiSkels n={THREE} />} />
|
||||||
|
)}
|
||||||
|
<Sec title="전국 노을 순위" sub={ranking.data?.summary ?? '오늘 기준'} />
|
||||||
|
{items.length ? (
|
||||||
|
<View className="mx-3 mt-1.5">
|
||||||
|
{items.map((r, i) => (
|
||||||
|
<Li key={r.region_code} no={r.rank} title={r.name} sub={[r.note, r.situation_label].filter(Boolean).join(' · ')} right={`${r.score}점`} mine={r.region_code === region.code} last={i === items.length - 1} />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
) : rankLoad === 'loading' ? (
|
||||||
|
<View className="mx-3 mt-1.5">
|
||||||
|
{RANK_SKELS.map((i) => (
|
||||||
|
<LiSkel key={i} last={i === RANK_SKELS.length - 1} />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
) : (
|
||||||
|
<StateBox load={rankLoad} onRetry={() => ranking.refetch()} empty="순위가 아직 없어요." hold={<LiSkels n={RANK_SKELS} />} boxClassName="inset-x-3 top-1.5 bottom-0" />
|
||||||
|
)}
|
||||||
|
</ScrollView>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import { loadOf, shortDay } from '@nalssigak/shared/lib';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useRef, useState } from 'react';
|
||||||
|
import { Pressable, RefreshControl, ScrollView, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
|
||||||
|
import { DayStrip, EventRow, PickCard, PlaceCard, RankRow } from '@/components/week/sections';
|
||||||
|
import { DaysSkel, EventsSkel, PickSkel, PlacesSkel, RankSkel } from '@/components/week/skels';
|
||||||
|
import { Chips, Rail, Sec, Skel, StateBox } from '@/components/ui';
|
||||||
|
import { useRegion } from '@/lib/region';
|
||||||
|
import { shareView } from '@/lib/share-image';
|
||||||
|
import { SITE_URL } from '@/lib/site';
|
||||||
|
|
||||||
|
// 불러오는 동안에도 탭 줄 높이를 지키려고 같은 칩을 미리 그린다
|
||||||
|
const RANK_TABS_HOLD = [
|
||||||
|
['토', '토요일'],
|
||||||
|
['일', '일요일'],
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export default function WeekScreen() {
|
||||||
|
const { region } = useRegion();
|
||||||
|
const week = useQuery(getWeekOptions({ query: { region: region.code } }));
|
||||||
|
const days = week.data?.days ?? [];
|
||||||
|
const [picked, setPicked] = useState<string | null>(null);
|
||||||
|
// 지역을 바꾸면 동네 고르기는 전체로 돌아간다
|
||||||
|
const [areaPick, setAreaPick] = useState({ region: region.code, area: '전체' });
|
||||||
|
const area = areaPick.region === region.code ? areaPick.area : '전체';
|
||||||
|
// 처음에는 이번 토요일을 고른다
|
||||||
|
const sel = days.find((d) => d.day === picked) ?? days.find((d) => d.weekday === '토') ?? days[0];
|
||||||
|
const places = useQuery({ ...listPlacesOptions({ query: { region: region.code, day: sel?.day, area: area === '전체' ? undefined : area } }), enabled: !!sel });
|
||||||
|
const events = useQuery(listEventsOptions({ query: { region: region.code } }));
|
||||||
|
const ranking = useQuery(getWeekRankingOptions());
|
||||||
|
const rankDays = ranking.data?.days ?? [];
|
||||||
|
const [rankPick, setRankPick] = useState<string | null>(null);
|
||||||
|
const rankDay = rankDays.find((d) => d.day === rankPick) ?? rankDays[0];
|
||||||
|
const rankItems = (rankDay?.items ?? []).slice(0, 10);
|
||||||
|
const rankLoad = loadOf(ranking);
|
||||||
|
const areas = places.data?.areas ?? [];
|
||||||
|
const rainy = places.data?.rainy ?? sel?.is_rainy;
|
||||||
|
const placeList = places.data?.places ?? [];
|
||||||
|
const eventList = events.data?.events ?? [];
|
||||||
|
const weekLoad = loadOf(week);
|
||||||
|
const eventLoad = loadOf(events);
|
||||||
|
// 날씨(고른 날)가 와야 명소를 부를 수 있다
|
||||||
|
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready';
|
||||||
|
const refresh = () => Promise.all([week.refetch(), events.refetch(), ranking.refetch(), sel ? places.refetch() : null]);
|
||||||
|
|
||||||
|
const pickShot = useRef<View>(null);
|
||||||
|
// 고른 날 추천 카드를 이미지로
|
||||||
|
const sendPlan = () => {
|
||||||
|
if (!sel) return;
|
||||||
|
const message = [`${sel.weekday}요일 일정 · ${region.name}`, sel.headline, sel.summary, sel.pick, `날씨각 ${SITE_URL}`].filter(Boolean).join('\n');
|
||||||
|
void shareView(pickShot, { title: `${sel.weekday}요일 일정`, message });
|
||||||
|
};
|
||||||
|
|
||||||
|
const placeSub = sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? undefined : '날씨에 맞춰 골라 보여 줘요';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScrollView key={region.code} contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={week.isRefetching && !week.isPlaceholderData} onRefresh={refresh} />}>
|
||||||
|
<Sec title="열흘 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
|
||||||
|
{days.length ? (
|
||||||
|
<DayStrip days={days} selected={sel?.day} onPick={setPicked} dim={week.isPlaceholderData} />
|
||||||
|
) : weekLoad === 'loading' ? (
|
||||||
|
<>
|
||||||
|
<DaysSkel />
|
||||||
|
<PickSkel />
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<StateBox
|
||||||
|
load={weekLoad}
|
||||||
|
onRetry={() => week.refetch()}
|
||||||
|
empty="날씨가 아직 없어요."
|
||||||
|
hold={
|
||||||
|
<>
|
||||||
|
<DaysSkel />
|
||||||
|
<PickSkel />
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{sel && (
|
||||||
|
<View ref={pickShot} collapsable={false}>
|
||||||
|
<PickCard day={sel} />
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
{(sel || weekLoad !== 'ready') && (
|
||||||
|
<>
|
||||||
|
<Text className="mx-4 mt-3.5 text-[13.5px] font-bold text-ink2">30km 안 · 데이트 명소</Text>
|
||||||
|
<Chips items={['전체', ...areas].map((a) => [a, a] as const)} value={area} onChange={(a) => setAreaPick({ region: region.code, area: a })} disabled={!areas.length} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{/* 명소 데이터가 없으면 칸 전체를 숨긴다 */}
|
||||||
|
{!(placeLoad === 'ready' && !placeList.length) && (
|
||||||
|
<>
|
||||||
|
<View className="-mt-2.5">
|
||||||
|
<Sec title="날씨 맞춤 데이트 명소" sub={placeSub} />
|
||||||
|
</View>
|
||||||
|
{!placeSub && <Skel className="mx-4 w-56" />}
|
||||||
|
{placeList.length ? (
|
||||||
|
<View style={{ opacity: places.isPlaceholderData ? 0.6 : 1 }}>
|
||||||
|
<Rail>
|
||||||
|
{placeList.map((p, i) => (
|
||||||
|
<PlaceCard key={p.place_id} place={p} index={i} />
|
||||||
|
))}
|
||||||
|
</Rail>
|
||||||
|
</View>
|
||||||
|
) : placeLoad === 'loading' ? (
|
||||||
|
<PlacesSkel />
|
||||||
|
) : (
|
||||||
|
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? '30km 안에 데이트 명소가 아직 없어요.' : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} />
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Sec title="이번 주말 전국 날씨 순위" sub="낮 10~17시 나들이 날씨 · 대표 지역 30곳 중 10위까지" />
|
||||||
|
{rankDays.length ? (
|
||||||
|
<Chips items={rankDays.map((d) => [d.day, `${d.weekday}요일 ${shortDay(d.day)}`] as const)} value={rankDay?.day ?? ''} onChange={setRankPick} />
|
||||||
|
) : (
|
||||||
|
<Chips items={RANK_TABS_HOLD} value="토" onChange={() => undefined} disabled />
|
||||||
|
)}
|
||||||
|
{rankItems.length ? (
|
||||||
|
<View className="mx-3 mt-1.5" style={{ opacity: ranking.isPlaceholderData ? 0.6 : 1 }}>
|
||||||
|
{rankItems.map((r) => (
|
||||||
|
<RankRow key={r.region_code} item={r} mine={r.region_code === region.code} />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
) : rankLoad === 'loading' ? (
|
||||||
|
<RankSkel />
|
||||||
|
) : (
|
||||||
|
<StateBox load={rankLoad} onRetry={() => ranking.refetch()} empty="주말 예보가 아직 없어요." hold={<RankSkel />} boxClassName="inset-x-3 top-1.5 bottom-0" />
|
||||||
|
)}
|
||||||
|
<Sec title="가까운 축제·행사" sub="30km 안 · 앞으로 30일 · 그날 날씨까지 같이 봐요" />
|
||||||
|
{eventList.length ? (
|
||||||
|
<View style={{ opacity: events.isPlaceholderData ? 0.6 : 1 }}>
|
||||||
|
{eventList.map((e, i) => (
|
||||||
|
<EventRow key={e.event_id} event={e} index={i} />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
) : eventLoad === 'loading' ? (
|
||||||
|
<EventsSkel />
|
||||||
|
) : (
|
||||||
|
<StateBox load={eventLoad} onRetry={() => events.refetch()} empty="30km 안에 열리는 행사가 아직 없어요. 다른 지역을 골라 보세요." hold={<EventsSkel />} boxClassName="inset-x-3 top-2.5 bottom-0" />
|
||||||
|
)}
|
||||||
|
{/* 행사 수가 정해진 뒤에 붙여 목록이 늘어날 때 밀리지 않게 */}
|
||||||
|
{eventLoad !== 'loading' && (
|
||||||
|
<Pressable onPress={sendPlan} disabled={!sel} className="mx-3 mt-4 items-center rounded-full border-b-[5px] border-orange-deep bg-orange p-[13px] disabled:opacity-60">
|
||||||
|
<Text className="font-jua text-[17px] text-white">이번 주말 일정 보내기</Text>
|
||||||
|
</Pressable>
|
||||||
|
)}
|
||||||
|
</ScrollView>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { useEffect, type ReactNode } from 'react';
|
||||||
|
import type { ViewStyle } from 'react-native';
|
||||||
|
import Animated, { cancelAnimation, Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
|
||||||
|
|
||||||
|
/** 하늘에서 떨어진 뒤 둥둥 (웹 b-fall: b-drop 1.05초 뒤 b-float 무한). d·f 는 밀리초 */
|
||||||
|
export function Fall({ d, f, amp = 9, style, children }: { d: number; f: number; amp?: number; style?: ViewStyle; children: ReactNode }) {
|
||||||
|
const reduce = useReducedMotion();
|
||||||
|
const drop = useSharedValue(reduce ? 1 : 0);
|
||||||
|
const float = useSharedValue(0);
|
||||||
|
useEffect(() => {
|
||||||
|
if (reduce) return;
|
||||||
|
drop.value = withDelay(d, withTiming(1, { duration: 1050, easing: Easing.bezier(0.22, 0.9, 0.3, 1) }));
|
||||||
|
float.value = withDelay(d + 1050, withRepeat(withTiming(1, { duration: f / 2, easing: Easing.inOut(Easing.ease) }), -1, true));
|
||||||
|
return () => {
|
||||||
|
cancelAnimation(drop);
|
||||||
|
cancelAnimation(float);
|
||||||
|
};
|
||||||
|
}, [reduce, d, f, drop, float]);
|
||||||
|
const anim = useAnimatedStyle(() => {
|
||||||
|
const p = drop.value;
|
||||||
|
const y = interpolate(p, [0, 0.72, 0.86, 1], [-400, 0, -10, 0]) - amp * float.value;
|
||||||
|
const rot = interpolate(p, [0, 0.72, 1], [-10, 2, 0]) + 1.2 * float.value;
|
||||||
|
return {
|
||||||
|
opacity: interpolate(p, [0, 0.55, 1], [0, 1, 1]),
|
||||||
|
transform: [{ translateY: y }, { rotate: `${rot}deg` }, { scaleX: interpolate(p, [0, 0.72, 0.86, 1], [1, 1.04, 1, 1]) }, { scaleY: interpolate(p, [0, 0.72, 0.86, 1], [1, 0.96, 1, 1]) }],
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return <Animated.View style={[style, anim]}>{children}</Animated.View>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import type { TimeKind } from '@nalssigak/shared/lib';
|
||||||
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { StyleSheet, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withRepeat, withSequence, withTiming } from 'react-native-reanimated';
|
||||||
|
|
||||||
|
import { Ic } from '@/components/ui';
|
||||||
|
import { useSky } from '@/lib/sky';
|
||||||
|
|
||||||
|
// 덮개 색: 시간대별 하늘 맨 위 색을 반쯤 비치게
|
||||||
|
const COVER: Record<TimeKind, string> = {
|
||||||
|
morning: 'rgb(255 230 207 / 0.72)',
|
||||||
|
day: 'rgb(214 235 255 / 0.72)',
|
||||||
|
sunset: 'rgb(255 216 194 / 0.72)',
|
||||||
|
night: 'rgb(14 20 51 / 0.72)',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 캐릭터가 통통 뛴다 (웹 b-hop) */
|
||||||
|
function Hop({ name }: { name: string }) {
|
||||||
|
const reduce = useReducedMotion();
|
||||||
|
const t = useSharedValue(0);
|
||||||
|
useEffect(() => {
|
||||||
|
if (reduce) return;
|
||||||
|
const ease = Easing.bezier(0.3, 0, 0.4, 1);
|
||||||
|
t.value = withRepeat(withSequence(withTiming(1, { duration: 405, easing: ease }), withTiming(0, { duration: 495, easing: ease })), -1);
|
||||||
|
return () => cancelAnimation(t);
|
||||||
|
}, [reduce, t]);
|
||||||
|
const style = useAnimatedStyle(() => ({
|
||||||
|
transform: [{ translateY: -22 * t.value }, { scaleX: 1.06 - 0.09 * t.value }, { scaleY: 0.94 + 0.09 * t.value }],
|
||||||
|
transformOrigin: 'bottom',
|
||||||
|
}));
|
||||||
|
return (
|
||||||
|
<Animated.View style={style}>
|
||||||
|
<Ic name={name} size={88} />
|
||||||
|
</Animated.View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 처음 들어올 때만: 첫 데이터를 다 받을 때까지 하늘 위에 캐릭터와 '날씨 불러오는 중…'. 한 번 사라지면 다시 안 뜬다 */
|
||||||
|
export function FirstLoad() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { kind } = useSky();
|
||||||
|
const [done, setDone] = useState(false);
|
||||||
|
const [gone, setGone] = useState(false);
|
||||||
|
// 받기 시작했다가 받는 게 없어지면 끝. 느린 망에서도 10초 넘게 막지 않는다 (그 뒤는 화면 안 스켈레톤이 맡는다)
|
||||||
|
useEffect(() => {
|
||||||
|
let seen = false;
|
||||||
|
const unsubscribe = queryClient.getQueryCache().subscribe(() => {
|
||||||
|
if (queryClient.isFetching() > 0) seen = true;
|
||||||
|
else if (seen) setDone(true);
|
||||||
|
});
|
||||||
|
const id = setTimeout(() => setDone(true), 10000);
|
||||||
|
return () => {
|
||||||
|
unsubscribe();
|
||||||
|
clearTimeout(id);
|
||||||
|
};
|
||||||
|
}, [queryClient]);
|
||||||
|
const shown = useSharedValue(1);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!done) return;
|
||||||
|
shown.value = withTiming(0, { duration: 400 });
|
||||||
|
const id = setTimeout(() => setGone(true), 400);
|
||||||
|
return () => clearTimeout(id);
|
||||||
|
}, [done, shown]);
|
||||||
|
const fade = useAnimatedStyle(() => ({ opacity: shown.value }));
|
||||||
|
if (gone) return null;
|
||||||
|
return (
|
||||||
|
<Animated.View pointerEvents={done ? 'none' : 'auto'} accessibilityRole="progressbar" accessibilityLabel="날씨 불러오는 중" style={[StyleSheet.absoluteFill, { zIndex: 50, backgroundColor: COVER[kind] }, fade]}>
|
||||||
|
<View className="flex-1 items-center justify-center gap-3">
|
||||||
|
<Hop name={kind === 'night' ? 'bear' : 'rabbit'} />
|
||||||
|
<Text className="font-jua text-[19px] text-ink">날씨 불러오는 중…</Text>
|
||||||
|
</View>
|
||||||
|
</Animated.View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import type { IndexSummary } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { Pressable, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
|
||||||
|
import { Ic, Skel } from '@/components/ui';
|
||||||
|
import { useSheet } from '@/lib/sheet';
|
||||||
|
|
||||||
|
const CELL = 'w-[32%] items-center rounded-[22px] border-b-[5px] border-shade bg-card px-1.5 pt-3 pb-2.5';
|
||||||
|
const SKELS = Array.from({ length: 9 }, (_, i) => i);
|
||||||
|
|
||||||
|
export function GridSkel() {
|
||||||
|
return (
|
||||||
|
<View className="flex-row flex-wrap justify-between gap-y-2 p-3">
|
||||||
|
{SKELS.map((i) => (
|
||||||
|
<View key={i} className={`${CELL} gap-1.5`}>
|
||||||
|
<View className="size-[50px] rounded-full bg-skel" />
|
||||||
|
<Skel className="w-14" />
|
||||||
|
<Skel className="h-5 w-8" />
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 3칸 바둑판. 지금 시간대가 아니거나 제철이 아닌 각은 흐리게 */
|
||||||
|
export function GakGrid({ items, dim }: { items: IndexSummary[]; dim: boolean }) {
|
||||||
|
const { open } = useSheet();
|
||||||
|
return (
|
||||||
|
<View className="flex-row flex-wrap gap-y-2 p-3" style={{ columnGap: '2%', opacity: dim ? 0.6 : 1 }}>
|
||||||
|
{items.map((g) => (
|
||||||
|
<Pressable
|
||||||
|
key={g.index_id}
|
||||||
|
onPress={() => open({ type: 'gak', indexId: g.index_id })}
|
||||||
|
accessibilityLabel={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, ${g.in_season === false ? '제철 아님' : '지금 시간대 아님'}`}
|
||||||
|
className={`${CELL} ${g.active ? '' : 'opacity-55'}`}
|
||||||
|
>
|
||||||
|
{g.active && <Text className="absolute top-[7px] left-[9px] font-jua text-[13px] text-ink3">{g.rank}</Text>}
|
||||||
|
{g.season && <Text className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">{g.season}</Text>}
|
||||||
|
<Ic name={g.icon} size={50} />
|
||||||
|
<Text numberOfLines={1} className="mt-1 font-jua text-[15px] text-ink">
|
||||||
|
{g.name}
|
||||||
|
</Text>
|
||||||
|
{g.active ? (
|
||||||
|
<Text className={`font-bagel text-[22px] leading-[24px] ${g.score < 50 ? 'text-ink3' : 'text-orange'}`}>{g.score}</Text>
|
||||||
|
) : (
|
||||||
|
<Text className="py-1 text-[12px] leading-[14px] font-extrabold text-ink3">{g.in_season === false ? '제철 아님' : '지금 아님'}</Text>
|
||||||
|
)}
|
||||||
|
</Pressable>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import type { IndexSummary } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { MEDALS } from '@nalssigak/shared/lib';
|
||||||
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
|
import { Pressable, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
|
||||||
|
import { Ic, Skel } from '@/components/ui';
|
||||||
|
import { useSheet } from '@/lib/sheet';
|
||||||
|
import { useSky } from '@/lib/sky';
|
||||||
|
|
||||||
|
// 가운데가 높은 3칸: 2위 · 1위 · 3위
|
||||||
|
const ORDER = [1, 0, 2] as const;
|
||||||
|
const FLEX = [1.15, 1, 1];
|
||||||
|
|
||||||
|
/** 1~3위 받침대와 같은 칸의 스켈레톤 */
|
||||||
|
export function PodiumSkel() {
|
||||||
|
return (
|
||||||
|
<View className="flex-row gap-1.5 px-3 pt-3">
|
||||||
|
{ORDER.map((k) => (
|
||||||
|
<View key={k} style={{ flex: FLEX[k] }} className={`items-center gap-1.5 rounded-3xl border-b-[6px] border-shade bg-card px-1.5 ${k === 0 ? 'py-4' : 'mt-6 py-3'}`}>
|
||||||
|
<View className={`aspect-square rounded-full bg-skel ${k === 0 ? 'w-20' : 'w-[62px]'}`} />
|
||||||
|
<Skel className="w-16" />
|
||||||
|
<Skel className="h-6 w-10" />
|
||||||
|
<Skel className="w-full" />
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Podium({ top, dim }: { top: IndexSummary[]; dim: boolean }) {
|
||||||
|
const { open } = useSheet();
|
||||||
|
const { kind } = useSky();
|
||||||
|
return (
|
||||||
|
<View className="flex-row gap-1.5 px-3 pt-3" style={{ opacity: dim ? 0.6 : 1 }}>
|
||||||
|
{ORDER.map((k) => {
|
||||||
|
const g = top[k];
|
||||||
|
return (
|
||||||
|
<Pressable key={g.index_id} style={{ flex: FLEX[k] }} onPress={() => open({ type: 'gak', indexId: g.index_id })} className={`items-center overflow-hidden rounded-3xl border-b-[6px] border-shade bg-card px-1.5 ${k === 0 ? 'py-4' : 'mt-6 py-3'}`}>
|
||||||
|
{k === 0 && kind !== 'night' && <LinearGradient colors={['#fff1c4', '#ffffff']} style={{ position: 'absolute', inset: 0 }} />}
|
||||||
|
<View>
|
||||||
|
<Ic name={g.icon} size={k === 0 ? 80 : 62} />
|
||||||
|
<Ic name={MEDALS[k]} size={28} style={{ position: 'absolute', top: -6, left: -12 }} />
|
||||||
|
</View>
|
||||||
|
<View className="mt-1.5 flex-1 justify-center">
|
||||||
|
<Text className="text-center font-jua text-base text-ink">
|
||||||
|
{k + 1}위 {g.name}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<Text className="font-bagel text-[30px] leading-[32px] text-orange">{g.score}</Text>
|
||||||
|
{g.summary && <Text className="text-center text-[11.5px] font-semibold text-ink2">{g.summary}</Text>}
|
||||||
|
</Pressable>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import Svg, { Path } from 'react-native-svg';
|
||||||
|
|
||||||
|
export const HEART = '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';
|
||||||
|
|
||||||
|
type P = { size: number; color: string };
|
||||||
|
|
||||||
|
export function HeartIcon({ size, color, filled }: P & { filled: boolean }) {
|
||||||
|
return (
|
||||||
|
<Svg viewBox="0 0 24 24" width={size} height={size} fill={filled ? color : 'none'} stroke={color} strokeWidth={1.9}>
|
||||||
|
<Path d={HEART} />
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CommentIcon({ size, color }: P) {
|
||||||
|
return (
|
||||||
|
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={1.9} strokeLinejoin="round">
|
||||||
|
<Path d="M20.5 12a8.5 8.5 0 0 1-12.6 7.4L3.5 20.5l1.2-4.2A8.5 8.5 0 1 1 20.5 12z" />
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SendIcon({ size, color }: P) {
|
||||||
|
return (
|
||||||
|
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
|
||||||
|
<Path d="M21 3 10 14M21 3l-6.5 18-4-7.5L3 9.5z" />
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
import { View } from 'react-native';
|
||||||
|
import Animated, { Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withTiming } from 'react-native-reanimated';
|
||||||
|
import Svg, { Path } from 'react-native-svg';
|
||||||
|
|
||||||
|
import { HEART } from '@/components/post/icons';
|
||||||
|
|
||||||
|
// 튀어 나가는 작은 하트: x·y 이동, 회전, 색 (웹 BURST)
|
||||||
|
const BURST: [number, number, number, string][] = [
|
||||||
|
[-86, -60, -24, '#ff3b5c'],
|
||||||
|
[84, -66, 22, '#ff8e4e'],
|
||||||
|
[-104, 18, -40, '#ffc86e'],
|
||||||
|
[102, 24, 36, '#ff3b5c'],
|
||||||
|
[-48, -104, -8, '#ff8aa0'],
|
||||||
|
[52, -100, 12, '#ffc86e'],
|
||||||
|
];
|
||||||
|
|
||||||
|
function Bit({ dx, dy, rot, color }: { dx: number; dy: number; rot: number; color: string }) {
|
||||||
|
const p = useSharedValue(0);
|
||||||
|
useEffect(() => {
|
||||||
|
p.value = withDelay(80, withTiming(1, { duration: 900, easing: Easing.bezier(0.2, 0.8, 0.3, 1) }));
|
||||||
|
}, [p]);
|
||||||
|
const style = useAnimatedStyle(() => ({
|
||||||
|
opacity: interpolate(p.value, [0, 0.25, 1], [0, 1, 0]),
|
||||||
|
transform: [{ translateX: dx * p.value }, { translateY: dy * p.value }, { scale: interpolate(p.value, [0, 1], [0.4, 1.1]) }, { rotate: `${rot * p.value}deg` }],
|
||||||
|
}));
|
||||||
|
return (
|
||||||
|
<Animated.View style={[{ position: 'absolute' }, style]}>
|
||||||
|
<Svg viewBox="0 0 24 24" width={20} height={20} fill={color}>
|
||||||
|
<Path d={HEART} />
|
||||||
|
</Svg>
|
||||||
|
</Animated.View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Toast() {
|
||||||
|
const p = useSharedValue(0);
|
||||||
|
useEffect(() => {
|
||||||
|
p.value = withTiming(1, { duration: 1300, easing: Easing.bezier(0.2, 0.9, 0.3, 1) });
|
||||||
|
}, [p]);
|
||||||
|
const style = useAnimatedStyle(() => ({
|
||||||
|
opacity: interpolate(p.value, [0, 0.18, 0.78, 1], [0, 1, 1, 0]),
|
||||||
|
transform: [{ translateY: interpolate(p.value, [0, 0.18, 0.78, 1], [14, 0, 0, -8]) }, { scale: interpolate(p.value, [0, 0.18, 0.3, 1], [0.85, 1.06, 1, 1]) }],
|
||||||
|
}));
|
||||||
|
return (
|
||||||
|
<Animated.View className="absolute top-[58%] rounded-full bg-white px-4 py-2" style={[{ boxShadow: '0 8px 18px rgb(40 48 74 / 0.18)' }, style]}>
|
||||||
|
<Animated.Text className="font-jua text-[17px] text-heart">좋아요했어요!</Animated.Text>
|
||||||
|
</Animated.View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 좋아요 때 하트 조각이 튀어 나가고 '좋아요했어요!' 가 떴다 사라진다 */
|
||||||
|
export function LikeBurst() {
|
||||||
|
const reduce = useReducedMotion();
|
||||||
|
if (reduce) return null;
|
||||||
|
return (
|
||||||
|
<View pointerEvents="none" className="absolute inset-0 items-center justify-center" accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
|
||||||
|
{BURST.map(([dx, dy, rot, color], k) => (
|
||||||
|
<Bit key={k} dx={dx} dy={dy} rot={rot} color={color} />
|
||||||
|
))}
|
||||||
|
<Toast />
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { ScrollView, View, type NativeScrollEvent, type NativeSyntheticEvent } from 'react-native';
|
||||||
|
|
||||||
|
/** 옆으로 한 장씩 넘기는 슬라이드 (웹 Embla 캐러셀 대신 가로 paging ScrollView) */
|
||||||
|
export function Pager({ width, height, onIndex, children }: { width: number; height: number; onIndex: (i: number) => void; children: ReactNode[] }) {
|
||||||
|
const onEnd = (e: NativeSyntheticEvent<NativeScrollEvent>) => onIndex(Math.round(e.nativeEvent.contentOffset.x / width));
|
||||||
|
return (
|
||||||
|
<ScrollView horizontal pagingEnabled showsHorizontalScrollIndicator={false} scrollEnabled={children.length > 1} onMomentumScrollEnd={onEnd} style={{ width, height }}>
|
||||||
|
{children.map((c, i) => (
|
||||||
|
<View key={i} style={{ width, height }}>
|
||||||
|
{c}
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</ScrollView>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 슬라이드 위치 점 */
|
||||||
|
export function Dots({ n, index }: { n: number; index: number }) {
|
||||||
|
if (n < 2) return null;
|
||||||
|
const items = Array.from({ length: n }, (_, i) => i);
|
||||||
|
return (
|
||||||
|
<View className="flex-row justify-center gap-1.5 pt-2" accessibilityElementsHidden>
|
||||||
|
{items.map((i) => (
|
||||||
|
<View key={i} className={`h-1.5 rounded-full ${i === index ? 'w-4 bg-orange' : 'w-1.5 bg-ink3/40'}`} />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import { PostType, type PostData, type ResFeed } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query';
|
||||||
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { Animated, Pressable, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
import Svg, { Path } from 'react-native-svg';
|
||||||
|
import { useCSSVariable } from 'uniwind';
|
||||||
|
|
||||||
|
import { CommentIcon, HEART, HeartIcon, SendIcon } from '@/components/post/icons';
|
||||||
|
import { LikeBurst } from '@/components/post/like-burst';
|
||||||
|
import { Dots, Pager } from '@/components/post/pager';
|
||||||
|
import { slideBg, SlideView, type Slide } from '@/components/post/slides';
|
||||||
|
import { Ic, Skel } from '@/components/ui';
|
||||||
|
import { useAuth } from '@/lib/auth';
|
||||||
|
import { useSheet } from '@/lib/sheet';
|
||||||
|
import { shareView } from '@/lib/share-image';
|
||||||
|
import { SITE_URL } from '@/lib/site';
|
||||||
|
|
||||||
|
const ACCOUNTS: Partial<Record<PostType, readonly [string, string]>> = {
|
||||||
|
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
|
||||||
|
[PostType.GAK]: ['오늘의 각', 'rabbit'],
|
||||||
|
[PostType.SUNSET]: ['노을', 'sunset'],
|
||||||
|
[PostType.SEASON]: ['계절 소식', 'maple'],
|
||||||
|
[PostType.EVENT]: ['가까운 행사', 'fireworks'],
|
||||||
|
[PostType.TIP]: ['날씨 상식', 'bulb'],
|
||||||
|
[PostType.WEEK]: ['주말 예보', 'calendar'],
|
||||||
|
[PostType.ALERT]: ['생활 알림', 'umbrella'],
|
||||||
|
[PostType.TOMORROW]: ['내일 미리보기', 'moon'],
|
||||||
|
[PostType.QUOTE]: ['오늘의 한 문장', 'letter'],
|
||||||
|
[PostType.WEEKEND_PLAN]: ['주말 플랜', 'calendar'],
|
||||||
|
[PostType.AIR]: ['미세먼지', 'vent'],
|
||||||
|
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
|
||||||
|
[PostType.MOON]: ['오늘 밤 달', 'moon'],
|
||||||
|
[PostType.UV]: ['자외선', 'glasses'],
|
||||||
|
};
|
||||||
|
|
||||||
|
const isSlide = (s: PostData['slides'][number]): s is Slide => s.kind !== 'image';
|
||||||
|
|
||||||
|
/** 앱이 그릴 줄 아는 글만 (웹 전용 글 종류·이미지 슬라이드가 든 글은 뺀다) */
|
||||||
|
export const isAppPost = (p: PostData) => p.post_type in ACCOUNTS && p.slides.every(isSlide);
|
||||||
|
|
||||||
|
type PostProps = { post: PostData };
|
||||||
|
|
||||||
|
/** 받아 둔 피드 데이터에도 좋아요를 반영한다. 안 하면 다른 탭에 다녀왔을 때 예전 값으로 다시 그려진다 */
|
||||||
|
function patchFeed(queryClient: QueryClient, postId: number, patch: Partial<PostData>) {
|
||||||
|
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
|
||||||
|
feed?.posts ? { ...feed, posts: feed.posts.map((p) => (p.post_id === postId ? { ...p, ...patch } : p)) } : feed,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 한 줄 카드 (흐린 날 노을처럼 큰 그림이 필요 없는 소식) */
|
||||||
|
function LineCard({ post }: PostProps) {
|
||||||
|
const [account, avatar] = ACCOUNTS[post.post_type] ?? ['날씨각', 'sun'];
|
||||||
|
return (
|
||||||
|
<View className="mx-3 mt-3.5 flex-row items-center gap-3 rounded-[22px] border-b-4 border-shade bg-card px-4 py-3" accessibilityLabel={post.title}>
|
||||||
|
<Ic name={post.icon || avatar} size={40} />
|
||||||
|
<View className="flex-1">
|
||||||
|
<Text className="text-xs font-bold text-ink3">{account}</Text>
|
||||||
|
<Text className="text-sm text-ink2">
|
||||||
|
<Text className="font-jua text-base text-ink">{post.title}</Text> {post.caption}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */
|
||||||
|
export function PostCard({ post }: PostProps) {
|
||||||
|
return post.size === 'line' ? <LineCard post={post} /> : <FullCard post={post} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** FullCard 와 같은 틀(머리줄·4:5 그림·버튼줄·글 한 줄)의 스켈레톤 */
|
||||||
|
export function PostCardSkel() {
|
||||||
|
return (
|
||||||
|
<View className="mt-3.5 border-y border-line bg-card" accessibilityElementsHidden>
|
||||||
|
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
|
||||||
|
<View className="size-[34px] rounded-full bg-skel" />
|
||||||
|
<View className="gap-1.5">
|
||||||
|
<Skel className="w-12" />
|
||||||
|
<Skel className="w-16" />
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<View className="aspect-[4/5] bg-skel" />
|
||||||
|
<View className="flex-row gap-3.5 px-3 pt-2.5 pb-1">
|
||||||
|
<View className="size-7 rounded-full bg-skel" />
|
||||||
|
<View className="size-7 rounded-full bg-skel" />
|
||||||
|
<View className="size-7 rounded-full bg-skel" />
|
||||||
|
</View>
|
||||||
|
<View className="gap-2 px-3 pt-1 pb-3">
|
||||||
|
<Skel className="w-20" />
|
||||||
|
<Skel className="w-4/5" />
|
||||||
|
<Skel className="w-32" />
|
||||||
|
<Skel className="w-8" />
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 좋아요 때 가운데에 커졌다 사라지는 하트 */
|
||||||
|
function HeartPop() {
|
||||||
|
const [v] = useState(() => new Animated.Value(0));
|
||||||
|
useEffect(() => {
|
||||||
|
Animated.timing(v, { toValue: 1, duration: 800, useNativeDriver: true }).start();
|
||||||
|
}, [v]);
|
||||||
|
const opacity = v.interpolate({ inputRange: [0, 0.25, 0.6, 1], outputRange: [0, 1, 1, 0] });
|
||||||
|
const scale = v.interpolate({ inputRange: [0, 0.25, 0.6, 1], outputRange: [0.3, 1.1, 1, 1] });
|
||||||
|
return (
|
||||||
|
<Animated.View pointerEvents="none" className="absolute inset-0 items-center justify-center" style={{ opacity, transform: [{ scale }] }}>
|
||||||
|
<Svg viewBox="0 0 24 24" width={112} height={112} fill="#ff3b5c">
|
||||||
|
<Path d={HEART} />
|
||||||
|
</Svg>
|
||||||
|
</Animated.View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FullCard({ post }: PostProps) {
|
||||||
|
const { open } = useSheet();
|
||||||
|
const { loggedIn } = useAuth();
|
||||||
|
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
|
||||||
|
const liked = !!post.liked;
|
||||||
|
const likeCount = post.like_count;
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const like = useMutation(likePostMutation());
|
||||||
|
const unlike = useMutation(unlikePostMutation());
|
||||||
|
const [width, setWidth] = useState(0);
|
||||||
|
const [index, setIndex] = useState(0);
|
||||||
|
const [pop, setPop] = useState(0);
|
||||||
|
const [likeFailed, setLikeFailed] = useState(0);
|
||||||
|
const lastTap = useRef(0);
|
||||||
|
const [account, avatar] = ACCOUNTS[post.post_type] ?? ['날씨각', 'sun'];
|
||||||
|
const n = post.slides.length;
|
||||||
|
const patch = (values: Partial<PostData>) => patchFeed(queryClient, post.post_id, values);
|
||||||
|
const comments = () => open({ type: 'comments', postId: post.post_id });
|
||||||
|
const shot = useRef<View>(null);
|
||||||
|
// 지금 보고 있는 슬라이드를 이미지로
|
||||||
|
const share = () => void shareView(shot, { title: post.title, message: `${post.title} · 날씨각 ${SITE_URL}` });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!likeFailed) return;
|
||||||
|
const t = setTimeout(() => setLikeFailed(0), 2500);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [likeFailed]);
|
||||||
|
|
||||||
|
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
|
||||||
|
const setLike = (on: boolean) => {
|
||||||
|
if (!loggedIn) return open({ type: 'login' });
|
||||||
|
if (on === liked || like.isPending || unlike.isPending) return;
|
||||||
|
if (on) setPop((p) => p + 1);
|
||||||
|
setLikeFailed(0);
|
||||||
|
patch({ liked: on, like_count: likeCount + (on ? 1 : -1) });
|
||||||
|
const revert = () => {
|
||||||
|
patch({ liked, like_count: likeCount });
|
||||||
|
setLikeFailed(Date.now());
|
||||||
|
};
|
||||||
|
(on ? like : unlike).mutate(
|
||||||
|
{ path: { post_id: post.post_id } },
|
||||||
|
{
|
||||||
|
onSuccess: (res) => (res.result?.success ? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) }) : revert()),
|
||||||
|
onError: revert,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onTap = () => {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - lastTap.current < 320) {
|
||||||
|
if (liked && loggedIn) setPop((p) => p + 1);
|
||||||
|
else setLike(true);
|
||||||
|
}
|
||||||
|
lastTap.current = now;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={post.title}>
|
||||||
|
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
|
||||||
|
<View className="size-[34px] rounded-full p-0.5">
|
||||||
|
<LinearGradient colors={['#ff7a45', '#ffc86e', '#8fcaff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={{ position: 'absolute', inset: 0, borderRadius: 17 }} />
|
||||||
|
<View className="flex-1 items-center justify-center rounded-full bg-card">
|
||||||
|
<Ic name={avatar} size={22} />
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<View>
|
||||||
|
<Text className="text-sm leading-tight font-extrabold text-ink">날씨각</Text>
|
||||||
|
<Text className="text-xs font-semibold text-ink2">{account}</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<Pressable onPress={onTap} onLayout={(e) => setWidth(e.nativeEvent.layout.width)} className="aspect-[4/5] overflow-hidden" accessibilityLabel={n > 1 ? `슬라이드 ${n}장, 옆으로 넘겨 보세요` : undefined}>
|
||||||
|
<View ref={shot} collapsable={false}>
|
||||||
|
{width > 0 && (
|
||||||
|
<Pager width={width} height={(width * 5) / 4} onIndex={setIndex}>
|
||||||
|
{post.slides.filter(isSlide).map((s, i) => (
|
||||||
|
<SlideView key={i} slide={s} bg={slideBg(post, s)} />
|
||||||
|
))}
|
||||||
|
</Pager>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
{n > 1 && (
|
||||||
|
<View pointerEvents="none" className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px]">
|
||||||
|
<Text className="text-xs font-extrabold text-white">
|
||||||
|
{index + 1}/{n}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
{pop > 0 && <HeartPop key={pop} />}
|
||||||
|
{pop > 0 && <LikeBurst key={`b${pop}`} />}
|
||||||
|
{likeFailed > 0 && (
|
||||||
|
<View pointerEvents="none" className="absolute inset-x-0 bottom-4 items-center px-4" accessibilityRole="alert">
|
||||||
|
<Text className="overflow-hidden rounded-full bg-[rgb(30_36_56/0.82)] px-3.5 py-2 text-[13px] font-bold text-white">{liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요.</Text>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
</Pressable>
|
||||||
|
<Dots n={n} index={index} />
|
||||||
|
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
|
||||||
|
<Pressable onPress={() => setLike(!liked)} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요">
|
||||||
|
<HeartIcon size={26} color={liked ? heart : ink} filled={liked} />
|
||||||
|
</Pressable>
|
||||||
|
<Pressable onPress={comments} hitSlop={8} accessibilityRole="button" accessibilityLabel="댓글 보기">
|
||||||
|
<CommentIcon size={26} color={ink} />
|
||||||
|
</Pressable>
|
||||||
|
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="보내기">
|
||||||
|
<SendIcon size={26} color={ink} />
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
<Text className="px-3 py-0.5 text-sm font-extrabold text-ink">좋아요 {likeCount.toLocaleString()}개</Text>
|
||||||
|
<Text className="px-3 py-0.5 text-sm text-ink">
|
||||||
|
<Text className="font-extrabold">날씨각 </Text>
|
||||||
|
{post.caption}
|
||||||
|
</Text>
|
||||||
|
<Pressable onPress={comments}>
|
||||||
|
<Text className="px-3 pt-[3px] text-sm font-semibold text-ink3">{post.comment_count ? `댓글 ${post.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
|
||||||
|
</Pressable>
|
||||||
|
<Text className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-ink3">오늘</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
import type { GakSlide, HoursSlide, PlanSlide, PostData, RowsSlide, SunsetSlide, WeekSlide } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { PostType, SlotTone } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { cardBg, clockShort } from '@nalssigak/shared/lib';
|
||||||
|
import type { SlideBg } from '@nalssigak/shared/lib/types';
|
||||||
|
import { deg } from '@nalssigak/shared/lib/weatherText';
|
||||||
|
import { Image } from 'expo-image';
|
||||||
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { Pressable, StyleSheet, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
import Svg, { Polygon } from 'react-native-svg';
|
||||||
|
|
||||||
|
import { Credit, Ic, Rows, Thumb } from '@/components/ui';
|
||||||
|
import { CARD_BG } from '@/lib/colors';
|
||||||
|
import { useSheet } from '@/lib/sheet';
|
||||||
|
import { imageUri } from '@/lib/site';
|
||||||
|
import { useSky } from '@/lib/sky';
|
||||||
|
|
||||||
|
export type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide;
|
||||||
|
|
||||||
|
type Stops = readonly [string, string, ...string[]];
|
||||||
|
|
||||||
|
const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac'];
|
||||||
|
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac', glasses: 'butter' };
|
||||||
|
const DARK = new Set<SlideBg>(['dusk', 'night']);
|
||||||
|
|
||||||
|
const chunk = <T,>(items: T[], n: number) => Array.from({ length: Math.ceil(items.length / n) }, (_, i) => items.slice(i * n, i * n + n));
|
||||||
|
|
||||||
|
// 노을 하늘 상황(1 가려짐 2 낮은 구름 3 물들 구름 적음 4 넓게 물듦 5 두꺼움)별 하늘, 시간 칸 색 (웹 .b-sit-*, .b-cut-*)
|
||||||
|
const SIT_BG: Record<number, { colors: Stops; locations: readonly [number, number, ...number[]] }> = {
|
||||||
|
1: { colors: ['#6f7690', '#9aa0b4', '#b9b4c0'], locations: [0, 0.55, 1] },
|
||||||
|
2: { colors: ['#7a7f9c', '#a7a3bb', '#c9b8b8'], locations: [0, 0.55, 1] },
|
||||||
|
3: { colors: ['#4b5aa8', '#7f86c6', '#e9b9a8', '#ffb27a', '#ff8a4c'], locations: [0, 0.38, 0.68, 0.86, 1] },
|
||||||
|
4: { colors: ['#5b3f9e', '#c2559a', '#ff7a6a', '#ffb35c'], locations: [0, 0.4, 0.68, 1] },
|
||||||
|
5: { colors: ['#6a6aa0', '#a98fb4', '#e3b1a0'], locations: [0, 0.55, 1] },
|
||||||
|
};
|
||||||
|
const CUT_BG: Stops[] = [
|
||||||
|
['#9fd0ff', '#ffd79a', '#ff9a5c'],
|
||||||
|
['#8f7cf0', '#ff6f8e', '#ff8a4c'],
|
||||||
|
['#34306e', '#7a5cc8'],
|
||||||
|
];
|
||||||
|
// 건물 실루엣 (웹 .b-skyline clip-path)
|
||||||
|
const SKYLINE = '0,55 8,55 8,30 15,30 15,50 22,50 22,10 28,10 28,45 36,45 36,25 44,25 44,55 52,55 52,35 60,35 60,5 66,5 66,40 74,40 74,20 82,20 82,50 90,50 90,30 100,30 100,100 0,100';
|
||||||
|
|
||||||
|
const HOUR_TONE: Record<string, { bg: string; edge: string }> = {
|
||||||
|
[SlotTone.NIGHT]: { bg: '#e3e7ff', edge: '#c7cff5' },
|
||||||
|
[SlotTone.SUNSET]: { bg: '#ffe3d2', edge: '#ffc19f' },
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 배경색은 API에 없어 글 종류·아이콘으로 고른다 */
|
||||||
|
export function slideBg(post: PostData, slide: Slide): SlideBg {
|
||||||
|
if (slide.kind === 'hours') return 'sky';
|
||||||
|
if (slide.kind === 'sunset') return 'dusk';
|
||||||
|
if (slide.kind === 'week') return 'mint';
|
||||||
|
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter';
|
||||||
|
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.TIP) return 'sky';
|
||||||
|
if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac';
|
||||||
|
if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint';
|
||||||
|
return (ROW_ICON_BG[slide.icon] ?? cardBg(slide.icon, post.post_id)) as SlideBg;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Base({ colors, locations, children }: { colors: Stops; locations?: readonly [number, number, ...number[]]; children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<View className="flex-1 px-5 py-[22px]">
|
||||||
|
<LinearGradient colors={colors} locations={locations} style={StyleSheet.absoluteFill} />
|
||||||
|
{children}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Eyebrow({ children, light, className }: { children: ReactNode; light?: boolean; className?: string }) {
|
||||||
|
return <Text className={`text-[13px] font-extrabold opacity-75 ${light ? 'text-white' : 'text-ink'} ${className ?? ''}`}>{children}</Text>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Big({ children, light, className }: { children: ReactNode; light?: boolean; className?: string }) {
|
||||||
|
return <Text className={`mt-1.5 font-jua text-[29px] leading-tight ${light ? 'text-white' : 'text-ink'} ${className ?? ''}`}>{children}</Text>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Pic({ name, widthPct = 42 }: { name: string; widthPct?: number }) {
|
||||||
|
return (
|
||||||
|
<View pointerEvents="none" className="absolute top-[30%] right-3.5 aspect-square" style={{ width: `${widthPct}%` }}>
|
||||||
|
<Ic name={name} size={0} style={{ width: '100%', height: '100%' }} />
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||||
|
const { open } = useSheet();
|
||||||
|
const { kind } = useSky();
|
||||||
|
const palette = CARD_BG[kind === 'night' ? 'night' : 'day'];
|
||||||
|
const colors = palette[bg] ?? palette.sky;
|
||||||
|
const light = DARK.has(bg);
|
||||||
|
|
||||||
|
if (slide.kind === 'hours') {
|
||||||
|
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]));
|
||||||
|
const lo = Math.min(...temps);
|
||||||
|
const span = Math.max(...temps) - lo || 1;
|
||||||
|
return (
|
||||||
|
<Base colors={palette.sky}>
|
||||||
|
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||||
|
<Big>{slide.line}</Big>
|
||||||
|
{/* 웹 grid-cols-4: 4칸씩 줄을 나눈다 */}
|
||||||
|
<View className="mt-3.5 flex-1 gap-2">
|
||||||
|
{chunk(slide.hours, 4).map((row) => (
|
||||||
|
<View key={row[0].label} className="flex-1 flex-row gap-2">
|
||||||
|
{row.map((h) => {
|
||||||
|
const tone = HOUR_TONE[h.tone ?? ''];
|
||||||
|
return (
|
||||||
|
<View key={h.label} className={`flex-1 items-center justify-between overflow-hidden rounded-[18px] px-1 pt-2.5 pb-[9px] ${tone ? '' : 'border-b-[5px] border-shade bg-card'}`} style={tone ? { backgroundColor: tone.bg, borderBottomWidth: 5, borderColor: tone.edge } : undefined}>
|
||||||
|
{h.temp_c != null && <LinearGradient colors={['rgba(255,122,69,0.1)', 'rgba(255,122,69,0.34)']} style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: `${20 + ((h.temp_c - lo) / span) * 70}%` }} />}
|
||||||
|
<Text className={`text-xs font-bold ${tone ? 'text-[#5a6380]' : 'text-ink2'}`}>{h.label}</Text>
|
||||||
|
<Ic name={h.icon} size={34} />
|
||||||
|
<Text className={`font-bagel text-[21px] ${tone ? 'text-[#28304a]' : 'text-ink'}`}>{deg(h.temp_c)}</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{/* 마지막 줄이 모자라면 빈 칸으로 너비를 맞춘다 */}
|
||||||
|
{Array.from({ length: 4 - row.length }, (_, i) => (
|
||||||
|
<View key={`pad${i}`} className="flex-1" />
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
</Base>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (slide.kind === 'gak')
|
||||||
|
return (
|
||||||
|
<Base colors={colors}>
|
||||||
|
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
|
||||||
|
<Big>{slide.line}</Big>
|
||||||
|
<Pic name={slide.code} />
|
||||||
|
<Text className="mt-auto font-bagel text-[82px] leading-[82px] text-orange">{slide.score}</Text>
|
||||||
|
<Text className="font-jua text-[29px] leading-tight text-ink">{slide.name}</Text>
|
||||||
|
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
|
||||||
|
<Pressable onPress={() => open({ type: 'gak', indexId: slide.index_id })} className="mt-3 self-start rounded-full border-b-[5px] border-orange-deep bg-orange px-4 py-[9px]">
|
||||||
|
<Text className="font-jua text-[15px] text-white">계산 근거 보기</Text>
|
||||||
|
</Pressable>
|
||||||
|
</Base>
|
||||||
|
);
|
||||||
|
if (slide.kind === 'sunset') {
|
||||||
|
const sit = slide.situation ? SIT_BG[slide.situation] : undefined;
|
||||||
|
return (
|
||||||
|
<Base colors={sit?.colors ?? palette.dusk} locations={sit?.locations}>
|
||||||
|
<Eyebrow light>{slide.eyebrow}</Eyebrow>
|
||||||
|
{/* 노을 탭 히어로와 같은 순서: 결론 → 가장 붉을 때 → 쉬운 이유 */}
|
||||||
|
<Big light>{slide.headline ?? slide.grade_label}</Big>
|
||||||
|
{slide.line && <Text className="mt-0.5 font-jua text-[18px] text-white">{slide.line}</Text>}
|
||||||
|
<View className="mt-3 flex-1 gap-2">
|
||||||
|
{slide.cuts.map((c, i) => (
|
||||||
|
<View key={c.kind} className="flex-1 overflow-hidden rounded-2xl px-3 py-2">
|
||||||
|
<LinearGradient colors={CUT_BG[Math.min(i, 2)]} style={StyleSheet.absoluteFill} />
|
||||||
|
<Svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: '32%' }}>
|
||||||
|
<Polygon points={SKYLINE} fill="#2d2440" />
|
||||||
|
</Svg>
|
||||||
|
<Text className="font-bagel text-[21px] text-white">
|
||||||
|
{clockShort(c.at)}
|
||||||
|
<Text className="font-jua text-sm"> {c.label}</Text>
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
</Base>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (slide.kind === 'week')
|
||||||
|
return (
|
||||||
|
<Base colors={palette.mint}>
|
||||||
|
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||||
|
<Big>{slide.line}</Big>
|
||||||
|
{/* 칸은 제목 바로 아래, 팁만 맨 아래로 */}
|
||||||
|
<View className="mt-4 flex-row flex-wrap gap-2.5">
|
||||||
|
{slide.days.map((d) => (
|
||||||
|
<View key={d.day} className="grow basis-[45%] gap-0.5 rounded-[18px] border-b-[5px] border-shade bg-card/85 px-3 py-2.5">
|
||||||
|
<Ic name={d.icon} size={34} />
|
||||||
|
<Text className="font-jua text-lg text-ink">
|
||||||
|
{d.weekday} {d.day.split('-').slice(1).map(Number).join('.')}
|
||||||
|
</Text>
|
||||||
|
<Text className="font-jua text-[22px] text-ink">
|
||||||
|
<Text className="text-rain">{deg(d.temp_min_c)}</Text> → <Text className="text-orange">{deg(d.temp_max_c)}</Text>
|
||||||
|
</Text>
|
||||||
|
<Text className="text-xs font-bold text-ink2">
|
||||||
|
비 {d.rain_prob ?? '?'}%{d.temp_min_c != null && d.temp_max_c != null && ` · 일교차 ${Math.round(d.temp_max_c - d.temp_min_c)}°`}
|
||||||
|
</Text>
|
||||||
|
{d.gaks && d.gaks.length > 0 && (
|
||||||
|
<View className="mt-2 gap-1.5 border-t border-shade pt-2" accessibilityLabel={`${d.weekday}요일 대표 각`}>
|
||||||
|
<Text className="text-[11px] font-extrabold text-ink2">이날 할 만한 각</Text>
|
||||||
|
{d.gaks.map((g) => (
|
||||||
|
<View key={g.index_id} className="flex-row items-center gap-1.5">
|
||||||
|
<Ic name={g.icon} size={26} />
|
||||||
|
<Text numberOfLines={1} className="flex-1 text-[14px] font-bold text-ink">
|
||||||
|
{g.name}
|
||||||
|
</Text>
|
||||||
|
<Text className="font-bagel text-[16px] text-orange">{g.score}</Text>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
{slide.tip && <Text className="mt-auto overflow-hidden rounded-[14px] bg-ink-btn px-3 py-2.5 text-[13px] leading-snug font-bold text-white">{slide.tip}</Text>}
|
||||||
|
</Base>
|
||||||
|
);
|
||||||
|
if (slide.kind === 'plan') {
|
||||||
|
const credits = [...new Set(slide.steps.flatMap((st) => (st.image && st.image_credit ? [st.image_credit] : [])))];
|
||||||
|
return (
|
||||||
|
<Base colors={colors}>
|
||||||
|
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||||
|
<Big className="text-[24px]">{slide.line}</Big>
|
||||||
|
<View className="mt-auto gap-2">
|
||||||
|
{slide.steps.map((st, i) => (
|
||||||
|
<View key={i} className="flex-row items-center gap-1.5 rounded-[14px] bg-card/80 px-2 py-1.5">
|
||||||
|
<Text className="w-[52px] font-jua text-sm text-ink2">{st.time}</Text>
|
||||||
|
<Ic name={st.icon} size={22} />
|
||||||
|
<View className="ml-1 flex-1">
|
||||||
|
<Text numberOfLines={1} className="text-[13.5px] font-bold text-ink">
|
||||||
|
{st.title}
|
||||||
|
</Text>
|
||||||
|
<Text numberOfLines={1} className="text-[11.5px] font-semibold text-ink2">
|
||||||
|
{st.sub}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
{st.image && <Thumb image={st.image} icon={st.icon} iconSize={26} className="size-[46px] rounded-[10px]" />}
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
{credits.length > 0 && <Text className="mt-1.5 text-right text-[10px] font-semibold text-ink2">사진 {credits.join(' · ')}</Text>}
|
||||||
|
</Base>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (slide.kind === 'rows' && slide.image)
|
||||||
|
return (
|
||||||
|
<View className="flex-1 justify-end">
|
||||||
|
<Image source={{ uri: imageUri(slide.image) }} style={StyleSheet.absoluteFill} contentFit="cover" />
|
||||||
|
{slide.image_credit && <Credit text={slide.image_credit} className="top-2.5 right-2.5" />}
|
||||||
|
<View className="px-5 pt-20 pb-3.5">
|
||||||
|
<LinearGradient colors={['rgba(16,20,34,0)', 'rgba(16,20,34,0.55)', 'rgba(16,20,34,0.85)']} locations={[0, 0.35, 1]} style={StyleSheet.absoluteFill} />
|
||||||
|
<Eyebrow light>{slide.eyebrow}</Eyebrow>
|
||||||
|
<Big light>{slide.line}</Big>
|
||||||
|
<Rows rows={slide.rows ?? []} dark />
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<Base colors={colors}>
|
||||||
|
<Eyebrow light={light} className={light ? 'opacity-85' : undefined}>
|
||||||
|
{slide.eyebrow}
|
||||||
|
</Eyebrow>
|
||||||
|
<Big light={light} className="z-[1]">
|
||||||
|
{slide.line}
|
||||||
|
</Big>
|
||||||
|
<Pic name={slide.icon} widthPct={36} />
|
||||||
|
<Rows rows={slide.rows ?? []} dark={light} />
|
||||||
|
</Base>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import type { ArticleSummary, ResSeasonWeek } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { ARTICLE_LABEL, cardBg, dateRange, shortDay } from '@nalssigak/shared/lib';
|
||||||
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
|
import { Pressable, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
|
||||||
|
import { Fall } from '@/components/fall';
|
||||||
|
import { Credit, Ic, Skel, Thumb } from '@/components/ui';
|
||||||
|
import { CARD_BG } from '@/lib/colors';
|
||||||
|
import { useSky } from '@/lib/sky';
|
||||||
|
|
||||||
|
const HEAD_BOX = 'mx-3 mt-3 min-h-[250px] overflow-hidden rounded-[28px] p-5';
|
||||||
|
const ROW = 'flex-row items-center gap-3 border-b-[1.5px] border-line px-4 py-3.5';
|
||||||
|
const ROW_SKELS = [0, 1, 2, 3];
|
||||||
|
|
||||||
|
// 분류 글자색 (웹 ARTICLE_CAT). 밤엔 밝게
|
||||||
|
const CAT_COLOR: Record<number, [string, string]> = { 1: ['#1f9d62', '#4fd39a'], 2: ['#7a5cd6', '#b9a6ff'], 3: ['#ff7a45', '#ff8a57'] };
|
||||||
|
|
||||||
|
/** 특집 상자와 같은 틀: 머리말 · 제목 두 줄 · 시 한 줄 · 절기 막대 */
|
||||||
|
export function HeadSkel() {
|
||||||
|
return (
|
||||||
|
<View className={`${HEAD_BOX} gap-1.5 bg-card`}>
|
||||||
|
<Skel className="w-36" />
|
||||||
|
<Skel className="mt-1 h-7 w-[62%]" />
|
||||||
|
<Skel className="h-7 w-[40%]" />
|
||||||
|
<Skel className="mt-auto h-5 w-[72%]" />
|
||||||
|
<Skel className="mt-2.5 w-[70%]" />
|
||||||
|
<View className="h-[7px] w-[70%] rounded-full bg-skel" />
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RowsSkel() {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{ROW_SKELS.map((i) => (
|
||||||
|
<View key={i} className={ROW}>
|
||||||
|
<View className="flex-1 gap-1.5">
|
||||||
|
<Skel className="w-12" />
|
||||||
|
<Skel className="h-4 w-48" />
|
||||||
|
<Skel className="w-14" />
|
||||||
|
</View>
|
||||||
|
<View className="h-[84px] w-[84px] rounded-[18px] bg-skel" />
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 이번 주 특집: 제목·시·절기 막대. 누르면 이번 주 절기 창 */
|
||||||
|
export function SeasonHead({ week: w, onPress }: { week: ResSeasonWeek; onPress: () => void }) {
|
||||||
|
const { kind } = useSky();
|
||||||
|
const night = kind === 'night';
|
||||||
|
const progress = Math.round((w.progress ?? 0) * 100);
|
||||||
|
const poem = w.poem_lines ?? [];
|
||||||
|
return (
|
||||||
|
<Pressable onPress={onPress} className={HEAD_BOX}>
|
||||||
|
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'].peach} style={{ position: 'absolute', inset: 0 }} />
|
||||||
|
<Fall d={100} f={4800} style={{ position: 'absolute', top: '18%', right: 14, width: '38%', alignItems: 'center' }}>
|
||||||
|
<Ic name="maple" size={140} />
|
||||||
|
</Fall>
|
||||||
|
<Text className="text-[13px] font-extrabold text-ink opacity-75">이번 주 특집{w.start && w.end ? ` · ${dateRange(w.start, w.end)}` : ''}</Text>
|
||||||
|
<Text className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight text-ink">{w.headline}</Text>
|
||||||
|
{poem.length > 0 && <Text className="mt-auto max-w-[72%] pt-3 font-batang text-[22px] leading-[37px] text-ink">{poem.join('\n')}</Text>}
|
||||||
|
{w.term_now && w.term_next && (
|
||||||
|
<View className={`max-w-[70%] ${poem.length ? 'mt-2.5' : 'mt-auto'}`}>
|
||||||
|
<View className="flex-row justify-between">
|
||||||
|
<Text className="text-xs font-extrabold text-ink2">
|
||||||
|
{w.term_now.name} {shortDay(w.term_now.day)}
|
||||||
|
</Text>
|
||||||
|
<Text className="text-xs font-extrabold text-ink2">
|
||||||
|
{w.term_next.name} {shortDay(w.term_next.day)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View className="mt-1 h-[7px] overflow-hidden rounded-full bg-[rgb(40_48_74/0.1)]" accessibilityRole="image" accessibilityLabel={`다음 절기까지 ${progress}% 지났어요`}>
|
||||||
|
<View className="h-full bg-orange" style={{ width: `${progress}%` }} />
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
</Pressable>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ArticleRow({ article: a, onPress }: { article: ArticleSummary; onPress: () => void }) {
|
||||||
|
const { kind } = useSky();
|
||||||
|
const night = kind === 'night';
|
||||||
|
const color = CAT_COLOR[a.category]?.[night ? 1 : 0];
|
||||||
|
return (
|
||||||
|
<Pressable onPress={onPress} className={ROW}>
|
||||||
|
<View className="flex-1">
|
||||||
|
{ARTICLE_LABEL[a.category] && (
|
||||||
|
<Text className="text-xs font-extrabold" style={{ color }}>
|
||||||
|
{ARTICLE_LABEL[a.category]}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
<Text className="mt-0.5 font-jua text-[17.5px] leading-snug text-ink">{a.title}</Text>
|
||||||
|
<Text className="mt-1 text-xs font-semibold text-ink3">{a.read_minutes}분 읽기</Text>
|
||||||
|
</View>
|
||||||
|
<Thumb image={a.image} icon={a.icon} iconSize={54} className="h-[84px] w-[84px] rounded-[18px]">
|
||||||
|
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'][cardBg(a.icon, a.article_id)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
|
||||||
|
{a.image && a.image_credit && <Credit text={a.image_credit} />}
|
||||||
|
</Thumb>
|
||||||
|
</Pressable>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { getArticleOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import { ARTICLE_LABEL, articleMeta, cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
import { Pressable, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
|
||||||
|
import { Credit, Ic, StateBox, Thumb } from '@/components/ui';
|
||||||
|
import { CARD_BG } from '@/lib/colors';
|
||||||
|
import { useSheet } from '@/lib/sheet';
|
||||||
|
import { useSky } from '@/lib/sky';
|
||||||
|
|
||||||
|
import { ArticleSkel, Body } from './parts';
|
||||||
|
|
||||||
|
export function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t: string) => void }) {
|
||||||
|
const q = useQuery(getArticleOptions({ path: { article_id: articleId } }));
|
||||||
|
const a = q.data?.article;
|
||||||
|
const night = useSky().kind === 'night';
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onTitle(a ? (ARTICLE_LABEL[a.category] ?? '') : '');
|
||||||
|
}, [a, onTitle]);
|
||||||
|
|
||||||
|
const load = loadOf(q);
|
||||||
|
if (!a) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." hold={<ArticleSkel />} boxClassName="inset-0" />}</Body>;
|
||||||
|
return (
|
||||||
|
<Body>
|
||||||
|
<Thumb image={a.image} icon={a.icon} iconSize={96} className="mb-3.5 h-[150px] rounded-[20px]">
|
||||||
|
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'][cardBg(a.icon, a.article_id)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
|
||||||
|
{a.image && a.image_credit && <Credit text={a.image_credit} />}
|
||||||
|
</Thumb>
|
||||||
|
<Text className="text-[13px] font-extrabold text-ink2">{articleMeta(a)}</Text>
|
||||||
|
<Text className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight text-ink">{a.title}</Text>
|
||||||
|
{(q.data?.body ?? []).map((t) => (
|
||||||
|
<Text key={t} className="mb-2.5 text-[15px] leading-[1.7] text-ink">
|
||||||
|
{t}
|
||||||
|
</Text>
|
||||||
|
))}
|
||||||
|
</Body>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SeasonWeekSheet() {
|
||||||
|
const { open } = useSheet();
|
||||||
|
const night = useSky().kind === 'night';
|
||||||
|
const q = useQuery(getSeasonWeekOptions());
|
||||||
|
const w = q.data;
|
||||||
|
const load = loadOf(q);
|
||||||
|
if (!w?.headline) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이번 주 특집이 아직 없어요." hold={<ArticleSkel />} boxClassName="inset-0" />}</Body>;
|
||||||
|
return (
|
||||||
|
<Body>
|
||||||
|
<View className="mb-3.5 h-[150px] items-center justify-center overflow-hidden rounded-[20px]">
|
||||||
|
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'].peach} style={{ position: 'absolute', inset: 0 }} />
|
||||||
|
<Ic name="maple" size={96} />
|
||||||
|
</View>
|
||||||
|
<Text className="text-[13px] font-extrabold text-ink2">{w.start && w.end ? dateRange(w.start, w.end) : '이번 주'}</Text>
|
||||||
|
<Text className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight text-ink">{w.headline}</Text>
|
||||||
|
{(w.poem_lines ?? []).length > 0 && (
|
||||||
|
<View className="mb-2.5">
|
||||||
|
<Text className="font-batang text-[17px] leading-[29px] text-ink">
|
||||||
|
{w.poem_lines?.join(' ')}
|
||||||
|
</Text>
|
||||||
|
{w.author && <Text className="text-xs font-semibold text-ink3">{w.author}</Text>}
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
{w.term_now && w.term_next && (
|
||||||
|
<Text className="mb-2.5 text-[15px] leading-[1.7] text-ink">
|
||||||
|
지금 절기는 {w.term_now.name}({shortDay(w.term_now.day)}), 다음 절기는 {w.term_next.name}({shortDay(w.term_next.day)})예요.
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{(w.news ?? []).map((n) => (
|
||||||
|
<Pressable key={n.code} onPress={() => open({ type: 'article', articleId: n.article_id })} className="flex-row items-center gap-2.5 border-b-[1.5px] border-line py-2.5">
|
||||||
|
<Ic name={n.icon} size={32} />
|
||||||
|
<Text className="flex-1 font-jua text-base text-ink">{n.title}</Text>
|
||||||
|
</Pressable>
|
||||||
|
))}
|
||||||
|
</Body>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,356 @@
|
|||||||
|
import {
|
||||||
|
addCommentMutation,
|
||||||
|
agreeTermsMutation,
|
||||||
|
blockAuthorMutation,
|
||||||
|
deleteCommentMutation,
|
||||||
|
getFeedQueryKey,
|
||||||
|
likeCommentMutation,
|
||||||
|
listBlockedQueryKey,
|
||||||
|
listCommentsInfiniteOptions,
|
||||||
|
listCommentsInfiniteQueryKey,
|
||||||
|
meQueryKey,
|
||||||
|
reportCommentMutation,
|
||||||
|
unlikeCommentMutation,
|
||||||
|
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import { ReportReason, type CommentData, type ResCommentList } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { ago, loadOf } from '@nalssigak/shared/lib';
|
||||||
|
import { useInfiniteQuery, useMutation, useQueryClient, type InfiniteData } from '@tanstack/react-query';
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { Linking, Pressable, TextInput, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
import { useCSSVariable } from 'uniwind';
|
||||||
|
|
||||||
|
import { Avatar, Skel, StateBox } from '@/components/ui';
|
||||||
|
import { useAuth } from '@/lib/auth';
|
||||||
|
import { useRegion } from '@/lib/region';
|
||||||
|
import { useSheet } from '@/lib/sheet';
|
||||||
|
import { SITE_URL } from '@/lib/site';
|
||||||
|
|
||||||
|
import { Body, ErrorLine, Field, HeartIcon, useSoft } from './parts';
|
||||||
|
|
||||||
|
const NOT_FOUND = 3001; // 서버 ErrorType.NOT_FOUND
|
||||||
|
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍'];
|
||||||
|
const N3 = [0, 1, 2];
|
||||||
|
const REPORT_REASONS = [
|
||||||
|
[ReportReason.ABUSE, '욕설·비하'],
|
||||||
|
[ReportReason.AD, '광고'],
|
||||||
|
[ReportReason.PRIVACY, '개인정보 노출'],
|
||||||
|
[ReportReason.OTHER, '기타'],
|
||||||
|
] as const;
|
||||||
|
export const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments';
|
||||||
|
|
||||||
|
function Chip({ label, onPress, disabled, danger }: { label: string; onPress: () => void; disabled?: boolean; danger?: boolean }) {
|
||||||
|
const s = useSoft();
|
||||||
|
return (
|
||||||
|
<Pressable onPress={onPress} disabled={disabled} className={`rounded-[12px] px-3 py-2 disabled:opacity-50 ${danger ? 'bg-heart' : ''}`} style={danger ? undefined : { backgroundColor: s.soft }}>
|
||||||
|
<Text className={`text-[13px] font-extrabold ${danger ? 'text-white' : 'text-ink'}`}>{label}</Text>
|
||||||
|
</Pressable>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
|
||||||
|
function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
|
||||||
|
const { loggedIn } = useAuth();
|
||||||
|
const { open } = useSheet();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [step, setStep] = useState<'closed' | 'menu' | 'report' | 'block'>('closed');
|
||||||
|
const [failed, setFailed] = useState(false);
|
||||||
|
const report = useMutation(reportCommentMutation());
|
||||||
|
const block = useMutation(blockAuthorMutation());
|
||||||
|
const pending = report.isPending || block.isPending;
|
||||||
|
|
||||||
|
const finish = (notice: string) => ({
|
||||||
|
onSuccess: (res: { result?: { success?: boolean } }) => {
|
||||||
|
if (!res.result?.success) return setFailed(true);
|
||||||
|
setStep('closed');
|
||||||
|
onNotice(notice);
|
||||||
|
queryClient.invalidateQueries({ predicate: isCommentList });
|
||||||
|
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() });
|
||||||
|
},
|
||||||
|
onError: () => setFailed(true),
|
||||||
|
});
|
||||||
|
const go = (next: typeof step) => {
|
||||||
|
setFailed(false);
|
||||||
|
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', postId } });
|
||||||
|
setStep(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Pressable onPress={() => go(step === 'closed' ? 'menu' : 'closed')} hitSlop={10} accessibilityRole="button" accessibilityState={{ expanded: step !== 'closed' }} accessibilityLabel="댓글 메뉴" className="px-1">
|
||||||
|
<Text className="text-sm font-extrabold text-ink3">⋯</Text>
|
||||||
|
</Pressable>
|
||||||
|
{step !== 'closed' && (
|
||||||
|
<View className="mt-2 w-full flex-row flex-wrap items-center gap-1.5" accessibilityLabel="댓글 메뉴">
|
||||||
|
{step === 'menu' && (
|
||||||
|
<>
|
||||||
|
<Chip label="신고하기" onPress={() => go('report')} />
|
||||||
|
<Chip label="이 사람 차단하기" onPress={() => go('block')} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{step === 'report' &&
|
||||||
|
REPORT_REASONS.map(([reason, label]) => (
|
||||||
|
<Chip key={reason} label={label} disabled={pending} onPress={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.'))} />
|
||||||
|
))}
|
||||||
|
{step === 'block' && (
|
||||||
|
<>
|
||||||
|
<Text className="w-full text-[13px] font-bold text-ink">{c.nickname}님 댓글을 더는 안 볼까요?</Text>
|
||||||
|
<Chip label="차단하기" danger disabled={pending} onPress={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.'))} />
|
||||||
|
<Chip label="취소" disabled={pending} onPress={() => go('closed')} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{failed && (
|
||||||
|
<Text className="w-full text-[13px] font-bold text-heart" accessibilityRole="alert">
|
||||||
|
잠시 뒤에 다시 해 주세요.
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommentsSkel() {
|
||||||
|
return (
|
||||||
|
<View>
|
||||||
|
{N3.map((i) => (
|
||||||
|
<View key={i} className="flex-row items-start gap-2.5 py-2">
|
||||||
|
<View className="size-[34px] rounded-full bg-skel" />
|
||||||
|
<View className="flex-1 gap-1.5">
|
||||||
|
<Skel className="w-3/4" />
|
||||||
|
<Skel className="w-24" />
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
|
||||||
|
const { region } = useRegion();
|
||||||
|
const { loggedIn } = useAuth();
|
||||||
|
const { open } = useSheet();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [heart, ink3] = useCSSVariable(['--color-heart', '--color-ink3']).map(String);
|
||||||
|
const [liked, setLiked] = useState(c.liked);
|
||||||
|
const [count, setCount] = useState(c.like_count);
|
||||||
|
const like = useMutation(likeCommentMutation());
|
||||||
|
const unlike = useMutation(unlikeCommentMutation());
|
||||||
|
const remove = useMutation(deleteCommentMutation());
|
||||||
|
const [removeFailed, setRemoveFailed] = useState(false);
|
||||||
|
const [likeFailed, setLikeFailed] = useState(false);
|
||||||
|
|
||||||
|
const toggle = () => {
|
||||||
|
if (!loggedIn) return open({ type: 'login' });
|
||||||
|
if (like.isPending || unlike.isPending) return;
|
||||||
|
const next = !liked;
|
||||||
|
setLikeFailed(false);
|
||||||
|
setLiked(next);
|
||||||
|
setCount((n) => n + (next ? 1 : -1));
|
||||||
|
const revert = () => {
|
||||||
|
setLiked(!next);
|
||||||
|
setCount(c.like_count);
|
||||||
|
};
|
||||||
|
(next ? like : unlike).mutate(
|
||||||
|
{ path: { comment_id: c.comment_id } },
|
||||||
|
{
|
||||||
|
onSuccess: (res) => {
|
||||||
|
if (res.result?.success) {
|
||||||
|
setLiked(!!res.liked);
|
||||||
|
if (res.like_count != null) setCount(res.like_count);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
revert();
|
||||||
|
// 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다
|
||||||
|
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) });
|
||||||
|
else setLikeFailed(true);
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
revert();
|
||||||
|
setLikeFailed(true);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 지우는 동안은 흐리게 두고, 성공하면 다시 받기 전에 목록 캐시에서 바로 뺀다
|
||||||
|
const del = () => {
|
||||||
|
setRemoveFailed(false);
|
||||||
|
remove.mutate(
|
||||||
|
{ path: { comment_id: c.comment_id } },
|
||||||
|
{
|
||||||
|
onSuccess: async (res) => {
|
||||||
|
if (!res.result?.success) return setRemoveFailed(true);
|
||||||
|
const key = listCommentsInfiniteQueryKey({ path: { post_id: postId } });
|
||||||
|
await queryClient.cancelQueries({ queryKey: key });
|
||||||
|
queryClient.setQueryData<InfiniteData<ResCommentList>>(key, (data) =>
|
||||||
|
data ? { ...data, pages: data.pages.map((p) => ({ ...p, comments: p.comments?.filter((x) => x.comment_id !== c.comment_id) })) } : data,
|
||||||
|
);
|
||||||
|
queryClient.invalidateQueries({ queryKey: key });
|
||||||
|
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
|
||||||
|
},
|
||||||
|
onError: () => setRemoveFailed(true),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View className={`flex-row items-start gap-2.5 py-2 ${remove.isPending ? 'opacity-50' : ''}`}>
|
||||||
|
<Avatar character={c.character} color={c.color} mood={c.mood} />
|
||||||
|
<View className="flex-1">
|
||||||
|
<Text className="text-sm text-ink">
|
||||||
|
<Text className="font-extrabold">{c.nickname} </Text>
|
||||||
|
{c.body}
|
||||||
|
</Text>
|
||||||
|
<View className="mt-0.5 flex-row flex-wrap items-center">
|
||||||
|
<Text className="text-xs font-bold text-ink3">
|
||||||
|
{ago(c.created_at)} · {likeFailed ? <Text className="text-heart">좋아요를 못 했어요. 잠시 뒤에 다시 눌러 주세요</Text> : `좋아요 ${count}개`}
|
||||||
|
{c.mine && (
|
||||||
|
<>
|
||||||
|
{' · '}
|
||||||
|
<Text onPress={remove.isPending ? undefined : del} className={removeFailed && !remove.isPending ? 'text-heart' : 'text-ink3'}>
|
||||||
|
{remove.isPending ? '지우는 중…' : removeFailed ? '못 지웠어요 · 다시' : '지우기'}
|
||||||
|
</Text>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
{!c.mine && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="댓글 좋아요" className="pt-1">
|
||||||
|
<HeartIcon size={16} fill={liked ? heart : 'none'} stroke={liked ? heart : ink3} />
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
||||||
|
const { region } = useRegion();
|
||||||
|
const { open } = useSheet();
|
||||||
|
const { loggedIn, me } = useAuth();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const list = useInfiniteQuery({
|
||||||
|
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
|
||||||
|
initialPageParam: { path: { post_id: postId } },
|
||||||
|
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
||||||
|
});
|
||||||
|
const add = useMutation(addCommentMutation());
|
||||||
|
const agree = useMutation(agreeTermsMutation());
|
||||||
|
const s = useSoft();
|
||||||
|
const [addFailed, setAddFailed] = useState(false);
|
||||||
|
const [askTerms, setAskTerms] = useState(false);
|
||||||
|
const [notice, setNotice] = useState('');
|
||||||
|
const [text, setText] = useState(draft ?? '');
|
||||||
|
const inputRef = useRef<TextInput>(null);
|
||||||
|
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? [];
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!notice) return;
|
||||||
|
const t = setTimeout(() => setNotice(''), 3000);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [notice]);
|
||||||
|
|
||||||
|
const send = () => {
|
||||||
|
const body = text.trim();
|
||||||
|
if (!body || add.isPending) return;
|
||||||
|
setAddFailed(false);
|
||||||
|
add.mutate(
|
||||||
|
{ path: { post_id: postId }, body: { body } },
|
||||||
|
{
|
||||||
|
onSuccess: (res) => {
|
||||||
|
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true);
|
||||||
|
setAddFailed(!res.result?.success);
|
||||||
|
if (!res.result?.success) return;
|
||||||
|
setText('');
|
||||||
|
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) });
|
||||||
|
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
|
||||||
|
},
|
||||||
|
onError: () => setAddFailed(true),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
|
||||||
|
const submit = () => {
|
||||||
|
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } });
|
||||||
|
if (me && !me.terms_agreed) return setAskTerms(true);
|
||||||
|
send();
|
||||||
|
};
|
||||||
|
const agreeAndSend = () => {
|
||||||
|
setAddFailed(false);
|
||||||
|
agree.mutate(
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
onSuccess: (res) => {
|
||||||
|
if (!res.result?.success) return setAddFailed(true);
|
||||||
|
queryClient.setQueryData(meQueryKey(), res);
|
||||||
|
setAskTerms(false);
|
||||||
|
send();
|
||||||
|
},
|
||||||
|
onError: () => setAddFailed(true),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Body>
|
||||||
|
{comments.length ? (
|
||||||
|
<>
|
||||||
|
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
|
||||||
|
{comments.map((c) => (
|
||||||
|
<CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} onNotice={setNotice} />
|
||||||
|
))}
|
||||||
|
{list.hasNextPage && (
|
||||||
|
<Pressable onPress={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 disabled:opacity-50">
|
||||||
|
<Text className="text-center text-sm font-bold text-ink3">{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}</Text>
|
||||||
|
</Pressable>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : loadOf(list) === 'loading' ? (
|
||||||
|
<CommentsSkel />
|
||||||
|
) : (
|
||||||
|
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} boxClassName="inset-0" />
|
||||||
|
)}
|
||||||
|
</Body>
|
||||||
|
{askTerms ? (
|
||||||
|
<View className="mx-3 gap-2 rounded-[16px] p-3" style={{ backgroundColor: s.soft }} accessibilityLabel="이용약관 동의">
|
||||||
|
<Text className="text-[13px] font-bold text-ink">댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요.</Text>
|
||||||
|
<View className="flex-row gap-2">
|
||||||
|
<Pressable onPress={() => void Linking.openURL(`${SITE_URL}/terms.html`)} accessibilityRole="link" className="flex-1 rounded-[12px] bg-card p-2.5">
|
||||||
|
<Text className="text-center text-[13px] font-extrabold text-ink">이용약관 보기</Text>
|
||||||
|
</Pressable>
|
||||||
|
<Pressable onPress={agreeAndSend} disabled={agree.isPending || add.isPending} className="flex-1 rounded-[12px] bg-orange p-2.5 disabled:opacity-60">
|
||||||
|
<Text className="text-center text-[13px] font-extrabold text-white">동의하고 쓰기</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
) : (
|
||||||
|
<View className="flex-row justify-around pt-1" accessibilityLabel="빠른 이모지">
|
||||||
|
{EMOJIS.map((e) => (
|
||||||
|
<Pressable
|
||||||
|
key={e}
|
||||||
|
disabled={add.isPending}
|
||||||
|
className="disabled:opacity-40"
|
||||||
|
onPress={() => {
|
||||||
|
setText((t) => (t + e).slice(0, 60));
|
||||||
|
inputRef.current?.focus();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Text className="text-[22px]">{e}</Text>
|
||||||
|
</Pressable>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
{addFailed ? <ErrorLine className="h-4 text-xs leading-4" text="댓글을 올리지 못했어요. 다시 해 주세요." /> : <Text className="h-4 text-center text-xs leading-4 font-bold text-ink2">{notice}</Text>}
|
||||||
|
<View className="flex-row items-center gap-2.5 border-t border-line px-3 py-2.5">
|
||||||
|
<View className="flex-1">
|
||||||
|
<Field ref={inputRef} round value={text} onChangeText={setText} editable={!add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} accessibilityLabel="댓글" returnKeyType="send" onSubmitEditing={submit} />
|
||||||
|
</View>
|
||||||
|
<Pressable onPress={submit} disabled={add.isPending || (loggedIn && !text.trim())} className="disabled:opacity-40">
|
||||||
|
<Text className="font-extrabold text-rain">{add.isPending ? '올리는 중…' : '게시'}</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
import { getIndexOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import type { Factor, ResIndexDetail } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { loadOf } from '@nalssigak/shared/lib';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
import { View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
import Svg, { Circle, Line, Polygon, Text as SvgText, TSpan } from 'react-native-svg';
|
||||||
|
|
||||||
|
import { Ic, Skel, StateBox } from '@/components/ui';
|
||||||
|
import { useRegion } from '@/lib/region';
|
||||||
|
import { useSky } from '@/lib/sky';
|
||||||
|
|
||||||
|
import { Body, useSoft } from './parts';
|
||||||
|
|
||||||
|
const SLOT_KEYS = ['morning', 'day', 'evening', 'night'] as const;
|
||||||
|
const SLOT_NAMES = { morning: '아침', day: '낮', evening: '저녁', night: '밤' } as const;
|
||||||
|
const N4 = [0, 1, 2, 3];
|
||||||
|
const N6 = [0, 1, 2, 3, 4, 5];
|
||||||
|
|
||||||
|
const labelLines = (label: string) => {
|
||||||
|
const cut = label.indexOf(' ');
|
||||||
|
return cut < 0 ? [label] : [label.slice(0, cut), label.slice(cut + 1)];
|
||||||
|
};
|
||||||
|
|
||||||
|
function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[]; size?: number }) {
|
||||||
|
const night = useSky().kind === 'night';
|
||||||
|
const c = size / 2;
|
||||||
|
const r = size / 2 - 40;
|
||||||
|
const n = factors.length;
|
||||||
|
const pt = (i: number, v: number) => {
|
||||||
|
const a = -Math.PI / 2 + (i * 2 * Math.PI) / n;
|
||||||
|
return [c + Math.cos(a) * r * v, c + Math.sin(a) * r * v] as const;
|
||||||
|
};
|
||||||
|
const ring = (v: number) => factors.map((_, i) => pt(i, v).join(',')).join(' ');
|
||||||
|
return (
|
||||||
|
<View className="mt-2 items-center" accessibilityRole="image" accessibilityLabel={`${name} 요소별 점수`}>
|
||||||
|
<Svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
|
||||||
|
{[0.25, 0.5, 0.75, 1].map((v) => (
|
||||||
|
<Polygon key={v} points={ring(v)} fill={v === 1 ? (night ? '#222a5c' : '#f7f9fc') : 'none'} stroke={night ? 'rgba(255,255,255,0.18)' : '#d9e2ef'} strokeWidth={1.5} />
|
||||||
|
))}
|
||||||
|
{factors.map((f, i) => (
|
||||||
|
<Line key={f.axis} x1={c} y1={c} x2={pt(i, 1)[0]} y2={pt(i, 1)[1]} stroke={night ? 'rgba(255,255,255,0.12)' : '#e3e9f2'} strokeWidth={1.5} />
|
||||||
|
))}
|
||||||
|
<Polygon points={factors.map((f, i) => pt(i, f.value / 100).join(',')).join(' ')} fill="rgba(255,122,69,0.38)" stroke="#ff7a45" strokeWidth={3} strokeLinejoin="round" />
|
||||||
|
{factors.map((f, i) => (
|
||||||
|
<Circle key={f.axis} cx={pt(i, f.value / 100)[0]} cy={pt(i, f.value / 100)[1]} r={4.5} fill="#fff" stroke="#ff7a45" strokeWidth={2.5} />
|
||||||
|
))}
|
||||||
|
{factors.map((f, i) => {
|
||||||
|
const lines = labelLines(f.label);
|
||||||
|
const [x, y] = pt(i, 1.24);
|
||||||
|
return (
|
||||||
|
<SvgText key={f.axis} x={x} y={y - (lines.length - 1) * 7} textAnchor="middle" fontFamily="Jua_400Regular" fontSize={13} fill={night ? '#eef1ff' : '#28304a'}>
|
||||||
|
{lines.map((line, k) => (
|
||||||
|
<TSpan key={k} x={x} dy={k === 0 ? 4 : 14}>
|
||||||
|
{line}
|
||||||
|
</TSpan>
|
||||||
|
))}
|
||||||
|
</SvgText>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Svg>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function GakSkel() {
|
||||||
|
const s = useSoft();
|
||||||
|
return (
|
||||||
|
<View>
|
||||||
|
<View className="flex-row items-center gap-3">
|
||||||
|
<View className="size-[58px] rounded-full bg-skel" />
|
||||||
|
<View className="flex-1 gap-1.5">
|
||||||
|
<Skel className="h-6 w-28" />
|
||||||
|
<Skel className="w-4/5" />
|
||||||
|
</View>
|
||||||
|
<Skel className="h-10 w-14" />
|
||||||
|
</View>
|
||||||
|
<View className="mt-2 aspect-square w-full max-w-[250px] self-center rounded-full bg-skel" />
|
||||||
|
<View className="mt-2.5 flex-row gap-1.5">
|
||||||
|
{N4.map((i) => (
|
||||||
|
<View key={i} className="flex-1 items-center gap-1.5 rounded-2xl px-1 py-2.5" style={{ backgroundColor: s.soft }}>
|
||||||
|
<Skel className="w-8" />
|
||||||
|
<Skel className="h-6 w-9" />
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
<View className="mt-3.5 gap-3">
|
||||||
|
{N6.map((i) => (
|
||||||
|
<View key={i} className="flex-row items-center gap-2.5">
|
||||||
|
<Skel className="w-[70px]" />
|
||||||
|
<View className="h-[9px] flex-1 rounded-full bg-skel" />
|
||||||
|
<Skel className="w-10" />
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) => void }) {
|
||||||
|
const { region } = useRegion();
|
||||||
|
const s = useSoft();
|
||||||
|
const q = useQuery(getIndexOptions({ path: { index_id: indexId }, query: { region: region.code } }));
|
||||||
|
const d: ResIndexDetail | undefined = q.data;
|
||||||
|
const g = d?.index;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onTitle(g ? `${g.rank}위 ${g.name}` : '계산 근거');
|
||||||
|
}, [g, onTitle]);
|
||||||
|
|
||||||
|
const load = loadOf(q);
|
||||||
|
if (!g) return <Body>{load === 'loading' ? <GakSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={<GakSkel />} boxClassName="inset-0" />}</Body>;
|
||||||
|
const factors = d.factors ?? [];
|
||||||
|
const bands = d.bands ?? [];
|
||||||
|
const now = bands.find((b) => b.current);
|
||||||
|
return (
|
||||||
|
<Body>
|
||||||
|
<View className="flex-row items-center gap-3">
|
||||||
|
<Ic name={g.icon} size={58} />
|
||||||
|
<View className="flex-1">
|
||||||
|
<Text className="font-jua text-[22px] text-ink">{g.name}</Text>
|
||||||
|
{d.description && <Text className="mt-0.5 text-[13.5px] font-semibold text-ink2">{d.description}</Text>}
|
||||||
|
</View>
|
||||||
|
<Text className={`font-bagel text-[42px] ${g.active ? 'text-orange' : 'text-ink3'}`}>{g.score}</Text>
|
||||||
|
</View>
|
||||||
|
{!g.active && <Text className="mt-2 text-[13px] font-bold text-ink2">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</Text>}
|
||||||
|
{now && (
|
||||||
|
<Text className="mt-3 overflow-hidden rounded-2xl px-3.5 py-2.5 text-[14.5px] font-bold text-ink" style={{ backgroundColor: s.warm }}>
|
||||||
|
<Text className="font-jua text-orange">
|
||||||
|
{now.low}~{now.high}점{' '}
|
||||||
|
</Text>
|
||||||
|
{now.text}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{factors.length > 2 && <Radar name={g.name} factors={factors} />}
|
||||||
|
{g.slots && g.slots.length > 0 && (
|
||||||
|
<View className="mt-2.5 flex-row gap-1.5" accessibilityLabel="오늘 시간대별 점수">
|
||||||
|
{SLOT_KEYS.map((k) => {
|
||||||
|
const sl = g.slots?.find((x) => x.slot === k);
|
||||||
|
const cur = g.active && g.slot === k;
|
||||||
|
return (
|
||||||
|
<View key={k} className="flex-1 items-center rounded-2xl px-1 py-2" style={{ backgroundColor: cur ? s.warm : s.soft }}>
|
||||||
|
<Text className="text-xs font-extrabold text-ink2">
|
||||||
|
{SLOT_NAMES[k]}
|
||||||
|
{cur && ' · 지금'}
|
||||||
|
</Text>
|
||||||
|
<Text className={`font-bagel text-xl ${sl ? 'text-orange' : 'text-ink3'}`}>{sl ? sl.score : '–'}</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
{g.trend && g.trend.length > 0 && (
|
||||||
|
<View className="mt-2.5 flex-row gap-1.5">
|
||||||
|
{g.trend.map((t) => (
|
||||||
|
<View key={t.day} className="flex-1 items-center rounded-2xl px-1 py-2.5" style={{ backgroundColor: s.soft }}>
|
||||||
|
<Text numberOfLines={1} className="text-xs font-extrabold text-ink2">
|
||||||
|
{t.label}
|
||||||
|
</Text>
|
||||||
|
<Text className="font-bagel text-2xl text-orange">{t.score}</Text>
|
||||||
|
<Text className={`text-[11px] leading-4 font-extrabold text-ink2 ${t.estimated ? '' : 'opacity-0'}`}>예상</Text>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
{bands.length > 0 && (
|
||||||
|
<View className="mt-3.5 gap-1.5" accessibilityLabel="점수 구간별 설명">
|
||||||
|
{bands.map((b) => (
|
||||||
|
<View key={b.low} className={`flex-row items-start gap-2 ${b.current ? '' : 'opacity-45'}`}>
|
||||||
|
<View className={`w-[62px] items-center rounded-full py-px ${b.current ? 'bg-orange' : 'bg-ink3'}`}>
|
||||||
|
<Text className="font-jua text-xs text-white">
|
||||||
|
{b.low}~{b.high}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<Text className="flex-1 text-[13px] font-semibold text-ink">{b.text}</Text>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
<View className="mt-3.5 gap-2.5">
|
||||||
|
{factors.map((f) => (
|
||||||
|
<View key={f.axis}>
|
||||||
|
<View className="flex-row items-center gap-2.5">
|
||||||
|
<Text className="w-[84px] text-[13.5px] font-bold text-ink">{f.label}</Text>
|
||||||
|
<View className="h-[9px] flex-1 overflow-hidden rounded-full" style={{ backgroundColor: s.bar }}>
|
||||||
|
<LinearGradient colors={['#ffc86e', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${f.value}%` }} />
|
||||||
|
</View>
|
||||||
|
<Text className="w-[52px] text-right text-xs text-ink2">비중 {f.weight}%</Text>
|
||||||
|
</View>
|
||||||
|
<Text className="mt-0.5 ml-[94px] text-[12.5px] font-semibold text-ink2">{f.note}</Text>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
<View className="mt-3.5 gap-1.5">
|
||||||
|
{d.zero_reason && (
|
||||||
|
<Text className="text-[13px] font-semibold text-ink2">
|
||||||
|
<Text className="font-bold text-heart">오늘 걸린 조건:</Text> {d.zero_reason}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{factors.length > 0 && (
|
||||||
|
<Text className="text-[13px] font-semibold text-ink2">
|
||||||
|
<Text className="font-bold text-ink">계산 방법:</Text> 요소 점수에 비중을 곱해 더하고, 가장 낮은 요소가 낮을수록 최대 25%까지 더 깎아요
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{d.zero_rules && (
|
||||||
|
<Text className="text-[13px] font-semibold text-ink2">
|
||||||
|
<Text className="font-bold text-ink">점수 깎이는 조건:</Text> {d.zero_rules}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{d.limit && (
|
||||||
|
<Text className="text-[13px] font-semibold text-ink2">
|
||||||
|
<Text className="font-bold text-ink">반영 못 한 것:</Text> {d.limit}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
</Body>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { GoogleSignin, isErrorWithCode, isSuccessResponse, statusCodes } from '@react-native-google-signin/google-signin';
|
||||||
|
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Platform, Pressable, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
|
||||||
|
/** 구글로 계속하기. 서버에 클라이언트 ID가 없거나 안드로이드가 아니면 그리지 않는다 */
|
||||||
|
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
|
||||||
|
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity, enabled: Platform.OS === 'android' }).data?.google_client_id;
|
||||||
|
const login = useMutation(googleLoginMutation());
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [broken, setBroken] = useState(false);
|
||||||
|
|
||||||
|
const press = async () => {
|
||||||
|
if (!clientId) return;
|
||||||
|
setBroken(false);
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
GoogleSignin.configure({ webClientId: clientId });
|
||||||
|
await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
|
||||||
|
const res = await GoogleSignin.signIn();
|
||||||
|
if (!isSuccessResponse(res)) return;
|
||||||
|
const token = res.data.idToken;
|
||||||
|
if (!token) return onFail();
|
||||||
|
login.mutate({ body: { credential: token } }, { onSuccess: onResult, onError: onFail });
|
||||||
|
} catch (e) {
|
||||||
|
if (isErrorWithCode(e) && e.code === statusCodes.IN_PROGRESS) return;
|
||||||
|
console.error('[google] sign in', e);
|
||||||
|
setBroken(true);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (Platform.OS !== 'android' || !clientId) return null;
|
||||||
|
const pending = busy || login.isPending;
|
||||||
|
return (
|
||||||
|
<View className="gap-2">
|
||||||
|
<Pressable onPress={press} disabled={pending} className="rounded-full border-[1.5px] border-line bg-white p-3 disabled:opacity-60" accessibilityRole="button">
|
||||||
|
<Text className="text-center text-[15px] font-extrabold text-[#28304a]">{pending ? '구글로 로그인 중…' : '구글로 계속하기'}</Text>
|
||||||
|
</Pressable>
|
||||||
|
{broken && <Text className="text-center text-[13px] font-bold text-ink3">구글 로그인을 하지 못했어요. 잠시 뒤에 다시 해 주세요.</Text>}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { subscribeAuth } from '@nalssigak/shared/api/auth';
|
||||||
|
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||||
|
import { KeyboardAvoidingView, Modal, Pressable, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
import Animated, { Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withTiming } from 'react-native-reanimated';
|
||||||
|
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||||
|
|
||||||
|
import { SheetContext, useSheet, type SheetState } from '@/lib/sheet';
|
||||||
|
|
||||||
|
import { ArticleSheet, SeasonWeekSheet } from './article';
|
||||||
|
import { CommentsSheet } from './comments';
|
||||||
|
import { GakSheet } from './gak';
|
||||||
|
import { LoginSheet } from './login';
|
||||||
|
import { MeSheet } from './me';
|
||||||
|
import { RegionSheet } from './region';
|
||||||
|
|
||||||
|
export function SheetProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [state, setState] = useState<SheetState>(null);
|
||||||
|
const open = useCallback((s: Exclude<SheetState, null>) => setState(s), []);
|
||||||
|
const close = useCallback(() => setState(null), []);
|
||||||
|
const api = useMemo(() => ({ open, close }), [open, close]);
|
||||||
|
|
||||||
|
// 로그인이 필요한 요청이 401을 받으면 로그인 창을 띄운다
|
||||||
|
useEffect(() => subscribeAuth((reason) => reason === 'required' && open({ type: 'login' })), [open]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SheetContext value={api}>
|
||||||
|
{children}
|
||||||
|
<SheetHost state={state} onClose={close} />
|
||||||
|
</SheetContext>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const;
|
||||||
|
|
||||||
|
/** 판만 아래에서 올라온다 (웹 b-sheet: 0.26초, 40px 아래·흐릿하게에서) */
|
||||||
|
function Rise({ children }: { children: ReactNode }) {
|
||||||
|
const reduce = useReducedMotion();
|
||||||
|
const p = useSharedValue(reduce ? 1 : 0);
|
||||||
|
useEffect(() => {
|
||||||
|
p.value = withTiming(1, { duration: 260, easing: Easing.bezier(0.2, 0.9, 0.3, 1) });
|
||||||
|
}, [p]);
|
||||||
|
const anim = useAnimatedStyle(() => ({ opacity: 0.4 + 0.6 * p.value, transform: [{ translateY: 40 * (1 - p.value) }] }));
|
||||||
|
return <Animated.View style={[{ width: '100%', maxHeight: '86%', alignItems: 'center' }, anim]}>{children}</Animated.View>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 아래에서 올라오는 창. 배경은 제자리에서 서서히. 바깥을 누르거나 뒤로 가기(안드로이드)로 닫는다 */
|
||||||
|
function SheetHost({ state: next, onClose }: { state: SheetState; onClose: () => void }) {
|
||||||
|
// 닫는 동안(배경이 사라지는 동안)에도 마지막 내용을 그대로 보여 준다. 열 때마다 판을 새로 올린다
|
||||||
|
const [last, setLast] = useState<SheetState>(next);
|
||||||
|
const [isOpen, setIsOpen] = useState(next != null);
|
||||||
|
const [opens, setOpens] = useState(0);
|
||||||
|
if (next && next !== last) setLast(next);
|
||||||
|
if ((next != null) !== isOpen) {
|
||||||
|
setIsOpen(next != null);
|
||||||
|
if (next) setOpens((n) => n + 1);
|
||||||
|
}
|
||||||
|
const state = next ?? last;
|
||||||
|
const { open } = useSheet();
|
||||||
|
const { bottom } = useSafeAreaInsets();
|
||||||
|
const [gakTitle, setGakTitle] = useState('');
|
||||||
|
const [articleTitle, setArticleTitle] = useState('');
|
||||||
|
|
||||||
|
const then = state?.type === 'login' ? state.then : undefined;
|
||||||
|
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal visible={next != null} transparent animationType="fade" onRequestClose={onClose} statusBarTranslucent>
|
||||||
|
{/* 안드로이드도 화면 끝까지 그려(edge-to-edge) 창이 줄지 않으니 양쪽 모두 키보드 높이만큼 밀어 올린다 */}
|
||||||
|
<KeyboardAvoidingView behavior="padding" className="flex-1 justify-end">
|
||||||
|
<Pressable onPress={onClose} accessibilityLabel="닫기" className="absolute inset-0 bg-[rgb(20_26_45/0.45)]" />
|
||||||
|
{state && (
|
||||||
|
<Rise key={opens}>
|
||||||
|
<View accessibilityViewIsModal accessibilityLabel={title} className="w-full max-w-[440px] shrink rounded-t-[22px] bg-card" style={{ paddingBottom: bottom }}>
|
||||||
|
<View className="border-b border-line px-4 pt-2 pb-2.5">
|
||||||
|
<View className="mb-2.5 h-1 w-10 self-center rounded-full bg-line" />
|
||||||
|
<Text numberOfLines={1} className="px-10 text-center text-[15px] font-extrabold text-ink">
|
||||||
|
{title}
|
||||||
|
</Text>
|
||||||
|
<Pressable onPress={onClose} hitSlop={10} accessibilityRole="button" accessibilityLabel="닫기" className="absolute right-3 bottom-2 size-[30px] items-center justify-center">
|
||||||
|
<Text className="text-xl text-ink2">×</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
|
||||||
|
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
|
||||||
|
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
|
||||||
|
{state.type === 'comments' && <CommentsSheet postId={state.postId} draft={state.draft} />}
|
||||||
|
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
|
||||||
|
{state.type === 'me' && <MeSheet onDone={onClose} />}
|
||||||
|
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||||
|
</View>
|
||||||
|
</Rise>
|
||||||
|
)}
|
||||||
|
</KeyboardAvoidingView>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { setTokens } from '@nalssigak/shared/api/auth';
|
||||||
|
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Pressable } from 'react-native';
|
||||||
|
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
import { useAuth } from '@/lib/auth';
|
||||||
|
|
||||||
|
import { GoogleButton } from './google';
|
||||||
|
import { MeSheet } from './me';
|
||||||
|
import { Body, ErrorLine } from './parts';
|
||||||
|
|
||||||
|
export function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
|
||||||
|
const { me } = useAuth();
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
const done = (res: ResAuth) => {
|
||||||
|
if (!res.result?.success || !res.access_token) {
|
||||||
|
setError('구글로 로그인하지 못했어요. 다시 해 주세요.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTokens(res.access_token, res.refresh_token ?? null);
|
||||||
|
onLoggedIn();
|
||||||
|
};
|
||||||
|
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.');
|
||||||
|
|
||||||
|
if (me) return <MeSheet onDone={onDone} />;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Body className="gap-2.5">
|
||||||
|
<Text className="text-center text-sm font-semibold text-ink2">좋아요·댓글은 로그인한 뒤에 할 수 있어요.</Text>
|
||||||
|
<GoogleButton
|
||||||
|
onResult={(res) => {
|
||||||
|
setError('');
|
||||||
|
done(res);
|
||||||
|
}}
|
||||||
|
onFail={fail}
|
||||||
|
/>
|
||||||
|
<ErrorLine text={error} />
|
||||||
|
<Pressable onPress={onDone} className="rounded-[14px] p-[13px]">
|
||||||
|
<Text className="text-center text-[15px] font-extrabold text-ink2">나중에 할게요</Text>
|
||||||
|
</Pressable>
|
||||||
|
</Body>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
import { clearTokens } from '@nalssigak/shared/api/auth';
|
||||||
|
import { listBlockedOptions, listBlockedQueryKey, meQueryKey, unblockMutation, updateMeMutation, withdrawMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import { AVATAR_COLORS, CHARACTERS, MOODS } from '@nalssigak/shared/lib';
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Pressable, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
|
||||||
|
import { Avatar, Ic } from '@/components/ui';
|
||||||
|
import { useAuth } from '@/lib/auth';
|
||||||
|
|
||||||
|
import { isCommentList } from './comments';
|
||||||
|
import { Body, Field, useSoft } from './parts';
|
||||||
|
|
||||||
|
/** 탈퇴: 한 번 더 묻고 지운다. 계정이 없어지니 이 기기 토큰도 지운다 */
|
||||||
|
function Withdraw({ onDone }: { onDone: () => void }) {
|
||||||
|
const withdraw = useMutation(withdrawMutation());
|
||||||
|
const [asking, setAsking] = useState(false);
|
||||||
|
const [failed, setFailed] = useState(false);
|
||||||
|
if (!asking)
|
||||||
|
return (
|
||||||
|
<Pressable onPress={() => setAsking(true)} hitSlop={8} className="self-center p-1">
|
||||||
|
<Text className="text-[13px] font-semibold text-ink3">탈퇴하기</Text>
|
||||||
|
</Pressable>
|
||||||
|
);
|
||||||
|
const run = () => {
|
||||||
|
setFailed(false);
|
||||||
|
withdraw.mutate(
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
onSuccess: (res) => {
|
||||||
|
if (!res.result?.success) return setFailed(true);
|
||||||
|
clearTokens();
|
||||||
|
onDone();
|
||||||
|
},
|
||||||
|
onError: () => setFailed(true),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<View className="gap-2.5 rounded-[18px] p-3.5" style={{ backgroundColor: 'rgb(255 59 92 / 0.08)' }} accessibilityRole="alert">
|
||||||
|
<Text className="text-center text-sm font-bold text-ink">{'탈퇴하면 계정과 남긴 댓글·좋아요가\n모두 지워져요. 되돌릴 수 없어요.'}</Text>
|
||||||
|
<View className="flex-row gap-2">
|
||||||
|
<Pressable onPress={() => setAsking(false)} disabled={withdraw.isPending} className="flex-1 rounded-[14px] bg-card p-3">
|
||||||
|
<Text className="text-center text-sm font-extrabold text-ink">그만둘게요</Text>
|
||||||
|
</Pressable>
|
||||||
|
<Pressable onPress={run} disabled={withdraw.isPending} className="flex-1 rounded-[14px] bg-heart p-3 disabled:opacity-60">
|
||||||
|
<Text className="text-center text-sm font-extrabold text-white">탈퇴할게요</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
{failed && <Text className="text-center text-[13px] font-bold text-heart">탈퇴하지 못했어요. 잠시 뒤에 다시 해 주세요.</Text>}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 차단한 사람: 있을 때만 보이고, 풀면 그 사람 댓글이 다시 보인다 */
|
||||||
|
function Blocked() {
|
||||||
|
const s = useSoft();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const list = useQuery(listBlockedOptions());
|
||||||
|
const unblock = useMutation(unblockMutation());
|
||||||
|
const [failed, setFailed] = useState(false);
|
||||||
|
const users = list.data?.users ?? [];
|
||||||
|
if (!users.length) return null;
|
||||||
|
const release = (user_id: string) => {
|
||||||
|
setFailed(false);
|
||||||
|
unblock.mutate(
|
||||||
|
{ path: { user_id } },
|
||||||
|
{
|
||||||
|
onSuccess: (res) => {
|
||||||
|
if (!res.result?.success) return setFailed(true);
|
||||||
|
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() });
|
||||||
|
queryClient.invalidateQueries({ predicate: isCommentList });
|
||||||
|
},
|
||||||
|
onError: () => setFailed(true),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<View accessibilityLabel="차단한 사람">
|
||||||
|
<Text className="mb-2 text-sm font-extrabold text-ink">차단한 사람</Text>
|
||||||
|
<View className="gap-2">
|
||||||
|
{users.map((u) => (
|
||||||
|
<View key={u.user_id} className="flex-row items-center gap-2.5">
|
||||||
|
<Avatar character={u.character} color={u.color} />
|
||||||
|
<Text className="flex-1 text-sm font-bold text-ink">{u.nickname}</Text>
|
||||||
|
<Pressable onPress={() => release(u.user_id)} disabled={unblock.isPending} className="rounded-[12px] px-3 py-2 disabled:opacity-50" style={{ backgroundColor: s.soft }}>
|
||||||
|
<Text className="text-[13px] font-extrabold text-ink">풀기</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
{failed && <Text className="mt-1.5 text-[13px] font-bold text-heart">잠시 뒤에 다시 해 주세요.</Text>}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 내 정보: 캐릭터·배경색·기분·닉네임·로그아웃·차단한 사람·탈퇴 */
|
||||||
|
export function MeSheet({ onDone }: { onDone: () => void }) {
|
||||||
|
const { me, logout } = useAuth();
|
||||||
|
const s = useSoft();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const update = useMutation(updateMeMutation());
|
||||||
|
const [nickname, setNickname] = useState(me?.nickname ?? '');
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
if (!me) return null;
|
||||||
|
|
||||||
|
const save = (body: { nickname?: string; character?: string; color?: string; mood?: string }) => {
|
||||||
|
setError('');
|
||||||
|
update.mutate(
|
||||||
|
{ body },
|
||||||
|
{
|
||||||
|
onSuccess: (res) => {
|
||||||
|
if (!res.result?.success) return setError(res.result?.desc === 'INVALID_INPUT' ? '닉네임은 2~12자로 써 주세요.' : '잠시 뒤에 다시 해 주세요.');
|
||||||
|
queryClient.setQueryData(meQueryKey(), res);
|
||||||
|
// 댓글에 보이는 내 캐릭터·닉네임도 바뀐다
|
||||||
|
queryClient.invalidateQueries({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments' });
|
||||||
|
},
|
||||||
|
onError: () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.'),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 저장하는 동안은 고른 값을 바로 선택으로 보여 준다. 실패하면 me 값으로 돌아간다
|
||||||
|
const saving = update.isPending ? update.variables?.body : undefined;
|
||||||
|
const character = saving?.character ?? me.character;
|
||||||
|
const color = saving?.color ?? me.color;
|
||||||
|
const mood = saving?.mood ?? me.mood;
|
||||||
|
const nick = nickname.trim();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Body className="gap-3">
|
||||||
|
<View className="items-center gap-1.5">
|
||||||
|
<Avatar character={me.character} color={me.color} mood={me.mood} size={64} />
|
||||||
|
<Text className="text-center text-sm font-semibold text-ink2">{me.login_id}(으)로 로그인했어요</Text>
|
||||||
|
</View>
|
||||||
|
<View accessibilityLabel="내 캐릭터">
|
||||||
|
<Text className="mb-2 text-sm font-extrabold text-ink">내 캐릭터</Text>
|
||||||
|
<View className="flex-row flex-wrap gap-2">
|
||||||
|
{CHARACTERS.map(([key, label]) => (
|
||||||
|
<Pressable
|
||||||
|
key={key}
|
||||||
|
accessibilityRole="radio"
|
||||||
|
accessibilityState={{ checked: character === key }}
|
||||||
|
disabled={update.isPending}
|
||||||
|
onPress={() => save({ character: key })}
|
||||||
|
className={`items-center gap-1 rounded-[18px] border-2 py-2.5 ${character === key ? 'border-orange' : 'border-transparent'}`}
|
||||||
|
style={{ width: '31.5%', backgroundColor: s.field }}
|
||||||
|
>
|
||||||
|
<Ic name={key} size={48} />
|
||||||
|
<Text className={`font-jua text-[15px] ${character === key ? 'text-orange' : 'text-ink'}`}>{label}</Text>
|
||||||
|
</Pressable>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<View accessibilityLabel="배경색">
|
||||||
|
<Text className="mb-2 text-sm font-extrabold text-ink">배경색</Text>
|
||||||
|
<View className="flex-row flex-wrap gap-2.5">
|
||||||
|
{Object.entries(AVATAR_COLORS).map(([key, hex]) => (
|
||||||
|
<Pressable
|
||||||
|
key={key}
|
||||||
|
accessibilityRole="radio"
|
||||||
|
accessibilityState={{ checked: color === key }}
|
||||||
|
accessibilityLabel={key}
|
||||||
|
disabled={update.isPending}
|
||||||
|
onPress={() => save({ color: key })}
|
||||||
|
className={`size-9 rounded-full border-[3px] ${color === key ? 'border-ink' : 'border-white'}`}
|
||||||
|
style={{ backgroundColor: hex }}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<View accessibilityLabel="오늘 기분">
|
||||||
|
<Text className="mb-2 text-sm font-extrabold text-ink">오늘 기분</Text>
|
||||||
|
<View className="flex-row flex-wrap gap-2">
|
||||||
|
{MOODS.map(([key, emoji, label]) => (
|
||||||
|
<Pressable
|
||||||
|
key={key}
|
||||||
|
accessibilityRole="radio"
|
||||||
|
accessibilityState={{ checked: mood === key }}
|
||||||
|
disabled={update.isPending}
|
||||||
|
onPress={() => save({ mood: mood === key ? '' : key })}
|
||||||
|
className={`items-center gap-0.5 rounded-[14px] border-2 py-2 ${mood === key ? 'border-orange' : 'border-transparent'}`}
|
||||||
|
style={{ width: '23%', backgroundColor: s.field }}
|
||||||
|
>
|
||||||
|
<Text className="text-[22px] leading-[26px]">{emoji}</Text>
|
||||||
|
<Text className={`text-xs font-bold ${mood === key ? 'text-orange' : 'text-ink2'}`}>{label}</Text>
|
||||||
|
</Pressable>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
<Text className="mt-1.5 text-xs font-semibold text-ink3">한 번 더 누르면 지워져요</Text>
|
||||||
|
</View>
|
||||||
|
<View className="flex-row items-center gap-2">
|
||||||
|
<View className="flex-1">
|
||||||
|
<Field value={nickname} onChangeText={setNickname} maxLength={12} accessibilityLabel="닉네임" placeholder="닉네임 (2~12자)" onSubmitEditing={() => nick.length >= 2 && save({ nickname: nick })} />
|
||||||
|
</View>
|
||||||
|
<Pressable onPress={() => save({ nickname: nick })} disabled={update.isPending || nick === me.nickname || nick.length < 2} className="rounded-[14px] bg-ink-btn px-4 py-3 disabled:opacity-40">
|
||||||
|
<Text className="text-sm font-extrabold text-white">{saving?.nickname != null ? '저장 중…' : '바꾸기'}</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
<Text className={`min-h-5 text-center text-[13px] font-bold ${saving ? 'text-ink2' : 'text-heart'}`}>{saving ? (saving.nickname == null ? '저장 중…' : '') : error}</Text>
|
||||||
|
<Pressable
|
||||||
|
onPress={() => {
|
||||||
|
logout();
|
||||||
|
onDone();
|
||||||
|
}}
|
||||||
|
className="rounded-[14px] p-[13px]"
|
||||||
|
style={{ backgroundColor: s.soft }}
|
||||||
|
>
|
||||||
|
<Text className="text-center text-[15px] font-extrabold text-ink">로그아웃</Text>
|
||||||
|
</Pressable>
|
||||||
|
<Blocked />
|
||||||
|
<Withdraw onDone={onDone} />
|
||||||
|
</Body>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import type { ReactNode, Ref } from 'react';
|
||||||
|
import { ScrollView, TextInput, View, type TextInputProps } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
import Svg, { Path } from 'react-native-svg';
|
||||||
|
|
||||||
|
import { Skel } from '@/components/ui';
|
||||||
|
import { useSky } from '@/lib/sky';
|
||||||
|
|
||||||
|
/** 웹의 연한 판(#f3f6fb)·입력칸·따뜻한 판(#fff4ec)을 밤엔 어두운 판으로 */
|
||||||
|
export function useSoft() {
|
||||||
|
const night = useSky().kind === 'night';
|
||||||
|
return {
|
||||||
|
soft: night ? '#2b3470' : '#f3f6fb',
|
||||||
|
field: night ? '#2b3470' : '#f7f9fc',
|
||||||
|
fieldBorder: night ? 'rgba(255,255,255,0.12)' : '#dfe5ee',
|
||||||
|
warm: night ? 'rgba(255,138,87,0.16)' : '#fff4ec',
|
||||||
|
bar: night ? 'rgba(255,255,255,0.12)' : '#e3eaf4',
|
||||||
|
placeholder: night ? '#a1a9db' : '#8a92aa',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Body({ children, className }: { children: ReactNode; className?: string }) {
|
||||||
|
return (
|
||||||
|
<ScrollView className="shrink" contentContainerClassName={`px-4 pt-3.5 pb-[18px] ${className ?? ''}`} keyboardShouldPersistTaps="handled">
|
||||||
|
{children}
|
||||||
|
</ScrollView>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 입력칸: 둥근 연한 판 */
|
||||||
|
export function Field({ round = false, style, ...props }: TextInputProps & { round?: boolean; ref?: Ref<TextInput> }) {
|
||||||
|
const s = useSoft();
|
||||||
|
return (
|
||||||
|
<TextInput
|
||||||
|
placeholderTextColor={s.placeholder}
|
||||||
|
className={`px-3.5 text-[16px] text-ink ${round ? 'rounded-full py-2.5' : 'rounded-[14px] py-3'}`}
|
||||||
|
style={[{ backgroundColor: s.field, borderWidth: 1, borderColor: s.fieldBorder }, style]}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function HeartIcon({ size, fill, stroke }: { size: number; fill: string; stroke: string }) {
|
||||||
|
return (
|
||||||
|
<Svg viewBox="0 0 24 24" width={size} height={size} fill={fill} stroke={stroke} strokeWidth={2}>
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const N3 = [0, 1, 2];
|
||||||
|
|
||||||
|
/** 읽을거리·이번 주 특집: 그림 150px · 머리말 · 제목 · 본문 */
|
||||||
|
export function ArticleSkel() {
|
||||||
|
return (
|
||||||
|
<View className="gap-2.5">
|
||||||
|
<View className="h-[150px] rounded-[20px] bg-skel" />
|
||||||
|
<Skel className="w-24" />
|
||||||
|
<Skel className="h-6 w-4/5" />
|
||||||
|
{N3.map((k) => (
|
||||||
|
<View key={k} className="gap-1.5">
|
||||||
|
<Skel className="w-full" />
|
||||||
|
<Skel className="w-2/3" />
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 빨간 안내 한 줄 (자리 높이는 그대로) */
|
||||||
|
export function ErrorLine({ text, className }: { text?: string; className?: string }) {
|
||||||
|
return <Text className={`min-h-5 text-center text-[13px] font-bold text-heart ${className ?? ''}`}>{text ?? ''}</Text>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { listRegionsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||||
|
import { loadOf } from '@nalssigak/shared/lib';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useDeferredValue, useEffect, useRef, useState } from 'react';
|
||||||
|
import { Pressable, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
|
||||||
|
import { Skel, StateBox } from '@/components/ui';
|
||||||
|
import { useAuth } from '@/lib/auth';
|
||||||
|
import { useRegion } from '@/lib/region';
|
||||||
|
import { useSheet } from '@/lib/sheet';
|
||||||
|
|
||||||
|
import { Body, Field } from './parts';
|
||||||
|
|
||||||
|
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const;
|
||||||
|
|
||||||
|
const N14 = Array.from({ length: 14 }, (_, i) => i);
|
||||||
|
|
||||||
|
function RegionsSkel() {
|
||||||
|
return (
|
||||||
|
<View className="mt-2">
|
||||||
|
{N14.map((i) => (
|
||||||
|
<View key={i} className="border-b-[1.5px] border-line px-1 py-3.5">
|
||||||
|
<Skel className="w-28" />
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 지역 바꾸기: 지금 위치로 찾기 + 구 이름으로 찾기 + 목록 */
|
||||||
|
export function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||||
|
const { region, setRegion, locate, locateStatus } = useRegion();
|
||||||
|
const alive = useRef(true);
|
||||||
|
useEffect(() => {
|
||||||
|
alive.current = true;
|
||||||
|
return () => {
|
||||||
|
alive.current = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
const { me, logout } = useAuth();
|
||||||
|
const { open } = useSheet();
|
||||||
|
const [q, setQ] = useState('');
|
||||||
|
const deferred = useDeferredValue(q.trim());
|
||||||
|
const list = useQuery(listRegionsOptions(deferred ? { query: { q: deferred } } : undefined));
|
||||||
|
const regions = list.data?.regions ?? [];
|
||||||
|
const listLoad = loadOf(list);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Body>
|
||||||
|
<Pressable onPress={() => locate(() => alive.current && onDone())} disabled={locateStatus === 'locating'} className="items-center rounded-full border-b-[5px] border-orange-deep bg-orange p-3 disabled:opacity-60">
|
||||||
|
<Text className="font-jua text-[17px] text-white">지금 위치로 찾기</Text>
|
||||||
|
</Pressable>
|
||||||
|
<Text className="mt-2 min-h-5 text-center text-[13px] font-bold text-ink2" accessibilityLiveRegion="polite">
|
||||||
|
{LOCATE_TEXT[locateStatus]}
|
||||||
|
</Text>
|
||||||
|
<Field round value={q} onChangeText={setQ} placeholder="구 이름으로 찾기 (예: 마포)" accessibilityLabel="구 이름으로 찾기" />
|
||||||
|
{listLoad === 'loading' && <RegionsSkel />}
|
||||||
|
{listLoad !== 'loading' && !regions.length && (listLoad === 'ready' ? <StateBox load={listLoad} empty="찾는 구가 없어요." /> : <StateBox load={listLoad} onRetry={() => list.refetch()} hold={<RegionsSkel />} boxClassName="inset-x-0 top-2 bottom-0" />)}
|
||||||
|
<View className={`mt-2 ${list.isPlaceholderData ? 'opacity-60' : ''}`}>
|
||||||
|
{regions.map((r) => {
|
||||||
|
const here = r.code === region.code;
|
||||||
|
return (
|
||||||
|
<Pressable
|
||||||
|
key={r.code}
|
||||||
|
accessibilityState={{ selected: here }}
|
||||||
|
onPress={() => {
|
||||||
|
setRegion(r);
|
||||||
|
onDone();
|
||||||
|
}}
|
||||||
|
className="flex-row items-center justify-between border-b-[1.5px] border-line px-1 py-3"
|
||||||
|
>
|
||||||
|
<Text className={`font-jua text-[17px] ${here ? 'text-orange' : 'text-ink'}`}>{r.name}</Text>
|
||||||
|
{here && <Text className="text-xs font-extrabold text-orange">지금 보는 곳</Text>}
|
||||||
|
</Pressable>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</View>
|
||||||
|
<View className="mt-4 flex-row items-center justify-center gap-2">
|
||||||
|
<Text className="text-[13px] font-bold text-ink2">{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'}</Text>
|
||||||
|
<Pressable onPress={me ? logout : () => open({ type: 'login' })} hitSlop={8}>
|
||||||
|
<Text className="text-[13px] font-extrabold text-rain">{me ? '로그아웃' : '로그인'}</Text>
|
||||||
|
</Pressable>
|
||||||
|
</View>
|
||||||
|
</Body>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import type { TimeKind } from '@nalssigak/shared/lib';
|
||||||
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
import { StyleSheet, View, type DimensionValue } from 'react-native';
|
||||||
|
import Animated, { cancelAnimation, Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
|
||||||
|
|
||||||
|
import { useSky } from '@/lib/sky';
|
||||||
|
|
||||||
|
const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night'];
|
||||||
|
|
||||||
|
const SKY: Record<TimeKind, { colors: readonly [string, string, string]; locations: readonly [number, number, number] }> = {
|
||||||
|
morning: { colors: ['#ffe0c4', '#fff0e2', '#e4f2ff'], locations: [0, 0.38, 1] },
|
||||||
|
day: { colors: ['#cde7ff', '#e9f5ff', '#f7fbff'], locations: [0, 0.45, 1] },
|
||||||
|
sunset: { colors: ['#ffd0b5', '#f9c3cf', '#ddd2f6'], locations: [0, 0.42, 1] },
|
||||||
|
night: { colors: ['#0e1433', '#1b2356', '#2a2e6e'], locations: [0, 0.5, 1] },
|
||||||
|
};
|
||||||
|
|
||||||
|
const STARS = Array.from({ length: 46 }, (_, i) => ({ left: `${(i * 41 + 7) % 100}%`, top: `${(i * 67 + 3) % 96}%`, size: 1 + (i % 3) * 0.8, period: (3 + (i % 5)) * 1000, delay: ((i * 0.7) % 6) * 1000 }) as const);
|
||||||
|
|
||||||
|
/** 시간대 하나의 하늘 판. 고른 시간대만 1.4초 동안 서서히 드러난다 */
|
||||||
|
function Layer({ kind, on, reduce }: { kind: TimeKind; on: boolean; reduce: boolean }) {
|
||||||
|
const shown = useSharedValue(on ? 1 : 0);
|
||||||
|
useEffect(() => {
|
||||||
|
shown.value = reduce ? (on ? 1 : 0) : withTiming(on ? 1 : 0, { duration: 1400, easing: Easing.ease });
|
||||||
|
}, [on, reduce, shown]);
|
||||||
|
const style = useAnimatedStyle(() => ({ opacity: shown.value }));
|
||||||
|
return (
|
||||||
|
<Animated.View style={[StyleSheet.absoluteFill, style]}>
|
||||||
|
<LinearGradient {...SKY[kind]} style={StyleSheet.absoluteFill} />
|
||||||
|
</Animated.View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 밤 별: 제각각 주기로 반짝인다 */
|
||||||
|
function Star({ star, reduce }: { star: (typeof STARS)[number]; reduce: boolean }) {
|
||||||
|
const glow = useSharedValue(0);
|
||||||
|
useEffect(() => {
|
||||||
|
if (reduce) return;
|
||||||
|
glow.value = withDelay(star.delay, withRepeat(withTiming(1, { duration: star.period / 2, easing: Easing.inOut(Easing.ease) }), -1, true));
|
||||||
|
return () => cancelAnimation(glow);
|
||||||
|
}, [reduce, glow, star]);
|
||||||
|
const style = useAnimatedStyle(() => ({ opacity: reduce ? 0.7 : 0.25 + glow.value * 0.75 }));
|
||||||
|
return <Animated.View style={[{ position: 'absolute', left: star.left, top: star.top, width: star.size, height: star.size, borderRadius: star.size, backgroundColor: '#fff', boxShadow: '0 0 6px rgb(255 255 255 / 0.8)' }, style]} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShootSpec = { top: DimensionValue; left: DimensionValue; len: number; dur: number; dl: number };
|
||||||
|
|
||||||
|
// 별똥별: 위치·길이·주기를 엇갈려 몇 초마다 하나씩 떨어지게 (웹 BLayout SHOOTS, 밀리초)
|
||||||
|
const SHOOTS: ShootSpec[] = [
|
||||||
|
{ top: '8%', left: '78%', len: 110, dur: 7000, dl: 1000 },
|
||||||
|
{ top: '22%', left: '46%', len: 80, dur: 9000, dl: 3500 },
|
||||||
|
{ top: '5%', left: '30%', len: 95, dur: 8000, dl: 5500 },
|
||||||
|
{ top: '36%', left: '88%', len: 70, dur: 10000, dl: 2200 },
|
||||||
|
{ top: '52%', left: '62%', len: 90, dur: 11000, dl: 7000 },
|
||||||
|
{ top: '14%', left: '96%', len: 120, dur: 12000, dl: 9000 },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 별똥별 하나: 주기 끝 14% 동안만 비스듬히 240px 미끄러지며 반짝 (웹 .b-shoot). 동작 줄이기면 그리지 않는다 */
|
||||||
|
export function Shoot({ top, left, len, dur, dl }: ShootSpec) {
|
||||||
|
const reduce = useReducedMotion();
|
||||||
|
const p = useSharedValue(0);
|
||||||
|
useEffect(() => {
|
||||||
|
if (reduce) return;
|
||||||
|
p.value = withDelay(dl, withRepeat(withTiming(1, { duration: dur, easing: Easing.in(Easing.ease) }), -1, false));
|
||||||
|
return () => cancelAnimation(p);
|
||||||
|
}, [reduce, dur, dl, p]);
|
||||||
|
const style = useAnimatedStyle(() => ({
|
||||||
|
opacity: interpolate(p.value, [0, 0.86, 0.89, 1], [0, 0, 1, 0]),
|
||||||
|
transform: [{ rotate: '-24deg' }, { translateX: interpolate(p.value, [0, 0.86, 1], [0, 0, -240]) }],
|
||||||
|
}));
|
||||||
|
if (reduce) return null;
|
||||||
|
return (
|
||||||
|
<Animated.View style={[{ position: 'absolute', top, left, width: len, height: 1.5 }, style]}>
|
||||||
|
<LinearGradient colors={['rgba(255,255,255,0)', '#ffffff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ flex: 1, borderRadius: 2 }} />
|
||||||
|
</Animated.View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 화면 전체 하늘: 시간대별 색이 서서히 바뀌고, 밤에는 별이 반짝이고 별똥별이 떨어진다 */
|
||||||
|
export function SkyBg() {
|
||||||
|
const { kind } = useSky();
|
||||||
|
const reduce = useReducedMotion();
|
||||||
|
return (
|
||||||
|
<View style={StyleSheet.absoluteFill} pointerEvents="none">
|
||||||
|
{KINDS.map((k) => (
|
||||||
|
<Layer key={k} kind={k} on={k === kind} reduce={reduce} />
|
||||||
|
))}
|
||||||
|
{kind === 'night' && STARS.map((s, i) => <Star key={i} star={s} reduce={reduce} />)}
|
||||||
|
{kind === 'night' && SHOOTS.map((s, i) => <Shoot key={i} {...s} />)}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
// 웹 b.css 노을 탭 그라데이션. 등급별 하늘색(히어로·3일 타일)과 시간표 막대
|
||||||
|
type Grad = { colors: readonly [string, string, ...string[]]; locations?: readonly [number, number, ...number[]] };
|
||||||
|
|
||||||
|
export const GRADE_SKY: Record<string, { hero: Grad; tile: Grad }> = {
|
||||||
|
잿빛: { hero: { colors: ['#6f7690', '#9aa0b4', '#b9b4c0'], locations: [0, 0.55, 1] }, tile: { colors: ['#8f8aa5', '#b9b0bf'] } },
|
||||||
|
은은함: { hero: { colors: ['#4b5aa8', '#7f86c6', '#e9b9a8', '#ffb27a'], locations: [0, 0.4, 0.78, 1] }, tile: { colors: ['#7f86c6', '#e9b9a8', '#f6b07a'], locations: [0, 0.7, 1] } },
|
||||||
|
고움: { hero: { colors: ['#5b3f9e', '#c2559a', '#ff7a6a', '#ffb35c'], locations: [0, 0.45, 0.78, 1] }, tile: { colors: ['#5b3f9e', '#c2559a', '#ff7a6a'], locations: [0, 0.55, 1] } },
|
||||||
|
붉음: { hero: { colors: ['#4a2a8a', '#b0306a', '#ff4a3a', '#ff9a3c'], locations: [0, 0.4, 0.72, 1] }, tile: { colors: ['#4a2a8a', '#b0306a', '#ff4a3a'], locations: [0, 0.5, 1] } },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const skyOf = (grade?: string | null) => GRADE_SKY[grade ?? ''] ?? GRADE_SKY['은은함'];
|
||||||
|
|
||||||
|
export const RAIL = {
|
||||||
|
sunset: { colors: ['#f2b84b', '#f6844e', '#e8506a', '#8c5aa6', '#2d3f8f'], locations: [0, 0.45, 0.62, 0.82, 1] },
|
||||||
|
sunrise: { colors: ['#2d3f8f', '#8c5aa6', '#e8506a', '#f6844e', '#f2b84b'], locations: [0, 0.25, 0.45, 0.6, 1] },
|
||||||
|
} satisfies Record<string, Grad>;
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import type { BestTime, SkyPlanData } from '@nalssigak/shared/api/client/types.gen';
|
||||||
|
import { clockShort } from '@nalssigak/shared/lib';
|
||||||
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
|
import { useState, type ReactNode } from 'react';
|
||||||
|
import { Pressable, View } from 'react-native';
|
||||||
|
import { Text } from '@/components/text';
|
||||||
|
import { useCSSVariable } from 'uniwind';
|
||||||
|
|
||||||
|
import { RAIL, skyOf } from '@/components/sky/colors';
|
||||||
|
import { SitSun, Skyline } from '@/components/sky/skyline';
|
||||||
|
import { MapLink, Skel } from '@/components/ui';
|
||||||
|
|
||||||
|
const SHADOW = { textShadowColor: 'rgb(50 25 70 / 0.35)', textShadowOffset: { width: 0, height: 2 }, textShadowRadius: 10 };
|
||||||
|
const FOUR = [0, 1, 2, 3];
|
||||||
|
|
||||||
|
/** 히어로엔 답만: 노을 피크 시각과 어떻게 물드는지. 상자는 불러오는 중·실패·빈 값 모두 같은 크기 */
|
||||||
|
export function SkyHero({ plan, children }: { plan?: SkyPlanData; children?: ReactNode }) {
|
||||||
|
const g = skyOf(plan?.grade_label).hero;
|
||||||
|
return (
|
||||||
|
<View className="mx-3 mt-1 min-h-[230px] overflow-hidden rounded-[32px] px-5 pt-5 pb-14">
|
||||||
|
<LinearGradient colors={g.colors} locations={g.locations} style={{ position: 'absolute', inset: 0 }} />
|
||||||
|
<SitSun />
|
||||||
|
<Skyline />
|
||||||
|
{children ?? (
|
||||||
|
<View>
|
||||||
|
{plan ? (
|
||||||
|
<Text className="font-jua text-[28px] leading-tight text-white" style={SHADOW}>
|
||||||
|
{plan.title}
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<Skel className="h-7 w-[230px]" />
|
||||||
|
)}
|
||||||
|
{!plan ? (
|
||||||
|
<Skel className="mt-2 w-[180px]" />
|
||||||
|
) : plan.situation_label ? (
|
||||||
|
<Text className="mt-1.5 text-[15px] font-bold text-white" style={SHADOW}>
|
||||||
|
{plan.situation_label}
|
||||||
|
</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 오늘·내일·모레를 그날 예상 하늘색 타일로. 누르면 그날로 */
|
||||||
|
export function DayTiles({ plans, day, onPick }: { plans: SkyPlanData[]; day?: string; onPick: (day: string) => void }) {
|
||||||
|
const ink = String(useCSSVariable('--color-ink'));
|
||||||
|
return (
|
||||||
|
<View className="mx-3 mt-2.5 flex-row gap-2">
|
||||||
|
{plans.map((p) => {
|
||||||
|
const g = skyOf(p.grade_label).tile;
|
||||||
|
const on = p.day === day;
|
||||||
|
return (
|
||||||
|
<Pressable key={p.day} accessibilityState={{ selected: on }} onPress={() => onPick(p.day)} className="flex-1 rounded-[18px] p-[2px]" style={{ borderWidth: 3, borderColor: on ? ink : 'transparent' }}>
|
||||||
|
<View className="overflow-hidden rounded-2xl px-2.5 pt-2 pb-2.5">
|
||||||
|
<LinearGradient colors={g.colors} locations={g.locations} start={{ x: 0.2, y: 0 }} end={{ x: 0.8, y: 1 }} style={{ position: 'absolute', inset: 0 }} />
|
||||||
|
<Text className="text-[11.5px] font-extrabold text-white">{p.when}</Text>
|
||||||
|
<Text className="font-jua text-lg leading-tight text-white">{p.best_at ? clockShort(p.best_at) : '–'}</Text>
|
||||||
|
<Text className="text-[11.5px] font-bold text-white">
|
||||||
|
{p.grade_label} {p.score}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
</Pressable>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Toggle({ label, children, end }: { label: ReactNode; children: ReactNode; end?: boolean }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
return (
|
||||||
|
<View>
|
||||||
|
<Pressable onPress={() => setOpen(!open)} accessibilityState={{ expanded: open }} className={`flex-row items-center gap-1.5 ${end ? 'justify-between' : ''}`}>
|
||||||
|
{label}
|
||||||
|
</Pressable>
|
||||||
|
{open && children}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const Q = ({ className = 'bg-card/80' }: { className?: string }) => (
|
||||||
|
<View className={`size-[18px] items-center justify-center rounded-full ${className}`}>
|
||||||
|
<Text className="text-[11px] font-extrabold text-ink">?</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 노을 점수 뜻. 지금 하늘이 아니라 해 질(뜰) 무렵 예보라는 것도 */
|
||||||
|
export function ScoreHelp({ plan }: { plan: SkyPlanData }) {
|
||||||
|
const sunAt = plan.timeline?.find((t) => t.kind === 'sun')?.at;
|
||||||
|
const rise = plan.kind === 'sunrise';
|
||||||
|
return (
|
||||||
|
<View className="mx-3 mt-1.5 px-1">
|
||||||
|
<Toggle
|
||||||
|
end
|
||||||
|
label={
|
||||||
|
<>
|
||||||
|
<Text className="text-[12px] font-bold text-ink2">노을 점수 100점 만점 · 높을수록 붉어요</Text>
|
||||||
|
<Q />
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Text className="mt-1.5 rounded-xl bg-card/70 px-2.5 py-2 text-[12px] leading-snug font-semibold text-ink2">
|
||||||
|
80점 넘으면 붉게, 60점 넘으면 곱게, 40점 넘으면 은은하게 물들어요.
|
||||||
|
{sunAt && ` 해 ${rise ? '뜰' : '질'} 무렵(${new Date(sunAt).getHours()}시) 날씨 예보로 계산했고, 노을 피크 시각은 해 ${rise ? '뜨기 10~20분 전' : '지고 10~20분 뒤'}로 어림한 거라 실제와 다를 수 있어요.`}
|
||||||
|
</Text>
|
||||||
|
</Toggle>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 언제 보면 좋을까: 왼쪽 세로 줄 색이 그 시각 하늘색, 노을 피크만 강조 */
|
||||||
|
export function Timeline({ rows, kind = 'sunset' }: { rows?: BestTime[]; kind?: SkyPlanData['kind'] }) {
|
||||||
|
const rail = RAIL[kind === 'sunrise' ? 'sunrise' : 'sunset'];
|
||||||
|
const list = rows ?? FOUR.map(() => undefined);
|
||||||
|
return (
|
||||||
|
<View className="mx-3 mt-3 rounded-[22px] border-b-[5px] border-shade bg-card px-4 pt-3.5 pb-3">
|
||||||
|
<View className="flex-row gap-3">
|
||||||
|
<LinearGradient colors={rail.colors} locations={rail.locations} style={{ width: 12, borderRadius: 6 }} />
|
||||||
|
<View className="flex-1">
|
||||||
|
{list.map((t, i) => {
|
||||||
|
const peak = t?.kind === 'peak';
|
||||||
|
return (
|
||||||
|
<View key={t?.kind ?? i} className={`flex-row items-baseline gap-2.5 ${peak ? '-mx-1.5 my-0.5 rounded-xl bg-[#fff1f2] px-2.5 py-2' : 'py-1.5'}`} style={!peak && i < list.length - 1 ? { borderBottomWidth: 1 } : undefined}>
|
||||||
|
<View className="min-w-[96px]">
|
||||||
|
{t ? <Text className={`font-jua ${peak ? 'text-[20px] text-[#d23d5a]' : 'text-[17px] text-ink'}`}>{t.end ? `${clockShort(t.at)}~${clockShort(t.end)}` : clockShort(t.at)}</Text> : <Skel className="w-11" />}
|
||||||
|
</View>
|
||||||
|
{t ? <Text className={`flex-1 ${peak ? 'font-jua text-base text-[#d23d5a]' : 'text-[13.5px] font-bold text-ink2'}`}>{t.label}</Text> : <Skel className="w-20" />}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
{rows && (
|
||||||
|
<View className="mt-2">
|
||||||
|
<Toggle
|
||||||
|
label={
|
||||||
|
<>
|
||||||
|
<Q className="bg-[#f1ebe3]" />
|
||||||
|
<Text className="text-[12px] font-bold text-ink2">골든아워·블루아워가 뭐예요</Text>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Text className="mt-1.5 rounded-xl bg-[#faf6f1] px-2.5 py-2 text-[12px] leading-snug text-[#5a6380]">
|
||||||
|
<Text className="font-bold text-[#28304a]">골든아워</Text> 해가 {kind === 'sunrise' ? '뜬 뒤' : '지기 전'}, 햇빛이 금빛으로 물드는 시간{'\n'}
|
||||||
|
<Text className="font-bold text-[#28304a]">블루아워</Text> 해가 {kind === 'sunrise' ? '뜨기 전' : '진 뒤'}, 하늘이 짙은 파랑으로 남는 시간
|
||||||
|
</Text>
|
||||||
|
</Toggle>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ROW = 'flex-row items-center gap-2.5 px-1 py-3';
|
||||||
|
|
||||||
|
export function LiSkel({ ghost = false, last = false }: { ghost?: boolean; last?: boolean }) {
|
||||||
|
return (
|
||||||
|
<View className={`${ROW} border-line ${ghost ? 'opacity-0' : ''}`} style={last ? undefined : { borderBottomWidth: 1.5 }}>
|
||||||
|
<View className="w-[34px] items-center">
|
||||||
|
<Skel className="w-5" />
|
||||||
|
</View>
|
||||||
|
<View className="flex-1 gap-1.5">
|
||||||
|
<Skel className="h-4 w-24" />
|
||||||
|
<Skel className="w-40" />
|
||||||
|
</View>
|
||||||
|
<Skel className="w-9" />
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 번호 · 이름(+설명) · 오른쪽 값 한 줄 */
|
||||||
|
export function Li({ no, title, sub, right, mine = false, place, last = false }: { no: number; title: string; sub?: string | null; right: string; mine?: boolean; place?: string; last?: boolean }) {
|
||||||
|
return (
|
||||||
|
<View className={`${ROW} border-line ${mine ? 'rounded-2xl bg-card' : ''}`} style={last ? undefined : { borderBottomWidth: 1.5 }}>
|
||||||
|
<Text className="w-[34px] text-center font-bagel text-xl text-orange">{no}</Text>
|
||||||
|
<View className="min-w-0 flex-1">
|
||||||
|
<Text className="font-jua text-[17px] text-ink">
|
||||||
|
{place ? <MapLink place={place}>{title}</MapLink> : title}
|
||||||
|
{mine && <Text className="text-xs font-extrabold text-rain"> 내 지역</Text>}
|
||||||
|
</Text>
|
||||||
|
<Text numberOfLines={1} className="text-[12.5px] font-semibold text-ink2">
|
||||||
|
{sub || ' '}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<Text className="font-jua text-base text-ink">{right}</Text>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { View } from 'react-native';
|
||||||
|
import Svg, { Defs, Polygon, RadialGradient, Rect, Stop } from 'react-native-svg';
|
||||||
|
|
||||||
|
// 웹 .b-skyline::after 의 clip-path 를 그대로 (0~100 비율)
|
||||||
|
const POINTS = '0,55 8,55 8,30 15,30 15,50 22,50 22,10 28,10 28,45 36,45 36,25 44,25 44,55 52,55 52,35 60,35 60,5 66,5 66,40 74,40 74,20 82,20 82,50 90,50 90,30 100,30 100,100 0,100';
|
||||||
|
|
||||||
|
/** 아래에 깔리는 동네 건물 실루엣. height 는 상자 높이 대비 비율 */
|
||||||
|
export function Skyline({ height = '22%' }: { height?: `${number}%` }) {
|
||||||
|
return (
|
||||||
|
<View pointerEvents="none" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height }}>
|
||||||
|
<Svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="none">
|
||||||
|
<Polygon points={POINTS} fill="#2d2440" />
|
||||||
|
</Svg>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 건물 뒤로 지는 해 (.b-sit-sun) */
|
||||||
|
export function SitSun({ size = 112, bottom = 24, opacity = 1 }: { size?: number; bottom?: number; opacity?: number }) {
|
||||||
|
return (
|
||||||
|
<View pointerEvents="none" style={{ position: 'absolute', bottom, left: '50%', marginLeft: -size / 2, width: size, height: size, opacity }}>
|
||||||
|
<Svg width={size} height={size} viewBox="0 0 2 2">
|
||||||
|
<Defs>
|
||||||
|
<RadialGradient id="sitsun" cx="1" cy="1" r="1" gradientUnits="userSpaceOnUse">
|
||||||
|
<Stop offset="0" stopColor="#fff6dd" />
|
||||||
|
<Stop offset="0.38" stopColor="#ffd08f" />
|
||||||
|
<Stop offset="0.7" stopColor="#ffa05a" stopOpacity={0} />
|
||||||
|
</RadialGradient>
|
||||||
|
</Defs>
|
||||||
|
<Rect x="0" y="0" width="2" height="2" fill="url(#sitsun)" />
|
||||||
|
</Svg>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import Svg, { Circle, Path, Rect } from 'react-native-svg';
|
||||||
|
|
||||||
|
export type TabName = 'today' | 'gak' | 'sky' | 'week' | 'season';
|
||||||
|
|
||||||
|
const line = { fill: 'none', strokeLinecap: 'round', strokeLinejoin: 'round' } as const;
|
||||||
|
|
||||||
|
export function PinIcon({ size, color }: { size: number; color: string }) {
|
||||||
|
return (
|
||||||
|
<Svg viewBox="0 0 24 24" width={size} height={size} {...line} stroke={color} strokeWidth={2.2}>
|
||||||
|
<Path d="M12 21s7-6.2 7-11.5A7 7 0 0 0 5 9.5C5 14.8 12 21 12 21z" />
|
||||||
|
<Circle cx="12" cy="9.5" r="2.5" />
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TabIcon({ name, size, color, strokeWidth }: { name: TabName; size: number; color: string; strokeWidth: number }) {
|
||||||
|
return (
|
||||||
|
<Svg viewBox="0 0 24 24" width={size} height={size} {...line} stroke={color} strokeWidth={strokeWidth}>
|
||||||
|
{name === 'today' && <Path d="M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />}
|
||||||
|
{name === 'gak' && (
|
||||||
|
<>
|
||||||
|
<Rect x="3.5" y="3.5" width="7" height="7" rx="2" />
|
||||||
|
<Rect x="13.5" y="3.5" width="7" height="7" rx="2" />
|
||||||
|
<Rect x="3.5" y="13.5" width="7" height="7" rx="2" />
|
||||||
|
<Rect x="13.5" y="13.5" width="7" height="7" rx="2" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{name === 'sky' && <Path d="M3 18h18M6 14a6 6 0 0 1 12 0M12 4v3M4.9 7.9l2 2M19.1 7.9l-2 2M8 21h8" />}
|
||||||
|
{name === 'week' && (
|
||||||
|
<>
|
||||||
|
<Rect x="3.5" y="5" width="17" height="15.5" rx="2.5" />
|
||||||
|
<Path d="M3.5 10h17M8 3v4M16 3v4" />
|
||||||
|
<Circle cx="12" cy="15" r="1.6" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{name === 'season' && <Path d="M12 6.5C10 5 7 4.5 3.5 5v14c3.5-.5 6.5 0 8.5 1.5 2-1.5 5-2 8.5-1.5V5C17 4.5 14 5 12 6.5zM12 6.5v14" />}
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user