Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
189d51f1ce | ||
|
|
9a7e0ddc75 | ||
|
|
e5cdfa2642 | ||
|
|
6daa2f4d2a | ||
|
|
02ebcda0ea | ||
|
|
47526c1cef | ||
|
|
697c4bfb20 | ||
|
|
5a88b08a44 | ||
|
|
f6884fe9c9 | ||
|
|
c15f045c64 | ||
|
|
e40a9a0539 | ||
|
|
01b5f917b9 | ||
|
|
e8b8cc79b6 | ||
|
|
709dcf742e | ||
|
|
cab3336859 | ||
|
|
fcc7ed804c | ||
|
|
a8efb36041 | ||
|
|
afa83d8b79 | ||
|
|
d7fffc80a4 | ||
|
|
ce1d222216 | ||
|
|
ed2ab86404 | ||
|
|
ec9e3a52c4 | ||
|
|
7a73c33c73 | ||
|
|
5dc61770f4 | ||
|
|
82ca286ea4 | ||
|
|
442441931f | ||
|
|
1f040bc6d4 | ||
|
|
df34d0a1b4 | ||
|
|
b436ee0e0a | ||
|
|
9f6a6b477b | ||
|
|
cfd45c3b3a | ||
|
|
70286030b1 | ||
|
|
89ad5e1600 | ||
|
|
1c9e15500b | ||
|
|
cff44be771 | ||
|
|
26624f0888 | ||
|
|
4a110c70de | ||
|
|
19d84397ce | ||
|
|
9431dc31c2 | ||
|
|
08f9275c45 | ||
|
|
66f0bf8072 | ||
|
|
4fec164364 | ||
|
|
3c58552852 |
No files matched your search
@@ -328,6 +328,8 @@
|
||||
| [x] | 10/28 세미정장 코디(철회: 20-30대 남자에 나팔바지라는 피드백, 포스트 4903 10/28 삭제함(deleted=true)·인스타 앱에서 삭제 필요) — 킹서버 카드 23→포스트 4903, 인스타 https://www.instagram.com/p/DfBIhUdAbbV/. 참고 스냅 f20 https://www.musinsa.com/snap/1560205304641814679 · m20 https://www.musinsa.com/snap/1551785083122597386 · f40 https://www.musinsa.com/snap/1551572173880406114 · m40 https://www.musinsa.com/snap/1556284432455808475. 4장 1:1 검수. 크롬이 2번째 장 렌더에서 멈춰 장마다 프로필을 따로 써서 다시 찍음, 인스타 API는 request limit을 돌려줬지만 실제 게시됨(ig_media_id 미기록) | 사용자 요청 (10/28) | `admin/scripts/card.mjs` |
|
||||
| [x] | 10/28 세미정장 코디 다시(20-30대 남자만 교체: 오피서 코트·헨리넥 니트·다크 브라운 와이드 팬츠·헤비 부츠·토트백, 코디 구성을 먼저 확인받고 그림) — 킹서버 카드 24→포스트 4904, 인스타 https://www.instagram.com/p/DfBJ4SlAaok/. 참고 스냅 m20 https://www.musinsa.com/snap/1562338908609136514 (나머지 3명은 카드 23과 같음). 첫 그림은 상품 썸네일을 따라 바지가 베이지로 나와 스냅 색(브라운)으로 다시 그림 | 사용자 요청 (10/28) | `admin/scripts/daily-ootd.mjs` |
|
||||
| [x] | 10/28 연애 타로(단풍각·데이트각·별보기각, 새 표지: 주제 배지 + 큰 질문) — 킹서버 카드 26→포스트 4906, 인스타 https://www.instagram.com/p/DfBQCW0ARgL/ (ig_media_id 17953447719320497). 처음 올린 카드 25→포스트 4905(인스타 DfBPIHJAR0m)는 행운 포인트가 날씨 정보뿐이라는 피드백으로 철회: 포스트 4905 deleted=true, 인스타 글은 앱에서 삭제됨. 행운 포인트를 "시각 · 행운 아이템"(리딩 속 행동에 쓰는 물건)으로 바꿔 다시 게시. 문구를 먼저 확인받음: 첫 기획의 행운 포인트(6시 1도·10시 바람)를 예보 slot 값으로 고치고, 연애와 관련 없는 카드(해돋이각·테니스각)를 데이트각·별보기각으로 바꿈. 5장 1:1 검수. 인스타 API는 두 번 다 request limit을 돌려줬지만 실제 게시됨(최신 글 확인 후 재시도 안 함) | 사용자 요청 (10/28) | `admin/src/cards/templates.tsx`, `admin/scripts/plan.mjs` |
|
||||
| [x] | 10/30 나들이 타로(억새각·캠핑각·야장각, 질문 "이번 주말, 어디로 놀러 갈까요?", 행운 시각은 토요일 서울 예보) — 킹서버 카드 29→포스트 6713, 인스타 https://www.instagram.com/p/DfGhl5YgUqE/ . 인스타 API가 'Application request limit reached'를 돌려줬지만 실제로 올라가 다시 안 올림(card_set.ig_media_id 는 비어 있음). '나들이'는 대주제 배경(skin)이 없어 star 태그(#공부 #직장인)가 붙던 것을 copy.tags 로 #주말나들이 #주말뭐하지 #가을나들이 #나들이타로 로 바꿈. 관리자 서버가 옛 로컬 백엔드(9810, /v1/index/list 500)를 보고 있어 운영 API(weather.o2o.kr)로 다시 켬 | 인스타 홍보 | `admin/src/cards/templates.tsx` |
|
||||
| [x] | 10/30 할로윈 느낌 캐주얼 코디(블랙·브라운 톤 — 무신사 인기 스냅에 주황 코디가 거의 없어 할로윈 색 중 블랙·브라운으로) — 킹서버 카드 31→포스트 6714, 인스타 https://www.instagram.com/p/DfGj0zRAdhx/ (ig 17864943492694006, 첫 시도 ReadTimeout·둘째 'request limit' 응답이었지만 한 번만 올라감, card_set.ig_media_id 는 비어 있음). 참고 스냅: 20-30대 여자 https://www.musinsa.com/snap/1559108562982052217 · 20-30대 남자 https://www.musinsa.com/snap/1561961004027044406 · 40대~ 여자 https://www.musinsa.com/snap/1564225528677543586 · 40대~ 남자 https://www.musinsa.com/snap/1555156723956691019. 검수에서 스냅 사진과 달라 다시 그림: 20대 여자 플랫 검정→브라운, 40대 여자 부츠 발목→무릎 슬라우치, 40대 남자 하이넥 아이보리→브라운·신발 레이스업→스웨이드 첼시. 첫 카드 30은 반려 | 인스타 홍보 | `admin/scripts/snap.mjs` `--prefer` |
|
||||
| [x] | 각 카드 그림 미리 생성 — 가을에 나올 만한 28장(피크닉·캠핑·놀이공원·빨래·단풍·억새·테니스·골프·군고구마·붕어빵·군밤·사진산책·별보기·환기·세차·이불빨래·데이트·치맥·막걸리·파전·우산·넷플릭스·집콕·한강밤바람·멍뭉산책·센치·감성노래·낚시) + 기존 8 = 36/68. 여름·한겨울 전용 32장은 철 되면 생성 | 사용자 요청 (10/26) | `admin/src/assets/gak-card/` |
|
||||
| [ ] | 카드 자동화 다음 단계 — ① 생성 직후 자동 검사(Claude 비전: 옷 개수·사람·글자·추가 옷, 불합격 1회 재생성) ② 승인 대기 카드 메일/Teams 알림 + 서명 토큰 승인 링크(`GET /v1/card/{id}/approve`) ③ 맥 launchd 매일 06:30 `claude -p "/daily-cards"` ④ 그림 세트가 차면 킹서버로 이전 | 사용자 요청 (10/26) | `backend/router/v1/card/card.py`, `admin/scripts/` |
|
||||
| [ ] | 앱 헤더가 400~448px 폭에서 컨테이너를 넘쳐 로그인 버튼이 잘림(`frontend/src/b/BLayout.tsx` TopBar). 캡처는 456px로 찍어 피했지만 실제 폰(430·440px)에서도 잘릴 수 있음 | 10/24 캡처 중 발견 | `frontend/src/b/BLayout.tsx` |
|
||||
@@ -448,3 +450,20 @@ docs를 6개로 합칠 때 옛 내용을 그대로 옮겼다. 아래는 코드
|
||||
| [ ] | **[결정 필요]** GA4 맞춤 측정기준(이벤트 범위) 추가 등록 — `icon`(today_icon)·`sheet`(sheet_open)·`from`·`method`·`content_type`·`round`(game) | 지금 등록된 건 `gak_name`·`platform`·`region_name` 뿐이라 오늘 탭 아이콘별·창별·게임 라운드별 사용을 GA에서 못 나눔. 등록 전 데이터는 소급 안 됨 | GA4 관리 → 맞춤 정의 |
|
||||
| [ ] | **[결정 필요]** '홈 화면에 추가' 카드 손보기 — 띄우는 조건(몇 번째 방문부터)·문구, 또는 빼기 | 10/22~10/28 테스트 트래픽 뺀 77명이 봤고 누른 사람 0 (앞 주 8명 중 1명 설치) | `frontend/src/b/installBanner.tsx` |
|
||||
|
||||
|
||||
## 기념일 꾸밈 (`frontend/src/b/holiday.ts`)
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [ ] | `feat/halloween` main 병합 → 킹서버 배포(백엔드 `TalkTopic` 6~9 포함). 10/31 00시 전에 올라가야 할로윈이 켜짐 | 10/30 킹서버 작업 중이라 배포 보류 | `deploy.sh` |
|
||||
| [ ] | 할로윈 타로·코디 카드 (`/daily-tarot 할로윈`, `/daily-ootd`) — 킹서버 게시라 보류 | 10/30 킹서버 작업 중 | |
|
||||
| [ ] | 2028년부터 추석 날짜 추가 (음력이라 해마다 `ranges` 에 한 줄) | 2027-09-14~16만 들어 있음 | `frontend/src/b/holiday.ts` |
|
||||
|
||||
## 검색 클릭률 (10/30)
|
||||
|
||||
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||
|---|---|---|---|
|
||||
| [ ] | `/today`·`/tomorrow` 검색 결과 새 문구(내일 제목 '○○ 내일 날씨 · 내일 1위는 ○○각', 날짜·지역 먼저인 설명)를 지역 절반에만 배포하고, 배포 2주 뒤 Search Console에서 두 그룹 클릭률 비교 + GA `search_landing` 의 `copy` 별 유입. 기준(10/7~27 클릭률): 내일 새 그룹 0.044%·예전 그룹 0.047%, 오늘 새 그룹 0.044%·예전 그룹 0.026% | 10/30 사용자: 색인 늘리기보다 클릭률. 10/30 배포, 11/13쯤 비교 (구글이 다시 가져가야 검색 결과 문구가 바뀜) | `backend/services/seo_service.py`, `backend/services/seo_copy_test.json` |
|
||||
| [ ] | (보류) `/foliage`·`/sky`·`/week` 서버 HTML에 실제 내용 넣기 — 새 URL 없이, 단풍 상태는 화면과 같은 4단계(단풍 전·첫 단풍·절정·절정 지남), 앱이 뜬 뒤에도 화면 아래에 글 남김. 지역 단풍·지역 주말 페이지는 안 만듦 | 10/30 사용자: 클릭률 먼저 | `frontend/vite.config.ts`, `frontend/nginx.conf`, `backend/services/seo_service.py` |
|
||||
| [ ] | 주말 순위가 Redis 13시간 보관이라 06:40·18:40 갱신이 두 번 연속 실패하면 비어 보임 — 마지막 정상값 따로 보관 | 10/30 조사 중 발견 | `backend/services/weekend_rank.py`, `backend/worker_main.py` |
|
||||
| [ ] | 오늘 페이지 설명에 "강수확률 60%, 비" 와 "낮은 한강각"이 같이 나옴(10/30 성남) — 하루 중 한 시간이라도 비면 "비"로 적는 요약과 시간대별 1위 각이 어긋나 보임. 계산이 맞는지 확인 | 10/30 클릭률 조사 중 발견 | `backend/services/seo_service.py` |
|
||||
@@ -1,5 +1,6 @@
|
||||
// 무신사 스냅(공개 API)에서 오늘 날씨에 맞는 인기 코디를 사람별로 하나씩 고른다. 사진·상품 썸네일은 그림 참고용으로만 내려받고 어디에도 올리지 않는다.
|
||||
// 사용(확인용): node scripts/snap.mjs --band mild --out out/2026-10-26/snaps
|
||||
// 그날 분위기 색을 먼저 고르려면 --prefer '오렌지|브라운|카멜' (태그·글·상품명에 그 말이 있는 스냅을 앞에 둔다)
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
|
||||
@@ -147,8 +148,9 @@ function fits(snap, band) {
|
||||
return hasTop && hasBottom && slots.has('shoes') && !!snap.image
|
||||
}
|
||||
|
||||
function score(snap, persona) {
|
||||
function score(snap, persona, prefer) {
|
||||
let s = Math.log10(snap.likes + 10)
|
||||
if (prefer && (prefer.test(`${snap.tags.join(' ')} ${snap.text}`) || (snap.goods ?? []).some((g) => prefer.test(g.name)))) s += 3
|
||||
const tagBlob = snap.tags.join(' ')
|
||||
const goods = snap.goods ?? []
|
||||
if (PERSONAS[persona].mature) {
|
||||
@@ -173,7 +175,7 @@ async function download(url, path) {
|
||||
}
|
||||
|
||||
/** 사람별로 스냅 하나씩: { f20: {...snap, files: { image, thumbs[] }}, ... }. style 을 주면 네 사람 모두 그 스타일 태그가 붙은 스냅에서 고른다 */
|
||||
export async function pickSnaps({ band, style, outDir, pages = 2, log = console.log }) {
|
||||
export async function pickSnaps({ band, style, prefer, outDir, pages = 2, log = console.log }) {
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
const rule = BAND[band] ?? BAND.mild
|
||||
const styleTags = STYLE_TAGS[style] ?? []
|
||||
@@ -182,6 +184,7 @@ export async function pickSnaps({ band, style, outDir, pages = 2, log = console.
|
||||
for (const tag of styleTags) add(await listSnaps({ tags: tag }, pages * 3))
|
||||
for (const tag of rule.tags) add(await listSnaps({ tags: tag }, pages))
|
||||
for (const gender of ['WOMEN', 'MEN']) for (const kw of MATURE_KEYWORDS[gender]) add(await listSnaps({ keyword: kw }, 1))
|
||||
for (const kw of prefer ? prefer.source.split('|') : []) add(await listSnaps({ keyword: kw }, 1))
|
||||
const hasStyle = (s) => styleTags.length === 0 || s.tags.some((t) => styleTags.some((st) => t.includes(st)))
|
||||
log(`무신사 스냅 후보 ${pool.size}개 (구간 ${band}${styleTags.length ? ` · 스타일 #${styleTags.join(' #')} ${[...pool.values()].filter(hasStyle).length}개` : ''}). 상품 정보를 받아 거르는 중…`)
|
||||
|
||||
@@ -194,7 +197,7 @@ export async function pickSnaps({ band, style, outDir, pages = 2, log = console.
|
||||
// 스타일 태그가 붙은 스냅을 먼저, 모자라면 나머지 (스타일 태그 없는 스냅은 뒤로)
|
||||
const candidates = [...pool.values()]
|
||||
.filter((s) => s.gender === gender && !used.has(s.id))
|
||||
.sort((a, b) => Number(hasStyle(b)) - Number(hasStyle(a)) || score(b, persona) - score(a, persona))
|
||||
.sort((a, b) => Number(hasStyle(b)) - Number(hasStyle(a)) || score(b, persona, prefer) - score(a, persona, prefer))
|
||||
.slice(0, 60)
|
||||
let best = null
|
||||
for (const c of candidates) {
|
||||
@@ -238,5 +241,6 @@ if (process.argv[1]?.endsWith('snap.mjs')) {
|
||||
const flag = (n) => (args.includes(n) ? args[args.indexOf(n) + 1] : null)
|
||||
const band = flag('--band') ?? 'mild'
|
||||
const outDir = flag('--out') ?? `out/${new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)}/snaps`
|
||||
await pickSnaps({ band, style: flag('--style') ?? undefined, outDir, pages: Number(flag('--pages') ?? 2) })
|
||||
const prefer = flag('--prefer') ? new RegExp(flag('--prefer'), 'i') : undefined
|
||||
await pickSnaps({ band, style: flag('--style') ?? undefined, prefer, outDir, pages: Number(flag('--pages') ?? 2) })
|
||||
}
|
||||
@@ -95,7 +95,8 @@ const ootd: Template = {
|
||||
post: (d, c) => ({
|
||||
title: `오늘의 코디 · ${styleLabel(c.style)}`,
|
||||
caption: `낮 최고 ${d.maxC}도, 20대부터 40대~까지 오늘 입을 옷을 넘겨 보세요`,
|
||||
hashtags: tags(STYLE_TAGS[c.style ?? DEFAULT_STYLE] ?? [], [seasonTag(), '#여자코디', '#남자코디', '#20대코디', '#40대코디'], ['#날씨각', '#오늘의코디', '#OOTD', '#데일리룩', '#코디추천', '#오늘날씨']),
|
||||
// 그날 분위기(할로윈 등) 태그는 copy.tags(띄어쓰기로 구분)로 맨 앞에 붙인다
|
||||
hashtags: tags(c.tags ? c.tags.split(' ') : [], STYLE_TAGS[c.style ?? DEFAULT_STYLE] ?? [], [seasonTag(), '#여자코디', '#남자코디', '#20대코디', '#40대코디'], ['#날씨각', '#오늘의코디', '#OOTD', '#데일리룩', '#코디추천', '#오늘날씨']),
|
||||
}),
|
||||
warnings: (d, c) => {
|
||||
if (dailyOutfits(c)) return []
|
||||
@@ -146,7 +147,8 @@ const tarot: Template = {
|
||||
post: (_d, c) => ({
|
||||
title: `오늘의 ${c.title.replaceAll('\n', ' ').replaceAll('*', '')}`,
|
||||
caption: `Q. ${c.question} 1·2·3 중 한 장을 골라 보세요`,
|
||||
hashtags: tags(SKIN_TAGS[c.skin ?? ''] ?? [], [c.n1, c.n2, c.n3].map((n) => (n ? `#${n.replace(/각$/, '').replace(/\s/g, '')}` : undefined)), ['#날씨각', '#날씨타로', '#타로', '#오늘의타로', '#오늘의운세', '#오늘날씨']),
|
||||
// 대주제 배경(skin)과 태그가 안 맞는 주제(나들이 등)는 copy.tags(띄어쓰기로 구분)로 주제 태그를 바꾼다
|
||||
hashtags: tags(c.tags ? c.tags.split(' ') : (SKIN_TAGS[c.skin ?? ''] ?? []), [c.n1, c.n2, c.n3].map((n) => (n ? `#${n.replace(/각$/, '').replace(/\s/g, '')}` : undefined)), ['#날씨각', '#날씨타로', '#타로', '#오늘의타로', '#오늘의운세', '#오늘날씨']),
|
||||
}),
|
||||
name: '날씨 타로',
|
||||
autoPlan: true,
|
||||
|
||||
@@ -125,6 +125,10 @@ class TalkTopic(CodeEnum):
|
||||
RAIN = 3 # 비·눈
|
||||
FOLIAGE = 4 # 단풍·꽃
|
||||
OUTFIT = 5 # 오늘 옷차림
|
||||
HALLOWEEN = 6 # 기념일 주제: 그 기간에만 고를 수 있다 (frontend holiday.ts)
|
||||
PEPERO = 7
|
||||
CHRISTMAS = 8
|
||||
CHUSEOK = 9
|
||||
|
||||
|
||||
class TalkReport(CodeEnum):
|
||||
|
||||
@@ -21,17 +21,17 @@ 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), 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, is_new: bool = False) -> Res_Auth:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Auth(result=error_info(err))
|
||||
access, refresh = service.tokens(user)
|
||||
return Res_Auth(access_token=access, refresh_token=refresh, me=_me(user))
|
||||
return Res_Auth(access_token=access, refresh_token=refresh, me=_me(user), is_new=is_new)
|
||||
|
||||
|
||||
@router.post("/signup", response_model=Res_Auth, response_model_exclude_none=True, summary="회원가입 (아이디 영문 소문자·숫자·_ 4~20자, 비밀번호 8자 이상, 닉네임 2~12자)")
|
||||
async def signup(req: Req_Signup, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.signup(req.login_id, req.password, req.nickname.strip())
|
||||
return _auth(err, user, service)
|
||||
return _auth(err, user, service, is_new=True)
|
||||
|
||||
|
||||
@router.post("/login", response_model=Res_Auth, response_model_exclude_none=True, summary="로그인")
|
||||
@@ -42,8 +42,8 @@ async def login(req: Req_Login, service: AuthService = Depends()) -> Res_Auth:
|
||||
|
||||
@router.post("/toss", response_model=Res_Auth, response_model_exclude_none=True, summary="토스 로그인 (앱인토스 TossAuth.login 의 authorizationCode·referrer)")
|
||||
async def toss(req: Req_TossLogin, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.toss_login(req.authorization_code, req.referrer)
|
||||
return _auth(err, user, service)
|
||||
err, user, created = await service.toss_login(req.authorization_code, req.referrer)
|
||||
return _auth(err, user, service, is_new=created)
|
||||
|
||||
|
||||
def _check_toss_basic(authorization: Optional[str]) -> None:
|
||||
@@ -68,8 +68,8 @@ async def toss_unlink(req: Req_TossUnlink, authorization: Optional[str] = Header
|
||||
|
||||
@router.post("/google", response_model=Res_Auth, response_model_exclude_none=True, summary="구글 로그인 (처음이면 자동 닉네임으로 가입)")
|
||||
async def google_login(req: Req_Google, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.google(req.credential)
|
||||
return _auth(err, user, service)
|
||||
err, user, created = await service.google(req.credential)
|
||||
return _auth(err, user, service, is_new=created)
|
||||
|
||||
|
||||
@router.get("/config", response_model=Res_AuthConfig, response_model_exclude_none=True, summary="로그인 화면 설정 (구글 클라이언트 ID)")
|
||||
|
||||
@@ -55,6 +55,7 @@ class Res_Auth(Res_WebPacketProtocol):
|
||||
access_token: Optional[str] = None
|
||||
refresh_token: Optional[str] = None
|
||||
me: Optional[Me] = None
|
||||
is_new: Optional[bool] = Field(None, description="이번 요청으로 새로 가입한 계정이면 true (GA sign_up)")
|
||||
|
||||
|
||||
class Res_TossUnlink(Res_WebPacketProtocol):
|
||||
|
||||
@@ -183,12 +183,23 @@ class WeatherWhy(WebPacketProtocol):
|
||||
note: str = Field(description="지금 값 (예: 체감 19°, 편한 범위 18~24° 안)")
|
||||
|
||||
|
||||
class TomorrowEvent(WebPacketProtocol):
|
||||
event_id: int
|
||||
name: str
|
||||
place: str
|
||||
icon: str
|
||||
start_date: date
|
||||
end_date: date
|
||||
|
||||
|
||||
class HeroTomorrow(WebPacketProtocol):
|
||||
"""히어로 '내일' 스위치. 3시간 칸 날씨는 /v1/weather/today?day=tomorrow 로 따로 받는다."""
|
||||
"""히어로 '내일' 스위치와 내일 페이지(/tomorrow/...). 3시간 칸 날씨는 /v1/weather/today?day=tomorrow 로 따로 받는다."""
|
||||
day: date
|
||||
weather_slots: dict[str, int] = Field(default_factory=dict, description="내일 구간별 날씨 점수 {morning·day·evening·night: 점수}")
|
||||
weather_why: dict[str, list[WeatherWhy]] = Field(default_factory=dict, description="내일 구간별 날씨 점수 근거")
|
||||
top1: Optional[TopIndex] = Field(default=None, description="내일 하루 점수로 1위인 각. score·summary 는 내일 값")
|
||||
ranked: list[TopIndex] = Field(default_factory=list, description="내일 하루 점수 순위 5개 (내일 페이지 '내일의 각'). top1 이 첫째")
|
||||
events: list[TomorrowEvent] = Field(default_factory=list, description="내일 열리는 같은 시도 근처 행사 최대 3개 (내일 페이지)")
|
||||
|
||||
|
||||
class Hero(WebPacketProtocol):
|
||||
|
||||
@@ -61,19 +61,20 @@ class AuthService:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def toss_login(self, authorization_code: str, referrer: str) -> tuple[ErrorType, Optional[User]]:
|
||||
"""토스 userKey 로 계정을 찾고, 없으면 만든다. 이름·전화번호 같은 개인정보는 받지 않는다."""
|
||||
async def toss_login(self, authorization_code: str, referrer: str) -> tuple[ErrorType, Optional[User], bool]:
|
||||
"""토스 userKey 로 계정을 찾고, 없으면 만든다(셋째 값 True = 이번에 가입). 이름·전화번호 같은 개인정보는 받지 않는다."""
|
||||
if not authorization_code or referrer not in TOSS_REFERRERS:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
return ErrorType.INVALID_INPUT, None, False
|
||||
try:
|
||||
key = str(await toss_login.user_key(authorization_code, referrer))
|
||||
except toss_login.TossLoginError as e:
|
||||
LOG.error(f"[auth] toss login: {e}")
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.AUTH_FAILED, None, False
|
||||
provider = AuthProvider.TOSS.value
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, provider, key))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return err, None, False
|
||||
created = user is None
|
||||
if user is None:
|
||||
err, user = await DB_SESSION_MNG.execute_lambda_write(
|
||||
lambda s: self.crud.create_social(s, provider, key, f"toss_{key}", f"토스{key[-4:]}")
|
||||
@@ -82,30 +83,33 @@ class AuthService:
|
||||
# 같은 사람이 동시에 두 번 들어온 경우 먼저 만든 계정을 쓴다
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, provider, key))
|
||||
if err is not ErrorType.SUCCESS or user is None:
|
||||
return err if err is not ErrorType.SUCCESS else ErrorType.DB_ERROR, None
|
||||
return err if err is not ErrorType.SUCCESS else ErrorType.DB_ERROR, None, False
|
||||
created = False
|
||||
if user.status != 1:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
return ErrorType.AUTH_FAILED, None, False
|
||||
return ErrorType.SUCCESS, user, created
|
||||
|
||||
async def google(self, credential: str) -> tuple[ErrorType, Optional[User]]:
|
||||
"""구글 ID 토큰으로 로그인. 처음이면 자동 닉네임으로 계정을 만든다. 구글 이름·이메일은 저장하지 않는다."""
|
||||
async def google(self, credential: str) -> tuple[ErrorType, Optional[User], bool]:
|
||||
"""구글 ID 토큰으로 로그인. 처음이면 자동 닉네임으로 계정을 만든다(셋째 값 True = 이번에 가입). 구글 이름·이메일은 저장하지 않는다."""
|
||||
sub = await verify_google(credential)
|
||||
if sub is None:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.AUTH_FAILED, None, False
|
||||
login_id = f"google_{sub}"
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return err, None, False
|
||||
created = user is None
|
||||
if user is None:
|
||||
err, user = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.create_google(s, sub, auto_nickname()))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
# 같은 계정이 동시에 처음 들어온 경우엔 먼저 만들어진 쪽을 쓴다
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||
if err is not ErrorType.SUCCESS or user is None:
|
||||
return ErrorType.DB_ERROR, None
|
||||
return ErrorType.DB_ERROR, None, False
|
||||
created = False
|
||||
if user.status != 1:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
return ErrorType.AUTH_FAILED, None, False
|
||||
return ErrorType.SUCCESS, user, created
|
||||
|
||||
async def toss_unlink(self, user_key: str) -> ErrorType:
|
||||
"""토스에서 연결을 끊으면 그 계정의 모든 토큰을 무효로 만든다. 계정이 없어도 성공으로 본다."""
|
||||
|
||||
@@ -22,7 +22,7 @@ from crud.season_crud import SeasonCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.v1.feed.protocol import (
|
||||
BandArticle, BandEvent, Bands, Cut, GakSlide, Hero, HeroStat, HeroTomorrow, HourCell, HoursSlide, ImageSlide, PostData, PostReaction, Res_Feed, Row, RowsSlide, SunsetSlide,
|
||||
PlanSlide, PlanStep, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide,
|
||||
PlanSlide, PlanStep, TomorrowEvent, TopIndex, WeatherWhy, WeekDay, WeekGak, WeekSlide,
|
||||
)
|
||||
from router.v1.index.protocol import TrendPoint
|
||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||
@@ -39,7 +39,7 @@ from services.now_service import NowService, NowWeather
|
||||
from services.season_service import SeasonService
|
||||
from services.sky_service import SkyService, SkyView, day_verdict
|
||||
from services.weather_service import TodayWeather, WeatherService
|
||||
from services.week_service import DayPlan, EventItem, WeekService, image_credit, mix_kinds
|
||||
from services.week_service import DayPlan, EventItem, WeekService, event_sidos, image_credit, mix_kinds
|
||||
from services.weekend_plan import day_plan, forecast, pick_events
|
||||
from services.weekend_rank import TripPick, WeekendRank, pick_trip, weekend_days
|
||||
|
||||
@@ -262,24 +262,24 @@ def _by_position(posts: list[Post]) -> list[Post]:
|
||||
return list(out.values())
|
||||
|
||||
|
||||
def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]:
|
||||
"""내일 하루 점수로 1위인 각과 그 점수 (동점이면 중요도 순)."""
|
||||
best = None
|
||||
for i in board.items:
|
||||
s = next((x for x in i.trend if x.score_date == day), None)
|
||||
if s is not None and (best is None or rank_score(s.score, i.definition.priority) > rank_score(best[1].score, best[0].definition.priority)):
|
||||
best = (i, s)
|
||||
return best
|
||||
def _tomorrow_ranked(board: IndexBoard, day: date) -> list[tuple[IndexItem, IndexScore]]:
|
||||
"""내일 하루 점수 순으로 제철 각과 그 점수 (동점이면 중요도 순)."""
|
||||
scored = [(i, s) for i in board.items if i.in_season for s in i.trend if s.score_date == day]
|
||||
return sorted(scored, key=lambda x: rank_score(x[1].score, x[0].definition.priority), reverse=True)
|
||||
|
||||
|
||||
def tomorrow_events(items: list[EventItem], region_code: str, day: date) -> list[TomorrowEvent]:
|
||||
"""그날 열리는 같은 시도 행사 3개 (종류를 섞어서)."""
|
||||
on = [e for e in items if e.event.sido_code in event_sidos(region_code) and e.event.start_date <= day <= e.event.end_date]
|
||||
return [TomorrowEvent(event_id=e.event.event_id, name=e.event.name, place=e.event.place_name, icon=e.event.icon,
|
||||
start_date=e.event.start_date, end_date=e.event.end_date) for e in mix_kinds(on)[:3]]
|
||||
|
||||
|
||||
def _hero_tomorrow(day: date, board: IndexBoard) -> HeroTomorrow:
|
||||
best = _tomorrow_best(board, day)
|
||||
top1 = None
|
||||
if best is not None:
|
||||
d, s = best[0].definition, best[1]
|
||||
top1 = TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=s.score, rank=1, summary=s.summary)
|
||||
ranked = [TopIndex(index_id=i.definition.index_id, code=i.definition.code, name=i.definition.name, icon=i.definition.icon, score=s.score,
|
||||
rank=n, summary=s.summary) for n, (i, s) in enumerate(_tomorrow_ranked(board, day)[:5], 1)]
|
||||
return HeroTomorrow(
|
||||
day=day, weather_slots=board.tomorrow_slots, top1=top1,
|
||||
day=day, weather_slots=board.tomorrow_slots, top1=ranked[0] if ranked else None, ranked=ranked,
|
||||
weather_why={k: [WeatherWhy(label=w.label, weight=w.weight, score=w.score, note=w.note) for w in ws] for k, ws in board.tomorrow_why.items()},
|
||||
)
|
||||
|
||||
@@ -436,9 +436,12 @@ class FeedService:
|
||||
has_warning = bool(now_w and now_w.warnings)
|
||||
# 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만)
|
||||
items = [i for i in board.items if i.in_season] if board else []
|
||||
hero = self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or []))
|
||||
if hero.tomorrow is not None:
|
||||
hero.tomorrow.events = tomorrow_events(events, region.code, hero.tomorrow.day)
|
||||
feed = Res_Feed(
|
||||
region_code=region.code, region_name=region.name, slot=slot,
|
||||
hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])),
|
||||
hero=hero,
|
||||
stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"), **pinned,
|
||||
bands=Bands(
|
||||
events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon,
|
||||
@@ -764,8 +767,9 @@ class FeedService:
|
||||
|
||||
def _tomorrow(self, base: dict, c: "_Ctx") -> PostData:
|
||||
rows = [Row(label=x.label, value=x.text) for x in c.now_w.commute]
|
||||
best = _tomorrow_best(c.board, c.now.date() + timedelta(days=1)) if c.board else None
|
||||
if best is not None:
|
||||
ranked = _tomorrow_ranked(c.board, c.now.date() + timedelta(days=1)) if c.board else []
|
||||
if ranked:
|
||||
best = ranked[0]
|
||||
rows.append(Row(label="내일 1위 각", value=f"{best[0].definition.name} {best[1].score}점"))
|
||||
caption = _temp_change(c.today, c.tomorrow) or "출근 전에 한 번 더 확인해 주세요."
|
||||
icon = c.now_w.commute[0].icon if c.now_w.commute else "sun"
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
{
|
||||
"about": "검색 결과 제목·설명 새 문구를 쓰는 지역 페이지. 나머지는 예전 문구로 두고 클릭률을 비교한다. Search Console 페이지 노출(2026-10-07~27) 많은 순으로 오늘·내일 따로 줄 세워 ABBA 로 나눔",
|
||||
"new": [
|
||||
"today/busan/busanjin",
|
||||
"today/busan/dong",
|
||||
"today/busan/geumjeong",
|
||||
"today/busan/gijang",
|
||||
"today/busan/nam",
|
||||
"today/busan/saha",
|
||||
"today/busan/suyeong",
|
||||
"today/busan/yeonje",
|
||||
"today/chungbuk/boeun",
|
||||
"today/chungbuk/eumseong",
|
||||
"today/chungbuk/jeungpyeong",
|
||||
"today/chungbuk/okcheon",
|
||||
"today/chungnam/boryeong",
|
||||
"today/chungnam/buyeo",
|
||||
"today/chungnam/cheonan/dongnam",
|
||||
"today/chungnam/cheongyang",
|
||||
"today/chungnam/geumsan",
|
||||
"today/chungnam/gongju",
|
||||
"today/chungnam/seocheon",
|
||||
"today/chungnam/seosan",
|
||||
"today/daegu/buk",
|
||||
"today/daegu/dalseo",
|
||||
"today/daegu/gunwi",
|
||||
"today/daegu/jung",
|
||||
"today/daegu/suseong",
|
||||
"today/daejeon/daedeok",
|
||||
"today/daejeon/dong",
|
||||
"today/daejeon/yuseong",
|
||||
"today/gangwon/cheorwon",
|
||||
"today/gangwon/donghae",
|
||||
"today/gangwon/goseong",
|
||||
"today/gangwon/hongcheon",
|
||||
"today/gangwon/hwacheon",
|
||||
"today/gangwon/pyeongchang",
|
||||
"today/gangwon/samcheok",
|
||||
"today/gangwon/wonju",
|
||||
"today/gangwon/yanggu",
|
||||
"today/gwangju/buk",
|
||||
"today/gwangju/dong",
|
||||
"today/gwangju/nam",
|
||||
"today/gyeongbuk/andong",
|
||||
"today/gyeongbuk/bonghwa",
|
||||
"today/gyeongbuk/cheongdo",
|
||||
"today/gyeongbuk/gimcheon",
|
||||
"today/gyeongbuk/goryeong",
|
||||
"today/gyeongbuk/gyeongsan",
|
||||
"today/gyeongbuk/mungyeong",
|
||||
"today/gyeongbuk/pohang",
|
||||
"today/gyeongbuk/pohang/buk",
|
||||
"today/gyeongbuk/uiseong",
|
||||
"today/gyeongbuk/uljin",
|
||||
"today/gyeongbuk/yeongdeok",
|
||||
"today/gyeongbuk/yeongju",
|
||||
"today/gyeonggi/anseong",
|
||||
"today/gyeonggi/anyang",
|
||||
"today/gyeonggi/anyang/dongan",
|
||||
"today/gyeonggi/anyang/manan",
|
||||
"today/gyeonggi/bucheon/sosa",
|
||||
"today/gyeonggi/bucheon/wonmi",
|
||||
"today/gyeonggi/gapyeong",
|
||||
"today/gyeonggi/gimpo",
|
||||
"today/gyeonggi/goyang/deogyang",
|
||||
"today/gyeonggi/guri",
|
||||
"today/gyeonggi/gwacheon",
|
||||
"today/gyeonggi/hanam",
|
||||
"today/gyeonggi/hwaseong/hyohaeng",
|
||||
"today/gyeonggi/namyangju",
|
||||
"today/gyeonggi/pocheon",
|
||||
"today/gyeonggi/pyeongtaek",
|
||||
"today/gyeonggi/seongnam",
|
||||
"today/gyeonggi/seongnam/bundang",
|
||||
"today/gyeonggi/seongnam/jungwon",
|
||||
"today/gyeonggi/suwon/gwonseon",
|
||||
"today/gyeonggi/suwon/jangan",
|
||||
"today/gyeonggi/suwon/paldal",
|
||||
"today/gyeonggi/suwon/yeongtong",
|
||||
"today/gyeonggi/uiwang",
|
||||
"today/gyeonggi/yangju",
|
||||
"today/gyeonggi/yeoncheon",
|
||||
"today/gyeonggi/yongin",
|
||||
"today/gyeonggi/yongin/suji",
|
||||
"today/gyeongnam/changnyeong",
|
||||
"today/gyeongnam/changwon/jinhae",
|
||||
"today/gyeongnam/changwon/masanhoewon",
|
||||
"today/gyeongnam/geoje",
|
||||
"today/gyeongnam/goseong",
|
||||
"today/gyeongnam/hadong",
|
||||
"today/gyeongnam/miryang",
|
||||
"today/gyeongnam/namhae",
|
||||
"today/gyeongnam/tongyeong",
|
||||
"today/gyeongnam/uiryeong",
|
||||
"today/incheon/ganghwa",
|
||||
"today/incheon/geomdan",
|
||||
"today/incheon/gyeyang",
|
||||
"today/incheon/namdong",
|
||||
"today/incheon/ongjin",
|
||||
"today/incheon/seohae",
|
||||
"today/jeju/jeju",
|
||||
"today/jeju/seogwipo",
|
||||
"today/jeonbuk/buan",
|
||||
"today/jeonbuk/imsil",
|
||||
"today/jeonbuk/jangsu",
|
||||
"today/jeonbuk/jeongeup",
|
||||
"today/jeonbuk/namwon",
|
||||
"today/jeonbuk/sunchang",
|
||||
"today/jeonbuk/wanju",
|
||||
"today/jeonnam/gangjin",
|
||||
"today/jeonnam/goheung",
|
||||
"today/jeonnam/gurye",
|
||||
"today/jeonnam/haenam",
|
||||
"today/jeonnam/hampyeong",
|
||||
"today/jeonnam/hwasun",
|
||||
"today/jeonnam/jindo",
|
||||
"today/jeonnam/mokpo",
|
||||
"today/jeonnam/suncheon",
|
||||
"today/jeonnam/wando",
|
||||
"today/jeonnam/yeongam",
|
||||
"today/sejong/sejong",
|
||||
"today/seoul/dobong",
|
||||
"today/seoul/dongdaemun",
|
||||
"today/seoul/gangbuk",
|
||||
"today/seoul/gangdong",
|
||||
"today/seoul/geumcheon",
|
||||
"today/seoul/guro",
|
||||
"today/seoul/jongno",
|
||||
"today/seoul/jung",
|
||||
"today/seoul/jungnang",
|
||||
"today/seoul/seocho",
|
||||
"today/seoul/seodaemun",
|
||||
"today/seoul/seongdong",
|
||||
"today/seoul/yeongdeungpo",
|
||||
"today/seoul/yongsan",
|
||||
"today/ulsan/jung",
|
||||
"today/ulsan/nam",
|
||||
"today/ulsan/ulju",
|
||||
"tomorrow/busan/gangseo",
|
||||
"tomorrow/busan/geumjeong",
|
||||
"tomorrow/busan/gijang",
|
||||
"tomorrow/busan/jung",
|
||||
"tomorrow/busan/sasang",
|
||||
"tomorrow/busan/seo",
|
||||
"tomorrow/busan/yeonje",
|
||||
"tomorrow/chungbuk/cheongju",
|
||||
"tomorrow/chungbuk/cheongju/heungdeok",
|
||||
"tomorrow/chungbuk/danyang",
|
||||
"tomorrow/chungbuk/goesan",
|
||||
"tomorrow/chungbuk/jecheon",
|
||||
"tomorrow/chungbuk/jincheon",
|
||||
"tomorrow/chungbuk/yeongdong",
|
||||
"tomorrow/chungnam/asan",
|
||||
"tomorrow/chungnam/boryeong",
|
||||
"tomorrow/chungnam/cheonan",
|
||||
"tomorrow/chungnam/cheonan/dongnam",
|
||||
"tomorrow/chungnam/cheonan/seobuk",
|
||||
"tomorrow/chungnam/dangjin",
|
||||
"tomorrow/chungnam/geumsan",
|
||||
"tomorrow/chungnam/hongseong",
|
||||
"tomorrow/chungnam/seocheon",
|
||||
"tomorrow/chungnam/seosan",
|
||||
"tomorrow/chungnam/taean",
|
||||
"tomorrow/daegu/dong",
|
||||
"tomorrow/daegu/gunwi",
|
||||
"tomorrow/daegu/nam",
|
||||
"tomorrow/daegu/suseong",
|
||||
"tomorrow/daejeon/daedeok",
|
||||
"tomorrow/daejeon/seo",
|
||||
"tomorrow/gangwon/chuncheon",
|
||||
"tomorrow/gangwon/hoengseong",
|
||||
"tomorrow/gangwon/inje",
|
||||
"tomorrow/gangwon/jeongseon",
|
||||
"tomorrow/gangwon/samcheok",
|
||||
"tomorrow/gangwon/sokcho",
|
||||
"tomorrow/gangwon/taebaek",
|
||||
"tomorrow/gangwon/wonju",
|
||||
"tomorrow/gangwon/yeongwol",
|
||||
"tomorrow/gwangju/buk",
|
||||
"tomorrow/gwangju/gwangsan",
|
||||
"tomorrow/gyeongbuk/cheongdo",
|
||||
"tomorrow/gyeongbuk/cheongsong",
|
||||
"tomorrow/gyeongbuk/goryeong",
|
||||
"tomorrow/gyeongbuk/gumi",
|
||||
"tomorrow/gyeongbuk/gyeongsan",
|
||||
"tomorrow/gyeongbuk/sangju",
|
||||
"tomorrow/gyeongbuk/seongju",
|
||||
"tomorrow/gyeongbuk/ulleung",
|
||||
"tomorrow/gyeongbuk/yeongju",
|
||||
"tomorrow/gyeonggi/ansan",
|
||||
"tomorrow/gyeonggi/ansan/sangnok",
|
||||
"tomorrow/gyeonggi/anyang",
|
||||
"tomorrow/gyeonggi/anyang/dongan",
|
||||
"tomorrow/gyeonggi/bucheon/ojeong",
|
||||
"tomorrow/gyeonggi/gimpo",
|
||||
"tomorrow/gyeonggi/goyang",
|
||||
"tomorrow/gyeonggi/gunpo",
|
||||
"tomorrow/gyeonggi/guri",
|
||||
"tomorrow/gyeonggi/gwangmyeong",
|
||||
"tomorrow/gyeonggi/hanam",
|
||||
"tomorrow/gyeonggi/hwaseong/hyohaeng",
|
||||
"tomorrow/gyeonggi/namyangju",
|
||||
"tomorrow/gyeonggi/paju",
|
||||
"tomorrow/gyeonggi/pocheon",
|
||||
"tomorrow/gyeonggi/seongnam/jungwon",
|
||||
"tomorrow/gyeonggi/siheung",
|
||||
"tomorrow/gyeonggi/suwon",
|
||||
"tomorrow/gyeonggi/suwon/gwonseon",
|
||||
"tomorrow/gyeonggi/suwon/yeongtong",
|
||||
"tomorrow/gyeonggi/uijeongbu",
|
||||
"tomorrow/gyeonggi/yangju",
|
||||
"tomorrow/gyeonggi/yangpyeong",
|
||||
"tomorrow/gyeonggi/yeoncheon",
|
||||
"tomorrow/gyeonggi/yongin/cheoin",
|
||||
"tomorrow/gyeonggi/yongin/suji",
|
||||
"tomorrow/gyeongnam/changnyeong",
|
||||
"tomorrow/gyeongnam/changwon/jinhae",
|
||||
"tomorrow/gyeongnam/changwon/uichang",
|
||||
"tomorrow/gyeongnam/geochang",
|
||||
"tomorrow/gyeongnam/goseong",
|
||||
"tomorrow/gyeongnam/haman",
|
||||
"tomorrow/gyeongnam/hamyang",
|
||||
"tomorrow/gyeongnam/hapcheon",
|
||||
"tomorrow/gyeongnam/jinju",
|
||||
"tomorrow/gyeongnam/namhae",
|
||||
"tomorrow/gyeongnam/sacheon",
|
||||
"tomorrow/gyeongnam/uiryeong",
|
||||
"tomorrow/gyeongnam/yangsan",
|
||||
"tomorrow/incheon/ganghwa",
|
||||
"tomorrow/incheon/jemulpo",
|
||||
"tomorrow/incheon/michuhol",
|
||||
"tomorrow/incheon/seohae",
|
||||
"tomorrow/jeju/jeju",
|
||||
"tomorrow/jeonbuk/buan",
|
||||
"tomorrow/jeonbuk/gimje",
|
||||
"tomorrow/jeonbuk/gochang",
|
||||
"tomorrow/jeonbuk/gunsan",
|
||||
"tomorrow/jeonbuk/jangsu",
|
||||
"tomorrow/jeonbuk/jeonju",
|
||||
"tomorrow/jeonbuk/muju",
|
||||
"tomorrow/jeonbuk/wanju",
|
||||
"tomorrow/jeonnam/boseong",
|
||||
"tomorrow/jeonnam/damyang",
|
||||
"tomorrow/jeonnam/gangjin",
|
||||
"tomorrow/jeonnam/gurye",
|
||||
"tomorrow/jeonnam/haenam",
|
||||
"tomorrow/jeonnam/jangseong",
|
||||
"tomorrow/jeonnam/jindo",
|
||||
"tomorrow/jeonnam/muan",
|
||||
"tomorrow/jeonnam/naju",
|
||||
"tomorrow/jeonnam/suncheon",
|
||||
"tomorrow/jeonnam/yeongam",
|
||||
"tomorrow/jeonnam/yeosu",
|
||||
"tomorrow/seoul/dongjak",
|
||||
"tomorrow/seoul/eunpyeong",
|
||||
"tomorrow/seoul/gangnam",
|
||||
"tomorrow/seoul/geumcheon",
|
||||
"tomorrow/seoul/guro",
|
||||
"tomorrow/seoul/gwanak",
|
||||
"tomorrow/seoul/gwangjin",
|
||||
"tomorrow/seoul/jongno",
|
||||
"tomorrow/seoul/jung",
|
||||
"tomorrow/seoul/jungnang",
|
||||
"tomorrow/seoul/nowon",
|
||||
"tomorrow/seoul/seocho",
|
||||
"tomorrow/seoul/seongdong",
|
||||
"tomorrow/seoul/songpa",
|
||||
"tomorrow/seoul/yangcheon",
|
||||
"tomorrow/seoul/yongsan",
|
||||
"tomorrow/ulsan/buk",
|
||||
"tomorrow/ulsan/dong",
|
||||
"tomorrow/ulsan/jung",
|
||||
"tomorrow/ulsan/nam"
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import date, datetime, timedelta
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
@@ -23,6 +25,11 @@ _CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
|
||||
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"')
|
||||
_NAME = re.compile(r"<h1>(.+?) (?:오늘|내일) 날씨")
|
||||
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
|
||||
_TITLE = re.compile(r"<title>[^<]*</title>")
|
||||
_TITLE_META = re.compile(r'(<meta (?:property|name)="(?:og:title|twitter:title)" content=")[^"]*"')
|
||||
_WEEKDAY = "월화수목금토일"
|
||||
# 검색 결과 새 문구를 쓰는 페이지(나머지 반은 예전 문구로 두고 클릭률을 견준다)
|
||||
NEW_COPY = frozenset(json.loads(Path(__file__).with_name("seo_copy_test.json").read_text(encoding="utf-8"))["new"])
|
||||
|
||||
|
||||
def _clock(at: datetime) -> str:
|
||||
@@ -31,19 +38,35 @@ def _clock(at: datetime) -> str:
|
||||
return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "")
|
||||
|
||||
|
||||
def _date(day: date) -> str:
|
||||
return f"{day.month}월 {day.day}일({_WEEKDAY[day.weekday()]})"
|
||||
|
||||
|
||||
def _final(word: str) -> bool:
|
||||
"""마지막 글자에 받침이 있는지 (한글이 아니면 없다고 본다)."""
|
||||
c = ord(word[-1]) - 0xAC00
|
||||
return 0 <= c < 11172 and c % 28 != 0
|
||||
|
||||
|
||||
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
|
||||
_RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
|
||||
|
||||
|
||||
def _day(rows: list[WeatherHourly]) -> tuple[int, int, int, str]:
|
||||
"""하루 예보: 최저, 최고, 강수확률, 하늘 (비·눈이 있으면 그것)."""
|
||||
temps = [float(r.temp_c) for r in rows]
|
||||
wet = next((RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value), None)
|
||||
day = [r for r in rows if 9 <= r.forecast_at.astimezone(KST).hour <= 18] or rows
|
||||
sky = _RAIN_WORD[wet] if wet else _SKY_WORD[Sky(max({r.sky for r in day}, key=[r.sky for r in day].count))]
|
||||
return round(min(temps)), round(max(temps)), max(r.rain_prob for r in rows), sky
|
||||
|
||||
|
||||
def day_summary(rows: list[WeatherHourly]) -> str:
|
||||
"""오늘 하루 예보 요약: 최저·최고, 강수확률, 하늘 (비·눈이 있으면 그것)."""
|
||||
if not rows:
|
||||
return ""
|
||||
temps = [float(r.temp_c) for r in rows]
|
||||
wet = next((RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value), None)
|
||||
day = [r for r in rows if 9 <= r.forecast_at.astimezone(KST).hour <= 18] or rows
|
||||
sky = _RAIN_WORD[wet] if wet else _SKY_WORD[Sky(max({r.sky for r in day}, key=[r.sky for r in day].count))]
|
||||
return f"최저 {round(min(temps))}°·최고 {round(max(temps))}°, 강수확률 {max(r.rain_prob for r in rows)}%, {sky}."
|
||||
lo, hi, prob, sky = _day(rows)
|
||||
return f"최저 {lo}°·최고 {hi}°, 강수확률 {prob}%, {sky}."
|
||||
|
||||
|
||||
def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
|
||||
@@ -69,6 +92,53 @@ def tomorrow_line(rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> s
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def today_copy(day: date, place: str, feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
|
||||
"""새 문구의 오늘 설명: 날짜·지역, 하루 예보, 아침·낮 1위 각, 미세먼지·불쾌지수·자외선, 해 지는 시각."""
|
||||
weather = ""
|
||||
if rows:
|
||||
lo, hi, prob, _ = _day(rows)
|
||||
weather = f": 최저 {lo}°·최고 {hi}°, 비 올 확률 {prob}%"
|
||||
parts = [f"{_date(day)} {place} 오늘 날씨{weather}."]
|
||||
# 아침·낮 1위가 같으면 한 번만: 아침·낮엔 캠핑각
|
||||
firsts: dict[str, list[str]] = {}
|
||||
for slot, label in SLOT_LABEL.items():
|
||||
for s in feed.stories:
|
||||
if slot in ("morning", "day") and s.slot_ranks.get(slot) == 1:
|
||||
firsts.setdefault(s.name, []).append(label)
|
||||
if firsts:
|
||||
said = ", ".join("·".join(labels) + f"엔 {name}" for name, labels in firsts.items())
|
||||
parts.append(f"{said}{'이' if _final(list(firsts)[-1]) else '가'} 1위예요.")
|
||||
status = {s.label: s.value for s in feed.hero.status} if feed.hero else {}
|
||||
tail = [f"{label} {status[label]}" for label in ("미세먼지", "불쾌지수", "자외선") if label in status]
|
||||
if sunset_at:
|
||||
tail.append(f"해 지는 시각 {_clock(sunset_at)}")
|
||||
if tail:
|
||||
parts.append(", ".join(tail) + ".")
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def tomorrow_copy(day: date, place: str, rows: list[WeatherHourly], top1: Optional[str], sunset_at: Optional[datetime]) -> str:
|
||||
"""새 문구의 내일 설명: 날짜·지역, 내일 하루 예보, 내일 1위 각, 해 지는 시각."""
|
||||
if not rows:
|
||||
return ""
|
||||
lo, hi, prob, sky = _day(rows)
|
||||
line = f"{_date(day)} {place} 내일 날씨: 최저 {lo}°·최고 {hi}°, {sky}, 비 올 확률 {prob}%."
|
||||
tail = ([f"내일 하기 좋은 일 1위는 {top1}"] if top1 else []) + ([f"해 지는 시각은 {_clock(sunset_at)}"] if sunset_at else [])
|
||||
if not tail:
|
||||
return line
|
||||
return f"{line} {', '.join(tail)}{'이에요' if _final(tail[-1]) else '예요'}."
|
||||
|
||||
|
||||
def _retitle(html: str, title: str) -> str:
|
||||
html = _TITLE.sub(lambda _: f"<title>{escape(title)}</title>", html, count=1)
|
||||
return _TITLE_META.sub(lambda m: f'{m.group(1)}{escape(title, quote=True)}"', html)
|
||||
|
||||
|
||||
def _mark(html: str, copy: str) -> str:
|
||||
"""앱이 검색 유입 GA 에 어느 문구로 들어왔는지 실어 보내게 표시한다."""
|
||||
return html.replace("</head>", f'<meta name="seo-copy" content="{copy}" />\n </head>', 1)
|
||||
|
||||
|
||||
def _put(template: str, line: str, extra: str = "") -> str:
|
||||
"""설명 메타와 본문 h1 바로 아래에 한 줄을 넣는다."""
|
||||
if not line:
|
||||
@@ -77,11 +147,14 @@ def _put(template: str, line: str, extra: str = "") -> str:
|
||||
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{extra}", html, count=1)
|
||||
|
||||
|
||||
def _ranks(feed: Res_Feed, name: str) -> str:
|
||||
top = feed.bands.top5 if feed.bands else []
|
||||
return f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
|
||||
|
||||
|
||||
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
|
||||
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
|
||||
top = feed.bands.top5 if feed.bands else []
|
||||
ranks = f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
|
||||
return _put(template, today_line(feed, rows, sunset_at), ranks)
|
||||
return _put(template, today_line(feed, rows, sunset_at), _ranks(feed, name))
|
||||
|
||||
|
||||
class SeoService:
|
||||
@@ -115,7 +188,16 @@ class SeoService:
|
||||
sunset_at = sun_times(day, float(region.lat), float(region.lon)).sunset_at if region else None
|
||||
start = kst_midnight(day)
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
|
||||
found = _NAME.search(template)
|
||||
name = found.group(1) if found else (feed.region_name or "")
|
||||
if path not in NEW_COPY:
|
||||
html = _put(template, tomorrow_line(rows or [], sunset_at)) if ahead else fill(template, feed, rows or [], name, sunset_at)
|
||||
return ErrorType.SUCCESS, _mark(html, "old")
|
||||
place = name.split(" ")[-1]
|
||||
if ahead:
|
||||
return ErrorType.SUCCESS, _put(template, tomorrow_line(rows or [], sunset_at))
|
||||
name = _NAME.search(template)
|
||||
return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
|
||||
top1 = feed.hero.tomorrow.top1.name if feed.hero and feed.hero.tomorrow and feed.hero.tomorrow.top1 else None
|
||||
html = _put(template, tomorrow_copy(day, place, rows or [], top1, sunset_at))
|
||||
if top1:
|
||||
html = _retitle(html, f"{place} 내일 날씨 · 내일 1위는 {top1} | 날씨각")
|
||||
return ErrorType.SUCCESS, _mark(html, "new")
|
||||
return ErrorType.SUCCESS, _mark(_put(template, today_copy(day, place, feed, rows or [], sunset_at), _ranks(feed, name)), "new")
|
||||
@@ -148,6 +148,8 @@ async def test_hero_tomorrow_and_tomorrow_slots(offline):
|
||||
async with client() as c:
|
||||
hero = (await c.get("/v1/feed", params={"region": REGION})).json()["hero"]
|
||||
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
|
||||
assert len(hero["tomorrow"]["ranked"]) <= 5 and len(hero["tomorrow"]["events"]) <= 3
|
||||
assert hero["tomorrow"]["top1"] == (hero["tomorrow"]["ranked"][0] if hero["tomorrow"]["ranked"] else None)
|
||||
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
|
||||
assert res["day"] == hero["tomorrow"]["day"]
|
||||
|
||||
|
||||
@@ -85,3 +85,21 @@ def test_success_reads_toss_wrapper():
|
||||
toss_login._success(fail, "login-me")
|
||||
with pytest.raises(toss_login.TossLoginError, match="invalid_grant"):
|
||||
toss_login._success(grant, "generate-token")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_toss_login_marks_only_first_as_new(monkeypatch):
|
||||
"""처음 들어온 요청만 is_new(GA sign_up), 같은 사람이 다시 들어오면 로그인"""
|
||||
import secrets
|
||||
|
||||
key = 10_000_000 + secrets.randbelow(80_000_000)
|
||||
|
||||
async def fake_user_key(code: str, referrer: str) -> int:
|
||||
return key
|
||||
|
||||
monkeypatch.setattr(toss_login, "user_key", fake_user_key)
|
||||
async with client() as c:
|
||||
first = (await c.post("/v1/auth/toss", json={"authorization_code": "code-x", "referrer": "DEFAULT"})).json()
|
||||
again = (await c.post("/v1/auth/toss", json={"authorization_code": "code-x", "referrer": "DEFAULT"})).json()
|
||||
assert first["result"]["success"] is True and first["is_new"] is True
|
||||
assert again["result"]["success"] is True and again["is_new"] is False
|
||||
@@ -210,6 +210,49 @@ def test_feed_events_keeps_every_festival_and_two_of_other_kinds():
|
||||
assert out[:4] == [EventKind.FESTIVAL.value, EventKind.POPUP.value, EventKind.EXHIBITION.value, EventKind.CONCERT.value]
|
||||
|
||||
|
||||
def test_tomorrow_events_keep_same_sido_events_running_that_day():
|
||||
"""내일 페이지 행사: 내일 열리는 같은 시도 행사만, 종류를 섞어 3개까지."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import EventKind
|
||||
from services.feed_service import tomorrow_events
|
||||
from services.week_service import EventItem
|
||||
|
||||
day = date(2026, 10, 31)
|
||||
|
||||
def ev(n, kind, sido="11", start=day, end=day):
|
||||
e = SimpleNamespace(event_id=n, name=f"행사{n}", place_name=f"장소{n}", icon="concert", kind=kind.value, sido_code=sido, start_date=start, end_date=end)
|
||||
return EventItem(event=e, status="live", status_label="진행 중", fit=None)
|
||||
|
||||
items = [
|
||||
ev(1, EventKind.CONCERT), ev(2, EventKind.CONCERT), ev(3, EventKind.FESTIVAL, start=day - timedelta(days=2)),
|
||||
ev(4, EventKind.FESTIVAL, end=day - timedelta(days=1)), ev(5, EventKind.EXHIBITION, sido="41"), ev(6, EventKind.POPUP, start=day + timedelta(days=1)),
|
||||
]
|
||||
out = tomorrow_events(items, "1144000000", day)
|
||||
assert [e.event_id for e in out] == [3, 1, 2]
|
||||
assert out[0].place == "장소3" and out[0].start_date == day - timedelta(days=2)
|
||||
|
||||
|
||||
def test_hero_tomorrow_ranks_in_season_gak_by_tomorrow_score():
|
||||
"""내일의 각: 내일 하루 점수(중요도 반영) 순 5개, 철 지난 각은 빼고, 1위는 top1 과 같다."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import _hero_tomorrow
|
||||
|
||||
day = date(2026, 10, 31)
|
||||
|
||||
def item(n, score, in_season=True, priority=1.0):
|
||||
d = SimpleNamespace(index_id=n, code=f"g{n}", name=f"각{n}", icon="sun", priority=priority)
|
||||
trend = [SimpleNamespace(score_date=day - timedelta(days=1), score=100, summary="오늘"), SimpleNamespace(score_date=day, score=score, summary=f"내일{n}")]
|
||||
return SimpleNamespace(definition=d, trend=trend, in_season=in_season)
|
||||
|
||||
board = SimpleNamespace(items=[item(1, 60), item(2, 99, in_season=False), item(3, 90), item(4, 70), item(5, 80), item(6, 50), item(7, 40)],
|
||||
tomorrow_slots={}, tomorrow_why={})
|
||||
hero = _hero_tomorrow(day, board)
|
||||
assert [(g.index_id, g.rank) for g in hero.ranked] == [(3, 1), (5, 2), (4, 3), (1, 4), (6, 5)]
|
||||
assert hero.top1 == hero.ranked[0] and hero.ranked[0].summary == "내일3"
|
||||
|
||||
|
||||
def test_arrange_spreads_many_events_through_whole_feed():
|
||||
"""행사가 앞쪽 절반 자리보다 많으면 끝까지 한 장씩 걸러 끼우고, 남은 건 맨 뒤에 다 붙인다."""
|
||||
from datetime import datetime
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
@@ -7,7 +7,8 @@ from common.utils.kma_time import KST
|
||||
from common.database.model.models import WeatherHourly
|
||||
from router.router import app
|
||||
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
|
||||
from services.seo_service import SeoService, day_summary, fill, today_line, tomorrow_line
|
||||
from services import seo_service
|
||||
from services.seo_service import SeoService, day_summary, fill, today_copy, today_line, tomorrow_copy, tomorrow_line
|
||||
|
||||
REGION = "1114000000"
|
||||
TEMPLATE = (
|
||||
@@ -55,6 +56,7 @@ def test_fill_keeps_template_when_no_weather():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_page_fills_real_feed(offline, monkeypatch):
|
||||
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
|
||||
async def template(self, path):
|
||||
return TEMPLATE if path == "today/seoul/jung" else None
|
||||
|
||||
@@ -69,6 +71,7 @@ async def test_today_page_fills_real_feed(offline, monkeypatch):
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
|
||||
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
|
||||
async def template(self, path):
|
||||
return TEMPLATE if path == "today/gyeonggi/seongnam/bundang" else None
|
||||
|
||||
@@ -86,6 +89,7 @@ def test_tomorrow_line_has_day_and_sunset():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_tomorrow_page_fills_tomorrow_forecast(offline, monkeypatch):
|
||||
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
|
||||
tmpl = TEMPLATE.replace("오늘 날씨", "내일 날씨")
|
||||
|
||||
async def template(self, path):
|
||||
@@ -98,3 +102,67 @@ async def test_tomorrow_page_fills_tomorrow_forecast(offline, monkeypatch):
|
||||
assert page.status_code == 200 and "<h1>서울 중구 내일 날씨, 뭐 할까?</h1><p>최저 " in page.text
|
||||
assert "지금 " not in page.text and "<ol>" not in page.text
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
def test_today_copy_has_date_place_morning_day_firsts_and_status():
|
||||
line = today_copy(date(2026, 10, 14), "중구", _feed(), [_hour(12, 19.5, prob=10)], datetime(2026, 10, 14, 17, 52, tzinfo=KST))
|
||||
assert line == "10월 14일(수) 중구 오늘 날씨: 최저 20°·최고 20°, 비 올 확률 10%. 아침엔 러닝각, 낮엔 빨래각이 1위예요. 미세먼지 좋음, 해 지는 시각 오후 5시 52분."
|
||||
same = _feed()
|
||||
same.stories = [_top("캠핑각", 90, {"morning": 1, "day": 1})]
|
||||
assert "아침·낮엔 캠핑각이 1위예요." in today_copy(date(2026, 10, 14), "중구", same, [], None)
|
||||
|
||||
|
||||
def test_today_copy_lists_dust_discomfort_uv_in_order():
|
||||
feed = _feed()
|
||||
feed.hero.status = [HeroStat(icon="m", label=label, value=value, tone="normal") for label, value in (("습도", "보통"), ("불쾌지수", "쾌적"), ("자외선", "보통"), ("미세먼지", "보통"))]
|
||||
line = today_copy(date(2026, 10, 30), "성남시", feed, [_hour(12, 18, rain=2, prob=60)], None)
|
||||
assert line.endswith("미세먼지 보통, 불쾌지수 쾌적, 자외선 보통.")
|
||||
assert "습도" not in line
|
||||
|
||||
|
||||
def test_tomorrow_copy_has_date_place_top1_and_sunset():
|
||||
sunset = datetime(2026, 10, 31, 17, 36, tzinfo=KST)
|
||||
line = tomorrow_copy(date(2026, 10, 31), "평택시", [_hour(12, 15, prob=30)], "빨래각", sunset)
|
||||
assert line == "10월 31일(토) 평택시 내일 날씨: 최저 15°·최고 15°, 맑음, 비 올 확률 30%. 내일 하기 좋은 일 1위는 빨래각, 해 지는 시각은 오후 5시 36분이에요."
|
||||
on_hour = tomorrow_copy(date(2026, 10, 31), "평택시", [_hour(12, 15)], None, datetime(2026, 10, 31, 18, 0, tzinfo=KST))
|
||||
assert on_hour.endswith("해 지는 시각은 오후 6시예요.")
|
||||
assert tomorrow_copy(date(2026, 10, 31), "평택시", [], "빨래각", sunset) == ""
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_new_copy_pages_get_new_title_and_description(offline, monkeypatch):
|
||||
tomorrow = TEMPLATE.replace("오늘 날씨", "내일 날씨").replace("</head>", "<title>중구 내일 날씨, 뭐 할까? · 서울 | 날씨각</title></head>")
|
||||
|
||||
async def template(self, path):
|
||||
return {"today/seoul/jung": TEMPLATE, "tomorrow/seoul/jung": tomorrow}.get(path)
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset({"today/seoul/jung", "tomorrow/seoul/jung"}))
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
today = await client.get("/v1/seo/today/seoul/jung")
|
||||
ahead = await client.get("/v1/seo/tomorrow/seoul/jung")
|
||||
assert today.status_code == 200 and ahead.status_code == 200
|
||||
assert '<meta name="description" content="10월 ' in today.text and " 중구 오늘 날씨: 최저 " in today.text
|
||||
assert "<ol><li>" in today.text and '<meta name="seo-copy" content="new" />' in today.text
|
||||
assert " 중구 내일 날씨: 최저 " in ahead.text and "해 지는 시각은 오후" in ahead.text
|
||||
assert "<title>중구 내일 날씨 · 내일 1위는 " in ahead.text and 'property="og:description" content="10월 ' in ahead.text
|
||||
assert '<meta name="seo-copy" content="new" />' in ahead.text
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_old_copy_pages_keep_old_text_and_are_marked(offline, monkeypatch):
|
||||
async def template(self, path):
|
||||
return TEMPLATE if path == "today/seoul/jung" else None
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/today/seoul/jung")
|
||||
assert "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>최저 " in page.text
|
||||
assert '<meta name="seo-copy" content="old" />' in page.text
|
||||
|
||||
|
||||
def test_copy_test_groups_split_region_pages_in_half():
|
||||
assert seo_service.NEW_COPY and all(p.startswith(("today/", "tomorrow/")) for p in seo_service.NEW_COPY)
|
||||
today = sum(p.startswith("today/") for p in seo_service.NEW_COPY)
|
||||
assert today == len(seo_service.NEW_COPY) - today
|
||||
@@ -0,0 +1,79 @@
|
||||
오늘 날씨 1241842B - 1242089B -
|
||||
내일 날씨 1255827B - 1241265B -
|
||||
모레 날씨 1146464B - 1150726B -
|
||||
이번주 날씨 1290799B - 1290981B -
|
||||
주말 날씨 1306886B - 1307070B -
|
||||
날씨 1404122B - 1404306B -
|
||||
서울 오늘 날씨 1241948B - 1242134B -
|
||||
서울 내일 날씨 1282168B - 1282348B -
|
||||
서울 날씨 985505B - 985689B -
|
||||
부산 오늘 날씨 1264133B - 1264313B -
|
||||
부산 내일 날씨 1265164B - 1265344B -
|
||||
부산 날씨 1213605B - 1213787B -
|
||||
인천 오늘 날씨 1300790B - 1300974B -
|
||||
인천 내일 날씨 1293527B - 1293711B -
|
||||
인천 날씨 1260461B - 1260641B -
|
||||
대구 오늘 날씨 1244846B - 1245026B -
|
||||
대구 내일 날씨 1305698B - 1305880B -
|
||||
대구 날씨 1231166B - 1231339B -
|
||||
대전 오늘 날씨 1260892B - 1261079B -
|
||||
대전 내일 날씨 1315087B - 1315271B -
|
||||
대전 날씨 1317624B - 1317802B -
|
||||
광주 오늘 날씨 1277429B - 1277605B -
|
||||
광주 내일 날씨 1282066B - 1282246B -
|
||||
광주 날씨 1265430B - 1265611B -
|
||||
울산 오늘 날씨 1238077B - 1238262B -
|
||||
울산 내일 날씨 1213012B - 1213192B -
|
||||
울산 날씨 1257139B - 1257323B -
|
||||
세종 오늘 날씨 1335637B - 1335817B -
|
||||
세종 내일 날씨 1244726B - 1244912B -
|
||||
세종 날씨 1350300B - 1350480B -
|
||||
수원 오늘 날씨 1238160B - 1238344B -
|
||||
수원 내일 날씨 1228071B - 1228249B -
|
||||
수원 날씨 1348504B - 1348684B -
|
||||
성남 오늘 날씨 1279860B - 1280042B -
|
||||
성남 내일 날씨 1189405B - 1189593B -
|
||||
성남 날씨 1239403B - 1239585B -
|
||||
고양 오늘 날씨 1286139B - 1286317B -
|
||||
고양 내일 날씨 1208419B - 1208605B -
|
||||
고양 날씨 1277571B - 1277753B -
|
||||
용인 오늘 날씨 1200469B - 1200659B -
|
||||
용인 내일 날씨 1236616B - 1236798B -
|
||||
용인 날씨 1368350B - 1368532B -
|
||||
창원 오늘 날씨 1244725B - 1244903B -
|
||||
창원 내일 날씨 1203664B - 1203844B -
|
||||
창원 날씨 1280151B - 1280329B -
|
||||
청주 오늘 날씨 1302209B - 1302391B -
|
||||
청주 내일 날씨 1278427B - 1278611B -
|
||||
청주 날씨 1368258B - 1368442B -
|
||||
천안 오늘 날씨 1236997B - 1237182B -
|
||||
천안 내일 날씨 1243104B - 1243289B -
|
||||
천안 날씨 1319722B - 1319904B -
|
||||
전주 오늘 날씨 1800004B - 1800190B -
|
||||
전주 내일 날씨 1783583B - 1783765B -
|
||||
전주 날씨 1261004B - 1261188B -
|
||||
군산 오늘 날씨 1282946B - 1283130B -
|
||||
군산 내일 날씨 1271879B - 1272061B -
|
||||
군산 날씨 1267946B - 1268128B -
|
||||
포항 오늘 날씨 1279182B - 1279362B -
|
||||
포항 내일 날씨 1261670B - 1261854B -
|
||||
포항 날씨 1308817B - 1309003B -
|
||||
제주 오늘 날씨 1253715B - 1253895B -
|
||||
제주 내일 날씨 1334766B - 1334942B -
|
||||
제주 날씨 1308240B - 1308434B -
|
||||
김해 오늘 날씨 1221203B - 1221389B -
|
||||
김해 내일 날씨 1221664B - 1221844B -
|
||||
김해 날씨 1287333B - 1287517B -
|
||||
화성 오늘 날씨 1249282B - 1249468B -
|
||||
화성 내일 날씨 1233491B - 1233673B -
|
||||
화성 날씨 997204B - 997384B -
|
||||
부천 오늘 날씨 924121B - 924303B -
|
||||
부천 내일 날씨 1239101B - 1239281B -
|
||||
부천 날씨 1060555B - 1060741B -
|
||||
안산 오늘 날씨 1271510B - 1271690B -
|
||||
안산 내일 날씨 1590933B - 1591114B -
|
||||
안산 날씨 1273204B - 1273392B -
|
||||
남양주 오늘 날씨 1240661B - 1240841B -
|
||||
남양주 내일 날씨 1263026B - 1263214B -
|
||||
남양주 날씨 1308914B - 1309096B -
|
||||
날씨각 612597B 1 https://weather.o2o.kr/tomorrow/incheon/namdong 612783B 1 https://weather.o2o.kr/tomorrow/incheon/namdong
|
||||
|
@@ -402,7 +402,13 @@
|
||||
순위 = 결과에서 weather.o2o.kr이 몇 번째 사이트인지(같은 사이트는 한 번만 셈). `-` 첫 페이지에 없음. 적힌 검색어만 나온 것, 나머지는 `-`.
|
||||
구글은 첫 페이지(사이트 6~9개)만 본다. 로그인한 브라우저·위치(성남) 기준.
|
||||
|
||||
### 최근 요약 (10/29, 직전 측정 대비 — 구글은 10/27, 네이버는 10/28)
|
||||
### 최근 요약 (10/30, 직전 10/29 대비)
|
||||
|
||||
- 새로 잡힘: 없음
|
||||
- 빠짐: 없음 (10/29에 빠진 `성남 오늘 날씨`·`고양 내일 날씨`·`수원 오늘 날씨`는 구글·네이버 모두 여전히 -)
|
||||
- 순위 바뀜: 없음 — `날씨각` 네이버 1 그대로(첫 링크가 `/` → `/tomorrow/incheon/namdong`으로 바뀜), 구글은 `제주 날씨`부터 CAPTCHA로 `날씨각` 포함 16개 못 잼
|
||||
|
||||
### 지난 요약 (10/29, 직전 측정 대비 — 구글은 10/27, 네이버는 10/28)
|
||||
|
||||
- 새로 잡힘: 없음
|
||||
- 빠짐: `성남 오늘 날씨` → 구글 2p8→-, 네이버 10→-. `고양 내일 날씨` → 구글 2p7→-. `수원 오늘 날씨` → 네이버 14→-. (구글 `site:weather.o2o.kr 성남` 은 9건 나와 색인은 살아 있음)
|
||||
@@ -430,21 +436,22 @@
|
||||
|
||||
실제 검색량이 큰 검색어 78개 + 날씨각. 구글 = 로그인 브라우저·성남 위치, 1~2페이지. 네이버 = 통합검색·웹 탭 첫 화면. `-` = 없음, `?` = 구글 차단으로 못 잼.
|
||||
|
||||
| 검색어 | 구글 10/26 | 구글 10/27 | 구글 10/28 | 구글 10/29 | 네이버 10/26 | 네이버 10/27 | 네이버 10/28 | 네이버 10/29 |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| 날씨각 | 1p1 | 1p1 | 1p1 | 1p1 | 1 | 1 | 1 | 1 |
|
||||
| 성남 오늘 날씨 | 2p10 `/today/gyeonggi/seongnam` | 2p8 | ? | - | 10 | 6 | 10 | - |
|
||||
| 수원 오늘 날씨 | - | - | ? | - | - | - | 14 `/today/gyeonggi/suwon` | - |
|
||||
| 고양 내일 날씨 | - | 2p7 `/tomorrow/gyeonggi/goyang` | ? | - | - | - | - | - |
|
||||
| 군산 오늘 날씨 | 3p4 (2p 밖) | ? | ? | - | - | - | - | - |
|
||||
| 오늘 날씨 · 내일 날씨 · 모레 날씨 · 이번주 날씨 · 주말 날씨 · 날씨 | - | - | ? | - | - | - | - | - |
|
||||
| 서울 · 부산 · 인천 · 대전 · 광주 · 울산 · 세종 × 오늘/내일/날씨, 수원 내일·수원 날씨, 대구 날씨, 성남 내일·성남 날씨 | - | - | ? | - | - | - | - | - |
|
||||
| 대구 오늘 날씨 · 대구 내일 날씨 | - | ? | ? | - | - | - | - | - |
|
||||
| 고양 오늘·고양 날씨, 용인 · 창원 · 청주 · 천안 · 전주 × 오늘/내일/날씨 | - | - | ? | - | - | - | - | - |
|
||||
| 군산 내일·군산 날씨, 포항 · 제주 · 김해 · 화성 · 부천 · 안산 · 남양주 × 오늘/내일/날씨 | - | ? | ? | - | - | - | - | - |
|
||||
| 검색어 | 구글 10/26 | 구글 10/27 | 구글 10/28 | 구글 10/29 | 구글 10/30 | 네이버 10/26 | 네이버 10/27 | 네이버 10/28 | 네이버 10/29 | 네이버 10/30 |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 날씨각 | 1p1 | 1p1 | 1p1 | 1p1 | ? | 1 | 1 | 1 | 1 | 1 `/tomorrow/incheon/namdong` |
|
||||
| 성남 오늘 날씨 | 2p10 `/today/gyeonggi/seongnam` | 2p8 | ? | - | - | 10 | 6 | 10 | - | - |
|
||||
| 수원 오늘 날씨 | - | - | ? | - | - | - | - | 14 `/today/gyeonggi/suwon` | - | - |
|
||||
| 고양 내일 날씨 | - | 2p7 `/tomorrow/gyeonggi/goyang` | ? | - | - | - | - | - | - | - |
|
||||
| 군산 오늘 날씨 | 3p4 (2p 밖) | ? | ? | - | - | - | - | - | - | - |
|
||||
| 오늘 날씨 · 내일 날씨 · 모레 날씨 · 이번주 날씨 · 주말 날씨 · 날씨 | - | - | ? | - | - | - | - | - | - | - |
|
||||
| 서울 · 부산 · 인천 · 대전 · 광주 · 울산 · 세종 × 오늘/내일/날씨, 수원 내일·수원 날씨, 대구 날씨, 성남 내일·성남 날씨 | - | - | ? | - | - | - | - | - | - | - |
|
||||
| 대구 오늘 날씨 · 대구 내일 날씨 | - | ? | ? | - | - | - | - | - | - | - |
|
||||
| 고양 오늘·고양 날씨, 용인 · 창원 · 청주 · 천안 · 전주 × 오늘/내일/날씨 | - | - | ? | - | - | - | - | - | - | - |
|
||||
| 군산 내일·군산 날씨, 포항 · 제주 · 김해 · 화성 · 부천 · 안산 · 남양주 × 오늘/내일/날씨 | - | ? | ? | - | - (제주 날씨·김해·화성·부천·안산·남양주는 ?) | - | - | - | - | - |
|
||||
|
||||
- 서울·부산·인천·대구·대전·광주·울산은 시 단위 페이지가 없음(구 페이지만). '서울 날씨'를 받을 페이지 자체가 없다.
|
||||
- 원본: `docs/search_log/{날짜}_naver_대표검색어.tsv`
|
||||
- 10/30 구글: 탭에서 열어 63개까지 잼, `제주 날씨`에서 CAPTCHA(sorry)로 멈춤. 나머지 16개(`날씨각` 포함)는 `?`.
|
||||
- 10/28 구글: 브라우저 fetch 로 받은 검색 결과가 'JavaScript 필요' 안내 페이지로 바뀌어 결과를 못 읽었고, 탭에서 직접 열자 CAPTCHA(sorry)가 떠 멈춤. 다음 측정은 탭에서 실제 페이지를 열어 읽는 방식으로 해야 함.
|
||||
|
||||
### 키워드별 잡힘 (10/26)
|
||||
|
||||
@@ -14,7 +14,9 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
||||
- 왜 GTM이 아니라 GA4 직접인가: 이벤트를 코드(`analytics.ts`)에서 정하므로, GTM을 쓰면 이벤트마다 트리거·태그를 한 번 더 만들어야 한다. 광고 픽셀도, 마케터가 직접 손볼 일도 아직 없다.
|
||||
- 모든 이벤트에 `platform: 'web' | 'toss'`가 붙는다. `index.html`의 `gtag('config')`에서 빌드 모드(`%MODE%`)로 정한다. GA4에서 보려면 맞춤 측정기준(이벤트 범위, `platform`)을 한 번 등록한다.
|
||||
- 개발 서버(`npm run dev`)에서는 `track()`이 이벤트를 보내지 않는다. 단 `index.html`의 페이지 조회(`page_view`)는 개발 서버에서도 나가므로 GA4에서 `localhost`를 걸러 본다.
|
||||
- 이벤트 이름은 영어 snake_case. GA4 추천 이벤트(`share`, `login`, `sign_up`, `select_content`)는 이름을 그대로 써야 GA4 기본 보고서에 잡힌다.
|
||||
- GA 에 찍히는 이벤트 이름은 한국어(띄어쓰기 대신 `_`, 40자 이내). 코드에서는 영어 키로 부르고 `analytics.ts` `GA_NAME` 이 한국어로 바꿔 보낸다. 새 이벤트는 `Events` 와 `GA_NAME` 둘 다 넣는다.
|
||||
- 로그인·회원가입·공유·글_열기도 한국어라 GA4 기본 보고서(추천 이벤트 집계)에는 안 잡힌다. 탐색 보고서에서 이벤트 이름으로 본다.
|
||||
- 2026-10-30 전 데이터는 영어 이름(괄호 안 코드 키)으로 남아 있다.
|
||||
- 값은 사람이 읽을 수 있게 한글 그대로 둔다 (예: `gak_name: '야장각'`).
|
||||
- 개인정보(아이디, 닉네임 등)는 값에 넣지 않는다.
|
||||
- 페이지 이동은 코드로 보내지 않는다. GA4 향상된 측정의 "브라우저 기록 이벤트 기반 페이지 변경"이 잡는다(기본 켜짐). 모든 이벤트에 GA4가 `page_location`을 붙이므로 어느 탭에서 일어났는지는 따로 보내지 않는다.
|
||||
@@ -23,52 +25,61 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
||||
|
||||
| 이벤트 | 언제 | 값 | 코드 |
|
||||
|---|---|---|---|
|
||||
| `view_gak` | 각 상세 시트가 열려 데이터가 뜸 (같은 각은 한 번만) | `index_id`, `gak_name`, `score`, `rank` | `Sheets.tsx` `GakSheet` |
|
||||
| `select_content` | 글 시트가 열려 데이터가 뜸 (같은 글은 한 번만) | `content_type: 'article'`, `item_id`(글 번호), `category`(분류 이름) | `Sheets.tsx` `ArticleSheet` |
|
||||
| `share` | 공유창으로 보내기 성공, 또는 이미지 내려받기 | `content_type: 'image'`, `item_id`(공유 제목), `method: 'share_sheet' \| 'download'`, `ratio`(이미지 비율) | `Sheets.tsx` `ShareSheet` `send` |
|
||||
| `login` | 로그인 성공 (구글로 처음 들어와 자동 가입된 경우도 `login`) | `method: 'id' \| 'google' \| 'toss'`(앱인토스) | `Sheets.tsx` `LoginSheet` `done`, `TossLoginSheet` |
|
||||
| `sign_up` | 가입 성공 | `method: 'id'` | `Sheets.tsx` `LoginSheet` `done` |
|
||||
| `region_change` | 지역 목록에서 고름, 또는 위치로 가까운 구를 찾음 | `region_name`, `method: 'list' \| 'location'` | `Sheets.tsx` `RegionSheet`, `region.tsx` `findNearest` |
|
||||
| `install_banner_view` | 오늘 탭의 '홈 화면에 추가' 카드가 보임 (설치할 수 있는 곳에서, 닫은 지 2주 안 지났으면 안 보임) | 없음 | `installBanner.tsx` `InstallBanner` |
|
||||
| `install_click` | '홈 화면에 추가'를 누름 | `from: 'banner' \| 'menu'`(카드·내 정보 메뉴), `method: 'prompt' \| 'guide'`(설치창을 띄움·기기별 안내를 염) | `install.ts` `useInstall` |
|
||||
| `install_choice` | 설치창에서 고름 (안드로이드·PC Chrome·Edge) | `outcome: 'accepted' \| 'dismissed'` | `install.ts` `promptInstall` |
|
||||
| `install_done` | 설치 완료 (브라우저가 `appinstalled`를 줄 때만. 아이폰은 오지 않음) | 없음 | `install.ts` |
|
||||
| `app_launch` | 홈 화면 아이콘(설치한 앱)으로 엶 | `mode: 'standalone'` | `main.tsx` |
|
||||
| `boot_stuck` | 8초 넘게 '날씨 불러오는 중' 첫 화면이 남음 (페이지마다 한 번) | `reason`(첫 오류 문구, 100자), `seconds`, `tries`(연달아 다시 불러온 횟수), `app_started`(앱 파일 실행 여부) | `index.html` 첫 화면 스크립트 |
|
||||
| `sheet_open` | 아래에서 올라오는 창이 열림 (각·글·보내기·댓글·로그인·내 정보·지역·내 각·홈 화면 추가·점수 근거·이야기 등) | `sheet`(창 종류: `gak`·`article`·`share`·`comments`·`login`·`me`·`region`·`mix`·`myGak`·`install`·`weatherWhy`·`talk`·`seasonWeek`) | `Sheets.tsx` `SheetProvider` `open` |
|
||||
| `like` | 좋아요 성공 (취소는 안 보냄) | `content_type: 'post' \| 'comment' \| 'talk' \| 'hero_post' \| 'gak_post' \| 'foliage_post' \| 'events_post' \| 'season_post'`, `item_id`(포스트·댓글·글 번호) | `Post.tsx` `FullCard`, `pinnedLike.ts`, `Sheets.tsx` `CommentRow`, `talk.tsx` |
|
||||
| `comment` | 댓글 올리기 성공 | `post_id` | `Sheets.tsx` `CommentsSheet` `send` |
|
||||
| `talk_comment` | 사람 글에 댓글 올리기 성공 (로그인한 사람만) | `talk_id`(글 번호) | `Sheets.tsx` `CommentsSheet` `send` |
|
||||
| `terms_agree` | 댓글 쓰기 전 이용약관 동의 성공 | 없음 | `Sheets.tsx` `CommentsSheet` `agreeAndSend` |
|
||||
| `report` | 신고 성공 | `content_type: 'comment' \| 'talk'`, `reason`(신고 이유 번호) | `Sheets.tsx` `CommentMenu`, `talk.tsx` |
|
||||
| `block` | 차단 성공 | `content_type: 'comment' \| 'talk'` | `Sheets.tsx` `CommentMenu`, `talk.tsx` |
|
||||
| `talk_post` | 이야기 글 올리기 성공 | `topic`(주제 번호), `with_image` | `talk.tsx` 글쓰기 `submit` |
|
||||
| `feed_item_view` | 오늘 피드에 섞인 사람 글·행사 포스트가 처음 반쯤 보임 (한 장에 한 번) | `item_type: 'talk' \| 'event'`, `position`(피드에서 그 종류의 몇 번째) | `TodayPage.tsx` `Seen` |
|
||||
| `hero_day_switch` | 히어로 오늘/내일 스위치를 바꿈 | `day: 'today' \| 'tomorrow'` | `TodayPage.tsx` |
|
||||
| `shorts_open` | 쇼츠 페이지(/shorts/영상ID)로 들어옴 (오늘 화면 쇼츠 줄·공유 링크) | `video_id` | `Shorts.tsx` `ShortsPage` |
|
||||
| `shorts_view` | 쇼츠를 넘겨 다른 영상으로 감 | `video_id`, `index`(목록 순서) | `Shorts.tsx` `ShortsPage` |
|
||||
| `shorts_sound` | 쇼츠 소리 켜기·끄기 | `on` | `Shorts.tsx` `toggleSound` |
|
||||
| `foliage_open` | 단풍 지도 페이지(/foliage)를 엶 | 없음 | `FoliagePage.tsx` |
|
||||
| `foliage_spot` | 단풍 명소를 고름 | `spot_name`, `from: 'page' \| 'card'`(지도 페이지·오늘 화면 카드) | `FoliagePage.tsx`, `foliageMap.tsx` |
|
||||
| `my_gak_save` | 내 각 만들기 성공 (로그인 전엔 기기에 저장) | `gak_name` | `myGakState.ts` `create` |
|
||||
| `toss_intro_start` | 토스판 첫 소개 화면에서 '시작하기' | 없음 | `tossIntro.tsx` |
|
||||
| `install_banner_close` | '홈 화면에 추가' 띠를 × 로 닫음 | 없음 | `installBanner.tsx` |
|
||||
| `fortune_draw` | 오늘 한 장에서 카드를 뽑음 (하루 한 번, 다시 열 때는 안 보냄) | `card`(각 코드) | `fortune.tsx` `useTodayCard` |
|
||||
| `day_log` | 저녁 체크인을 적어 둠 (고쳐 적어도 보냄). 다녀온 곳 이름은 보내지 않음 | `mood`(1~5), `went_out`, `card_hit`(맞았어요 true·글쎄요 false·안 고름 null) | `fortune.tsx` `useTodayCard` |
|
||||
| `today_icon` | 오늘 탭 아이콘 줄에서 아이콘을 누름 | `icon`(`tarot`·`saju`·`game`·`foliage`·`shorts`·`myGak`·`talk`) | `todayIcons.tsx` `TodayIcons` |
|
||||
| `saju_input` | 날씨 사주 생년월일을 넣음 (생년월일 값은 보내지 않음) | `with_time` | `SajuPage.tsx` `BirthForm` |
|
||||
| `saju_view` | 날씨 사주 결과가 뜸 | `scene`(내 기운 이름), `score`, `strength`(신강·중화·신약), `top_element`(가장 센 오행) | `SajuPage.tsx` `Reading` |
|
||||
| `game_start` | 구름 합치기 한 판의 첫 그림을 떨어뜨림 (페이지만 열고 안 한 사람과 구분) | `again`(다시 하기로 시작), `logged_in`, `wind_ms`(오늘 우리 구 풍속) | `CloudMergePage.tsx` `onUp` |
|
||||
| `game_round` | 구름 합치기 라운드를 깸 | `round`(깬 라운드), `score`(그때 총점), `logged_in`(각을 받는지) | `CloudMergePage.tsx` `onScore` |
|
||||
| `game_over` | 구름 합치기가 넘쳐서 끝남 | `round`(끝난 라운드), `score`, `best`(최고 기록 갱신), `drops`(떨어뜨린 횟수) | `CloudMergePage.tsx` `onOver` |
|
||||
| `각_보기` (코드 `view_gak`) | 각 상세 시트가 열려 데이터가 뜸 (같은 각은 한 번만) | `index_id`, `gak_name`, `score`, `rank` | `Sheets.tsx` `GakSheet` |
|
||||
| `글_열기` (코드 `select_content`) | 글 시트가 열려 데이터가 뜸 (같은 글은 한 번만) | `content_type: 'article'`, `item_id`(글 번호), `category`(분류 이름) | `Sheets.tsx` `ArticleSheet` |
|
||||
| `공유` (코드 `share`) | 공유창으로 보내기 성공, 또는 이미지 내려받기 | `content_type: 'image'`, `item_id`(공유 제목), `method: 'share_sheet' \| 'download'`, `ratio`(이미지 비율) | `Sheets.tsx` `ShareSheet` `send` |
|
||||
| `로그인` (코드 `login`) | 로그인 성공 (이미 있던 계정) | `method: 'id' \| 'google' \| 'toss'`(앱인토스) | `Sheets.tsx` `LoginSheet` `done`, `TossLoginSheet` |
|
||||
| `회원가입` (코드 `sign_up`) | 가입 성공 (구글·토스로 처음 들어와 계정이 새로 생김, 서버 응답 `is_new`) | `method: 'id' \| 'google' \| 'toss'` | `Sheets.tsx` `LoginSheet` `done`, `TossLoginSheet` |
|
||||
| `지역_변경` (코드 `region_change`) | 지역 목록에서 고름, 또는 위치로 가까운 구를 찾음 | `region_name`, `method: 'list' \| 'location'` | `Sheets.tsx` `RegionSheet`, `region.tsx` `findNearest` |
|
||||
| `설치배너_노출` (코드 `install_banner_view`) | 오늘 탭의 '홈 화면에 추가' 카드가 보임 (설치할 수 있는 곳에서, 닫은 지 2주 안 지났으면 안 보임) | 없음 | `installBanner.tsx` `InstallBanner` |
|
||||
| `설치_누름` (코드 `install_click`) | '홈 화면에 추가'를 누름 | `from: 'banner' \| 'menu'`(카드·내 정보 메뉴), `method: 'prompt' \| 'guide'`(설치창을 띄움·기기별 안내를 염) | `install.ts` `useInstall` |
|
||||
| `설치_선택` (코드 `install_choice`) | 설치창에서 고름 (안드로이드·PC Chrome·Edge) | `outcome: 'accepted' \| 'dismissed'` | `install.ts` `promptInstall` |
|
||||
| `설치_완료` (코드 `install_done`) | 설치 완료 (브라우저가 `appinstalled`를 줄 때만. 아이폰은 오지 않음) | 없음 | `install.ts` |
|
||||
| `앱_실행` (코드 `app_launch`) | 홈 화면 아이콘(설치한 앱)으로 엶 | `mode: 'standalone'` | `main.tsx` |
|
||||
| `첫화면_멈춤` (코드 `boot_stuck`) | 8초 넘게 '날씨 불러오는 중' 첫 화면이 남음 (페이지마다 한 번) | `reason`(첫 오류 문구, 100자), `seconds`, `tries`(연달아 다시 불러온 횟수), `app_started`(앱 파일 실행 여부) | `index.html` 첫 화면 스크립트 |
|
||||
| `창_열기` (코드 `sheet_open`) | 아래에서 올라오는 창이 열림 (각·글·보내기·댓글·로그인·내 정보·지역·내 각·홈 화면 추가·점수 근거·이야기 등) | `sheet`(창 종류: `gak`·`article`·`share`·`comments`·`login`·`me`·`region`·`mix`·`myGak`·`install`·`weatherWhy`·`talk`·`seasonWeek`) | `Sheets.tsx` `SheetProvider` `open` |
|
||||
| `좋아요` (코드 `like`) | 좋아요 성공 (취소는 안 보냄) | `content_type: 'post' \| 'comment' \| 'talk' \| 'hero_post' \| 'gak_post' \| 'foliage_post' \| 'events_post' \| 'season_post'`, `item_id`(포스트·댓글·글 번호) | `Post.tsx` `FullCard`, `pinnedLike.ts`, `Sheets.tsx` `CommentRow`, `talk.tsx` |
|
||||
| `댓글` (코드 `comment`) | 댓글 올리기 성공 | `post_id` | `Sheets.tsx` `CommentsSheet` `send` |
|
||||
| `이야기_댓글` (코드 `talk_comment`) | 사람 글에 댓글 올리기 성공 (로그인한 사람만) | `talk_id`(글 번호) | `Sheets.tsx` `CommentsSheet` `send` |
|
||||
| `약관_동의` (코드 `terms_agree`) | 댓글 쓰기 전 이용약관 동의 성공 | 없음 | `Sheets.tsx` `CommentsSheet` `agreeAndSend` |
|
||||
| `신고` (코드 `report`) | 신고 성공 | `content_type: 'comment' \| 'talk'`, `reason`(신고 이유 번호) | `Sheets.tsx` `CommentMenu`, `talk.tsx` |
|
||||
| `차단` (코드 `block`) | 차단 성공 | `content_type: 'comment' \| 'talk'` | `Sheets.tsx` `CommentMenu`, `talk.tsx` |
|
||||
| `이야기_올림` (코드 `talk_post`) | 이야기 글 올리기 성공 | `topic`(주제 번호, 6~9 는 기념일: 할로윈·빼빼로데이·크리스마스·추석), `with_image` | `talk.tsx` 글쓰기 `submit` |
|
||||
| `피드_항목_노출` (코드 `feed_item_view`) | 오늘 피드에 섞인 사람 글·행사 포스트가 처음 반쯤 보임 (한 장에 한 번) | `item_type: 'talk' \| 'event'`, `position`(피드에서 그 종류의 몇 번째) | `TodayPage.tsx` `Seen` |
|
||||
| `오늘내일_전환` (코드 `hero_day_switch`) | 히어로 오늘/내일 스위치를 바꿈 | `day: 'today' \| 'tomorrow'` | `TodayPage.tsx` |
|
||||
| `내일에서_오늘로` (코드 `tomorrow_to_today`) | 내일 날씨 페이지(`/tomorrow/...`) 맨 아래 '오늘 ○○ 소식 보기'를 누름 | `region_name` | `TomorrowFeed.tsx` |
|
||||
| `검색_유입` (코드 `search_landing`) | 구글·네이버 검색 결과에서 지역 오늘·내일 페이지(/today·/tomorrow)로 들어옴 (페이지 열 때 한 번). 검색 결과 제목·설명 새 문구와 예전 문구의 유입을 견주려고 | `page: 'today' \| 'tomorrow'`, `engine: 'google' \| 'naver'`, `copy: 'new' \| 'old' \| 'none'`(서버가 넣은 `seo-copy` 표시, 서버가 못 채운 정적 페이지면 none. 새 문구 페이지 목록은 `backend/services/seo_copy_test.json`) | `regionContext.ts` |
|
||||
| `쇼츠_열기` (코드 `shorts_open`) | 쇼츠 페이지(/shorts/영상ID)로 들어옴 (오늘 화면 쇼츠 줄·공유 링크) | `video_id` | `Shorts.tsx` `ShortsPage` |
|
||||
| `쇼츠_보기` (코드 `shorts_view`) | 쇼츠를 넘겨 다른 영상으로 감 | `video_id`, `index`(목록 순서) | `Shorts.tsx` `ShortsPage` |
|
||||
| `쇼츠_소리` (코드 `shorts_sound`) | 쇼츠 소리 켜기·끄기 | `on` | `Shorts.tsx` `toggleSound` |
|
||||
| `단풍지도_열기` (코드 `foliage_open`) | 단풍 지도 페이지(/foliage)를 엶 | 없음 | `FoliagePage.tsx` |
|
||||
| `단풍명소_보기` (코드 `foliage_spot`) | 단풍 명소를 고름 | `spot_name`, `from: 'page' \| 'card'`(지도 페이지·오늘 화면 카드) | `FoliagePage.tsx`, `foliageMap.tsx` |
|
||||
| `내각_저장` (코드 `my_gak_save`) | 내 각 만들기 성공 (로그인 전엔 기기에 저장) | `gak_name` | `myGakState.ts` `create` |
|
||||
| `토스소개_시작` (코드 `toss_intro_start`) | 토스판 첫 소개 화면에서 '시작하기' | 없음 | `tossIntro.tsx` |
|
||||
| `설치배너_닫기` (코드 `install_banner_close`) | '홈 화면에 추가' 띠를 × 로 닫음 | 없음 | `installBanner.tsx` |
|
||||
| `타로_뽑기` (코드 `fortune_draw`) | 오늘 한 장에서 카드를 뽑음 (하루 한 번, 다시 열 때는 안 보냄) | `card`(각 코드) | `fortune.tsx` `useTodayCard` |
|
||||
| `하루_기록` (코드 `day_log`) | 저녁 체크인을 적어 둠 (고쳐 적어도 보냄). 다녀온 곳 이름은 보내지 않음 | `mood`(1~5), `went_out`, `card_hit`(맞았어요 true·글쎄요 false·안 고름 null) | `fortune.tsx` `useTodayCard` |
|
||||
| `오늘아이콘_누름` (코드 `today_icon`) | 오늘 탭 아이콘 줄에서 아이콘을 누름 | `icon`(`tarot`·`saju`·`game`·`foliage`·`shorts`·`myGak`·`talk`) | `todayIcons.tsx` `TodayIcons` |
|
||||
| `사주_입력` (코드 `saju_input`) | 날씨 사주 생년월일을 넣음 (생년월일 값은 보내지 않음) | `with_time` | `SajuPage.tsx` `BirthForm` |
|
||||
| `사주_결과` (코드 `saju_view`) | 날씨 사주 결과가 뜸 | `scene`(내 기운 이름), `score`, `strength`(신강·중화·신약), `top_element`(가장 센 오행) | `SajuPage.tsx` `Reading` |
|
||||
| `게임_시작` (코드 `game_start`) | 구름 합치기 한 판의 첫 그림을 떨어뜨림 (페이지만 열고 안 한 사람과 구분) | `again`(다시 하기로 시작), `logged_in`, `wind_ms`(오늘 우리 구 풍속), `theme`(그림: `basic`·`halloween`·`pepero`·`christmas`·`chuseok`, `holiday.ts`) | `CloudMergePage.tsx` `onUp` |
|
||||
| `게임_라운드` (코드 `game_round`) | 구름 합치기 라운드를 깸 | `round`(깬 라운드), `score`(그때 총점), `logged_in`(각을 받는지) | `CloudMergePage.tsx` `onScore` |
|
||||
| `게임_끝` (코드 `game_over`) | 구름 합치기가 넘쳐서 끝남 | `round`(끝난 라운드), `score`, `best`(최고 기록 갱신), `drops`(떨어뜨린 횟수) | `CloudMergePage.tsx` `onOver` |
|
||||
|
||||
- 공유창에서 사용자가 취소하면 `share`를 보내지 않는다.
|
||||
- 구름 합치기 게임 방법 창은 `sheet_open`(`sheet: 'gameHelp'`)으로 잡혀 따로 보내지 않는다.
|
||||
- 토스판은 로그인이 없어 `login` `toss`는 나가지 않는다. `id`·`sign_up`도 지금 화면에 아이디 가입이 없어 나가지 않는다.
|
||||
- 가입·로그인은 둘 중 하나만 나간다: 처음이면 `sign_up`, 다시 들어오면 `login`. `id` 는 지금 화면에 아이디 가입·로그인이 없어 나가지 않는다.
|
||||
- 점수 근거·댓글창 열기처럼 창으로 여는 기능은 따로 이벤트를 두지 않고 `sheet_open`의 `sheet`로 나눠 본다.
|
||||
- `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다.
|
||||
- 설치는 카드 노출 → 누름 → 설치 완료 → 홈 화면 실행 순서로 본다. 아이폰은 설치 완료를 알 수 없어 `app_launch`로 대신 본다.
|
||||
- 새 이벤트는 `analytics.ts`의 `Events` 타입에 먼저 더한다. 타입에 없는 이름은 빌드에서 걸린다.
|
||||
- 새 이벤트는 `shared/lib/analytics.ts`의 `Events` 타입과 `GA_NAME` 에 먼저 더한다 (웹·앱이 같이 씀). 타입에 없는 이름은 빌드에서 걸린다.
|
||||
|
||||
## 앱 (안드로이드, `mobile/`)
|
||||
|
||||
- 앱도 같은 이벤트 이름·값으로 `track()`을 부른다 (`mobile/src/lib/analytics.ts`). 모든 이벤트에 `platform: 'app'`이 붙는다.
|
||||
- **아직 GA4로 보내지 않는다 (2026-11-04).** Firebase Analytics(`google-services.json`)를 붙이면 앱 시작 때 `setAnalyticsSender`로 보내는 함수를 단다. 그 전까지 `track()`은 아무것도 보내지 않는다. 개발 빌드(`__DEV__`)는 붙인 뒤에도 보내지 않는다.
|
||||
- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`). 오늘 아이콘 줄: `today_icon`(`components/today/icons.tsx`). 사주: `saju_input`(`components/saju/birth-form.tsx`), `saju_view`(`saju/reading.tsx`). 단풍 지도: `foliage_open`(`app/foliage.tsx`), `foliage_spot`(`components/foliage/*`, 화면 `page`·피드 카드 `card`). 쇼츠: `shorts_open`·`shorts_view`·`shorts_sound`(`app/shorts/[id].tsx`). 구름 합치기 게임은 앱이 웹 `/game`을 웹뷰로 띄우므로 `game_start`·`game_round`·`game_over`는 웹 페이지가 보내고 `platform: 'web'`으로 찍힌다(앱 안 게임과 웹 게임을 GA에서 나눠 볼 수 없음).
|
||||
- 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다.
|
||||
|
||||
## GA4 설정
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@
|
||||
}
|
||||
boot.appendChild(p)
|
||||
boot.appendChild(b)
|
||||
gtag('event', 'boot_stuck', { reason: reason.slice(0, 100), seconds: Math.round((Date.now() - start) / 1000), tries: tries(), app_started: !!window.__appStarted })
|
||||
gtag('event', '첫화면_멈춤', { reason: reason.slice(0, 100), seconds: Math.round((Date.now() - start) / 1000), tries: tries(), app_started: !!window.__appStarted })
|
||||
}, 8000)
|
||||
var timer = setInterval(function () {
|
||||
if (document.getElementById('boot')) retry()
|
||||
|
||||
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 42 KiB |
@@ -9,6 +9,7 @@ import { AuthProvider } from './auth'
|
||||
import { RegionProvider } from './region'
|
||||
import { useAuth } from './authContext'
|
||||
import { preloadGoogle } from './googleScript'
|
||||
import { currentHoliday } from './holiday'
|
||||
import { LevelBadge, LevelWatcher } from './level'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
@@ -106,6 +107,8 @@ const SHOOTS = [
|
||||
{ top: '14%', left: '96%', '--len': '120px', '--dur': '12s', '--dl': '9s' },
|
||||
]
|
||||
|
||||
const HOLIDAY = currentHoliday()
|
||||
|
||||
/** 화면 전체 하늘: 시간대별 색, 아주 느리게 일렁이는 색 덩어리, 밤에는 별 */
|
||||
function SkyBg() {
|
||||
const { kind } = useSky()
|
||||
@@ -116,10 +119,11 @@ function SkyBg() {
|
||||
return () => document.removeEventListener('visibilitychange', onVis)
|
||||
}, [])
|
||||
return (
|
||||
<div className={cx('b-skybg pointer-events-none fixed inset-0 overflow-hidden', hidden && 'b-paused')} data-t={kind} aria-hidden="true">
|
||||
<div className={cx('b-skybg pointer-events-none fixed inset-0 overflow-hidden', hidden && 'b-paused')} data-t={kind} data-h={HOLIDAY?.key} aria-hidden="true">
|
||||
{(['morning', 'day', 'sunset', 'night'] as const).map((k) => (
|
||||
<div key={k} className={cx('b-sky-lay absolute inset-0', `b-sky-${k}`)} />
|
||||
))}
|
||||
{HOLIDAY && <div className="b-sky-lay b-sky-holiday absolute inset-0" />}
|
||||
<span className="b-blob b-blob-1" />
|
||||
<span className="b-blob b-blob-2" />
|
||||
<span className="b-blob b-blob-3" />
|
||||
@@ -264,6 +268,11 @@ function Shell() {
|
||||
<FirstLoad />
|
||||
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
|
||||
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
|
||||
{HOLIDAY && (
|
||||
<div className="b-holiday-head pointer-events-none fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] overflow-hidden" data-h={HOLIDAY.key} data-t={kind} aria-hidden="true">
|
||||
<i />
|
||||
</div>
|
||||
)}
|
||||
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
|
||||
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(104px+env(safe-area-inset-bottom,0px))]">
|
||||
<TopBar />
|
||||
|
||||
@@ -10,7 +10,7 @@ import { slotAt } from '@nalssigak/shared/lib/weatherText'
|
||||
import { track } from '../lib/analytics'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { createGame, DROP_Y, H, LEVELS, LINE_Y, loadBest, randomLevel, roundTarget, saveBest, W, windDir, type Game } from './cloudMerge'
|
||||
import { createGame, DROP_Y, H, HOLIDAY, LEVELS, LINE_Y, loadBest, randomLevel, roundTarget, saveBest, W, windDir, type Game } from './cloudMerge'
|
||||
import { useLevel } from './level'
|
||||
import { iconSrc } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
@@ -213,7 +213,7 @@ export function CloudMergePage() {
|
||||
const onUp = (e: PointerEvent<HTMLCanvasElement>) => {
|
||||
const game = gameRef.current
|
||||
if (!game || over || performance.now() < coolRef.current) return
|
||||
if (dropsRef.current === 0) track('game_start', { again: play > 0, logged_in: loggedIn, wind_ms: windMs })
|
||||
if (dropsRef.current === 0) track('game_start', { again: play > 0, logged_in: loggedIn, wind_ms: windMs, theme: HOLIDAY?.key ?? 'basic' })
|
||||
dropsRef.current += 1
|
||||
game.drop(nextRef.current, toX(e))
|
||||
coolRef.current = performance.now() + 450
|
||||
|
||||
@@ -126,7 +126,7 @@ function MoonPic({ pct, waxing }: { pct: number; waxing: boolean }) {
|
||||
)
|
||||
}
|
||||
|
||||
function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
|
||||
export function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
|
||||
const { open } = useSheet()
|
||||
if (slide.kind === 'hours') {
|
||||
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]))
|
||||
|
||||
@@ -1061,7 +1061,8 @@ function LoginSheet({ onDone, onLoggedIn, why }: { onDone: () => void; onLoggedI
|
||||
return
|
||||
}
|
||||
setTokens(res.access_token, res.refresh_token ?? null)
|
||||
track('login', { method: 'google' })
|
||||
if (res.is_new) track('sign_up', { method: 'google' })
|
||||
else track('login', { method: 'google' })
|
||||
onLoggedIn()
|
||||
}
|
||||
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
||||
@@ -1117,7 +1118,8 @@ function TossLoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn
|
||||
onSuccess: (res) => {
|
||||
if (!res.result?.success || !res.access_token) return setError('토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.')
|
||||
setTokens(res.access_token, res.refresh_token ?? null)
|
||||
track('login', { method: 'toss' })
|
||||
if (res.is_new) track('sign_up', { method: 'toss' })
|
||||
else track('login', { method: 'toss' })
|
||||
onLoggedIn()
|
||||
},
|
||||
onError: () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.'),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { FeedComposer, TalkCard } from './talk'
|
||||
import { TOPICS, useMyTalks, useTopicTalks } from './talkState'
|
||||
import { openTopics, TOPICS, useMyTalks, useTopicTalks } from './talkState'
|
||||
import { Rail, Sec } from './ui'
|
||||
|
||||
type Tab = TalkTopic | 'all' | 'mine'
|
||||
@@ -34,7 +34,7 @@ export function TalkPage() {
|
||||
const topicList = useTopicTalks(tab === 'all' || tab === 'mine' ? undefined : tab)
|
||||
const mineList = useMyTalks(tab === 'mine' && loggedIn)
|
||||
const { talks, loaded, more, loadMore } = tab === 'mine' ? mineList : topicList
|
||||
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...TOPICS, ['mine', '내 글']]
|
||||
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...openTopics(), ['mine', '내 글']]
|
||||
const go = (k: Tab) => setParams(k === 'mine' ? { mine: '1' } : k === 'all' ? {} : { topic: String(k) }, { replace: true })
|
||||
|
||||
return (
|
||||
|
||||
@@ -27,6 +27,7 @@ import { usePinnedLike } from './pinnedLike'
|
||||
import { ShortsRail } from './Shorts'
|
||||
import { FeedComposer, TalkPost } from './talk'
|
||||
import { useTopicTalks } from './talkState'
|
||||
import { TomorrowFeed } from './TomorrowFeed'
|
||||
import { useLandingAbout, useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { useSky } from './skyContext'
|
||||
@@ -579,6 +580,8 @@ function Seen({ item, position, children }: { item: 'talk' | 'event'; position:
|
||||
export function TodayPage() {
|
||||
const { region } = useRegion()
|
||||
const about = useLandingAbout()
|
||||
// 내일 날씨 페이지는 히어로 아래를 내일 것으로 (오늘 페이지와 본문이 거의 같아 구글이 둘 중 하나만 색인하던 것)
|
||||
const ahead = useLocation().pathname.startsWith('/tomorrow/')
|
||||
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
|
||||
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
|
||||
const { preview } = useSky()
|
||||
@@ -615,61 +618,67 @@ export function TodayPage() {
|
||||
|
||||
return (
|
||||
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
|
||||
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
|
||||
<section key={region.code} aria-label={ahead ? '내일' : '오늘'} aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
|
||||
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} />
|
||||
<TodayIcons />
|
||||
<ShortsRail />
|
||||
<FeedComposer />
|
||||
<div id={MY_GAK_ID} className="scroll-mt-16">
|
||||
<MyGakRow />
|
||||
</div>
|
||||
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
|
||||
{stories.some((g) => g.active) ? (
|
||||
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
|
||||
) : load === 'loading' ? (
|
||||
<PostCardSkel />
|
||||
{ahead ? (
|
||||
<TomorrowFeed tomorrow={f?.hero?.tomorrow} load={load} />
|
||||
) : (
|
||||
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
|
||||
)}
|
||||
<InstallBanner />
|
||||
<div>
|
||||
{load === 'loading' && <PostsSkel />}
|
||||
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
|
||||
{load !== 'loading' && !posts.length && (
|
||||
<StateBox load="ready" empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'} hold={<PostsSkel />} className="inset-x-3 top-3.5 bottom-auto" />
|
||||
)}
|
||||
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에 */}
|
||||
{load !== 'loading' && posts.length > 0 && <FoliageCard post={f?.foliage_post} />}
|
||||
{posts.map((p, i) => {
|
||||
const t = talkAt(i)
|
||||
const ev = eventNo.get(p.post_id)
|
||||
return (
|
||||
<Fragment key={p.post_id}>
|
||||
{ev ? (
|
||||
<Seen item="event" position={ev}>
|
||||
<PostCard post={p} />
|
||||
</Seen>
|
||||
) : (
|
||||
<PostCard post={p} />
|
||||
)}
|
||||
{bandAt.find(([at]) => at === i + 1)?.[1]}
|
||||
{t && (
|
||||
<Seen item="talk" position={(i + 1) / TALK_EVERY}>
|
||||
<>
|
||||
<ShortsRail />
|
||||
<FeedComposer />
|
||||
<div id={MY_GAK_ID} className="scroll-mt-16">
|
||||
<MyGakRow />
|
||||
</div>
|
||||
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
|
||||
{stories.some((g) => g.active) ? (
|
||||
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
|
||||
) : load === 'loading' ? (
|
||||
<PostCardSkel />
|
||||
) : (
|
||||
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
|
||||
)}
|
||||
<InstallBanner />
|
||||
<div>
|
||||
{load === 'loading' && <PostsSkel />}
|
||||
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
|
||||
{load !== 'loading' && !posts.length && (
|
||||
<StateBox load="ready" empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'} hold={<PostsSkel />} className="inset-x-3 top-3.5 bottom-auto" />
|
||||
)}
|
||||
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에 */}
|
||||
{load !== 'loading' && posts.length > 0 && <FoliageCard post={f?.foliage_post} />}
|
||||
{posts.map((p, i) => {
|
||||
const t = talkAt(i)
|
||||
const ev = eventNo.get(p.post_id)
|
||||
return (
|
||||
<Fragment key={p.post_id}>
|
||||
{ev ? (
|
||||
<Seen item="event" position={ev}>
|
||||
<PostCard post={p} />
|
||||
</Seen>
|
||||
) : (
|
||||
<PostCard post={p} />
|
||||
)}
|
||||
{bandAt.find(([at]) => at === i + 1)?.[1]}
|
||||
{t && (
|
||||
<Seen item="talk" position={(i + 1) / TALK_EVERY}>
|
||||
<TalkPost t={t} />
|
||||
</Seen>
|
||||
)}
|
||||
</Fragment>
|
||||
)
|
||||
})}
|
||||
{/* 포스트가 모자라 끼울 자리가 없던 사람 글은 맨 뒤에 */}
|
||||
{feed.isSuccess &&
|
||||
talks.slice(talkFrom).map((t, n) => (
|
||||
<Seen key={t.talk_id} item="talk" position={talkFrom + n + 1}>
|
||||
<TalkPost t={t} />
|
||||
</Seen>
|
||||
)}
|
||||
</Fragment>
|
||||
)
|
||||
})}
|
||||
{/* 포스트가 모자라 끼울 자리가 없던 사람 글은 맨 뒤에 */}
|
||||
{feed.isSuccess &&
|
||||
talks.slice(talkFrom).map((t, n) => (
|
||||
<Seen key={t.talk_id} item="talk" position={talkFrom + n + 1}>
|
||||
<TalkPost t={t} />
|
||||
</Seen>
|
||||
))}
|
||||
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
|
||||
</div>
|
||||
))}
|
||||
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{about && (
|
||||
<div
|
||||
data-nosnippet
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Link, useLocation } from 'react-router'
|
||||
import { getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import type { HeroTomorrow, HoursSlide, TomorrowEvent } from '@nalssigak/shared/api/client'
|
||||
import { type Load, MEDALS } from '@nalssigak/shared/lib'
|
||||
import { track } from '../lib/analytics'
|
||||
import { PostCardSkel, PostFrame, SlideView } from './Post'
|
||||
import { useRegion } from './regionContext'
|
||||
import { Ic } from './ui'
|
||||
|
||||
const md = (d: string) => `${Number(d.slice(5, 7))}/${Number(d.slice(8, 10))}`
|
||||
const days = (e: TomorrowEvent) => (e.start_date === e.end_date ? md(e.start_date) : `${md(e.start_date)}~${md(e.end_date)}`)
|
||||
|
||||
/** 내일 날씨 페이지(/tomorrow/...)의 히어로 아래. 오늘 피드 대신 내일 것만 둬서 오늘 페이지와 본문이 겹치지 않게 한다 */
|
||||
export function TomorrowFeed({ tomorrow, load }: { tomorrow?: HeroTomorrow | null; load: Load }) {
|
||||
const { region } = useRegion()
|
||||
const { pathname } = useLocation()
|
||||
const [sido] = region.name.split(' ')
|
||||
const place = region.name.split(' ').at(-1)!
|
||||
const w = useQuery(getWeatherTodayOptions({ query: { region: region.code, day: 'tomorrow' } })).data
|
||||
const hours: HoursSlide | null =
|
||||
w?.slots?.length && w.headline
|
||||
? { kind: 'hours', eyebrow: '내일 하루 · 3시간마다', line: w.headline, hours: w.slots.map((s) => ({ label: s.label, icon: s.icon, temp_c: s.temp_c, tone: s.tone })) }
|
||||
: null
|
||||
const ranked = tomorrow?.ranked ?? []
|
||||
const events = tomorrow?.events ?? []
|
||||
|
||||
return (
|
||||
<div>
|
||||
{ranked.length > 0 ? (
|
||||
<PostFrame title={`내일의 각 · ${place}`} account="내일의 각" avatar="rabbit">
|
||||
<div className="b-band-2 px-4 pt-3.5 pb-3">
|
||||
<p className="m-0 font-jua text-[19px]">내일의 각 · {place} 하루 기준</p>
|
||||
<ol className="m-0 mt-2 grid list-none gap-1.5 p-0">
|
||||
{ranked.map((g, i) => (
|
||||
<li key={g.index_id} className="flex items-center gap-2.5 rounded-[18px] bg-white px-3 py-2 shadow-[inset_0_-4px_0_var(--shade)]">
|
||||
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="w-[24px] shrink-0" /> : <span className="w-[24px] shrink-0 text-center font-jua text-(--ink3)">{i + 1}</span>}
|
||||
<Ic name={g.icon} className="w-[34px] shrink-0" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<b className="block font-jua text-[16px] leading-tight font-normal">{g.name}</b>
|
||||
{g.summary && <small className="block truncate text-xs font-semibold text-(--ink2)">{g.summary}</small>}
|
||||
</span>
|
||||
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
</PostFrame>
|
||||
) : (
|
||||
load === 'loading' && <PostCardSkel />
|
||||
)}
|
||||
{hours && (
|
||||
<PostFrame title="내일 날씨" account="내일 날씨" avatar="sun">
|
||||
<div className="relative flex aspect-[4/5] overflow-hidden">
|
||||
<SlideView slide={hours} bg="sky" />
|
||||
</div>
|
||||
</PostFrame>
|
||||
)}
|
||||
{events.length > 0 && (
|
||||
<PostFrame title={`내일 열리는 행사 · ${sido}`} account="주말·행사" avatar="concert" more={<Link to="/week">행사 더 보기 ›</Link>}>
|
||||
<div className="b-band-3 px-4 pt-3.5 pb-3">
|
||||
<p className="m-0 font-jua text-[19px]">내일 열리는 행사 · {sido}</p>
|
||||
<ul className="m-0 mt-2 grid list-none gap-1.5 p-0">
|
||||
{events.map((e) => (
|
||||
<li key={e.event_id} className="flex items-center gap-2.5 rounded-[18px] bg-white px-3 py-2 shadow-[inset_0_-4px_0_var(--shade)]">
|
||||
<Ic name={e.icon} className="w-[32px] shrink-0" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<b className="block font-jua text-[16px] leading-tight font-normal">{e.name}</b>
|
||||
<small className="block truncate text-xs font-semibold text-(--ink2)">
|
||||
{e.place} · {days(e)}
|
||||
</small>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</PostFrame>
|
||||
)}
|
||||
<Link
|
||||
to={pathname.replace(/^\/tomorrow\//, '/today/')}
|
||||
onClick={() => track('tomorrow_to_today', { region_name: region.name })}
|
||||
className="mx-3 mt-4 mb-2 block rounded-full bg-white py-3 text-center font-jua text-[16px] shadow-[inset_0_-4px_0_var(--shade)]"
|
||||
>
|
||||
오늘 {place} 소식 보기 ›
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -456,6 +456,33 @@
|
||||
.b-skybg[data-t='night'] .b-sky-night {
|
||||
opacity: 1;
|
||||
}
|
||||
/* 기념일 소품 (holiday.ts): 하늘은 그대로 두고 투명 배경 소품 그림을 화면 네 귀퉁이에 (public/b/holiday/<key>-tl·tr·bl·br.webp).
|
||||
폰은 반씩 나눠 폭을 채우고, 넓은 화면은 300px 로 귀퉁이에 붙어 잘리지 않는다. 헤더 칸은 .b-holiday-head 가 흐림 막 위에 한 번 더 그린다 */
|
||||
.b-sky-holiday,
|
||||
.b-holiday-head > i {
|
||||
--hw: min(50%, 300px);
|
||||
background:
|
||||
var(--h-tl) left top / var(--hw) auto no-repeat,
|
||||
var(--h-tr) right top / var(--hw) auto no-repeat,
|
||||
var(--h-bl) left bottom / var(--hw) auto no-repeat,
|
||||
var(--h-br) right bottom / var(--hw) auto no-repeat;
|
||||
}
|
||||
.b-skybg[data-h] .b-sky-holiday {
|
||||
opacity: 1;
|
||||
}
|
||||
.b-holiday-head > i {
|
||||
position: absolute;
|
||||
inset: 0 0 auto;
|
||||
height: 100dvh;
|
||||
}
|
||||
[data-t='night'] .b-sky-holiday,
|
||||
.b-holiday-head[data-t='night'] > i {
|
||||
filter: brightness(0.8);
|
||||
}
|
||||
[data-h='halloween'] { --h-tl: url('/b/holiday/halloween-tl.webp'); --h-tr: url('/b/holiday/halloween-tr.webp'); --h-bl: url('/b/holiday/halloween-bl.webp'); --h-br: url('/b/holiday/halloween-br.webp'); }
|
||||
[data-h='pepero'] { --h-tl: url('/b/holiday/pepero-tl.webp'); --h-tr: url('/b/holiday/pepero-tr.webp'); --h-bl: url('/b/holiday/pepero-bl.webp'); --h-br: url('/b/holiday/pepero-br.webp'); }
|
||||
[data-h='christmas'] { --h-tl: url('/b/holiday/christmas-tl.webp'); --h-tr: url('/b/holiday/christmas-tr.webp'); --h-bl: url('/b/holiday/christmas-bl.webp'); --h-br: url('/b/holiday/christmas-br.webp'); }
|
||||
[data-h='chuseok'] { --h-tl: url('/b/holiday/chuseok-tl.webp'); --h-tr: url('/b/holiday/chuseok-tr.webp'); --h-bl: url('/b/holiday/chuseok-bl.webp'); --h-br: url('/b/holiday/chuseok-br.webp'); }
|
||||
.b-skybg[data-t='morning'] {
|
||||
--b1: #ffc39b;
|
||||
--b2: #bfe5ff;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import Matter from 'matter-js'
|
||||
import { currentHoliday } from './holiday'
|
||||
|
||||
/** 작은 것부터 큰 것 순서. 같은 단계 둘이 닿으면 다음 단계로 합쳐지고, 해 둘은 사라지며 보너스 */
|
||||
export const LEVELS = [
|
||||
const BASE = [
|
||||
{ icon: 'muggy', name: '물방울', r: 15, color: '#d9f0ff' },
|
||||
{ icon: 'snow', name: '눈송이', r: 21, color: '#e4ecff' },
|
||||
{ icon: 'cloud', name: '구름', r: 28, color: '#f1f3f8' },
|
||||
@@ -12,6 +13,10 @@ export const LEVELS = [
|
||||
{ icon: 'sun', name: '해', r: 78, color: '#ffd2a1' },
|
||||
] as const
|
||||
|
||||
/** 기념일엔 그림·이름만 그날 것으로 (크기·색·합치기 규칙은 그대로) */
|
||||
export const HOLIDAY = currentHoliday()
|
||||
export const LEVELS = BASE.map((l, i) => (HOLIDAY ? { ...l, ...HOLIDAY.game[i] } : l))
|
||||
|
||||
export const W = 360
|
||||
export const H = 540
|
||||
/** 이 선 위에 쌓인 채로 LOSE_MS 넘게 있으면 끝 */
|
||||
|
||||
@@ -1,187 +1,16 @@
|
||||
import { useLayoutEffect, useMemo, useState, type RefObject } from 'react'
|
||||
import data from '../../seo/foliage_2026.json'
|
||||
import { kst } from '@nalssigak/shared/lib'
|
||||
import { foliageOn, foliageToday, type Kind } from '@nalssigak/shared/lib/foliage'
|
||||
|
||||
export type Kind = 'maple' | 'ginkgo'
|
||||
export type Stage = 'before' | 'first' | 'peak' | 'gone'
|
||||
type Raw = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string }
|
||||
/** x·y 는 지도 그림 안 위치(0~1), own 은 산림청 예측 지점 자기 날짜인지(아니면 가까운 지점에서 빌린 날짜) */
|
||||
export type Spot = Omit<Raw, 'basis' | 'lat' | 'lon'> & { stage: Stage; d: number; x: number; y: number; own: boolean }
|
||||
// 데이터·단계·배치 계산은 앱과 같이 쓴다 (shared/lib/foliage.ts). 여기는 웹 화면에 붙는 것만
|
||||
export { headline, ICON_R, KIND, LAND_CX, labelBoxes, md, placeLabels, placeProvinces, provinceBox, PROVINCES, rankNow, spread, STAGE } from '@nalssigak/shared/lib/foliage'
|
||||
export type { Box, Kind, Pt, Spot, Stage } from '@nalssigak/shared/lib/foliage'
|
||||
|
||||
// 지도 그림(public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값
|
||||
const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 }
|
||||
export const MAP_SRC = '/foliage/korea-map.webp'
|
||||
// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 PEAK_AFTER 일 뒤까지 절정으로 본다
|
||||
const FIRST_DAYS = 14
|
||||
const PEAK_DAYS = 3
|
||||
const PEAK_AFTER = 7
|
||||
|
||||
export const STAGE: Record<Stage, string> = { before: '단풍 전', first: '첫 단풍', peak: '절정', gone: '절정 지남' }
|
||||
export const KIND: Record<Kind, string> = { maple: '단풍', ginkgo: '은행' }
|
||||
|
||||
const DAY = 86_400_000
|
||||
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
|
||||
|
||||
function stage(peak: string, today: string): Stage {
|
||||
const d = days(today, peak)
|
||||
if (d < -PEAK_AFTER) return 'gone'
|
||||
if (d <= PEAK_DAYS) return 'peak'
|
||||
return d <= FIRST_DAYS ? 'first' : 'before'
|
||||
}
|
||||
|
||||
const toXY = (lat: number, lon: number) => ({ x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size })
|
||||
// 처음 화면 가로 가운데: 명소 가운데(127.9°)로 잡으면 서해 섬까지 든 땅이 왼쪽으로 쏠려 보여 서쪽으로 당김
|
||||
export const LAND_CX = toXY(36, 127.65).x
|
||||
|
||||
// 지도 위 시·도 이름 자리(위경도). 서울·경기는 겹치지 않게 경기를 북쪽으로 조금 올림
|
||||
export const PROVINCES = (
|
||||
[
|
||||
['서울', 37.56, 126.98],
|
||||
['경기', 37.95, 127.05],
|
||||
['강원', 37.65, 128.35],
|
||||
['충북', 36.8, 127.75],
|
||||
['충남', 36.45, 126.85],
|
||||
['전북', 35.72, 127.1],
|
||||
['전남', 34.85, 126.9],
|
||||
['경북', 36.3, 128.75],
|
||||
['경남', 35.3, 128.2],
|
||||
['제주', 33.38, 126.55],
|
||||
] as const
|
||||
).map(([name, lat, lon]) => ({ name, ...toXY(lat, lon) }))
|
||||
|
||||
export const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
|
||||
const province = (m: Spot) => m.region.split(' ')[0].split('·')
|
||||
|
||||
/** 오늘(한국 시각) 기준 명소 67곳과 단계. 단풍철이 아니면 inSeason 이 false */
|
||||
export function useFoliage() {
|
||||
const [today] = useState(() => {
|
||||
const t = kst(new Date())
|
||||
return `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}`
|
||||
})
|
||||
return useMemo(() => {
|
||||
const spots: Spot[] = (data.spots as Raw[]).map(({ basis, lat, lon, ...m }) => ({
|
||||
...m,
|
||||
stage: stage(m.peak, today),
|
||||
d: days(today, m.peak),
|
||||
...toXY(lat, lon),
|
||||
own: basis.startsWith('산림청'),
|
||||
}))
|
||||
// 가장 이른 명소가 첫 단풍에 들 때부터 가장 늦은 명소의 절정이 끝날 때까지
|
||||
const peaks = spots.map((m) => m.peak).sort()
|
||||
const inSeason = days(peaks[0], today) >= -FIRST_DAYS && days(peaks[peaks.length - 1], today) <= PEAK_AFTER
|
||||
return { today, spots, inSeason }
|
||||
}, [today])
|
||||
}
|
||||
|
||||
/** 절정 명소가 많은 시·도 3곳, 절정이 없으면 가장 먼저 올 절정, 다 지났으면 지는 중 */
|
||||
export function headline(spots: Spot[]) {
|
||||
const peak = spots.filter((m) => m.stage === 'peak')
|
||||
if (peak.length) {
|
||||
const count = new Map<string, number>()
|
||||
for (const p of peak.flatMap(province)) count.set(p, (count.get(p) ?? 0) + 1)
|
||||
return `지금 절정: ${[...count].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([p]) => p).join('·')}`
|
||||
}
|
||||
if (spots.some((m) => m.stage === 'gone')) return '올해 단풍이 지고 있어요'
|
||||
const first = spots.reduce((a, b) => (b.peak < a.peak ? b : a))
|
||||
return `첫 절정은 ${province(first)[0]}, ${md(first.peak)}쯤`
|
||||
}
|
||||
|
||||
/** 지금 가기 좋은 순: 절정인 곳 중 절정 예상일이 오늘과 가까운 순, 같으면 자기 예측 날짜 먼저, 그다음 이름 순 */
|
||||
export const rankNow = (spots: Spot[]) =>
|
||||
spots.filter((m) => m.stage === 'peak').sort((a, b) => Math.abs(a.d) - Math.abs(b.d) || Number(b.own) - Number(a.own) || a.name.localeCompare(b.name))
|
||||
|
||||
/** 시·도 이름 자리(명소 이름표를 먼저 놓은 뒤): 원래 자리가 잎·점·이름표에 덮이면 둘레를 돌며 가장 가까운 빈자리로 옮긴다(최대 반경 R, 바다 쪽도 됨) */
|
||||
export function placeProvinces(provs: { name: string; x: number; y: number }[], pts: Pt[], labels: Box[] = [], R = 90) {
|
||||
// 앞에서 놓은 시·도 이름도 피한다(서울·경기처럼 붙은 곳)
|
||||
const placed: Box[] = []
|
||||
const free = (x: number, y: number) =>
|
||||
pts.every((p) => Math.abs(p.x - x) > p.r + 17 || Math.abs(p.y - y) > p.r + 10) && [...labels, ...placed].every((b) => !overlaps(provinceBox(x, y), b))
|
||||
return provs.map((v) => {
|
||||
const at = pick(v)
|
||||
placed.push(provinceBox(at.x, at.y))
|
||||
return at
|
||||
})
|
||||
function pick(v: { name: string; x: number; y: number }) {
|
||||
if (free(v.x, v.y)) return v
|
||||
for (let d = 5; d <= R; d += 5)
|
||||
for (let a = 0; a < 24; a++) {
|
||||
const x = v.x + Math.cos((a / 24) * 2 * Math.PI) * d
|
||||
const y = v.y + Math.sin((a / 24) * 2 * Math.PI) * d
|
||||
if (free(x, y)) return { ...v, x, y }
|
||||
}
|
||||
return v
|
||||
}
|
||||
}
|
||||
export function provinceBox(x: number, y: number): Box {
|
||||
return { l: x - 16, t: y - 9, r: x + 16, b: y + 9 }
|
||||
}
|
||||
|
||||
/** placeLabels 결과를 상자로: 시·도 이름이 피해 갈 자리 */
|
||||
export const labelBoxes = (at: Record<string, { left: number; top: number }>, size: Record<string, { w: number; h: number }>) =>
|
||||
Object.entries(at).map(([n, a]) => ({ l: a.left, t: a.top, r: a.left + (size[n]?.w ?? 0), b: a.top + (size[n]?.h ?? 0) }))
|
||||
|
||||
export type Pt = { m: Spot; x: number; y: number; r: number }
|
||||
const LABEL_GAP = 4
|
||||
export type Box = { l: number; t: number; r: number; b: number }
|
||||
const overlaps = (a: Box, b: Box) => a.l < b.r && b.l < a.r && a.t < b.b && b.t < a.b
|
||||
|
||||
/** 화면 위 점끼리 겹치면 서로 밀어 떼어 놓는다 (pts 를 고쳐서 돌려줌) */
|
||||
export function spread(pts: Pt[], gap = 1.5) {
|
||||
for (let it = 0; it < 60; it++) {
|
||||
let moved = false
|
||||
for (let i = 0; i < pts.length; i++)
|
||||
for (let j = i + 1; j < pts.length; j++) {
|
||||
const a = pts[i]
|
||||
const b = pts[j]
|
||||
let dx = b.x - a.x
|
||||
let dy = b.y - a.y
|
||||
let d = Math.hypot(dx, dy)
|
||||
const need = a.r + b.r + gap
|
||||
if (d >= need) continue
|
||||
if (d < 0.01) [dx, dy, d] = [Math.cos(i + j), Math.sin(i + j), 1]
|
||||
const push = (need - d) / 2
|
||||
a.x -= (dx / d) * push
|
||||
a.y -= (dy / d) * push
|
||||
b.x += (dx / d) * push
|
||||
b.y += (dy / d) * push
|
||||
moved = true
|
||||
}
|
||||
if (!moved) break
|
||||
}
|
||||
return pts
|
||||
}
|
||||
|
||||
/** 이름표를 점 오른쪽·왼쪽 순으로 놓아 보고(잎과 짝이 헷갈리지 않게 옆 먼저), 점·다른 이름표·막힌 칸과 겹치거나 영역 밖이면 그 이름은 뺀다. 앞 순서가 먼저 자리를 잡는다 */
|
||||
export function placeLabels(order: Pt[], all: Pt[], size: Record<string, { w: number; h: number }>, area: Box, blocked: Box[] = [], vertical: (p: Pt) => boolean = () => false) {
|
||||
const dots = all.map((p) => ({ name: p.m.name, box: { l: p.x - p.r, t: p.y - p.r, r: p.x + p.r, b: p.y + p.r } }))
|
||||
const taken = [...blocked.map((box) => ({ name: '', box })), ...dots]
|
||||
const out: Record<string, { left: number; top: number }> = {}
|
||||
for (const p of order) {
|
||||
const s = size[p.m.name]
|
||||
if (!s || p.x < area.l || p.x > area.r || p.y < area.t || p.y > area.b) continue
|
||||
// 옆 자리가 없을 때 vertical 인 명소(절정)만 위·아래도 써 본다
|
||||
const tries = [
|
||||
[p.r + 2, -s.h / 2],
|
||||
[-s.w - p.r - 2, -s.h / 2],
|
||||
...(vertical(p) ? [[-s.w / 2, -s.h - p.r - 1], [-s.w / 2, p.r + 1]] : []),
|
||||
]
|
||||
for (const [dx, dy] of tries) {
|
||||
const r = { l: p.x + dx, t: p.y + dy, r: p.x + dx + s.w, b: p.y + dy + s.h }
|
||||
if (r.l < area.l || r.t < area.t || r.r > area.r || r.b > area.b) continue
|
||||
// 이름표끼리는 LABEL_GAP 만큼 띄워 손가락으로 옆 이름을 잘못 누르지 않게
|
||||
const pad = { l: r.l - LABEL_GAP, t: r.t - LABEL_GAP, r: r.r + LABEL_GAP, b: r.b + LABEL_GAP }
|
||||
if (taken.some((o) => o.name !== p.m.name && overlaps(o.name ? r : pad, o.box))) continue
|
||||
// 위·아래 자리는 이름표에서 가장 가까운 표시가 자기 것일 때만: 아니면 다른 점의 이름처럼 읽힌다
|
||||
const cx = (r.l + r.r) / 2
|
||||
const cy = (r.t + r.b) / 2
|
||||
const mine = Math.hypot(cx - p.x, cy - p.y)
|
||||
if (dy !== -s.h / 2 && all.some((q) => q.m.name !== p.m.name && Math.hypot(cx - q.x, cy - q.y) < mine)) continue
|
||||
taken.push({ name: '', box: r })
|
||||
out[p.m.name] = { left: r.l, top: r.t }
|
||||
break
|
||||
}
|
||||
}
|
||||
return out
|
||||
const [today] = useState(foliageToday)
|
||||
return useMemo(() => foliageOn(today), [today])
|
||||
}
|
||||
|
||||
/** 이름표 크기를 재 둔다: host 안 data-label 이 붙은 요소의 폭·높이 (host 크기가 바뀌면 다시) */
|
||||
@@ -209,7 +38,6 @@ export const LABEL = "b-keep-bg absolute rounded-[7px] before:absolute before:-i
|
||||
export const LABEL_INK: Record<Kind, string> = { maple: 'bg-[#ffffffeb] text-[#b5321f]', ginkgo: 'bg-[#ffffffeb] text-[#8a6508]' }
|
||||
// 지도 그림 색을 빼서 단풍 아이콘이 묻히지 않게
|
||||
export const MAP_IMG = 'pointer-events-none absolute inset-0 size-full select-none mix-blend-multiply brightness-[1.08] saturate-[.3]'
|
||||
export const ICON_R = 10
|
||||
// 시·도 이름: 지도에 옅게 깔리는 글자
|
||||
// 어두운 산 무늬 위에서도 읽히게 종이색 테두리를 두른다
|
||||
export const PROVINCE = 'pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 font-jua text-[13px] leading-none whitespace-nowrap text-[#5c4a36]/85 [text-shadow:0_0_2px_#fff6ea,0_0_4px_#fff6ea,0_0_6px_#fff6ea]'
|
||||
@@ -0,0 +1,18 @@
|
||||
import { HOLIDAYS, holidayOn, type Holiday } from '@nalssigak/shared/lib/holiday'
|
||||
|
||||
// 기념일 목록·기간은 앱과 같이 쓴다 (shared/lib/holiday.ts)
|
||||
export { HOLIDAYS, holidayByTopic, type Holiday } from '@nalssigak/shared/lib/holiday'
|
||||
|
||||
/** 미리 보기 기념일: 주소의 ?holiday= 를 탭이 닫힐 때까지 기억 */
|
||||
function previewKey() {
|
||||
const q = new URLSearchParams(location.search).get('holiday')
|
||||
if (q) sessionStorage.setItem('holiday', q)
|
||||
return q ?? sessionStorage.getItem('holiday')
|
||||
}
|
||||
|
||||
/** 오늘(KST) 켜진 기념일. ?holiday=christmas 로 미리 보기 */
|
||||
export function currentHoliday(now = new Date()): Holiday | undefined {
|
||||
const preview = previewKey()
|
||||
if (preview) return HOLIDAYS.find((h) => h.key === preview)
|
||||
return holidayOn(now)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ 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 OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert', 'crystal_ball', 'yin_yang', 'tshirt', 'clapper', 'speech', 'droplet', 'leaf', 'rainbow', 'milky_way', 'shooting_star', 'alarm_clock', 'check_mark_button', 'sparkles', 'warning', 'locked', 'money_bag', 'red_heart', 'briefcase', 'spiral_calendar', 'two_hearts', 'sunrise'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert', 'crystal_ball', 'yin_yang', 'tshirt', 'clapper', 'speech', 'droplet', 'leaf', 'rainbow', 'milky_way', 'shooting_star', 'alarm_clock', 'check_mark_button', 'sparkles', 'warning', 'locked', 'money_bag', 'red_heart', 'briefcase', 'spiral_calendar', 'two_hearts', 'sunrise', 'candy', 'lollipop', 'spider', 'spider_web', 'bat', 'ghost', 'skull', 'jack_o_lantern', 'pepero_choco', 'pepero_almond', 'pepero_strawberry', 'pepero_nude', 'pepero_pair', 'pepero_bundle', 'pepero_box', 'pepero_basket', 'xmas_candy_cane', 'xmas_ornament', 'xmas_gingerbread', 'xmas_santa_hat', 'xmas_stocking', 'xmas_wreath', 'xmas_santa', 'christmas_tree', 'pear', 'dango', 'moon_viewing', 'full_moon'])
|
||||
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
|
||||
export function iconSrc(name: string) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createContext, use } from 'react'
|
||||
import { useLocation } from 'react-router'
|
||||
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||
import regionPages from '../../seo/region.json'
|
||||
import { track } from '../lib/analytics'
|
||||
|
||||
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
||||
|
||||
@@ -21,6 +22,17 @@ export function pageOf(pathname: string) {
|
||||
/** 지역 페이지로 들어오면 서버가 채운 소개 글(#root 안)을 앱이 덮기 전에 잡아 둔다. 구글은 JS 실행 뒤 화면으로 색인한다 */
|
||||
const landingAbout = pageOf(location.pathname) ? { path: location.pathname, html: document.querySelector('#root > main')?.innerHTML ?? '' } : null
|
||||
|
||||
// 구글·네이버 검색으로 지역 페이지에 들어옴: 검색 결과 문구(새·예전, 서버가 못 채웠으면 none)별 유입을 견준다
|
||||
const searchEngine = document.referrer ? new URL(document.referrer).hostname.match(/(?:^|\.)(google|naver)\./)?.[1] : undefined
|
||||
if (landingAbout && (searchEngine === 'google' || searchEngine === 'naver')) {
|
||||
const copy = document.querySelector<HTMLMetaElement>('meta[name="seo-copy"]')?.content
|
||||
track('search_landing', {
|
||||
page: location.pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today',
|
||||
engine: searchEngine,
|
||||
copy: copy === 'new' || copy === 'old' ? copy : 'none',
|
||||
})
|
||||
}
|
||||
|
||||
/** 들어온 지역 페이지에 그대로 있을 때만 그 소개 글 */
|
||||
export function useLandingAbout(): string | null {
|
||||
const { pathname } = useLocation()
|
||||
|
||||
@@ -15,7 +15,8 @@ import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { kst } from '@nalssigak/shared/lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { topicName, TOPICS, useMyTalks } from './talkState'
|
||||
import { holidayByTopic } from './holiday'
|
||||
import { openTopics, topicName, useMyTalks } from './talkState'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { CameraIcon, CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||
import { Avatar, TAP44 } from './ui'
|
||||
@@ -153,7 +154,7 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-2 flex flex-wrap gap-1.5" role="radiogroup" aria-label="글 주제">
|
||||
{TOPICS.map(([k, label]) => (
|
||||
{openTopics().map(([k, label]) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
@@ -377,7 +378,7 @@ export function TalkPost({ t }: { t: TalkData }) {
|
||||
<MenuButton menu={menu} setMenu={setMenu} className="ml-auto" />
|
||||
</div>
|
||||
{menu !== 'closed' && <TalkMenu t={t} menu={menu} setMenu={setMenu} className="px-3 pb-2.5" />}
|
||||
<div ref={bodyRef} onClick={onTap} className={cx('b-day aspect-[4/5] overflow-hidden', !src && `b-bg-${(t.topic && TOPIC_BG[t.topic]) || 'mint'} grid place-items-center px-7`)}>
|
||||
<div ref={bodyRef} onClick={onTap} className={cx('b-day aspect-[4/5] overflow-hidden', !src && `b-bg-${(t.topic && (TOPIC_BG[t.topic] ?? holidayByTopic(t.topic)?.bg)) || 'mint'} grid place-items-center px-7`)}>
|
||||
{src ? (
|
||||
<img src={src} alt="" loading="lazy" className="size-full bg-[#eef4fc] object-cover" />
|
||||
) : (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import { TalkTopic } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { currentHoliday, HOLIDAYS } from './holiday'
|
||||
import { useRegion } from './regionContext'
|
||||
|
||||
// 글 주제와 이름
|
||||
@@ -10,9 +11,16 @@ export const TOPICS = [
|
||||
[TalkTopic.RAIN, '비·눈'],
|
||||
[TalkTopic.FOLIAGE, '단풍·꽃'],
|
||||
[TalkTopic.OUTFIT, '오늘 옷차림'],
|
||||
...HOLIDAYS.map((h) => [h.topic, h.name] as const),
|
||||
] as const
|
||||
export const topicName = (t?: number) => TOPICS.find(([k]) => k === t)?.[1] ?? '동네 이야기'
|
||||
|
||||
/** 지금 고를 수 있는 주제: 기념일 주제는 그 기간에만 */
|
||||
export function openTopics() {
|
||||
const on = currentHoliday()?.topic
|
||||
return TOPICS.filter(([k]) => !HOLIDAYS.some((h) => h.topic === k) || k === on)
|
||||
}
|
||||
|
||||
/** 주제별 글 페이지 목록 (topic 없으면 전체) */
|
||||
export function useTopicTalks(topic?: TalkTopic) {
|
||||
const { region } = useRegion()
|
||||
|
||||
@@ -1,48 +1,8 @@
|
||||
import type { PinnedKey } from '../b/pinnedLike'
|
||||
import { GA_NAME, type Events as SharedEvents } from '@nalssigak/shared/lib/analytics'
|
||||
import type { SheetState } from '../b/sheetContext'
|
||||
|
||||
/** GA4로 보내는 이벤트와 값. 목록은 docs/이벤트_추적.md */
|
||||
type Events = {
|
||||
view_gak: { index_id: number; gak_name: string; score: number; rank: number }
|
||||
select_content: { content_type: 'article'; item_id: number; category: string }
|
||||
share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string }
|
||||
login: { method: 'id' | 'google' | 'toss' }
|
||||
sign_up: { method: 'id' }
|
||||
region_change: { region_name: string; method: 'list' | 'location' }
|
||||
install_banner_view: Record<string, never>
|
||||
install_click: { from: 'banner' | 'menu'; method: 'prompt' | 'guide' }
|
||||
install_choice: { outcome: 'accepted' | 'dismissed' }
|
||||
install_done: Record<string, never>
|
||||
app_launch: { mode: 'standalone' }
|
||||
/** index.html 첫 화면 스크립트가 gtag 로 바로 보낸다 */
|
||||
boot_stuck: { reason: string; seconds: number; tries: number; app_started: boolean }
|
||||
sheet_open: { sheet: SheetType }
|
||||
like: { content_type: 'post' | 'comment' | 'talk' | PinnedKey; item_id: number }
|
||||
comment: { post_id: number }
|
||||
talk_comment: { talk_id: number }
|
||||
report: { content_type: 'comment' | 'talk'; reason: number }
|
||||
block: { content_type: 'comment' | 'talk' }
|
||||
terms_agree: Record<string, never>
|
||||
talk_post: { topic: number; with_image: boolean }
|
||||
feed_item_view: { item_type: 'talk' | 'event'; position: number }
|
||||
hero_day_switch: { day: 'today' | 'tomorrow' }
|
||||
shorts_open: { video_id: string }
|
||||
shorts_view: { video_id: string; index: number }
|
||||
shorts_sound: { on: boolean }
|
||||
foliage_open: Record<string, never>
|
||||
foliage_spot: { spot_name: string; from: 'page' | 'card' }
|
||||
my_gak_save: { gak_name: string }
|
||||
fortune_draw: { card: string }
|
||||
day_log: { mood: number; went_out: boolean; card_hit: boolean | null }
|
||||
today_icon: { icon: string }
|
||||
saju_input: { with_time: boolean }
|
||||
saju_view: { scene: string; score: number; strength: string; top_element: string }
|
||||
game_start: { again: boolean; logged_in: boolean; wind_ms: number }
|
||||
game_round: { round: number; score: number; logged_in: boolean }
|
||||
game_over: { round: number; score: number; best: boolean; drops: number }
|
||||
toss_intro_start: Record<string, never>
|
||||
install_banner_close: Record<string, never>
|
||||
}
|
||||
/** 이벤트 목록은 앱과 같이 쓴다 (shared/lib/analytics.ts, docs/이벤트_추적.md) */
|
||||
type Events = SharedEvents<SheetType>
|
||||
|
||||
type SheetType = Exclude<SheetState, null>['type']
|
||||
|
||||
@@ -54,5 +14,5 @@ declare global {
|
||||
|
||||
export function track<E extends keyof Events>(event: E, params: Events[E]) {
|
||||
if (import.meta.env.DEV) return
|
||||
window.gtag?.('event', event, params)
|
||||
window.gtag?.('event', GA_NAME[event], params)
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"expo": {
|
||||
"name": "날씨각",
|
||||
"slug": "nalssigak",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/images/icon.png",
|
||||
"scheme": "nalssigak",
|
||||
@@ -55,7 +55,15 @@
|
||||
"locationWhenInUsePermission": "가장 가까운 동네 날씨를 보여 드리려고 위치를 써요."
|
||||
}
|
||||
],
|
||||
"@react-native-google-signin/google-signin"
|
||||
"@react-native-google-signin/google-signin",
|
||||
[
|
||||
"expo-image-picker",
|
||||
{
|
||||
"photosPermission": "동네 이야기에 사진을 붙이려고 사진 앨범을 써요.",
|
||||
"cameraPermission": false,
|
||||
"microphonePermission": false
|
||||
}
|
||||
]
|
||||
],
|
||||
"experiments": {
|
||||
"typedRoutes": true,
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"expo-font": "~57.0.4",
|
||||
"expo-glass-effect": "~57.0.4",
|
||||
"expo-image": "~57.0.5",
|
||||
"expo-image-picker": "~57.0.20",
|
||||
"expo-linear-gradient": "~57.0.2",
|
||||
"expo-linking": "~57.0.12",
|
||||
"expo-location": "~57.0.21",
|
||||
@@ -37,6 +38,7 @@
|
||||
"react-native-svg": "15.15.4",
|
||||
"react-native-view-shot": "5.1.0",
|
||||
"react-native-web": "~0.21.0",
|
||||
"react-native-webview": "13.16.1",
|
||||
"react-native-worklets": "0.10.1",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"uniwind": "^1.12.2"
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Tabs } from 'expo-router/tabs';
|
||||
|
||||
import { TabBar } from '@/components/tab-bar';
|
||||
import { TopBar } from '@/components/top-bar';
|
||||
|
||||
/** 아래 탭 다섯 개. 사주·게임 같은 화면은 탭 밖(루트 스택)에서 연다 */
|
||||
export default function TabsLayout() {
|
||||
return (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||
import { PostType } from '@nalssigak/shared/api/client/types.gen';
|
||||
import { kst, loadOf } from '@nalssigak/shared/lib';
|
||||
import { atSlot, PREVIEW } from '@nalssigak/shared/lib/today';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { Fragment, useEffect, useRef, type ReactNode } from 'react';
|
||||
import { RefreshControl, ScrollView, View, type LayoutRectangle } from 'react-native';
|
||||
|
||||
import { FoliageCard } from '@/components/foliage/foliage-card';
|
||||
import { MyGakRow } from '@/components/my-gak/my-gak';
|
||||
import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card';
|
||||
import { ShortsRail } from '@/components/shorts/rail';
|
||||
import { Composer, TalkPost } from '@/components/talk/talk';
|
||||
import { GakCard } from '@/components/today/gak-card';
|
||||
import { Hero } from '@/components/today/hero';
|
||||
import { TodayIcons } from '@/components/today/icons';
|
||||
import { SeasonBand } from '@/components/today/rails';
|
||||
import { StateBox } from '@/components/ui';
|
||||
import { track } from '@/lib/analytics';
|
||||
import { useFoliage } from '@/lib/foliage';
|
||||
import { fromShare } from '@/lib/my-gak';
|
||||
import { useRegion } from '@/lib/region';
|
||||
import { useSheet } from '@/lib/sheet';
|
||||
import { useSky } from '@/lib/sky';
|
||||
import { useTopicTalks } from '@/lib/talk';
|
||||
|
||||
// 사람 글은 포스트 두 장마다 한 장씩 최신순으로 끼운다
|
||||
const TALK_EVERY = 2;
|
||||
|
||||
type Spot = { item: 'talk' | 'event'; position: number; y: number; h: number };
|
||||
|
||||
/** 피드에 섞인 사람 글·행사 포스트가 처음 반쯤 보일 때 한 번 GA 로 보낸다 (웹 Seen) */
|
||||
function useSeen() {
|
||||
const spots = useRef(new Map<string, Spot>());
|
||||
const sent = useRef(new Set<string>());
|
||||
const view = useRef({ y: 0, h: 0 });
|
||||
const check = () => {
|
||||
const { y, h } = view.current;
|
||||
if (!h) return;
|
||||
for (const [key, s] of spots.current) {
|
||||
if (sent.current.has(key) || !s.h) continue;
|
||||
const shown = Math.min(y + h, s.y + s.h) - Math.max(y, s.y);
|
||||
if (shown < s.h / 2) continue;
|
||||
sent.current.add(key);
|
||||
track('feed_item_view', { item_type: s.item, position: s.position });
|
||||
}
|
||||
};
|
||||
const at = (item: Spot['item'], position: number) => (l: LayoutRectangle) => {
|
||||
spots.current.set(`${item}:${position}`, { item, position, y: l.y, h: l.height });
|
||||
check();
|
||||
};
|
||||
const onScroll = (y: number, h: number) => {
|
||||
view.current = { y, h };
|
||||
check();
|
||||
};
|
||||
return { at, onScroll };
|
||||
}
|
||||
|
||||
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 talkList = useTopicTalks();
|
||||
const talks = talkList.talks;
|
||||
const talkAt = (i: number) => ((i + 1) % TALK_EVERY === 0 ? talks[(i + 1) / TALK_EVERY - 1] : undefined);
|
||||
const talkFrom = Math.floor(posts.length / TALK_EVERY);
|
||||
const eventNo = new Map(posts.filter((p) => p.post_type === PostType.EVENT).map((p, n) => [p.post_id, n + 1]));
|
||||
const seen = useSeen();
|
||||
const { inSeason } = useFoliage();
|
||||
const scroll = useRef<ScrollView>(null);
|
||||
const myGakY = useRef(0);
|
||||
const { open } = useSheet();
|
||||
const { my } = useLocalSearchParams<{ my?: string }>();
|
||||
|
||||
// 친구가 보낸 내 각 링크(?my=...)로 들어오면 내 동네 기준으로 보여 준다
|
||||
useEffect(() => {
|
||||
if (!my) return;
|
||||
router.setParams({ my: undefined });
|
||||
const g = fromShare(my);
|
||||
if (g) open({ type: 'mix', shared: g });
|
||||
}, [my, open]);
|
||||
const refresh = () => Promise.all([feed.refetch(), today.refetch(), talkList.refetch()]);
|
||||
|
||||
// 웹처럼 9번째 글 뒤에 계절 이야기 띠를 넣고, 글이 모자라면 맨 뒤에 붙인다
|
||||
const bandAt: [number, ReactNode][] = [[9, bands?.season?.length ? <SeasonBand news={bands.season} /> : null]];
|
||||
|
||||
return (
|
||||
// 지역마다 새로 그려 넘긴 슬라이드 위치가 남지 않게 한다
|
||||
<ScrollView
|
||||
ref={scroll}
|
||||
key={region.code}
|
||||
contentContainerClassName="pb-6"
|
||||
refreshControl={<RefreshControl refreshing={feed.isRefetching && !feed.isPlaceholderData} onRefresh={refresh} />}
|
||||
style={{ opacity: feed.isPlaceholderData ? 0.6 : 1 }}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
scrollEventThrottle={200}
|
||||
onLayout={(e) => seen.onScroll(0, e.nativeEvent.layout.height)}
|
||||
onScroll={(e) => seen.onScroll(e.nativeEvent.contentOffset.y, e.nativeEvent.layoutMeasurement.height)}
|
||||
>
|
||||
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
|
||||
<TodayIcons foliage={inSeason} onMyGak={() => scroll.current?.scrollTo({ y: myGakY.current, animated: true })} />
|
||||
<ShortsRail />
|
||||
<Composer />
|
||||
{/* 아이콘 줄 '내 각'이 여기로 내려온다 */}
|
||||
<View onLayout={(e) => (myGakY.current = e.nativeEvent.layout.y)}>
|
||||
<MyGakRow />
|
||||
</View>
|
||||
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
|
||||
{stories.some((g) => g.active) ? (
|
||||
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
|
||||
) : load === 'loading' ? (
|
||||
<PostCardSkel />
|
||||
) : (
|
||||
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} 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"
|
||||
/>
|
||||
)}
|
||||
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에 */}
|
||||
{load !== 'loading' && posts.length > 0 && <FoliageCard post={f?.foliage_post} />}
|
||||
{posts.map((p, i) => {
|
||||
const t = talkAt(i);
|
||||
const ev = eventNo.get(p.post_id);
|
||||
return (
|
||||
<Fragment key={p.post_id}>
|
||||
{ev ? (
|
||||
<View onLayout={(e) => seen.at('event', ev)(e.nativeEvent.layout)}>
|
||||
<PostCard post={p} />
|
||||
</View>
|
||||
) : (
|
||||
<PostCard post={p} />
|
||||
)}
|
||||
{bandAt.find(([at]) => at === i + 1)?.[1]}
|
||||
{t && (
|
||||
<View onLayout={(e) => seen.at('talk', (i + 1) / TALK_EVERY)(e.nativeEvent.layout)}>
|
||||
<TalkPost key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
|
||||
</View>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
{/* 포스트가 모자라 끼울 자리가 없던 사람 글은 맨 뒤에 */}
|
||||
{feed.isSuccess &&
|
||||
talks.slice(talkFrom).map((t, n) => (
|
||||
<View key={t.talk_id} onLayout={(e) => seen.at('talk', talkFrom + n + 1)(e.nativeEvent.layout)}>
|
||||
<TalkPost t={t} />
|
||||
</View>
|
||||
))}
|
||||
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import { DayStrip, EventRow, PickCard, PlaceCard, RankRow } from '@/components/w
|
||||
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 { useShare } from '@/lib/share-image';
|
||||
import { SITE_URL } from '@/lib/site';
|
||||
|
||||
// 불러오는 동안에도 탭 줄 높이를 지키려고 같은 칩을 미리 그린다
|
||||
@@ -46,6 +46,7 @@ export default function WeekScreen() {
|
||||
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready';
|
||||
const refresh = () => Promise.all([week.refetch(), events.refetch(), ranking.refetch(), sel ? places.refetch() : null]);
|
||||
|
||||
const shareView = useShare();
|
||||
const pickShot = useRef<View>(null);
|
||||
// 고른 날 추천 카드를 이미지로
|
||||
const sendPlan = () => {
|
||||
@@ -3,7 +3,7 @@ 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 { Stack } from 'expo-router';
|
||||
import * as SplashScreen from 'expo-splash-screen';
|
||||
import { StatusBar } from 'expo-status-bar';
|
||||
import { useEffect } from 'react';
|
||||
@@ -11,11 +11,10 @@ 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 { LevelWatcher } from '@/lib/level';
|
||||
import { queryClient } from '@/lib/query-client';
|
||||
import { RegionProvider } from '@/lib/region';
|
||||
import { SkyProvider, useSky } from '@/lib/sky';
|
||||
@@ -28,14 +27,10 @@ function Shell() {
|
||||
<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>
|
||||
{/* 탭 묶음 위에 사주·게임 같은 탭 밖 화면이 쌓인다. 하늘 배경이 비치게 화면 바탕은 투명 */}
|
||||
<Stack screenOptions={{ headerShown: false, contentStyle: { backgroundColor: 'transparent' } }}>
|
||||
<Stack.Screen name="(tabs)" />
|
||||
</Stack>
|
||||
<FirstLoad />
|
||||
</View>
|
||||
);
|
||||
@@ -53,6 +48,7 @@ export default function RootLayout() {
|
||||
<AuthProvider>
|
||||
<RegionProvider>
|
||||
<SheetProvider>
|
||||
<LevelWatcher />
|
||||
<Shell />
|
||||
</SheetProvider>
|
||||
</RegionProvider>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { headline, md, type Kind, type Spot } from '@nalssigak/shared/lib/foliage';
|
||||
import { useLocalSearchParams } from 'expo-router';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Pressable, ScrollView, useWindowDimensions, View } from 'react-native';
|
||||
import { useCSSVariable } from 'uniwind';
|
||||
|
||||
import { FoliageMap, type FoliageMapHandle } from '@/components/foliage/foliage-map';
|
||||
import { ChosenBar, SpotList } from '@/components/foliage/spot-list';
|
||||
import { SendIcon } from '@/components/post/icons';
|
||||
import { ScreenHeader } from '@/components/screen-header';
|
||||
import { Text } from '@/components/text';
|
||||
import { Chips, Ic } from '@/components/ui';
|
||||
import { track } from '@/lib/analytics';
|
||||
import { useFoliage } from '@/lib/foliage';
|
||||
import { useShare } from '@/lib/share-image';
|
||||
import { SITE_URL } from '@/lib/site';
|
||||
|
||||
type Filter = 'all' | Kind;
|
||||
const FILTERS: [Filter, string][] = [
|
||||
['all', '전체'],
|
||||
['maple', '단풍'],
|
||||
['ginkgo', '은행'],
|
||||
];
|
||||
|
||||
/** 단풍 지도: 명소 67곳을 지도에서 확대해 보고 아래 목록으로 고른다. ?spot= 으로 열면 그 명소로 (웹 FoliagePage) */
|
||||
export default function FoliageScreen() {
|
||||
const params = useLocalSearchParams<{ spot?: string }>();
|
||||
const { today, spots } = useFoliage();
|
||||
const [filter, setFilter] = useState<Filter>('all');
|
||||
const [sel, setSel] = useState<string | null>(params.spot ?? null);
|
||||
const mapRef = useRef<FoliageMapHandle>(null);
|
||||
const shotRef = useRef<View>(null);
|
||||
const shareView = useShare();
|
||||
const ink = String(useCSSVariable('--color-ink'));
|
||||
const { width, height: winH } = useWindowDimensions();
|
||||
// 지도는 스크롤 밖에 고정: 가로만큼 정사각형, 화면이 낮으면 화면 높이의 45%까지
|
||||
const mapH = Math.max(280, Math.min(width * 1.05, winH * 0.45, 560));
|
||||
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.kind === filter), [spots, filter]);
|
||||
|
||||
useEffect(() => track('foliage_open', {}), []);
|
||||
useEffect(() => {
|
||||
if (sel) track('foliage_spot', { spot_name: sel, from: 'page' });
|
||||
}, [sel]);
|
||||
|
||||
const chosen = spots.find((m) => m.name === sel);
|
||||
const peakCount = spots.filter((m) => m.stage === 'peak').length;
|
||||
const title = headline(spots);
|
||||
const pick = (m: Spot) => {
|
||||
setSel(m.name);
|
||||
mapRef.current?.focus(m);
|
||||
};
|
||||
const share = () => void shareView(shotRef, { title: chosen ? `${chosen.name} 단풍` : '단풍 지도', message: `${title} · 날씨각 단풍 지도 ${SITE_URL}/foliage` });
|
||||
|
||||
return (
|
||||
<View className="flex-1">
|
||||
<ScreenHeader
|
||||
title="단풍 지도"
|
||||
right={
|
||||
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="단풍 지도 보내기" className="size-10 items-center justify-center">
|
||||
<SendIcon size={24} color={ink} />
|
||||
</Pressable>
|
||||
}
|
||||
/>
|
||||
<View className="px-4 pt-1 pb-2">
|
||||
<View className="flex-row items-center gap-1">
|
||||
<Ic name="maple" size={16} />
|
||||
<Text className="text-[13px] font-extrabold text-ink2">{`단풍 지도 · ${md(today)}`}</Text>
|
||||
</View>
|
||||
<Text className="mt-0.5 font-jua text-[24px] leading-tight text-ink">{title}</Text>
|
||||
</View>
|
||||
{/* 보내기는 지금 보이는 지도 그대로 찍어 보낸다 (웹은 따로 만든 공유 그림) */}
|
||||
<View ref={shotRef} collapsable={false}>
|
||||
<FoliageMap ref={mapRef} spots={shown} sel={sel} onSelect={setSel} height={mapH} />
|
||||
</View>
|
||||
<ChosenBar chosen={chosen} legendColor={ink} />
|
||||
<ScrollView className="flex-1" contentContainerClassName="pb-8">
|
||||
<Chips items={FILTERS} value={filter} onChange={setFilter} />
|
||||
<SpotList spots={shown} sel={sel} onPick={pick} />
|
||||
<Text className="px-5 pt-4 text-[11.5px] leading-relaxed font-semibold text-ink3">
|
||||
{`출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요${peakCount ? ` · 지금 절정 ${peakCount}곳` : ''}`}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { getAccessToken } from '@nalssigak/shared/api/auth';
|
||||
import { router } from 'expo-router';
|
||||
import { useRef, useState } from 'react';
|
||||
import { ActivityIndicator, Linking, View } from 'react-native';
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
import { WebView, type WebViewMessageEvent } from 'react-native-webview';
|
||||
|
||||
import { ScreenHeader } from '@/components/screen-header';
|
||||
import { Text } from '@/components/text';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { useRegion } from '@/lib/region';
|
||||
import { useSheet } from '@/lib/sheet';
|
||||
import { SITE_URL } from '@/lib/site';
|
||||
|
||||
const SITE_ORIGIN = new URL(SITE_URL).origin;
|
||||
|
||||
/** 게임 웹뷰는 날씨각 사이트 안에서만 움직인다. 다른 주소(외부 링크)는 휴대폰 브라우저로 연다 */
|
||||
function stayOnSite(url: string) {
|
||||
if (url.startsWith(`${SITE_ORIGIN}/`) || url === SITE_ORIGIN || url === 'about:blank') return true;
|
||||
if (/^https?:/.test(url)) Linking.openURL(url).catch((e: unknown) => console.warn('[game] 외부 주소를 열지 못함', url, e));
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 웹 페이지가 뜨기 전에 넣는 스크립트: 앱의 지역·로그인을 웹 저장소에 옮기고,
|
||||
* 게임 화면을 떠나는 이동(뒤로 버튼)과 '로그인하면 …' 버튼은 앱으로 알린다 (웹 구글 로그인은 앱 안 웹뷰에서 막힌다).
|
||||
* 갱신 토큰은 넘기지 않는다: 웹이 갱신하면 앱이 가진 갱신 토큰이 쓸모없어질 수 있다.
|
||||
* 날씨각 사이트에서 열렸을 때만 토큰을 넣는다 (다른 곳으로 넘어가면 아무것도 하지 않는다).
|
||||
*/
|
||||
function bridge(region: unknown, token: string | null) {
|
||||
return `(function () {
|
||||
if (location.origin !== ${JSON.stringify(SITE_ORIGIN)}) return;
|
||||
try {
|
||||
localStorage.setItem('nalssigak.b.region', ${JSON.stringify(JSON.stringify(region))});
|
||||
${token ? `localStorage.setItem('nalssigak.accessToken', ${JSON.stringify(token)});` : `localStorage.removeItem('nalssigak.accessToken');`}
|
||||
localStorage.removeItem('nalssigak.refreshToken');
|
||||
} catch (e) {}
|
||||
var post = function (t) { window.ReactNativeWebView.postMessage(t); };
|
||||
var check = function () { if (location.pathname !== '/game') post('leave'); };
|
||||
var push = history.pushState, replace = history.replaceState;
|
||||
history.pushState = function () { push.apply(this, arguments); check(); };
|
||||
history.replaceState = function () { replace.apply(this, arguments); check(); };
|
||||
window.addEventListener('popstate', check);
|
||||
document.addEventListener('click', function (e) {
|
||||
var b = e.target && e.target.closest && e.target.closest('button');
|
||||
if (b && b.textContent && b.textContent.trim().indexOf('로그인') === 0) { e.preventDefault(); e.stopPropagation(); post('login'); }
|
||||
}, true);
|
||||
})();
|
||||
true;`;
|
||||
}
|
||||
|
||||
/** 구름 합치기 게임: 웹 /game 을 그대로 띄운다 (물리 엔진·캔버스라 웹과 같은 화면, 사용자 결정 11/04) */
|
||||
export default function GameScreen() {
|
||||
const { region } = useRegion();
|
||||
const { loggedIn } = useAuth();
|
||||
const { open } = useSheet();
|
||||
const { top, bottom } = useSafeAreaInsets();
|
||||
const [failed, setFailed] = useState(false);
|
||||
const left = useRef(false);
|
||||
|
||||
const onMessage = (e: WebViewMessageEvent) => {
|
||||
if (e.nativeEvent.data === 'leave' && !left.current) {
|
||||
left.current = true;
|
||||
if (router.canGoBack()) router.back();
|
||||
else router.replace('/');
|
||||
}
|
||||
if (e.nativeEvent.data === 'login') open({ type: 'login' });
|
||||
};
|
||||
|
||||
if (failed)
|
||||
return (
|
||||
<View className="flex-1">
|
||||
<ScreenHeader title="구름 합치기" />
|
||||
<Text className="mx-6 mt-10 text-center text-[15px] font-bold text-ink2">게임을 불러오지 못했어요. 인터넷 연결을 확인하고 다시 들어와 주세요.</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-[#cfe9ff]" style={{ paddingTop: top, paddingBottom: bottom }}>
|
||||
{/* 로그인하면 토큰을 다시 넣어야 해서 로그인 여부로 새로 띄운다 */}
|
||||
<WebView
|
||||
key={`${region.code}:${loggedIn}`}
|
||||
source={{ uri: `${SITE_URL}/game` }}
|
||||
originWhitelist={[SITE_ORIGIN]}
|
||||
onShouldStartLoadWithRequest={(req) => stayOnSite(req.url)}
|
||||
injectedJavaScriptBeforeContentLoaded={bridge(region, getAccessToken())}
|
||||
onMessage={onMessage}
|
||||
onError={() => setFailed(true)}
|
||||
startInLoadingState
|
||||
renderLoading={() => <ActivityIndicator style={{ position: 'absolute', top: '45%', alignSelf: 'center' }} />}
|
||||
overScrollMode="never"
|
||||
bounces={false}
|
||||
setSupportMultipleWindows={false}
|
||||
style={{ backgroundColor: 'transparent' }}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
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,63 @@
|
||||
import { useLocalSearchParams } from 'expo-router';
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import { ScrollView, View } from 'react-native';
|
||||
|
||||
import { BirthForm } from '@/components/saju/birth-form';
|
||||
import { OpenTarget } from '@/components/saju/parts';
|
||||
import { Reading } from '@/components/saju/reading';
|
||||
import { ScreenHeader } from '@/components/screen-header';
|
||||
import { Text } from '@/components/text';
|
||||
import { useAccountBirth, useBirth } from '@/lib/saju-birth';
|
||||
|
||||
type Pos = { base: number | null; panel: number | null; done: boolean };
|
||||
|
||||
function tryScroll(p: Pos, view: ScrollView | null) {
|
||||
if (p.done || p.base == null || p.panel == null || !view) return;
|
||||
p.done = true;
|
||||
view.scrollTo({ y: Math.max(0, p.base + p.panel - 12), animated: true });
|
||||
}
|
||||
|
||||
/** 날씨 사주(/saju): 오늘 점수와 할 일, 내 기운, 레벨로 열리는 칸. ?open=saju_love 처럼 열면 그 칸으로 내려간다 (웹 SajuPage, #hash) */
|
||||
export default function SajuScreen() {
|
||||
const params = useLocalSearchParams<{ open?: string }>();
|
||||
const birth = useBirth();
|
||||
const loading = useAccountBirth();
|
||||
const [editing, setEditing] = useState(false);
|
||||
const scroll = useRef<ScrollView>(null);
|
||||
// 결과 묶음의 위치와 그 안에서 연 칸의 위치를 둘 다 알아야 내려갈 수 있다 (어느 쪽이 먼저 잡힐지 모른다)
|
||||
const pos = useRef<Pos>({ base: null, panel: null, done: false });
|
||||
const target = useMemo(
|
||||
() => ({
|
||||
id: params.open,
|
||||
onLayout: (y: number) => {
|
||||
pos.current.panel = y;
|
||||
tryScroll(pos.current, scroll.current);
|
||||
},
|
||||
}),
|
||||
[params.open],
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="flex-1">
|
||||
<ScreenHeader title="날씨 사주" />
|
||||
<ScrollView ref={scroll} contentContainerClassName="pb-8" keyboardShouldPersistTaps="handled">
|
||||
{loading && !birth ? (
|
||||
<Text className="px-4 py-16 text-center font-semibold text-ink2">내 생년월일을 불러오는 중이에요…</Text>
|
||||
) : !birth || editing ? (
|
||||
<BirthForm initial={birth} onDone={() => setEditing(false)} onCancel={birth ? () => setEditing(false) : undefined} />
|
||||
) : (
|
||||
<View
|
||||
onLayout={(e) => {
|
||||
pos.current.base = e.nativeEvent.layout.y;
|
||||
tryScroll(pos.current, scroll.current);
|
||||
}}
|
||||
>
|
||||
<OpenTarget value={target}>
|
||||
<Reading birth={birth} onEdit={() => setEditing(true)} />
|
||||
</OpenTarget>
|
||||
</View>
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||
import type { ShortItem } from '@nalssigak/shared/api/client/types.gen';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Image } from 'expo-image';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { FlatList, Pressable, View, type ViewToken } from 'react-native';
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
import Svg, { Path } from 'react-native-svg';
|
||||
|
||||
import { ShortPlayer, type PlayerHandle } from '@/components/shorts/player';
|
||||
import { thumb } from '@/components/shorts/rail';
|
||||
import { Text } from '@/components/text';
|
||||
import { track } from '@/lib/analytics';
|
||||
|
||||
const BAR = 48;
|
||||
|
||||
/** 쇼츠 화면: 그 영상부터 위아래로 넘겨 본다. 보이는 영상과 앞뒤만 소리 없이 미리 띄우고, 누르면 소리 켜기·끄기 (웹 ShortsPage) */
|
||||
export default function ShortsScreen() {
|
||||
const { id } = useLocalSearchParams<{ id?: string }>();
|
||||
const q = useQuery(listShortsOptions());
|
||||
const { top, bottom } = useSafeAreaInsets();
|
||||
// 처음 들어온 영상만 시작점으로 쓴다
|
||||
const [firstId] = useState(id);
|
||||
const listed = q.data?.items ?? [];
|
||||
const items: ShortItem[] = firstId && listed.length && !listed.some((s) => s.id === firstId) ? [{ id: firstId, title: '' }, ...listed] : listed;
|
||||
const start = Math.max(0, items.findIndex((s) => s.id === firstId));
|
||||
const [at, setAt] = useState(start);
|
||||
const [sound, setSound] = useState(false);
|
||||
const [ready, setReady] = useState<ReadonlySet<number>>(new Set());
|
||||
const [box, setBox] = useState({ w: 0, h: 0 });
|
||||
const players = useRef(new Map<number, PlayerHandle>());
|
||||
const soundRef = useRef(false);
|
||||
const atRef = useRef(start);
|
||||
|
||||
useEffect(() => {
|
||||
if (firstId) track('shorts_open', { video_id: firstId });
|
||||
}, [firstId]);
|
||||
|
||||
// 넘어온 영상만 처음부터 다시 틀고 소리를 맞춘다. 앞뒤는 소리만 끈다 (멈추면 유튜브 버튼이 떠서 멈추지 않는다)
|
||||
useEffect(() => {
|
||||
for (const [i, p] of players.current) {
|
||||
if (i === at) {
|
||||
p.command('seekTo', [0, true]);
|
||||
p.command(soundRef.current ? 'unMute' : 'mute');
|
||||
p.command('playVideo');
|
||||
} else p.command('mute');
|
||||
}
|
||||
}, [at]);
|
||||
|
||||
// FlatList 는 이 함수가 바뀌면 안 되어 처음 한 번만 만든다
|
||||
const [onViewable] = useState(() => ({ viewableItems }: { viewableItems: ViewToken<ShortItem>[] }) => {
|
||||
const i = viewableItems[0]?.index;
|
||||
if (i == null || i === atRef.current) return;
|
||||
atRef.current = i;
|
||||
setAt(i);
|
||||
const s = viewableItems[0].item;
|
||||
track('shorts_view', { video_id: s.id, index: i });
|
||||
});
|
||||
|
||||
const toggleSound = () => {
|
||||
const on = !soundRef.current;
|
||||
soundRef.current = on;
|
||||
setSound(on);
|
||||
track('shorts_sound', { on });
|
||||
players.current.get(at)?.command(on ? 'unMute' : 'mute');
|
||||
};
|
||||
|
||||
const close = () => (router.canGoBack() ? router.back() : router.replace('/'));
|
||||
// 9:16 을 칸 안에 맞춘다
|
||||
const w = Math.min(box.w, (box.h * 9) / 16);
|
||||
const h = (w * 16) / 9;
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-[#1d2233]" style={{ paddingTop: top, paddingBottom: bottom }}>
|
||||
{!!items[at] && <Image source={{ uri: thumb(items[at].id) }} style={{ position: 'absolute', inset: 0, opacity: 0.7, transform: [{ scale: 1.25 }] }} blurRadius={40} contentFit="cover" />}
|
||||
<View className="absolute inset-0 bg-black/35" />
|
||||
<View className="flex-row items-center justify-between px-3" style={{ height: BAR }}>
|
||||
<Pressable onPress={close} hitSlop={8} accessibilityRole="button" accessibilityLabel="닫기" className="size-9 items-center justify-center rounded-full bg-white/15">
|
||||
<Svg viewBox="0 0 24 24" width={18} height={18} fill="none" stroke="#fff" strokeWidth={2.4} strokeLinecap="round">
|
||||
<Path d="M6 6l12 12M18 6L6 18" />
|
||||
</Svg>
|
||||
</Pressable>
|
||||
<Pressable onPress={toggleSound} accessibilityRole="button" accessibilityState={{ selected: sound }} className="h-9 justify-center rounded-full bg-white/15 px-3.5">
|
||||
<Text className="text-[13px] font-bold text-white">{sound ? '소리 끄기' : '소리 켜기'}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
<View className="flex-1" onLayout={(e) => setBox({ w: e.nativeEvent.layout.width, h: e.nativeEvent.layout.height })}>
|
||||
{box.h > 0 && items.length > 0 && (
|
||||
<FlatList
|
||||
data={items}
|
||||
keyExtractor={(s) => s.id}
|
||||
pagingEnabled
|
||||
showsVerticalScrollIndicator={false}
|
||||
initialScrollIndex={start}
|
||||
getItemLayout={(_, i) => ({ length: box.h, offset: box.h * i, index: i })}
|
||||
onViewableItemsChanged={onViewable}
|
||||
viewabilityConfig={{ itemVisiblePercentThreshold: 60 }}
|
||||
windowSize={3}
|
||||
renderItem={({ item: s, index: i }) => (
|
||||
<View style={{ height: box.h }} className="items-center justify-center">
|
||||
<View style={{ width: w, height: h }}>
|
||||
<Image source={{ uri: thumb(s.id) }} style={{ position: 'absolute', inset: 0 }} contentFit="cover" />
|
||||
{/* 릴스처럼 앞뒤 영상을 소리 없이 미리 받아 둔다. 첫 장면 전엔 표지가 보이게 숨긴다 */}
|
||||
{Math.abs(i - at) <= 1 && (
|
||||
<View pointerEvents="none" style={{ position: 'absolute', inset: 0, opacity: ready.has(i) ? 1 : 0 }}>
|
||||
<ShortPlayer
|
||||
id={s.id}
|
||||
ref={(p) => {
|
||||
if (p) players.current.set(i, p);
|
||||
else players.current.delete(i);
|
||||
}}
|
||||
onPlaying={() => setReady((r) => (r.has(i) ? r : new Set(r).add(i)))}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
{/* 누르면 소리 켜기·끄기, 위아래로 밀면 목록이 넘어간다 */}
|
||||
<Pressable onPress={toggleSound} accessibilityLabel={sound ? '소리 끄기' : '소리 켜기'} style={{ position: 'absolute', inset: 0 }} />
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
// 아이콘 줄 '쇼츠'(/shorts)는 첫 영상부터
|
||||
export { default } from './[id]';
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { FlatList, Pressable, RefreshControl, ScrollView, View } from 'react-native';
|
||||
|
||||
import { ScreenHeader } from '@/components/screen-header';
|
||||
import { Composer, TalkCard } from '@/components/talk/talk';
|
||||
import { Text } from '@/components/text';
|
||||
import { Sec } from '@/components/ui';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { useSheet } from '@/lib/sheet';
|
||||
import { openTopics, TOPICS, useMyTalks, useTopicTalks } from '@/lib/talk';
|
||||
|
||||
type Tab = TalkTopic | 'all' | 'mine';
|
||||
|
||||
/** 주제별 사람 글: 위 주제 탭(한 줄 가로로 밀기, 끝에 '내 글'), 아래 글 목록. ?topic= · ?mine=1 로 연다 (웹 TalkPage) */
|
||||
export default function TalkScreen() {
|
||||
const params = useLocalSearchParams<{ topic?: string; mine?: string }>();
|
||||
const { loggedIn } = useAuth();
|
||||
const { open } = useSheet();
|
||||
const raw = Number(params.topic);
|
||||
const tab: Tab = params.mine ? 'mine' : TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : 'all';
|
||||
const topicList = useTopicTalks(tab === 'all' || tab === 'mine' ? undefined : tab);
|
||||
const mineList = useMyTalks(tab === 'mine' && loggedIn);
|
||||
const { talks, loaded, more, loadMore } = tab === 'mine' ? mineList : topicList;
|
||||
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...openTopics(), ['mine', '내 글']];
|
||||
const go = (k: Tab) => router.setParams(k === 'mine' ? { mine: '1', topic: undefined } : k === 'all' ? { mine: undefined, topic: undefined } : { mine: undefined, topic: String(k) });
|
||||
|
||||
const head = (
|
||||
<View>
|
||||
<Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" />
|
||||
<View accessibilityRole="tablist" accessibilityLabel="글 주제">
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerClassName="gap-1.5 px-4 pb-1">
|
||||
{tabs.map(([k, label]) => (
|
||||
<Pressable key={label} onPress={() => go(k)} accessibilityRole="tab" accessibilityState={{ selected: tab === k }} className={`rounded-full px-3 py-1.5 ${tab === k ? 'bg-ink-btn' : 'bg-card'}`}>
|
||||
<Text className={`text-[13px] font-extrabold ${tab === k ? 'text-white' : 'text-ink2'}`}>{label}</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</ScrollView>
|
||||
</View>
|
||||
<Composer />
|
||||
{tab === 'mine' && !loggedIn ? (
|
||||
<Text className="mx-4 mt-6 text-center text-[14px] font-semibold text-ink3">
|
||||
로그인하면 내가 쓴 글을 모아 볼 수 있어요.{' '}
|
||||
<Text onPress={() => open({ type: 'login' })} className="font-extrabold text-orange">
|
||||
로그인
|
||||
</Text>
|
||||
</Text>
|
||||
) : (
|
||||
loaded && !talks.length && <Text className="mx-4 mt-6 text-center text-[14px] font-semibold text-ink3">{tab === 'mine' ? '아직 쓴 글이 없어요. 위 칸에서 첫 글을 써 주세요.' : '아직 이 주제 글이 없어요. 위 칸에서 첫 글을 써 주세요.'}</Text>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="flex-1">
|
||||
<ScreenHeader title="동네 이야기" />
|
||||
<FlatList
|
||||
data={talks}
|
||||
keyExtractor={(t) => `${t.talk_id}:${t.liked}:${t.like_count}`}
|
||||
renderItem={({ item }) => <TalkCard t={item} />}
|
||||
ListHeaderComponent={head}
|
||||
contentContainerClassName="pb-8"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
// 목록 끝이 가까워지면 다음 쪽을 받는다 (글이 많아도 버튼 없이 이어서)
|
||||
onEndReached={() => more && loadMore()}
|
||||
onEndReachedThreshold={1}
|
||||
refreshControl={tab !== 'mine' ? <RefreshControl refreshing={topicList.refetching} onRefresh={() => topicList.refetch()} /> : undefined}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen';
|
||||
import { headline, ICON_R, labelBoxes, md, nearest, placeLabels, placeProvinces, PROVINCES, rankNow, spread } from '@nalssigak/shared/lib/foliage';
|
||||
import { router } from 'expo-router';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Pressable, View, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native';
|
||||
|
||||
import { Label, Legend, MapImage, MAP_INK, MAP_INK3, Marker, PAPER, Province, useLabelSizes } from '@/components/foliage/parts';
|
||||
import { Pager } from '@/components/post/pager';
|
||||
import { PostFrame } from '@/components/post/post-frame';
|
||||
import { Text } from '@/components/text';
|
||||
import { Ic } from '@/components/ui';
|
||||
import { track } from '@/lib/analytics';
|
||||
import { useFoliage } from '@/lib/foliage';
|
||||
|
||||
const RANK_N = 7;
|
||||
// 지도 아래 고른 명소 줄(범례 자리) 높이
|
||||
const BAR_H = 60;
|
||||
// 지도 그림은 땅이 왼쪽에 치우쳐 있어 오른쪽(빈 바다)으로 밀어 가운데에 맞춘다
|
||||
const SHIFT = 0.07;
|
||||
|
||||
const goMap = (spot?: string) => router.push(spot ? { pathname: '/foliage', params: { spot } } : '/foliage');
|
||||
|
||||
/**
|
||||
* 피드의 단풍 지도 카드 (웹 FoliageCard): 1장은 지금 절정인 곳만 잎으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위.
|
||||
* '지도 크게 보기'로 단풍 지도 화면. 단풍철이 아니면 그리지 않는다
|
||||
*/
|
||||
export function FoliageCard({ post }: { post?: PostReaction | null }) {
|
||||
const { today, spots, inSeason } = useFoliage();
|
||||
const peak = useMemo(() => spots.filter((m) => m.stage === 'peak').sort((a, b) => Number(a.kind === 'ginkgo') - Number(b.kind === 'ginkgo') || a.y - b.y), [spots]);
|
||||
const [size, measure] = useLabelSizes();
|
||||
const [W, setW] = useState(0);
|
||||
const [picked, setPicked] = useState<string | null>(null);
|
||||
const [index, setIndex] = useState(0);
|
||||
|
||||
const pts = useMemo(() => spread(peak.map((m) => ({ m, x: m.x * W, y: m.y * W, r: ICON_R }))), [peak, W]);
|
||||
const labelAt = useMemo(() => placeLabels(pts, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true), [pts, size, W]);
|
||||
const provs = useMemo(() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: v.x * W, y: v.y * W })), pts, labelBoxes(labelAt, size)), [pts, W, labelAt, size]);
|
||||
|
||||
useEffect(() => {
|
||||
if (picked) track('foliage_spot', { spot_name: picked, from: 'card' });
|
||||
}, [picked]);
|
||||
|
||||
if (!inSeason) return null;
|
||||
const toggle = (name: string) => setPicked(name === picked ? null : name);
|
||||
// 잎이 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 명소를 고른다
|
||||
const tapMap = (e: GestureResponderEvent) => {
|
||||
const best = nearest(pts, e.nativeEvent.locationX, e.nativeEvent.locationY);
|
||||
setPicked(best && best !== picked ? best : null);
|
||||
};
|
||||
const onLayout = (e: LayoutChangeEvent) => setW(e.nativeEvent.layout.width);
|
||||
const sel = peak.find((m) => m.name === picked);
|
||||
// 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로
|
||||
const ranked = rankNow(spots).slice(0, RANK_N);
|
||||
const caption = peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined;
|
||||
const pageH = W + 8 + BAR_H;
|
||||
|
||||
const mapPage = (
|
||||
<View className="overflow-hidden" style={{ width: W, height: pageH }}>
|
||||
<Pressable onPress={tapMap} accessibilityLabel="단풍 지도, 지금 절정인 곳" style={{ width: W, height: W, transform: [{ translateX: W * SHIFT }], backgroundColor: PAPER }}>
|
||||
<MapImage style={{ left: 0, top: 0, width: W, height: W }} />
|
||||
{provs.map((v) => (
|
||||
<Province key={v.name} name={v.name} x={v.x} y={v.y} />
|
||||
))}
|
||||
{pts.map((p) => (
|
||||
<Marker key={p.m.name} p={p} sel={p.m.name === picked} />
|
||||
))}
|
||||
{peak.map((m) => (
|
||||
<Label key={m.name} m={m} at={labelAt[m.name]} onPress={() => toggle(m.name)} onLayout={measure(m.name)} accessibilityLabel={`${m.name} 정보 보기`} />
|
||||
))}
|
||||
</Pressable>
|
||||
{/* 고른 명소 정보는 지도 밖, 범례 자리에: 지도 위 잎을 가리지 않게 */}
|
||||
{sel ? (
|
||||
<View className="mt-2 flex-row items-center gap-3 rounded-[16px] bg-white px-3" style={{ height: BAR_H, boxShadow: 'inset 0 -3px 0 rgba(40,48,74,0.08)' }}>
|
||||
<Ic name={sel.kind} size={32} />
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text numberOfLines={1} className="font-jua text-[18px] leading-tight" style={{ color: MAP_INK }}>
|
||||
{sel.name}
|
||||
</Text>
|
||||
<Text numberOfLines={1} className="text-[12px] font-bold" style={{ color: MAP_INK3 }}>
|
||||
{`${sel.region.split(' ')[0]} · 절정 예상 ${md(sel.peak)}`}
|
||||
</Text>
|
||||
</View>
|
||||
<Pressable onPress={() => goMap(sel.name)} accessibilityRole="link" className="rounded-full px-3 py-1.5" style={{ backgroundColor: MAP_INK }}>
|
||||
<Text className="text-[12.5px] font-extrabold text-white">지도에서 보기 ›</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
) : (
|
||||
<View className="mt-2 items-start" style={{ height: BAR_H }}>
|
||||
<Legend color={MAP_INK} />
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
|
||||
const rankPage = (
|
||||
<View className="pl-1" style={{ width: W, height: pageH }}>
|
||||
<Text className="font-jua text-[20px] leading-tight" style={{ color: MAP_INK }}>
|
||||
지금 가기 좋은 곳
|
||||
</Text>
|
||||
<Text className="mt-0.5 text-[12px] font-bold" style={{ color: MAP_INK3 }}>
|
||||
절정 예상일이 오늘과 가까운 순서예요
|
||||
</Text>
|
||||
<View className="mt-2 flex-1 justify-between">
|
||||
{ranked.map((m, i) => (
|
||||
<Pressable key={m.name} onPress={() => goMap(m.name)} accessibilityRole="link" accessibilityLabel={`${i + 1}위 ${m.name}, 절정 예상 ${md(m.peak)}`} className="flex-row items-center gap-2.5 py-1.5">
|
||||
<Text className="w-6 text-center font-jua text-[22px]" style={{ color: i < 3 ? '#b5321f' : '#9a8f80' }}>
|
||||
{String(i + 1)}
|
||||
</Text>
|
||||
<Ic name={m.kind} size={28} />
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text numberOfLines={1} className="text-[15px] font-extrabold" style={{ color: MAP_INK }}>
|
||||
{m.name}
|
||||
</Text>
|
||||
<Text numberOfLines={1} className="text-[12px] font-semibold" style={{ color: MAP_INK3 }}>
|
||||
{m.region}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="text-[14px] font-extrabold" style={{ color: MAP_INK, fontVariant: ['tabular-nums'] }}>
|
||||
{md(m.peak)}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
|
||||
return (
|
||||
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" pinned={{ key: 'foliage_post', post }} caption={caption}>
|
||||
{/* 밤에도 지도 카드는 밝은 종이 그대로 (웹 b-keep-bg) */}
|
||||
<View className="px-4 pt-4 pb-3" style={{ backgroundColor: PAPER }}>
|
||||
<Text className="text-[13px] font-extrabold opacity-75" style={{ color: MAP_INK }}>{`단풍 지도 · ${md(today)}`}</Text>
|
||||
<Text className="mt-1 font-jua text-[24px] leading-tight" style={{ color: MAP_INK }}>
|
||||
{headline(spots)}
|
||||
</Text>
|
||||
<View className="mt-1" onLayout={onLayout}>
|
||||
{W > 0 ? (
|
||||
<Pager width={W} height={pageH} onIndex={setIndex}>
|
||||
{[mapPage, rankPage]}
|
||||
</Pager>
|
||||
) : null}
|
||||
<View pointerEvents="none" className="absolute top-0 right-0 rounded-full px-[9px] py-[3px]" style={{ zIndex: 4, backgroundColor: 'rgba(30,36,56,0.55)' }} accessibilityElementsHidden>
|
||||
<Text className="text-xs font-extrabold text-white">{`${index + 1}/2`}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<Pressable onPress={() => goMap()} accessibilityRole="link" className="mt-2 w-full items-center rounded-full bg-white py-2" style={{ boxShadow: 'inset 0 -3px 0 rgba(40,48,74,0.08)' }}>
|
||||
<Text className="text-[14px] font-extrabold" style={{ color: MAP_INK }}>
|
||||
지도 크게 보기 ›
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</PostFrame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import { ICON_R, LAND_CX, labelBoxes, nearest, placeLabels, placeProvinces, PROVINCES, spread, type Box, type Spot, type Stage } from '@nalssigak/shared/lib/foliage';
|
||||
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type Ref } from 'react';
|
||||
import { Pressable, View, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native';
|
||||
|
||||
import { Label, MapImage, Marker, MAP_INK, PAPER, Province, useLabelSizes } from '@/components/foliage/parts';
|
||||
import { Text } from '@/components/text';
|
||||
|
||||
type Cam = { s: number; tx: number; ty: number };
|
||||
|
||||
const DOT_R: Record<Stage, number> = { peak: ICON_R, first: 4, before: 3, gone: 3 };
|
||||
const MAX_ZOOM = 5;
|
||||
const FIT_TOP = 30;
|
||||
const FIT_BOTTOM = 14;
|
||||
// 이름 우선순위(절정 단풍 > 절정 은행 > 첫 단풍 > 나머지)와 그 이름이 나오기 시작하는 배율(처음 화면 대비)
|
||||
const pri = (m: Spot) => (m.stage === 'peak' ? (m.kind === 'maple' ? 0 : 1) : m.stage === 'first' ? 2 : 3);
|
||||
const LABEL_FROM = [1, 1.6, 2.5, 3.5];
|
||||
// 점이 나오기 시작하는 배율: 처음엔 절정 잎만 보여 차분하게
|
||||
const DOT_FROM: Record<Stage, number> = { peak: 1, first: 1.6, before: 2.5, gone: 2.5 };
|
||||
const ZOOM_BTNS = [
|
||||
['+', '확대', 1.6],
|
||||
['−', '축소', 1 / 1.6],
|
||||
] as const;
|
||||
|
||||
export type FoliageMapHandle = { focus: (m: Spot) => void };
|
||||
|
||||
type Props = { spots: Spot[]; sel: string | null; onSelect: (name: string | null) => void; height: number; ref?: Ref<FoliageMapHandle> };
|
||||
|
||||
/**
|
||||
* 단풍 지도 페이지의 지도: 두 손가락으로 확대·이동, 한 손가락으로 이동, 누르면 가까운 명소 고르기, 두 번 누르면 확대 (웹 FoliagePage 지도).
|
||||
* 앱은 지도를 스크롤 밖에 고정해 손짓이 페이지 스크롤과 다투지 않는다
|
||||
*/
|
||||
export function FoliageMap({ spots, sel, onSelect, height, ref }: Props) {
|
||||
const vpRef = useRef<View>(null);
|
||||
const origin = useRef({ x: 0, y: 0 });
|
||||
const [box, setBox] = useState({ W: 0, H: 0 });
|
||||
const [view, setView] = useState<Cam>({ s: 1, tx: 0, ty: 0 });
|
||||
const viewRef = useRef(view);
|
||||
useLayoutEffect(() => {
|
||||
viewRef.current = view;
|
||||
}, [view]);
|
||||
const [size, measure] = useLabelSizes();
|
||||
|
||||
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
|
||||
const fit = useMemo<Cam>(() => {
|
||||
const { W, H } = box;
|
||||
if (!W || !spots.length) return { s: 1, tx: 0, ty: 0 };
|
||||
const xs = spots.map((m) => m.x);
|
||||
const ys = spots.map((m) => m.y);
|
||||
const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
|
||||
// 위쪽은 맨 북쪽 이름표가 잘리지 않게 FIT_TOP 만큼 띄우고, 아래는 제주까지만
|
||||
const h = H - FIT_TOP - FIT_BOTTOM;
|
||||
// 가로는 땅 가운데(LAND_CX)에 맞추되 동·서 끝 명소가 다 들어오게
|
||||
const half = Math.max(LAND_CX - x0, x1 - LAND_CX) + 0.07;
|
||||
const s = Math.min(W / (2 * half * W), h / ((y1 - y0) * W));
|
||||
return { s, tx: W / 2 - LAND_CX * W * s, ty: FIT_TOP + h / 2 - ((y0 + y1) / 2) * W * s };
|
||||
}, [box, spots]);
|
||||
|
||||
const clamp = useCallback(
|
||||
(v: Cam): Cam => {
|
||||
const { W, H } = box;
|
||||
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s));
|
||||
const w = W * s;
|
||||
// 지도 그림 가장자리가 화면 안쪽으로 너무 들어오지 않게
|
||||
const tx = Math.min(W * 0.25, Math.max(W * 0.75 - w, v.tx));
|
||||
const ty = Math.min(H * 0.25, Math.max(H * 0.75 - w, v.ty));
|
||||
return { s, tx, ty };
|
||||
},
|
||||
[box, fit],
|
||||
);
|
||||
|
||||
const anim = useRef(0);
|
||||
const set = useCallback((v: Cam) => {
|
||||
cancelAnimationFrame(anim.current);
|
||||
setView(v);
|
||||
}, []);
|
||||
const animateTo = useCallback(
|
||||
(to: Cam) => {
|
||||
cancelAnimationFrame(anim.current);
|
||||
const from = viewRef.current;
|
||||
const target = clamp(to);
|
||||
const start = performance.now();
|
||||
const step = (now: number) => {
|
||||
const k = Math.min(1, (now - start) / 280);
|
||||
const e = 1 - (1 - k) ** 3;
|
||||
setView({ s: from.s + (target.s - from.s) * e, tx: from.tx + (target.tx - from.tx) * e, ty: from.ty + (target.ty - from.ty) * e });
|
||||
if (k < 1) anim.current = requestAnimationFrame(step);
|
||||
};
|
||||
anim.current = requestAnimationFrame(step);
|
||||
},
|
||||
[clamp],
|
||||
);
|
||||
const zoomAt = useCallback(
|
||||
(f: number, cx: number, cy: number, smooth = false) => {
|
||||
const v = viewRef.current;
|
||||
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s * f));
|
||||
const k = s / v.s;
|
||||
const next = clamp({ s, tx: cx - (cx - v.tx) * k, ty: cy - (cy - v.ty) * k });
|
||||
if (smooth) animateTo(next);
|
||||
else set(next);
|
||||
},
|
||||
[fit, clamp, animateTo, set],
|
||||
);
|
||||
const focus = useCallback(
|
||||
(m: Spot) => {
|
||||
const { W, H } = box;
|
||||
const s = Math.max(viewRef.current.s, fit.s * 2.5);
|
||||
animateTo({ s, tx: W / 2 - m.x * W * s, ty: H * 0.42 - m.y * W * s });
|
||||
},
|
||||
[box, fit, animateTo],
|
||||
);
|
||||
useImperativeHandle(ref, () => ({ focus }), [focus]);
|
||||
|
||||
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로. 그 뒤 크기가 바뀌면 지금 화면을 범위 안으로
|
||||
const started = useRef(false);
|
||||
const linked = useRef(sel);
|
||||
useEffect(() => {
|
||||
if (!box.W) return;
|
||||
if (started.current) {
|
||||
set(clamp(viewRef.current));
|
||||
return;
|
||||
}
|
||||
started.current = true;
|
||||
set(fit);
|
||||
const m = spots.find((s) => s.name === linked.current);
|
||||
if (m) focus(m);
|
||||
}, [box, fit, spots, set, clamp, focus]);
|
||||
useEffect(() => () => cancelAnimationFrame(anim.current), []);
|
||||
|
||||
const pts = useMemo(() => {
|
||||
const ratio = view.s / fit.s;
|
||||
const visible = spots.filter((m) => m.name === sel || ratio >= DOT_FROM[m.stage] - 0.01);
|
||||
return spread(visible.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: DOT_R[m.stage] })));
|
||||
}, [spots, view, box.W, fit.s, sel]);
|
||||
const ptsRef = useRef(pts);
|
||||
useLayoutEffect(() => {
|
||||
ptsRef.current = pts;
|
||||
}, [pts]);
|
||||
|
||||
const labelAt = useMemo(() => {
|
||||
const ratio = view.s / fit.s;
|
||||
const order = pts.filter((p) => p.m.name === sel || ratio >= LABEL_FROM[pri(p.m)]).sort((a, b) => Number(b.m.name === sel) - Number(a.m.name === sel) || pri(a.m) - pri(b.m));
|
||||
// 오른쪽 위 +/− 단추 자리는 비운다
|
||||
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }];
|
||||
return placeLabels(order, pts, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.stage === 'peak' || p.m.name === sel);
|
||||
}, [pts, size, sel, view.s, fit.s, box]);
|
||||
const provs = useMemo(
|
||||
() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: view.tx + v.x * box.W * view.s, y: view.ty + v.y * box.W * view.s })), pts, labelBoxes(labelAt, size)),
|
||||
[view, box.W, pts, labelAt, size],
|
||||
);
|
||||
|
||||
// 손짓 상태: 두 손가락 거리·가운데, 한 손가락 시작점과 움직였는지, 마지막으로 누른 때(두 번 누르기)
|
||||
const gesture = useRef<{ pinch: { d: number; x: number; y: number } | null; one: { x: number; y: number; moved: boolean } | null; lastTap: number }>({ pinch: null, one: null, lastTap: 0 });
|
||||
const local = (t: { pageX: number; pageY: number }) => ({ x: t.pageX - origin.current.x, y: t.pageY - origin.current.y });
|
||||
const pickAt = (x: number, y: number) => {
|
||||
const best = nearest(ptsRef.current, x, y);
|
||||
onSelect(best && best !== sel ? best : null);
|
||||
};
|
||||
const begin = (e: GestureResponderEvent) => {
|
||||
const g = gesture.current;
|
||||
const ts = e.nativeEvent.touches;
|
||||
if (ts.length >= 2) {
|
||||
const [a, b] = [local(ts[0]), local(ts[1])];
|
||||
g.pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
|
||||
g.one = null;
|
||||
} else if (ts.length === 1) {
|
||||
g.pinch = null;
|
||||
g.one = { ...local(ts[0]), moved: false };
|
||||
}
|
||||
};
|
||||
const onGrant = (e: GestureResponderEvent) => {
|
||||
cancelAnimationFrame(anim.current);
|
||||
// 지도 칸의 화면 위치: 손가락 좌표(pageX)를 지도 안 좌표로 바꾸는 데 쓴다
|
||||
vpRef.current?.measure((_x, _y, _w, _h, px, py) => {
|
||||
origin.current = { x: px, y: py };
|
||||
});
|
||||
begin(e);
|
||||
};
|
||||
const onMove = (e: GestureResponderEvent) => {
|
||||
const g = gesture.current;
|
||||
const ts = e.nativeEvent.touches;
|
||||
if (ts.length >= 2) {
|
||||
if (!g.pinch) return begin(e);
|
||||
const [a, b] = [local(ts[0]), local(ts[1])];
|
||||
const d = Math.hypot(a.x - b.x, a.y - b.y);
|
||||
const x = (a.x + b.x) / 2;
|
||||
const y = (a.y + b.y) / 2;
|
||||
const v = viewRef.current;
|
||||
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, (v.s * d) / g.pinch.d));
|
||||
const k = s / v.s;
|
||||
set(clamp({ s, tx: x - (g.pinch.x - v.tx) * k, ty: y - (g.pinch.y - v.ty) * k }));
|
||||
g.pinch = { d, x, y };
|
||||
return;
|
||||
}
|
||||
// 두 손가락에서 한 손가락이 떨어지면 남은 손가락으로 이어서 이동 (누르기로는 안 친다)
|
||||
if (!g.one || g.pinch) {
|
||||
if (ts.length === 1) g.one = { ...local(ts[0]), moved: true };
|
||||
g.pinch = null;
|
||||
return;
|
||||
}
|
||||
const p = local(ts[0]);
|
||||
if (Math.hypot(p.x - g.one.x, p.y - g.one.y) > 6) g.one.moved = true;
|
||||
if (!g.one.moved) return;
|
||||
const v = viewRef.current;
|
||||
set(clamp({ s: v.s, tx: v.tx + p.x - g.one.x, ty: v.ty + p.y - g.one.y }));
|
||||
g.one = { ...p, moved: true };
|
||||
};
|
||||
const onRelease = (e: GestureResponderEvent) => {
|
||||
const g = gesture.current;
|
||||
const tap = g.one && !g.one.moved ? g.one : null;
|
||||
g.one = null;
|
||||
g.pinch = null;
|
||||
if (!tap) return;
|
||||
// 두 번 누르기: 300ms 안에 또 누르면 확대
|
||||
if (e.nativeEvent.timestamp - g.lastTap < 300) {
|
||||
g.lastTap = 0;
|
||||
zoomAt(2, tap.x, tap.y, true);
|
||||
} else {
|
||||
g.lastTap = e.nativeEvent.timestamp;
|
||||
pickAt(tap.x, tap.y);
|
||||
}
|
||||
};
|
||||
const onEnd = () => {
|
||||
gesture.current.one = null;
|
||||
gesture.current.pinch = null;
|
||||
};
|
||||
|
||||
const onLayout = (e: LayoutChangeEvent) => {
|
||||
const { width, height: h } = e.nativeEvent.layout;
|
||||
setBox({ W: width, H: h });
|
||||
vpRef.current?.measure((_x, _y, _w, _h, px, py) => {
|
||||
origin.current = { x: px, y: py };
|
||||
});
|
||||
};
|
||||
const markers = [...pts].sort((a, b) => Number(a.m.stage === 'peak') - Number(b.m.stage === 'peak'));
|
||||
|
||||
return (
|
||||
<View
|
||||
ref={vpRef}
|
||||
onLayout={onLayout}
|
||||
onStartShouldSetResponder={() => true}
|
||||
onMoveShouldSetResponder={() => true}
|
||||
onResponderTerminationRequest={() => false}
|
||||
onResponderGrant={onGrant}
|
||||
onResponderMove={onMove}
|
||||
onResponderRelease={onRelease}
|
||||
onResponderTerminate={onEnd}
|
||||
className="overflow-hidden"
|
||||
style={{ height, backgroundColor: PAPER }}
|
||||
accessibilityLabel="단풍 지도"
|
||||
>
|
||||
{box.W > 0 ? <MapImage style={{ left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} /> : null}
|
||||
{provs.map((v) => (
|
||||
<Province key={v.name} name={v.name} x={v.x} y={v.y} />
|
||||
))}
|
||||
{markers.map((p) => (
|
||||
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
|
||||
))}
|
||||
{spots.map((m) => (
|
||||
<Label key={m.name} m={m} at={labelAt[m.name]} sel={m.name === sel} onPress={() => onSelect(m.name === sel ? null : m.name)} onLayout={measure(m.name)} accessibilityLabel={`${m.name} 고르기`} />
|
||||
))}
|
||||
<View className="absolute top-2.5 right-2.5 gap-2" style={{ zIndex: 4 }}>
|
||||
{ZOOM_BTNS.map(([t, label, f]) => (
|
||||
<Pressable key={t} onPress={() => zoomAt(f, box.W / 2, box.H / 2, true)} accessibilityRole="button" accessibilityLabel={label} className="size-9 items-center justify-center rounded-full bg-white" style={{ boxShadow: '0 2px 6px rgba(40,48,74,0.2)' }}>
|
||||
<Text className="text-[20px] leading-6 font-bold" style={{ color: MAP_INK }}>
|
||||
{t}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { Kind, LabelSize, Pt, Spot, Stage } from '@nalssigak/shared/lib/foliage';
|
||||
import { Image } from 'expo-image';
|
||||
import { useCallback, useRef, useState, type ReactNode } from 'react';
|
||||
import { Platform, Pressable, View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from 'react-native';
|
||||
|
||||
import { Text } from '@/components/text';
|
||||
import { Ic } from '@/components/ui';
|
||||
import { MAP_IMAGE } from '@/lib/foliage';
|
||||
|
||||
// 지도는 밤에도 밝은 종이 그대로 (웹 b-keep-bg)
|
||||
export const PAPER = '#fff6ea';
|
||||
export const MAP_INK = '#28304a';
|
||||
export const MAP_INK3 = '#6b7189';
|
||||
const LABEL_INK: Record<Kind, string> = { maple: '#b5321f', ginkgo: '#8a6508' };
|
||||
|
||||
/**
|
||||
* 지도 그림. 웹은 채도를 빼서(saturate .3) 잎 아이콘이 묻히지 않게 한다.
|
||||
* 안드로이드는 같은 filter, iOS 는 filter 의 채도를 못 써서 종이색을 반쯤 덮어 옅게 한다
|
||||
*/
|
||||
export function MapImage({ style }: { style: StyleProp<ViewStyle> }) {
|
||||
const android = Platform.OS === 'android';
|
||||
return (
|
||||
<View pointerEvents="none" style={[{ position: 'absolute' }, style, android ? { filter: [{ saturate: 0.3 }, { brightness: 1.08 }] } : null]}>
|
||||
<Image source={MAP_IMAGE} style={{ width: '100%', height: '100%' }} contentFit="contain" accessibilityIgnoresInvertColors />
|
||||
{!android && <View style={{ position: 'absolute', inset: 0, backgroundColor: PAPER, opacity: 0.5 }} />}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const DOT: Record<Exclude<Stage, 'peak'>, { size: number; color: string }> = {
|
||||
first: { size: 7, color: 'rgba(217,119,46,0.85)' },
|
||||
before: { size: 5, color: 'rgba(143,138,128,0.6)' },
|
||||
gone: { size: 5, color: 'rgba(143,138,128,0.6)' },
|
||||
};
|
||||
|
||||
/** 단계 표시: 절정은 잎, 첫 단풍은 주황 점, 단풍 전·지남은 회색 점(big 이면 점을 크게) */
|
||||
export function StageMark({ m, big }: { m: Spot; big?: boolean }) {
|
||||
if (m.stage === 'peak') return <Ic name={m.kind} size={big ? 32 : 20} />;
|
||||
const dot = DOT[m.stage];
|
||||
const size = big ? 14 : dot.size;
|
||||
return <View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: dot.color }} />;
|
||||
}
|
||||
|
||||
/** 지도 위 점·잎. 고른 명소는 속이 빈 고리만 둘러 옆 명소를 가리지 않게 */
|
||||
export function Marker({ p, sel }: { p: Pt; sel: boolean }) {
|
||||
return (
|
||||
<View pointerEvents="none" className="absolute size-8 items-center justify-center" style={{ left: p.x - 16, top: p.y - 16, zIndex: sel ? 3 : 1 }}>
|
||||
{sel ? <View className="absolute size-8 rounded-full border-[2.5px]" style={{ borderColor: MAP_INK, backgroundColor: 'rgba(255,255,255,0.3)' }} /> : null}
|
||||
<StageMark m={p.m} big={sel && p.m.stage !== 'peak'} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** 시·도 이름: 지도에 옅게 깔리는 글자. 산 무늬 위에서도 읽히게 종이색 번짐을 두른다 */
|
||||
export function Province({ name, x, y }: { name: string; x: number; y: number }) {
|
||||
return (
|
||||
<View pointerEvents="none" className="absolute w-10 items-center" style={{ left: x - 20, top: y - 8 }} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
|
||||
<Text className="font-jua text-[13px] leading-4" style={{ color: 'rgba(92,74,54,0.85)', textShadowColor: PAPER, textShadowRadius: 4 }}>
|
||||
{name}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 명소 이름표. 자리를 못 받았으면(at 없음) 숨긴 채 왼쪽 위에 두고 크기만 잰다 (웹 useLabelSize 대신 onLayout).
|
||||
* tone: 고름(진한 바탕) · 절정(잎 색 글자) · 그 밖(회색 글자)
|
||||
*/
|
||||
export function Label({ m, at, sel, onPress, onLayout, accessibilityLabel }: { m: Spot; at?: { left: number; top: number }; sel?: boolean; onPress: () => void; onLayout: (e: LayoutChangeEvent) => void; accessibilityLabel: string }) {
|
||||
const color = sel ? '#ffffff' : m.stage === 'peak' ? LABEL_INK[m.kind] : '#5b6075';
|
||||
return (
|
||||
<Pressable
|
||||
onPress={onPress}
|
||||
onLayout={onLayout}
|
||||
disabled={!at}
|
||||
hitSlop={{ top: 8, bottom: 8, left: 4, right: 4 }}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
accessibilityElementsHidden={!at}
|
||||
importantForAccessibility={at ? 'auto' : 'no-hide-descendants'}
|
||||
className="absolute rounded-[7px] px-[5px] py-px"
|
||||
style={{
|
||||
left: at?.left ?? 0,
|
||||
top: at?.top ?? 0,
|
||||
opacity: at ? 1 : 0,
|
||||
zIndex: sel ? 3 : 2,
|
||||
backgroundColor: sel ? MAP_INK : 'rgba(255,255,255,0.92)',
|
||||
boxShadow: '0 1px 3px rgba(40,48,74,0.18)',
|
||||
}}
|
||||
>
|
||||
<Text numberOfLines={1} className="text-[11.5px] leading-[15.5px] font-extrabold" style={{ color }}>
|
||||
{m.name}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
/** 이름표 크기 모으기: Label 의 onLayout 을 받아 이름별 폭·높이. 한 프레임에 한 번만 다시 그린다 */
|
||||
export function useLabelSizes() {
|
||||
const [size, setSize] = useState<LabelSize>({});
|
||||
const acc = useRef<LabelSize>({});
|
||||
const frame = useRef(0);
|
||||
const measure = useCallback(
|
||||
(name: string) => (e: LayoutChangeEvent) => {
|
||||
const { width: w, height: h } = e.nativeEvent.layout;
|
||||
const old = acc.current[name];
|
||||
if (old && Math.abs(old.w - w) < 0.5 && Math.abs(old.h - h) < 0.5) return;
|
||||
acc.current = { ...acc.current, [name]: { w, h } };
|
||||
cancelAnimationFrame(frame.current);
|
||||
frame.current = requestAnimationFrame(() => setSize(acc.current));
|
||||
},
|
||||
[],
|
||||
);
|
||||
return [size, measure] as const;
|
||||
}
|
||||
|
||||
/** 범례: 절정 잎 둘, full 이면 첫 단풍·단풍 전 점까지 */
|
||||
export function Legend({ full, color }: { full?: boolean; color: string }) {
|
||||
const item = (mark: ReactNode, label: string) => (
|
||||
<View key={label} className="flex-row items-center gap-1">
|
||||
{mark}
|
||||
<Text className="text-[12.5px] font-bold" style={{ color }}>
|
||||
{label}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
return (
|
||||
<View className="h-[52px] flex-row flex-wrap items-center justify-center gap-x-3 gap-y-1">
|
||||
{item(<Ic name="maple" size={16} />, '단풍 절정')}
|
||||
{item(<Ic name="ginkgo" size={16} />, '은행 절정')}
|
||||
{full ? item(<View style={{ width: 7, height: 7, borderRadius: 4, backgroundColor: DOT.first.color }} />, '첫 단풍') : null}
|
||||
{full ? item(<View style={{ width: 5, height: 5, borderRadius: 3, backgroundColor: DOT.before.color }} />, '단풍 전') : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { md, STAGE, type Spot, type Stage } from '@nalssigak/shared/lib/foliage';
|
||||
import { Pressable, View } from 'react-native';
|
||||
|
||||
import { Legend, StageMark } from '@/components/foliage/parts';
|
||||
import { Text } from '@/components/text';
|
||||
|
||||
const GROUPS: [Stage, string][] = [
|
||||
['peak', '지금 절정'],
|
||||
['first', '곧 절정'],
|
||||
['before', '아직'],
|
||||
['gone', '절정 지남'],
|
||||
];
|
||||
|
||||
const CHIP: Partial<Record<Stage, { bg: string; ink: string }>> = {
|
||||
peak: { bg: '#ffe3db', ink: '#b5321f' },
|
||||
first: { bg: '#ffe8d2', ink: '#a34f12' },
|
||||
};
|
||||
|
||||
/** 지도 아래 한 줄: 고른 명소가 있으면 그 명소 정보, 없으면 범례 (지도 위를 가리지 않게 범례 자리에) */
|
||||
export function ChosenBar({ chosen, legendColor }: { chosen?: Spot; legendColor: string }) {
|
||||
if (!chosen)
|
||||
return (
|
||||
<View className="mx-3 mt-2 h-[60px] justify-center">
|
||||
<Legend full color={legendColor} />
|
||||
</View>
|
||||
);
|
||||
const chip = CHIP[chosen.stage];
|
||||
return (
|
||||
<View className="mx-3 mt-2 h-[60px] flex-row items-center gap-3 rounded-[18px] border-b-4 border-shade bg-card px-3.5">
|
||||
<View className="size-8 items-center justify-center">
|
||||
<StageMark m={chosen} big />
|
||||
</View>
|
||||
<View className="min-w-0 flex-1">
|
||||
<View className="flex-row items-center gap-1.5">
|
||||
<Text numberOfLines={1} className="shrink font-jua text-[18px] text-ink">
|
||||
{chosen.name}
|
||||
</Text>
|
||||
<Text className={`overflow-hidden rounded-full px-1.5 py-px text-[11px] font-extrabold ${chip ? '' : 'bg-chip text-ink2'}`} style={chip ? { backgroundColor: chip.bg, color: chip.ink } : undefined}>
|
||||
{STAGE[chosen.stage]}
|
||||
</Text>
|
||||
</View>
|
||||
<Text numberOfLines={1} className="text-[12px] font-bold text-ink3">
|
||||
{`${chosen.region} · 절정 예상 ${md(chosen.peak)}`}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** 단계별 명소 목록 (지금 절정 · 곧 절정 · 아직 · 절정 지남). 누르면 지도에서 그 명소로 */
|
||||
export function SpotList({ spots, sel, onPick }: { spots: Spot[]; sel: string | null; onPick: (m: Spot) => void }) {
|
||||
return (
|
||||
<View className="px-4">
|
||||
{GROUPS.map(([g, title]) => {
|
||||
const rows = spots.filter((m) => m.stage === g).sort((a, b) => a.peak.localeCompare(b.peak));
|
||||
if (!rows.length) return null;
|
||||
return (
|
||||
<View key={g} accessibilityLabel={title} className="pt-5">
|
||||
<View className="flex-row items-baseline gap-1.5 px-1 pb-1.5">
|
||||
<Text className="font-jua text-[19px] text-ink">{title}</Text>
|
||||
<Text className="text-[13px] font-extrabold text-ink3">{`${rows.length}곳`}</Text>
|
||||
</View>
|
||||
<View className="border-t border-line">
|
||||
{rows.map((m) => (
|
||||
<Pressable
|
||||
key={m.name}
|
||||
onPress={() => onPick(m)}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: m.name === sel }}
|
||||
className="flex-row items-center gap-3 border-b border-line py-2.5 pl-1"
|
||||
style={m.name === sel ? { backgroundColor: 'rgba(255,122,69,0.08)' } : undefined}
|
||||
>
|
||||
<View className="size-7 items-center justify-center">
|
||||
<StageMark m={m} big />
|
||||
</View>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text numberOfLines={1} className="text-[15px] font-extrabold text-ink">
|
||||
{m.name}
|
||||
</Text>
|
||||
<Text numberOfLines={1} className="text-[12px] font-semibold text-ink3">
|
||||
{`${m.region} · ${m.own ? '절정 예상' : '가까운 지점 날짜'}`}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className={`pr-1 font-jua text-[18px] ${g === 'peak' ? 'text-orange' : 'text-ink2'}`}>{md(m.peak)}</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -35,7 +35,7 @@ export function GakGrid({ items, dim }: { items: IndexSummary[]; dim: boolean })
|
||||
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>}
|
||||
{!!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}
|
||||
|
||||