Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5df1cfb49f | ||
|
|
38e7c7adde | ||
|
|
96e40d00c8 | ||
|
|
639ca83553 | ||
|
|
11ce52a2d1 | ||
|
|
3257360b5b | ||
|
|
d5f6484aa6 | ||
|
|
c5129d14ed | ||
|
|
dc8201e5f5 | ||
|
|
1a98adc155 | ||
|
|
490f39f712 | ||
|
|
727f8852af | ||
|
|
5c134ddf2f | ||
|
|
520fae93a8 | ||
|
|
ceda60bde7 | ||
|
|
b6664f2b5d | ||
|
|
cd77589d86 | ||
|
|
502b6e5396 | ||
|
|
016b77f234 | ||
|
|
d4f937b439 | ||
|
|
9c4852959b |
No files matched your search
@@ -38,3 +38,6 @@ secrets/
|
|||||||
*.pem
|
*.pem
|
||||||
*.key
|
*.key
|
||||||
*.crt
|
*.crt
|
||||||
|
|
||||||
|
# 기획 중 띄우는 시안 화면(brainstorming): 커밋하지 않는다
|
||||||
|
.superpowers/
|
||||||
@@ -8,3 +8,11 @@
|
|||||||
3. `docs/이벤트_추적.md` 이벤트 목록 표에 행 추가
|
3. `docs/이벤트_추적.md` 이벤트 목록 표에 행 추가
|
||||||
- 완료 보고의 검증 결과에 넣은 이벤트 이름을 적는다. GA 없이 "완료"라고 하지 않는다.
|
- 완료 보고의 검증 결과에 넣은 이벤트 이름을 적는다. GA 없이 "완료"라고 하지 않는다.
|
||||||
- 값에 개인정보(아이디·닉네임·생년월일 등)를 넣지 않는다.
|
- 값에 개인정보(아이디·닉네임·생년월일 등)를 넣지 않는다.
|
||||||
|
|
||||||
|
## 백엔드 테스트 실행
|
||||||
|
|
||||||
|
- Git Bash 에서 아래처럼 돌린다. 도커의 postgres·redis 가 떠 있어야 한다.
|
||||||
|
`cd backend && AZURE_STORAGE_CONNECTION_STRING= AZURE_STORAGE_CONTAINER= AZURE_BLOB_BASE_URL= AZURE_BLOB_SAS_TOKEN= PGSSLMODE=disable .venv/Scripts/python.exe -m pytest -q`
|
||||||
|
- `PGSSLMODE=disable`: 없으면 DB 접속에서 `OSError: [Errno 42] Illegal byte sequence` 로 죽는다. asyncpg 가 홈 폴더 아래 기본 인증서 경로를 여는데, 사용자 이름이 한글이면 그 경로를 못 읽는다.
|
||||||
|
- Azure 변수 4개 비우기: `.env` 에 Azure 사진 저장소가 켜져 있으면 `tests/test_talk_image.py` 가 시험용 사진을 실제 저장소에 올리고, 로컬에서 못 읽어 404 로 실패한다. 비우면 로컬 폴더에 저장한다.
|
||||||
|
- 2026-11-25 기준 main 에서도 실패하는 테스트: `test_saju_api::test_level_unlocks_sections_and_awards_once`, `test_seo::test_new_copy_pages_get_new_title_and_description`.
|
||||||
@@ -480,3 +480,9 @@ docs를 6개로 합칠 때 옛 내용을 그대로 옮겼다. 아래는 코드
|
|||||||
| [ ] | 공유 → 유입 숫자 보기: `type_share` 대비 `type_landing`, `type_landing` 대비 `type_start`·`type_result`. 사내 IP 제외 필터가 없어 초기 숫자에 팀 접속이 섞임 | 목적이 처음 오는 사람 늘리기 | `docs/이벤트_추적.md` |
|
| [ ] | 공유 → 유입 숫자 보기: `type_share` 대비 `type_landing`, `type_landing` 대비 `type_start`·`type_result`. 사내 IP 제외 필터가 없어 초기 숫자에 팀 접속이 섞임 | 목적이 처음 오는 사람 늘리기 | `docs/이벤트_추적.md` |
|
||||||
| [ ] | **[결정 필요]** 잘 맞는 각이 오늘 0점이어도 그대로 보임(예: 저녁의 낚시각 0) — 그대로 둘지, 점수 낮은 각은 빼고 뽑을지 | 11/23 화면 확인 중 발견. 지금은 '풀 6개에서 날짜 기준 무작위 3개' 결정대로 | `frontend/src/b/weatherType.ts` `pickGaks` |
|
| [ ] | **[결정 필요]** 잘 맞는 각이 오늘 0점이어도 그대로 보임(예: 저녁의 낚시각 0) — 그대로 둘지, 점수 낮은 각은 빼고 뽑을지 | 11/23 화면 확인 중 발견. 지금은 '풀 6개에서 날짜 기준 무작위 3개' 결정대로 | `frontend/src/b/weatherType.ts` `pickGaks` |
|
||||||
| [ ] | (나중) 링크 공유 숫자를 본 뒤 '그림 저장' 버튼, 결과 통계("전체의 몇 %") 검토 | 설계에서 뒤로 미룸 | |
|
| [ ] | (나중) 링크 공유 숫자를 본 뒤 '그림 저장' 버튼, 결과 통계("전체의 몇 %") 검토 | 설계에서 뒤로 미룸 | |
|
||||||
|
|
||||||
|
## 날씨 위젯 (2026-11-26)
|
||||||
|
|
||||||
|
| 상태 | 할 일 | 이유 | 관련 파일 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| [ ] | 남은 일 — ① 군산각·스테이머뭄의 기존 카드를 새 위젯으로 교체(다른 저장소) ② 배포 뒤 확인: 다른 사이트에서 카드가 보이는지, 노출 집계(`/v1/admin/widget/views`)에 그 사이트 주소가 남는지, 앞단 프록시가 `Referer` 를 지우지 않는지, 카드 응답에 쿠키가 없는지 ③ 필요하면 문제 사이트 차단 기능 ④ 카드 내용 높이 자동 맞춤(스크립트 방식, postMessage)은 카드 모양을 크게 바꿀 때 | 위젯 구현 후 남은 것. 운영 방법은 `docs/위젯_운영.md` | `backend/services/embed_service.py`, `frontend/public/embed/widget.js`, `frontend/src/lib/embedWidget.ts` |
|
||||||
@@ -538,3 +538,12 @@ class TalkReport(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
|
||||||
|
|
||||||
|
class WidgetViewDaily(Base):
|
||||||
|
__tablename__ = "widget_view_daily"
|
||||||
|
|
||||||
|
day: Mapped[date] = mapped_column(Date, primary_key=True)
|
||||||
|
host: Mapped[str] = mapped_column(String(253), primary_key=True)
|
||||||
|
kind: Mapped[str] = mapped_column(String(8), primary_key=True)
|
||||||
|
views: Mapped[int] = mapped_column(Integer, default=0)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.dialects.postgresql import insert
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from common.database.model.models import WidgetViewDaily
|
||||||
|
|
||||||
|
|
||||||
|
class WidgetCRUD:
|
||||||
|
async def add_views(self, s: AsyncSession, day: date, counts: dict[tuple[str, str], int]) -> None:
|
||||||
|
"""그날 (host, kind) 별 노출 수를 표에 더한다 (없으면 넣는다)."""
|
||||||
|
if not counts:
|
||||||
|
return
|
||||||
|
stmt = insert(WidgetViewDaily).values([{"day": day, "host": host, "kind": kind, "views": n} for (host, kind), n in counts.items()])
|
||||||
|
await s.execute(stmt.on_conflict_do_update(index_elements=[WidgetViewDaily.day, WidgetViewDaily.host, WidgetViewDaily.kind], set_={"views": WidgetViewDaily.views + stmt.excluded.views}))
|
||||||
|
|
||||||
|
async def views_since(self, s: AsyncSession, since: date) -> dict[str, int]:
|
||||||
|
"""since 날짜부터(포함) 호스트별 노출 수 합"""
|
||||||
|
rows = await s.execute(select(WidgetViewDaily.host, func.sum(WidgetViewDaily.views)).where(WidgetViewDaily.day >= since).group_by(WidgetViewDaily.host))
|
||||||
|
return {host: int(n) for host, n in rows.all()}
|
||||||
@@ -566,3 +566,12 @@ CREATE TABLE IF NOT EXISTS public.reel (
|
|||||||
ig_media_id VARCHAR(40) NULL,
|
ig_media_id VARCHAR(40) NULL,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
-- 위젯 하루 노출 수. host 는 부른 사이트 호스트, '(알 수 없음)', '(기타)'. 방문자 정보는 없다
|
||||||
|
CREATE TABLE IF NOT EXISTS public.widget_view_daily (
|
||||||
|
day DATE NOT NULL,
|
||||||
|
host VARCHAR(253) NOT NULL,
|
||||||
|
kind VARCHAR(8) NOT NULL, -- side | home
|
||||||
|
views INTEGER NOT NULL DEFAULT 0,
|
||||||
|
PRIMARY KEY (day, host, kind)
|
||||||
|
);
|
||||||
@@ -8,8 +8,10 @@ from common.cache.redis_client import REDIS
|
|||||||
from common.database.db_session_manager import DB_SESSION_MNG
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
from common.models.gmodel import Res_WebPacketProtocol
|
from common.models.gmodel import Res_WebPacketProtocol
|
||||||
from router.v1.admin.users import router as admin_users_router
|
from router.v1.admin.users import router as admin_users_router
|
||||||
|
from router.v1.admin.widget import router as admin_widget_router
|
||||||
from router.v1.auth.account import router as auth_router
|
from router.v1.auth.account import router as auth_router
|
||||||
from router.v1.card.card import router as card_router
|
from router.v1.card.card import router as card_router
|
||||||
|
from router.v1.embed.embed import router as embed_router
|
||||||
from router.v1.reel.reel import router as reel_router
|
from router.v1.reel.reel import router as reel_router
|
||||||
from router.v1.feed.feed import router as feed_router
|
from router.v1.feed.feed import router as feed_router
|
||||||
from router.v1.image.image import router as image_router
|
from router.v1.image.image import router as image_router
|
||||||
@@ -60,9 +62,11 @@ app.include_router(watch_router)
|
|||||||
app.include_router(image_router)
|
app.include_router(image_router)
|
||||||
app.include_router(seo_router)
|
app.include_router(seo_router)
|
||||||
app.include_router(card_router)
|
app.include_router(card_router)
|
||||||
|
app.include_router(embed_router)
|
||||||
app.include_router(reel_router)
|
app.include_router(reel_router)
|
||||||
app.include_router(shorts_router)
|
app.include_router(shorts_router)
|
||||||
app.include_router(admin_users_router)
|
app.include_router(admin_users_router)
|
||||||
|
app.include_router(admin_widget_router)
|
||||||
|
|
||||||
|
|
||||||
class Res_Health(Res_WebPacketProtocol):
|
class Res_Health(Res_WebPacketProtocol):
|
||||||
|
|||||||
@@ -22,3 +22,15 @@ class Res_AdminUsers(Res_WebPacketProtocol):
|
|||||||
total: int = 0
|
total: int = 0
|
||||||
counts: dict[int, int] = Field({}, description="가입 경로(AuthProvider)별 인원")
|
counts: dict[int, int] = Field({}, description="가입 경로(AuthProvider)별 인원")
|
||||||
items: list[AdminUser] = []
|
items: list[AdminUser] = []
|
||||||
|
|
||||||
|
|
||||||
|
class WidgetViewData(WebPacketProtocol):
|
||||||
|
host: str = Field(description="부른 사이트 호스트(소문자), (알 수 없음), (기타)")
|
||||||
|
views_7d: int = Field(description="오늘 포함 최근 7일(한국 날짜) 노출 수")
|
||||||
|
views_30d: int = Field(description="오늘 포함 최근 30일(한국 날짜) 노출 수")
|
||||||
|
|
||||||
|
|
||||||
|
class Res_WidgetViews(Res_WebPacketProtocol):
|
||||||
|
items: list[WidgetViewData] = Field([], description="views_30d 많은 순 (같으면 호스트 이름순)")
|
||||||
|
total_7d: int = Field(0, description="최근 7일 노출 수 합")
|
||||||
|
total_30d: int = Field(0, description="최근 30일 노출 수 합")
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from common.auth import require_admin
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.enums import ErrorType
|
||||||
|
from common.models.errors import error_info
|
||||||
|
from common.utils.kma_time import now_kst
|
||||||
|
from crud.widget_crud import WidgetCRUD
|
||||||
|
from router.v1.admin.protocol import Res_WidgetViews, WidgetViewData
|
||||||
|
from services.embed_service import flush_views
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/v1/admin/widget", tags=["admin"])
|
||||||
|
|
||||||
|
_crud = WidgetCRUD()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/views", response_model=Res_WidgetViews, response_model_exclude_none=True, summary="위젯 노출 수 (관리자). 부른 사이트별 최근 7일·30일. 부를 때 Redis 에 쌓인 수를 표로 옮긴다", dependencies=[Depends(require_admin)])
|
||||||
|
async def list_views() -> Res_WidgetViews:
|
||||||
|
await flush_views() # 카드 요청은 Redis 에만 세므로 읽기 전에 표로 옮긴다
|
||||||
|
today = now_kst().date() # 오늘을 포함한 한국 날짜 7일·30일
|
||||||
|
|
||||||
|
async def run(s):
|
||||||
|
return await _crud.views_since(s, today - timedelta(days=6)), await _crud.views_since(s, today - timedelta(days=29))
|
||||||
|
|
||||||
|
err, res = await DB_SESSION_MNG.execute_lambda(run)
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
return Res_WidgetViews(result=error_info(err))
|
||||||
|
d7, d30 = res
|
||||||
|
items = sorted((WidgetViewData(host=host, views_7d=d7.get(host, 0), views_30d=n) for host, n in d30.items()), key=lambda v: (-v.views_30d, v.host))
|
||||||
|
return Res_WidgetViews(items=items, total_7d=sum(d7.values()), total_30d=sum(d30.values()))
|
||||||
Whitespace-only changes.
@@ -0,0 +1,19 @@
|
|||||||
|
from fastapi import APIRouter, Depends, Query, Request
|
||||||
|
from fastapi.responses import HTMLResponse
|
||||||
|
|
||||||
|
from services.embed_service import EmbedService
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/v1/embed", tags=["embed"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/card", response_class=HTMLResponse, summary="다른 사이트가 iframe 으로 붙이는 날씨 카드 (nginx 가 /embed/card 를 넘김). 신청 없이 누구나 붙인다")
|
||||||
|
async def get_card(
|
||||||
|
request: Request,
|
||||||
|
region: str = Query("", description="지역 코드 10자리"),
|
||||||
|
kind: str = Query("", alias="type", description="side 또는 home"),
|
||||||
|
bg: str = Query("sky", description="카드 배경: sky, light, dark"),
|
||||||
|
service: EmbedService = Depends(),
|
||||||
|
) -> HTMLResponse:
|
||||||
|
# region·type·bg 는 문자열로 받아 서비스가 검사한다 (FastAPI 의 422 JSON 이 iframe 에 뜨지 않게)
|
||||||
|
status, html = await service.card(region, kind, bg, request.headers.get("referer"), request.headers.get("host", ""))
|
||||||
|
return HTMLResponse(html, status_code=status, headers={"Cache-Control": "no-store", "X-Robots-Tag": "noindex"})
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
"""프론트 지역 검색 페이지 목록(frontend/seo/region.json)을 seed/region.csv 로 다시 만든다.
|
"""프론트 지역 검색 페이지 목록(frontend/seo/region.json)과 백엔드용 지역 코드 → 주소 이름(backend/seed/region_path.json)을
|
||||||
|
seed/region.csv 로 다시 만든다.
|
||||||
|
|
||||||
region.csv 가 바뀌면 실행: python backend/scripts/gen_region_pages.py
|
region.csv 가 바뀌면 실행: python backend/scripts/gen_region_pages.py
|
||||||
"""
|
"""
|
||||||
@@ -10,6 +11,7 @@ import os
|
|||||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
SRC = os.path.join(ROOT, "backend", "seed", "region.csv")
|
SRC = os.path.join(ROOT, "backend", "seed", "region.csv")
|
||||||
OUT = os.path.join(ROOT, "frontend", "seo", "region.json")
|
OUT = os.path.join(ROOT, "frontend", "seo", "region.json")
|
||||||
|
PATH_OUT = os.path.join(ROOT, "backend", "seed", "region_path.json")
|
||||||
|
|
||||||
SIDO = dict(서울='seoul', 부산='busan', 대구='daegu', 인천='incheon', 광주='gwangju', 대전='daejeon', 울산='ulsan', 세종='sejong', 경기='gyeonggi', 강원='gangwon', 충북='chungbuk', 충남='chungnam', 전북='jeonbuk', 전남='jeonnam', 경북='gyeongbuk', 경남='gyeongnam', 제주='jeju')
|
SIDO = dict(서울='seoul', 부산='busan', 대구='daegu', 인천='incheon', 광주='gwangju', 대전='daejeon', 울산='ulsan', 세종='sejong', 경기='gyeonggi', 강원='gangwon', 충북='chungbuk', 충남='chungnam', 전북='jeonbuk', 전남='jeonnam', 경북='gyeongbuk', 경남='gyeongnam', 제주='jeju')
|
||||||
R = '''종로 jongno 중 jung 용산 yongsan 성동 seongdong 광진 gwangjin 동대문 dongdaemun 중랑 jungnang 성북 seongbuk 강북 gangbuk 도봉 dobong 노원 nowon 은평 eunpyeong 서대문 seodaemun 마포 mapo 양천 yangcheon 강서 gangseo 구로 guro 금천 geumcheon 영등포 yeongdeungpo 동작 dongjak 관악 gwanak 서초 seocho 강남 gangnam 송파 songpa 강동 gangdong
|
R = '''종로 jongno 중 jung 용산 yongsan 성동 seongdong 광진 gwangjin 동대문 dongdaemun 중랑 jungnang 성북 seongbuk 강북 gangbuk 도봉 dobong 노원 nowon 은평 eunpyeong 서대문 seodaemun 마포 mapo 양천 yangcheon 강서 gangseo 구로 guro 금천 geumcheon 영등포 yeongdeungpo 동작 dongjak 관악 gwanak 서초 seocho 강남 gangnam 송파 songpa 강동 gangdong
|
||||||
@@ -30,6 +32,7 @@ GU = dict(zip(G[::2], G[1::2]))
|
|||||||
# 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다
|
# 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다
|
||||||
CITY_MAIN = {'수원시': '팔달구', '성남시': '중원구', '안양시': '동안구', '부천시': '원미구', '안산시': '단원구', '고양시': '덕양구', '용인시': '처인구', '화성시': '만세구', '청주시': '상당구', '천안시': '서북구', '포항시': '남구', '창원시': '의창구', '전주시': '완산구'}
|
CITY_MAIN = {'수원시': '팔달구', '성남시': '중원구', '안양시': '동안구', '부천시': '원미구', '안산시': '단원구', '고양시': '덕양구', '용인시': '처인구', '화성시': '만세구', '청주시': '상당구', '천안시': '서북구', '포항시': '남구', '창원시': '의창구', '전주시': '완산구'}
|
||||||
pages = {}
|
pages = {}
|
||||||
|
paths = {} # 지역 코드 → 그 지역 페이지 주소 이름 (구로 나뉜 시의 구는 구 주소)
|
||||||
for row in csv.DictReader(open(SRC, encoding='utf-8')):
|
for row in csv.DictReader(open(SRC, encoding='utf-8')):
|
||||||
sido, *rest = row['name'].split()
|
sido, *rest = row['name'].split()
|
||||||
place = rest[0]
|
place = rest[0]
|
||||||
@@ -39,12 +42,19 @@ for row in csv.DictReader(open(SRC, encoding='utf-8')):
|
|||||||
p['regions'].append(r)
|
p['regions'].append(r)
|
||||||
if len(rest) == 1 or CITY_MAIN[place] == rest[1]:
|
if len(rest) == 1 or CITY_MAIN[place] == rest[1]:
|
||||||
p['main'] = r['code']
|
p['main'] = r['code']
|
||||||
|
paths[r['code']] = path
|
||||||
# 구로 나뉜 시의 구도 자기 주소를 갖는다: /today/gyeonggi/seongnam/bundang
|
# 구로 나뉜 시의 구도 자기 주소를 갖는다: /today/gyeonggi/seongnam/bundang
|
||||||
if len(rest) == 2:
|
if len(rest) == 2:
|
||||||
gu = f"{path}/{GU[rest[1][:-1]]}"
|
gu = f"{path}/{GU[rest[1][:-1]]}"
|
||||||
pages[gu] = dict(path=gu, name=row['name'], main=r['code'], regions=[r])
|
pages[gu] = dict(path=gu, name=row['name'], main=r['code'], regions=[r])
|
||||||
|
paths[r['code']] = gu
|
||||||
out = list(pages.values())
|
out = list(pages.values())
|
||||||
assert all(p['main'] for p in out), [p['path'] for p in out if not p['main']]
|
assert all(p['main'] for p in out), [p['path'] for p in out if not p['main']]
|
||||||
assert sum(len(p['regions']) for p in out if p['path'].count('/') == 1) == 256
|
assert sum(len(p['regions']) for p in out if p['path'].count('/') == 1) == 256
|
||||||
json.dump(out, open(OUT, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
|
assert len(paths) == 256
|
||||||
print(len(out), 'pages', sum(len(p['regions']) > 1 for p in out), 'cities')
|
# 윈도우에서 돌려도 줄바꿈이 \r\n 으로 바뀌지 않게 \n 으로 쓴다
|
||||||
|
with open(OUT, 'w', encoding='utf-8', newline='\n') as f:
|
||||||
|
json.dump(out, f, ensure_ascii=False, indent=1)
|
||||||
|
with open(PATH_OUT, 'w', encoding='utf-8', newline='\n') as f:
|
||||||
|
json.dump(paths, f, ensure_ascii=False, indent=1)
|
||||||
|
print(len(out), 'pages', sum(len(p['regions']) > 1 for p in out), 'cities', len(paths), 'region paths')
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
{
|
||||||
|
"1111000000": "seoul/jongno",
|
||||||
|
"1114000000": "seoul/jung",
|
||||||
|
"1117000000": "seoul/yongsan",
|
||||||
|
"1120000000": "seoul/seongdong",
|
||||||
|
"1121500000": "seoul/gwangjin",
|
||||||
|
"1123000000": "seoul/dongdaemun",
|
||||||
|
"1126000000": "seoul/jungnang",
|
||||||
|
"1129000000": "seoul/seongbuk",
|
||||||
|
"1130500000": "seoul/gangbuk",
|
||||||
|
"1132000000": "seoul/dobong",
|
||||||
|
"1135000000": "seoul/nowon",
|
||||||
|
"1138000000": "seoul/eunpyeong",
|
||||||
|
"1141000000": "seoul/seodaemun",
|
||||||
|
"1144000000": "seoul/mapo",
|
||||||
|
"1147000000": "seoul/yangcheon",
|
||||||
|
"1150000000": "seoul/gangseo",
|
||||||
|
"1153000000": "seoul/guro",
|
||||||
|
"1154500000": "seoul/geumcheon",
|
||||||
|
"1156000000": "seoul/yeongdeungpo",
|
||||||
|
"1159000000": "seoul/dongjak",
|
||||||
|
"1162000000": "seoul/gwanak",
|
||||||
|
"1165000000": "seoul/seocho",
|
||||||
|
"1168000000": "seoul/gangnam",
|
||||||
|
"1171000000": "seoul/songpa",
|
||||||
|
"1174000000": "seoul/gangdong",
|
||||||
|
"1211000000": "jeonnam/mokpo",
|
||||||
|
"1213000000": "jeonnam/yeosu",
|
||||||
|
"1215000000": "jeonnam/suncheon",
|
||||||
|
"1217000000": "jeonnam/naju",
|
||||||
|
"1219000000": "jeonnam/gwangyang",
|
||||||
|
"1221000000": "gwangju/dong",
|
||||||
|
"1224000000": "gwangju/seo",
|
||||||
|
"1227000000": "gwangju/nam",
|
||||||
|
"1230000000": "gwangju/buk",
|
||||||
|
"1233000000": "gwangju/gwangsan",
|
||||||
|
"1271000000": "jeonnam/damyang",
|
||||||
|
"1272000000": "jeonnam/gokseong",
|
||||||
|
"1273000000": "jeonnam/gurye",
|
||||||
|
"1274000000": "jeonnam/goheung",
|
||||||
|
"1275000000": "jeonnam/boseong",
|
||||||
|
"1276000000": "jeonnam/hwasun",
|
||||||
|
"1277000000": "jeonnam/jangheung",
|
||||||
|
"1278000000": "jeonnam/gangjin",
|
||||||
|
"1279000000": "jeonnam/haenam",
|
||||||
|
"1280000000": "jeonnam/yeongam",
|
||||||
|
"1281000000": "jeonnam/muan",
|
||||||
|
"1282000000": "jeonnam/hampyeong",
|
||||||
|
"1283000000": "jeonnam/yeonggwang",
|
||||||
|
"1284000000": "jeonnam/jangseong",
|
||||||
|
"1285000000": "jeonnam/wando",
|
||||||
|
"1286000000": "jeonnam/jindo",
|
||||||
|
"1287000000": "jeonnam/sinan",
|
||||||
|
"2611000000": "busan/jung",
|
||||||
|
"2614000000": "busan/seo",
|
||||||
|
"2617000000": "busan/dong",
|
||||||
|
"2620000000": "busan/yeongdo",
|
||||||
|
"2623000000": "busan/busanjin",
|
||||||
|
"2626000000": "busan/dongnae",
|
||||||
|
"2629000000": "busan/nam",
|
||||||
|
"2632000000": "busan/buk",
|
||||||
|
"2635000000": "busan/haeundae",
|
||||||
|
"2638000000": "busan/saha",
|
||||||
|
"2641000000": "busan/geumjeong",
|
||||||
|
"2644000000": "busan/gangseo",
|
||||||
|
"2647000000": "busan/yeonje",
|
||||||
|
"2650000000": "busan/suyeong",
|
||||||
|
"2653000000": "busan/sasang",
|
||||||
|
"2671000000": "busan/gijang",
|
||||||
|
"2711000000": "daegu/jung",
|
||||||
|
"2714000000": "daegu/dong",
|
||||||
|
"2717000000": "daegu/seo",
|
||||||
|
"2720000000": "daegu/nam",
|
||||||
|
"2723000000": "daegu/buk",
|
||||||
|
"2726000000": "daegu/suseong",
|
||||||
|
"2729000000": "daegu/dalseo",
|
||||||
|
"2771000000": "daegu/dalseong",
|
||||||
|
"2772000000": "daegu/gunwi",
|
||||||
|
"2812500000": "incheon/jemulpo",
|
||||||
|
"2815500000": "incheon/yeongjong",
|
||||||
|
"2817700000": "incheon/michuhol",
|
||||||
|
"2818500000": "incheon/yeonsu",
|
||||||
|
"2820000000": "incheon/namdong",
|
||||||
|
"2823700000": "incheon/bupyeong",
|
||||||
|
"2824500000": "incheon/gyeyang",
|
||||||
|
"2827500000": "incheon/seohae",
|
||||||
|
"2829000000": "incheon/geomdan",
|
||||||
|
"2871000000": "incheon/ganghwa",
|
||||||
|
"2872000000": "incheon/ongjin",
|
||||||
|
"3011000000": "daejeon/dong",
|
||||||
|
"3014000000": "daejeon/jung",
|
||||||
|
"3017000000": "daejeon/seo",
|
||||||
|
"3020000000": "daejeon/yuseong",
|
||||||
|
"3023000000": "daejeon/daedeok",
|
||||||
|
"3111000000": "ulsan/jung",
|
||||||
|
"3114000000": "ulsan/nam",
|
||||||
|
"3117000000": "ulsan/dong",
|
||||||
|
"3120000000": "ulsan/buk",
|
||||||
|
"3171000000": "ulsan/ulju",
|
||||||
|
"3611000000": "sejong/sejong",
|
||||||
|
"4111100000": "gyeonggi/suwon/jangan",
|
||||||
|
"4111300000": "gyeonggi/suwon/gwonseon",
|
||||||
|
"4111500000": "gyeonggi/suwon/paldal",
|
||||||
|
"4111700000": "gyeonggi/suwon/yeongtong",
|
||||||
|
"4113100000": "gyeonggi/seongnam/sujeong",
|
||||||
|
"4113300000": "gyeonggi/seongnam/jungwon",
|
||||||
|
"4113500000": "gyeonggi/seongnam/bundang",
|
||||||
|
"4115000000": "gyeonggi/uijeongbu",
|
||||||
|
"4117100000": "gyeonggi/anyang/manan",
|
||||||
|
"4117300000": "gyeonggi/anyang/dongan",
|
||||||
|
"4119200000": "gyeonggi/bucheon/wonmi",
|
||||||
|
"4119400000": "gyeonggi/bucheon/sosa",
|
||||||
|
"4119600000": "gyeonggi/bucheon/ojeong",
|
||||||
|
"4121000000": "gyeonggi/gwangmyeong",
|
||||||
|
"4122000000": "gyeonggi/pyeongtaek",
|
||||||
|
"4125000000": "gyeonggi/dongducheon",
|
||||||
|
"4127100000": "gyeonggi/ansan/sangnok",
|
||||||
|
"4127300000": "gyeonggi/ansan/danwon",
|
||||||
|
"4128100000": "gyeonggi/goyang/deogyang",
|
||||||
|
"4128500000": "gyeonggi/goyang/ilsandong",
|
||||||
|
"4128700000": "gyeonggi/goyang/ilsanseo",
|
||||||
|
"4129000000": "gyeonggi/gwacheon",
|
||||||
|
"4131000000": "gyeonggi/guri",
|
||||||
|
"4136000000": "gyeonggi/namyangju",
|
||||||
|
"4137000000": "gyeonggi/osan",
|
||||||
|
"4139000000": "gyeonggi/siheung",
|
||||||
|
"4141000000": "gyeonggi/gunpo",
|
||||||
|
"4143000000": "gyeonggi/uiwang",
|
||||||
|
"4145000000": "gyeonggi/hanam",
|
||||||
|
"4146100000": "gyeonggi/yongin/cheoin",
|
||||||
|
"4146300000": "gyeonggi/yongin/giheung",
|
||||||
|
"4146500000": "gyeonggi/yongin/suji",
|
||||||
|
"4148000000": "gyeonggi/paju",
|
||||||
|
"4150000000": "gyeonggi/icheon",
|
||||||
|
"4155000000": "gyeonggi/anseong",
|
||||||
|
"4157000000": "gyeonggi/gimpo",
|
||||||
|
"4159100000": "gyeonggi/hwaseong/manse",
|
||||||
|
"4159300000": "gyeonggi/hwaseong/hyohaeng",
|
||||||
|
"4159500000": "gyeonggi/hwaseong/byeongjeom",
|
||||||
|
"4159700000": "gyeonggi/hwaseong/dongtan",
|
||||||
|
"4161000000": "gyeonggi/gwangju",
|
||||||
|
"4163000000": "gyeonggi/yangju",
|
||||||
|
"4165000000": "gyeonggi/pocheon",
|
||||||
|
"4167000000": "gyeonggi/yeoju",
|
||||||
|
"4180000000": "gyeonggi/yeoncheon",
|
||||||
|
"4182000000": "gyeonggi/gapyeong",
|
||||||
|
"4183000000": "gyeonggi/yangpyeong",
|
||||||
|
"4311100000": "chungbuk/cheongju/sangdang",
|
||||||
|
"4311200000": "chungbuk/cheongju/seowon",
|
||||||
|
"4311300000": "chungbuk/cheongju/heungdeok",
|
||||||
|
"4311400000": "chungbuk/cheongju/cheongwon",
|
||||||
|
"4313000000": "chungbuk/chungju",
|
||||||
|
"4315000000": "chungbuk/jecheon",
|
||||||
|
"4372000000": "chungbuk/boeun",
|
||||||
|
"4373000000": "chungbuk/okcheon",
|
||||||
|
"4374000000": "chungbuk/yeongdong",
|
||||||
|
"4374500000": "chungbuk/jeungpyeong",
|
||||||
|
"4375000000": "chungbuk/jincheon",
|
||||||
|
"4376000000": "chungbuk/goesan",
|
||||||
|
"4377000000": "chungbuk/eumseong",
|
||||||
|
"4380000000": "chungbuk/danyang",
|
||||||
|
"4413100000": "chungnam/cheonan/dongnam",
|
||||||
|
"4413300000": "chungnam/cheonan/seobuk",
|
||||||
|
"4415000000": "chungnam/gongju",
|
||||||
|
"4418000000": "chungnam/boryeong",
|
||||||
|
"4420000000": "chungnam/asan",
|
||||||
|
"4421000000": "chungnam/seosan",
|
||||||
|
"4423000000": "chungnam/nonsan",
|
||||||
|
"4425000000": "chungnam/gyeryong",
|
||||||
|
"4427000000": "chungnam/dangjin",
|
||||||
|
"4471000000": "chungnam/geumsan",
|
||||||
|
"4476000000": "chungnam/buyeo",
|
||||||
|
"4477000000": "chungnam/seocheon",
|
||||||
|
"4479000000": "chungnam/cheongyang",
|
||||||
|
"4480000000": "chungnam/hongseong",
|
||||||
|
"4481000000": "chungnam/yesan",
|
||||||
|
"4482500000": "chungnam/taean",
|
||||||
|
"4711100000": "gyeongbuk/pohang/nam",
|
||||||
|
"4711300000": "gyeongbuk/pohang/buk",
|
||||||
|
"4713000000": "gyeongbuk/gyeongju",
|
||||||
|
"4715000000": "gyeongbuk/gimcheon",
|
||||||
|
"4717000000": "gyeongbuk/andong",
|
||||||
|
"4719000000": "gyeongbuk/gumi",
|
||||||
|
"4721000000": "gyeongbuk/yeongju",
|
||||||
|
"4723000000": "gyeongbuk/yeongcheon",
|
||||||
|
"4725000000": "gyeongbuk/sangju",
|
||||||
|
"4728000000": "gyeongbuk/mungyeong",
|
||||||
|
"4729000000": "gyeongbuk/gyeongsan",
|
||||||
|
"4773000000": "gyeongbuk/uiseong",
|
||||||
|
"4775000000": "gyeongbuk/cheongsong",
|
||||||
|
"4776000000": "gyeongbuk/yeongyang",
|
||||||
|
"4777000000": "gyeongbuk/yeongdeok",
|
||||||
|
"4782000000": "gyeongbuk/cheongdo",
|
||||||
|
"4783000000": "gyeongbuk/goryeong",
|
||||||
|
"4784000000": "gyeongbuk/seongju",
|
||||||
|
"4785000000": "gyeongbuk/chilgok",
|
||||||
|
"4790000000": "gyeongbuk/yecheon",
|
||||||
|
"4792000000": "gyeongbuk/bonghwa",
|
||||||
|
"4793000000": "gyeongbuk/uljin",
|
||||||
|
"4794000000": "gyeongbuk/ulleung",
|
||||||
|
"4812100000": "gyeongnam/changwon/uichang",
|
||||||
|
"4812300000": "gyeongnam/changwon/seongsan",
|
||||||
|
"4812500000": "gyeongnam/changwon/masanhappo",
|
||||||
|
"4812700000": "gyeongnam/changwon/masanhoewon",
|
||||||
|
"4812900000": "gyeongnam/changwon/jinhae",
|
||||||
|
"4817000000": "gyeongnam/jinju",
|
||||||
|
"4822000000": "gyeongnam/tongyeong",
|
||||||
|
"4824000000": "gyeongnam/sacheon",
|
||||||
|
"4825000000": "gyeongnam/gimhae",
|
||||||
|
"4827000000": "gyeongnam/miryang",
|
||||||
|
"4831000000": "gyeongnam/geoje",
|
||||||
|
"4833000000": "gyeongnam/yangsan",
|
||||||
|
"4872000000": "gyeongnam/uiryeong",
|
||||||
|
"4873000000": "gyeongnam/haman",
|
||||||
|
"4874000000": "gyeongnam/changnyeong",
|
||||||
|
"4882000000": "gyeongnam/goseong",
|
||||||
|
"4884000000": "gyeongnam/namhae",
|
||||||
|
"4885000000": "gyeongnam/hadong",
|
||||||
|
"4886000000": "gyeongnam/sancheong",
|
||||||
|
"4887000000": "gyeongnam/hamyang",
|
||||||
|
"4888000000": "gyeongnam/geochang",
|
||||||
|
"4889000000": "gyeongnam/hapcheon",
|
||||||
|
"5011000000": "jeju/jeju",
|
||||||
|
"5013000000": "jeju/seogwipo",
|
||||||
|
"5111000000": "gangwon/chuncheon",
|
||||||
|
"5113000000": "gangwon/wonju",
|
||||||
|
"5115000000": "gangwon/gangneung",
|
||||||
|
"5117000000": "gangwon/donghae",
|
||||||
|
"5119000000": "gangwon/taebaek",
|
||||||
|
"5121000000": "gangwon/sokcho",
|
||||||
|
"5123000000": "gangwon/samcheok",
|
||||||
|
"5172000000": "gangwon/hongcheon",
|
||||||
|
"5173000000": "gangwon/hoengseong",
|
||||||
|
"5175000000": "gangwon/yeongwol",
|
||||||
|
"5176000000": "gangwon/pyeongchang",
|
||||||
|
"5177000000": "gangwon/jeongseon",
|
||||||
|
"5178000000": "gangwon/cheorwon",
|
||||||
|
"5179000000": "gangwon/hwacheon",
|
||||||
|
"5180000000": "gangwon/yanggu",
|
||||||
|
"5181000000": "gangwon/inje",
|
||||||
|
"5182000000": "gangwon/goseong",
|
||||||
|
"5183000000": "gangwon/yangyang",
|
||||||
|
"5211100000": "jeonbuk/jeonju/wansan",
|
||||||
|
"5211300000": "jeonbuk/jeonju/deokjin",
|
||||||
|
"5213000000": "jeonbuk/gunsan",
|
||||||
|
"5214000000": "jeonbuk/iksan",
|
||||||
|
"5218000000": "jeonbuk/jeongeup",
|
||||||
|
"5219000000": "jeonbuk/namwon",
|
||||||
|
"5221000000": "jeonbuk/gimje",
|
||||||
|
"5271000000": "jeonbuk/wanju",
|
||||||
|
"5272000000": "jeonbuk/jinan",
|
||||||
|
"5273000000": "jeonbuk/muju",
|
||||||
|
"5274000000": "jeonbuk/jangsu",
|
||||||
|
"5275000000": "jeonbuk/imsil",
|
||||||
|
"5277000000": "jeonbuk/sunchang",
|
||||||
|
"5279000000": "jeonbuk/gochang",
|
||||||
|
"5280000000": "jeonbuk/buan"
|
||||||
|
}
|
||||||
@@ -6,15 +6,22 @@ SLOTS = ("morning", "day", "evening", "night")
|
|||||||
SLOT_LABEL = {"morning": "아침", "day": "낮", "evening": "저녁", "night": "밤"}
|
SLOT_LABEL = {"morning": "아침", "day": "낮", "evening": "저녁", "night": "밤"}
|
||||||
NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
|
NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤
|
||||||
NIGHT_END_HOUR = 5
|
NIGHT_END_HOUR = 5
|
||||||
|
EVENING_EARLIEST_HOUR = 17 # 겨울엔 일몰 2시간 전이 15시대라, 사람들이 아직 낮으로 느끼는 오후 3시가 저녁이 되지 않게
|
||||||
|
|
||||||
|
|
||||||
|
def evening_start(sunset_at: datetime) -> datetime:
|
||||||
|
"""저녁이 시작하는 시각: 일몰 2시간 전, 단 17시보다 이르지 않게."""
|
||||||
|
sunset = sunset_at.astimezone(KST)
|
||||||
|
return max(sunset - timedelta(hours=2), sunset.replace(hour=EVENING_EARLIEST_HOUR, minute=0, second=0, microsecond=0))
|
||||||
|
|
||||||
|
|
||||||
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
def slot_of(now: datetime, sunset_at: datetime) -> str:
|
||||||
"""아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
|
"""아침 05–11 · 낮 11–저녁 시작 · 저녁 일몰 2시간 전(17시보다 이르지 않게)–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다."""
|
||||||
h = now.hour
|
h = now.hour
|
||||||
if NIGHT_END_HOUR <= h < 11:
|
if NIGHT_END_HOUR <= h < 11:
|
||||||
return "morning"
|
return "morning"
|
||||||
if h >= 11 and now < sunset_at + NIGHT_AFTER_SUNSET:
|
if h >= 11 and now < sunset_at + NIGHT_AFTER_SUNSET:
|
||||||
return "day" if now < sunset_at - timedelta(hours=2) else "evening"
|
return "day" if now < evening_start(sunset_at) else "evening"
|
||||||
return "night"
|
return "night"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from dataclasses import dataclass
|
|||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from typing import Literal, Optional
|
from typing import Literal, Optional
|
||||||
|
|
||||||
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS
|
from services.calc.day_slot import EVENING_EARLIEST_HOUR, NIGHT_END_HOUR, SLOTS
|
||||||
|
|
||||||
Rain = Literal["dry", "wet"]
|
Rain = Literal["dry", "wet"]
|
||||||
Air = Literal["good", "normal"]
|
Air = Literal["good", "normal"]
|
||||||
@@ -59,11 +59,12 @@ _TEMP_MIN, _TEMP_MAX = -20, 40
|
|||||||
|
|
||||||
def _slot_of_hour(h: int) -> str:
|
def _slot_of_hour(h: int) -> str:
|
||||||
h %= 24
|
h %= 24
|
||||||
|
evening_from = max(_SUNSET_HOUR - 2, EVENING_EARLIEST_HOUR)
|
||||||
if NIGHT_END_HOUR <= h < 11:
|
if NIGHT_END_HOUR <= h < 11:
|
||||||
return "morning"
|
return "morning"
|
||||||
if 11 <= h < _SUNSET_HOUR - 2:
|
if 11 <= h < evening_from:
|
||||||
return "day"
|
return "day"
|
||||||
if _SUNSET_HOUR - 2 <= h < _SUNSET_HOUR + 1:
|
if evening_from <= h < _SUNSET_HOUR + 1:
|
||||||
return "evening"
|
return "evening"
|
||||||
return "night"
|
return "night"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import re
|
||||||
|
from typing import Optional
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
UNKNOWN_HOST = "(알 수 없음)"
|
||||||
|
OTHER_HOST = "(기타)" # 하루에 셀 호스트 수를 넘긴 새 호스트
|
||||||
|
|
||||||
|
_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?") # 영문·숫자로 시작하고 끝남, 하이픈은 가운데만
|
||||||
|
_MAX_HOST = 253
|
||||||
|
_MAX_LABEL = 63
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_host(raw: str) -> Optional[str]:
|
||||||
|
"""주소나 호스트를 받아 소문자 호스트만 돌려준다. 헤더에 넣을 수 없는 값(포트·IP·와일드카드·공백·너무 긴 이름 등)은 None."""
|
||||||
|
text = raw.strip()
|
||||||
|
if "://" in text:
|
||||||
|
try:
|
||||||
|
text = urlsplit(text).netloc
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
host = text.lower()
|
||||||
|
if len(host) > _MAX_HOST:
|
||||||
|
return None
|
||||||
|
labels = host.split(".")
|
||||||
|
if len(labels) < 2 or labels[-1].isdigit():
|
||||||
|
return None
|
||||||
|
if not all(len(label) <= _MAX_LABEL and _LABEL.fullmatch(label) for label in labels):
|
||||||
|
return None
|
||||||
|
return host
|
||||||
|
|
||||||
|
|
||||||
|
def view_host(referer: Optional[str], own_hosts: frozenset[str]) -> Optional[str]:
|
||||||
|
"""Referer 에서 노출 수를 셀 호스트를 꺼낸다. 날씨각 자신이면 None(세지 않음), 알 수 없으면 UNKNOWN_HOST.
|
||||||
|
own_hosts 는 부르는 쪽이 소문자 호스트[:포트]로 넘긴다고 가정한다."""
|
||||||
|
if not referer:
|
||||||
|
return UNKNOWN_HOST
|
||||||
|
try:
|
||||||
|
parts = urlsplit(referer)
|
||||||
|
except ValueError:
|
||||||
|
return UNKNOWN_HOST
|
||||||
|
if parts.netloc.lower() in own_hosts:
|
||||||
|
return None
|
||||||
|
if parts.scheme in ("http", "https") and parts.hostname:
|
||||||
|
return normalize_host(parts.hostname) or UNKNOWN_HOST
|
||||||
|
return UNKNOWN_HOST
|
||||||
@@ -0,0 +1,407 @@
|
|||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import re
|
||||||
|
import uuid
|
||||||
|
from datetime import date, datetime
|
||||||
|
from html import escape
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
from urllib.parse import urlencode, urlsplit
|
||||||
|
|
||||||
|
from fastapi import Depends
|
||||||
|
from redis.exceptions import RedisError
|
||||||
|
|
||||||
|
from common.cache.lock import redis_lock
|
||||||
|
from common.cache.redis_client import REDIS
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.enums import ErrorType, RainType, Sky
|
||||||
|
from common.logger import LOG
|
||||||
|
from common.utils.kma_time import KST, now_kst
|
||||||
|
from config.settings import settings
|
||||||
|
from crud.region_crud import RegionCRUD
|
||||||
|
from crud.widget_crud import WidgetCRUD
|
||||||
|
from router.v1.feed.protocol import Res_Feed
|
||||||
|
from services.calc.day_slot import SLOT_LABEL
|
||||||
|
from services.embed_referer import OTHER_HOST, UNKNOWN_HOST, view_host
|
||||||
|
from services.feed_service import _SKY_MODE, HERO_BUBBLE_MIN_SCORE, FeedService
|
||||||
|
from services.weather_service import Slot, TodayWeather, WeatherService
|
||||||
|
|
||||||
|
ASSET_VERSION = "11" # 카드 파일(card.css·card.js)을 고치면 올린다
|
||||||
|
KINDS = ("side", "home")
|
||||||
|
BGS = ("sky", "light", "dark")
|
||||||
|
DAILY_HOST_CAP = 500 # 하루에 따로 셀 호스트 수. 넘친 새 호스트는 OTHER_HOST 로 센다
|
||||||
|
CARD_TTL_SEC = 300 # 카드 데이터 저장 시간
|
||||||
|
CARD_BUILD_TIMEOUT_SEC = 8 # 캐시가 빌 때 카드 데이터 만들기(기다림·지역 조회·피드·오늘 날씨) 제한. 넘으면 조용한 화면 (nginx 는 10초에 끊는다)
|
||||||
|
# 같은 지역 카드를 다른 요청이 만드는 중이면 최대 4초 캐시를 기다리고, 그래도 없으면 직접 만든다 (CARD_BUILD_TIMEOUT_SEC 안)
|
||||||
|
_LOCK_WAIT_STEPS, _LOCK_WAIT_SEC = 20, 0.2
|
||||||
|
_VIEW_HOSTS_TTL_SEC = 2 * 24 * 3600
|
||||||
|
# 노출 수: 카드를 줄 때 Redis 해시 widget:views:<한국 날짜>(필드 '호스트\t모양')에 더하고, 관리자 API 가 표로 옮긴다(flush_views)
|
||||||
|
_VIEWS_PREFIX = "widget:views:"
|
||||||
|
_FLUSH_PREFIX = "widget:views-flush:" # 옮기는 동안 떼어 둔 임시 키: widget:views-flush:<날짜>:<무작위>
|
||||||
|
_REGION_CODE = re.compile(r"[0-9]{10}")
|
||||||
|
# 지역 코드 → 지역 페이지 주소 이름 (scripts/gen_region_pages.py 가 만든다)
|
||||||
|
_PATHS: dict[str, str] = json.loads((Path(__file__).resolve().parent.parent / "seed" / "region_path.json").read_text(encoding="utf-8"))
|
||||||
|
_widgets = WidgetCRUD()
|
||||||
|
|
||||||
|
# 날씨각 umami(frontend/index.html 과 같은 사이트 ID): 카드 조회를 날씨각 통계 안의 /widget 페이지로 보낸다.
|
||||||
|
# 쿠키를 쓰지 않는다. 자동 수집을 끄고 주소를 바꿔 보내, 붙인 사이트는 umami '유입 경로'에 남는다(iframe 의 referrer).
|
||||||
|
# 스크립트는 날씨각에 복사해 둔 것(frontend/public/embed/umami.js)을 쓰고 기록만 umami 서버(UMAMI_HOST)로 보낸다 — 외부 스크립트를 직접 실행하지 않게
|
||||||
|
UMAMI_SRC = "/embed/umami.js"
|
||||||
|
UMAMI_HOST = "https://analytics.webforai.kr"
|
||||||
|
UMAMI_WEBSITE_ID = "b2244cf7-9b43-49c0-b1c0-acfaaab95ddb"
|
||||||
|
UMAMI_PATH = "/widget" # 2026-11-26 까지는 /widget-card. 그날 전의 umami /widget 은 사용 방법 페이지(지금 /widget-guide) 방문이다
|
||||||
|
_KIND_LABEL = {"side": "기본형", "home": "상세형"}
|
||||||
|
|
||||||
|
_FONT = '-apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", sans-serif' # card.css --font 의 시스템 글꼴 부분
|
||||||
|
# 조용한 화면 바탕: 카드(card.css)의 배경별 낮 하늘과 같은 색. 링크는 카드 is-failed 의 흰 알약과 같은 모양
|
||||||
|
# (frontend/public/embed/quiet.html 은 nginx 가 백엔드 없이 주는 같은 모양의 sky 판이다)
|
||||||
|
_QUIET_BG = {
|
||||||
|
"sky": "linear-gradient(#9fd3ff,#cfe9ff 55%,#f1f8ff)",
|
||||||
|
"light": "linear-gradient(#e3f1ff,#f0f8ff 55%,#fbfdff);box-shadow:inset 0 0 0 1px rgba(40,48,74,.08)",
|
||||||
|
"dark": "linear-gradient(#1c3252,#20304c 55%,#1c2540)",
|
||||||
|
}
|
||||||
|
_QUIET_STYLE = (
|
||||||
|
"html,body{margin:0;height:100%}body{display:flex;align-items:center;justify-content:center;box-sizing:border-box;padding:16px}"
|
||||||
|
f"a{{display:inline-flex;align-items:center;min-height:44px;padding:0 18px;border-radius:999px;background:#fff;color:#28304a;"
|
||||||
|
f"font:700 14px/1.3 {_FONT};text-decoration:none;white-space:nowrap;box-shadow:0 4px 12px rgba(40,48,74,.12)}}"
|
||||||
|
"a:hover{color:#1d4f96;text-decoration:underline}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def region_path(code: str) -> Optional[str]:
|
||||||
|
return _PATHS.get(code)
|
||||||
|
|
||||||
|
|
||||||
|
def card_link(path: Optional[str], campaign: str) -> str:
|
||||||
|
"""카드에서 날씨각으로 가는 링크. campaign 은 부른 사이트 호스트·unknown·preview 중 하나."""
|
||||||
|
query = urlencode({"utm_source": "widget", "utm_medium": "embed", "utm_campaign": campaign})
|
||||||
|
return f"/today/{path}?{query}" if path else f"/?{query}"
|
||||||
|
|
||||||
|
|
||||||
|
def _slot(s: Slot) -> dict:
|
||||||
|
"""/v1/weather/today 의 칸과 같은 숫자·같은 시각 표기."""
|
||||||
|
row = s.row
|
||||||
|
return {
|
||||||
|
"at": s.at.astimezone(KST).isoformat(),
|
||||||
|
"temp_c": float(row.temp_c) if row is not None else None,
|
||||||
|
"sky": Sky(row.sky).value if row is not None else None,
|
||||||
|
"rain_type": RainType(row.rain_type).value if row is not None else None,
|
||||||
|
"icon": s.icon,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _picks(feed: Res_Feed, sky_mode: str) -> dict:
|
||||||
|
"""카드 칸(morning·day·sunset·night)마다 그 시간대 한마디. 앱 TodayPage.tsx 의 atSlot·bubble 과 같은 규칙:
|
||||||
|
그 구간 점수·순위가 다 있는 각 중 순위가 가장 앞선 것(같으면 피드 순서)의 구간 점수가 기준 이상이면 그 각을 권한다.
|
||||||
|
머리말은 지금 칸(hero.sky_mode)이면 '지금', 아니면 '오늘 아침' 등. 고를 각이 없는 칸은 뺀다.
|
||||||
|
각 설명(summary)은 넣지 않는다: 지금 시각 기준 글이라 카드는 다른 칸을 고르면 요약을 감춘다."""
|
||||||
|
out = {}
|
||||||
|
for slot, cell in _SKY_MODE.items():
|
||||||
|
on = [g for g in feed.stories if slot in g.slot_ranks and slot in g.slots]
|
||||||
|
if not on:
|
||||||
|
continue
|
||||||
|
top = min(on, key=lambda g: g.slot_ranks[slot]) # min 은 같은 값이면 앞의 것을 고른다
|
||||||
|
when = "지금" if cell == sky_mode else f"오늘 {SLOT_LABEL[slot]}"
|
||||||
|
bubble = f"{when}은 {top.name}!" if top.slots[slot] >= HERO_BUBBLE_MIN_SCORE else f"{when}은 쉬어 가요"
|
||||||
|
out[cell] = {"bubble": bubble}
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def card_data(feed: Res_Feed, today: TodayWeather, name: str, now: datetime) -> Optional[dict]:
|
||||||
|
"""카드가 그릴 값 (링크는 부른 사이트마다 달라 빼고 저장한다). 오늘 값이 아니거나 그릴 것이 없으면 None."""
|
||||||
|
h = feed.hero
|
||||||
|
if h is None or h.weather_score is None:
|
||||||
|
return None
|
||||||
|
day = now.astimezone(KST).date()
|
||||||
|
if h.now_at.astimezone(KST).date() != day or today.day != day:
|
||||||
|
return None
|
||||||
|
slots = [_slot(s) for s in today.slots]
|
||||||
|
if all(s["temp_c"] is None for s in slots):
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"name": name,
|
||||||
|
"hero": {
|
||||||
|
"now_at": h.now_at.astimezone(KST).isoformat(), "sky_mode": h.sky_mode, "temp_c": h.temp_c, "weather_score": h.weather_score,
|
||||||
|
# 서버 구간 이름 → 카드 칸 이름 (evening → sunset)
|
||||||
|
"weather_slots": {_SKY_MODE[k]: v for k, v in h.weather_slots.items() if k in _SKY_MODE},
|
||||||
|
"bubble": h.bubble, "top1": {"summary": h.top1.summary} if h.top1 else None,
|
||||||
|
"status": [{"label": s.label, "value": s.value, "tone": s.tone} for s in h.status],
|
||||||
|
"moon_name": h.moon_name, "moon_pct": h.moon_pct,
|
||||||
|
},
|
||||||
|
"picks": _picks(feed, h.sky_mode),
|
||||||
|
"today": {"day": today.day.isoformat(), "slots": slots},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _page(title: str, head: str, body: str, body_class: str = "") -> str:
|
||||||
|
body_tag = f'<body class="{escape(body_class, quote=True)}">' if body_class else "<body>"
|
||||||
|
return (
|
||||||
|
'<!doctype html>\n<html lang="ko">\n<head>\n<meta charset="utf-8">\n'
|
||||||
|
'<meta name="viewport" content="width=device-width, initial-scale=1">\n<meta name="robots" content="noindex">\n'
|
||||||
|
f"<title>{escape(title)}</title>\n{head}\n</head>\n{body_tag}\n{body}\n</body>\n</html>\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _umami(kind: str) -> str:
|
||||||
|
"""umami 로 카드 조회 한 번(/widget, 제목에 모양). 스크립트가 늦거나 막혀도 카드 그리기와는 상관없다."""
|
||||||
|
title = json.dumps(f"날씨 위젯 · {_KIND_LABEL[kind]}", ensure_ascii=False)
|
||||||
|
send = f"umami.track(function(p){{p.url={json.dumps(UMAMI_PATH)};p.title={title};return p}})"
|
||||||
|
return (
|
||||||
|
f'<script defer src="{UMAMI_SRC}" data-host-url="{UMAMI_HOST}" data-website-id="{UMAMI_WEBSITE_ID}" data-domains="weather.o2o.kr,www.weather.o2o.kr" '
|
||||||
|
f'data-auto-track="false" onload="{escape(send, quote=True)}"></script>'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def render_card(kind: str, bg: str, data: dict, link: str, track: bool = False) -> str:
|
||||||
|
"""카드 화면. 상자는 군산각 카드(.wx)와 같은 구조이고, 본문 칸(data-wx-b)은 card.js 가 #wx-data 를 읽어 그린다.
|
||||||
|
그리기 전에는 토끼 로딩 화면(.wx-load)이 보이고, 못 그리면(is-failed, 또는 8초 안에 스크립트가 안 돌면) 날씨각 링크(.wx-go)가 보인다.
|
||||||
|
track 이면 umami 로 조회를 보낸다(날씨각 자신의 미리보기는 빼려고 부르는 쪽이 정한다)."""
|
||||||
|
payload = json.dumps({**data, "link": link}, ensure_ascii=False).replace("<", "\\u003c") # 값 안의 </script> 가 태그를 닫지 못하게
|
||||||
|
# color-scheme 은 light 로 고정: light dark 면 색 선언이 없는 사이트(대부분)에서 방문자 기기가 다크 모드일 때 모서리 밖이 검게 칠해진다.
|
||||||
|
# color-scheme: dark 를 선언한 사이트에서 생기는 불투명 바탕은 붙이는 코드의 iframe border-radius 가 잘라 낸다
|
||||||
|
head = f'<meta name="color-scheme" content="light">\n<link rel="stylesheet" href="/embed/card.css?v={ASSET_VERSION}">'
|
||||||
|
name = escape(data["name"])
|
||||||
|
body = (
|
||||||
|
f'<div class="wx wx-{escape(kind, quote=True)} wx-bg-{escape(bg, quote=True)}">\n'
|
||||||
|
f'<p class="wx-h"><span class="wx-t">{name} 날씨</span><span class="wx-dt" data-wx-dt></span>'
|
||||||
|
f'<a class="wx-go" href="{escape(link, quote=True)}" target="_blank" rel="noopener"><span data-wx-gl>날씨각에서 날씨 보기 ›</span></a></p>\n'
|
||||||
|
'<div class="wx-load" role="status"><img src="/icons/rabbit.webp" alt="" width="88" height="88"><span>날씨 불러오는 중…</span></div>\n'
|
||||||
|
'<div class="wx-b" data-wx-b></div>\n'
|
||||||
|
"</div>\n"
|
||||||
|
f'<noscript><a class="wx-ns" href="{escape(link, quote=True)}" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a></noscript>\n'
|
||||||
|
f'<script type="application/json" id="wx-data">{payload}</script>\n'
|
||||||
|
f'<script src="/embed/card.js?v={ASSET_VERSION}" defer></script>'
|
||||||
|
)
|
||||||
|
if track:
|
||||||
|
body += "\n" + _umami(kind)
|
||||||
|
return _page(f"{data['name']} 날씨 - 날씨각", head, body)
|
||||||
|
|
||||||
|
|
||||||
|
def render_quiet(link: str, bg: str) -> str:
|
||||||
|
"""카드를 못 그릴 때 보이는 조용한 화면: 고른 배경(틀린 값이면 sky) 위에 날씨각 링크 하나.
|
||||||
|
바탕은 카드처럼 모서리 28px. body 에 바로 칠하면 화면 전체(캔버스)로 번져 둥글게 잘리지 않아 body::before 에 칠한다."""
|
||||||
|
bg = bg if bg in BGS else "sky"
|
||||||
|
head = (
|
||||||
|
f'<meta name="color-scheme" content="light">\n<style>{_QUIET_STYLE}'
|
||||||
|
f'.wx-q-{bg}::before{{content:"";position:fixed;inset:0;z-index:-1;border-radius:28px;background:{_QUIET_BG[bg]}}}</style>'
|
||||||
|
)
|
||||||
|
body = f'<a href="{escape(link, quote=True)}" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a>'
|
||||||
|
return _page("날씨각", head, body, f"wx-q-{bg}")
|
||||||
|
|
||||||
|
|
||||||
|
async def count_host(host: str) -> str:
|
||||||
|
"""노출 수를 셀 호스트. 하루에 따로 세는 호스트는 DAILY_HOST_CAP 개까지이고, 넘친 새 호스트는 OTHER_HOST 로 센다."""
|
||||||
|
if host == UNKNOWN_HOST:
|
||||||
|
return host
|
||||||
|
key = f"widget:view-hosts:{now_kst().date().isoformat()}"
|
||||||
|
try:
|
||||||
|
if await REDIS.conn.sismember(key, host):
|
||||||
|
return host
|
||||||
|
if await REDIS.conn.scard(key) < DAILY_HOST_CAP:
|
||||||
|
await REDIS.conn.sadd(key, host)
|
||||||
|
await REDIS.conn.expire(key, _VIEW_HOSTS_TTL_SEC)
|
||||||
|
return host
|
||||||
|
except RedisError as e:
|
||||||
|
LOG.error(f"[embed] view hosts: {e}")
|
||||||
|
return OTHER_HOST
|
||||||
|
|
||||||
|
|
||||||
|
def _card_key(region_code: str) -> str:
|
||||||
|
# 카드 파일이 바뀌면(ASSET_VERSION) 예전 모양에 맞춘 저장 데이터를 쓰지 않는다
|
||||||
|
return f"widget:card:v{ASSET_VERSION}:{region_code}"
|
||||||
|
|
||||||
|
|
||||||
|
async def _cached_card(region_code: str, now: datetime) -> Optional[dict]:
|
||||||
|
"""저장해 둔 카드 데이터. 없거나 오늘(한국 날짜) 값이 아니거나 깨졌으면 None."""
|
||||||
|
try:
|
||||||
|
cached = await REDIS.conn.get(_card_key(region_code))
|
||||||
|
except RedisError as e:
|
||||||
|
LOG.error(f"[embed] card cache get: {e}")
|
||||||
|
return None
|
||||||
|
if cached is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
data = json.loads(cached)
|
||||||
|
day = data["today"]["day"]
|
||||||
|
except (ValueError, TypeError, KeyError) as e: # ValueError: 깨진 JSON
|
||||||
|
LOG.error(f"[embed] card cache broken {region_code}: {e}")
|
||||||
|
return None
|
||||||
|
return data if day == now.astimezone(KST).date().isoformat() else None
|
||||||
|
|
||||||
|
|
||||||
|
async def _wait_cached(region_code: str, now: datetime, lock: str) -> Optional[dict]:
|
||||||
|
"""다른 요청이 잠금을 잡고 카드를 만드는 동안 캐시를 본다. 그 요청이 못 만들고 잠금을 풀었거나 기다림이 끝나면 None."""
|
||||||
|
for _ in range(_LOCK_WAIT_STEPS):
|
||||||
|
await asyncio.sleep(_LOCK_WAIT_SEC)
|
||||||
|
cached = await _cached_card(region_code, now)
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
|
try:
|
||||||
|
held = await REDIS.conn.exists(lock)
|
||||||
|
except RedisError as e:
|
||||||
|
LOG.error(f"[embed] card lock wait: {e}")
|
||||||
|
return None
|
||||||
|
if not held:
|
||||||
|
# 만든 쪽이 저장하고 잠금을 푼 것이 캐시를 읽은 뒤일 수 있어 한 번 더 본다
|
||||||
|
return await _cached_card(region_code, now)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _views_key(day: date) -> str:
|
||||||
|
return f"{_VIEWS_PREFIX}{day.isoformat()}"
|
||||||
|
|
||||||
|
|
||||||
|
async def flush_views() -> None:
|
||||||
|
"""Redis 에 쌓인 노출 수를 widget_view_daily 로 옮긴다 (관리자 API 가 표를 읽기 전에 부른다).
|
||||||
|
날짜 키마다 RENAME 으로 임시 키에 떼어 내 옮기므로, 그동안 오는 노출은 원래 키에 새로 쌓인다. 이전 요청이 남긴 임시 키도
|
||||||
|
함께 옮긴다. 두 요청이 같은 임시 키를 두 번 더하지 않게 잠금을 잡은 요청만 옮긴다. 실패는 기록만 한다 (표는 그대로 읽힌다)."""
|
||||||
|
async with redis_lock("lock:widget:views-flush", ttl_sec=60) as mine:
|
||||||
|
if not mine:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
for key in [k async for k in REDIS.conn.scan_iter(match=f"{_VIEWS_PREFIX}*")]:
|
||||||
|
await REDIS.conn.rename(key, f"{_FLUSH_PREFIX}{key.removeprefix(_VIEWS_PREFIX)}:{uuid.uuid4().hex}")
|
||||||
|
temps = [k async for k in REDIS.conn.scan_iter(match=f"{_FLUSH_PREFIX}*")]
|
||||||
|
except RedisError as e:
|
||||||
|
LOG.error(f"[embed] views flush: {e}")
|
||||||
|
return
|
||||||
|
for temp in temps:
|
||||||
|
await _flush_one(temp)
|
||||||
|
|
||||||
|
|
||||||
|
async def _flush_one(temp: str) -> None:
|
||||||
|
"""임시 키 하나를 표에 더하고 지운다. 표에 못 쓰면 수치를 잃지 않게 원래 날짜 키에 되돌려 더하고 지운다."""
|
||||||
|
try:
|
||||||
|
day = date.fromisoformat(temp.removeprefix(_FLUSH_PREFIX).split(":", 1)[0])
|
||||||
|
except ValueError:
|
||||||
|
LOG.error(f"[embed] views flush: bad key {temp}")
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
raw = await REDIS.conn.hgetall(temp)
|
||||||
|
except RedisError as e:
|
||||||
|
LOG.error(f"[embed] views flush {temp}: {e}")
|
||||||
|
return
|
||||||
|
counts: dict[tuple[str, str], int] = {}
|
||||||
|
for field, n in raw.items():
|
||||||
|
host, _, kind = field.rpartition("\t")
|
||||||
|
views = int(n) if n.isdigit() else 0
|
||||||
|
if not host or kind not in KINDS or views <= 0:
|
||||||
|
LOG.error(f"[embed] views flush {temp}: bad field {field!r}={n!r}")
|
||||||
|
continue
|
||||||
|
counts[(host, kind)] = views
|
||||||
|
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: _widgets.add_views(s, day, counts))
|
||||||
|
try:
|
||||||
|
if err is ErrorType.SUCCESS:
|
||||||
|
await REDIS.conn.delete(temp)
|
||||||
|
return
|
||||||
|
LOG.error(f"[embed] views flush {temp}: {err}")
|
||||||
|
# 되돌려 더하기와 임시 키 지우기를 한 번에 (반만 된 채 남아 다음에 두 번 더하지 않게)
|
||||||
|
async with REDIS.conn.pipeline(transaction=True) as p:
|
||||||
|
for (host, kind), views in counts.items():
|
||||||
|
p.hincrby(_views_key(day), f"{host}\t{kind}", views)
|
||||||
|
p.delete(temp)
|
||||||
|
await p.execute()
|
||||||
|
except RedisError as e:
|
||||||
|
LOG.error(f"[embed] views flush {temp}: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
def _campaign(viewer: Optional[str]) -> str:
|
||||||
|
if viewer is None:
|
||||||
|
return "preview"
|
||||||
|
return "unknown" if viewer == UNKNOWN_HOST else viewer
|
||||||
|
|
||||||
|
|
||||||
|
class EmbedService:
|
||||||
|
def __init__(
|
||||||
|
self, feed: FeedService = Depends(FeedService), weather: WeatherService = Depends(WeatherService), regions: RegionCRUD = Depends(RegionCRUD)
|
||||||
|
) -> None:
|
||||||
|
self.feed, self.weather, self.regions = feed, weather, regions
|
||||||
|
|
||||||
|
async def card(self, region_code: str, kind: str, bg: str, referer: Optional[str], host: str) -> tuple[int, str]:
|
||||||
|
"""(상태 코드, HTML)"""
|
||||||
|
if not _REGION_CODE.fullmatch(region_code) or kind not in KINDS or bg not in BGS:
|
||||||
|
return 404, render_quiet(card_link(None, "unknown"), bg)
|
||||||
|
# 아래에서 예상 못 한 예외가 나도 iframe 에 오류 화면 대신 조용한 화면을 돌려준다 (기록은 남긴다)
|
||||||
|
link = card_link(region_path(region_code), "unknown")
|
||||||
|
try:
|
||||||
|
own = frozenset(h for h in (host.lower(), urlsplit(settings.public_base_url).netloc.lower()) if h)
|
||||||
|
viewer = view_host(referer, own)
|
||||||
|
link = card_link(region_path(region_code), _campaign(viewer))
|
||||||
|
|
||||||
|
# 캐시가 있으면 DB 를 읽지 않는다 (캐시는 있는 지역만 저장되므로 캐시가 있으면 지역도 있다)
|
||||||
|
now = now_kst()
|
||||||
|
data = await _cached_card(region_code, now)
|
||||||
|
if data is None:
|
||||||
|
try:
|
||||||
|
# 시간을 넘기면 wait_for 가 만들던 작업(gather 와 그 안의 두 작업)을 취소하고 끝날 때까지 기다린 뒤 올린다
|
||||||
|
# (남아 떠도는 작업 없음, 잠금은 redis_lock 의 finally 가 푼다)
|
||||||
|
status, data = await asyncio.wait_for(self._fresh(region_code, now), CARD_BUILD_TIMEOUT_SEC)
|
||||||
|
except TimeoutError:
|
||||||
|
LOG.warning(f"[embed] card build over {CARD_BUILD_TIMEOUT_SEC}s {region_code}")
|
||||||
|
status, data = 200, None
|
||||||
|
if data is None:
|
||||||
|
return status, render_quiet(link, bg)
|
||||||
|
|
||||||
|
html = render_card(kind, bg, data, link, track=viewer is not None)
|
||||||
|
if viewer is not None:
|
||||||
|
try:
|
||||||
|
await self._count(viewer, kind)
|
||||||
|
except Exception: # 집계가 어떤 이유로 실패해도 이미 만든 카드는 돌려준다
|
||||||
|
LOG.exception(f"[embed] view count {viewer} {kind}")
|
||||||
|
return 200, html
|
||||||
|
except Exception:
|
||||||
|
LOG.exception(f"[embed] card {region_code} {kind} {bg}")
|
||||||
|
return 200, render_quiet(link, bg)
|
||||||
|
|
||||||
|
async def _fresh(self, region_code: str, now: datetime) -> tuple[int, Optional[dict]]:
|
||||||
|
"""캐시가 빈 지역의 (상태 코드, 카드 데이터). 지역마다 잠금을 잡은 요청 하나만 만들고, 못 잡은 요청은 잠깐 그 결과(캐시)를
|
||||||
|
기다렸다가 그래도 없으면 직접 만든다. Redis 오류면 redis_lock 이 잡은 것으로 쳐(기록을 남기고) 잠금 없이 만든다."""
|
||||||
|
lock = f"lock:widget:card:{region_code}"
|
||||||
|
async with redis_lock(lock, ttl_sec=math.ceil(CARD_BUILD_TIMEOUT_SEC) + 2) as mine:
|
||||||
|
if mine:
|
||||||
|
# 캐시를 읽은 뒤 잠금을 잡기 전에 다른 요청이 다 만들고 풀었을 수 있다
|
||||||
|
cached = await _cached_card(region_code, now)
|
||||||
|
return (200, cached) if cached is not None else await self._make(region_code, now)
|
||||||
|
cached = await _wait_cached(region_code, now, lock)
|
||||||
|
return (200, cached) if cached is not None else await self._make(region_code, now)
|
||||||
|
|
||||||
|
async def _make(self, region_code: str, now: datetime) -> tuple[int, Optional[dict]]:
|
||||||
|
"""지역을 찾아 카드 데이터를 만들고 CARD_TTL_SEC 초 저장한다. 없는 지역이면 (404, None), 못 만들면 (200, None)."""
|
||||||
|
err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code))
|
||||||
|
if err is not ErrorType.SUCCESS:
|
||||||
|
LOG.error(f"[embed] region {region_code}: {err}")
|
||||||
|
return 200, None
|
||||||
|
if region is None:
|
||||||
|
return 404, None
|
||||||
|
data = await self._build(region_code, region.short_name, now)
|
||||||
|
if data is None:
|
||||||
|
return 200, None
|
||||||
|
try:
|
||||||
|
await REDIS.conn.set(_card_key(region_code), json.dumps(data, ensure_ascii=False), ex=CARD_TTL_SEC)
|
||||||
|
except RedisError as e:
|
||||||
|
LOG.error(f"[embed] card cache set: {e}")
|
||||||
|
return 200, data
|
||||||
|
|
||||||
|
async def _build(self, region_code: str, name: str, now: datetime) -> Optional[dict]:
|
||||||
|
"""피드·오늘 날씨로 카드 데이터를 만든다. 그릴 것이 없으면 None."""
|
||||||
|
results = await asyncio.gather(self.feed.feed(region_code), self.weather.today(region_code), return_exceptions=True)
|
||||||
|
for res in results: # 한쪽이 예외여도 다른 쪽이 끝난 뒤에 올린다 (끝나지 않은 작업이 남아 떠돌지 않게)
|
||||||
|
if isinstance(res, BaseException):
|
||||||
|
raise res
|
||||||
|
(err_f, feed), (err_t, today) = results
|
||||||
|
if err_f is not ErrorType.SUCCESS or feed is None or err_t is not ErrorType.SUCCESS or today is None:
|
||||||
|
LOG.error(f"[embed] no card {region_code}: feed {err_f.name}, today {err_t.name}")
|
||||||
|
return None
|
||||||
|
data = card_data(feed, today, name, now)
|
||||||
|
if data is None: # 자정 무렵 피드·예보가 아직 어제 값일 때 생길 수 있다
|
||||||
|
LOG.warning(f"[embed] no card data {region_code}")
|
||||||
|
return data
|
||||||
|
|
||||||
|
async def _count(self, viewer: str, kind: str) -> None:
|
||||||
|
"""노출 수 1 올리기: DB 가 아니라 Redis 해시에 더한다 (표로는 관리자 API 가 flush_views 로 옮긴다). 실패해도 카드는 돌려준다."""
|
||||||
|
host = await count_host(viewer)
|
||||||
|
try:
|
||||||
|
await REDIS.conn.hincrby(_views_key(now_kst().date()), f"{host}\t{kind}", 1)
|
||||||
|
except RedisError as e:
|
||||||
|
LOG.error(f"[embed] view count {host} {kind}: {e}")
|
||||||
@@ -28,7 +28,7 @@ from router.v1.index.protocol import TrendPoint
|
|||||||
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
|
||||||
from services.air_service import pm10_grade, pm25_grade
|
from services.air_service import pm10_grade, pm25_grade
|
||||||
from services.bot_comment import fill_bot_comments
|
from services.bot_comment import fill_bot_comments
|
||||||
from services.calc.day_slot import NIGHT_AFTER_SUNSET, slot_of
|
from services.calc.day_slot import NIGHT_AFTER_SUNSET, evening_start, slot_of
|
||||||
from services.calc.index_calc import rank_score
|
from services.calc.index_calc import rank_score
|
||||||
from services.calc.moon import MoonNight, nearest, night, view_line
|
from services.calc.moon import MoonNight, nearest, night, view_line
|
||||||
from services.calc.sky_score import GRADE_LABEL, sky_title
|
from services.calc.sky_score import GRADE_LABEL, sky_title
|
||||||
@@ -177,7 +177,7 @@ def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
|
|||||||
day = now.date()
|
day = now.date()
|
||||||
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
|
||||||
sunset = sunset_at.astimezone(KST)
|
sunset = sunset_at.astimezone(KST)
|
||||||
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + NIGHT_AFTER_SUNSET,
|
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), evening_start(sunset), sunset, sunset + NIGHT_AFTER_SUNSET,
|
||||||
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now), latest_ultra_base(now) + timedelta(hours=1) + ULTRA_DELAY,
|
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now), latest_ultra_base(now) + timedelta(hours=1) + ULTRA_DELAY,
|
||||||
latest_ncst_base(now) + timedelta(hours=1) + NCST_DELAY, now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)]
|
latest_ncst_base(now) + timedelta(hours=1) + NCST_DELAY, now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)]
|
||||||
air = now.replace(minute=20, second=0, microsecond=0)
|
air = now.replace(minute=20, second=0, microsecond=0)
|
||||||
@@ -284,6 +284,14 @@ def _hero_tomorrow(day: date, board: IndexBoard) -> HeroTomorrow:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
HERO_BUBBLE_MIN_SCORE = 65 # 화면의 TodayPage.tsx BUBBLE_MIN_SCORE 와 같은 값
|
||||||
|
|
||||||
|
|
||||||
|
def hero_bubble(name: str, score: int) -> str:
|
||||||
|
"""히어로 말풍선: 1위 각의 화면 점수(중요도 배율을 곱한 점수)가 기준 이상이면 그 각을 권하고, 아니면 쉬어 가자고 한다."""
|
||||||
|
return f"지금은 {name}!" if score >= HERO_BUBBLE_MIN_SCORE else "지금은 쉬어 가요"
|
||||||
|
|
||||||
|
|
||||||
def _top(i: IndexItem) -> TopIndex:
|
def _top(i: IndexItem) -> TopIndex:
|
||||||
d = i.definition
|
d = i.definition
|
||||||
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active,
|
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary, active=i.active,
|
||||||
@@ -496,7 +504,7 @@ class FeedService:
|
|||||||
top = board.ranked[0] if board and board.ranked else None
|
top = board.ranked[0] if board and board.ranked else None
|
||||||
bubble = None
|
bubble = None
|
||||||
if top is not None:
|
if top is not None:
|
||||||
bubble = f"지금은 {top.definition.name}!" if top.score.score >= 70 else "지금은 쉬어 가요"
|
bubble = hero_bubble(top.definition.name, top.score.score)
|
||||||
x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None)
|
x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None)
|
||||||
return Hero(
|
return Hero(
|
||||||
now_at=now, sky_mode=_SKY_MODE[slot],
|
now_at=now, sky_mode=_SKY_MODE[slot],
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ def anyio_backend():
|
|||||||
_VOLATILE = (
|
_VOLATILE = (
|
||||||
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
||||||
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "comment_report", "user_block", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
|
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "comment_report", "user_block", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
|
||||||
|
"widget_view_daily",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from types import SimpleNamespace
|
|||||||
from common.database.model.models import WeatherHourly
|
from common.database.model.models import WeatherHourly
|
||||||
from common.enums import RainType, Sky
|
from common.enums import RainType, Sky
|
||||||
from common.utils.kma_time import KST, kst_midnight
|
from common.utils.kma_time import KST, kst_midnight
|
||||||
from services.calc.day_slot import slot_hours
|
from services.calc.day_slot import slot_hours, slot_of
|
||||||
from services.calc.index_calc import Context
|
from services.calc.index_calc import Context
|
||||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, _shown_parts, current_slot, slot_results
|
from services.index_service import EARLY, WEATHER_SCORE_DEF, _shown_parts, current_slot, slot_results
|
||||||
from services.weather_service import RainHour, with_ultra_rain
|
from services.weather_service import RainHour, with_ultra_rain
|
||||||
@@ -36,16 +36,34 @@ def _defn(windows):
|
|||||||
|
|
||||||
|
|
||||||
def test_slot_hours_split_by_sunset():
|
def test_slot_hours_split_by_sunset():
|
||||||
|
"""일몰 18:00: 일몰 2시간 전은 16시지만 저녁은 17시부터, 밤은 일몰 1시간 뒤 19시부터."""
|
||||||
hours = slot_hours(DAY, SUNSET)
|
hours = slot_hours(DAY, SUNSET)
|
||||||
assert hours["morning"] == set(range(5, 11))
|
assert hours["morning"] == set(range(5, 11))
|
||||||
assert hours["day"] == set(range(11, 16))
|
assert hours["day"] == set(range(11, 17))
|
||||||
assert hours["evening"] == {16, 17, 18}
|
assert hours["evening"] == {17, 18}
|
||||||
assert hours["night"] == set(range(19, 29))
|
assert hours["night"] == set(range(19, 29))
|
||||||
|
|
||||||
|
|
||||||
|
def test_evening_starts_no_earlier_than_17():
|
||||||
|
"""겨울(일몰 17:14)엔 일몰 2시간 전이 15시대라 오후 3시가 저녁이던 것: 저녁은 17시보다 이르게 시작하지 않는다. 밤(일몰 1시간 뒤~)은 그대로."""
|
||||||
|
winter = datetime(2026, 12, 21, 17, 14, tzinfo=KST)
|
||||||
|
at = lambda h, m=0: datetime(2026, 12, 21, h, m, tzinfo=KST) # noqa: E731
|
||||||
|
assert [slot_of(at(h, m), winter) for h, m in ((16, 59), (17, 0), (18, 13), (18, 14))] == ["day", "evening", "evening", "night"]
|
||||||
|
hours = slot_hours(date(2026, 12, 21), winter)
|
||||||
|
assert hours["day"] == set(range(11, 17))
|
||||||
|
assert hours["evening"] == {17}
|
||||||
|
|
||||||
|
|
||||||
|
def test_evening_follows_sunset_when_it_sets_late():
|
||||||
|
"""일몰이 19시 넘으면 지금처럼 일몰 2시간 전부터 저녁."""
|
||||||
|
summer = datetime(2026, 6, 21, 19, 57, tzinfo=KST)
|
||||||
|
assert slot_of(datetime(2026, 6, 21, 17, 56, tzinfo=KST), summer) == "day"
|
||||||
|
assert slot_of(datetime(2026, 6, 21, 17, 57, tzinfo=KST), summer) == "evening"
|
||||||
|
|
||||||
|
|
||||||
def test_current_slot_before_5_is_previous_night():
|
def test_current_slot_before_5_is_previous_night():
|
||||||
assert current_slot(datetime(2026, 10, 8, 2, 0, tzinfo=KST), SUNSET) == EARLY
|
assert current_slot(datetime(2026, 10, 8, 2, 0, tzinfo=KST), SUNSET) == EARLY
|
||||||
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
|
assert current_slot(datetime(2026, 10, 8, 17, 30, tzinfo=KST), SUNSET) == "evening"
|
||||||
|
|
||||||
|
|
||||||
def test_gak_scores_every_slot_and_time_match_is_binary():
|
def test_gak_scores_every_slot_and_time_match_is_binary():
|
||||||
@@ -213,10 +231,10 @@ def test_umbrella_now_follows_the_slot_the_screen_shows_even_at_a_slot_boundary(
|
|||||||
|
|
||||||
|
|
||||||
def test_umbrella_other_slots_have_no_raining_now_bonus():
|
def test_umbrella_other_slots_have_no_raining_now_bonus():
|
||||||
"""13:30 에 낮 구간이 지금. 저녁 구간(16시~)은 16시에만 비가 와도 지금 비 보너스 없이 평균 × 100 → 약 12점."""
|
"""13:30 에 낮 구간이 지금. 저녁 구간(17시~)은 17시에만 비가 와도 지금 비 보너스 없이 평균 × 100 → 17~23시 7시간 중 1시간, 약 14점."""
|
||||||
now = datetime(2026, 10, 8, 13, 30, tzinfo=KST)
|
now = datetime(2026, 10, 8, 13, 30, tzinfo=KST)
|
||||||
parts = slot_results(_umbrella_defn(), DAY, REGION, _rain_at({16}), {}, CTX, SUNSET, now)
|
parts = slot_results(_umbrella_defn(), DAY, REGION, _rain_at({17}), {}, CTX, SUNSET, now)
|
||||||
assert 10 <= parts["evening"].score <= 13
|
assert 13 <= parts["evening"].score <= 15
|
||||||
|
|
||||||
|
|
||||||
def test_umbrella_rest_of_day_stops_at_midnight():
|
def test_umbrella_rest_of_day_stops_at_midnight():
|
||||||
|
|||||||
@@ -0,0 +1,481 @@
|
|||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
from redis.asyncio import Redis
|
||||||
|
from redis.exceptions import RedisError
|
||||||
|
|
||||||
|
import services.embed_service as embed_service
|
||||||
|
from common.cache.redis_client import REDIS
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.database.model.models import Region, WeatherHourly
|
||||||
|
from common.enums import ErrorType, SlotTone
|
||||||
|
from common.utils.kma_time import KST, now_kst
|
||||||
|
from crud.region_crud import RegionCRUD
|
||||||
|
from crud.widget_crud import WidgetCRUD
|
||||||
|
from router.router import app
|
||||||
|
from router.v1.feed.protocol import Hero, HeroStat, Res_Feed, TopIndex
|
||||||
|
from services.embed_referer import OTHER_HOST, UNKNOWN_HOST
|
||||||
|
from services.embed_service import card_data, card_link, region_path, render_card, render_quiet
|
||||||
|
from services.feed_service import FeedService
|
||||||
|
from services.weather_service import Slot, TodayWeather
|
||||||
|
|
||||||
|
REGION = "1114000000"
|
||||||
|
CARD = "/v1/embed/card"
|
||||||
|
CARD_KEY = f"widget:card:v{embed_service.ASSET_VERSION}:{REGION}"
|
||||||
|
SITE = "co.webforai.kr"
|
||||||
|
NOW = datetime(2026, 11, 25, 9, tzinfo=KST)
|
||||||
|
_DATA = re.compile(r'<script type="application/json" id="wx-data">(.*?)</script>', re.S)
|
||||||
|
|
||||||
|
|
||||||
|
def client():
|
||||||
|
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _roomy_build_timeout(monkeypatch):
|
||||||
|
"""빈 시험 DB 에서 처음 만드는 카드는 날씨 수집부터 해서 8초를 넘기기도 한다. 시간 제한은 그것을 보는 시험만 줄인다."""
|
||||||
|
monkeypatch.setattr(embed_service, "CARD_BUILD_TIMEOUT_SEC", 60)
|
||||||
|
|
||||||
|
|
||||||
|
def _feed(now_at: datetime = NOW, weather_score=56, bubble: str = "포근해요", sky_mode: str = "day",
|
||||||
|
stories: tuple[TopIndex, ...] = ()) -> Res_Feed:
|
||||||
|
top1 = TopIndex(index_id=1, code="x", name="산책각", icon="x", score=80, rank=1, summary="걷기 좋아요")
|
||||||
|
hero = Hero(now_at=now_at, sky_mode=sky_mode, temp_c=8.2, weather_score=weather_score, bubble=bubble, top1=top1,
|
||||||
|
weather_slots={"morning": 40, "day": 56, "evening": 61, "night": 30},
|
||||||
|
status=[HeroStat(icon="m", label="습도", value="보통", tone="normal")], moon_name="보름달", moon_pct=99)
|
||||||
|
return Res_Feed(hero=hero, stories=list(stories))
|
||||||
|
|
||||||
|
|
||||||
|
def _gak(index_id: int, name: str, slots: dict[str, int], ranks: dict[str, int]) -> TopIndex:
|
||||||
|
return TopIndex(index_id=index_id, code=f"g{index_id}", name=name, icon="x", score=50, rank=index_id, slots=slots, slot_ranks=ranks)
|
||||||
|
|
||||||
|
|
||||||
|
# 아침 1위 러닝각 64점(순위가 점수보다 앞선다), 낮 1위 러닝각 65점, 저녁 1위 산책각 72점, 밤은 구간 값이 있는 각이 없다
|
||||||
|
_GAKS = (
|
||||||
|
_gak(1, "러닝각", {"morning": 64, "day": 65, "evening": 70}, {"morning": 1, "day": 1, "evening": 2}),
|
||||||
|
_gak(2, "산책각", {"morning": 90, "day": 50, "evening": 72}, {"morning": 2, "day": 2, "evening": 1}),
|
||||||
|
_gak(3, "별보기각", {}, {"night": 1}), # 순위만 있고 점수가 없으면 고르지 않는다 (앱 atSlot 과 같음)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _today(temp=0.0) -> TodayWeather:
|
||||||
|
at = datetime(2026, 11, 25, 0, tzinfo=KST)
|
||||||
|
row = WeatherHourly(forecast_at=at, temp_c=temp, sky=2, rain_type=1, rain_prob=0) if temp is not None else None
|
||||||
|
slot = Slot(at=at, row=row, icon="cloud" if row else "none", tone=SlotTone.NIGHT, note="")
|
||||||
|
return TodayWeather(region=Region(code="5213000000", short_name="군산시"), day=NOW.date(), issued_at=None, headline="", slots=[slot])
|
||||||
|
|
||||||
|
|
||||||
|
def _card(html: str) -> dict:
|
||||||
|
return json.loads(_DATA.search(html).group(1))
|
||||||
|
|
||||||
|
|
||||||
|
def _count_feed_calls(monkeypatch) -> list[str]:
|
||||||
|
"""FeedService.feed 를 부른 지역 코드를 모은다 (원래 동작은 그대로)."""
|
||||||
|
calls: list[str] = []
|
||||||
|
original = FeedService.feed
|
||||||
|
|
||||||
|
async def counting(self, region_code):
|
||||||
|
calls.append(region_code)
|
||||||
|
return await original(self, region_code)
|
||||||
|
|
||||||
|
monkeypatch.setattr(FeedService, "feed", counting)
|
||||||
|
return calls
|
||||||
|
|
||||||
|
|
||||||
|
def _views_key() -> str:
|
||||||
|
return f"widget:views:{now_kst().date().isoformat()}"
|
||||||
|
|
||||||
|
|
||||||
|
async def _views() -> dict[str, int]:
|
||||||
|
"""오늘 Redis 에 쌓인 노출 수, 호스트별 합 (관리자 API 가 DB 로 옮기기 전)."""
|
||||||
|
out: dict[str, int] = {}
|
||||||
|
for field, n in (await REDIS.conn.hgetall(_views_key())).items():
|
||||||
|
host = field.split("\t", 1)[0]
|
||||||
|
out[host] = out.get(host, 0) + int(n)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
async def _db_views() -> dict[str, int]:
|
||||||
|
err, views = await DB_SESSION_MNG.execute_lambda(lambda s: WidgetCRUD().views_since(s, now_kst().date()))
|
||||||
|
assert err is ErrorType.SUCCESS
|
||||||
|
return views
|
||||||
|
|
||||||
|
|
||||||
|
async def _cache_today(name: str) -> None:
|
||||||
|
cached = card_data(_feed(), _today(), name, NOW)
|
||||||
|
cached["today"]["day"] = now_kst().date().isoformat()
|
||||||
|
await REDIS.conn.set(CARD_KEY, json.dumps(cached, ensure_ascii=False))
|
||||||
|
|
||||||
|
|
||||||
|
def test_region_path():
|
||||||
|
assert region_path("5213000000") == "jeonbuk/gunsan"
|
||||||
|
assert region_path("0000000000") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_link():
|
||||||
|
assert card_link("jeonbuk/gunsan", "co.webforai.kr") == "/today/jeonbuk/gunsan?utm_source=widget&utm_medium=embed&utm_campaign=co.webforai.kr"
|
||||||
|
assert card_link(None, "unknown") == "/?utm_source=widget&utm_medium=embed&utm_campaign=unknown"
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_data_shape():
|
||||||
|
assert card_data(_feed(), _today(), "군산시", NOW) == {
|
||||||
|
"name": "군산시",
|
||||||
|
"hero": {"now_at": "2026-11-25T09:00:00+09:00", "sky_mode": "day", "temp_c": 8.2, "weather_score": 56,
|
||||||
|
"weather_slots": {"morning": 40, "day": 56, "sunset": 61, "night": 30}, "bubble": "포근해요",
|
||||||
|
"top1": {"summary": "걷기 좋아요"}, "status": [{"label": "습도", "value": "보통", "tone": "normal"}],
|
||||||
|
"moon_name": "보름달", "moon_pct": 99},
|
||||||
|
"picks": {},
|
||||||
|
"today": {"day": "2026-11-25", "slots": [{"at": "2026-11-25T00:00:00+09:00", "temp_c": 0.0, "sky": 2, "rain_type": 1, "icon": "cloud"}]},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_picks_follow_app_bubble_rule():
|
||||||
|
# 지금은 낮: 낮 칸 머리말은 '지금', 다른 칸은 '오늘 아침' 등. 65점 이상이면 각 이름, 64점이면 쉬어 가요. 밤은 고를 각이 없어 빠진다
|
||||||
|
assert card_data(_feed(stories=_GAKS), _today(), "군산시", NOW)["picks"] == {
|
||||||
|
"morning": {"bubble": "오늘 아침은 쉬어 가요"},
|
||||||
|
"day": {"bubble": "지금은 러닝각!"},
|
||||||
|
"sunset": {"bubble": "오늘 저녁은 산책각!"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_picks_now_prefix_follows_sky_mode():
|
||||||
|
picks = card_data(_feed(sky_mode="sunset", stories=_GAKS), _today(), "군산시", NOW)["picks"]
|
||||||
|
assert picks["sunset"]["bubble"] == "지금은 산책각!"
|
||||||
|
assert picks["day"]["bubble"] == "오늘 낮은 러닝각!"
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_picks_tie_keeps_feed_order():
|
||||||
|
tied = (_gak(1, "러닝각", {"night": 70}, {"night": 1}), _gak(2, "산책각", {"night": 80}, {"night": 1}))
|
||||||
|
assert card_data(_feed(stories=tied), _today(), "군산시", NOW)["picks"] == {"night": {"bubble": "오늘 밤은 러닝각!"}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_data_none_when_stale_or_empty():
|
||||||
|
assert card_data(_feed(now_at=datetime(2026, 11, 24, 23, tzinfo=KST)), _today(), "군산시", NOW) is None
|
||||||
|
assert card_data(_feed(weather_score=None), _today(), "군산시", NOW) is None
|
||||||
|
assert card_data(_feed(), _today(temp=None), "군산시", NOW) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_card_escapes():
|
||||||
|
bubble = '</script><b>"x"'
|
||||||
|
link = card_link(None, "unknown")
|
||||||
|
html = render_card("side", "sky", card_data(_feed(bubble=bubble), _today(), "군산시", NOW), link)
|
||||||
|
assert "</script><b>" not in html
|
||||||
|
data = _card(html)
|
||||||
|
assert data["hero"]["bubble"] == bubble and data["link"] == link
|
||||||
|
assert 'class="wx wx-side wx-bg-sky"' in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_markup():
|
||||||
|
link = card_link("jeonbuk/gunsan", "co.webforai.kr")
|
||||||
|
html = render_card("home", "sky", card_data(_feed(), _today(), "군산시", NOW), link)
|
||||||
|
head, body = html.split("<body>", 1)
|
||||||
|
assert '<meta name="color-scheme" content="light">' in head
|
||||||
|
assert '<span class="wx-t">군산시 날씨</span>' in body
|
||||||
|
assert 'class="wx-go"' in body and 'target="_blank"' in body and 'rel="noopener"' in body
|
||||||
|
assert f'href="{link.replace("&", "&")}"' in body
|
||||||
|
assert "data-wx-dt" in body and "data-wx-b" in body
|
||||||
|
assert "/embed/card.js?v=" in body
|
||||||
|
assert f'<noscript><a class="wx-ns" href="{link.replace("&", "&")}" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a></noscript>' in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_has_rabbit_loading():
|
||||||
|
html = render_card("side", "sky", card_data(_feed(), _today(), "군산시", NOW), card_link(None, "unknown"))
|
||||||
|
box = html.split('<div class="wx wx-side wx-bg-sky">', 1)[1].split('<div class="wx-b" data-wx-b></div>', 1)[0]
|
||||||
|
assert 'class="wx-load"' in box and 'role="status"' in box
|
||||||
|
assert '<img src="/icons/rabbit.webp" alt=""' in box
|
||||||
|
assert "날씨 불러오는 중…" in box
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_link_matches_quiet_words():
|
||||||
|
html = render_card("home", "sky", card_data(_feed(), _today(), "군산시", NOW), card_link(None, "unknown"))
|
||||||
|
assert "<span data-wx-gl>날씨각에서 날씨 보기 ›</span>" in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_quiet_follows_bg():
|
||||||
|
link = card_link("jeonbuk/gunsan", "unknown")
|
||||||
|
dark, sky = render_quiet(link, "dark"), render_quiet(link, "sky")
|
||||||
|
assert 'class="wx-q-dark"' in dark and 'class="wx-q-sky"' in sky
|
||||||
|
assert "#1c3252" in dark and "#9fd3ff" in sky
|
||||||
|
for html in (dark, sky):
|
||||||
|
assert '<meta name="color-scheme" content="light">' in html
|
||||||
|
assert f'href="{link.replace("&", "&")}" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a>' in html
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_umami_sends_widget_card_page():
|
||||||
|
data = card_data(_feed(), _today(), "군산시", NOW)
|
||||||
|
assert "/embed/umami.js" not in render_card("side", "sky", data, card_link(None, "preview"))
|
||||||
|
html = render_card("home", "dark", data, card_link(None, "unknown"), track=True)
|
||||||
|
# 외부 스크립트를 직접 실행하지 않는다: 날씨각에 복사해 둔 스크립트를 쓰고 기록만 umami 서버로 보낸다
|
||||||
|
tag = re.search(r'<script defer src="/embed/umami\.js"[^>]*></script>', html).group(0)
|
||||||
|
assert 'data-host-url="https://analytics.webforai.kr"' in tag
|
||||||
|
assert 'data-auto-track="false"' in tag and 'data-domains="weather.o2o.kr,www.weather.o2o.kr"' in tag
|
||||||
|
assert ""/widget"" in tag and "날씨 위젯 · 상세형" in tag
|
||||||
|
assert 'src="https://analytics.webforai.kr' not in html
|
||||||
|
assert "날씨 위젯 · 기본형" in render_card("side", "sky", data, card_link(None, "unknown"), track=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_umami_matches_index_html():
|
||||||
|
frontend = Path(__file__).resolve().parents[2] / "frontend"
|
||||||
|
index = (frontend / "index.html").read_text(encoding="utf-8")
|
||||||
|
assert f'data-website-id="{embed_service.UMAMI_WEBSITE_ID}"' in index
|
||||||
|
assert f'src="{embed_service.UMAMI_SRC}"' in index and f'data-host-url="{embed_service.UMAMI_HOST}"' in index
|
||||||
|
assert (frontend / "public" / embed_service.UMAMI_SRC.lstrip("/")).is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def test_card_markup_escapes_name():
|
||||||
|
html = render_card("side", "sky", card_data(_feed(), _today(), '<b>"군산"', NOW), card_link(None, "unknown"))
|
||||||
|
body = html.split("<body>", 1)[1].split('<script type="application/json"', 1)[0]
|
||||||
|
assert "<b>" not in body and "<b>"군산" 날씨" in body
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_any_site_gets_card(offline):
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": "https://evil.example/x"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert 'id="wx-data"' in res.text and "wx-side" in res.text and "wx-bg-sky" in res.text
|
||||||
|
for header in ("content-security-policy", "x-frame-options", "set-cookie"):
|
||||||
|
assert header not in res.headers, header
|
||||||
|
assert res.headers["cache-control"] == "no-store"
|
||||||
|
assert res.headers["x-robots-tag"] == "noindex"
|
||||||
|
assert "/embed/umami.js" in res.text
|
||||||
|
assert await _views() == {"evil.example": 1}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_card_view_counts_in_redis_not_db(offline):
|
||||||
|
async with client() as c:
|
||||||
|
for kind in ("side", "home", "side"):
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": kind}, headers={"Referer": f"https://{SITE}/s/stay"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
assert await REDIS.conn.hgetall(_views_key()) == {f"{SITE}\tside": "2", f"{SITE}\thome": "1"}
|
||||||
|
assert await _db_views() == {}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_bg_and_kind_classes(offline):
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "home", "bg": "dark"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert "wx-home" in res.text and "wx-bg-dark" in res.text
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_no_referer_counts_unknown(offline):
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert "utm_campaign=unknown" in _card(res.text)["link"]
|
||||||
|
assert await _views() == {UNKNOWN_HOST: 1}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_self_preview_not_counted(offline):
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": "http://test/widget"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
assert "utm_campaign=preview" in _card(res.text)["link"]
|
||||||
|
assert "/embed/umami.js" not in res.text
|
||||||
|
assert await _views() == {}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_daily_host_cap(offline, monkeypatch):
|
||||||
|
monkeypatch.setattr(embed_service, "DAILY_HOST_CAP", 2)
|
||||||
|
async with client() as c:
|
||||||
|
for host in ("a.example", "b.example", "c.example", "a.example"):
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{host}/"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text, host
|
||||||
|
assert await _views() == {"a.example": 2, "b.example": 1, OTHER_HOST: 1}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_bad_input_is_quiet_html():
|
||||||
|
async with client() as c:
|
||||||
|
for params in ({"region": "abc", "type": "side"}, {"region": "9999999999", "type": "side"}, {"region": REGION, "type": "big"},
|
||||||
|
{"region": REGION, "type": "side", "bg": "pink"}):
|
||||||
|
res = await c.get(CARD, params=params)
|
||||||
|
assert res.status_code == 404, params
|
||||||
|
assert res.headers["content-type"].startswith("text/html"), params
|
||||||
|
assert "wx-data" not in res.text, params
|
||||||
|
# 위젯 유입이 GA 에서 구분되게 잘못된 입력도 utm 이 붙은 링크
|
||||||
|
assert f'href="{card_link(None, "unknown").replace("&", "&")}"' in res.text, params
|
||||||
|
assert await _views() == {}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_bad_bg_is_sky_quiet():
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side", "bg": "pink"})
|
||||||
|
assert res.status_code == 404
|
||||||
|
assert 'class="wx-q-sky"' in res.text and "pink" not in res.text
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_slow_card_build_is_quiet(offline, monkeypatch):
|
||||||
|
original = FeedService.feed
|
||||||
|
|
||||||
|
async def slow(self, region_code):
|
||||||
|
await asyncio.sleep(30)
|
||||||
|
return await original(self, region_code)
|
||||||
|
|
||||||
|
monkeypatch.setattr(embed_service, "CARD_BUILD_TIMEOUT_SEC", 0.1)
|
||||||
|
monkeypatch.setattr(FeedService, "feed", slow)
|
||||||
|
async with client() as c:
|
||||||
|
res = await asyncio.wait_for(c.get(CARD, params={"region": REGION, "type": "side", "bg": "dark"},
|
||||||
|
headers={"Referer": f"https://{SITE}/s/stay"}), 5)
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert "날씨각에서 날씨 보기" in res.text and "wx-data" not in res.text and 'class="wx-q-dark"' in res.text
|
||||||
|
assert await _views() == {}
|
||||||
|
# 시간을 넘겨 멈춘 작업이 남아 DB·Redis 를 망가뜨리지 않는다: 바로 다음 요청은 카드를 그린다
|
||||||
|
monkeypatch.setattr(FeedService, "feed", original)
|
||||||
|
monkeypatch.setattr(embed_service, "CARD_BUILD_TIMEOUT_SEC", 60)
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/s/stay"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
assert await _views() == {SITE: 1}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_feed_failure_is_quiet(offline, monkeypatch):
|
||||||
|
async def broken(self, region_code):
|
||||||
|
return ErrorType.DB_ERROR, None
|
||||||
|
|
||||||
|
monkeypatch.setattr(FeedService, "feed", broken)
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/s/stay"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert "날씨각에서 날씨 보기" in res.text and "wx-data" not in res.text
|
||||||
|
assert res.headers["cache-control"] == "no-store"
|
||||||
|
assert await _views() == {}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_feed_exception_is_quiet(offline, monkeypatch):
|
||||||
|
async def crash(self, region_code):
|
||||||
|
raise RuntimeError("feed down")
|
||||||
|
|
||||||
|
monkeypatch.setattr(FeedService, "feed", crash)
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/s/stay"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert res.headers["content-type"].startswith("text/html")
|
||||||
|
assert "날씨각에서 날씨 보기" in res.text and "Internal Server Error" not in res.text
|
||||||
|
assert await _views() == {}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_card_data_is_cached(offline, monkeypatch):
|
||||||
|
calls = _count_feed_calls(monkeypatch)
|
||||||
|
async with client() as c:
|
||||||
|
for _ in range(2):
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
assert calls == [REGION]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_cached_card_skips_region_lookup(monkeypatch):
|
||||||
|
await _cache_today("캐시된곳")
|
||||||
|
lookups: list[str] = []
|
||||||
|
|
||||||
|
async def counting_get(self, s, code):
|
||||||
|
lookups.append(code)
|
||||||
|
raise AssertionError("캐시가 있으면 지역을 조회하지 않는다")
|
||||||
|
|
||||||
|
monkeypatch.setattr(RegionCRUD, "get", counting_get)
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
assert "캐시된곳 날씨" in res.text
|
||||||
|
assert lookups == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_concurrent_misses_build_once(offline, monkeypatch):
|
||||||
|
# 빈 시험 DB 에서 처음 만드는 카드는 몇 초 걸려, 기다리는 쪽이 먼저 포기하지 않게 기다림을 넉넉히 준다
|
||||||
|
monkeypatch.setattr(embed_service, "_LOCK_WAIT_STEPS", 300)
|
||||||
|
calls: list[str] = []
|
||||||
|
original = FeedService.feed
|
||||||
|
|
||||||
|
async def slow_counting(self, region_code):
|
||||||
|
calls.append(region_code)
|
||||||
|
await asyncio.sleep(0.5) # 두 요청이 확실히 겹치게
|
||||||
|
return await original(self, region_code)
|
||||||
|
|
||||||
|
monkeypatch.setattr(FeedService, "feed", slow_counting)
|
||||||
|
async with client() as c:
|
||||||
|
results = await asyncio.gather(*[c.get(CARD, params={"region": REGION, "type": kind}) for kind in ("side", "home")])
|
||||||
|
for res in results:
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
assert calls == [REGION]
|
||||||
|
assert await REDIS.conn.get(f"lock:widget:card:{REGION}") is None # 다 만든 뒤 잠금이 풀렸다
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_card_builds_without_lock_when_lock_fails(offline, monkeypatch):
|
||||||
|
calls = _count_feed_calls(monkeypatch)
|
||||||
|
original = Redis.set
|
||||||
|
|
||||||
|
async def lock_down(self, name, *a, **kw):
|
||||||
|
if str(name).startswith("lock:widget:card:"):
|
||||||
|
raise RedisError("redis down")
|
||||||
|
return await original(self, name, *a, **kw)
|
||||||
|
|
||||||
|
monkeypatch.setattr(Redis, "set", lock_down)
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
assert calls == [REGION]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_stale_cached_card_is_rebuilt(offline, monkeypatch):
|
||||||
|
stale = card_data(_feed(), _today(), "군산시", NOW)
|
||||||
|
stale["today"]["day"] = (now_kst().date() - timedelta(days=1)).isoformat()
|
||||||
|
await REDIS.conn.set(CARD_KEY, json.dumps(stale, ensure_ascii=False))
|
||||||
|
calls = _count_feed_calls(monkeypatch)
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
assert calls == [REGION]
|
||||||
|
assert _card(res.text)["today"]["day"] == now_kst().date().isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_cached_card_key_has_asset_version(offline, monkeypatch):
|
||||||
|
cached = card_data(_feed(), _today(), "캐시된곳", NOW)
|
||||||
|
cached["today"]["day"] = now_kst().date().isoformat()
|
||||||
|
await REDIS.conn.set(CARD_KEY, json.dumps(cached, ensure_ascii=False))
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"})
|
||||||
|
assert res.status_code == 200 and "캐시된곳" in res.text
|
||||||
|
monkeypatch.setattr(embed_service, "ASSET_VERSION", "999") # 카드 파일이 바뀌면 예전 저장 데이터를 쓰지 않는다
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
assert "캐시된곳" not in res.text
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_broken_cached_card_is_rebuilt(offline):
|
||||||
|
await REDIS.conn.set(CARD_KEY, "not json{")
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
@pytest.mark.parametrize("error", [RedisError("redis down"), RuntimeError("count broke")])
|
||||||
|
async def test_count_failure_still_serves_card(offline, monkeypatch, error):
|
||||||
|
async def down(self, *a, **kw):
|
||||||
|
raise error
|
||||||
|
|
||||||
|
monkeypatch.setattr(Redis, "hincrby", down)
|
||||||
|
async with client() as c:
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": f"https://{SITE}/s/stay"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
from services.embed_referer import UNKNOWN_HOST, normalize_host, view_host
|
||||||
|
|
||||||
|
OWN = frozenset({"weather.o2o.kr", "localhost:8080"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_host_trims_address_to_host():
|
||||||
|
assert normalize_host("https://Co.WebForAI.kr/s/stay") == "co.webforai.kr"
|
||||||
|
assert normalize_host(" gunsan.webforai.kr ") == "gunsan.webforai.kr"
|
||||||
|
assert normalize_host("www.example.co.kr") == "www.example.co.kr"
|
||||||
|
assert normalize_host("my-shop.example.co.kr") == "my-shop.example.co.kr"
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_host_rejects_what_cannot_go_in_a_header():
|
||||||
|
for bad in ("", "localhost", "exa mple.com", "a.com; script-src *", "https://a.com:8443", "1.2.3.4", "*.example.com", "a..com", "'self'", "-a.com", "a-.com", "a.-b.kr"):
|
||||||
|
assert normalize_host(bad) is None, bad
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_host_length_limits():
|
||||||
|
assert normalize_host("a" * 63 + ".example.com") == "a" * 63 + ".example.com"
|
||||||
|
assert normalize_host("a" * 64 + ".example.com") is None
|
||||||
|
ok = ".".join(["a" * 63, "b" * 63, "c" * 63, "d" * 58]) + ".kr" # 253자
|
||||||
|
assert len(ok) == 253 and normalize_host(ok) == ok
|
||||||
|
assert normalize_host(".".join(["a" * 63, "b" * 63, "c" * 63, "d" * 59]) + ".kr") is None # 254자
|
||||||
|
|
||||||
|
|
||||||
|
def test_view_host_takes_site_host():
|
||||||
|
assert view_host("https://co.webforai.kr/s/stay", OWN) == "co.webforai.kr"
|
||||||
|
assert view_host("http://Blog.Example.com:8080/a", OWN) == "blog.example.com"
|
||||||
|
|
||||||
|
|
||||||
|
def test_view_host_self_is_not_counted():
|
||||||
|
assert view_host("https://weather.o2o.kr/widget", OWN) is None
|
||||||
|
assert view_host("http://localhost:8080/widget", OWN) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_view_host_unknown():
|
||||||
|
for bad in (None, "", "null", "about:blank", "android-app://com.example/", "https://", "not a url",
|
||||||
|
"https://1.2.3.4/", "https://a.com; x/", "https://" + "a" * 300 + ".com/"):
|
||||||
|
assert view_host(bad, OWN) == UNKNOWN_HOST, bad
|
||||||
@@ -132,6 +132,15 @@ async def test_hero_shows_the_observed_current_weather(offline, monkeypatch):
|
|||||||
assert (hero["temp_c"], hero["humidity"]) == (3.3, 88)
|
assert (hero["temp_c"], hero["humidity"]) == (3.3, 88)
|
||||||
|
|
||||||
|
|
||||||
|
def test_hero_bubble_recommends_the_top_gak_from_65_points():
|
||||||
|
"""중요도 '하' 각은 만점이어도 화면 점수가 70점이라, 기준이 70이면 날씨에 꼭 맞아도(예: 겨울 군밤각 68점) 늘 '쉬어 가요'였다."""
|
||||||
|
from services.feed_service import hero_bubble
|
||||||
|
|
||||||
|
assert hero_bubble("군밤각", 68) == "지금은 군밤각!"
|
||||||
|
assert hero_bubble("군밤각", 65) == "지금은 군밤각!"
|
||||||
|
assert hero_bubble("군밤각", 64) == "지금은 쉬어 가요"
|
||||||
|
|
||||||
|
|
||||||
def _card(post_type, post_id=1):
|
def _card(post_type, post_id=1):
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
@@ -148,7 +157,7 @@ def test_slot_follows_sunset():
|
|||||||
|
|
||||||
sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST)
|
sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST)
|
||||||
at = lambda h, m=0: datetime(2026, 10, 2, h, m, tzinfo=KST) # noqa: E731
|
at = lambda h, m=0: datetime(2026, 10, 2, h, m, tzinfo=KST) # noqa: E731
|
||||||
assert [slot_of(at(h, m), sunset) for h, m in ((4, 59), (5, 0), (11, 0), (16, 9), (16, 10), (19, 9), (19, 10), (23, 0))] == [
|
assert [slot_of(at(h, m), sunset) for h, m in ((4, 59), (5, 0), (11, 0), (16, 59), (17, 0), (19, 9), (19, 10), (23, 0))] == [
|
||||||
"night", "morning", "day", "day", "evening", "evening", "night", "night"]
|
"night", "morning", "day", "day", "evening", "evening", "night", "night"]
|
||||||
summer = datetime(2026, 6, 21, 19, 57, tzinfo=KST)
|
summer = datetime(2026, 6, 21, 19, 57, tzinfo=KST)
|
||||||
assert slot_of(datetime(2026, 6, 21, 20, 30, tzinfo=KST), summer) == "evening"
|
assert slot_of(datetime(2026, 6, 21, 20, 30, tzinfo=KST), summer) == "evening"
|
||||||
|
|||||||
@@ -114,10 +114,10 @@ def test_running_muggy_morning_does_not_exceed_original_weather_score():
|
|||||||
|
|
||||||
|
|
||||||
def test_now_slot_summary_shows_current_hour_not_middle_of_rest():
|
def test_now_slot_summary_shows_current_hour_not_middle_of_rest():
|
||||||
"""오후 4시 10분이면 지금 구간 줄은 남은 16~18시의 가운데(5시)가 아니라 지금(4시) 날씨로."""
|
"""오후 5시 10분이면 지금 구간 줄은 남은 17~19시의 가운데(6시)가 아니라 지금(5시) 날씨로."""
|
||||||
start = kst_midnight(SAT)
|
start = kst_midnight(SAT)
|
||||||
hourly = _hourly(SAT) | _hourly(SAT + timedelta(days=1))
|
hourly = _hourly(SAT) | _hourly(SAT + timedelta(days=1))
|
||||||
sunset = start + timedelta(hours=17, minutes=30)
|
sunset = start + timedelta(hours=19)
|
||||||
results = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset, now=start + timedelta(hours=16, minutes=10))
|
results = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset, now=start + timedelta(hours=17, minutes=10))
|
||||||
assert results["evening"].summary.startswith("오후 4시"), results["evening"].summary
|
assert results["evening"].summary.startswith("오후 5시"), results["evening"].summary
|
||||||
assert results["night"].summary.startswith("오후 4시") is False
|
assert results["night"].summary.startswith("오후 5시") is False
|
||||||
@@ -113,6 +113,13 @@ def test_preset_copies_rules_that_fit_and_drops_the_rest():
|
|||||||
assert p == {"slots": ["evening"], "rain": "dry"}
|
assert p == {"slots": ["evening"], "rain": "dry"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_preset_evening_starts_at_17_like_the_feed():
|
||||||
|
"""피드와 같은 규칙: 저녁은 17시보다 이르게 시작하지 않으니 16시대는 낮."""
|
||||||
|
rules = {"rain": {"dir": "dry"}, "temp": {"type": "range", "lo": 18, "hi": 24}}
|
||||||
|
assert preset(_defn(rules, [{"from": 16, "to": 17}]))["slots"] == ["day"]
|
||||||
|
assert preset(_defn(rules, [{"from": 17, "to": 19}]))["slots"] == ["evening"]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_presets_cover_every_gak_with_valid_rules():
|
async def test_presets_cover_every_gak_with_valid_rules():
|
||||||
async with client() as c:
|
async with client() as c:
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
from sqlalchemy.exc import SQLAlchemyError
|
||||||
|
|
||||||
|
import services.embed_service as embed_service
|
||||||
|
from common.cache.redis_client import REDIS
|
||||||
|
from common.database.db_session_manager import DB_SESSION_MNG
|
||||||
|
from common.enums import ErrorType
|
||||||
|
from common.utils.kma_time import now_kst
|
||||||
|
from config.settings import settings
|
||||||
|
from crud.widget_crud import WidgetCRUD
|
||||||
|
from router.router import app
|
||||||
|
from services.embed_referer import UNKNOWN_HOST
|
||||||
|
|
||||||
|
KEY = "test-admin-key"
|
||||||
|
H = {"X-Admin-Key": KEY}
|
||||||
|
VIEWS = "/v1/admin/widget/views"
|
||||||
|
CARD = "/v1/embed/card"
|
||||||
|
REGION = "1114000000"
|
||||||
|
|
||||||
|
|
||||||
|
def client():
|
||||||
|
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||||
|
|
||||||
|
|
||||||
|
def _key(days_ago: int = 0) -> str:
|
||||||
|
return f"widget:views:{(now_kst().date() - timedelta(days=days_ago)).isoformat()}"
|
||||||
|
|
||||||
|
|
||||||
|
async def _redis_view_keys() -> list[str]:
|
||||||
|
return sorted([k async for k in REDIS.conn.scan_iter(match="widget:views*")])
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_views(c) -> dict:
|
||||||
|
res = (await c.get(VIEWS, headers=H)).json()
|
||||||
|
assert res["result"]["code"] == ErrorType.SUCCESS.value
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_widget_views_need_key(monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "admin_api_key", KEY)
|
||||||
|
async with client() as c:
|
||||||
|
for headers in ({}, {"X-Admin-Key": "wrong"}):
|
||||||
|
assert (await c.get(VIEWS, headers=headers)).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_widget_views_sums_by_host(monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "admin_api_key", KEY)
|
||||||
|
crud = WidgetCRUD()
|
||||||
|
today = now_kst().date()
|
||||||
|
views = [
|
||||||
|
(today, "co.webforai.kr", "side"), (today, "co.webforai.kr", "side"), (today - timedelta(days=6), "co.webforai.kr", "home"),
|
||||||
|
(today - timedelta(days=7), "co.webforai.kr", "side"), (today, "blog.example.com", "side"), (today, UNKNOWN_HOST, "side"),
|
||||||
|
]
|
||||||
|
for day, host, kind in views:
|
||||||
|
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s, d=day, h=host, k=kind: crud.add_views(s, d, {(h, k): 1}))
|
||||||
|
assert err is ErrorType.SUCCESS
|
||||||
|
|
||||||
|
async with client() as c:
|
||||||
|
res = await _get_views(c)
|
||||||
|
assert res["items"] == [
|
||||||
|
{"host": "co.webforai.kr", "views_7d": 3, "views_30d": 4},
|
||||||
|
{"host": UNKNOWN_HOST, "views_7d": 1, "views_30d": 1},
|
||||||
|
{"host": "blog.example.com", "views_7d": 1, "views_30d": 1},
|
||||||
|
]
|
||||||
|
assert res["total_7d"] == 5 and res["total_30d"] == 6
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_widget_views_moves_redis_counts_to_db_once(monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "admin_api_key", KEY)
|
||||||
|
crud = WidgetCRUD()
|
||||||
|
today = now_kst().date()
|
||||||
|
err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: crud.add_views(s, today, {("a.example", "side"): 5}))
|
||||||
|
assert err is ErrorType.SUCCESS
|
||||||
|
await REDIS.conn.hset(_key(), mapping={"a.example\tside": 2, "a.example\thome": 1, f"{UNKNOWN_HOST}\tside": 4})
|
||||||
|
await REDIS.conn.hset(_key(10), mapping={"a.example\tside": 7})
|
||||||
|
# 이전 요청이 옮기다 남긴 임시 키도 함께 옮긴다
|
||||||
|
await REDIS.conn.hset(f"widget:views-flush:{today.isoformat()}:leftover", mapping={"b.example\tside": 3})
|
||||||
|
|
||||||
|
async with client() as c:
|
||||||
|
first = await _get_views(c)
|
||||||
|
assert await _redis_view_keys() == []
|
||||||
|
second = await _get_views(c) # 두 번 불러도 두 번 더하지 않는다
|
||||||
|
for res in (first, second):
|
||||||
|
assert res["items"] == [
|
||||||
|
{"host": "a.example", "views_7d": 8, "views_30d": 15},
|
||||||
|
{"host": UNKNOWN_HOST, "views_7d": 4, "views_30d": 4},
|
||||||
|
{"host": "b.example", "views_7d": 3, "views_30d": 3},
|
||||||
|
]
|
||||||
|
assert res["total_7d"] == 15 and res["total_30d"] == 22
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_widget_views_keeps_redis_counts_when_db_write_fails(monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "admin_api_key", KEY)
|
||||||
|
original = WidgetCRUD.add_views
|
||||||
|
|
||||||
|
async def broken(self, s, day, counts):
|
||||||
|
raise SQLAlchemyError("db down")
|
||||||
|
|
||||||
|
await REDIS.conn.hset(_key(), mapping={"a.example\tside": 2})
|
||||||
|
monkeypatch.setattr(WidgetCRUD, "add_views", broken)
|
||||||
|
async with client() as c:
|
||||||
|
await c.get(VIEWS, headers=H)
|
||||||
|
# 수치는 원래 키로 돌아가 있고, 임시 키는 남지 않는다
|
||||||
|
assert await _redis_view_keys() == [_key()]
|
||||||
|
assert await REDIS.conn.hgetall(_key()) == {"a.example\tside": "2"}
|
||||||
|
|
||||||
|
monkeypatch.setattr(WidgetCRUD, "add_views", original)
|
||||||
|
res = await _get_views(c)
|
||||||
|
assert res["items"] == [{"host": "a.example", "views_7d": 2, "views_30d": 2}]
|
||||||
|
assert await _redis_view_keys() == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_card_views_reach_admin_api(offline, monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "admin_api_key", KEY)
|
||||||
|
monkeypatch.setattr(embed_service, "CARD_BUILD_TIMEOUT_SEC", 60) # 빈 시험 DB 의 첫 카드는 8초를 넘기기도 한다 (test_embed 와 같음)
|
||||||
|
async with client() as c:
|
||||||
|
for _ in range(2):
|
||||||
|
res = await c.get(CARD, params={"region": REGION, "type": "side"}, headers={"Referer": "https://blog.example.com/post"})
|
||||||
|
assert res.status_code == 200 and 'id="wx-data"' in res.text
|
||||||
|
views = await _get_views(c)
|
||||||
|
assert views["items"] == [{"host": "blog.example.com", "views_7d": 2, "views_30d": 2}]
|
||||||
|
# 옮긴 뒤 새 요청은 새 키에 다시 쌓인다
|
||||||
|
await c.get(CARD, params={"region": REGION, "type": "home"}, headers={"Referer": "https://blog.example.com/post"})
|
||||||
|
assert await REDIS.conn.hgetall(_key()) == {"blog.example.com\thome": "1"}
|
||||||
|
views = await _get_views(c)
|
||||||
|
assert views["items"] == [{"host": "blog.example.com", "views_7d": 3, "views_30d": 3}]
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
# 날씨각 위젯 Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** 누구나 iframe 한 줄로 붙일 수 있는 날씨각 카드(`/embed/card`, 좁은 형·넓은 형 × 배경 3종)와, 지역·모양·배경을 고르면 바로 쓸 코드가 나오는 사용 방법 페이지(`/widget`)를 만든다.
|
||||||
|
|
||||||
|
**Architecture:** nginx 가 `/embed/card` 를 백엔드로 넘기고, 백엔드가 카드 HTML(그릴 데이터 포함)을 돌려주며 `Referer` 의 사이트 주소로 하루 노출 수를 센다. 어느 사이트에서 불러도 같은 카드다. 카드는 군산각의 순수 자바스크립트·CSS 를 옮겨 온 정적 파일(`frontend/public/embed/`)이 그린다. 사용 방법 페이지는 기존 React 앱의 새 경로다.
|
||||||
|
|
||||||
|
**Tech Stack:** FastAPI, SQLAlchemy(async), PostgreSQL, Redis, pytest / nginx / React 19, react-router, TanStack Query, Tailwind 4, `node --test` / 순수 JS·CSS(카드). 새 패키지 없음.
|
||||||
|
|
||||||
|
**Spec:** `docs/superpowers/specs/2026-11-25-embed-widget-design.md`
|
||||||
|
|
||||||
|
**변경 기록:** Task 1~3 은 첫 설계(등록한 사이트에서만 보임)로 끝냈다. 2026-11-25 에 '완전 오픈 + 배경 3종'으로 바뀌어 Task 4 가 등록·차단을 걷어 낸다. Task 5~7 은 바뀐 설계 기준이다.
|
||||||
|
|
||||||
|
## Global Constraints
|
||||||
|
|
||||||
|
- 주소는 `/embed/card?region=<숫자 10자리>&type=side|home&bg=sky|light|dark`(`bg` 를 빼면 `sky`), `/widget`. 공개 뒤에는 바꾸지 않는다.
|
||||||
|
- 신청·등록·차단이 없다. 어느 사이트에서 불러도 같은 카드를 돌려주고, 액자에 넣는 것을 막는 헤더(`X-Frame-Options`, `Content-Security-Policy: frame-ancestors`)를 붙이지 않는다.
|
||||||
|
- 카드에 나오는 것은 군산각 카드 그대로다: 날씨 점수, 해·달·구름, 한마디, 아침·낮·저녁·밤 4칸(넓은 형은 요약 문장·상태 줄 추가). 날씨각의 다른 기능(각 순위, 타로, 포스트, 댓글 등)은 넣지 않는다.
|
||||||
|
- 카드 화면에는 GA·쿠키·로그인 코드를 넣지 않는다. 응답에 `Set-Cookie` 가 없어야 한다.
|
||||||
|
- 요청에서 받은 문자열(`region`, `type`, `bg`, `Referer`)을 HTML 이나 헤더에 그대로 넣지 않는다. 집계에 남기는 호스트는 `normalize_host` 를 거친 값만이다.
|
||||||
|
- 오류는 iframe 안에 조용한 화면(`날씨각에서 날씨 보기 ›` 링크 하나)으로 돌려준다. 오류 JSON·오류 글자를 띄우지 않는다.
|
||||||
|
- 방문자 IP·페이지 주소는 저장하지 않는다. 테스트 데이터는 가짜 값으로 만든다.
|
||||||
|
- 새 외부 패키지는 설치 전에 이유와 대안을 말하고 확인받는다. 이 계획은 새 패키지 없이 짜여 있다.
|
||||||
|
- GA 이벤트는 같은 작업 안에서 넣는다: `shared/lib/analytics.ts`(`Events`, `GA_NAME`) + `track()` + `docs/이벤트_추적.md`.
|
||||||
|
- 커밋·푸시·PR 은 그때마다 승인받는다. 커밋은 기능 단위로 한 번이고 작업마다 나누지 않는다. 작업자는 커밋하지 않는다.
|
||||||
|
- 단계마다 확인받는다. 확인 지점은 Task 5·6·7 끝이다(① 은 Task 3 뒤에 했다).
|
||||||
|
- 로컬 확인은 이미 떠 있는 도커(`localhost:8080`)로 한다. vite 를 따로 띄우지 않는다.
|
||||||
|
- 백엔드 테스트 명령(이 PC): `cd backend && AZURE_STORAGE_CONNECTION_STRING= AZURE_STORAGE_CONTAINER= AZURE_BLOB_BASE_URL= AZURE_BLOB_SAS_TOKEN= PGSSLMODE=disable .venv/Scripts/python.exe -m pytest -q …`. `.env` 는 읽지 않는다.
|
||||||
|
- 전체 테스트에서 원래(main)부터 실패하는 것: `test_saju_api::test_level_unlocks_sections_and_awards_once`, `test_seo::test_new_copy_pages_get_new_title_and_description`. 고치지 않는다.
|
||||||
|
- 운영에 영향을 주는 것(배포, 운영 DB)은 실행 전에 명령과 영향 범위를 설명하고 확인받는다. `deploy.sh` 는 배포 때 `init.sql` 을 돌려 표를 만든다.
|
||||||
|
- 주석 처리된 코드, 안 쓰는 import, 디버그용 출력을 남기지 않는다. 오류를 빈 `except`/`catch` 로 삼키지 않는다.
|
||||||
|
- 요청받은 것만 고친다. 작업 중 본 다른 문제는 마지막 보고에 적는다.
|
||||||
|
|
||||||
|
## Review Focus
|
||||||
|
|
||||||
|
테스트가 없으면 놓치기 쉬운 것. 괄호 안 Task 에 확인이 들어 있다.
|
||||||
|
|
||||||
|
1. 이상한 `Referer`(`null`, `about:blank`, `android-app://…`, IP 주소, 세미콜론·공백이 섞인 값, 300자짜리) → 500 이 아니라 `(알 수 없음)` 으로 센다. (Task 4 `view_host` 테스트)
|
||||||
|
2. 누군가 `Referer` 를 바꿔 가며 수천 번 부름 → 집계 표에 사이트가 무한정 쌓이지 않고 하루 500곳을 넘으면 `(기타)` 로 합쳐진다. (Task 4 상한 테스트)
|
||||||
|
3. 피드를 못 만들었거나 예외가 남 → iframe 안에 오류 글자가 아니라 조용한 링크 화면이 뜬다. (Task 4 테스트, Task 3 에서 만든 것 유지)
|
||||||
|
4. 같은 지역 요청이 몰림 → 5분 안에는 피드·오늘 날씨를 다시 부르지 않는다. 저장된 값이 어제 것이면 버린다. (Task 4 저장 테스트)
|
||||||
|
5. 폭 240px·긴 한마디, 그리고 밝은·어두운 바탕 → 카드가 정해진 높이를 넘지 않고, 글자가 바탕에 묻히지 않는다. (Task 5 화면 확인)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 파일 구조 (바뀐 설계 기준)
|
||||||
|
|
||||||
|
| 파일 | 상태 | 맡는 일 |
|
||||||
|
|---|---|---|
|
||||||
|
| `backend/services/embed_referer.py` | Task 4 (`embed_access.py` 에서 이름 바꿈) | 순수 함수: 호스트 다듬기, `Referer` 에서 집계할 호스트 꺼내기 |
|
||||||
|
| `backend/tests/test_embed_referer.py` | Task 4 (`test_embed_access.py` 에서) | 위 함수 테스트 |
|
||||||
|
| `backend/postgres-init/init.sql`, `backend/common/database/model/models.py` | Task 4 가 `widget_site` 삭제 | 표 `widget_view_daily` 만 남김 |
|
||||||
|
| `backend/crud/widget_crud.py` | Task 4 가 줄임 | 노출 수 더하기·합계 |
|
||||||
|
| `backend/router/v1/admin/widget.py`, `protocol.py` | Task 4 가 바꿈 | `GET /v1/admin/widget/views` 하나 |
|
||||||
|
| `backend/services/embed_service.py`, `backend/router/v1/embed/embed.py` | Task 4 가 바꿈 | 카드 데이터(5분 저장)·HTML, 노출 집계(하루 상한) |
|
||||||
|
| `backend/seed/region_path.json`, `backend/scripts/gen_region_pages.py` | 완료 | 지역 코드 → 주소 이름 |
|
||||||
|
| `backend/tests/test_embed.py`, `test_widget_admin.py`, `conftest.py` | Task 4 가 바꿈 | 테스트 |
|
||||||
|
| `frontend/public/embed/card.js`, `card.css` | Task 5 | 카드를 그리는 코드(군산각에서 옮김), 배경 3종 |
|
||||||
|
| `frontend/nginx.conf` | Task 5 | `/embed/card` → 백엔드, `/embed/` 정적 파일 캐시 |
|
||||||
|
| `frontend/src/lib/embedWidget.ts`, `frontend/tests/embedWidget.test.mjs` | Task 6 | 순수 함수: iframe 주소·붙이는 코드 만들기 |
|
||||||
|
| `frontend/src/b/WidgetPage.tsx`, `frontend/src/App.tsx` | Task 6 | 사용 방법 페이지와 경로 |
|
||||||
|
| `shared/lib/analytics.ts`, `docs/이벤트_추적.md` | Task 6 | 이벤트 3개 |
|
||||||
|
| `docs/위젯_운영.md`, `docs/서비스_동작_안내.md`, `TODO.md` | Task 7 | 운영 문서, 남은 일 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 0: 시작 전 확인 — 완료
|
||||||
|
|
||||||
|
브랜치 `feat/embed-widget` 생성, 테스트 환경 확인, 군산각 원본 받기(저장소 밖 임시 폴더).
|
||||||
|
|
||||||
|
### Task 1: 접근 규칙 (순수 함수) — 완료 (Task 4 가 일부를 걷어 낸다)
|
||||||
|
|
||||||
|
`backend/services/embed_access.py`: `UNKNOWN_HOST`, `normalize_host`, `Access`, `classify`, `frame_ancestors`.
|
||||||
|
|
||||||
|
### Task 2: 등록 표와 관리자 API — 완료 (Task 4 가 일부를 걷어 낸다)
|
||||||
|
|
||||||
|
표 `widget_site`·`widget_view_daily`, `WidgetCRUD`, `/v1/admin/widget/sites` 4개.
|
||||||
|
|
||||||
|
### Task 3: 카드 응답 (`GET /v1/embed/card`) — 완료, 확인 지점 ① 보고함 (Task 4 가 일부를 바꾼다)
|
||||||
|
|
||||||
|
`backend/services/embed_service.py`(`region_path`, `card_link`, `card_data`, `render_card`, `render_notice`, `render_quiet`, `allowed_hosts`, `EmbedService.card`), `backend/router/v1/embed/embed.py`, `backend/seed/region_path.json`.
|
||||||
|
|
||||||
|
### Task 4: 완전 오픈으로 바꾸기
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Rename: `backend/services/embed_access.py` → `backend/services/embed_referer.py`, `backend/tests/test_embed_access.py` → `backend/tests/test_embed_referer.py`
|
||||||
|
- Modify: `backend/postgres-init/init.sql`, `backend/common/database/model/models.py`, `backend/crud/widget_crud.py`, `backend/router/v1/admin/widget.py`, `backend/router/v1/admin/protocol.py`, `backend/services/embed_service.py`, `backend/router/v1/embed/embed.py`, `backend/tests/conftest.py`(`_VOLATILE` 에서 `widget_site` 빼기)
|
||||||
|
- Test: `backend/tests/test_embed_referer.py`, `backend/tests/test_widget_admin.py`, `backend/tests/test_embed.py`
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: 지금 있는 Task 1~3 코드, `FeedService.feed`, `WeatherService.today`, `settings.public_base_url`
|
||||||
|
- Produces:
|
||||||
|
- `embed_referer.py`
|
||||||
|
- `UNKNOWN_HOST = "(알 수 없음)"`, `OTHER_HOST = "(기타)"`
|
||||||
|
- `normalize_host(raw: str) -> Optional[str]` — 지금 것 그대로 + 전체 253자·라벨 63자를 넘으면 `None`
|
||||||
|
- `view_host(referer: Optional[str], own_hosts: frozenset[str]) -> Optional[str]` — 집계할 호스트. 날씨각 자신이면 `None`(세지 않음)
|
||||||
|
- 없앰: `Access`, `classify`, `frame_ancestors`
|
||||||
|
- 표: `widget_site` 와 모델 `WidgetSite` 를 지운다. `widget_view_daily` 는 그대로다(주석의 '등록 호스트'는 '부른 사이트 호스트, `(알 수 없음)`, `(기타)`'로 고친다).
|
||||||
|
- `WidgetCRUD`: `add_view(s, day, host, kind)`, `views_since(s, since) -> dict[str, int]` 만 남긴다.
|
||||||
|
- 관리자 API: `/v1/admin/widget/sites` 4개와 그 요청·응답 틀을 지우고 하나를 만든다.
|
||||||
|
- `GET /v1/admin/widget/views` → `Res_WidgetViews { items: list[WidgetViewData], total_7d: int, total_30d: int }`, `WidgetViewData { host: str, views_7d: int, views_30d: int }`. `items` 는 `views_30d` 많은 순(같으면 호스트 이름순). 7일·30일은 오늘을 포함한 한국 날짜 기준이다.
|
||||||
|
- `embed_service.py`
|
||||||
|
- `KINDS = ("side", "home")`, `BGS = ("sky", "light", "dark")`, `ASSET_VERSION`
|
||||||
|
- `DAILY_HOST_CAP = 500`, `CARD_TTL_SEC = 300`
|
||||||
|
- `region_path`, `card_link`, `render_quiet` 는 그대로
|
||||||
|
- `card_data(feed, today, name, now) -> Optional[dict]` — 지금 것에서 `link` 를 뺀 값(저장하려고). 조건은 그대로다.
|
||||||
|
- `render_card(kind: str, bg: str, data: dict, link: str) -> str` — 상자 클래스 `wx wx-{kind} wx-bg-{bg}`. `#wx-data` JSON 에는 `data` 에 `link` 를 더한 값을 넣는다.
|
||||||
|
- `async count_host(host: str) -> str` — 하루 상한. `UNKNOWN_HOST` 는 그대로 돌려준다. 그 밖에는 Redis 집합 `widget:view-hosts:<한국 날짜>`(2일 뒤 만료)에 이미 있으면 그대로, 없고 크기가 `DAILY_HOST_CAP` 미만이면 넣고 그대로, 아니면 `OTHER_HOST`. Redis 오류는 로그를 남기고 `OTHER_HOST`.
|
||||||
|
- 카드 데이터 저장: Redis `widget:card:<지역코드>` 에 `card_data` 결과를 JSON 으로 `CARD_TTL_SEC` 초 저장한다. 읽을 때 `today.day` 가 오늘(한국 날짜)이 아니면 버리고 다시 만든다. `None`(못 만든 경우)은 저장하지 않는다. Redis 오류·깨진 값은 로그를 남기고 새로 만든다.
|
||||||
|
- `EmbedService.card(self, region_code: str, kind: str, bg: str, referer: Optional[str], host: str) -> tuple[int, str]` → `(상태 코드, HTML)`
|
||||||
|
- 없앰: `HOSTS_KEY`, `forget_hosts`, `allowed_hosts`, `render_notice`, CSP 값
|
||||||
|
- 라우트 `GET /v1/embed/card?region=&type=&bg=` — `bg` 기본값 `sky`. 헤더는 `Cache-Control: no-store`, `X-Robots-Tag: noindex` 둘뿐이다.
|
||||||
|
|
||||||
|
`view_host` 규칙: `Referer` 가 없거나 비었으면 `UNKNOWN_HOST`. `호스트[:포트]`(소문자)가 `own_hosts` 에 있으면 `None`. 스킴이 `http`·`https` 이고 호스트 이름(포트 뺌)이 `normalize_host` 를 통과하면 그 값. 그 밖에는 `UNKNOWN_HOST`.
|
||||||
|
|
||||||
|
`card()` 의 순서:
|
||||||
|
|
||||||
|
| 순서 | 조건 | 결과 | 노출 집계 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | `region` 이 숫자 10자리가 아니거나 `type` 이 `KINDS` 밖이거나 `bg` 가 `BGS` 밖 | `(404, render_quiet("/"))` | 안 함 |
|
||||||
|
| 2 | 없는 지역 | `(404, render_quiet(link))` | 안 함 |
|
||||||
|
| 3 | 피드·오늘 날씨 오류, `card_data` 가 `None`, 예상 못 한 예외 | `(200, render_quiet(link))` | 안 함 |
|
||||||
|
| 4 | 그 밖 | `(200, render_card(kind, bg, data, link))` | `view_host` 가 `None` 이 아니면 `count_host` 를 거친 값으로 |
|
||||||
|
|
||||||
|
`link` 는 `card_link(region_path(지역코드), campaign)` 이고 `campaign` 은 `view_host` 결과가 호스트면 그 호스트, `UNKNOWN_HOST` 면 `unknown`, `None` 이면 `preview` 다. 집계가 실패해도 로그만 남기고 카드는 돌려준다.
|
||||||
|
|
||||||
|
- [ ] **Step 1: 테스트를 바뀐 설계에 맞게 고친다(먼저 실패를 본다).**
|
||||||
|
- `test_embed_referer.py` (지금의 `normalize_host` 테스트 2개는 남기고, `classify`·`frame_ancestors` 테스트는 지운다)
|
||||||
|
```python
|
||||||
|
OWN = frozenset({"weather.o2o.kr", "localhost:8080"})
|
||||||
|
|
||||||
|
def test_normalize_host_length_limits():
|
||||||
|
assert normalize_host("a" * 63 + ".example.com") == "a" * 63 + ".example.com"
|
||||||
|
assert normalize_host("a" * 64 + ".example.com") is None
|
||||||
|
ok = ".".join(["a" * 63, "b" * 63, "c" * 63, "d" * 58]) + ".kr" # 253자
|
||||||
|
assert len(ok) == 253 and normalize_host(ok) == ok
|
||||||
|
assert normalize_host(".".join(["a" * 63, "b" * 63, "c" * 63, "d" * 59]) + ".kr") is None # 254자
|
||||||
|
|
||||||
|
def test_view_host_takes_site_host():
|
||||||
|
assert view_host("https://co.webforai.kr/s/stay", OWN) == "co.webforai.kr"
|
||||||
|
assert view_host("http://Blog.Example.com:8080/a", OWN) == "blog.example.com"
|
||||||
|
|
||||||
|
def test_view_host_self_is_not_counted():
|
||||||
|
assert view_host("https://weather.o2o.kr/widget", OWN) is None
|
||||||
|
assert view_host("http://localhost:8080/widget", OWN) is None
|
||||||
|
|
||||||
|
def test_view_host_unknown():
|
||||||
|
for bad in (None, "", "null", "about:blank", "android-app://com.example/", "https://", "not a url",
|
||||||
|
"https://1.2.3.4/", "https://a.com; x/", "https://" + "a" * 300 + ".com/"):
|
||||||
|
assert view_host(bad, OWN) == UNKNOWN_HOST, bad
|
||||||
|
```
|
||||||
|
- `test_widget_admin.py` (전부 새로): `test_widget_views_need_key`(키 없이·틀린 키로 401) / `test_widget_views_sums_by_host` — `WidgetCRUD.add_view` 로 오늘 `co.webforai.kr`/`side` 2번, 6일 전 `co.webforai.kr`/`home` 1번, 7일 전 `co.webforai.kr`/`side` 1번, 오늘 `blog.example.com`/`side` 1번, 오늘 `UNKNOWN_HOST`/`side` 1번 → `items[0] == {"host": "co.webforai.kr", "views_7d": 3, "views_30d": 4}`, 나머지 두 호스트는 각각 1·1, `total_7d == 5`, `total_30d == 6`.
|
||||||
|
- `test_embed.py`: 순수 함수 테스트(`region_path`, `card_link`, `card_data`, `render_card` 이스케이프·모양)는 시그니처만 맞춰 남긴다. API 테스트는 아래로 바꾼다(`offline` 픽스처, 지역 `1114000000`).
|
||||||
|
- `test_any_site_gets_card`: `Referer: https://evil.example/x` → 200, 본문에 `id="wx-data"`·`wx-side`·`wx-bg-sky`, `content-security-policy`·`x-frame-options`·`set-cookie` 헤더 없음, `cache-control == "no-store"`, 집계 `{"evil.example": 1}`.
|
||||||
|
- `test_bg_and_kind_classes`: `type=home&bg=dark` → 본문에 `wx-home`, `wx-bg-dark`.
|
||||||
|
- `test_no_referer_counts_unknown`: 집계 `{"(알 수 없음)": 1}`, 링크에 `utm_campaign=unknown`.
|
||||||
|
- `test_self_preview_not_counted`: `Referer: http://test/widget` → 200 카드, 집계 `{}`, 링크에 `utm_campaign=preview`.
|
||||||
|
- `test_daily_host_cap`: `DAILY_HOST_CAP` 을 2 로 바꾸고 `a.example`, `b.example`, `c.example`, 다시 `a.example` 순서로 부름 → 집계 `{"a.example": 2, "b.example": 1, "(기타)": 1}`.
|
||||||
|
- `test_bad_input_is_quiet_html`: `region=abc`, `region=9999999999`, `type=big`, `bg=pink` → 404, `text/html`, `wx-data` 없음.
|
||||||
|
- `test_feed_failure_is_quiet`, `test_feed_exception_is_quiet`: 지금 것 유지(헤더 단언에서 CSP 는 뺀다). 집계 0.
|
||||||
|
- `test_card_data_is_cached`: 같은 지역을 두 번 부르면 `FeedService.feed` 는 한 번만 불린다(부른 횟수를 세는 대역).
|
||||||
|
- `test_stale_cached_card_is_rebuilt`: Redis `widget:card:1114000000` 에 `today.day` 가 어제인 값을 넣어 둠 → 200 카드, `FeedService.feed` 가 불린다.
|
||||||
|
- `test_broken_cached_card_is_rebuilt`: 같은 키에 `"not json{"` → 200 카드.
|
||||||
|
- `test_count_failure_still_serves_card`: `WidgetCRUD.add_view` 가 예외 → 200 카드.
|
||||||
|
- 지운다: 등록·미등록·끄기·`Referer` 없음 허용 목록·등록 목록 DB 실패·깨진 호스트 캐시 테스트.
|
||||||
|
- [ ] **Step 2:** 위젯 테스트 3개 파일을 돌려 실패를 확인한다.
|
||||||
|
- [ ] **Step 3:** 구현한다. 파일 이름 바꾸기는 새 파일을 만들고 옛 파일을 지우는 것으로 한다(git 명령을 쓰지 않는다). `router.py` 의 `admin_widget_router`·`embed_router` 등록은 그대로 둔다. 걷어 낸 것의 흔적(안 쓰는 import, 죽은 함수)을 남기지 않는다.
|
||||||
|
- [ ] **Step 4:** 위젯 테스트 3개 파일 → PASS. 전체 테스트 한 번 → 원래 실패 2개 외에 실패가 없어야 한다.
|
||||||
|
|
||||||
|
### Task 5: 카드 화면 — 끝나면 확인 지점 ②
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `frontend/public/embed/card.js`, `frontend/public/embed/card.css`
|
||||||
|
- Modify: `frontend/nginx.conf`, `backend/services/embed_service.py`(`render_card` 의 상자 마크업), `backend/tests/test_embed.py`(마크업 단언)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: `render_card` 가 넣는 `#wx-data` JSON 과 상자 클래스 `wx wx-{side|home} wx-bg-{sky|light|dark}` (Task 4), 아이콘 `/icons/{sun,sun_cloud,cloud,rain,snow,moon}.webp`, 군산각 원본(임시 폴더의 `weather.js`, `style.css`, `page.html`)
|
||||||
|
- Produces: 모양별 iframe 높이 두 값(px) — Task 6 의 `EMBED_HEIGHT` 가 쓴다.
|
||||||
|
|
||||||
|
이 Task 는 두 번에 나눠 한다. 5-A 는 작업자가, 시안 고르기는 컨트롤러가 사용자와 하고, 5-B 는 고른 시안으로 작업자가 한다.
|
||||||
|
|
||||||
|
**5-A: 군산각 그대로(`sky`) + nginx**
|
||||||
|
|
||||||
|
- [ ] **Step 1: `card.css`.** 군산각 `style.css` 에서 선택자에 `.wx` 가 들어간 규칙과 그 규칙이 쓰는 `@keyframes`, 화면에서만 숨기는 `.vh`, `.icon` 을 골라 줄을 풀어 옮긴다. 규칙이 기대는 변수(`--ink`, `--font`, `--hair`, `--sea-deep`, `--g0`, `--ease-out`, `--focus`, `--d`, `--f` 와 `--wx-*`)는 군산각 `:root` 값을 찾아 `card.css` 맨 위에 적는다. 더하는 것: `html, body { margin: 0; height: 100%; background: transparent; overflow: hidden }`, 상자가 iframe 을 꽉 채우게, 한마디·요약 문장 줄 수 제한(`-webkit-line-clamp`).
|
||||||
|
- [ ] **Step 2: `card.js`.** 군산각 `weather.js` 를 옮기며 아래만 바꾼다. 파일 맨 위 주석에 원본 주소와 바꾼 곳을 적는다.
|
||||||
|
- `fetch` 두 번 대신 `#wx-data` 의 JSON 을 읽어 `usable(feed, today)` 에 `{hero}`, `today` 로 넘긴다. 8초 제한·`ask()`·`data-wx`/`data-wx-day` 는 뺀다.
|
||||||
|
- 문구(`score: '지금 날씨 점수'`, 칸 이름 `아침·낮·저녁·밤·지금`, `자세히 보기`, 하늘 이름)는 `data-wx-w` 대신 파일 안 상수로 둔다. 한국어 갈래만 남긴다.
|
||||||
|
- `ICONS = "/icons/"`. 일출·일몰(`[data-sd-days]`) 부분을 뺀다.
|
||||||
|
- 글꼴 불러오기, 화면 밖에서 멈추기(`is-off`), 그리다 실패하면 `is-failed` 는 그대로 둔다.
|
||||||
|
- [ ] **Step 3: 마크업.** `render_card` 의 상자를 군산각 첫 화면의 `.wx.wx-side`, `.wx.wx-home` 두 상자와 같은 구조로 채운다(제목 `{name} 날씨`, 날짜 칸, 링크 `href=link` `target="_blank" rel="noopener"`, 본문 칸). `test_embed.py` 에 `test_card_markup`: 본문에 `class="wx-go"`, `target="_blank"`, `data-wx-b`, 제목 글자, `/embed/card.js?v=` 가 있다.
|
||||||
|
- [ ] **Step 4: nginx.** `location /v1/` 앞에 아래를 넣는다(본보기: 같은 파일의 지역 검색 페이지 블록).
|
||||||
|
```nginx
|
||||||
|
# 다른 사이트에 붙이는 날씨 카드: 백엔드가 HTML 을 만든다 (Referer 는 노출 집계에 쓴다)
|
||||||
|
location = /embed/card {
|
||||||
|
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||||
|
set $api http://backend:9800;
|
||||||
|
proxy_pass $api/v1/embed/card$is_args$args;
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_connect_timeout 3s;
|
||||||
|
proxy_read_timeout 20s;
|
||||||
|
}
|
||||||
|
# 카드가 쓰는 정적 파일. 이름에 해시가 없어 짧게 캐시하고, 고치면 주소의 ?v= 를 올린다
|
||||||
|
location /embed/ {
|
||||||
|
add_header Cache-Control "public, max-age=3600";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- [ ] **Step 5: 띄워 본다.** `docker compose up -d --build backend frontend` 뒤 `http://localhost:8080/embed/card?region=5213000000&type=side`, `…&type=home`. `curl -s -D - -o /dev/null "http://localhost:8080/embed/card?region=5213000000&type=side"` 응답에 `content-security-policy`·`x-frame-options`·`set-cookie` 가 없고 `cache-control: no-store` 가 있다.
|
||||||
|
- [ ] **Step 6: 경우별 모양.** 임시 폴더의 스크립트로 `render_card` 에 가짜 데이터를 넣어 HTML 을 만든다(`<base href="http://localhost:8080/">` 추가): 아침·낮·저녁·밤 × 맑음·비·눈, 달 보이는 밤, 한마디 40자, 상태 줄 4개. 폭 240·320·440px(좁은 형), 320·440·720px(넓은 형)에서 열어 넘침·스크롤바가 없는지 본다. 모양별 높이를 정한다(모든 폭에서 내용이 들어가는 가장 작은 값).
|
||||||
|
- [ ] **Step 7:** 위젯 테스트 3개 파일 → PASS.
|
||||||
|
|
||||||
|
**시안 고르기 (컨트롤러 + 사용자)**
|
||||||
|
|
||||||
|
- [ ] **Step 8:** 밝은 바탕용·어두운 바탕용 카드를 방향이 서로 다른 시안 4개로 보여 주고 고르게 한다. 시안마다 정할 것: 카드에 바탕색을 깔지(테두리만 둘지), 해·달·구름·별·비·눈을 어디까지 남길지, 날씨 점수 동그라미 색. 흰 바탕과 검은 바탕의 시험 페이지 위에 놓은 모습으로 보여 준다.
|
||||||
|
|
||||||
|
**5-B: 밝은 바탕용·어두운 바탕용**
|
||||||
|
|
||||||
|
- [ ] **Step 9:** 고른 시안대로 `card.css` 에 `.wx-bg-light`, `.wx-bg-dark` 규칙을 더한다(`card.js` 는 배경을 몰라도 되게 CSS 로만 가른다. 안 되면 보고한다). `ASSET_VERSION` 을 올린다.
|
||||||
|
- [ ] **Step 10:** Step 6 의 경우들을 `bg=light`(흰 바탕 시험 페이지), `bg=dark`(검은 바탕 시험 페이지)로 다시 본다. 글자와 바탕의 명도 대비가 본문 기준 4.5:1 이상인지 잰다. 높이는 `sky` 와 같아야 한다.
|
||||||
|
- [ ] **Step 11: 다른 주소에서 붙여 본다.** 임시 폴더에 iframe 3줄(배경 3종)짜리 HTML 을 두고 `python -m http.server 8090` 으로 연다 → 세 카드가 모두 보인다. 관리자 API 로 `localhost` 가 아닌 `(알 수 없음)` 으로 집계됐는지 본다(`localhost` 는 도메인 꼴이 아니다).
|
||||||
|
- [ ] **Step 12: 확인 지점 ②** — 좁은 형·넓은 형 × 배경 3종 화면 캡처, 정한 높이, Task 4·5 테스트 결과를 사용자에게 보고하고 확인받는다.
|
||||||
|
|
||||||
|
### Task 6: 사용 방법 페이지 — 끝나면 확인 지점 ③
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `frontend/src/lib/embedWidget.ts`, `frontend/tests/embedWidget.test.mjs`, `frontend/src/b/WidgetPage.tsx`
|
||||||
|
- Modify: `frontend/src/App.tsx`, `shared/lib/analytics.ts`, `docs/이벤트_추적.md`
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: Task 5 의 높이 두 값, `listRegionsOptions`(지역 목록), `useRegion`(지금 지역), `SITE_URL`, `track`
|
||||||
|
- Produces:
|
||||||
|
- `embedWidget.ts`
|
||||||
|
- `type EmbedKind = 'side' | 'home'`, `type EmbedBg = 'sky' | 'light' | 'dark'`
|
||||||
|
- `EMBED_KIND_LABEL = { side: '좁은 형', home: '넓은 형' }`, `EMBED_BG_LABEL = { sky: '하늘', light: '밝은 바탕용', dark: '어두운 바탕용' }`(화면 문구는 시안 때 확정)
|
||||||
|
- 크기 범위(모두 `Record<EmbedKind, number>`, px. 2026-11-26 사용자 결정): `EMBED_HEIGHT = { side: 245, home: 400 }`(전부 보이는 최소 높이이자 기본 높이), `EMBED_MAX_HEIGHT = { side: 320, home: 520 }`, `EMBED_MIN_WIDTH = { side: 220, home: 280 }`(이름이 가장 긴 지역 '창원시 마산합포구'로도 제목·버튼이 다 보이는 폭), `EMBED_MAX_WIDTH = { side: 440, home: 720 }`
|
||||||
|
- iframe 의 `style`(넷 다 코드에 넣어 붙인 사이트의 다른 스타일에 밀리지 않게 한다): 좁은 형 `border:0;width:100%;height:245px;min-width:220px;max-width:440px;min-height:245px;max-height:320px`, 넓은 형은 같은 차례에 넓은 형 값 + 끝에 `;border-radius:28px`. 넓은 형의 `border-radius` 는 붙인 사이트가 `color-scheme: dark` 를 선언했을 때 둥근 모서리 밖이 희게 칠해지는 것을 잘라 낸다(2026-11-26 캡처로 확인). 좁은 형은 모서리가 각져서 필요 없다.
|
||||||
|
- `embedSrc(origin: string, region: string, kind: EmbedKind, bg: EmbedBg): string`
|
||||||
|
- `embedCode(p: { origin: string; region: string; regionName: string; kind: EmbedKind; bg: EmbedBg }): string`
|
||||||
|
- 이벤트: `widget_guide_view`(값 없음, `위젯_안내_보기`), `widget_option_select`(`{ option: 'region' | 'kind' | 'bg'; value: string }`, `위젯_옵션_고름`), `widget_code_copy`(`{ kind: EmbedKind; bg: EmbedBg; region: string }`, `위젯_코드_복사`). 값 없는 이벤트의 타입은 `shared/lib/analytics.ts` 의 기존 값 없는 이벤트를 따른다.
|
||||||
|
|
||||||
|
- [ ] **Step 1: 실패하는 테스트를 쓴다** (본보기: `frontend/tests/linkShare.test.mjs`)
|
||||||
|
|
||||||
|
```js
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import { EMBED_HEIGHT, EMBED_MAX_HEIGHT, EMBED_MAX_WIDTH, EMBED_MIN_WIDTH, embedCode, embedSrc } from '../src/lib/embedWidget.ts'
|
||||||
|
|
||||||
|
const ORIGIN = 'https://weather.o2o.kr'
|
||||||
|
|
||||||
|
test('iframe 주소', () => {
|
||||||
|
assert.equal(embedSrc(ORIGIN, '5213000000', 'side', 'sky'), 'https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('모양별 크기', () => {
|
||||||
|
assert.deepEqual(EMBED_HEIGHT, { side: 245, home: 400 })
|
||||||
|
assert.deepEqual(EMBED_MAX_HEIGHT, { side: 320, home: 520 })
|
||||||
|
assert.deepEqual(EMBED_MIN_WIDTH, { side: 220, home: 280 })
|
||||||
|
assert.deepEqual(EMBED_MAX_WIDTH, { side: 440, home: 720 })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('붙이는 코드(넓은 형): 배경·크기 범위·둥근 모서리·referrerpolicy 가 들어간다', () => {
|
||||||
|
assert.equal(
|
||||||
|
embedCode({ origin: ORIGIN, region: '5213000000', regionName: '군산시', kind: 'home', bg: 'dark' }),
|
||||||
|
'<iframe src="https://weather.o2o.kr/embed/card?region=5213000000&type=home&bg=dark" title="군산시 날씨 - 날씨각" width="100%" height="400" style="border:0;width:100%;height:400px;min-width:280px;max-width:720px;min-height:400px;max-height:520px;border-radius:28px" loading="lazy" referrerpolicy="origin"></iframe>',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('붙이는 코드(좁은 형): 크기 범위, 둥근 모서리 없음', () => {
|
||||||
|
assert.equal(
|
||||||
|
embedCode({ origin: ORIGIN, region: '5213000000', regionName: '군산시', kind: 'side', bg: 'sky' }),
|
||||||
|
'<iframe src="https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky" title="군산시 날씨 - 날씨각" width="100%" height="245" style="border:0;width:100%;height:245px;min-width:220px;max-width:440px;min-height:245px;max-height:320px" loading="lazy" referrerpolicy="origin"></iframe>',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('붙이는 코드: 지역 이름의 따옴표가 속성을 깨지 않는다', () => {
|
||||||
|
assert.ok(embedCode({ origin: ORIGIN, region: '5213000000', regionName: '가"짜', kind: 'side', bg: 'sky' }).includes('title="가"짜 날씨 - 날씨각"'))
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2:** `cd frontend && npm test` → 새 테스트 FAIL
|
||||||
|
- [ ] **Step 3:** `embedWidget.ts` 를 구현한다(React·브라우저 전용 API 없음). `npm test` → PASS
|
||||||
|
- [ ] **Step 4: 시안 4개 (컨트롤러 + 사용자).** 사용 방법 페이지의 방향이 서로 다른 시안 4개를 보여 주고 고르게 한다. 들어갈 것은 설계서 5.5 그대로다: 한두 줄 소개, 지역·모양·배경 고르기, 미리보기(iframe), 코드와 '복사', 이용 조건 세 줄. 화면 문구도 이때 확정한다.
|
||||||
|
- [ ] **Step 5: 고른 시안으로 `WidgetPage.tsx` 를 만든다** (본보기: `frontend/src/b/TypePage.tsx` 의 뒤로 가기 머리줄·버튼 모양).
|
||||||
|
- 처음 지역은 지금 날씨각 지역(`useRegion`), 모양은 `side`, 배경은 `sky`.
|
||||||
|
- 미리보기 iframe 은 `embedSrc(window.location.origin, …)`(도커에서도 보이게), 높이는 `EMBED_HEIGHT`, 넓은 형은 `border-radius:28px`. 미리보기 뒤 바탕은 배경이 `light` 면 흰색, `dark` 면 어두운 색으로 바꾼다. 코드 상자는 `embedCode({ origin: SITE_URL, … })`.
|
||||||
|
- 고른 시안은 2번 "미리보기 먼저"(2026-11-26 사용자 결정): 맨 위에 미리보기, 그 아래 지역·모양·배경을 한 줄씩, 그 아래 '코드 복사' 버튼과 코드, 안내 문구.
|
||||||
|
- 코드 아래 안내: 폭은 자리에 맞춰 자동(`EMBED_MIN_WIDTH`~`EMBED_MAX_WIDTH`), 높이는 기본 `EMBED_HEIGHT`·최대 `EMBED_MAX_HEIGHT`, "코드의 style 은 지우지 말아 주세요", 이용 조건 세 줄.
|
||||||
|
- 카드 쪽 작은 변경(2026-11-26 사용자 결정): 넓은 형의 날짜(`.wx-dt`)는 통째로 들어갈 자리가 없으면 잘린 채(`1…`) 두지 않고 숨긴다. `frontend/public/embed/card.js`·`card.css` 를 고치고 `ASSET_VERSION` 을 `"3"` 으로 올린다.
|
||||||
|
- 고르는 값을 바꾸면 `track('widget_option_select', { option, value })`. 지역의 `value` 는 지역 코드다.
|
||||||
|
- '복사' → 클립보드에 넣고 `track('widget_code_copy', { kind, bg, region })`. 클립보드를 못 쓰면 코드를 선택 상태로 만들어 직접 복사하게 한다.
|
||||||
|
- 열릴 때 한 번 `track('widget_guide_view', …)`.
|
||||||
|
- `App.tsx` 에 `<Route path="widget" element={<WidgetPage />} />`. 탭·아이콘 줄·`vite.config.ts` 의 `PAGES`(사이트맵)에는 넣지 않는다.
|
||||||
|
- [ ] **Step 6: 이벤트.** `shared/lib/analytics.ts` 의 `Events`·`GA_NAME` 에 3개를 더하고 `docs/이벤트_추적.md` 표에 3행을 더한다.
|
||||||
|
- [ ] **Step 7:** `cd frontend && npm run lint && npm test && npm run build` → 모두 통과.
|
||||||
|
- [ ] **Step 8: 띄워 본다.** `docker compose up -d --build frontend` 뒤 `http://localhost:8080/widget`: 지역·모양·배경을 바꾸면 미리보기와 코드가 같이 바뀐다 / 복사한 코드가 화면의 코드와 같다 / 복사한 코드를 임시 폴더의 시험 HTML 에 붙이면 카드가 보인다 / 폭 360px 에서 넘치지 않는다.
|
||||||
|
- [ ] **Step 9: 확인 지점 ③** — 화면 캡처와 검증 결과, 넣은 이벤트 이름 3개를 보고한다.
|
||||||
|
|
||||||
|
### Task 7: 문서와 전체 검증 — 확인 지점 ④
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `docs/위젯_운영.md`
|
||||||
|
- Modify: `docs/서비스_동작_안내.md`, `TODO.md`
|
||||||
|
|
||||||
|
- [ ] **Step 1: `docs/위젯_운영.md`** — 아래 차례로 쓴다. 명령 예시의 키는 `$ADMIN_API_KEY` 로 적고 실제 값을 쓰지 않는다.
|
||||||
|
1. 위젯이 무엇이고 어디서 코드를 받는지(`/widget`), 붙이는 코드 예시
|
||||||
|
2. 노출 수 보는 법: `GET /v1/admin/widget/views` `curl` 예시(`X-Admin-Key` 헤더), 응답 읽는 법(`(알 수 없음)`, `(기타)` 의 뜻, 사이트 주소는 속일 수 있다는 점), 위젯 유입은 GA 에서 `utm_source=widget`
|
||||||
|
3. 붙이는 쪽이 알아야 할 것: 외부 iframe 을 막는 보안 설정(CSP `frame-src`)이 있으면 `https://weather.o2o.kr` 허용, `referrerpolicy="origin"` 은 집계용이라 빼도 카드는 보임
|
||||||
|
4. 카드 파일을 고쳤을 때: `embed_service.py` 의 `ASSET_VERSION` 올리기
|
||||||
|
- [ ] **Step 2:** `docs/서비스_동작_안내.md` 에 위젯 한 단락. `TODO.md` 에 남은 일 한 행: 군산각·스테이머뭄 기존 카드 교체, 높이 자동 스크립트, 문제 사이트 차단 기능, 배포 뒤 확인.
|
||||||
|
- [ ] **Step 3: 전체 검증.** 백엔드 전체 테스트 / `cd frontend && npm run lint && npm test && npm run build`. 실패가 남으면 '완료'라고 하지 않고 명령과 결과를 그대로 적는다.
|
||||||
|
- [ ] **Step 4: 완료 보고** — 변경 내용(파일별 한 줄), 검증 결과(명령·통과 여부·넣은 GA 이벤트 이름), 남은 이슈. 남은 이슈에는 반드시 넣는다: 운영 배포 뒤 확인(다른 사이트에서 카드가 보이는지, 집계에 그 사이트 주소가 남는지, 쿠키가 없는지), 저장소 `CLAUDE.md` 의 `Events` 위치 안내가 실제(`shared/lib/analytics.ts`)와 다름.
|
||||||
|
- [ ] **Step 5:** 커밋 승인을 받는다(`feat: 다른 사이트에 붙이는 날씨각 위젯 — 누구나 붙이는 카드(/embed/card, 배경 3종)와 사용 방법 페이지(/widget)`). 푸시·PR·배포는 따로 승인받는다.
|
||||||
|
- [ ] **Step 6:** 사용자가 변경 내용을 이해했는지 확인하는 퀴즈 2~3문제를 낸다(개인 지침).
|
||||||
|
|
||||||
|
### Task 6.5: 로딩(토끼)·실패 처리 — 2026-11-26 사용자 결정
|
||||||
|
|
||||||
|
토끼 로딩 화면, 실패 문구 `날씨각에서 날씨 보기 ›` 로 통일, 8초 지나도 안 그려지면 링크(CSS 만), 조용한 화면 색을 배경에 맞춤(`render_quiet(link, bg)`), 카드 만들기 5초 제한(`CARD_BUILD_TIMEOUT_SEC`), nginx 502/503/504 → `frontend/public/embed/quiet.html`, `ASSET_VERSION` "5". 자세한 지시는 작업 기록(`.superpowers/sdd/…/task-6b-report.md`)에.
|
||||||
|
|
||||||
|
### Task 6.6: 스크립트로 붙이기 — 2026-11-26 사용자 결정
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `frontend/public/embed/widget.js`, `frontend/tests/embedLoader.test.mjs`
|
||||||
|
- Modify: `frontend/src/lib/embedWidget.ts`, `frontend/tests/embedWidget.test.mjs`, `frontend/src/b/WidgetPage.tsx`, `shared/lib/analytics.ts`, `docs/이벤트_추적.md`
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- `widget.js`(순수 JS, ES5, 즉시 실행 함수로 감싸 전역 이름을 남기지 않음): 문서에서 `a.nalssigak-weather[data-region]` 을 찾아, 아직 처리하지 않은 것마다 카드 iframe 을 만들어 그 링크 자리에 넣는다. 값이 틀리면(지역이 숫자 10자리가 아님, `data-type`·`data-bg` 가 정해진 값이 아님) 그 링크는 그대로 둔다. `data-type` 기본 `side`, `data-bg` 기본 `sky`. iframe 의 주소·`title`·`width`·`height`·`style`·`loading`·`referrerpolicy` 는 `embedCode` 가 만드는 iframe 과 같다(`title` 은 링크 글자). 날씨각 주소(origin)는 스크립트 자신의 주소에서 얻는다(로컬 도커에서도 동작). 문서가 다 읽히기 전에 실행돼도 동작하고, 두 번 실려도 카드가 두 번 생기지 않으며, 한 페이지에 여러 개 붙여도 된다. 쿠키·저장소·추가 요청·콘솔 출력이 없다.
|
||||||
|
- `embedWidget.ts`: `embedScript(p: { origin: string; region: string; regionName: string; regionPath: string | null; kind: EmbedKind; bg: EmbedBg }): string` — 위 설계서의 두 줄 코드. 링크 주소는 `regionPath` 가 있으면 `/today/{regionPath}`, 없으면 `/`, 뒤에 `?utm_source=widget&utm_medium=embed&utm_campaign=fallback`. 링크 글자는 `{regionName} 날씨 - 날씨각`(속성·본문 이스케이프).
|
||||||
|
- `widget_code_copy` 값에 `method: 'script' | 'iframe'` 를 더한다.
|
||||||
|
- 사용 방법 페이지: 코드 상자 위에 탭 두 개 `스크립트(권장)` / `iframe 코드`(처음은 스크립트). iframe 탭에는 `스크립트를 넣을 수 없는 곳이라면 이 코드를 쓰세요.` 와 `코드의 style은 지우지 말아 주세요.` 를 보이고, 스크립트 탭에서는 style 안내를 뺀다. 보안 설정 안내는 `카드가 안 보이면 사이트 보안 설정에서 weather.o2o.kr 을 허용해 주세요.` 그대로. 지역 주소 이름은 앱의 `ownPage(code)?.path`(`frontend/src/b/regionContext.ts`)로 얻는다.
|
||||||
|
|
||||||
|
**검증:** `embedLoader.test.mjs` 는 `widget.js` 를 node `vm` 에 가짜 문서(링크 요소 몇 개)와 함께 실행해, 만들어진 iframe 의 속성이 같은 값으로 만든 `embedCode` 의 iframe 속성과 같은지, 틀린 값의 링크는 그대로인지, 두 번 실행해도 iframe 이 하나인지 확인한다(크기 상수가 두 파일에서 어긋나지 않게 묶는 테스트). 도커에서 `/widget` 의 두 탭, 스크립트 코드를 8090 시험 페이지에 붙여 카드가 보이는지, `widget.js` 를 막았을 때 링크가 남는지 캡처로 확인.
|
||||||
|
|
||||||
|
**Task 6.6 에 더함 — 지역은 페이지 안에서만 (2026-11-26 사용자 결정, 1안):** 사용 방법 페이지의 `바꾸기 ›` 는 기존 지역 창을 "고르기만" 모드로 연다. `SheetState` 의 `{ type: 'region' }` 에 선택값 `pick?: { current: string; onPick: (r: RegionData) => void }` 를 더하고(창 상태는 방문 기록에 저장되지 않아 함수를 넣어도 된다 — `Sheets.tsx` 는 `history.state` 에 `sheet: true` 만 넣는다), `RegionSheet` 는 `pick` 이 있으면 `setRegion` 과 `region_change` 이벤트 대신 `onPick` 을 부르고, '지금 보는 곳' 표시는 `pick.current` 기준, 위치로 찾기 버튼과 로그인 줄은 숨긴다. 위젯 페이지는 지역을 자기 상태로 들고(처음 값은 앱 지역), 앱 지역이 나중에 바뀌어도 따라가지 않는다. `widget_option_select` 의 지역 이벤트는 이 페이지에서 고를 때만 보낸다(자동 위치 변경은 세지 않음).
|
||||||
|
|
||||||
|
**Task 6.6 에 더함 — 기본형도 둥근 모서리 (2026-11-26 사용자 결정):** 기본형 카드의 모서리를 상세형과 같은 28px 로 둥글게 한다. `card.css` 의 `:root .wx-side { border-radius: 0 }` 과 링크 덮개(`:root .wx.is-ready .wx-go::after { border-radius: 0 }`)를 상세형처럼 28px 로, 로딩·실패·조용한 화면도 같은 모서리. 붙이는 코드는 두 모양 모두 `style` 끝에 `;border-radius:28px`(색 설정을 어둡게 선언한 사이트에서 모서리 밖이 희게 칠해지는 것을 잘라 내는 이유가 이제 기본형에도 해당), `widget.js` 와 사용 방법 페이지 미리보기도 같게. `ASSET_VERSION` 을 올린다. 모서리에 머리줄 알약·아래 4칸 줄이 잘리지 않는지 캡처로 확인하고, 잘리면 여백을 바꾸지 말고 보고한다(높이 245px 유지).
|
||||||
|
|
||||||
|
### Task 6.7: 사용 방법 페이지로 들어오는 길 — 2026-11-26 사용자 결정(1·2안)
|
||||||
|
|
||||||
|
- **문의 창**(`frontend/src/b/Sheets.tsx` `ContactSheet`): 전화·이메일 아래에 `날씨 위젯 달기 ›` 버튼 하나. 누르면 창을 닫고 `/widget` 으로 간다(`navigate('/widget', { state: { from: 'contact' } })`). 안내 문구에 '날씨 위젯'을 더한다(예: `날씨에 맞춘 광고, 지역 축제·행사 소개, 날씨 위젯, 콘텐츠 협업 같은 제휴 문의를 받아요.` — 문구는 보고 때 확인).
|
||||||
|
- **검색 노출**: `frontend/vite.config.ts` 의 `PAGES` 에 `widget` 한 줄(제목 `날씨 위젯 · 내 사이트에 날씨 카드 달기 | 날씨각`, 설명·본문은 위젯이 무엇이고 무료로 바로 쓸 수 있다는 소개, 키워드 `날씨 위젯, 홈페이지 날씨, 날씨 퍼가기, 날씨 iframe`). 사이트맵에 저절로 들어간다(제외 목록에 해당하지 않음). 앞서 '메뉴·사이트맵에 넣지 않는다'로 정했던 것을 바꾸는 결정이다. 색인 페이지를 일부러 줄인 적이 있지만 이 한 장은 사용자가 정해 넣는다.
|
||||||
|
- **GA**: `widget_guide_view` 에 `from: 'contact' | 'direct'` 를 더한다(`location.state?.from === 'contact'` 이면 contact). `docs/이벤트_추적.md` 행 수정.
|
||||||
|
- 확인: `npm run build` 뒤 `dist/widget.html` 의 제목·설명·canonical, `dist/sitemap.xml` 에 `/widget`, 도커에서 문의 창 → 버튼 → 위젯 페이지.
|
||||||
|
|
||||||
|
### Task 6.8: 높이도 폭에 따라 (비율 유지) — 2026-11-26 사용자 결정
|
||||||
|
|
||||||
|
- 붙이는 iframe 의 `style` 을 `border:0;width:100%;height:auto;aspect-ratio:{비율};min-width:…;max-width:…;min-height:{기본 높이};max-height:{최대 높이};border-radius:28px` 로 바꾼다. 비율은 최대 폭 ÷ 최대 높이: 기본형 `11/8`(440/320), 상세형 `18/13`(720/520). 그러면 기본형은 폭 337px 까지 245px, 440px 에서 320px; 상세형은 폭 554px 까지 400px, 720px 에서 520px. `height` 속성(245·400)은 `aspect-ratio` 를 모르는 옛 브라우저용으로 남긴다 — 그 경우 `min-height` 가 기본 높이를 지킨다.
|
||||||
|
- `embedWidget.ts`(`EMBED_RATIO` 상수 추가, `embedStyle`), `widget.js`(같은 값), 테스트(`embedWidget.test.mjs`·`embedLoader.test.mjs` 기대 문자열), 사용 방법 페이지 미리보기 iframe 도 같은 규칙.
|
||||||
|
- 안내 문구: 두 탭 모두 `높이는 폭에 맞춰 {기본 높이}~{최대 높이}px 사이에서 자동으로 바뀌어요.` (스크립트 탭의 `높이는 {h}px이에요.`, iframe 탭의 `…늘릴 수 있어요.` 를 대체)
|
||||||
|
- 확인: 폭 220·300·337·380·440(기본형), 280·400·554·640·720(상세형)에서 iframe 높이가 위 값대로인지, 카드가 넘치지 않고 간격만 벌어지는지 배경 3종 캡처.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# 날씨 위젯 시간대 골라 보기 Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** 위젯 카드의 아침·낮·저녁·밤 칸을 누르면 그 시간대의 점수·하늘·한마디·요약을 보여 준다.
|
||||||
|
|
||||||
|
**Architecture:** 서버가 카드 데이터에 시간대별 점수와 한마디·요약(`picks`)을 미리 만들어 넣고, 카드 스크립트는 고른 칸에 맞춰 다시 그리기만 한다.
|
||||||
|
|
||||||
|
**Tech Stack:** FastAPI, pytest / 순수 JS·CSS(`card.js`·`card.css`). 새 패키지 없음.
|
||||||
|
|
||||||
|
**Spec:** `docs/superpowers/specs/2026-11-26-widget-slot-pick-design.md`
|
||||||
|
|
||||||
|
## Global Constraints
|
||||||
|
|
||||||
|
- 카드 높이·폭 규칙과 붙이는 코드는 바뀌지 않는다(기본형 245~320px, 상세형 400~520px).
|
||||||
|
- 한마디 규칙은 앱과 같다: 65점(`HERO_BUBBLE_MIN_SCORE`) 이상이면 `{머리말}은 {각 이름}!`, 아니면 `{머리말}은 쉬어 가요`. 머리말은 고른 칸이 지금 시간대면 `지금`, 아니면 `오늘 아침`·`오늘 낮`·`오늘 저녁`·`오늘 밤`.
|
||||||
|
- 카드에는 GA·쿠키·저장소를 쓰지 않는다. 다 그린 카드의 링크는 `자세히 보기 ›` 뿐이다.
|
||||||
|
- `card.js` 는 ES5·`var`·`catch (e)`·디버그 출력 없음을 지킨다. 값은 `textContent` 로만 넣는다.
|
||||||
|
- 백엔드 테스트 명령은 저장소 `CLAUDE.md` 의 것(`PGSSLMODE=disable`, Azure 변수 비우기).
|
||||||
|
- 커밋은 기능 단위로 한 번, 승인받고. 작업자는 커밋하지 않는다.
|
||||||
|
|
||||||
|
## Review Focus
|
||||||
|
|
||||||
|
1. 시간대별 데이터가 비었거나 예전 저장분 → 눌러도 지금 상태 유지, 오류 없음. (Task 1·2 테스트)
|
||||||
|
2. 1위 각이 없거나 동점 → 앱과 같은 순서(순위 → 원래 순서). (Task 1)
|
||||||
|
3. 상세형에서 다른 시간대를 고르면 상태 줄이 사라져도 높이·배치가 흔들리지 않는다. (Task 2 화면)
|
||||||
|
4. 키보드(Tab·Enter·Space)로 칸을 고를 수 있고, 고른 칸이 화면 낭독기에 전달된다. (Task 2)
|
||||||
|
5. 밤·저녁을 고르면 달이 보이는 조건이 지금과 같다(달 이름·밝기는 오늘 밤 것). (Task 2)
|
||||||
|
|
||||||
|
### Task 1: 서버 — 시간대별 점수와 한마디
|
||||||
|
|
||||||
|
**Files:** Modify `backend/services/embed_service.py`(`card_data`), `backend/tests/test_embed.py`. 필요하면 `backend/services/feed_service.py` 에서 `HERO_BUBBLE_MIN_SCORE` 를 가져다 쓴다(값을 따로 적지 않는다).
|
||||||
|
|
||||||
|
**Interfaces — Produces:** 카드 데이터 `hero.weather_slots: {morning, day, sunset, night: 점수}`(서버 구간 `evening` → 카드 칸 `sunset`), `picks: {morning|day|sunset|night: {bubble: str, summary: str|null}}`. `picks` 는 `feed.stories` 에서 `slot_ranks[구간]`·`slots[구간]` 이 있는 각 중 순위가 가장 앞선 것으로 만든다(앱 `atSlot` 과 같음). 그 구간에 해당하는 각이 없으면 그 칸은 `picks` 에서 뺀다. 머리말의 '지금'은 `hero.sky_mode` 와 같은 칸.
|
||||||
|
|
||||||
|
- [ ] 테스트 먼저: 65점 경계(65 → 각 이름, 64 → 쉬어 가요), 지금 칸 머리말 `지금`, 다른 칸 `오늘 낮` 등, 구간 데이터 없는 칸 빠짐, `evening` → `sunset` 키, 기존 카드 데이터 모양 테스트 갱신.
|
||||||
|
- [ ] 구현, 위젯 테스트 3개 파일 통과.
|
||||||
|
|
||||||
|
### Task 2: 카드 — 칸을 눌러 다시 그리기
|
||||||
|
|
||||||
|
**Files:** Modify `frontend/public/embed/card.js`, `frontend/public/embed/card.css`, `backend/services/embed_service.py`(`ASSET_VERSION` 올림).
|
||||||
|
|
||||||
|
**Interfaces — Consumes:** Task 1 의 `hero.weather_slots`, `picks`.
|
||||||
|
|
||||||
|
- [ ] 4칸을 `<button type="button" aria-pressed>` 로(지금 모양 유지, 고른 칸 강조는 지금의 '지금' 칸 강조와 같은 모양, 칸 이름은 고른 칸이 지금이면 `지금`). 누르면 하늘(`data-t`)·`data-sky`·구름·비·눈·해/달·점수와 그 위 작은 글(`지금 날씨 점수` / `아침 날씨 점수` 등)·한마디·요약을 고른 칸으로 다시 그린다. 상세형 상태 줄은 지금이 아닐 때 숨긴다(자리는 그대로 두어 높이가 흔들리지 않게 — `visibility` 등). 지금 칸을 다시 누르면 처음 상태. `picks` 나 점수가 없는 칸은 눌러도 지금 상태.
|
||||||
|
- [ ] 다 그린 카드의 링크는 `자세히 보기 ›` 뿐인지, 칸 버튼이 링크 위로 겹치지 않는지 확인.
|
||||||
|
- [ ] 확인: 기본형·상세형 × 배경 3종에서 각 칸을 고른 캡처, 넘침 0, 키보드로 고르기. 위젯 테스트·프런트 린트·테스트 통과.
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
# 날씨각 위젯(다른 사이트에 붙이는 카드) 설계
|
||||||
|
|
||||||
|
- 작성: 2026-11-25 (김성경)
|
||||||
|
- 상태: 승인 (2026-11-25. 같은 날 '완전 오픈 + 배경 3종'으로 변경해 다시 승인)
|
||||||
|
- 표시: **[결정]** 은 사용자가 정한 것, **[제안]** 은 작성자가 채운 것(바꿀 수 있음), **[만드는 사람]** 은 구현하면서 정할 것
|
||||||
|
|
||||||
|
## 0. 변경 기록
|
||||||
|
|
||||||
|
| 날짜 | 바뀐 것 |
|
||||||
|
|---|---|
|
||||||
|
| 2026-11-25 | 첫 설계: 문의하기로 신청 → 등록한 사이트에서만 카드가 보임 |
|
||||||
|
| 2026-11-25 | **완전 오픈으로 변경 [결정]**: 신청·등록 없이 누구나 바로 쓴다. 사용 방법 페이지에서 지역·모양·배경을 고르면 바로 쓸 수 있는 코드가 나온다. 배경 3종(군산각처럼 / 밝은 바탕용 / 어두운 바탕용) 추가. 사이트별 노출 집계는 계속 |
|
||||||
|
|
||||||
|
첫 설계로 이미 만든 백엔드(등록 표, 등록 관리자 API, 부른 사이트 확인·브라우저 차단 헤더, 신청 안내 화면)는 걷어 낸다. 카드 데이터·HTML, 지역 주소 목록, 노출 집계, 장애 때 조용한 화면은 그대로 쓴다.
|
||||||
|
|
||||||
|
## 1. 왜 만드나
|
||||||
|
|
||||||
|
날씨각 첫 화면 카드를 다른 사이트가 쉽게 붙이게 해서, 그 사이트 방문자가 '자세히 보기'로 날씨각에 들어오게 하려는 것이다. (10/2 회의 '관광형 날씨 위젯 무료 제공', 10/21 회의 '위젯으로 넣고 더 보기로 유입')
|
||||||
|
|
||||||
|
지금은 날씨각이 주는 위젯이 없다. 군산각(gunsan.webforai.kr)과 스테이머뭄(co.webforai.kr/s/stay)은 카드를 그리는 스크립트·스타일·아이콘을 각자 복사해 들고 있고, 날씨각 공개 API(`/v1/feed`, `/v1/weather/today`)를 직접 부른다. 그래서
|
||||||
|
|
||||||
|
- 날씨각 카드 디자인이나 API 항목 이름이 바뀌면 복사본은 따라오지 않거나 깨진다.
|
||||||
|
- 붙이려는 사이트마다 파일 세 종류를 복사하고 지역 코드·링크를 손으로 적어야 한다.
|
||||||
|
- 어느 사이트에 붙었는지, 거기서 몇 명이 들어왔는지 알 수 없다.
|
||||||
|
|
||||||
|
## 2. 무엇을 만드나
|
||||||
|
|
||||||
|
- 날씨각이 직접 내보내는 카드 화면. 다른 사이트는 iframe(페이지 안에 다른 화면을 액자처럼 끼우는 태그) 한 줄로 붙인다. **[결정]**
|
||||||
|
- 신청·등록 없이 누구나, 어느 사이트에나 붙일 수 있다. **[결정]**
|
||||||
|
- 카드에 나오는 것은 군산각 카드 그대로다. 날씨각의 다른 기능은 넣지 않는다. **[결정]**
|
||||||
|
- 고를 수 있는 것은 세 가지다. **[결정]**
|
||||||
|
- 지역: 날씨각에 있는 지역 전부
|
||||||
|
- 모양: 좁은 형(`side`: 날씨 점수, 해·달·구름, 한마디, 아침·낮·저녁·밤 4칸) / 넓은 형(`home`: 좁은 형 + 요약 문장 + 상태 줄)
|
||||||
|
- 배경: 군산각처럼(`sky`: 시간대에 따라 바뀌는 하늘) / 밝은 바탕용(`light`) / 어두운 바탕용(`dark`)
|
||||||
|
- 날씨각 안에 사용 방법 페이지를 둔다. 지역·모양·배경을 고르면 미리보기와 바로 붙여 넣을 코드가 나온다. 들어오는 길은 문의 창의 `날씨 위젯 달기` 버튼과 검색(사이트맵·검색용 제목·설명). **[결정]** (2026-11-26)
|
||||||
|
- 어느 사이트에서 하루에 몇 번 보였는지 집계한다. **[결정]**
|
||||||
|
|
||||||
|
```
|
||||||
|
붙이는 사이트 날씨각
|
||||||
|
┌──────────────────────┐
|
||||||
|
│ (그 사이트 내용) │
|
||||||
|
│ ┌──────────────────┐ │ iframe /embed/card?region=5213000000&type=side&bg=sky
|
||||||
|
│ │ 군산 날씨 11월 25일│ │ ───────▶ 1. 카드 HTML(그릴 값 포함)을 돌려준다
|
||||||
|
│ │ ☀ 지금 날씨 점수 │ │ 2. 부른 사이트 주소로 노출 수 +1
|
||||||
|
│ │ 82 │ │
|
||||||
|
│ │ "산책하기 좋아요" │ │
|
||||||
|
│ │ 아침 지금 저녁 밤 │ │ '자세히 보기'를 누르면 새 창으로
|
||||||
|
│ │ 8° 14° 11° 7° │ │ ───────▶ weather.o2o.kr/today/jeonbuk/gunsan?utm_source=widget…
|
||||||
|
│ │ 자세히 보기 ›│ │
|
||||||
|
│ └──────────────────┘ │
|
||||||
|
└──────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 목표
|
||||||
|
|
||||||
|
- 붙이는 사람은 사용 방법 페이지에서 고르고 코드 한 덩어리를 복사해 넣으면 끝이다. 기다릴 것이 없다.
|
||||||
|
- 날씨각 카드를 고치면 붙인 모든 사이트에 바로 반영된다.
|
||||||
|
- 붙인 사이트의 화면·스타일을 건드리지 않는다.
|
||||||
|
- 사이트별 하루 노출 수가 남고, 위젯으로 들어온 방문이 날씨각 GA 유입에 구분되어 보인다.
|
||||||
|
|
||||||
|
### 하지 않는 것 **[결정]**
|
||||||
|
|
||||||
|
- 신청·등록·승인 절차, 등록한 사이트에서만 보이게 막기
|
||||||
|
- 날씨각의 다른 기능을 카드에 넣는 것(오늘의 각 순위, 타로, 포스트, 댓글 등)
|
||||||
|
- 배경 3종 밖의 색·글꼴 바꾸기, 외국어판
|
||||||
|
- 높이를 자동으로 맞추는 스크립트(나중에)
|
||||||
|
- 특정 사이트 차단(문제 사이트가 집계에 보이면 그때 만든다)
|
||||||
|
- 군산각·스테이머뭄의 기존 카드 교체(다른 저장소. 위젯 검증 뒤 따로)
|
||||||
|
- 위젯 화면 안의 GA·쿠키
|
||||||
|
|
||||||
|
### 이렇게 되면 실패다
|
||||||
|
|
||||||
|
- 위젯 때문에 붙인 사이트가 느려지거나 깨진다.
|
||||||
|
- 붙인 사이트 방문자에게 날씨각 쿠키가 심긴다.
|
||||||
|
- 날씨각이 느리거나 죽었을 때 붙인 사이트에 오류 화면이 크게 보인다.
|
||||||
|
- 위젯 요청이 몰려 날씨각 본 서비스가 느려진다.
|
||||||
|
|
||||||
|
## 3. 제약
|
||||||
|
|
||||||
|
- 날씨각 본체는 React 앱이고 화면 폭 440px 기준이다. 카드 화면은 앱 묶음을 싣지 않고 가볍게 따로 만든다.
|
||||||
|
- `frontend/nginx.conf` 의 `location /` 는 모든 응답에 `Cache-Control: no-store` 를 붙인다. 카드용 정적 파일은 따로 캐시 규칙이 필요하다.
|
||||||
|
- 지역 코드 → 주소 이름(`jeonbuk/gunsan`)은 `backend/seed/region_path.json` 에 있다(`backend/scripts/gen_region_pages.py` 출력, 256개. 만들어 둠).
|
||||||
|
- 피드는 지역별로 Redis 에 최대 1시간 저장된다(`backend/services/feed_service.py`). 오늘 시간대별 날씨(`WeatherService.today`)는 저장되지 않아 부를 때마다 DB 를 읽는다.
|
||||||
|
- 관리자 API 는 `X-Admin-Key` 헤더로 지킨다(`backend/common/auth.py` `require_admin`).
|
||||||
|
- DB 표는 `backend/postgres-init/init.sql` 에 `CREATE TABLE IF NOT EXISTS` 로 추가한다. `deploy.sh` 가 배포할 때마다 `init.sql` 을 돌리므로 표는 배포와 함께 운영 DB 에 생긴다. 배포 전에 확인받는다.
|
||||||
|
- 운영에는 nginx 앞에 프록시가 하나 더 있고 그 설정은 저장소에 없다. 2026-11-25 에 운영 응답을 확인한 결과 앞단은 `X-Frame-Options`·CSP·쿠키를 붙이지 않는다. 들어오는 `Referer` 를 지우는지는 밖에서 확인할 수 없어 배포 뒤에 확인한다.
|
||||||
|
- 개인정보는 저장하지 않는다. 방문자 IP·페이지 주소를 남기지 않는다.
|
||||||
|
|
||||||
|
## 4. 접근 방식
|
||||||
|
|
||||||
|
| | A. 스크립트 한 줄 | B. iframe | C. iframe 본체 + 높이 스크립트는 선택 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 붙인 페이지와 섞임 | 같은 페이지에서 돌아 격리를 따로 해야 함 | 서로 영향 없음 | B 와 같음 |
|
||||||
|
| 높이 | 자동 | 붙이는 사람이 숫자로 적음 | 기본은 숫자, 스크립트를 쓰면 자동 |
|
||||||
|
| 우리 쪽 사고의 영향 | 붙인 페이지 전체 | 카드 칸 안 | 카드 칸 안 |
|
||||||
|
|
||||||
|
**C 로 정했다. [결정]** 누구나 붙이는 위젯은 붙인 사이트를 망가뜨리지 않는 것이 먼저다. 이번에는 iframe 본체만 만들고 높이 스크립트는 뒤로 미룬다.
|
||||||
|
|
||||||
|
쓸 수 있는 범위는 세 안을 거쳤다.
|
||||||
|
|
||||||
|
- ① 신청하라고 안내만 함
|
||||||
|
- ② 신청해 등록한 사이트에서만 보임 (첫 설계)
|
||||||
|
- ③ **완전 오픈: 신청·등록 없음 ← 최종 [결정]**
|
||||||
|
|
||||||
|
## 5. 설계
|
||||||
|
|
||||||
|
### 5.1 주소 **[제안]**
|
||||||
|
|
||||||
|
| 주소 | 무엇 |
|
||||||
|
|---|---|
|
||||||
|
| `https://weather.o2o.kr/embed/card?region=<지역코드 10자리>&type=side\|home&bg=sky\|light\|dark` | 카드 화면 (iframe 에 넣는 주소) |
|
||||||
|
| `https://weather.o2o.kr/widget` | 사용 방법 페이지 |
|
||||||
|
|
||||||
|
공개하면 바꾸기 어렵다. 이미 붙인 사이트가 깨지기 때문이다. `bg` 를 빼면 `sky` 다.
|
||||||
|
|
||||||
|
붙이는 코드는 이런 모양이다(좁은 형).
|
||||||
|
|
||||||
|
```html
|
||||||
|
<iframe src="https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky"
|
||||||
|
title="군산시 날씨 - 날씨각" width="100%" height="245"
|
||||||
|
style="border:0;width:100%;height:245px;min-width:220px;max-width:440px;min-height:245px;max-height:320px"
|
||||||
|
loading="lazy" referrerpolicy="origin"></iframe>
|
||||||
|
```
|
||||||
|
|
||||||
|
크기 범위 **[결정]** (2026-11-26, 실제 카드를 캡처해 정함). 폭은 놓인 자리에 맞춰 범위 안에서 자동으로 늘고 줄고, 높이는 최소 높이가 기본이며 붙이는 사람이 최대 높이까지 늘릴 수 있다. 네 값 모두 코드의 `style` 에 넣어 붙인 사이트의 다른 스타일에 밀리지 않게 한다.
|
||||||
|
|
||||||
|
| | 최소 폭 | 최대 폭 | 최소(기본) 높이 | 최대 높이 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 기본형(좁은 형, `side`) | 220px | 440px | 245px | 320px |
|
||||||
|
| 상세형(넓은 형, `home`) | 280px | 720px | 400px | 520px |
|
||||||
|
|
||||||
|
- 최소 폭: 이름이 가장 긴 지역(창원시 마산합포구)으로도 제목·'자세히 보기'·점수·한마디·4칸이 전부 보이는 폭. 가장 좁은 폰(320px)에도 들어간다.
|
||||||
|
- 최소 높이: 이보다 낮으면 아래 4칸 줄이 잘린다. 최대 높이: 이보다 높으면 빈 자리가 눈에 띈다.
|
||||||
|
- 넓은 형은 `style` 끝에 `border-radius:28px` 가 더 붙는다. 붙인 사이트가 `color-scheme: dark` 를 선언한 경우 둥근 모서리 밖이 희게 칠해지는 것을 액자째 잘라 낸다.
|
||||||
|
- 넓은 형의 날짜는 통째로 들어갈 자리가 없으면 숨긴다(군산각은 `1…` 로 잘린 채 둔다).
|
||||||
|
|
||||||
|
`referrerpolicy="origin"` 은 "어느 사이트에서 부르는지"를 날씨각에 알려 주게 하는 설정이다. 노출 집계에만 쓴다. 빼도 카드는 보이고, 그 노출은 `(알 수 없음)` 으로 셀 수 있다.
|
||||||
|
|
||||||
|
### 5.2 카드 화면이 응답하는 방법
|
||||||
|
|
||||||
|
nginx 가 `/embed/card` 를 백엔드 `/v1/embed/card` 로 넘기고, 백엔드가 HTML 을 돌려준다(지역 검색 페이지 `/v1/seo/...` 와 같은 방식). 어느 사이트에서 불러도 같은 카드를 돌려준다. 액자에 넣는 것을 막는 헤더(`X-Frame-Options`, `frame-ancestors`)는 붙이지 않는다.
|
||||||
|
|
||||||
|
| 순서 | 조건 | 돌려주는 것 | 노출 집계 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | `region` 이 숫자 10자리가 아님, `type`·`bg` 가 정해진 값이 아님 | 404, 조용한 화면 | 안 함 |
|
||||||
|
| 2 | 없는 지역 | 404, 조용한 화면 | 안 함 |
|
||||||
|
| 3 | 값을 못 만듦(오류, 오늘 날짜가 아닌 값, 예상 못 한 예외) | 200, 조용한 화면 | 안 함 |
|
||||||
|
| 4 | 그 밖 | 200, 날씨 카드 | 함 |
|
||||||
|
|
||||||
|
- 조용한 화면은 `날씨각에서 날씨 보기 ›` 링크 하나다. 오류 문구·오류 JSON 을 iframe 에 띄우지 않는다.
|
||||||
|
- 응답은 `Cache-Control: no-store`, `X-Robots-Tag: noindex`. 쿠키를 심지 않는다.
|
||||||
|
- 요청에서 받은 문자열(`region`, `type`, `bg`, `Referer`)은 HTML 이나 헤더에 그대로 넣지 않는다.
|
||||||
|
|
||||||
|
카드 HTML 에는 그릴 데이터가 함께 들어 있다(따로 API 를 한 번 더 부르지 않는다). **[제안]**
|
||||||
|
|
||||||
|
- 넣는 값: 지역 이름, 날씨각 링크, 그리고 군산각 스크립트가 쓰는 값만 — 피드 `hero` 의 `now_at`·`sky_mode`·`temp_c`·`weather_score`·`bubble`·`top1.summary`·`status`·`moon_name`·`moon_pct`, 오늘 시간대 칸(`day`·`slots`).
|
||||||
|
- 링크: `/today/<주소 이름>?utm_source=widget&utm_medium=embed&utm_campaign=<부른 사이트 호스트>`, 새 창으로 연다. 주소 이름이 없는 지역은 날씨각 홈으로 보낸다. 호스트를 모르면 `unknown`, 날씨각 자신이면 `preview`.
|
||||||
|
- **서버 부담 줄이기 [제안]**: 완전히 열면 방문자 많은 사이트에 붙을 수 있다. 지역별 카드 데이터(링크를 뺀 값)를 Redis 에 5분 저장해, 같은 지역 요청이 몰려도 피드·오늘 날씨·DB 조회를 5분에 한 번만 한다. 저장된 값이 오늘 날짜가 아니면 버리고 다시 만든다.
|
||||||
|
|
||||||
|
### 5.3 카드를 그리는 코드
|
||||||
|
|
||||||
|
- 군산각의 `https://gunsan.webforai.kr/assets/weather.js`(23KB, 주석 달린 원문)와 `https://gunsan.webforai.kr/assets/style.css`(압축된 421KB) 안의 `.wx-*` 규칙을 날씨각 저장소로 옮겨 원본으로 삼는다. **[제안]** 같은 회사 코드이고, 그 카드 자체가 날씨각 첫 화면 카드를 옮겨 그린 것이다. 군산각 원본 저장소를 볼 수 있으면 거기서 가져오는 쪽이 낫다.
|
||||||
|
- 둘 곳: `frontend/public/embed/card.js`, `frontend/public/embed/card.css`. React·Tailwind 를 쓰지 않는 순수 자바스크립트·CSS 다.
|
||||||
|
- 좁은 형과 넓은 형은 같은 스크립트·같은 스타일이고 카드 상자의 클래스(`wx-side` / `wx-home`)로 갈린다. 상자 안 마크업은 군산각 첫 화면의 `.wx` 상자 두 개를 따른다.
|
||||||
|
- 옮기면서 바꾸는 것:
|
||||||
|
- API 를 부르는 대신 HTML 에 들어 있는 데이터를 읽는다.
|
||||||
|
- 아이콘은 날씨각의 `/icons/{sun,sun_cloud,cloud,rain,snow,moon}.webp` 를 쓴다(이미 있다).
|
||||||
|
- 군산각 스타일이 기대는 색·글꼴 변수는 군산각 값을 확인해 `card.css` 안에 직접 적는다.
|
||||||
|
- 일출·일몰, 외국어 문구 부분은 뺀다.
|
||||||
|
- 글이 길어도 정해진 높이를 넘지 않게 줄 수를 제한한다.
|
||||||
|
- **배경 3종 [결정]** — 카드 상자의 클래스(`wx-bg-sky` / `wx-bg-light` / `wx-bg-dark`)로 갈린다.
|
||||||
|
- `sky`: 군산각 그대로. 시간대(아침·낮·저녁·밤)에 따라 하늘 그림이 바뀌고 별·비·눈이 움직인다.
|
||||||
|
- `light`·`dark`: 밝은 바탕, 어두운 바탕의 사이트에 어울리게 하늘 그림을 뺀 카드다. 어떤 모습으로 할지(테두리만 둘지, 바탕색을 깔지, 해·달·구름과 움직임을 어디까지 남길지)는 시안 4개를 보여 주고 고른다(개인 지침). 날씨 점수·한마디·4칸 등 내용은 `sky` 와 같다.
|
||||||
|
- 글꼴은 날씨각 본체처럼 구글 폰트(Jua, Bagel Fat One)를 쓴다. 못 받으면 기본 글꼴로 그린다.
|
||||||
|
- 카드 화면에는 GA·쿠키·로그인 관련 코드를 넣지 않는다.
|
||||||
|
- nginx: `/embed/card` 는 백엔드로, `/embed/` 아래 나머지는 정적 파일로 준다. 정적 파일은 1시간 캐시하고, 고치면 주소의 `?v=` 를 올린다.
|
||||||
|
- 열어 둔 페이지에서 카드가 스스로 새로 고쳐지지는 않는다(군산각과 같다).
|
||||||
|
|
||||||
|
### 5.4 노출 집계
|
||||||
|
|
||||||
|
표 하나. **[제안]**
|
||||||
|
|
||||||
|
| 표 | 칸 | 뜻 |
|
||||||
|
|---|---|---|
|
||||||
|
| `widget_view_daily` | `day`, `host`, `kind`(side/home), `views` — (day, host, kind) 가 기본 키 | 사이트별 하루 노출 수 |
|
||||||
|
|
||||||
|
- 날씨 카드를 돌려줄 때 1 올린다. 요청마다 DB 에 쓰지 않고 Redis 해시(`widget:views:<한국 날짜>`)에 쌓았다가, 관리자 API 를 부를 때 이 표로 옮긴다(옮기기 전에 Redis 를 비우면 그 수치를 잃는다). 방문자 IP 나 페이지 주소는 저장하지 않는다.
|
||||||
|
- `host` 는 `Referer` 에서 꺼낸 사이트 주소(호스트)다. 도메인 꼴이 아니거나 없으면 `(알 수 없음)`, 날씨각 자신(사용 방법 페이지 미리보기)은 세지 않는다.
|
||||||
|
- `Referer` 는 속일 수 있어 엉뚱한 주소가 무한정 쌓일 수 있다. 하루에 새로 기록하는 사이트는 500곳까지만 받고, 넘으면 `(기타)` 로 합친다. **[제안]** (지금 붙을 사이트 수보다 훨씬 크게 잡은 값이다.)
|
||||||
|
- 집계가 실패해도 카드는 돌려준다.
|
||||||
|
|
||||||
|
관리자 API (`X-Admin-Key`, 기존 `/v1/admin` 과 같은 방식): **[제안]**
|
||||||
|
|
||||||
|
| 주소 | 무엇 |
|
||||||
|
|---|---|
|
||||||
|
| `GET /v1/admin/widget/views` | 사이트별 최근 7일·30일 노출 수(많은 순), 전체 합 |
|
||||||
|
|
||||||
|
보는 방법(명령 예시)은 운영 문서에 적는다.
|
||||||
|
|
||||||
|
### 5.5 사용 방법 페이지 (`/widget`)
|
||||||
|
|
||||||
|
- 날씨각 앱의 새 화면이다(`frontend/src/App.tsx` 에 경로 추가). 탭·메뉴에는 넣지 않는다. 들어오는 길은 문의 창의 `날씨 위젯 달기 ›` 버튼(토스 미니앱에서는 숨김)과 검색(사이트맵·검색용 제목·설명)이다. **[결정]** (2026-11-26 변경. 처음에는 주소로만)
|
||||||
|
- 들어가는 것:
|
||||||
|
- 위젯이 무엇인지 한두 줄
|
||||||
|
- 지역 고르기(기존 지역 목록 `/v1/region/list`), 모양 고르기(좁은 형·넓은 형), 배경 고르기(군산각처럼·밝은 바탕용·어두운 바탕용)
|
||||||
|
- 미리보기 — 실제 `/embed/card` 를 iframe 으로 보여 준다. 고른 배경에 맞춰 미리보기 뒤 바탕도 밝게/어둡게 바꾼다.
|
||||||
|
- 붙여 넣을 코드와 '복사' 버튼
|
||||||
|
- 이용 조건 세 줄: 무료이며 신청 없이 쓸 수 있다 / 날씨각 링크는 지우지 않는다 / 예고 없이 바뀌거나 중단될 수 있다 **[제안]**
|
||||||
|
- 화면 디자인은 시안 4개를 먼저 보여 주고 고른다(개인 지침). 문구도 그때 확정한다.
|
||||||
|
|
||||||
|
### 5.6 GA 이벤트
|
||||||
|
|
||||||
|
위젯 화면 안에는 GA 를 넣지 않는다. **[결정]** 붙인 사이트 방문자에게 쿠키가 심기고 날씨각 지표에 위젯 노출이 섞이기 때문이다. 대신
|
||||||
|
|
||||||
|
- 노출 수: 서버 집계(5.4)
|
||||||
|
- 위젯으로 들어온 방문: 링크의 `utm_source=widget` 으로 GA 유입에 구분
|
||||||
|
|
||||||
|
사용 방법 페이지에는 저장소 규칙대로 이벤트를 넣는다. **[제안]** (`shared/lib/analytics.ts` `Events`·`GA_NAME`, `docs/이벤트_추적.md`)
|
||||||
|
|
||||||
|
| 코드 | GA 이름 | 언제 | 값 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `widget_guide_view` | `위젯_안내_보기` | 사용 방법 페이지를 열었을 때 | `from`(contact: 문의 창에서, direct: 그 밖) |
|
||||||
|
| `widget_option_select` | `위젯_옵션_고름` | 이 페이지에서 지역·모양·배경을 직접 바꿨을 때(앱 지역을 따라갈 때는 안 보냄) | `option`(region·kind·bg), `value` |
|
||||||
|
| `widget_code_copy` | `위젯_코드_복사` | 코드 '복사'를 눌렀을 때 | `kind`, `bg`, `region`(지역 코드), `method`(script·iframe) |
|
||||||
|
|
||||||
|
### 5.7 검증
|
||||||
|
|
||||||
|
- 백엔드 테스트: 어느 사이트의 `Referer` 로 불러도 카드가 온다 / 액자를 막는 헤더와 쿠키가 없다 / 잘못된 `region`·`type`·`bg` 는 404 조용한 화면 / 피드 오류·예외는 200 조용한 화면 / 노출 수가 사이트별로 오른다, `Referer` 없음은 `(알 수 없음)`, 날씨각 자신은 안 셈, 하루 상한을 넘으면 `(기타)` / 카드 데이터 저장분을 다시 쓴다 / 관리자 API 는 키 없이 401.
|
||||||
|
- 프런트 테스트(`node --test`): 붙이는 코드 만들기.
|
||||||
|
- 눈으로 확인: 도커(`localhost:8080`)에서 좁은 형·넓은 형 × 배경 3종을 아침·낮·저녁·밤, 맑음·비·눈으로 확인하고, 다른 주소의 시험 페이지(밝은 바탕, 어두운 바탕)에 iframe 으로 넣어 본다.
|
||||||
|
- 배포 뒤 확인: 실제 다른 사이트에서 카드가 보이는지, 집계에 그 사이트 주소가 남는지(앞단 프록시가 `Referer` 를 지우지 않는지), 쿠키가 없는지.
|
||||||
|
- 저장소 명령: `frontend` 에서 `npm run lint`, `npm run build`, `npm test`. 백엔드는 `pytest`.
|
||||||
|
|
||||||
|
### 5.8 문서
|
||||||
|
|
||||||
|
- `docs/위젯_운영.md`(새로): 노출 수 보는 법, 붙이는 코드 예시, 붙이는 쪽 주의점, 카드 파일을 고쳤을 때 할 일 **[제안]**
|
||||||
|
- `docs/이벤트_추적.md`: 5.6 의 세 줄
|
||||||
|
- `docs/서비스_동작_안내.md`: 위젯 한 단락
|
||||||
|
|
||||||
|
## 6. 진행 순서 **[결정]** — 단계마다 확인받고 넘어간다
|
||||||
|
|
||||||
|
| 단계 | 내용 | 상태·확인받을 것 |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | 백엔드(첫 설계): 접근 규칙, 등록 표·관리자 API, 카드 응답 | 완료(확인 지점 ①) |
|
||||||
|
| 2 | 완전 오픈으로 바꾸기: 등록·차단 걷어 내기, 배경 값, 노출 집계 상한, 카드 데이터 저장 | 테스트 결과(② 에서 함께 보고) |
|
||||||
|
| 3 | 카드 화면: `card.js`·`card.css`, nginx, 좁은 형·넓은 형, 배경 3종(밝은·어두운은 시안 4개) | ② 카드 모양, 시안 선택, 모양별 높이 |
|
||||||
|
| 4 | 사용 방법 페이지: 시안 4개 → 구현, GA 이벤트 | ③ 시안 선택, 화면 문구 |
|
||||||
|
| 5 | 문서, 전체 검증 | ④ 완료 보고 |
|
||||||
|
|
||||||
|
브랜치는 `feat/embed-widget`. **[결정]** 커밋·푸시·PR 은 그때마다 승인받는다.
|
||||||
|
|
||||||
|
## 7. 알고 넘어가는 것
|
||||||
|
|
||||||
|
- **누가 붙이든 막지 못한다.** 원치 않는 사이트에 붙어도 지금은 집계로 알 수 있을 뿐이다. 문제가 보이면 그 사이트만 막는 기능을 그때 만든다.
|
||||||
|
- **집계의 사이트 주소는 정확하지 않을 수 있다.** 브라우저가 알려 주는 값이라 속이거나 숨길 수 있다. 추세를 보는 용도다.
|
||||||
|
- **기존 공개 API 는 그대로 열려 있다.** 군산각·스테이머뭄처럼 카드 코드를 복사해 `/v1/feed` 를 직접 부르는 방식도 계속 된다.
|
||||||
|
- **붙이는 사이트의 보안 설정**: 외부 iframe 을 막는 설정(CSP `frame-src`)을 켠 사이트는 `weather.o2o.kr` 을 허용해야 한다. 스테이머뭄 사이트가 이 설정을 시험 모드로 켜 두고 있다. 사용 방법 페이지와 운영 문서에 적는다.
|
||||||
|
- **글꼴**: 카드가 구글 폰트를 부르므로 붙인 사이트 방문자의 브라우저가 구글에 접속한다(지금 군산각·스테이머뭄 카드도 같다).
|
||||||
|
- **운영 반영**: 표 1개 추가와 nginx 설정 변경이 있다. 배포 전에 명령과 영향 범위를 설명하고 확인받는다.
|
||||||
|
|
||||||
|
## 8. 변경 기록 (2026-11-26)
|
||||||
|
|
||||||
|
- 화면 이름: 모양 '좁은 형/넓은 형' → '기본형/상세형', 배경 '하늘/밝은/어두운' → '기본형/밝은/어두운'. 주소의 값(`side`·`home`, `sky`·`light`·`dark`)은 그대로다. **[결정]**
|
||||||
|
- 기본(최소) 높이: 기본형 246→245px, 상세형 401→400px. 카드 아래 여백을 1px 줄여 맞췄고, 이름이 가장 긴 지역을 포함해 배경 3종·폭 3가지에서 잘리지 않는 것을 확인했다. **[결정]**
|
||||||
|
- **붙이는 방법을 두 가지로 [결정]**: 기본은 스크립트(권장), 스크립트를 넣을 수 없는 곳을 위해 지금의 iframe 코드도 함께 준다. 스크립트는 우리 코드가 남의 페이지를 직접 그리는 방식이 아니라, 미리 넣어 둔 날씨각 링크 자리에 지금의 카드 iframe 을 끼워 넣는 작은 로더다(카드는 그대로 액자 안). 장점: 날씨각 서버에 아예 접속이 안 돼도 링크가 남는다, 붙인 뒤에도 로더만 고치면 모든 사이트에 반영된다, 코드가 짧다. 대가: 스크립트를 막는 곳에서는 안 되고, 우리 스크립트가 남의 페이지에서 돈다(그래서 iframe 끼워 넣기 외에는 아무것도 하지 않는다).
|
||||||
|
|
||||||
|
```html
|
||||||
|
<a class="nalssigak-weather" href="https://weather.o2o.kr/today/jeonbuk/gunsan?utm_source=widget&utm_medium=embed&utm_campaign=fallback"
|
||||||
|
data-region="5213000000" data-type="side" data-bg="sky">군산시 날씨 - 날씨각</a>
|
||||||
|
<script src="https://weather.o2o.kr/embed/widget.js" async></script>
|
||||||
|
```
|
||||||
|
- 로딩 화면은 토끼(`/icons/rabbit.webp`, 앱 첫 화면과 같은 깡충 움직임), 실패하면 어느 경우든 `날씨각에서 날씨 보기 ›` 링크. 링크 화면 바탕은 고른 배경을 따르고, 서버가 죽었을 때 nginx 가 보내는 정적 화면만 하늘색 고정. 카드 만들기는 8초 제한(로컬에서 첫 카드가 최대 6.4초 걸려 5초에서 올림). **[결정]**
|
||||||
|
- **높이도 폭에 따라 [결정]** (2026-11-26): 폭이 넓어지면 높이도 비율(기본형 11:8, 상세형 18:13)대로 커진다. 최소·최대 높이 범위 안에서만 움직인다(기본형 폭 337px 까지 245px → 440px 에서 320px, 상세형 폭 554px 까지 400px → 720px 에서 520px). CSS `aspect-ratio` 로 하므로 스크립트·iframe 두 방법 모두 같다.
|
||||||
|
- **주소 이름 변경 [결정]** (2026-11-26): 사용 방법 페이지 `/widget` → `/widget-guide`(옛 주소는 nginx 301), umami 의 위젯 카드 조회 이름 `/widget-card` → `/widget`. 이날 전의 umami `/widget` 기록은 사용 방법 페이지 방문이다.
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# 날씨 위젯 시간대 골라 보기 설계 (짧은 설계)
|
||||||
|
|
||||||
|
- 작성: 2026-11-26 (김성경)
|
||||||
|
- 상태: 승인 (대화에서 2026-11-26 사용자가 동작을 정함: "응 그렇게 진행")
|
||||||
|
- 바탕: `docs/superpowers/specs/2026-11-25-embed-widget-design.md` (위젯 본 설계)
|
||||||
|
- 표시: **[결정]** 사용자가 정한 것, **[제안]** 작성자가 채운 것
|
||||||
|
|
||||||
|
## 왜
|
||||||
|
|
||||||
|
위젯 카드 아래 4칸(아침·낮·저녁·밤)은 기온만 보여 주고 눌러도 아무 일이 없다. 날씨각 앱 첫 화면처럼 칸을 눌러 그 시간대의 날씨 점수와 추천 각을 보게 해, 카드만으로도 "오늘 언제 뭐 하기 좋은지"가 보이게 한다.
|
||||||
|
|
||||||
|
## 무엇을 **[결정]**
|
||||||
|
|
||||||
|
4칸을 누르면 그 시간대로 카드가 바뀐다. 처음은 "지금" 칸이 골라져 있고, 지금과 같은 칸을 다시 누르면 처음 상태로 돌아간다.
|
||||||
|
|
||||||
|
| 바뀌는 것 | 지금(처음) | 다른 시간대를 고르면 |
|
||||||
|
|---|---|---|
|
||||||
|
| 큰 원 위 작은 글 | `지금 날씨 점수` | `아침 날씨 점수` 등 **[제안]** |
|
||||||
|
| 점수 | 지금 날씨 점수 | 그 시간대 날씨 점수(`hero.weather_slots`) |
|
||||||
|
| 하늘·해·달·구름·비·눈 | 지금 | 그 시간대(아침·낮·저녁·밤 하늘, 그 칸의 하늘 상태) |
|
||||||
|
| 한마디 | `지금은 산책각!` | `오늘 낮은 러닝각!` / `오늘 밤은 쉬어 가요` |
|
||||||
|
| 요약 문장(상세형) | 지금 1위 각 설명 | 숨김(지금 기준 글이라 — 자리는 남김) **[제안]**, 2026-11-26 |
|
||||||
|
| 상태 줄(상세형: 습도·미세먼지 등) | 보임 | 숨김(지금 측정값이라) |
|
||||||
|
| 4칸 | "지금" 칸 강조 | 고른 칸 강조 |
|
||||||
|
|
||||||
|
- 한마디는 앱과 같은 규칙이다: 그 시간대 1위 각(각의 `slot_ranks` 가 가장 앞선 것)의 그 시간대 점수(`slots`)가 65점(`HERO_BUBBLE_MIN_SCORE`) 이상이면 `오늘 {시간대}은 {각 이름}!`, 아니면 `오늘 {시간대}은 쉬어 가요`. 고른 칸이 지금 시간대이면 머리말은 `지금`. 같은 지역이면 앱과 위젯이 같은 한마디를 보여 준다. (`frontend/src/b/TodayPage.tsx` 의 `atSlot`·`bubble` 과 같다)
|
||||||
|
- 시간대별 데이터가 없으면(예전 저장분, 빈 값) 그 칸은 눌러도 지금 상태를 유지한다 **[제안]**.
|
||||||
|
|
||||||
|
## 하지 않는 것
|
||||||
|
|
||||||
|
- 방문자 위치로 지역 바꾸기(2026-11-26 사용자 결정: 지금처럼 붙인 사람이 정한 지역 고정)
|
||||||
|
- 내일 날씨, 시간대 고른 상태 기억하기, 카드 안 GA
|
||||||
|
|
||||||
|
## 어떻게 **[제안]**
|
||||||
|
|
||||||
|
- 서버(`backend/services/embed_service.py` `card_data`): 카드 데이터에 `hero.weather_slots`(4칸 점수)와 `picks`(시간대별 `{bubble}`)를 더한다. 1위 각 고르기와 한마디 만들기는 서버에서 한다(규칙이 앱과 한 곳에서 어긋나지 않게 `HERO_BUBBLE_MIN_SCORE` 를 같이 쓴다). 키는 카드의 칸 이름(`morning`·`day`·`sunset`·`night`), 서버 구간 이름은 `evening` 이니 맞춰 바꾼다.
|
||||||
|
- 카드(`card.js`·`card.css`): 4칸을 버튼(`aria-pressed`)으로 바꾸고, 누르면 고른 시간대로 하늘·원·점수·한마디·요약을 다시 그린다(높이·자리는 그대로). 상태 줄은 숨긴다. `ASSET_VERSION` 을 올린다. 카드 데이터 저장 키에 `ASSET_VERSION` 이 들어 있어 옛 저장분은 저절로 버려진다.
|
||||||
|
- 붙이는 코드는 바뀌지 않는다. 이미 붙인 사이트에도 카드 파일만 바뀌어 반영된다.
|
||||||
|
- 다 그린 카드에서 링크는 여전히 `자세히 보기 ›` 버튼뿐이다(칸 버튼은 링크가 아니다).
|
||||||
|
|
||||||
|
## 검증
|
||||||
|
|
||||||
|
- 백엔드 테스트: 시간대별 `picks` 가 앱 규칙대로(65점 경계, 지금 칸 머리말, 데이터 없음) 나온다.
|
||||||
|
- 화면: 기본형·상세형 × 배경 3종에서 칸을 눌렀을 때 하늘·점수·한마디가 바뀌고 넘침이 없다, 키보드로도 고를 수 있다.
|
||||||
@@ -15,6 +15,7 @@
|
|||||||
| 6 | 피드 기획 원칙 |
|
| 6 | 피드 기획 원칙 |
|
||||||
| 7 | 토스판 |
|
| 7 | 토스판 |
|
||||||
| 8 | 알아 두실 점 |
|
| 8 | 알아 두실 점 |
|
||||||
|
| 9 | 날씨 위젯 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -687,3 +688,11 @@ frontend/
|
|||||||
- **노을 피크 시각:** 해 지는 시각에 10~20분을 더한 어림값이라 실제와 다를 수 있습니다.
|
- **노을 피크 시각:** 해 지는 시각에 10~20분을 더한 어림값이라 실제와 다를 수 있습니다.
|
||||||
- **밤 날씨 점수:** 해가 진 뒤엔 햇빛이 0점이라 날씨가 완벽해도 최대 64점입니다 (`docs/점수_계산식.md` 10-6).
|
- **밤 날씨 점수:** 해가 진 뒤엔 햇빛이 0점이라 날씨가 완벽해도 최대 64점입니다 (`docs/점수_계산식.md` 10-6).
|
||||||
- **점수 기준값:** 대부분 경험으로 잡은 값입니다. 실제 분포(예: 노을 점수가 1년에 며칠 붉음인지)는 아직 확인 중입니다.
|
- **점수 기준값:** 대부분 경험으로 잡은 값입니다. 실제 분포(예: 노을 점수가 1년에 며칠 붉음인지)는 아직 확인 중입니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 날씨 위젯
|
||||||
|
|
||||||
|
기준: 2026-11-26, `feat/embed-widget` (아직 배포 전).
|
||||||
|
|
||||||
|
다른 사이트가 자기 페이지에 붙이는 오늘 날씨 카드입니다. 지금 날씨 점수와 아침·낮·저녁·밤 하늘·기온을 보여 주고, 카드의 `자세히 보기 ›` 버튼을 누르면 날씨각 그 지역 페이지가 새 창으로 열립니다(카드의 다른 곳은 링크가 아닙니다). 누구나 신청 없이 쓸 수 있습니다. 코드는 사용 방법 페이지 https://weather.o2o.kr/widget-guide 에서 지역·모양(기본형·상세형)·배경(기본형·밝은·어두운)을 골라 복사합니다. 붙이는 방법은 스크립트(권장)와 iframe 코드 두 가지입니다. 카드 값은 오늘 피드·오늘 날씨와 같은 데이터로 만들고 지역별로 5분 저장합니다. 붙이는 코드, 크기, 실패할 때 모습, 노출 수 보는 법, 고칠 때 주의할 점은 `docs/위젯_운영.md`에 있습니다.
|
||||||
+241
@@ -0,0 +1,241 @@
|
|||||||
|
# 위젯 운영
|
||||||
|
|
||||||
|
다른 사이트가 붙이는 날씨각 날씨 카드(날씨 위젯)를 운영할 때 볼 문서입니다. 붙이는 코드, 크기, 실패할 때 모습, 노출 수 보는 법, 고칠 때 주의할 점을 모았습니다.
|
||||||
|
|
||||||
|
- 기준: 2026-11-26, `feat/embed-widget` (아직 배포 전)
|
||||||
|
- 설계: `docs/superpowers/specs/2026-11-25-embed-widget-design.md`
|
||||||
|
|
||||||
|
| 장 | 내용 |
|
||||||
|
|---|---|
|
||||||
|
| 1 | 위젯이 무엇이고 코드를 어디서 받나 |
|
||||||
|
| 2 | 크기 규칙 |
|
||||||
|
| 3 | 실패할 때 보이는 것 |
|
||||||
|
| 4 | 노출 수 보는 법 (관리자 API, GA) |
|
||||||
|
| 5 | 붙이는 쪽에 안내할 것 |
|
||||||
|
| 6 | 고칠 때 주의 |
|
||||||
|
| 7 | 알려진 한계 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 위젯이 무엇이고 코드를 어디서 받나
|
||||||
|
|
||||||
|
### 1-1. 위젯
|
||||||
|
|
||||||
|
- 다른 사이트에 붙이는 오늘 날씨 카드입니다. 지금 날씨 점수, 아침·낮·저녁·밤 하늘과 기온을 보여 줍니다.
|
||||||
|
- 카드 오른쪽 위 `자세히 보기 ›` 버튼을 누르면 새 창으로 날씨각 그 지역 페이지(`/today/…`)가 열립니다. 카드의 다른 곳은 링크가 아닙니다(붙인 사이트 방문자가 잘못 눌러 떠나지 않게).
|
||||||
|
- 누구나 신청 없이 씁니다. 막는 장치는 없습니다.
|
||||||
|
- 카드 주소: `GET /embed/card?region=<지역 코드 10자리>&type=side|home&bg=sky|light|dark`
|
||||||
|
- nginx(`frontend/nginx.conf`)가 백엔드 `/v1/embed/card`(`backend/router/v1/embed/embed.py`)로 넘깁니다.
|
||||||
|
- HTML은 `backend/services/embed_service.py`가 만들고, 카드 그림은 `frontend/public/embed/card.js`·`card.css`가 그립니다.
|
||||||
|
|
||||||
|
| 고르는 것 | 주소 값 | 화면 이름 |
|
||||||
|
|---|---|---|
|
||||||
|
| 모양 | `side` | 기본형 |
|
||||||
|
| 모양 | `home` | 상세형 (날짜, 1위 각 한 줄, 상태 줄이 더 나옴) |
|
||||||
|
| 배경 | `sky` | 기본형 배경 |
|
||||||
|
| 배경 | `light` | 밝은 바탕용 |
|
||||||
|
| 배경 | `dark` | 어두운 바탕용 |
|
||||||
|
|
||||||
|
주소 값(`side`·`home`, `sky`·`light`·`dark`)은 이미 붙인 코드가 깨지지 않게 바꾸지 않습니다. 화면 이름만 바꿉니다(`frontend/src/lib/embedWidget.ts`).
|
||||||
|
|
||||||
|
### 1-2. 코드 받는 곳: 사용 방법 페이지
|
||||||
|
|
||||||
|
- 주소: https://weather.o2o.kr/widget-guide (`frontend/src/b/WidgetPage.tsx`). 2026-11-26 전에는 /widget 이었고, 옛 주소는 nginx 가 새 주소로 넘긴다(301)
|
||||||
|
- 할 수 있는 것: 지역·모양·배경 고르기 → 미리보기 → 탭(스크립트·iframe)으로 코드 보기 → 코드 복사
|
||||||
|
- 들어오는 길
|
||||||
|
- 오른쪽 아래 문의 창의 `날씨 위젯 달기 ›` (토스 미니앱에는 이 버튼이 없음)
|
||||||
|
- 검색 (사이트맵에 들어 있음, `frontend/vite.config.ts`)
|
||||||
|
- 토스 미니앱에서 `/widget-guide` 주소로 열면 미리보기 대신 웹 주소(weather.o2o.kr/widget-guide) 안내 한 줄이 나옵니다. 고르기·코드는 그대로입니다.
|
||||||
|
- 지역은 이 페이지에서만 쓰는 값입니다. 여기서 골라도 앱 지역은 바뀌지 않습니다.
|
||||||
|
|
||||||
|
### 1-3. 붙이는 코드 두 가지
|
||||||
|
|
||||||
|
예: 군산시(`5213000000`, 주소 이름 `jeonbuk/gunsan`), 기본형, 기본형 배경. 아래는 `embedScript`·`embedCode`가 실제로 내는 문자열입니다.
|
||||||
|
|
||||||
|
**스크립트 (권장)**
|
||||||
|
|
||||||
|
```html
|
||||||
|
<a class="nalssigak-weather" href="https://weather.o2o.kr/today/jeonbuk/gunsan?utm_source=widget&utm_medium=embed&utm_campaign=fallback"
|
||||||
|
data-region="5213000000" data-type="side" data-bg="sky">군산시 날씨 - 날씨각</a>
|
||||||
|
<script src="https://weather.o2o.kr/embed/widget.js" async></script>
|
||||||
|
```
|
||||||
|
|
||||||
|
- `widget.js`가 링크 자리에 카드 iframe을 끼워 넣습니다.
|
||||||
|
- 스크립트가 막히거나 날씨각에 접속이 안 되면 링크가 그대로 남습니다. 빈 칸이 생기지 않습니다.
|
||||||
|
- 크기 규칙을 날씨각이 나중에 바꾸면, 스크립트로 붙인 사이트는 코드를 안 바꿔도 따라옵니다.
|
||||||
|
|
||||||
|
**iframe 코드**
|
||||||
|
|
||||||
|
```html
|
||||||
|
<iframe src="https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky" title="군산시 날씨 - 날씨각" width="100%" height="245" style="border:0;width:100%;height:auto;aspect-ratio:11/8;min-width:220px;max-width:440px;min-height:245px;max-height:320px;border-radius:28px" loading="lazy" referrerpolicy="origin"></iframe>
|
||||||
|
```
|
||||||
|
|
||||||
|
- 스크립트를 넣을 수 없는 곳(블로그, 사이트 빌더)에 씁니다.
|
||||||
|
- 크기 규칙이 `style`에 들어 있습니다. 붙인 뒤에는 그 사이트에 그대로 남습니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 크기 규칙
|
||||||
|
|
||||||
|
폭은 놓인 자리에 맞춰 자동으로 늘고 줄어듭니다. 높이는 폭에 따라 비율대로 바뀝니다(CSS `aspect-ratio`). 값은 `frontend/src/lib/embedWidget.ts`의 상수입니다.
|
||||||
|
|
||||||
|
| 모양 | 폭 (`EMBED_MIN_WIDTH`~`EMBED_MAX_WIDTH`) | 높이 (`EMBED_HEIGHT`~`EMBED_MAX_HEIGHT`) | 폭:높이 (`EMBED_RATIO`) | 높이가 늘기 시작하는 폭 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 기본형 (`side`) | 220~440px | 245~320px | 11:8 | 약 337px |
|
||||||
|
| 상세형 (`home`) | 280~720px | 400~520px | 18:13 | 약 554px |
|
||||||
|
|
||||||
|
- 최대 폭에서 최대 높이가 됩니다. 그보다 좁으면 비율대로 낮아지다가 기본 높이에서 멈춥니다.
|
||||||
|
- 기본 높이: 카드가 넘치거나 스크롤이 생기지 않고 다 보이는 최소 높이입니다.
|
||||||
|
- 최소 폭: 이름이 가장 긴 지역 '창원시 마산합포구'도 제목·버튼이 다 보이는 폭입니다. 자리가 이보다 좁으면 카드가 자리 밖으로 삐져나옵니다.
|
||||||
|
- `aspect-ratio`를 모르는 옛 브라우저는 기본 높이로 보입니다.
|
||||||
|
- 모서리는 둥글게(28px) 잘립니다. 어두운 사이트에서 모서리 밖이 희게 칠해지는 것을 막습니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 실패할 때 보이는 것
|
||||||
|
|
||||||
|
카드를 못 그려도 오류 화면은 나오지 않습니다. 날씨각으로 가는 링크 하나가 남습니다.
|
||||||
|
|
||||||
|
| 상황 | 보이는 것 |
|
||||||
|
|---|---|
|
||||||
|
| 카드를 그리기 전 | 토끼와 '날씨 불러오는 중…' |
|
||||||
|
| 받은 값이 오늘(한국 날짜) 값이 아님, 그리다 오류 | 카드 가운데 흰 알약 링크 `날씨각에서 날씨 보기 ›` |
|
||||||
|
| 카드 스크립트(`card.js`)가 8초 안에 안 돎 | 토끼가 사라지고 같은 링크 (CSS만으로 보임) |
|
||||||
|
| 방문자 브라우저가 스크립트를 끔 | 같은 링크 (`<noscript>`) |
|
||||||
|
| 카드 데이터 만들기가 8초(`CARD_BUILD_TIMEOUT_SEC`)를 넘김, 피드·예보를 못 받음, 그릴 값이 없음(자정 무렵) | 조용한 화면: 고른 배경 위에 `날씨각에서 날씨 보기 ›` (상태 200) |
|
||||||
|
| 없는 지역 코드 (10자리지만 지역 목록에 없음) | 조용한 화면 (상태 404) |
|
||||||
|
| 주소 값이 틀림 (지역 코드가 10자리 숫자가 아님, `type`·`bg`가 목록 밖) | 조용한 화면 (상태 404). 링크는 날씨각 홈 `/`(`utm_campaign=unknown`), `bg`가 틀리면 `sky` 배경 |
|
||||||
|
| 백엔드가 죽었거나 10초 안에 답하지 않음 (500·502·503·504) | nginx가 `frontend/public/embed/quiet.html`을 줌: `sky` 배경 조용한 화면, 링크는 날씨각 홈 |
|
||||||
|
| `widget.js`가 막힘·안 옴 (붙인 사이트의 보안 설정, 날씨각 접속 불가) | 붙인 사이트에 글자 링크 `군산시 날씨 - 날씨각`이 그대로 남음 |
|
||||||
|
| 스크립트 코드의 `data-region`·`data-type`·`data-bg` 값이 틀림 | `widget.js`가 그 링크는 건드리지 않음. 글자 링크로 남음 |
|
||||||
|
| 붙인 사이트가 iframe을 막음 (`frame-src`) | 브라우저가 빈 칸이나 차단 표시를 띄움. 날씨각 쪽에서 손쓸 수 없음 |
|
||||||
|
|
||||||
|
- 카드 데이터(값)는 지역별로 Redis에 5분 저장합니다(`CARD_TTL_SEC`). 오늘 값이 아니면 저장분을 쓰지 않습니다. 저장분이 있으면 DB를 읽지 않습니다(지역 조회도 안 함).
|
||||||
|
- 저장분이 빈 지역에 요청이 몰리면 지역별 잠금(`lock:widget:card:<지역>`)을 잡은 요청 하나만 만듭니다. 나머지는 최대 4초 저장분을 기다리고, 그래도 없으면 직접 만듭니다. 기다림까지 합쳐 8초 제한 안입니다.
|
||||||
|
- Redis가 안 되면 잠금·저장 없이 매번 만듭니다. 카드는 그대로 나옵니다.
|
||||||
|
- 조용한 화면 모양은 두 곳에 있습니다: 백엔드 `render_quiet`(배경 3가지)와 `quiet.html`(sky 하나). 한쪽을 고치면 다른 쪽도 맞춥니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 노출 수 보는 법
|
||||||
|
|
||||||
|
### 4-1. 무엇을 세나
|
||||||
|
|
||||||
|
- 표 `widget_view_daily` (`day`, `host`, `kind`, `views`): 날짜(한국)·부른 사이트 주소·모양별 하루 노출 수
|
||||||
|
- 카드 요청은 DB에 쓰지 않습니다. 노출 수는 먼저 Redis 해시 `widget:views:<한국 날짜>`(필드 `호스트<탭>모양`)에 쌓이고, 관리자 API(4-2)를 부를 때 표로 옮겨집니다. 그래서 관리자 API를 부르기 전에 Redis를 비우면(`FLUSHDB`, Redis 데이터 삭제) 옮기기 전 수치를 잃습니다.
|
||||||
|
- 부른 사이트 주소는 브라우저가 보내는 `Referer`에서 꺼냅니다. 붙이는 코드에 `referrerpolicy="origin"`이 있어 페이지 경로는 오지 않고 사이트 주소만 옵니다.
|
||||||
|
- 셀 때: 카드를 그려 보낼 때마다 1. 같은 사람이 새로 고쳐도 또 셉니다. 방문자 수가 아니라 카드를 부른 횟수입니다.
|
||||||
|
- 세지 않을 때: 조용한 화면을 보낼 때, 날씨각 자신(사용 방법 페이지 미리보기)이 부를 때
|
||||||
|
|
||||||
|
| `host` 값 | 뜻 |
|
||||||
|
|---|---|
|
||||||
|
| `blog.example.com` 같은 주소 | 그 사이트가 부름 (소문자) |
|
||||||
|
| `(알 수 없음)` | 브라우저가 주소를 안 알려 줌, 또는 주소가 이상함 (IP, 포트만 등) |
|
||||||
|
| `(기타)` | 그날 따로 센 사이트가 500곳(`DAILY_HOST_CAP`)을 넘은 뒤 처음 온 사이트 |
|
||||||
|
|
||||||
|
Redis가 안 되면 그동안의 노출은 세지 못합니다(기록만 남기고 카드는 그대로 나감).
|
||||||
|
|
||||||
|
### 4-2. 관리자 API로 보기
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s -H "X-Admin-Key: $ADMIN_API_KEY" https://weather.o2o.kr/v1/admin/widget/views
|
||||||
|
```
|
||||||
|
|
||||||
|
- 키는 운영 서버 `.env`의 `ADMIN_API_KEY` 값입니다. 키 값을 문서·채팅·명령 기록에 적지 않습니다. 셸 변수로만 넘깁니다.
|
||||||
|
- 키가 틀리거나 서버에 키가 비어 있으면 401 `{"detail":"AUTH_FAILED"}`가 옵니다.
|
||||||
|
- 부를 때마다 먼저 Redis에 쌓인 노출 수(오늘 것 포함)를 표로 옮기고 나서 표를 읽습니다. 날짜 키를 `RENAME`으로 임시 키(`widget:views-flush:<날짜>:<무작위>`)에 떼어 내 옮기므로, 옮기는 동안 온 노출은 원래 키에 새로 쌓였다가 다음에 옮겨집니다.
|
||||||
|
- 표에 쓰지 못하면 그 수치를 원래 키에 되돌려 두어 다음에 부를 때 다시 옮깁니다. 이전에 옮기다 남은 임시 키도 함께 옮깁니다.
|
||||||
|
|
||||||
|
응답 예 (사이트 주소는 가짜 값):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"result": {"success": true, "code": 0, "desc": "SUCCESS"},
|
||||||
|
"items": [
|
||||||
|
{"host": "blog.example.com", "views_7d": 120, "views_30d": 480},
|
||||||
|
{"host": "(알 수 없음)", "views_7d": 15, "views_30d": 60}
|
||||||
|
],
|
||||||
|
"total_7d": 135,
|
||||||
|
"total_30d": 540
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 칸 | 뜻 |
|
||||||
|
|---|---|
|
||||||
|
| `items` | 사이트별 노출 수. 30일 많은 순, 같으면 주소 이름순 |
|
||||||
|
| `views_7d` | 오늘 포함 최근 7일(한국 날짜) |
|
||||||
|
| `views_30d` | 오늘 포함 최근 30일 |
|
||||||
|
| `total_7d`·`total_30d` | 모든 사이트 합 |
|
||||||
|
| `result.success` | `false`면 DB를 못 읽은 것. 숫자를 믿지 않음 |
|
||||||
|
|
||||||
|
- 모양(`kind`)별 숫자는 API에 없습니다. 필요하면 관리자 API를 한 번 불러 Redis 수치를 옮긴 뒤 `widget_view_daily` 표를 직접 봅니다.
|
||||||
|
- 사이트 주소는 브라우저가 알려 주는 값이라 속일 수 있습니다. 추세를 보는 데만 씁니다.
|
||||||
|
|
||||||
|
### 4-3. GA에서 위젯 유입 보기
|
||||||
|
|
||||||
|
카드와 링크에서 날씨각으로 오는 주소에는 `utm_*` 값이 붙습니다. GA4가 이 값으로 유입 경로를 나눕니다.
|
||||||
|
|
||||||
|
| 값 | 내용 |
|
||||||
|
|---|---|
|
||||||
|
| `utm_source` | `widget` |
|
||||||
|
| `utm_medium` | `embed` |
|
||||||
|
| `utm_campaign` | 부른 사이트 주소. `unknown`(주소를 모름, 주소 값이 틀린 조용한 화면, 백엔드가 죽어 `quiet.html`이 나갈 때도), `preview`(날씨각 미리보기), `fallback`(스크립트가 안 돌아 남은 글자 링크) |
|
||||||
|
|
||||||
|
- 보는 곳: GA4 보고서 → 획득 → 트래픽 획득. 측정기준을 '세션 소스/매체'로 두면 `widget / embed`, '세션 캠페인'으로 바꾸면 사이트별로 나옵니다.
|
||||||
|
- 사용 방법 페이지의 GA 이벤트(`widget_guide_view`·`widget_option_select`·`widget_code_copy`)는 `docs/이벤트_추적.md` 이벤트 목록 표의 위젯 행에 있습니다.
|
||||||
|
|
||||||
|
### 4-4. umami에서 카드 조회 보기
|
||||||
|
|
||||||
|
다른 사이트에 붙은 카드가 보일 때마다, 날씨각 umami(`analytics.webforai.kr`, 날씨각 웹과 같은 사이트)에 `/widget` 페이지 조회로 한 번 보냅니다(`backend/services/embed_service.py` 의 `_umami`).
|
||||||
|
|
||||||
|
| umami 화면 | 보이는 것 |
|
||||||
|
|---|---|
|
||||||
|
| 페이지 | `/widget` = 위젯 카드 조회 수 (2026-11-26 까지는 `/widget-card`. 그날 전의 `/widget` 은 사용 방법 페이지 방문) |
|
||||||
|
| 유입 경로 | 카드를 붙인 사이트 주소 |
|
||||||
|
| 페이지 제목 | `날씨 위젯 · 기본형` / `날씨 위젯 · 상세형` |
|
||||||
|
|
||||||
|
- 날씨각 자신의 미리보기(사용 방법 페이지)는 보내지 않습니다. 서버 집계와 같은 기준입니다.
|
||||||
|
- 쿠키를 쓰지 않습니다. umami 스크립트가 늦거나 막혀도 카드는 그대로 보입니다(그 조회만 빠짐).
|
||||||
|
- 날씨각 전체 방문자·조회 수에 위젯 조회가 더해집니다. 위젯을 빼고 보려면 umami에서 페이지 `/widget` 을 필터로 뺍니다.
|
||||||
|
- `data-domains` 가 `weather.o2o.kr` 이라 로컬(`localhost`)에서는 보내지 않습니다.
|
||||||
|
- umami 사이트 ID 는 `frontend/index.html` 과 같아야 합니다(`tests/test_embed.py` 가 확인).
|
||||||
|
- umami 스크립트는 외부(`analytics.webforai.kr/script.js`)에서 직접 부르지 않고 날씨각에 복사해 둔 `frontend/public/embed/umami.js` 를 씁니다(날씨각 웹 `index.html` 도 같음). 기록은 `data-host-url` 의 umami 서버로 갑니다. 외부 스크립트가 바뀌거나 그 서버가 뚫려도 날씨각과 위젯을 붙인 사이트에서 다른 코드가 돌지 않게 하려는 것입니다(무결성 확인 SRI 대신. umami 서버가 다른 사이트의 파일 확인 요청을 허락하지 않아 SRI 를 쓸 수 없다).
|
||||||
|
- umami 서버를 업그레이드한 뒤 기록이 안 쌓이면: `https://analytics.webforai.kr/script.js` 를 다시 받아 `umami.js` 맨 위 주석만 남기고 덮어씁니다. 이 파일은 린트에서 뺐습니다(`frontend/.oxlintrc.json`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 붙이는 쪽에 안내할 것
|
||||||
|
|
||||||
|
| 안내 | 이유 |
|
||||||
|
|---|---|
|
||||||
|
| 사이트 보안 설정(CSP)에 `weather.o2o.kr`을 허용. 스크립트 방식은 `script-src`와 `frame-src`, iframe 방식은 `frame-src` | 허용하지 않으면 스크립트는 글자 링크로 남고, iframe은 빈 칸이 됨 |
|
||||||
|
| 스크립트를 막는 블로그·사이트 빌더는 iframe 코드를 씀 | 스크립트가 지워지면 글자 링크만 남음 |
|
||||||
|
| iframe 코드의 `style`은 지우지 않음 | 크기 범위가 모두 `style`에 있음. 지우면 사이트의 다른 스타일에 밀려 카드가 잘리거나 늘어남 |
|
||||||
|
| 날씨각 링크는 그대로 둠 | 사용 방법 페이지의 조건 |
|
||||||
|
| 스크립트가 끝난 뒤에 새로 생기는 링크는 카드로 바뀌지 않음 | `widget.js`는 처음 실행될 때와 문서를 다 읽었을 때 두 번만 링크를 찾음. 글을 나중에 그리는 블로그나 SPA(화면을 스크립트로 바꾸는 사이트)에서는 글자 링크로 남음. 이런 곳은 iframe 코드를 씀 |
|
||||||
|
| 예고 없이 바뀌거나 중단될 수 있음 | 사용 방법 페이지의 조건 |
|
||||||
|
|
||||||
|
개인정보 질문을 받으면: 카드는 쿠키·브라우저 저장소·통계 스크립트를 쓰지 않습니다. 카드 안에서 밖으로 나가는 요청은 날씨각 글꼴을 받는 Google Fonts뿐입니다(`card.js`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 고칠 때 주의
|
||||||
|
|
||||||
|
| 고치는 것 | 함께 할 일 |
|
||||||
|
|---|---|
|
||||||
|
| `card.css`·`card.js` | `embed_service.py`의 `ASSET_VERSION`을 올림. 카드 HTML이 `?v=` 값으로 새 파일을 부르고, 같은 값이 카드 데이터 저장 키(`widget:card:v{ASSET_VERSION}:{지역}`)에도 들어가 옛 모양에 맞춘 저장분을 버림 |
|
||||||
|
| 배포 | 백엔드와 프런트를 함께 올림 (`deploy.sh`는 함께 올림). 백엔드만 먼저 나가면 새 `?v=` 주소로 옛 `card.css`를 받아 방문자 브라우저가 1시간 저장함 |
|
||||||
|
| `widget.js` | 주소에 버전이 없음. 고치면 nginx 캐시(`/embed/` 1시간) 때문에 최대 1시간 뒤 모든 사이트에 반영됨. 이미 붙인 코드(링크 모양, `data-*` 이름)가 그대로 돌게 고침 |
|
||||||
|
| 크기 상수 | `embedWidget.ts`와 `widget.js`의 `SIZE`를 같이 바꿈. 어긋나면 `frontend/tests/embedLoader.test.mjs`가 실패함 (`frontend`에서 `npm test`) |
|
||||||
|
| 조용한 화면 모양 | 백엔드 `render_quiet`와 `frontend/public/embed/quiet.html`을 같이 맞춤 |
|
||||||
|
| 주소 값 (`side`·`home`, `sky`·`light`·`dark`) | 바꾸지 않음. 이미 붙인 코드가 깨짐 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 알려진 한계
|
||||||
|
|
||||||
|
- **원치 않는 사이트를 막을 수 없음.** 신청 없이 누구나 붙입니다. 막아야 할 사이트가 생기면 차단 기능을 따로 만들어야 합니다.
|
||||||
|
- **집계의 사이트 주소는 속일 수 있음.** `Referer`는 브라우저가 보내는 값입니다. 추세용으로만 봅니다.
|
||||||
|
- **관리자 API를 부르기 전 노출 수는 Redis에만 있음.** Redis를 비우거나 Redis 데이터가 사라지면 그 수치를 잃습니다. 오래 부르지 않아도 키는 날짜마다 하나씩 쌓일 뿐이라 크지 않습니다.
|
||||||
|
- **iframe 코드로 붙인 사이트는 그때 규칙 그대로.** 크기 규칙을 바꿔도 그 사이트가 코드를 새로 붙이기 전까지는 옛 `style`이 남습니다. 스크립트로 붙인 사이트는 따라옵니다.
|
||||||
|
- **문의 창으로 들어온 위젯 페이지를 새로 고치면 `from: contact`가 다시 집계됨.** 들어온 경로를 방문 기록에 들고 있어서, 새로 고치면 `widget_guide_view`가 `from: contact`로 한 번 더 남습니다.
|
||||||
+9
-7
@@ -31,6 +31,8 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
|||||||
| `로그인` (코드 `login`) | 로그인 성공 (이미 있던 계정) | `method: 'id' \| 'google' \| 'toss'`(앱인토스) | `Sheets.tsx` `LoginSheet` `done`, `TossLoginSheet` |
|
| `로그인` (코드 `login`) | 로그인 성공 (이미 있던 계정) | `method: 'id' \| 'google' \| 'toss'`(앱인토스) | `Sheets.tsx` `LoginSheet` `done`, `TossLoginSheet` |
|
||||||
| `회원가입` (코드 `sign_up`) | 가입 성공 (구글·토스로 처음 들어와 계정이 새로 생김, 서버 응답 `is_new`) | `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' \| 'auto'` | `Sheets.tsx` `RegionSheet`, `region.tsx` `locate`·`follow` |
|
| `지역_변경` (코드 `region_change`) | 지역 목록에서 고름, 위치로 가까운 구를 찾음, 또는 다시 들어왔을 때 지금 위치로 구가 바뀜 | `region_name`, `method: 'list' \| 'location' \| 'auto'` | `Sheets.tsx` `RegionSheet`, `region.tsx` `locate`·`follow` |
|
||||||
|
| `지역안내_말풍선_노출` (코드 `region_hint_view`) | 위쪽 지역 버튼 아래 '다른 동네 날씨도 볼 수 있어요' 말풍선이 뜸 (앱을 열거나 새로고침할 때마다 한 번. 첫 화면 덮개·토스 소개가 걷힌 뒤, 쇼츠 페이지 제외. 화면을 만지면 사라짐) | 없음 | `BLayout.tsx` `TopBar` |
|
||||||
|
| `지역안내_말풍선_누름` (코드 `region_hint_tap`) | 말풍선이 떠 있는 동안 말풍선이나 지역 버튼을 눌러 지역 창을 엶 (지역 창을 연 전체 횟수는 `창_열기`의 `sheet: 'region'`) | `from: 'bubble' \| 'button'`(말풍선·지역 버튼) | `BLayout.tsx` `TopBar` `openRegion` |
|
||||||
| `설치배너_노출` (코드 `install_banner_view`) | 오늘 탭의 '홈 화면에 추가' 카드가 보임 (설치할 수 있는 곳에서, 닫은 지 2주 안 지났으면 안 보임) | 없음 | `installBanner.tsx` `InstallBanner` |
|
| `설치배너_노출` (코드 `install_banner_view`) | 오늘 탭의 '홈 화면에 추가' 카드가 보임 (설치할 수 있는 곳에서, 닫은 지 2주 안 지났으면 안 보임) | 없음 | `installBanner.tsx` `InstallBanner` |
|
||||||
| `설치_누름` (코드 `install_click`) | '홈 화면에 추가'를 누름 | `from: 'banner' \| 'menu'`(카드·내 정보 메뉴), `method: 'prompt' \| 'guide'`(설치창을 띄움·기기별 안내를 염) | `install.ts` `useInstall` |
|
| `설치_누름` (코드 `install_click`) | '홈 화면에 추가'를 누름 | `from: 'banner' \| 'menu'`(카드·내 정보 메뉴), `method: 'prompt' \| 'guide'`(설치창을 띄움·기기별 안내를 염) | `install.ts` `useInstall` |
|
||||||
| `설치_선택` (코드 `install_choice`) | 설치창에서 고름 (안드로이드·PC Chrome·Edge) | `outcome: 'accepted' \| 'dismissed'` | `install.ts` `promptInstall` |
|
| `설치_선택` (코드 `install_choice`) | 설치창에서 고름 (안드로이드·PC Chrome·Edge) | `outcome: 'accepted' \| 'dismissed'` | `install.ts` `promptInstall` |
|
||||||
@@ -38,7 +40,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
|||||||
| `앱_실행` (코드 `app_launch`) | 홈 화면 아이콘(설치한 앱)으로 엶, 또는 날씨각 안드로이드 앱(웹뷰)을 켬 | `mode: 'standalone' \| 'android_app'`, `version`(앱일 때 앱 버전) | `main.tsx` |
|
| `앱_실행` (코드 `app_launch`) | 홈 화면 아이콘(설치한 앱)으로 엶, 또는 날씨각 안드로이드 앱(웹뷰)을 켬 | `mode: 'standalone' \| 'android_app'`, `version`(앱일 때 앱 버전) | `main.tsx` |
|
||||||
| `앱_연결_오류` (코드 `app_bridge_error`) | 앱 안에서 웹이 앱에 시킨 일이 실패함 (사용자가 구글 계정창·공유창을 닫거나 위치 권한을 거부한 것은 안 보냄) | `action: 'google_login' \| 'share' \| 'location'` | `googleLogin.tsx` `AppGoogleButton`, `Sheets.tsx` `ShareSheet` `send`, `region.tsx` `findNearest` |
|
| `앱_연결_오류` (코드 `app_bridge_error`) | 앱 안에서 웹이 앱에 시킨 일이 실패함 (사용자가 구글 계정창·공유창을 닫거나 위치 권한을 거부한 것은 안 보냄) | `action: 'google_login' \| 'share' \| 'location'` | `googleLogin.tsx` `AppGoogleButton`, `Sheets.tsx` `ShareSheet` `send`, `region.tsx` `findNearest` |
|
||||||
| `첫화면_멈춤` (코드 `boot_stuck`) | 8초 넘게 '날씨 불러오는 중' 첫 화면이 남음 (페이지마다 한 번) | `reason`(첫 오류 문구, 100자), `seconds`, `tries`(연달아 다시 불러온 횟수), `app_started`(앱 파일 실행 여부) | `index.html` 첫 화면 스크립트 |
|
| `첫화면_멈춤` (코드 `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`·`contact`) | `Sheets.tsx` `SheetProvider` `open` |
|
| `창_열기` (코드 `sheet_open`) | 아래에서 올라오는 창이 열림 (각·글·보내기·댓글·로그인·내 정보·지역·내 각·홈 화면 추가·점수 근거·이야기 등) | `sheet`(창 종류: `gak`·`article`·`share`·`comments`·`login`·`me`·`region`·`mix`·`myGak`·`install`·`weatherWhy`·`talk`·`seasonWeek`·`contact`). `region`에는 위젯 페이지(/widget-guide)의 지역 '바꾸기 ›'로 연 지역 고르기 창도 섞인다 | `Sheets.tsx` `SheetProvider` `open` |
|
||||||
| `좋아요` (코드 `like`) | 좋아요 성공 (취소는 안 보냄) | `content_type: 'post' \| 'comment' \| 'talk' \| 'hero_post' \| 'gak_post' \| 'foliage_post' \| 'events_post' \| 'season_post'`, `item_id`(포스트·댓글·글 번호). `foliage_post`는 계절 지도 카드 자리라 단풍 지도가 끝나면 첫눈 지도 카드(~12/20), 그 뒤 해돋이 지도 카드(~2월)의 좋아요가 이 값으로 찍힌다 | `Post.tsx` `FullCard`, `pinnedLike.ts`, `Sheets.tsx` `CommentRow`, `talk.tsx` |
|
| `좋아요` (코드 `like`) | 좋아요 성공 (취소는 안 보냄) | `content_type: 'post' \| 'comment' \| 'talk' \| 'hero_post' \| 'gak_post' \| 'foliage_post' \| 'events_post' \| 'season_post'`, `item_id`(포스트·댓글·글 번호). `foliage_post`는 계절 지도 카드 자리라 단풍 지도가 끝나면 첫눈 지도 카드(~12/20), 그 뒤 해돋이 지도 카드(~2월)의 좋아요가 이 값으로 찍힌다 | `Post.tsx` `FullCard`, `pinnedLike.ts`, `Sheets.tsx` `CommentRow`, `talk.tsx` |
|
||||||
| `댓글` (코드 `comment`) | 댓글 올리기 성공 | `post_id` | `Sheets.tsx` `CommentsSheet` `send` |
|
| `댓글` (코드 `comment`) | 댓글 올리기 성공 | `post_id` | `Sheets.tsx` `CommentsSheet` `send` |
|
||||||
| `이야기_댓글` (코드 `talk_comment`) | 사람 글에 댓글 올리기 성공 (로그인한 사람만) | `talk_id`(글 번호) | `Sheets.tsx` `CommentsSheet` `send` |
|
| `이야기_댓글` (코드 `talk_comment`) | 사람 글에 댓글 올리기 성공 (로그인한 사람만) | `talk_id`(글 번호) | `Sheets.tsx` `CommentsSheet` `send` |
|
||||||
@@ -86,6 +88,9 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
|||||||
| `유형_각_누름` (코드 `type_gak`) | 결과 화면의 잘 맞는 각을 눌러 각 상세 창을 엶 | `type`, `index_code`(각 코드), `score`(오늘 점수) | `TypePage.tsx` `Result` |
|
| `유형_각_누름` (코드 `type_gak`) | 결과 화면의 잘 맞는 각을 눌러 각 상세 창을 엶 | `type`, `index_code`(각 코드), `score`(오늘 점수) | `TypePage.tsx` `Result` |
|
||||||
| `유형_궁합_누름` (코드 `type_match`) | 결과 화면 궁합표에서 다른 유형을 눌러 그 결과 화면으로 감 | `type`, `to_type`, `level: 'best' \| 'good' \| 'fun' \| 'bad'`(찰떡·잘 맞아요·서로 달라서 재밌어요·삐걱삐걱) | `TypePage.tsx` `Result` |
|
| `유형_궁합_누름` (코드 `type_match`) | 결과 화면 궁합표에서 다른 유형을 눌러 그 결과 화면으로 감 | `type`, `to_type`, `level: 'best' \| 'good' \| 'fun' \| 'bad'`(찰떡·잘 맞아요·서로 달라서 재밌어요·삐걱삐걱) | `TypePage.tsx` `Result` |
|
||||||
| `유형_오늘로` (코드 `type_to_today`) | 결과 화면에서 '오늘 날씨 보러 가기'를 누름 | `type` | `TypePage.tsx` `Result` |
|
| `유형_오늘로` (코드 `type_to_today`) | 결과 화면에서 '오늘 날씨 보러 가기'를 누름 | `type` | `TypePage.tsx` `Result` |
|
||||||
|
| `위젯_안내_보기` (코드 `widget_guide_view`) | 날씨 위젯 사용 방법 페이지(/widget-guide, 2026-11-26 전에는 /widget)를 엶 | `from: 'contact' \| 'direct'`(문의 창의 '날씨 위젯 달기'로 옴·그 밖에 주소·검색 등으로 바로 옴) | `WidgetPage.tsx` |
|
||||||
|
| `위젯_옵션_고름` (코드 `widget_option_select`) | 위젯 페이지에서 모양·배경을 바꾸거나 지역을 고름 (지역은 이 페이지의 '바꾸기 ›' 창에서 고를 때만. 앱 지역이 바뀌어도 세지 않음) | `option: 'region' \| 'kind' \| 'bg'`, `value`(지역 코드·`side`·`home`·`sky`·`light`·`dark`) | `WidgetPage.tsx` |
|
||||||
|
| `위젯_코드_복사` (코드 `widget_code_copy`) | 위젯 페이지 '코드 복사' 성공 (클립보드를 못 써 직접 복사하게 한 것은 세지 않음) | `kind: 'side' \| 'home'`, `bg: 'sky' \| 'light' \| 'dark'`, `region`(지역 코드), `method: 'script' \| 'iframe'`(복사한 코드: 스크립트·iframe) | `WidgetPage.tsx` |
|
||||||
|
|
||||||
- 공유창에서 사용자가 취소하면 `share`를 보내지 않는다.
|
- 공유창에서 사용자가 취소하면 `share`를 보내지 않는다.
|
||||||
- 날씨 유형 테스트는 유입(`type_landing`) → 시작(`type_start`) → 결과(`type_result`) → 공유(`type_share`) 순서로 본다. 공유는 그림을 붙이지 않고 주소만 보내서 `share`가 아니라 `type_share`로 따로 잡는다. 공유창을 그냥 닫으면 보내지 않는다.
|
- 날씨 유형 테스트는 유입(`type_landing`) → 시작(`type_start`) → 결과(`type_result`) → 공유(`type_share`) 순서로 본다. 공유는 그림을 붙이지 않고 주소만 보내서 `share`가 아니라 `type_share`로 따로 잡는다. 공유창을 그냥 닫으면 보내지 않는다.
|
||||||
@@ -98,12 +103,9 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
|||||||
|
|
||||||
## 앱 (안드로이드, `mobile/`)
|
## 앱 (안드로이드, `mobile/`)
|
||||||
|
|
||||||
- **웹뷰 셸 전환(`feat/app-webview-shell`)**: 앱이 날씨각 웹을 웹뷰로 띄우는 껍데기가 되면 아래 앱 이벤트는 쓰지 않고, 웹이 같은 이벤트를 그대로 보내며 `platform: 'android_app'`으로 찍힌다. 앱 안에서 구글 로그인·공유·위치가 실패하면 `app_bridge_error`, 앱을 켜면 `app_launch`(`mode: 'android_app'`)가 나간다. 앱 사용자는 `platform`으로 가른다.
|
- 앱은 날씨각 웹을 웹뷰로 띄우는 껍데기라(`mobile/src/components/web-shell.tsx`) 앱에서 따로 보내는 이벤트가 없다. 웹이 같은 이벤트를 그대로 보내고 `platform: 'android_app'`으로 찍힌다. 앱 사용자는 `platform`으로 가른다.
|
||||||
|
- 앱에서만 나가는 것: 앱을 켜면 `app_launch`(`mode: 'android_app'`), 앱 안에서 구글 로그인·공유·위치가 실패하면 `app_bridge_error`. 둘 다 웹 코드가 보낸다.
|
||||||
- 앱도 같은 이벤트 이름·값으로 `track()`을 부른다 (`mobile/src/lib/analytics.ts`). 모든 이벤트에 `platform: 'app'`이 붙는다.
|
- 예전 네이티브 화면과 그 화면의 `track()`(`mobile/src/lib/analytics.ts`)은 지웠다. 새 화면·이벤트는 웹(`frontend/`)에만 더한다.
|
||||||
- **아직 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 설정
|
## GA4 설정
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||||
"plugins": ["react", "typescript", "oxc"],
|
"plugins": ["react", "typescript", "oxc"],
|
||||||
|
"ignorePatterns": ["public/embed/umami.js"],
|
||||||
"rules": {
|
"rules": {
|
||||||
"react/rules-of-hooks": "error",
|
"react/rules-of-hooks": "error",
|
||||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||||
|
|||||||
+7
-5
@@ -10,8 +10,9 @@
|
|||||||
|
|
||||||
gtag('config', 'G-D378J4X373', { platform: '%MODE%' === 'toss' ? 'toss' : /NalssigakApp\//.test(navigator.userAgent) ? 'android_app' : 'web' });
|
gtag('config', 'G-D378J4X373', { platform: '%MODE%' === 'toss' ? 'toss' : /NalssigakApp\//.test(navigator.userAgent) ? 'android_app' : 'web' });
|
||||||
</script>
|
</script>
|
||||||
<!-- 유입 추적 (analytics.webforai.kr) — weather.o2o.kr 에서만 보낸다 -->
|
<!-- 유입 추적 (analytics.webforai.kr) — weather.o2o.kr 에서만 보낸다. 스크립트는 날씨각에 복사해 둔 것을 쓰고(외부 스크립트를 직접 실행하지 않게) 기록만 umami 서버로 보낸다 -->
|
||||||
<script defer src="https://analytics.webforai.kr/script.js"
|
<script defer src="/embed/umami.js"
|
||||||
|
data-host-url="https://analytics.webforai.kr"
|
||||||
data-website-id="b2244cf7-9b43-49c0-b1c0-acfaaab95ddb"
|
data-website-id="b2244cf7-9b43-49c0-b1c0-acfaaab95ddb"
|
||||||
data-domains="weather.o2o.kr,www.weather.o2o.kr"
|
data-domains="weather.o2o.kr,www.weather.o2o.kr"
|
||||||
data-exclude-search="true"
|
data-exclude-search="true"
|
||||||
@@ -111,14 +112,15 @@
|
|||||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||||
<meta name="theme-color" content="#d6ebff" />
|
<meta name="theme-color" content="#d6ebff" />
|
||||||
<meta name="description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 내 사주와 오늘 날씨를 함께 보는 날씨 사주, 오늘의 날씨 코디, 날씨 타로, 날씨 게임도 있어요. 노을이 예쁜 시간과 이번 주말 축제까지 확인하세요." />
|
<!-- 설명은 80자 이내 (네이버 서치어드바이저 사이트 간단 체크 기준). og·twitter 설명도 같은 문구 -->
|
||||||
|
<meta name="description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 날씨 사주·코디·타로·게임, 노을 시간, 주말 축제도 확인하세요." />
|
||||||
<meta name="keywords" content="날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달, 날씨 사주, 오늘의 코디, 날씨 코디, 날씨 타로, 날씨 게임" />
|
<meta name="keywords" content="날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달, 날씨 사주, 오늘의 코디, 날씨 코디, 날씨 타로, 날씨 게임" />
|
||||||
<title>날씨각 · 오늘 날씨 지수, 날씨 사주, 노을, 주말 행사</title>
|
<title>날씨각 · 오늘 날씨 지수, 날씨 사주, 노을, 주말 행사</title>
|
||||||
<link rel="manifest" href="/manifest.webmanifest" />
|
<link rel="manifest" href="/manifest.webmanifest" />
|
||||||
<meta property="og:type" content="website" />
|
<meta property="og:type" content="website" />
|
||||||
<meta property="og:site_name" content="날씨각" />
|
<meta property="og:site_name" content="날씨각" />
|
||||||
<meta property="og:title" content="날씨각 · 오늘 날씨 지수, 날씨 사주, 노을, 주말 행사" />
|
<meta property="og:title" content="날씨각 · 오늘 날씨 지수, 날씨 사주, 노을, 주말 행사" />
|
||||||
<meta property="og:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 내 사주와 오늘 날씨를 함께 보는 날씨 사주, 오늘의 날씨 코디, 날씨 타로, 날씨 게임도 있어요. 노을이 예쁜 시간과 이번 주말 축제까지 확인하세요." />
|
<meta property="og:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 날씨 사주·코디·타로·게임, 노을 시간, 주말 축제도 확인하세요." />
|
||||||
<meta property="og:url" content="%VITE_SITE_URL%/" />
|
<meta property="og:url" content="%VITE_SITE_URL%/" />
|
||||||
<link rel="canonical" href="%VITE_SITE_URL%/" />
|
<link rel="canonical" href="%VITE_SITE_URL%/" />
|
||||||
<meta property="og:image" content="%VITE_SITE_URL%/og.png" />
|
<meta property="og:image" content="%VITE_SITE_URL%/og.png" />
|
||||||
@@ -127,7 +129,7 @@
|
|||||||
<meta property="og:image:alt" content="날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스" />
|
<meta property="og:image:alt" content="날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스" />
|
||||||
<meta name="twitter:card" content="summary_large_image" />
|
<meta name="twitter:card" content="summary_large_image" />
|
||||||
<meta name="twitter:title" content="날씨각 · 오늘 날씨 지수, 날씨 사주, 노을, 주말 행사" />
|
<meta name="twitter:title" content="날씨각 · 오늘 날씨 지수, 날씨 사주, 노을, 주말 행사" />
|
||||||
<meta name="twitter:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 내 사주와 오늘 날씨를 함께 보는 날씨 사주, 오늘의 날씨 코디, 날씨 타로, 날씨 게임도 있어요. 노을이 예쁜 시간과 이번 주말 축제까지 확인하세요." />
|
<meta name="twitter:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 날씨 사주·코디·타로·게임, 노을 시간, 주말 축제도 확인하세요." />
|
||||||
<meta name="twitter:image" content="%VITE_SITE_URL%/og.png" />
|
<meta name="twitter:image" content="%VITE_SITE_URL%/og.png" />
|
||||||
<meta property="og:locale" content="ko_KR" />
|
<meta property="og:locale" content="ko_KR" />
|
||||||
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
|
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
|
||||||
|
|||||||
@@ -42,6 +42,36 @@ server {
|
|||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 위젯 사용 방법 페이지는 /widget-guide 로 옮겼다(2026-11-26). 옛 주소는 앱을 띄우지 않고 바로 넘긴다 —
|
||||||
|
# 앱에서 넘기면 umami 에 /widget(이제 위젯 카드 조회 이름)이 먼저 찍혀 섞인다
|
||||||
|
location = /widget {
|
||||||
|
return 301 /widget-guide$is_args$args;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 다른 사이트에 붙이는 날씨 카드: 백엔드가 HTML 을 만든다 (Referer 는 노출 집계에 쓴다)
|
||||||
|
# 백엔드가 죽었거나(502) 10초 안에 답하지 않으면(504) 오류 화면 대신 조용한 화면(quiet.html, 200)을 준다.
|
||||||
|
# 404(잘못된 입력)는 백엔드가 만든 조용한 화면 그대로 둔다. 백엔드는 카드 만들기를 8초에 끊는다(CARD_BUILD_TIMEOUT_SEC)
|
||||||
|
location = /embed/card {
|
||||||
|
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||||
|
set $api http://backend:9800;
|
||||||
|
proxy_pass $api/v1/embed/card$is_args$args;
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_connect_timeout 3s;
|
||||||
|
proxy_read_timeout 10s;
|
||||||
|
proxy_intercept_errors on;
|
||||||
|
error_page 500 502 503 504 = @embed_quiet;
|
||||||
|
}
|
||||||
|
|
||||||
|
location @embed_quiet {
|
||||||
|
add_header Cache-Control "no-store";
|
||||||
|
try_files /embed/quiet.html =404;
|
||||||
|
}
|
||||||
|
# 카드가 쓰는 정적 파일. 이름에 해시가 없어 짧게 캐시하고, 고치면 주소의 ?v= 를 올린다
|
||||||
|
location /embed/ {
|
||||||
|
add_header Cache-Control "public, max-age=3600";
|
||||||
|
try_files $uri =404;
|
||||||
|
}
|
||||||
|
|
||||||
# API 는 같은 주소로 받아 backend 컨테이너로 넘긴다
|
# API 는 같은 주소로 받아 backend 컨테이너로 넘긴다
|
||||||
location /v1/ {
|
location /v1/ {
|
||||||
# 카드뉴스 올리기(/v1/card)는 1080×1350 JPEG 최대 20장을 base64 로 한 번에 보낸다 (기본 1m 로는 413)
|
# 카드뉴스 올리기(/v1/card)는 1080×1350 JPEG 최대 20장을 base64 로 한 번에 보낸다 (기본 1m 로는 413)
|
||||||
|
|||||||
@@ -0,0 +1,887 @@
|
|||||||
|
/* 날씨각 카드 — 다른 사이트가 iframe 으로 붙이는 /embed/card 의 모양 (그리는 것은 card.js).
|
||||||
|
군산각(https://gunsan.webforai.kr/ 의 style.css, 2026-11-25 받은 것)에서 .wx 카드 규칙과 그 규칙이 쓰는 @keyframes,
|
||||||
|
.vh 를 옮겨 왔다. 원본과 다른 곳:
|
||||||
|
1. 원본의 html.js(스크립트가 도는 페이지) → :root. 이 화면은 늘 card.js 가 그린다. 우선순위(클래스 수)는 원본과 같다.
|
||||||
|
2. 카드 높이 401px(상세형 home)·246px(기본형 side) → 100%. 상자가 iframe 을 꽉 채우고, iframe 높이를 그 값으로 준다.
|
||||||
|
기본 높이를 400px(상세형)·245px(기본형)로 맞추려고 아래 여백을 1px 줄였다(:root .wx-home, :root .wx-side).
|
||||||
|
3. 군산각 :root 변수(--ink 등) 중 카드가 쓰는 것과, 군산각 기본 규칙 중 카드 안에서 먹던 것(box-sizing, p·ol 바깥
|
||||||
|
여백, body 의 글자 설정, img·a 기본값)을 아래 첫 두 덩어리에 옮겼다. 기본 규칙은 :where(.wx) 로 카드 안에만,
|
||||||
|
원본처럼 낮은 우선순위로 둔다.
|
||||||
|
4. 뺀 것: 외국어판(.wx-intl, .wx-fold·.wx-fl·.wx-fd), 군산각 옆 패널이 낮은 창에서 접히는 규칙
|
||||||
|
(@media (min-width: 1200px) and (max-height: …)), 시계로 미리 칠하는 html[data-wxt] 갈래.
|
||||||
|
5. 더한 것: html·body 초기화, 상세형(home)의 한마디·요약 한 줄, 상태 줄 두 줄까지 (넘친 글이 반쯤 잘려 보이지 않게),
|
||||||
|
스크립트가 돌지 않을 때의 링크(.wx-ns), 상세형(home) 날짜가 통째로 안 들어가면 숨기기(.is-nodt, card.js 가 붙인다).
|
||||||
|
6. 그리기 전 자리 표시(빈 원과 띠, --wx-skel)를 빼고 토끼 로딩 화면(.wx-load, 날씨각 앱 첫 화면과 같은 토끼와
|
||||||
|
'날씨 불러오는 중…')을 둔다. 못 그리면(is-failed) 가운데 흰 알약 링크 '날씨각에서 날씨 보기 ›'(원본은 '○○ 날씨 보기'와
|
||||||
|
새 창 그림 .icon·.wx-x, 둘 다 뺐다). 8초가 지나도 is-ready·is-failed 가 안 붙으면(card.js 가 안 옴) 스크립트 없이
|
||||||
|
애니메이션 지연만으로 토끼를 감추고 같은 링크를 보인다. 나중에라도 그려지면 그린 카드가 이긴다.
|
||||||
|
7. 기본형(side)도 상세형(home)처럼 모서리를 28px 로 둥글게 했다(원본은 각진 모서리).
|
||||||
|
로딩·실패 화면은 상자(.wx) 안에 있어 같은 모서리로 잘린다.
|
||||||
|
8. 원본은 다 그린 카드 전체가 링크(.wx-go::after 가 카드를 덮음)다. 여기서는 '자세히 보기 ›' 버튼만 링크다 — 붙인 사이트
|
||||||
|
방문자가 카드를 잘못 눌러 페이지를 떠나지 않게. ::after 는 버튼의 눌리는 자리를 위아래로 넓히는 데만 쓴다.
|
||||||
|
9. 아래 4칸이 버튼(.wx-cell, card.js 가 누르면 그 시간대로 다시 그린다)이다. 모양은 원본 칸 그대로이고, 원본의 '지금'
|
||||||
|
칸 강조(li.is-now)를 보이는 칸 강조(.wx-cell.is-on)로 옮겼다. 다른 시간대를 보일 때 상세형 요약·상태 줄은 자리만 남긴다.
|
||||||
|
배경(상자 클래스 wx-bg-*, card.js 는 몰라도 된다):
|
||||||
|
- sky: 군산각 그대로, 시간대별 하늘.
|
||||||
|
- light: 밝은 바탕 사이트용. 시간대별 하늘을 옅은 파스텔로, 어두운 글자, 얇은 안쪽 테두리, 별 없음, 흰 구름.
|
||||||
|
- dark: 어두운 바탕 사이트용. 시간대별 하늘을 짙게, 흰 글자, 밤에는 별, 푸른 회색 구름.
|
||||||
|
해·달·구름·비·눈과 움직임은 셋이 같다. */
|
||||||
|
|
||||||
|
/* 군산각 :root 값 (--focus 는 원본도 var(--sea), --link 는 var(--sea-hi)) */
|
||||||
|
:root {
|
||||||
|
--ink: #172033;
|
||||||
|
--sea: #2F6FC9;
|
||||||
|
--sea-hi: #255DAF;
|
||||||
|
--sea-deep: #1D4F96;
|
||||||
|
--link: var(--sea-hi);
|
||||||
|
--focus: var(--sea);
|
||||||
|
--ease-out: cubic-bezier(.16, 1, .3, 1);
|
||||||
|
--fb: cubic-bezier(.25, .1, .25, 1);
|
||||||
|
--font: 'Pretendard', 'Pretendard Fallback Noto', 'Pretendard Fallback WQY', 'Pretendard Fallback Inter', -apple-system, BlinkMacSystemFont, 'Apple SD Gothic Neo', 'Noto Sans KR', 'Malgun Gothic', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 카드 화면: 카드 하나뿐이다. 바탕은 붙인 사이트가 비쳐 보이게 투명, 스크롤바 없음 */
|
||||||
|
html {
|
||||||
|
-webkit-text-size-adjust: 100%;
|
||||||
|
text-size-adjust: 100%;
|
||||||
|
}
|
||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
height: 100%;
|
||||||
|
background: transparent;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 군산각 기본 규칙 중 카드 안에서 먹던 것 (*, p·ol, li, img, a, body 의 글자) */
|
||||||
|
:where(.wx, .wx *, .wx *::before, .wx *::after) {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
:where(.wx) :where(p, ol) {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
:where(.wx) :where(p, li) {
|
||||||
|
text-wrap: pretty;
|
||||||
|
}
|
||||||
|
:where(.wx) :where(img) {
|
||||||
|
max-width: 100%;
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
:where(.wx) :where(a) {
|
||||||
|
color: var(--link);
|
||||||
|
text-decoration: none;
|
||||||
|
transition: color .2s var(--fb);
|
||||||
|
}
|
||||||
|
:where(.wx) {
|
||||||
|
font: 400 17px/1.47 var(--font);
|
||||||
|
letter-spacing: -.01em;
|
||||||
|
word-break: keep-all;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
line-break: strict;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
text-rendering: optimizeLegibility;
|
||||||
|
}
|
||||||
|
|
||||||
|
.vh {
|
||||||
|
position: absolute !important;
|
||||||
|
width: 1px;
|
||||||
|
height: 1px;
|
||||||
|
overflow: hidden;
|
||||||
|
clip: rect(0 0 0 0);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- 카드 (군산각 style.css 의 .wx 규칙) */
|
||||||
|
.wx {
|
||||||
|
position: relative;
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
.wx-h {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 6px;
|
||||||
|
margin: 0;
|
||||||
|
padding: 12px 14px;
|
||||||
|
}
|
||||||
|
.wx-t {
|
||||||
|
font: 700 13.5px/1.3 var(--font);
|
||||||
|
color: var(--sea-deep);
|
||||||
|
letter-spacing: -.01em;
|
||||||
|
}
|
||||||
|
.wx-dt, .wx-ar {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.wx-go {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
min-height: 24px;
|
||||||
|
font: 700 12.5px/1.3 var(--font);
|
||||||
|
color: var(--sea-deep);
|
||||||
|
text-decoration: underline;
|
||||||
|
text-decoration-thickness: 1px;
|
||||||
|
text-underline-offset: .18em;
|
||||||
|
}
|
||||||
|
.wx-go:hover {
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
.wx-b:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.wx-home .wx-h {
|
||||||
|
padding: 16px 18px;
|
||||||
|
}
|
||||||
|
.wx-home .wx-t {
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
@media (max-width: 1023px) {
|
||||||
|
.wx-go {
|
||||||
|
min-height: 44px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
:where(:root .wx) {
|
||||||
|
--wx-bg: linear-gradient(#9fd3ff, #cfe9ff 55%, #f1f8ff);
|
||||||
|
--wx-fg: #28304a;
|
||||||
|
--wx-strip: rgba(255, 255, 255, .42);
|
||||||
|
--wx-o1: .85;
|
||||||
|
--wx-o2: .75;
|
||||||
|
--wx-o3: .75;
|
||||||
|
--wx-warn: #a8401a;
|
||||||
|
}
|
||||||
|
:root .wx {
|
||||||
|
isolation: isolate;
|
||||||
|
overflow: hidden;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
padding: 12px 16px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 28px;
|
||||||
|
background: var(--wx-bg);
|
||||||
|
color: var(--wx-fg);
|
||||||
|
}
|
||||||
|
.wx[data-t=morning] {
|
||||||
|
--wx-bg: linear-gradient(#ffd9b8, #ffe9d4 40%, #dff0ff);
|
||||||
|
}
|
||||||
|
.wx:is([data-t=morning], [data-t=day]):is([data-sky=cloudy], [data-sky=rain], [data-sky=snow], [data-sky=sleet]) {
|
||||||
|
--wx-bg: linear-gradient(#a9bbd0, #cbd7e4 55%, #eef2f7);
|
||||||
|
}
|
||||||
|
.wx[data-t=sunset] {
|
||||||
|
--wx-bg: linear-gradient(#4c42b0, #6a48b0 45%, #8e4482);
|
||||||
|
--wx-fg: #fff;
|
||||||
|
--wx-strip: rgba(255, 255, 255, .14);
|
||||||
|
--wx-o2: .85;
|
||||||
|
--wx-o3: 1;
|
||||||
|
--wx-warn: #ffd2b8;
|
||||||
|
}
|
||||||
|
.wx[data-t=night] {
|
||||||
|
--wx-bg: linear-gradient(#141b3d, #27306a 60%, #3d3f86);
|
||||||
|
--wx-fg: #fff;
|
||||||
|
--wx-strip: rgba(255, 255, 255, .14);
|
||||||
|
--wx-o2: .85;
|
||||||
|
--wx-o3: .85;
|
||||||
|
--wx-warn: #ffb38a;
|
||||||
|
}
|
||||||
|
:root .wx-home {
|
||||||
|
height: 100%;
|
||||||
|
padding-bottom: 11px;
|
||||||
|
}
|
||||||
|
:root .wx .wx-h {
|
||||||
|
flex: none;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0;
|
||||||
|
height: 32px;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
:root .wx .wx-t {
|
||||||
|
flex: none;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
height: 24px;
|
||||||
|
margin: 0 3px;
|
||||||
|
padding: 0 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #fff;
|
||||||
|
color: #28304a;
|
||||||
|
box-shadow: 0 0 0 3px var(--wx-strip), 0 4px 12px rgba(40, 48, 74, .1);
|
||||||
|
font: 700 13px/1 WxJua, var(--font);
|
||||||
|
font-synthesis: none;
|
||||||
|
letter-spacing: 0;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
:root .wx .wx-dt {
|
||||||
|
display: block;
|
||||||
|
flex: 0 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
margin-left: 10px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
font: 700 13px/1.5 var(--font);
|
||||||
|
opacity: var(--wx-o1);
|
||||||
|
}
|
||||||
|
:root .wx .wx-go {
|
||||||
|
visibility: hidden;
|
||||||
|
}
|
||||||
|
:root .wx.is-ready .wx-go {
|
||||||
|
visibility: visible;
|
||||||
|
flex: none;
|
||||||
|
display: inline-flex;
|
||||||
|
gap: 3px;
|
||||||
|
height: 30px;
|
||||||
|
min-height: 0;
|
||||||
|
margin-left: auto;
|
||||||
|
padding: 0 12px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--wx-strip);
|
||||||
|
color: inherit;
|
||||||
|
font: 700 13px/1 var(--font);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
:root .wx.is-ready .wx-ar {
|
||||||
|
display: inline;
|
||||||
|
margin-left: 2px;
|
||||||
|
font-size: 15px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
:root .wx.is-ready .wx-go {
|
||||||
|
position: relative;
|
||||||
|
z-index: 5;
|
||||||
|
}
|
||||||
|
:root .wx.is-ready .wx-go::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: -7px -4px;
|
||||||
|
border-radius: 999px;
|
||||||
|
}
|
||||||
|
:root .wx.is-ready .wx-go:hover {
|
||||||
|
background: rgba(255, 255, 255, .62);
|
||||||
|
color: #28304a;
|
||||||
|
}
|
||||||
|
:root .wx.is-ready .wx-go:focus-visible {
|
||||||
|
outline: 3px solid var(--focus);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
/* 못 그렸을 때(is-failed)와 8초가 지나도 그리지 못했을 때(아래 '더한 것: 토끼 로딩 화면') 가운데 뜨는 날씨각 링크 */
|
||||||
|
:root .wx:not(.is-ready) .wx-go {
|
||||||
|
position: absolute;
|
||||||
|
left: 50%;
|
||||||
|
top: 50%;
|
||||||
|
transform: translate(-50%, -50%);
|
||||||
|
z-index: 2;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 0 18px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #fff;
|
||||||
|
color: #28304a;
|
||||||
|
font: 700 14px/1.3 var(--font);
|
||||||
|
text-decoration: none;
|
||||||
|
white-space: nowrap;
|
||||||
|
box-shadow: 0 4px 12px rgba(40, 48, 74, .12);
|
||||||
|
}
|
||||||
|
:root .wx.is-failed .wx-go {
|
||||||
|
visibility: visible;
|
||||||
|
}
|
||||||
|
:root .wx:not(.is-ready) .wx-go:hover {
|
||||||
|
color: var(--sea-deep);
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
:root .wx .wx-b {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: space-between;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
.wx-stars, .wx-fx {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
z-index: -1;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.wx-stars {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
.wx[data-t=night] .wx-stars {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
.wx-stars i {
|
||||||
|
position: absolute;
|
||||||
|
width: 3px;
|
||||||
|
height: 3px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 0 6px #fff;
|
||||||
|
}
|
||||||
|
.wx-shoot {
|
||||||
|
display: none;
|
||||||
|
position: absolute;
|
||||||
|
width: var(--len, 90px);
|
||||||
|
height: 1.5px;
|
||||||
|
border-radius: 2px;
|
||||||
|
opacity: 0;
|
||||||
|
background: linear-gradient(90deg, rgba(255, 255, 255, 0), #fff);
|
||||||
|
}
|
||||||
|
.wx-drop, .wx-flake {
|
||||||
|
position: absolute;
|
||||||
|
top: var(--top);
|
||||||
|
}
|
||||||
|
.wx-drop {
|
||||||
|
width: 2px;
|
||||||
|
height: 18px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: linear-gradient(rgba(0, 0, 0, 0), rgba(80, 130, 200, .7));
|
||||||
|
}
|
||||||
|
.wx:is([data-t=sunset], [data-t=night]) .wx-drop {
|
||||||
|
background: linear-gradient(rgba(0, 0, 0, 0), rgba(220, 230, 255, .7));
|
||||||
|
}
|
||||||
|
.wx-flake {
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 0 4px rgba(120, 150, 200, .5);
|
||||||
|
--drift: 18px;
|
||||||
|
}
|
||||||
|
.wx-sky, .wx-say, .wx-strip {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 440px;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
}
|
||||||
|
.wx-sky {
|
||||||
|
flex: none;
|
||||||
|
height: 9.125em;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
.wx-cl {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
.wx-c1 {
|
||||||
|
top: 2.25em;
|
||||||
|
left: 5%;
|
||||||
|
width: 5.25em;
|
||||||
|
height: 2em;
|
||||||
|
--d: .1s;
|
||||||
|
--f: 6s;
|
||||||
|
}
|
||||||
|
.wx-c2 {
|
||||||
|
top: 6em;
|
||||||
|
left: 63%;
|
||||||
|
width: 6em;
|
||||||
|
height: 2.25em;
|
||||||
|
--d: .25s;
|
||||||
|
--f: 6.4s;
|
||||||
|
}
|
||||||
|
.wx-c3 {
|
||||||
|
top: 1.875em;
|
||||||
|
left: 72%;
|
||||||
|
width: 4em;
|
||||||
|
height: 1.75em;
|
||||||
|
--d: .4s;
|
||||||
|
--f: 5.4s;
|
||||||
|
}
|
||||||
|
.wx-cb, .wx-cb::before, .wx-cb::after {
|
||||||
|
position: absolute;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
.wx-cb {
|
||||||
|
inset: 0;
|
||||||
|
box-shadow: inset 0 -.75em 1.125em rgba(160, 190, 230, .45), 0 1em 1.75em rgba(40, 70, 120, .13);
|
||||||
|
}
|
||||||
|
.wx-cb::before, .wx-cb::after {
|
||||||
|
content: "";
|
||||||
|
aspect-ratio: 1;
|
||||||
|
box-shadow: inset 0 -.625em 1em rgba(160, 190, 230, .35);
|
||||||
|
}
|
||||||
|
.wx-cb::before {
|
||||||
|
width: 46%;
|
||||||
|
top: -58%;
|
||||||
|
left: 16%;
|
||||||
|
}
|
||||||
|
.wx-cb::after {
|
||||||
|
width: 36%;
|
||||||
|
top: -36%;
|
||||||
|
left: 50%;
|
||||||
|
}
|
||||||
|
.wx[data-t=night] .wx-cb, .wx[data-t=night] .wx-cb::before, .wx[data-t=night] .wx-cb::after {
|
||||||
|
background: #c9cdf0;
|
||||||
|
}
|
||||||
|
.wx-ob {
|
||||||
|
position: absolute;
|
||||||
|
top: .5em;
|
||||||
|
left: 50%;
|
||||||
|
width: 8em;
|
||||||
|
height: 8em;
|
||||||
|
margin-left: -4em;
|
||||||
|
--d: 0s;
|
||||||
|
--f: 5.6s;
|
||||||
|
}
|
||||||
|
.wx-orb {
|
||||||
|
position: relative;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
border-radius: 50%;
|
||||||
|
text-align: center;
|
||||||
|
color: #5c1f08;
|
||||||
|
background: radial-gradient(circle at 34% 30%, #fff5cf, #ffc86e 30%, #ff8e4e 68%, #ee6436);
|
||||||
|
box-shadow: inset -1.125em -1.5em 2.5em rgba(170, 50, 20, .34), inset 1em 1.125em 1.75em rgba(255, 255, 255, .55), 0 1.875em 3.5em rgba(240, 106, 58, .32);
|
||||||
|
}
|
||||||
|
.wx[data-t=sunset] .wx-orb {
|
||||||
|
color: #4a2442;
|
||||||
|
background: radial-gradient(circle at 34% 30%, #fff4e6, #ffd9b8 32%, #f7a991 68%, #e07a8f);
|
||||||
|
box-shadow: inset -1.125em -1.5em 2.5em rgba(150, 50, 90, .3), inset 1em 1.125em 1.75em rgba(255, 255, 255, .55), 0 0 3.75em rgba(255, 150, 110, .5);
|
||||||
|
}
|
||||||
|
.wx[data-t=night] .wx-orb {
|
||||||
|
color: #2b2a5c;
|
||||||
|
background: radial-gradient(circle at 34% 30%, #fff, #e7e3ff 35%, #b9b0f2 72%, #8f86d9);
|
||||||
|
box-shadow: inset -1.125em -1.5em 2.5em rgba(60, 50, 140, .3), inset 1em 1.125em 1.75em rgba(255, 255, 255, .6), 0 0 3.75em rgba(190, 180, 255, .45);
|
||||||
|
}
|
||||||
|
.wx:is([data-sky=cloudy], [data-sky=rain], [data-sky=snow], [data-sky=sleet]) .wx-orb {
|
||||||
|
filter: saturate(.7) brightness(.96);
|
||||||
|
}
|
||||||
|
.wx .wx-orb.wx-moon {
|
||||||
|
background: none;
|
||||||
|
box-shadow: none;
|
||||||
|
filter: none;
|
||||||
|
}
|
||||||
|
.wx-mo {
|
||||||
|
position: absolute;
|
||||||
|
top: -25%;
|
||||||
|
left: -25%;
|
||||||
|
width: 150%;
|
||||||
|
height: 150%;
|
||||||
|
max-width: none;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.wx-sc {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.wx-sc small {
|
||||||
|
display: block;
|
||||||
|
font: 700 12px/1.5 WxJua, var(--font);
|
||||||
|
font-synthesis: none;
|
||||||
|
letter-spacing: 0;
|
||||||
|
}
|
||||||
|
.wx-sc b {
|
||||||
|
display: block;
|
||||||
|
font: 700 3.25em/.95 WxBagel, WxJua, var(--font);
|
||||||
|
font-synthesis: none;
|
||||||
|
letter-spacing: 0;
|
||||||
|
}
|
||||||
|
.wx-moon.is-lit .wx-sc {
|
||||||
|
text-shadow: 0 0 6px #fff, 0 0 12px #fff;
|
||||||
|
}
|
||||||
|
.wx-moon.is-dim .wx-sc {
|
||||||
|
color: #fff;
|
||||||
|
text-shadow: 0 1px 8px rgba(10, 14, 40, .6);
|
||||||
|
}
|
||||||
|
.wx-say {
|
||||||
|
flex: none;
|
||||||
|
height: 103px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.wx-bub {
|
||||||
|
margin: 0;
|
||||||
|
font: 700 24px/30px WxJua, var(--font);
|
||||||
|
font-synthesis: none;
|
||||||
|
letter-spacing: 0;
|
||||||
|
}
|
||||||
|
.wx-sum {
|
||||||
|
margin: 2px 0 0;
|
||||||
|
font: 700 15px/22.5px var(--font);
|
||||||
|
opacity: var(--wx-o1);
|
||||||
|
}
|
||||||
|
.wx-st {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 0 6px;
|
||||||
|
margin: 6px 0 0;
|
||||||
|
font: 700 14px/21px WxJua, var(--font);
|
||||||
|
font-synthesis: none;
|
||||||
|
letter-spacing: 0;
|
||||||
|
}
|
||||||
|
.wx-si {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.wx-si b {
|
||||||
|
font-weight: inherit;
|
||||||
|
}
|
||||||
|
.wx-sl {
|
||||||
|
opacity: var(--wx-o2);
|
||||||
|
}
|
||||||
|
.wx-dot {
|
||||||
|
opacity: .3;
|
||||||
|
}
|
||||||
|
.wx-si.is-warn {
|
||||||
|
color: var(--wx-warn);
|
||||||
|
}
|
||||||
|
.wx-si.is-warn .wx-sl {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
.wx-strip {
|
||||||
|
flex: none;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||||
|
gap: 4px;
|
||||||
|
margin-top: 10px;
|
||||||
|
padding: 3px;
|
||||||
|
list-style: none;
|
||||||
|
border-radius: 18px;
|
||||||
|
background: var(--wx-strip);
|
||||||
|
}
|
||||||
|
/* 칸은 버튼(.wx-cell, 원본은 li 자체가 칸). 버튼 기본 테두리·바탕·글자를 지워 원본 칸 모양 그대로 */
|
||||||
|
.wx-strip li {
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.wx-cell {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
min-width: 0;
|
||||||
|
margin: 0;
|
||||||
|
padding: 6px 0;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 14px;
|
||||||
|
background: none;
|
||||||
|
color: inherit;
|
||||||
|
font: inherit;
|
||||||
|
letter-spacing: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
-webkit-tap-highlight-color: transparent;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
.wx-cell:focus-visible {
|
||||||
|
outline: 3px solid var(--focus);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
.wx-cn {
|
||||||
|
max-width: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
font: 700 13px/19.5px var(--font);
|
||||||
|
opacity: var(--wx-o3);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.wx-ic {
|
||||||
|
display: block;
|
||||||
|
width: 22px;
|
||||||
|
height: 22px;
|
||||||
|
margin: 2px 0;
|
||||||
|
object-fit: contain;
|
||||||
|
}
|
||||||
|
.wx-tc {
|
||||||
|
font: 700 15px/22.5px WxJua, var(--font);
|
||||||
|
font-synthesis: none;
|
||||||
|
letter-spacing: 0;
|
||||||
|
}
|
||||||
|
.wx-cell.is-on {
|
||||||
|
background: #fff;
|
||||||
|
color: #28304a;
|
||||||
|
box-shadow: 0 4px 12px rgba(40, 48, 74, .1);
|
||||||
|
}
|
||||||
|
.wx-cell.is-on .wx-cn {
|
||||||
|
color: #c2471b;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
:root .wx-side {
|
||||||
|
height: 100%;
|
||||||
|
padding: 10px 12px 9px;
|
||||||
|
border-radius: 28px;
|
||||||
|
}
|
||||||
|
:root .wx-side .wx-h {
|
||||||
|
height: 24px;
|
||||||
|
}
|
||||||
|
:root .wx-side .wx-t {
|
||||||
|
height: 20px;
|
||||||
|
margin: 0 2px;
|
||||||
|
padding: 0 8px;
|
||||||
|
box-shadow: 0 0 0 2px var(--wx-strip);
|
||||||
|
font-size: 11.5px;
|
||||||
|
}
|
||||||
|
:root .wx-side .wx-dt {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
/* 상세형(home) 날짜가 통째로 들어가지 않으면 card.js 가 상자에 is-nodt 를 붙인다: 잘린 채('1…') 두지 않고 자리째 숨긴다 */
|
||||||
|
:root .wx.is-nodt .wx-dt {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
:root .wx-side.is-ready .wx-go {
|
||||||
|
height: 24px;
|
||||||
|
padding: 0 9px;
|
||||||
|
font-size: 11.5px;
|
||||||
|
}
|
||||||
|
:root .wx-side.is-ready .wx-ar {
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.wx-side .wx-sky {
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
.wx-side .wx-sc small {
|
||||||
|
font-size: 9.5px;
|
||||||
|
line-height: 1.35;
|
||||||
|
}
|
||||||
|
.wx-side .wx-say {
|
||||||
|
height: 26px;
|
||||||
|
}
|
||||||
|
.wx-side .wx-bub {
|
||||||
|
overflow: hidden;
|
||||||
|
font-size: 17px;
|
||||||
|
line-height: 26px;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.wx-side .wx-strip {
|
||||||
|
gap: 3px;
|
||||||
|
margin-top: 6px;
|
||||||
|
border-radius: 14px;
|
||||||
|
}
|
||||||
|
.wx-side .wx-cell {
|
||||||
|
padding: 4px 0;
|
||||||
|
border-radius: 11px;
|
||||||
|
}
|
||||||
|
.wx-side .wx-cn {
|
||||||
|
font-size: 11px;
|
||||||
|
line-height: 16px;
|
||||||
|
}
|
||||||
|
.wx-side .wx-ic {
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
margin: 1px 0;
|
||||||
|
}
|
||||||
|
.wx-side .wx-tc {
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 19px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- 배경: 밝은 바탕용(light)·어두운 바탕용(dark)
|
||||||
|
같은 갈래의 sky 규칙(.wx[data-t=…], .wx:is(…):is(…))보다 클래스가 많아 순서와 상관없이 이긴다 */
|
||||||
|
:root .wx.wx-bg-light {
|
||||||
|
--wx-bg: linear-gradient(#e3f1ff, #f0f8ff 55%, #fbfdff);
|
||||||
|
--wx-fg: #28304a;
|
||||||
|
--wx-strip: rgba(255, 255, 255, .7);
|
||||||
|
--wx-o1: .85;
|
||||||
|
--wx-o2: .75;
|
||||||
|
--wx-o3: .75;
|
||||||
|
--wx-warn: #a8401a;
|
||||||
|
box-shadow: inset 0 0 0 1px rgba(40, 48, 74, .08);
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-light[data-t=morning] {
|
||||||
|
--wx-bg: linear-gradient(#ffeedd, #fff6ee 45%, #f3f9ff);
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-light:is([data-t=morning], [data-t=day]):is([data-sky=cloudy], [data-sky=rain], [data-sky=snow], [data-sky=sleet]) {
|
||||||
|
--wx-bg: linear-gradient(#e6ebf1, #f1f4f8 55%, #fafbfc);
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-light[data-t=sunset] {
|
||||||
|
--wx-bg: linear-gradient(#ece8ff, #f4ecfb 45%, #fdeef3);
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-light[data-t=night] {
|
||||||
|
--wx-bg: linear-gradient(#e4e8fa, #ecedfa 60%, #f3f0fb);
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-light .wx-stars {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-light .wx-cb, :root .wx.wx-bg-light .wx-cb::before, :root .wx.wx-bg-light .wx-cb::after {
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-light .wx-drop {
|
||||||
|
background: linear-gradient(rgba(0, 0, 0, 0), rgba(80, 130, 200, .7));
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-light .wx-flake {
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 0 4px rgba(120, 150, 200, .7);
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-dark {
|
||||||
|
--wx-bg: linear-gradient(#1c3252, #20304c 55%, #1c2540);
|
||||||
|
--wx-fg: #fff;
|
||||||
|
--wx-strip: rgba(255, 255, 255, .12);
|
||||||
|
--wx-o1: .85;
|
||||||
|
--wx-o2: .85;
|
||||||
|
--wx-o3: .85;
|
||||||
|
--wx-warn: #ffb38a;
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-dark[data-t=morning] {
|
||||||
|
--wx-bg: linear-gradient(#3b2e3c, #34303f 45%, #252c42);
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-dark:is([data-t=morning], [data-t=day]):is([data-sky=cloudy], [data-sky=rain], [data-sky=snow], [data-sky=sleet]) {
|
||||||
|
--wx-bg: linear-gradient(#2a313d, #262c38 55%, #20242e);
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-dark[data-t=sunset] {
|
||||||
|
--wx-bg: linear-gradient(#2b2660, #39295d 45%, #482747);
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-dark[data-t=night] {
|
||||||
|
--wx-bg: linear-gradient(#10152f, #1a2048 60%, #262852);
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-dark .wx-cb, :root .wx.wx-bg-dark .wx-cb::before, :root .wx.wx-bg-dark .wx-cb::after {
|
||||||
|
background: #aab3d6;
|
||||||
|
}
|
||||||
|
:root .wx.wx-bg-dark .wx-drop {
|
||||||
|
background: linear-gradient(rgba(0, 0, 0, 0), rgba(220, 230, 255, .7));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 더한 것: 스크립트가 돌지 않을 때 날씨각 링크 (render_card 의 <noscript>, 모양은 is-failed 의 링크와 같다) */
|
||||||
|
.wx-ns {
|
||||||
|
position: fixed;
|
||||||
|
left: 50%;
|
||||||
|
top: 50%;
|
||||||
|
transform: translate(-50%, -50%);
|
||||||
|
z-index: 6;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 0 18px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #fff;
|
||||||
|
color: #28304a;
|
||||||
|
font: 700 14px/1.3 var(--font);
|
||||||
|
text-decoration: none;
|
||||||
|
white-space: nowrap;
|
||||||
|
box-shadow: 0 4px 12px rgba(40, 48, 74, .12);
|
||||||
|
}
|
||||||
|
.wx-ns:hover {
|
||||||
|
color: var(--sea-deep);
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 더한 것: 토끼 로딩 화면 (render_card 의 .wx-load. 날씨각 앱 첫 화면 #boot 와 같은 토끼·문구, 움직임은 앱의 b-hop).
|
||||||
|
카드 가운데에 두고, 그리면(is-ready)·못 그리면(is-failed) 사라진다. 글자색은 배경을 따른다(dark 는 흰 글자).
|
||||||
|
글꼴은 카드 본문과 같은 시스템 글꼴 굵은 글씨다 (이 화면은 Jua 를 싣지 않고, 둥근 글꼴은 card.js 가 카드 글자에만 받는다) */
|
||||||
|
.wx-load {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 12px;
|
||||||
|
color: var(--wx-fg);
|
||||||
|
font: 700 19px/1.3 var(--font);
|
||||||
|
letter-spacing: 0;
|
||||||
|
text-align: center;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.wx-load img {
|
||||||
|
display: block;
|
||||||
|
width: 88px;
|
||||||
|
height: 88px;
|
||||||
|
transform-origin: 50% 100%;
|
||||||
|
}
|
||||||
|
.wx-side .wx-load {
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
.wx-side .wx-load img {
|
||||||
|
width: 64px;
|
||||||
|
height: 64px;
|
||||||
|
}
|
||||||
|
.wx.is-ready .wx-load, .wx.is-failed .wx-load {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
/* card.js 가 오지 않으면(막힘·404) 8초 뒤 스크립트 없이 토끼를 감추고 날씨각 링크를 보인다. 움직임이 아니라 바뀌기만 하므로
|
||||||
|
움직임 줄이기 설정과 상관없이 둔다. is-ready·is-failed 가 붙으면 이 규칙이 안 맞아 그린 카드(또는 실패 링크)가 이긴다 */
|
||||||
|
:root .wx:not(.is-ready):not(.is-failed) .wx-load {
|
||||||
|
animation: wx-gone 0s linear 8s forwards;
|
||||||
|
}
|
||||||
|
:root .wx:not(.is-ready):not(.is-failed) .wx-go {
|
||||||
|
animation: wx-late 0s linear 8s forwards;
|
||||||
|
}
|
||||||
|
@keyframes wx-gone {
|
||||||
|
to { visibility: hidden; }
|
||||||
|
}
|
||||||
|
@keyframes wx-late {
|
||||||
|
to { visibility: visible; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 더한 것: 상세형(home)의 글 줄 수 (한마디 한 줄 30px + 요약 한 줄 2+22.5px + 상태 두 줄 6+42px = 102.5px, .wx-say 103px 안) */
|
||||||
|
.wx-home .wx-bub, .wx-home .wx-sum {
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
-webkit-line-clamp: 1;
|
||||||
|
line-clamp: 1;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.wx-home .wx-st {
|
||||||
|
max-height: 42px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
/* 더한 것: 다른 시간대 칸을 고르면 지금 값인 요약·상태 줄을 감춘다. 자리는 남겨 카드가 움직이지 않게 (card.js 가 is-hidden 을 붙인다) */
|
||||||
|
.wx-sum.is-hidden, .wx-st.is-hidden {
|
||||||
|
visibility: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 움직임 */
|
||||||
|
@media (prefers-reduced-motion: no-preference) {
|
||||||
|
.wx.is-ready .wx-b {
|
||||||
|
animation: wx-in .45s var(--ease-out) both;
|
||||||
|
}
|
||||||
|
.wx-home :is(.wx-cl, .wx-ob) {
|
||||||
|
animation: wx-drop 1.05s cubic-bezier(.22, .9, .3, 1) var(--d, 0s) backwards;
|
||||||
|
}
|
||||||
|
/* 칸을 눌러 다시 그린 카드(is-again, card.js)는 해·구름이 다시 떨어지지 않고 제자리에 있다 */
|
||||||
|
.wx-home.is-again :is(.wx-cl, .wx-ob) {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
.wx :is(.wx-cb, .wx-orb) {
|
||||||
|
animation: wx-float var(--f, 4.8s) ease-in-out calc(var(--d, 0s) + 1.05s) infinite;
|
||||||
|
}
|
||||||
|
.wx[data-t=night] .wx-shoot {
|
||||||
|
display: block;
|
||||||
|
animation: wx-shoot var(--dur, 8s) ease-in var(--dl, 0s) infinite;
|
||||||
|
}
|
||||||
|
.wx[data-t=night] .wx-tw {
|
||||||
|
animation: wx-twinkle 5s ease-in-out var(--dl, 0s) infinite;
|
||||||
|
}
|
||||||
|
.wx-drop, .wx-flake {
|
||||||
|
top: -24px;
|
||||||
|
animation: wx-fall var(--dur) linear var(--dl) infinite;
|
||||||
|
}
|
||||||
|
.wx.is-off * {
|
||||||
|
animation-play-state: paused !important;
|
||||||
|
}
|
||||||
|
.wx-load img {
|
||||||
|
animation: wx-hop .9s cubic-bezier(.3, 0, .4, 1) infinite;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@keyframes wx-hop {
|
||||||
|
0%, to { transform: translateY(0) scale(1.06, .94); }
|
||||||
|
45% { transform: translateY(-22px) scale(.97, 1.03); }
|
||||||
|
}
|
||||||
|
@keyframes wx-drop {
|
||||||
|
0% { opacity: 0; transform: translateY(-60vh) rotate(-10deg); }
|
||||||
|
55% { opacity: 1; }
|
||||||
|
72% { transform: translateY(0) rotate(2deg) scale(1.04, .96); }
|
||||||
|
86% { transform: translateY(-10px); }
|
||||||
|
to { opacity: 1; transform: none; }
|
||||||
|
}
|
||||||
|
@keyframes wx-fall {
|
||||||
|
to { transform: translate(var(--drift, -8px), 440px); }
|
||||||
|
}
|
||||||
|
@keyframes wx-float {
|
||||||
|
0%, to { transform: translateY(0); }
|
||||||
|
50% { transform: translateY(-.5625em) rotate(1.2deg); }
|
||||||
|
}
|
||||||
|
@keyframes wx-in {
|
||||||
|
from { opacity: 0; }
|
||||||
|
}
|
||||||
|
@keyframes wx-shoot {
|
||||||
|
0%, 86% { opacity: 0; transform: rotate(-24deg) translate(0); }
|
||||||
|
89% { opacity: 1; }
|
||||||
|
to { opacity: 0; transform: rotate(-24deg) translate(-240px); }
|
||||||
|
}
|
||||||
|
@keyframes wx-twinkle {
|
||||||
|
0%, to { opacity: .25; }
|
||||||
|
50% { opacity: 1; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,419 @@
|
|||||||
|
/* 날씨각 카드 — 다른 사이트가 iframe 으로 붙이는 /embed/card 의 카드를 그린다 (모양은 card.css).
|
||||||
|
군산각(https://gunsan.webforai.kr/assets/weather.js, 2026-11-25 받은 것)의 카드 스크립트를 옮겨 왔다. 군산각의 이
|
||||||
|
카드는 날씨각 첫 화면 카드를 그대로 그린 위젯이라 점수·달 모양·하늘·4칸 줄이 날씨각과 같다. 원본과 다른 곳:
|
||||||
|
1. 날씨 값을 fetch 두 번(data-wx, data-wx-day)으로 받지 않고, 백엔드가 이 페이지에 넣어 둔 #wx-data JSON
|
||||||
|
({name, link, hero, picks, today})을 읽어 usable() 에 {hero}, today 로 넘긴다. 8초 제한·ask()·화면에 가까워지면 묻기는
|
||||||
|
뺐고, 바로 그린다. fetch 가 없는 브라우저는 카드 전체가 아니라 글꼴만 포기한다.
|
||||||
|
2. 문구(지금 날씨 점수, 아침·낮·저녁·밤·지금, 자세히 보기, 하늘 이름)는 data-wx-w 대신 이 파일의 WORDS 에 둔다.
|
||||||
|
외국어 갈래(wx-intl: 숫자만 보이는 줄, 접힌 줄)는 빼고 한국어 갈래만 남겼다. 날짜는 한국어 긴 꼴로만 쓴다.
|
||||||
|
3. 아이콘 경로 /assets/wx/ → /icons/ (날씨각 아이콘). 일출·일몰([data-sd-days]) 부분을 뺐다.
|
||||||
|
4. 원본의 빈 catch 두 곳(FontFace 만들기, document.fonts.add)을 뺐다. 글꼴 하나가 잘못되면 그 글꼴만 포기하고
|
||||||
|
(faces 의 catch), 글꼴을 붙이다 오류가 나도 카드는 그린다(finally).
|
||||||
|
5. 상세형(home) 날짜(.wx-dt)는 통째로 들어갈 때만 보인다. 원본은 좁으면 '1…' 처럼 말줄임으로 잘렸다. 카드를 그린 직후와
|
||||||
|
iframe 폭이 바뀔 때(resize) 글자 폭과 칸 폭을 비교해, 안 들어가면 상자에 is-nodt 를 붙여 숨긴다(card.css).
|
||||||
|
6. 그리기 전에는 원본의 빈 자리 표시 대신 서버 HTML 에 처음부터 든 토끼 로딩 화면(.wx-load)이 보이고, is-ready·
|
||||||
|
is-failed 가 붙으면 card.css 가 감춘다. 못 그렸을 때 링크 글자는 서버가 넣은 '날씨각에서 날씨 보기 ›'(원본은 '○○ 날씨
|
||||||
|
보기'와 새 창 그림)이고, 실패할 때 이 파일은 그 글자를 바꾸지 않는다. 이 파일이 아예 안 오면 card.css 가 8초 뒤 같은
|
||||||
|
링크를 보인다.
|
||||||
|
7. 아래 4칸은 버튼이다(원본은 보기만 하는 칸). 날씨각 앱 첫 화면처럼 칸을 누르면 그 시간대로 카드를 다시 그린다: 하늘
|
||||||
|
(data-t·data-sky, 구름·비·눈, 저녁·밤이면 오늘 밤 달)은 그 칸 그림과 같은 예보 칸, 점수는 hero.weather_slots, 한마디는
|
||||||
|
서버가 앱과 같은 규칙으로 만든 picks. 상세형 요약·상태 줄은 지금 값이라 자리만 두고 감춘다. '지금' 칸을 누르면 처음
|
||||||
|
모습이고, 점수나 picks 가 없는 칸도 지금 모습이다. 다시 그릴 때는 본문을 비우고 처음과 같이 만든다(글꼴은 처음 한 번만
|
||||||
|
받으므로 picks 의 한마디도 처음 글자 목록에 넣는다).
|
||||||
|
그대로 둔 것: 오늘(한국 날짜) 값이 아니면 그리지 않음, 날씨각 둥근 글꼴(Jua, Bagel Fat One)을 Google Fonts 에서
|
||||||
|
카드 글자만 받기(2.5초 넘으면 기본 글꼴), 화면 밖이면 움직임 멈춤(is-off), 그리다 실패하면 is-failed.
|
||||||
|
밖으로 나가는 요청은 이 글꼴뿐이다(쿠키·localStorage·통계 없음). 글은 textContent 로만 넣는다.
|
||||||
|
움직임 줄이기 설정이면 떨어지기·떠 있기·별똥별·반짝임·비 내리기·토끼 뛰기가 없다(card.css). */
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
var doc = document, win = window;
|
||||||
|
var SVG = "http://www.w3.org/2000/svg";
|
||||||
|
function $all(sel, el) { return Array.prototype.slice.call((el || doc).querySelectorAll(sel)); }
|
||||||
|
// the visitor's date and time in Korea
|
||||||
|
function seoul() {
|
||||||
|
var o = {};
|
||||||
|
try {
|
||||||
|
new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Seoul", year: "numeric", month: "2-digit", day: "2-digit",
|
||||||
|
hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(new Date()).forEach(function (p) { o[p.type] = p.value; });
|
||||||
|
// oxlint-disable-next-line no-unused-vars -- 바인딩 없는 catch 는 옛 브라우저에서 파일 전체가 문법 오류가 된다
|
||||||
|
} catch (e) { return null; }
|
||||||
|
if (!(o.year && o.month && o.day)) return null;
|
||||||
|
return { iso: o.year + "-" + o.month + "-" + o.day, mo: +o.month, h: (+o.hour || 0) % 24, mi: +o.minute || 0 };
|
||||||
|
}
|
||||||
|
var T = seoul(), day = T ? T.iso : "";
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ weather
|
||||||
|
var boxes = $all(".wx");
|
||||||
|
if (!boxes.length) return;
|
||||||
|
|
||||||
|
// the card's words (군산각's data-wx-w on its Korean pages)
|
||||||
|
var WORDS = {
|
||||||
|
more: "자세히 보기",
|
||||||
|
score: "날씨 점수", // after the cell's name: '지금 날씨 점수', '아침 날씨 점수'
|
||||||
|
slots: { morning: "아침", day: "낮", sunset: "저녁", night: "밤", now: "지금" },
|
||||||
|
sky: { sun: "맑음", sun_cloud: "구름 조금", cloud: "흐림", rain: "비", snow: "눈", moon: "맑음" }
|
||||||
|
};
|
||||||
|
// 날씨각's own tables (its app: the hero card)
|
||||||
|
var COLS = ["morning", "day", "sunset", "night"];
|
||||||
|
var HOUR = { morning: 7, day: 13, sunset: 18, night: 22 };
|
||||||
|
var ICON = { clear: "sun", partly: "sun_cloud", cloudy: "cloud", rain: "rain", snow: "snow", sleet: "snow" };
|
||||||
|
var CLOUDS = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3 };
|
||||||
|
var WANING = ["기우는 달", "하현달", "그믐달"];
|
||||||
|
var SUNSET = [17.7, 18.2, 18.6, 19.1, 19.5, 19.9, 19.9, 19.5, 18.9, 18.2, 17.6, 17.3]; // its sky by the clock
|
||||||
|
var ICONS = "/icons/";
|
||||||
|
function num(v) { return typeof v === "number" && isFinite(v); }
|
||||||
|
function deg(v) { return num(v) ? Math.round(v) + "°" : "–"; }
|
||||||
|
function el(tag, cls, text) {
|
||||||
|
var e = doc.createElement(tag);
|
||||||
|
if (cls) e.className = cls;
|
||||||
|
if (text != null) e.textContent = text;
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
function clockSky() {
|
||||||
|
if (!T) return "day";
|
||||||
|
var h = T.h + T.mi / 60, s = SUNSET[T.mo - 1] || 18.5;
|
||||||
|
return h >= 5 && h < 11 ? "morning" : h >= 11 && h < s + 1 ? (h < s - 2 ? "day" : "sunset") : "night";
|
||||||
|
}
|
||||||
|
// a slot's sky as 날씨각 reads it (rain_type: 2 rain · 3 sleet · 4 snow · 5 shower; sky: 2 partly · 3 cloudy)
|
||||||
|
function kind(s) {
|
||||||
|
if (!s) return "clear";
|
||||||
|
var r = s.rain_type, k = s.sky;
|
||||||
|
if (r === 2 || r === 5) return "rain";
|
||||||
|
if (r === 4) return "snow";
|
||||||
|
if (r === 3) return "sleet";
|
||||||
|
if (k === 3) return "cloudy";
|
||||||
|
if (k === 2) return "partly";
|
||||||
|
if (r == null && k == null) return { cloud: "cloudy", rain: "rain", snow: "snow" }[s.icon] || "clear";
|
||||||
|
return "clear";
|
||||||
|
}
|
||||||
|
// the slot for a cell: the last at or before its hour (one with a figure after it when that one has none)
|
||||||
|
function pick(slots, hour) {
|
||||||
|
var n = null;
|
||||||
|
slots.forEach(function (s) { if (s.hh <= hour) n = s; });
|
||||||
|
n = n || slots[0];
|
||||||
|
if (!num(n.temp_c)) n = slots.filter(function (s) { return s.hh > hour && num(s.temp_c); })[0] || n;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
function nearest(slots) {
|
||||||
|
var t = Date.now(), have = slots.filter(function (s) { return num(s.temp_c); });
|
||||||
|
return have.reduce(function (a, s) { return Math.abs(s.ms - t) < Math.abs(a.ms - t) ? s : a; }, have[0]);
|
||||||
|
}
|
||||||
|
function usable(feed, today) {
|
||||||
|
var h = feed && feed.hero;
|
||||||
|
if (!h || typeof h !== "object" || !num(h.weather_score)) return null;
|
||||||
|
if (!today || typeof today !== "object") return null;
|
||||||
|
if (day && (String(h.now_at || "").slice(0, 10) !== day || today.day !== day)) return null;
|
||||||
|
var slots = (today.slots || []).filter(function (s) { return s && !isNaN(Date.parse(s.at)); }).map(function (s) {
|
||||||
|
var ms = Date.parse(s.at), k = new Date(ms + 324e5); // its hour in Korea
|
||||||
|
return { ms: ms, hh: k.getUTCHours() + k.getUTCMinutes() / 60, temp_c: s.temp_c, sky: s.sky, rain_type: s.rain_type, icon: s.icon };
|
||||||
|
});
|
||||||
|
if (!slots.some(function (s) { return num(s.temp_c); })) return null;
|
||||||
|
return { hero: h, slots: slots };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 날씨각's moon (its app's own drawing: the disc, its seas and craters, the shade of its phase)
|
||||||
|
var SEAS = [[-.32, -.36, .3, .26], [.12, -.36, .17, .15], [.3, -.06, .2, .17], [-.56, .06, .26, .42], [.66, -.26, .1, .12],
|
||||||
|
[.52, .22, .13, .15], [-.14, .44, .18, .13], [-.46, .5, .1, .09]];
|
||||||
|
var CRATERS = [[.1, .72, .07], [.42, .52, .05], [-.66, -.5, .05], [.62, .52, .04], [-.2, .08, .04]];
|
||||||
|
var TONES = { night: { body: ["#fffcf2", "#f6ebcb", "#e0cc98"], shade: "#1a2050" },
|
||||||
|
dusk: { body: ["#fff8ee", "#ffe2cc", "#f2b9a2"], shade: "#4a2a63" } };
|
||||||
|
var uid = 0;
|
||||||
|
function node(tag, at, kids) {
|
||||||
|
var e = doc.createElementNS(SVG, tag);
|
||||||
|
Object.keys(at || {}).forEach(function (k) { e.setAttribute(k, at[k]); });
|
||||||
|
(kids || []).forEach(function (c) { if (c) e.appendChild(c); });
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
function shadePath(pct, r) {
|
||||||
|
var f = pct / 100;
|
||||||
|
return "M0," + (-r) + " A" + r + "," + r + " 0 0 0 0," + r + " A" + (r * Math.abs(1 - 2 * f)) + "," + r + " 0 0 " + (f < .5 ? 0 : 1) + " 0," + (-r);
|
||||||
|
}
|
||||||
|
function moon(pct, waxing, tone) {
|
||||||
|
var id = "wxm" + (++uid), a = TONES[tone], o = pct / 100, full = pct >= 99, nw = pct <= 1;
|
||||||
|
var stop = function (off, c, op) { return node("stop", op == null ? { offset: off, "stop-color": c } : { offset: off, "stop-color": c, "stop-opacity": op }); };
|
||||||
|
var defs = node("defs", {}, [
|
||||||
|
node("radialGradient", { id: id + "g" }, [stop("0.6", "#fff4cf", "0.55"), stop("0.8", "#ffe9a8", "0.16"), stop("1", "#ffe9a8", "0")]),
|
||||||
|
node("radialGradient", { id: id + "b", cx: "0.4", cy: "0.36", r: "0.72" }, [stop("0", a.body[0]), stop("0.6", a.body[1]), stop("1", a.body[2])]),
|
||||||
|
node("radialGradient", { id: id + "l" }, [stop("0.72", "#8a6f3c", "0"), stop("1", "#8a6f3c", "0.28")]),
|
||||||
|
node("clipPath", { id: id + "c" }, [node("circle", { r: "1" })]),
|
||||||
|
node("filter", { id: id + "f", x: "-0.2", y: "-0.2", width: "1.4", height: "1.4" }, [node("feGaussianBlur", { stdDeviation: "0.035" })])
|
||||||
|
]);
|
||||||
|
var seas = node("g", { filter: "url(#" + id + "f)", fill: "#c4b287", opacity: "0.55" },
|
||||||
|
SEAS.map(function (e) { return node("ellipse", { cx: e[0], cy: e[1], rx: e[2], ry: e[3] }); }));
|
||||||
|
var disc = node("g", { "clip-path": "url(#" + id + "c)" }, [node("circle", { r: "1", fill: "url(#" + id + "b)" }), seas]
|
||||||
|
.concat(CRATERS.map(function (e) { return node("circle", { cx: e[0], cy: e[1], r: e[2], fill: "#efe2bd", stroke: "#cdbb8c", "stroke-width": "0.018", opacity: "0.8" }); }))
|
||||||
|
.concat([node("circle", { r: "1", fill: "url(#" + id + "l)" }),
|
||||||
|
full ? null : node("path", waxing ? { d: shadePath(pct, 1.04), fill: a.shade, opacity: "0.94", filter: "url(#" + id + "f)" }
|
||||||
|
: { d: shadePath(pct, 1.04), fill: a.shade, opacity: "0.94", filter: "url(#" + id + "f)", transform: "scale(-1,1)" })]));
|
||||||
|
return node("svg", { viewBox: "-1.5 -1.5 3 3", class: "wx-mo", "aria-hidden": "true", focusable: "false" }, [defs,
|
||||||
|
nw ? null : node("circle", { r: "1.5", fill: "url(#" + id + "g)", opacity: String(full ? 1 : .12 + .8 * o) }), disc,
|
||||||
|
nw ? node("circle", { r: "1", fill: "none", stroke: "#fff", "stroke-opacity": "0.18", "stroke-width": "0.025" }) : null]);
|
||||||
|
}
|
||||||
|
// the night sky: 날씨각's 26 stars (kept between the head and the words: a star by a letter reads as part of it,
|
||||||
|
// one behind the see-through link as a dot after it) and 3 shooting stars; rain and snow
|
||||||
|
function sky(kindNow) {
|
||||||
|
var s = el("div", "wx-stars");
|
||||||
|
s.setAttribute("aria-hidden", "true");
|
||||||
|
for (var i = 0; i < 26; i++) {
|
||||||
|
var st = el("i", i % 3 ? "" : "wx-tw");
|
||||||
|
st.style.left = (i * 37 % 100) + "%";
|
||||||
|
st.style.top = (12 + (i * 53 % 60) * .55).toFixed(1) + "%";
|
||||||
|
st.style.opacity = String(.4 + i * 7 % 6 / 10);
|
||||||
|
st.style.setProperty("--dl", (i * 0.7 % 5).toFixed(1) + "s");
|
||||||
|
s.appendChild(st);
|
||||||
|
}
|
||||||
|
[["6%", "80%", "90px", "7s", "1.5s"], ["20%", "52%", "70px", "9s", "4s"], ["34%", "94%", "80px", "11s", "6.5s"]].forEach(function (x) {
|
||||||
|
var sh = el("span", "wx-shoot");
|
||||||
|
sh.style.top = x[0];
|
||||||
|
sh.style.left = x[1];
|
||||||
|
sh.style.setProperty("--len", x[2]);
|
||||||
|
sh.style.setProperty("--dur", x[3]);
|
||||||
|
sh.style.setProperty("--dl", x[4]);
|
||||||
|
s.appendChild(sh);
|
||||||
|
});
|
||||||
|
var out = [s];
|
||||||
|
var rain = kindNow === "rain" || kindNow === "sleet", snow = kindNow === "snow" || kindNow === "sleet";
|
||||||
|
if (rain || snow) {
|
||||||
|
var f = el("div", "wx-fx");
|
||||||
|
f.setAttribute("aria-hidden", "true");
|
||||||
|
var add = function (n, cls, step, a, b, c, d) {
|
||||||
|
for (var i = 0; i < n; i++) {
|
||||||
|
var x = el("i", cls);
|
||||||
|
x.style.left = (i * step % 100) + "%";
|
||||||
|
x.style.setProperty("--top", (i * a % 90) + "%");
|
||||||
|
x.style.setProperty("--dl", (i * b % 100 / c) + "s");
|
||||||
|
x.style.setProperty("--dur", d(i) + "s");
|
||||||
|
f.appendChild(x);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (rain) add(22, "wx-drop", 41, 29, 37, 100, function (i) { return .55 + i * 13 % 5 / 10; });
|
||||||
|
if (snow) add(16, "wx-flake", 47, 31, 53, 25, function (i) { return 3.2 + i * 7 % 5 / 2; });
|
||||||
|
out.push(f);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// the date as 날씨각 writes it ('10월 31일 토요일')
|
||||||
|
function dateWords() {
|
||||||
|
try {
|
||||||
|
return new Intl.DateTimeFormat("ko", { timeZone: "Asia/Seoul", month: "long", day: "numeric", weekday: "long" }).format(new Date());
|
||||||
|
// oxlint-disable-next-line no-unused-vars -- 옛 브라우저용 catch 바인딩 (seoul() 참고)
|
||||||
|
} catch (e) { return ""; }
|
||||||
|
}
|
||||||
|
// the date shows only whole: hidden (is-nodt, card.css) when its letters are wider than its room, never cut ('1…')
|
||||||
|
function fitDate(box) {
|
||||||
|
var dt = box.querySelector("[data-wx-dt]");
|
||||||
|
if (!dt || !dt.textContent) return;
|
||||||
|
box.classList.remove("is-nodt");
|
||||||
|
var r = doc.createRange();
|
||||||
|
r.selectNodeContents(dt);
|
||||||
|
box.classList.toggle("is-nodt", r.getBoundingClientRect().width > dt.getBoundingClientRect().width + .01);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ 날씨각's round fonts, only the letters the card shows
|
||||||
|
var FONTS = "https://fonts.googleapis.com/css2?family=";
|
||||||
|
function faces(family, as, text) {
|
||||||
|
// the stylesheet's faces (one or more, each with its unicode-range), loaded before they join the page; none when
|
||||||
|
// the stylesheet or a face does not come
|
||||||
|
var url = FONTS + family + "&text=" + encodeURIComponent(text) + "&display=swap";
|
||||||
|
return win.fetch(url, { mode: "cors", credentials: "omit" }).then(function (r) { return r.ok ? r.text() : ""; }).then(function (css) {
|
||||||
|
var out = [];
|
||||||
|
(css.match(/@font-face\s*{[^}]*}/g) || []).forEach(function (blk) {
|
||||||
|
var src = /src:\s*url\((https:\/\/fonts\.gstatic\.com\/[^)\s]+)\)\s*format\(['"]?woff2['"]?\)/.exec(blk);
|
||||||
|
var ur = /unicode-range:\s*([^;]+);/.exec(blk);
|
||||||
|
if (!src) return;
|
||||||
|
out.push(new win.FontFace(as, "url(" + src[1] + ") format('woff2')", ur ? { unicodeRange: ur[1].trim() } : {}));
|
||||||
|
});
|
||||||
|
return Promise.all(out.map(function (f) { return f.load(); }));
|
||||||
|
}).catch(function () { return []; });
|
||||||
|
}
|
||||||
|
function fonts(round, digits, done) {
|
||||||
|
var over = false;
|
||||||
|
var end = function (list) {
|
||||||
|
if (over) return;
|
||||||
|
over = true;
|
||||||
|
clearTimeout(t);
|
||||||
|
// they join the page now, before the card is drawn in them — never afterwards (nothing changes its letters)
|
||||||
|
try {
|
||||||
|
(list || []).forEach(function (fs) { (fs || []).forEach(function (f) { doc.fonts.add(f); }); });
|
||||||
|
} finally {
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var t = setTimeout(function () { end(null); }, 2500);
|
||||||
|
if (!win.FontFace || !doc.fonts || !win.Promise || !win.fetch) return end(null);
|
||||||
|
Promise.all([faces("Jua", "WxJua", round), faces("Bagel+Fat+One", "WxBagel", digits)]).then(end);
|
||||||
|
}
|
||||||
|
function letters(s) {
|
||||||
|
var seen = {}, out = "";
|
||||||
|
s.replace(/\s+/g, "").split("").forEach(function (c) { if (!seen[c]) { seen[c] = 1; out += c; } });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ the card
|
||||||
|
// the cell shown other than now: one with its own score and words (picks, from the server); null shows now
|
||||||
|
function chosen(D, mode, k) {
|
||||||
|
var p = D.picks[k], ws = D.hero.weather_slots;
|
||||||
|
return k && k !== mode && p && typeof p.bubble === "string" && p.bubble.trim() && ws && num(ws[k]) ? k : null;
|
||||||
|
}
|
||||||
|
// k: the cell pressed (null at first: now)
|
||||||
|
function draw(box, D, k) {
|
||||||
|
var w = WORDS, side = box.classList.contains("wx-side"), h = D.hero, slots = D.slots;
|
||||||
|
var S = w.slots, SKY = w.sky;
|
||||||
|
var mode = HOUR[h.sky_mode] ? h.sky_mode : clockSky();
|
||||||
|
var now = nearest(slots), at = chosen(D, mode, k), cell = at || mode, pk = at ? D.picks[at] : null;
|
||||||
|
box.setAttribute("data-wx-at", at || "");
|
||||||
|
// the sky of the cell shown: the same forecast as its picture in the cells below
|
||||||
|
var skyNow = kind(at ? pick(slots, HOUR[at]) : now);
|
||||||
|
var body = box.querySelector("[data-wx-b]");
|
||||||
|
if (!body) return;
|
||||||
|
body.textContent = ""; // drawn again (a cell pressed): its stars, rain and snow made anew, never twice
|
||||||
|
box.setAttribute("data-t", cell);
|
||||||
|
box.setAttribute("data-sky", skyNow);
|
||||||
|
var dt = box.querySelector("[data-wx-dt]");
|
||||||
|
if (dt && !side) dt.textContent = dateWords();
|
||||||
|
sky(skyNow).forEach(function (x) { body.appendChild(x); });
|
||||||
|
// the sun, or the moon, with the score; 날씨각's clouds for the sky now
|
||||||
|
var stage = el("div", "wx-sky");
|
||||||
|
for (var i = 0; i < CLOUDS[skyNow]; i++) {
|
||||||
|
var c = el("span", "wx-cl wx-c" + (i + 1));
|
||||||
|
c.setAttribute("aria-hidden", "true");
|
||||||
|
c.appendChild(el("span", "wx-cb"));
|
||||||
|
stage.appendChild(c);
|
||||||
|
}
|
||||||
|
// tonight's moon from 저녁 on (the cell shown, now or pressed)
|
||||||
|
var mn = (cell === "sunset" || cell === "night") && h.moon_name && num(h.moon_pct)
|
||||||
|
? { pct: Math.max(0, Math.min(100, h.moon_pct)), waning: WANING.indexOf(h.moon_name) > -1 } : null;
|
||||||
|
var orb = el("div", "wx-orb" + (mn ? " wx-moon " + (mn.pct >= 50 ? "is-lit" : "is-dim") : ""));
|
||||||
|
if (mn) orb.appendChild(moon(mn.pct, !mn.waning, cell === "sunset" ? "dusk" : "night"));
|
||||||
|
var ob = el("div", "wx-ob");
|
||||||
|
ob.appendChild(orb);
|
||||||
|
stage.appendChild(ob);
|
||||||
|
body.appendChild(stage);
|
||||||
|
var score = el("p", "wx-sc");
|
||||||
|
score.appendChild(el("small", "", (at ? S[at] : S.now) + " " + w.score));
|
||||||
|
score.appendChild(el("b", "", String(Math.round(at ? h.weather_slots[at] : h.weather_score))));
|
||||||
|
orb.appendChild(score);
|
||||||
|
// the words: 날씨각's own (of the cell pressed: its picks). The summary and the status line tell of now: kept in their
|
||||||
|
// place but unseen when another cell is shown (the card does not move)
|
||||||
|
var say = el("div", "wx-say");
|
||||||
|
var bub = at ? pk.bubble : h.bubble;
|
||||||
|
if (typeof bub === "string" && bub.trim()) say.appendChild(el("p", "wx-bub", bub.trim()));
|
||||||
|
var sum = h.top1 && typeof h.top1.summary === "string" ? h.top1.summary.trim() : "";
|
||||||
|
if (!side && sum) say.appendChild(el("p", "wx-sum" + (at ? " is-hidden" : ""), sum));
|
||||||
|
var st = (Array.isArray(h.status) ? h.status : []).filter(function (x) { return x && typeof x.label === "string" && typeof x.value === "string"; });
|
||||||
|
if (!side && st.length) {
|
||||||
|
var p = el("p", "wx-st" + (at ? " is-hidden" : ""));
|
||||||
|
st.forEach(function (x, i) {
|
||||||
|
if (i) { var dot = el("span", "wx-dot", "·"); dot.setAttribute("aria-hidden", "true"); p.appendChild(dot); }
|
||||||
|
var one = el("span", "wx-si" + (x.tone === "warn" ? " is-warn" : ""));
|
||||||
|
one.appendChild(el("span", "wx-sl", x.label));
|
||||||
|
one.appendChild(doc.createTextNode(" "));
|
||||||
|
one.appendChild(el("b", "", x.value));
|
||||||
|
p.appendChild(one);
|
||||||
|
});
|
||||||
|
say.appendChild(p);
|
||||||
|
}
|
||||||
|
body.appendChild(say); // always, even empty: its room stays the same whichever cell is shown
|
||||||
|
// the four cells: 아침 · 낮 · 저녁 · 밤, the one it is now '지금'; a button each, the one shown pressed
|
||||||
|
var ol = el("ol", "wx-strip");
|
||||||
|
COLS.forEach(function (c) {
|
||||||
|
var isNow = c === mode, s = isNow ? now : pick(slots, HOUR[c]), sk = kind(s);
|
||||||
|
var ic = c === "night" && sk === "clear" ? "moon" : ICON[sk];
|
||||||
|
var name = isNow ? S.now : S[c], tc = isNow && num(h.temp_c) ? h.temp_c : s && s.temp_c;
|
||||||
|
var li = el("li");
|
||||||
|
var b = el("button", "wx-cell" + (c === cell ? " is-on" : ""));
|
||||||
|
b.type = "button";
|
||||||
|
b.setAttribute("data-wx-k", c);
|
||||||
|
b.setAttribute("aria-pressed", c === cell ? "true" : "false");
|
||||||
|
b.setAttribute("aria-label", num(tc) ? name + " " + Math.round(tc) + "도" : name);
|
||||||
|
b.appendChild(el("span", "wx-cn", name));
|
||||||
|
var img = el("img", "wx-ic");
|
||||||
|
img.src = ICONS + ic + ".webp";
|
||||||
|
img.alt = SKY[ic] || "";
|
||||||
|
img.width = img.height = side ? 18 : 22;
|
||||||
|
img.decoding = "async";
|
||||||
|
b.appendChild(img);
|
||||||
|
b.appendChild(el("b", "wx-tc", deg(tc)));
|
||||||
|
b.addEventListener("click", function () { again(box, D, c); });
|
||||||
|
li.appendChild(b);
|
||||||
|
ol.appendChild(li);
|
||||||
|
});
|
||||||
|
body.appendChild(ol);
|
||||||
|
// the link: only the 자세히 보기 button goes to 날씨각 (the rest of the card is not a link)
|
||||||
|
var go = box.querySelector("[data-wx-gl]");
|
||||||
|
if (go) {
|
||||||
|
var t = box.querySelector(".wx-t");
|
||||||
|
go.textContent = "";
|
||||||
|
go.appendChild(el("span", "vh", (t ? t.textContent : "") + " "));
|
||||||
|
go.appendChild(doc.createTextNode(w.more));
|
||||||
|
var arr = el("span", "wx-ar", "›");
|
||||||
|
arr.setAttribute("aria-hidden", "true");
|
||||||
|
go.appendChild(arr);
|
||||||
|
}
|
||||||
|
box.classList.add("is-ready");
|
||||||
|
if (!side) fitDate(box);
|
||||||
|
}
|
||||||
|
// the letters the card will show in 날씨각's round font (Jua) and in its score font (Bagel Fat One)
|
||||||
|
function roundText(D) {
|
||||||
|
var h = D.hero, S = WORDS.slots, s = "";
|
||||||
|
boxes.forEach(function (b) {
|
||||||
|
s += (b.querySelector(".wx-t") || {}).textContent || "";
|
||||||
|
s += WORDS.score + S.morning + S.day + S.sunset + S.night + S.now;
|
||||||
|
s += typeof h.bubble === "string" ? h.bubble : "";
|
||||||
|
COLS.forEach(function (k) { var p = D.picks[k]; s += p && typeof p.bubble === "string" ? p.bubble : ""; });
|
||||||
|
(Array.isArray(h.status) ? h.status : []).forEach(function (x) { s += (x && x.label || "") + (x && x.value || ""); });
|
||||||
|
});
|
||||||
|
return letters(s + "0123456789-–°·");
|
||||||
|
}
|
||||||
|
|
||||||
|
// the values the server put in the page (#wx-data); null when missing or broken
|
||||||
|
function given() {
|
||||||
|
var x = doc.getElementById("wx-data");
|
||||||
|
if (!x) return null;
|
||||||
|
// oxlint-disable-next-line no-unused-vars -- 옛 브라우저용 catch 바인딩 (seoul() 참고)
|
||||||
|
try { return JSON.parse(x.textContent); } catch (e) { return null; }
|
||||||
|
}
|
||||||
|
function fail() { boxes.forEach(function (b) { b.classList.add("is-failed"); }); }
|
||||||
|
// draw a card for cell k (null: now); one that cannot be drawn shows the link (is-failed)
|
||||||
|
function show(b, D, k) {
|
||||||
|
// oxlint-disable-next-line no-unused-vars -- 옛 브라우저용 catch 바인딩 (seoul() 참고)
|
||||||
|
try { draw(b, D, k); } catch (e) {
|
||||||
|
var x = b.querySelector("[data-wx-b]");
|
||||||
|
if (x) x.textContent = "";
|
||||||
|
b.classList.remove("is-ready");
|
||||||
|
b.classList.add("is-failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// a cell pressed: the card drawn again for it (is-again: the sun and clouds do not fall in again, card.css), the
|
||||||
|
// focus on that cell's new button (the cells are made anew), so the next Tab goes on to the cell after it
|
||||||
|
// a press that would show what is already shown (the same cell, or a cell without its own values) draws nothing
|
||||||
|
function again(box, D, k) {
|
||||||
|
var h = D.hero, mode = HOUR[h.sky_mode] ? h.sky_mode : clockSky();
|
||||||
|
if ((chosen(D, mode, k) || "") !== box.getAttribute("data-wx-at")) {
|
||||||
|
box.classList.add("is-again");
|
||||||
|
show(box, D, k);
|
||||||
|
}
|
||||||
|
var b = box.querySelector('[data-wx-k="' + k + '"]');
|
||||||
|
if (b) b.focus({ preventScroll: true });
|
||||||
|
}
|
||||||
|
function start() {
|
||||||
|
var g = given(), D = g && typeof g === "object" ? usable({ hero: g.hero }, g.today) : null;
|
||||||
|
if (!D) return fail();
|
||||||
|
D.picks = g.picks && typeof g.picks === "object" ? g.picks : {};
|
||||||
|
fonts(roundText(D), "0123456789", function () {
|
||||||
|
boxes.forEach(function (b) { show(b, D, null); });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
start();
|
||||||
|
// the iframe's width changed (the host page resized): look again whether the date fits
|
||||||
|
win.addEventListener("resize", function () {
|
||||||
|
boxes.forEach(function (b) { if (b.classList.contains("is-ready") && !b.classList.contains("wx-side")) fitDate(b); });
|
||||||
|
});
|
||||||
|
// a card off the screen (the host page scrolled it away) rests: its motion paused
|
||||||
|
if (win.IntersectionObserver) {
|
||||||
|
var rest = new win.IntersectionObserver(function (seen) {
|
||||||
|
seen.forEach(function (e) { e.target.classList.toggle("is-off", !e.isIntersecting); });
|
||||||
|
});
|
||||||
|
boxes.forEach(function (b) { rest.observe(b); });
|
||||||
|
}
|
||||||
|
})();
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ko">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="robots" content="noindex">
|
||||||
|
<title>날씨각</title>
|
||||||
|
<meta name="color-scheme" content="light">
|
||||||
|
<!-- 백엔드가 안 될 때 nginx 가 /embed/card 대신 주는 화면 (nginx.conf 의 @embed_quiet). 백엔드의 조용한 화면(embed_service.render_quiet)과 같은 모양, 배경은 sky -->
|
||||||
|
<style>html,body{margin:0;height:100%}body{display:flex;align-items:center;justify-content:center;box-sizing:border-box;padding:16px}a{display:inline-flex;align-items:center;min-height:44px;padding:0 18px;border-radius:999px;background:#fff;color:#28304a;font:700 14px/1.3 -apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", sans-serif;text-decoration:none;white-space:nowrap;box-shadow:0 4px 12px rgba(40,48,74,.12)}a:hover{color:#1d4f96;text-decoration:underline}.wx-q-sky::before{content:"";position:fixed;inset:0;z-index:-1;border-radius:28px;background:linear-gradient(#9fd3ff,#cfe9ff 55%,#f1f8ff)}</style>
|
||||||
|
</head>
|
||||||
|
<body class="wx-q-sky">
|
||||||
|
<a href="https://weather.o2o.kr/?utm_source=widget&utm_medium=embed&utm_campaign=unknown" target="_blank" rel="noopener">날씨각에서 날씨 보기 ›</a>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
/* umami 방문 통계 스크립트 — https://analytics.webforai.kr/script.js 를 2026-11-26 그대로 복사한 것.
|
||||||
|
외부 스크립트를 날씨각 페이지에서 직접 실행하지 않으려고(무결성 확인 대신) 날씨각에서 준다. 기록은 data-host-url 의 umami 서버로 간다.
|
||||||
|
umami 서버를 업그레이드해 기록이 안 되면 같은 주소에서 다시 받아 덮어쓴다(이 주석은 남긴다). 손으로 고치지 않는다. */
|
||||||
|
!function(){"use strict";function e(e,t=2e3){return e.slice(0,t).replace(/https?:\/\/[^\s)]+/g,e=>{try{const t=e.match(/:\d+:\d+$/)?.[0]||"",n=new URL(t?e.slice(0,-t.length):e);return`${n.origin}${n.pathname}${t}`}catch{return"[url]"}}).replace(/[\w.+-]+@[\w.-]+\.[a-z]{2,}/gi,"[email]").replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]+\b/g,"[token]").replace(/\b(password|secret|token|authorization|api[_-]?key)\s*[:=]\s*[^\s,;]+/gi,"$1=[redacted]").slice(0,t)}function t(t){try{return e(new URL(t,"https://localhost").pathname,500)}catch{return"/"}}function n(t={}){return Object.fromEntries(Object.entries(t).slice(0,20).filter(([e])=>!/password|secret|token|authorization|cookie|email|api.?key/i.test(e)).map(([t,n])=>[e(t,50),e(String(n),200)]))}function a(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function r(r){const i=new WeakMap,o=[];let s=!1,c=!1,l=0,d=0,f=0;async function u(u,m={},p=!0){try{if(!r.enabled||c||r.disabled()||o.length>=20)return;const h=Date.now();if(h<l)return;const y=Math.floor(h/6e4);if(d!==y&&(d=y,f=0),f>=20)return;if(u&&"object"==typeof u){if(h-(i.get(u)||0)<1e3)return;i.set(u,h)}f++;const g=r.context(),b=r.cache(),v=u&&"object"==typeof u?u:null,w="string"==typeof v?.message?v.message:"string"==typeof u?u:"Non-Error exception",T={version:1,website:g.website,eventId:a(),timestamp:h,name:e("string"==typeof v?.name?v.name:"Error",200)||"Error",message:e(w),stack:e("string"==typeof v?.stack?v.stack:"",16e3),handled:p,url:t(g.url),id:g.id,salt:g.salt,screen:g.screen,language:g.language,release:e(m.release||r.release,100),environment:e(m.environment||r.environment,50),tags:n(m.tags),...m.fingerprint?.length?{fingerprint:m.fingerprint.slice(0,5).map(t=>e(t,200))}:{}};let S;c=!0;try{S=r.beforeSend(T)}finally{c=!1}const k=await S;if(!k||r.disabled())return;o.push({payload:{...k,website:T.website,eventId:T.eventId,timestamp:h,version:1},cache:b}),async function(){if(!s){s=!0;try{for(;o.length;){const e=o.shift();if(!e||r.disabled())continue;const t=JSON.stringify({type:"error",payload:e.payload});if(!((new TextEncoder).encode(t).byteLength>48e3))for(let n=0;n<3&&!r.disabled();n++){try{const n=await fetch(r.endpoint,{method:"POST",keepalive:!0,credentials:"omit",body:t,headers:{"Content-Type":"application/json",...e.cache?{"x-umami-cache":e.cache}:{}}});if(n.ok){const t=await n.json();t.cache&&r.cache()===e.cache&&r.context().id===e.payload.id&&r.updateCache(t.cache);break}if(429===n.status){o.length=0;const e=Number(n.headers.get("Retry-After"))||60;l=Date.now()+1e3*Math.max(1,Math.min(e,300));break}if(n.status<500)break}catch{}n<2&&await new Promise(e=>setTimeout(e,1e3*2**n))}}}finally{s=!1}}}().catch(()=>{})}catch{}}return r.enabled&&(window.addEventListener("error",e=>{e.message&&u(e.error||{name:"Error",message:e.message,stack:e.filename?`at ${e.filename}:${e.lineno}:${e.colno}`:""},{},!1)}),window.addEventListener("unhandledrejection",e=>{u(e.reason,{},!1)})),{captureException:(e,t)=>u(e,t)}}(e=>{const{screen:{width:t,height:n},navigator:{language:a,doNotTrack:i,msDoNotTrack:o},location:s,document:c,history:l,top:d,doNotTrack:f}=e,{currentScript:u,referrer:m}=c,p=e.umamiConfig||{};if(!u&&!p.websiteId)return;const{hostname:h,href:y,origin:g}=s;let b;try{b=y.startsWith("data:")?void 0:e.localStorage}catch{}const v="data-",w="false",T="true",S=u?u.getAttribute.bind(u):()=>null,k=e=>{const t=S(`${v}${e}`);if(null!=t)return t;const n=p[(e=>e.replace(/-([a-z])/g,e=>e[1].toUpperCase()))(e)];return null==n||"function"==typeof n?null:Array.isArray(n)?n.join(","):String(n)},$=()=>{const t=k("before-send"),n=t?e[t]:p.beforeSend;return"function"==typeof n?n:void 0},x=k("website-id"),E=k("host-url"),j=k("distinct-id")||void 0,M=k("tag")||void 0,I=k("salt")||void 0,U=k("salt-rotation"),L=k("auto-track")!==w,O=k("do-not-track")===T,A=k("exclude-search")===T,D=k("exclude-hash")===T,C=k("domains")||"",N=k("fetch-credentials")||"omit",R=k("performance")===T,P=k("auto-pageview")!==w,z=C.split(",").map(e=>e.trim()),_=E||""||(u?u.src.split("/").slice(0,-1).join("/"):"");if(!u&&!_)return;const J=`${_.replace(/\/$/,"")}/api/send`,K=`${t}x${n}`,W=/data-umami-event-([\w-_]+)/,B=`${v}umami-event`,V=300,q=e=>{if(!e)return e;try{const t=new URL(e,s.href);return A&&(t.search=""),D&&(t.hash=""),t.toString()}catch{return e}},F=()=>{if(I)return I;const e={hourly:13,daily:10,weekly:10,monthly:7}[U];if(!e)return;const t=new Date;return"weekly"===U&&t.setUTCDate(t.getUTCDate()-t.getUTCDay()),t.toISOString().slice(0,e)},G=()=>{return{website:x,screen:K,language:a,title:c.title,hostname:h,url:re,referrer:(e=ie,e===g||e?.startsWith(`${g}/`)?e.slice(g.length):e),tag:M,id:ce||void 0,salt:F()};var e},H=(e,t,n)=>{n&&("function"==typeof ae&&ae(),ie=re,re=q(n),re!==ie&&P&&setTimeout(Z,VLine truncated
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/* 날씨각 위젯 스크립트 — 다른 사이트가 날씨각 링크와 함께 붙이는 작은 로더 (붙이는 코드는 src/lib/embedWidget.ts 의 embedScript).
|
||||||
|
<a class="nalssigak-weather" data-region="지역 코드 10자리" data-type="side|home" data-bg="sky|light|dark"> 링크 자리에
|
||||||
|
카드 iframe(/embed/card)을 끼워 넣는다. iframe 의 주소·크기·style 은 embedCode 가 만드는 iframe 과 같다
|
||||||
|
(tests/embedLoader.test.mjs 가 둘이 같은지 본다). 값이 틀린 링크는 그대로 두고, 이 파일이 막히거나 안 오면 링크가 남는다.
|
||||||
|
- 주소에 버전이 없어 붙인 사이트가 늘 최신 파일을 받는다(nginx /embed/ 1시간 캐시). 고칠 때 붙인 코드가 바뀌지 않게 한다.
|
||||||
|
- 날씨각 주소(origin)는 이 스크립트의 주소에서 얻는다 (로컬 도커에서도 그 서버의 카드를 붙인다).
|
||||||
|
- 남의 페이지에서 도니까 iframe 끼워 넣기 외에는 하지 않는다: 전역 이름·쿠키·저장소·추가 요청·콘솔 출력 없음.
|
||||||
|
- 옛 브라우저에서도 돌게 ES5 로만 쓴다. 화면에 가까워질 때 불러오기는 iframe 의 loading="lazy" 에 맡긴다. */
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
var doc = document;
|
||||||
|
// 모양별 [기본 높이, 최대 높이, 최소 폭, 최대 폭] (px), 폭:높이 비율 — embedWidget.ts 의 EMBED_HEIGHT·EMBED_MAX_HEIGHT·EMBED_MIN_WIDTH·EMBED_MAX_WIDTH, EMBED_RATIO
|
||||||
|
var SIZE = { side: [245, 320, 220, 440, "11/8"], home: [400, 520, 280, 720, "18/13"] };
|
||||||
|
var BGS = { sky: 1, light: 1, dark: 1 };
|
||||||
|
var own = Object.prototype.hasOwnProperty;
|
||||||
|
|
||||||
|
// currentScript 는 처음 실행될 때만 있다. 없는 브라우저면 이 파일을 부른 script 태그를 찾는다
|
||||||
|
var me = doc.currentScript;
|
||||||
|
if (!me) {
|
||||||
|
var found = doc.querySelectorAll('script[src*="/embed/widget.js"]');
|
||||||
|
me = found[found.length - 1];
|
||||||
|
}
|
||||||
|
var origin = me && /^https?:\/\/[^/?#]+/i.exec(me.src || "");
|
||||||
|
if (!origin) return;
|
||||||
|
origin = origin[0];
|
||||||
|
|
||||||
|
function put(a) {
|
||||||
|
var region = a.getAttribute("data-region");
|
||||||
|
var kind = a.getAttribute("data-type") || "side";
|
||||||
|
var bg = a.getAttribute("data-bg") || "sky";
|
||||||
|
if (!/^[0-9]{10}$/.test(region || "") || !own.call(SIZE, kind) || !own.call(BGS, bg) || !a.parentNode) return;
|
||||||
|
var s = SIZE[kind];
|
||||||
|
var title = (a.textContent || "").replace(/\s+/g, " ").replace(/^ | $/g, "") || "날씨각";
|
||||||
|
var f = doc.createElement("iframe");
|
||||||
|
f.setAttribute("src", origin + "/embed/card?region=" + encodeURIComponent(region) + "&type=" + kind + "&bg=" + bg);
|
||||||
|
f.setAttribute("title", title);
|
||||||
|
f.setAttribute("width", "100%");
|
||||||
|
f.setAttribute("height", String(s[0]));
|
||||||
|
f.setAttribute("style", "border:0;width:100%;height:auto;aspect-ratio:" + s[4] + ";min-width:" + s[2] + "px;max-width:" + s[3] + "px;min-height:" + s[0] + "px;max-height:" + s[1] + "px;border-radius:28px");
|
||||||
|
f.setAttribute("loading", "lazy");
|
||||||
|
f.setAttribute("referrerpolicy", "origin");
|
||||||
|
a.parentNode.replaceChild(f, a);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 끼워 넣은 링크는 문서에서 빠지므로 여러 번 돌아도(스크립트를 두 번 붙임) 카드는 하나다
|
||||||
|
function place() {
|
||||||
|
var links = doc.querySelectorAll("a.nalssigak-weather[data-region]");
|
||||||
|
for (var i = 0; i < links.length; i++) put(links[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
place();
|
||||||
|
// 문서가 다 읽히기 전에 돌았으면 스크립트보다 아래에 있는 링크를 위해 다 읽힌 뒤 한 번 더
|
||||||
|
if (doc.readyState === "loading") doc.addEventListener("DOMContentLoaded", place);
|
||||||
|
})();
|
||||||
@@ -37,7 +37,7 @@
|
|||||||
<p>회원 정보는 회원 탈퇴 시까지 보관하며, 탈퇴 요청을 받으면 지체 없이 파기합니다. 접속 기록은 「통신비밀보호법」에 따라 3개월간 보관합니다.</p>
|
<p>회원 정보는 회원 탈퇴 시까지 보관하며, 탈퇴 요청을 받으면 지체 없이 파기합니다. 접속 기록은 「통신비밀보호법」에 따라 3개월간 보관합니다.</p>
|
||||||
|
|
||||||
<h2>3. 제3자 제공 및 처리 위탁</h2>
|
<h2>3. 제3자 제공 및 처리 위탁</h2>
|
||||||
<p>회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 광고 게재를 위해 Google AdSense(Google LLC)를 사용하며, Google은 쿠키로 이 사이트와 다른 사이트 방문 기록을 바탕으로 광고를 보여 줄 수 있습니다. 맞춤 광고는 Google 광고 설정(https://adssettings.google.com)에서 끌 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.</p>
|
<p>회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 이용 통계를 위해 쿠키를 쓰지 않는 방문 통계 도구 umami(analytics.webforai.kr)도 사용합니다. umami는 본 페이지 주소, 들어온 경로, 브라우저·기기 종류, 국가를 집계하며 IP 주소는 저장하지 않습니다. 다른 사이트에 붙은 날씨각 위젯(날씨 카드)이 보일 때도 그 조회와 위젯을 붙인 사이트 주소를 같은 방식으로 집계합니다. 광고 게재를 위해 Google AdSense(Google LLC)를 사용하며, Google은 쿠키로 이 사이트와 다른 사이트 방문 기록을 바탕으로 광고를 보여 줄 수 있습니다. 맞춤 광고는 Google 광고 설정(https://adssettings.google.com)에서 끌 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.</p>
|
||||||
|
|
||||||
<h2>4. 파기 절차 및 방법</h2>
|
<h2>4. 파기 절차 및 방법</h2>
|
||||||
<p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p>
|
<p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p>
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { TalkPage } from './b/TalkPage'
|
|||||||
import { TodayPage } from './b/TodayPage'
|
import { TodayPage } from './b/TodayPage'
|
||||||
import { TypePage } from './b/TypePage'
|
import { TypePage } from './b/TypePage'
|
||||||
import { WeekPage } from './b/WeekPage'
|
import { WeekPage } from './b/WeekPage'
|
||||||
|
import { WidgetPage } from './b/WidgetPage'
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
@@ -34,6 +35,7 @@ export default function App() {
|
|||||||
<Route path="talk" element={<TalkPage />} />
|
<Route path="talk" element={<TalkPage />} />
|
||||||
<Route path="shorts/:id?" element={<ShortsPage />} />
|
<Route path="shorts/:id?" element={<ShortsPage />} />
|
||||||
<Route path="game" element={<CloudMergePage />} />
|
<Route path="game" element={<CloudMergePage />} />
|
||||||
|
<Route path="widget-guide" element={<WidgetPage />} />
|
||||||
<Route path="*" element={<TodayPage />} />
|
<Route path="*" element={<TodayPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
+91
-14
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||||
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
|
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
|
||||||
import { useIsFetching, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useIsFetching, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { authConfigOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
import { authConfigOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||||
@@ -16,8 +16,8 @@ import { useRegion } from './regionContext'
|
|||||||
import { useSheet } from './sheetContext'
|
import { useSheet } from './sheetContext'
|
||||||
import { SheetProvider } from './Sheets'
|
import { SheetProvider } from './Sheets'
|
||||||
import { SkyContext, useSky } from './skyContext'
|
import { SkyContext, useSky } from './skyContext'
|
||||||
import { TossIntro } from './tossIntro'
|
import { TossIntro, tossIntroPending } from './tossIntro'
|
||||||
import { PinIcon, TabIcon } from './svg'
|
import { ChevronDownIcon, PinIcon, TabIcon } from './svg'
|
||||||
import { Avatar, Ic, Skel } from './ui'
|
import { Avatar, Ic, Skel } from './ui'
|
||||||
|
|
||||||
const TABS = [
|
const TABS = [
|
||||||
@@ -45,7 +45,11 @@ function SeasonChip() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function TopBar() {
|
/** 지역 말풍선이 사라지는 데 걸리는 시간(ms). 말풍선의 duration-200 과 같게 */
|
||||||
|
const HINT_FADE = 200
|
||||||
|
|
||||||
|
/** hintReady: 첫 화면 덮개(불러오는 중·토스 소개)가 걷혀 지역 말풍선을 띄워도 되는지 */
|
||||||
|
function TopBar({ hintReady }: { hintReady: boolean }) {
|
||||||
const { pathname } = useLocation()
|
const { pathname } = useLocation()
|
||||||
const { region, locateStatus } = useRegion()
|
const { region, locateStatus } = useRegion()
|
||||||
const { open } = useSheet()
|
const { open } = useSheet()
|
||||||
@@ -53,6 +57,48 @@ function TopBar() {
|
|||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
||||||
const loggedOut = !mePending && !me
|
const loggedOut = !mePending && !me
|
||||||
|
// '경기 성남시 분당구' → 앞쪽 '경기 성남시' 와 구 이름 '분당구'
|
||||||
|
const nameParts = region.name.split(' ')
|
||||||
|
const place = nameParts.at(-1)!
|
||||||
|
const upper = nameParts.slice(0, -1).join(' ')
|
||||||
|
// 지역 말풍선: 들어올 때마다 뜨고, 화면을 만지면(터치·클릭·휠·키) 사라진다. 한 번 사라지면 탭을 옮겨도 다시 안 뜬다
|
||||||
|
const [hint, setHint] = useState<'on' | 'leaving' | 'gone'>('on')
|
||||||
|
const hintWrap = useRef<HTMLDivElement>(null)
|
||||||
|
// 위치를 찾는 중에는 버튼에 구 이름이 아직 없다. 쇼츠는 화면 전체가 영상이라 가리지 않는다
|
||||||
|
const hintCan = hintReady && locateStatus !== 'locating' && !pathname.startsWith('/shorts')
|
||||||
|
const hintOn = hintCan && hint === 'on'
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hintOn) return
|
||||||
|
track('region_hint_view', {})
|
||||||
|
const leave = (e: Event) => {
|
||||||
|
// 지역 버튼·말풍선을 누른 것은 openRegion 이 맡는다 (여기서 먼저 지우면 말풍선을 보고 눌렀는지 알 수 없다)
|
||||||
|
if (e.target instanceof Node && hintWrap.current?.contains(e.target)) return
|
||||||
|
setHint('leaving')
|
||||||
|
}
|
||||||
|
// 스크롤 대신 터치·휠을 본다: 뒤로 가기 때 화면이 제자리를 찾아가는 스크롤에 꺼지지 않게
|
||||||
|
const opts = { capture: true, passive: true }
|
||||||
|
window.addEventListener('pointerdown', leave, opts)
|
||||||
|
window.addEventListener('wheel', leave, opts)
|
||||||
|
window.addEventListener('keydown', leave, opts)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('pointerdown', leave, opts)
|
||||||
|
window.removeEventListener('wheel', leave, opts)
|
||||||
|
window.removeEventListener('keydown', leave, opts)
|
||||||
|
}
|
||||||
|
}, [hintOn])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (hint !== 'leaving') return
|
||||||
|
const id = setTimeout(() => setHint('gone'), HINT_FADE)
|
||||||
|
return () => clearTimeout(id)
|
||||||
|
}, [hint])
|
||||||
|
|
||||||
|
const openRegion = (from: 'bubble' | 'button') => {
|
||||||
|
if (hintOn) track('region_hint_tap', { from })
|
||||||
|
setHint('gone')
|
||||||
|
open({ type: 'region' })
|
||||||
|
}
|
||||||
|
|
||||||
// 로그인 창을 처음 열 때 버벅이지 않게 구글 로그인 준비물을 미리 받아 둔다
|
// 로그인 창을 처음 열 때 버벅이지 않게 구글 로그인 준비물을 미리 받아 둔다
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -65,15 +111,38 @@ function TopBar() {
|
|||||||
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
|
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
|
||||||
{tab?.title ? <h1 className="shrink-0 font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="shrink-0 font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
|
{tab?.title ? <h1 className="shrink-0 font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="shrink-0 font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
|
||||||
<SeasonChip />
|
<SeasonChip />
|
||||||
|
{/* 400px 부터는 시·도까지 쓴 긴 이름이라 자리가 모자라면 앞쪽(시·도·시)만 줄이고(…) 구 이름은 남긴다. 그대로 두면 오른쪽 로그인 버튼이 화면 밖으로 밀린다 */}
|
||||||
|
<div ref={hintWrap} className="relative ml-auto flex shrink-0 min-[400px]:min-w-0 min-[400px]:shrink">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => open({ type: 'region' })}
|
onClick={() => openRegion('button')}
|
||||||
aria-label={`위치 바꾸기, 지금 ${region.name}`}
|
aria-label={`위치 바꾸기, 지금 ${region.name}`}
|
||||||
className="ml-auto flex shrink-0 cursor-pointer items-center gap-1 rounded-full bg-white px-3 pt-1 pb-2 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
|
className="flex min-w-0 cursor-pointer items-center gap-1 rounded-full bg-white pt-1 pr-2.5 pb-2 pl-3 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
|
||||||
>
|
>
|
||||||
<PinIcon className="size-3.5 shrink-0" />
|
<PinIcon className="size-3.5 shrink-0" />
|
||||||
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : <span className="truncate whitespace-nowrap"><span className="max-[399px]:hidden">{region.name}</span><span className="min-[400px]:hidden">{region.name.split(' ').at(-1)}</span></span>}
|
{locateStatus === 'locating' ? (
|
||||||
|
<Skel className="w-[72px]" />
|
||||||
|
) : (
|
||||||
|
<span className="flex min-w-0 whitespace-nowrap">
|
||||||
|
{upper && <span className="mr-[0.28em] truncate max-[400px]:hidden">{upper}</span>}
|
||||||
|
<span className="shrink-0">{place}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{/* 360px 보다 좁은 화면은 위 바에 자리가 없어 화살표를 뺀다 (로그인 버튼이 밀려 잘린다) */}
|
||||||
|
<ChevronDownIcon className="size-3 shrink-0 opacity-60 max-[360px]:hidden" />
|
||||||
</button>
|
</button>
|
||||||
|
{hintCan && hint !== 'gone' && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => openRegion('bubble')}
|
||||||
|
className={cx('b-hint absolute top-full right-0 mt-2 cursor-pointer rounded-2xl bg-(--ink) px-3.5 py-2 text-left text-[13px] leading-snug font-bold whitespace-nowrap text-white shadow-[0_8px_18px_rgb(40_48_74/0.25)] transition-opacity duration-200', hint === 'leaving' && 'opacity-0')}
|
||||||
|
>
|
||||||
|
<i className="absolute -top-1 right-7 size-3 rotate-45 rounded-[2px] bg-inherit" aria-hidden="true" />
|
||||||
|
다른 동네 날씨도 볼 수 있어요
|
||||||
|
<span className="block font-extrabold text-[#ffd9b5]">눌러서 바꾸기</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
{mePending ? (
|
{mePending ? (
|
||||||
<Skel shape className="size-9 shrink-0 rounded-full" />
|
<Skel shape className="size-9 shrink-0 rounded-full" />
|
||||||
) : me ? (
|
) : me ? (
|
||||||
@@ -219,8 +288,8 @@ const NOTCH_BG: Record<TimeKind, string> = {
|
|||||||
night: '#0e1433',
|
night: '#0e1433',
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 처음 들어올 때만: 첫 데이터를 다 받을 때까지 하늘 위에 캐릭터와 '날씨 불러오는 중…'. 한 번 사라지면 다시 안 뜬다 */
|
/** 처음 들어올 때만: 첫 데이터를 다 받을 때까지 하늘 위에 캐릭터와 '날씨 불러오는 중…'. 한 번 사라지면 다시 안 뜬다. 걷히기 시작하면 onDone 을 부른다 */
|
||||||
function FirstLoad() {
|
function FirstLoad({ onDone }: { onDone: () => void }) {
|
||||||
const fetching = useIsFetching()
|
const fetching = useIsFetching()
|
||||||
const { kind } = useSky()
|
const { kind } = useSky()
|
||||||
const [started, setStarted] = useState(false)
|
const [started, setStarted] = useState(false)
|
||||||
@@ -237,6 +306,10 @@ function FirstLoad() {
|
|||||||
const id = setTimeout(() => setDone(true), 10000)
|
const id = setTimeout(() => setDone(true), 10000)
|
||||||
return () => clearTimeout(id)
|
return () => clearTimeout(id)
|
||||||
}, [])
|
}, [])
|
||||||
|
const cleared = done || gone
|
||||||
|
useEffect(() => {
|
||||||
|
if (cleared) onDone()
|
||||||
|
}, [cleared, onDone])
|
||||||
if (gone) return null
|
if (gone) return null
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -255,10 +328,13 @@ function FirstLoad() {
|
|||||||
// 페이지마다 마지막 스크롤 위치: 뒤로 가기로 돌아오면 그 자리로
|
// 페이지마다 마지막 스크롤 위치: 뒤로 가기로 돌아오면 그 자리로
|
||||||
const scrolled = new Map<string, number>()
|
const scrolled = new Map<string, number>()
|
||||||
|
|
||||||
function Shell() {
|
/** intro: 토스 첫 소개 화면이 떠 있는지 */
|
||||||
|
function Shell({ intro }: { intro: boolean }) {
|
||||||
const { pathname, key } = useLocation()
|
const { pathname, key } = useLocation()
|
||||||
const navType = useNavigationType()
|
const navType = useNavigationType()
|
||||||
const { kind } = useSky()
|
const { kind } = useSky()
|
||||||
|
const [loaded, setLoaded] = useState(false)
|
||||||
|
const onLoaded = useCallback(() => setLoaded(true), [])
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const save = () => scrolled.set(key, window.scrollY)
|
const save = () => scrolled.set(key, window.scrollY)
|
||||||
window.addEventListener('scroll', save, { passive: true })
|
window.addEventListener('scroll', save, { passive: true })
|
||||||
@@ -298,7 +374,7 @@ function Shell() {
|
|||||||
return (
|
return (
|
||||||
<div className="min-h-dvh text-(--ink)">
|
<div className="min-h-dvh text-(--ink)">
|
||||||
<SkyBg />
|
<SkyBg />
|
||||||
<FirstLoad />
|
<FirstLoad onDone={onLoaded} />
|
||||||
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
|
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
|
||||||
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
|
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
|
||||||
{HOLIDAY && (
|
{HOLIDAY && (
|
||||||
@@ -308,7 +384,7 @@ function Shell() {
|
|||||||
)}
|
)}
|
||||||
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
|
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
|
||||||
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(104px+var(--sab))]">
|
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(104px+var(--sab))]">
|
||||||
<TopBar />
|
<TopBar hintReady={loaded && !intro} />
|
||||||
<main className="relative z-[1]">
|
<main className="relative z-[1]">
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</main>
|
</main>
|
||||||
@@ -355,13 +431,14 @@ function SkyApp({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function BLayout() {
|
export function BLayout() {
|
||||||
|
const [intro, setIntro] = useState(tossIntroPending)
|
||||||
return (
|
return (
|
||||||
<SkyRoot>
|
<SkyRoot>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<RegionProvider>
|
<RegionProvider>
|
||||||
<SheetProvider>
|
<SheetProvider>
|
||||||
<Shell />
|
<Shell intro={intro} />
|
||||||
<TossIntro />
|
{intro && <TossIntro onStart={() => setIntro(false)} />}
|
||||||
<LevelWatcher />
|
<LevelWatcher />
|
||||||
</SheetProvider>
|
</SheetProvider>
|
||||||
</RegionProvider>
|
</RegionProvider>
|
||||||
|
|||||||
+19
-1
@@ -103,6 +103,20 @@ function Pic({ name, className }: { name: string; className?: string }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 표(Rows) 위에 뜨는 그림. 제목 칸(카드 위 여백 아래부터 표 바로 위까지, relative) 안에 두고, 카드 높이 30% 선에서 시작해 표 6px 위에서 끝나는 상자에 맞춘다.
|
||||||
|
* 자리가 넉넉하면 Pic 과 같은 자리·크기(카드 너비의 42%)이고, 표가 길거나 화면이 좁으면 표를 덮지 않게 줄어든다.
|
||||||
|
* 계산: 제목 칸 너비 = 카드 너비 − 40px(좌우 여백), 카드는 4:5 라 카드 높이의 30% = 칸 너비의 37.5% + 15px. 칸은 카드 위에서 22px 아래라 15 − 22 = −7px.
|
||||||
|
* top 의 % 는 칸 높이 기준이라 못 쓰고, 너비 기준인 margin-top 으로 37.5% 를 준다
|
||||||
|
*/
|
||||||
|
function RowsPic({ name }: { name: string }) {
|
||||||
|
return (
|
||||||
|
<span className="b-fall pointer-events-none absolute -top-[7px] right-[-6px] bottom-1.5 mt-[37.5%] w-[calc(42%+16.8px)]" style={fall('.1s', '5s')}>
|
||||||
|
<Ic name={name} className="b-bob size-full object-contain object-[right_top] drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const slideBase = 'relative flex h-full w-full shrink-0 flex-col px-5 py-[22px]'
|
const slideBase = 'relative flex h-full w-full shrink-0 flex-col px-5 py-[22px]'
|
||||||
|
|
||||||
// 달 포스트 밤하늘 별: [left %, top %, 크기 px]
|
// 달 포스트 밤하늘 별: [left %, top %, 크기 px]
|
||||||
@@ -292,11 +306,15 @@ export function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?:
|
|||||||
)
|
)
|
||||||
return (
|
return (
|
||||||
<div className={cx(slideBase, `b-bg-${bg}`, slide.moon_pct != null && 'isolate')} style={img}>
|
<div className={cx(slideBase, `b-bg-${bg}`, slide.moon_pct != null && 'isolate')} style={img}>
|
||||||
|
{/* 제목 칸: 표 바로 위까지 차지해, 그림(RowsPic)이 표를 덮지 않게 아래 끝을 잡아 준다 */}
|
||||||
|
<div className="relative min-h-0 flex-1">
|
||||||
<Eyebrow className={DARK.has(bg) ? 'opacity-85' : undefined}>{slide.eyebrow}</Eyebrow>
|
<Eyebrow className={DARK.has(bg) ? 'opacity-85' : undefined}>{slide.eyebrow}</Eyebrow>
|
||||||
<Big className="relative z-[1]">
|
<Big className="relative z-[1]">
|
||||||
<Lines text={slide.line} />
|
<Lines text={slide.line} />
|
||||||
</Big>
|
</Big>
|
||||||
{slide.moon_pct != null ? <MoonPic pct={slide.moon_pct} waxing={!!slide.moon_waxing} /> : <Pic name={slide.icon} className="w-[36%]" />}
|
{slide.moon_pct == null && <RowsPic name={slide.icon} />}
|
||||||
|
</div>
|
||||||
|
{slide.moon_pct != null && <MoonPic pct={slide.moon_pct} waxing={!!slide.moon_waxing} />}
|
||||||
<Rows rows={slide.rows ?? []} dark={DARK.has(bg)} />
|
<Rows rows={slide.rows ?? []} dark={DARK.has(bg)} />
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
||||||
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||||
|
import { useLocation, useNavigate } from 'react-router'
|
||||||
import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
|
import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
|
||||||
import { SITE_URL } from '../api/setup'
|
import { SITE_URL } from '../api/setup'
|
||||||
import {
|
import {
|
||||||
@@ -46,7 +47,7 @@ import { WeatherWhySheet } from './weatherWhy'
|
|||||||
import { useSky } from './skyContext'
|
import { useSky } from './skyContext'
|
||||||
import { LEVELS } from './cloudMerge'
|
import { LEVELS } from './cloudMerge'
|
||||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||||
import { SheetContext, sheetEntryOnTop, useSheet, type CommentTarget, type SharePayload, type SheetState } from './sheetContext'
|
import { SheetContext, sheetEntryOnTop, useSheet, type CommentTarget, type RegionPick, type SharePayload, type SheetState } from './sheetContext'
|
||||||
import { HeartIcon } from './svg'
|
import { HeartIcon } from './svg'
|
||||||
import { MyTalks } from './talk'
|
import { MyTalks } from './talk'
|
||||||
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
|
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
|
||||||
@@ -141,7 +142,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
|||||||
}, [isOpen])
|
}, [isOpen])
|
||||||
|
|
||||||
const then = shown?.type === 'login' ? shown.then : undefined
|
const then = shown?.type === 'login' ? shown.then : undefined
|
||||||
const title = !shown ? '' : shown.type === 'gak' ? gakTitle : shown.type === 'article' ? articleTitle || TITLES.article : shown.type === 'mix' ? (shown.shared ? '받은 각' : '내 각 만들기') : shown.type === 'myGak' ? '내 각' : TITLES[shown.type]
|
const title = !shown ? '' : shown.type === 'gak' ? gakTitle : shown.type === 'article' ? articleTitle || TITLES.article : shown.type === 'mix' ? (shown.shared ? '받은 각' : '내 각 만들기') : shown.type === 'myGak' ? '내 각' : shown.type === 'region' && shown.pick ? '미리 볼 지역 고르기' : TITLES[shown.type]
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<dialog
|
<dialog
|
||||||
@@ -175,7 +176,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
|||||||
{shown.type === 'comments' && <CommentsSheet to={shown} draft={shown.draft} />}
|
{shown.type === 'comments' && <CommentsSheet to={shown} draft={shown.draft} />}
|
||||||
{shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} why={shown.why} />}
|
{shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} why={shown.why} />}
|
||||||
{shown.type === 'me' && <MeSheet onDone={onClose} />}
|
{shown.type === 'me' && <MeSheet onDone={onClose} />}
|
||||||
{shown.type === 'region' && <RegionSheet onDone={onClose} />}
|
{shown.type === 'region' && <RegionSheet onDone={onClose} pick={shown.pick} />}
|
||||||
{shown.type === 'mix' && <MixSheet shared={shown.shared} onDone={onClose} />}
|
{shown.type === 'mix' && <MixSheet shared={shown.shared} onDone={onClose} />}
|
||||||
{shown.type === 'myGak' && <MyGakSheet gak={shown.gak} shot={shown.shot} onDone={onClose} />}
|
{shown.type === 'myGak' && <MyGakSheet gak={shown.gak} shot={shown.shot} onDone={onClose} />}
|
||||||
{shown.type === 'install' && <InstallSheet />}
|
{shown.type === 'install' && <InstallSheet />}
|
||||||
@@ -560,9 +561,28 @@ const CONTACTS = [
|
|||||||
{ method: 'phone', label: '전화 문의', value: '010-2755-6463', href: 'tel:010-2755-6463', icon: 'M6.6 3h3l1.5 4.2-2 1.5a12 12 0 0 0 6.2 6.2l1.5-2L21 14.4v3A2.6 2.6 0 0 1 18.4 20 15.4 15.4 0 0 1 4 5.6 2.6 2.6 0 0 1 6.6 3Z' },
|
{ method: 'phone', label: '전화 문의', value: '010-2755-6463', href: 'tel:010-2755-6463', icon: 'M6.6 3h3l1.5 4.2-2 1.5a12 12 0 0 0 6.2 6.2l1.5-2L21 14.4v3A2.6 2.6 0 0 1 18.4 20 15.4 15.4 0 0 1 4 5.6 2.6 2.6 0 0 1 6.6 3Z' },
|
||||||
{ method: 'email', label: '이메일 문의', value: 'sales@o2o.kr', href: 'mailto:sales@o2o.kr', icon: 'M3.5 6.5h17v11h-17zM4 7l8 6.5L20 7' },
|
{ method: 'email', label: '이메일 문의', value: 'sales@o2o.kr', href: 'mailto:sales@o2o.kr', icon: 'M3.5 6.5h17v11h-17zM4 7l8 6.5L20 7' },
|
||||||
] as const
|
] as const
|
||||||
|
// 창 안의 해: 다른 사이트에 붙이는 날씨 카드
|
||||||
|
const WIDGET_ICON = 'M5 4.5h14A1.5 1.5 0 0 1 20.5 6v12a1.5 1.5 0 0 1-1.5 1.5H5A1.5 1.5 0 0 1 3.5 18V6A1.5 1.5 0 0 1 5 4.5ZM3.5 8.5h17M14.5 14a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0Z'
|
||||||
|
|
||||||
/** 오른쪽 아래 문의 버튼으로 여는 창: 운영사 소개와 전화·이메일 */
|
/** 오른쪽 아래 문의 버튼으로 여는 창: 운영사 소개와 전화·이메일, 날씨 위젯 사용 방법으로 가는 줄(토스 빌드에는 없음) */
|
||||||
function ContactSheet({ onDone }: { onDone: () => void }) {
|
function ContactSheet({ onDone }: { onDone: () => void }) {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const { pathname } = useLocation()
|
||||||
|
// 창이 쌓아 둔 방문 기록을 닫으며 되돌리므로(history.back), 되돌린 뒤(popstate)에 옮겨야 새 주소가 안 지워지고 뒤로 가기가 이 화면으로 온다
|
||||||
|
const toWidget = () => {
|
||||||
|
if (pathname === '/widget-guide') {
|
||||||
|
onDone()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const go = () => navigate('/widget-guide', { state: { from: 'contact' } })
|
||||||
|
if (sheetEntryOnTop()) {
|
||||||
|
window.addEventListener('popstate', go, { once: true })
|
||||||
|
onDone()
|
||||||
|
} else {
|
||||||
|
onDone()
|
||||||
|
go()
|
||||||
|
}
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<Body className="flex flex-col items-center text-center">
|
<Body className="flex flex-col items-center text-center">
|
||||||
<img src="/b/aio2o.png" alt="AIO2O" width={162} height={27} className="mt-1 block h-[27px] w-auto" />
|
<img src="/b/aio2o.png" alt="AIO2O" width={162} height={27} className="mt-1 block h-[27px] w-auto" />
|
||||||
@@ -570,7 +590,7 @@ function ContactSheet({ onDone }: { onDone: () => void }) {
|
|||||||
<p className="mt-1.5 mb-0 text-[13.5px] leading-[1.6] font-semibold text-(--ink2)">
|
<p className="mt-1.5 mb-0 text-[13.5px] leading-[1.6] font-semibold text-(--ink2)">
|
||||||
날씨에 맞춘 광고, 지역 축제·행사 소개,
|
날씨에 맞춘 광고, 지역 축제·행사 소개,
|
||||||
<br />
|
<br />
|
||||||
콘텐츠 협업 같은 제휴 문의를 받아요.
|
날씨 위젯, 콘텐츠 협업 같은 제휴 문의를 받아요.
|
||||||
<br />
|
<br />
|
||||||
전화나 이메일로 편하게 알려 주세요.
|
전화나 이메일로 편하게 알려 주세요.
|
||||||
</p>
|
</p>
|
||||||
@@ -591,6 +611,20 @@ function ContactSheet({ onDone }: { onDone: () => void }) {
|
|||||||
</span>
|
</span>
|
||||||
</a>
|
</a>
|
||||||
))}
|
))}
|
||||||
|
{/* 위젯은 다른 사이트에 붙이는 웹 기능이라 토스 미니앱에서는 보이지 않는다 */}
|
||||||
|
{!IS_TOSS && (
|
||||||
|
<button type="button" onClick={toWidget} className="flex w-full cursor-pointer items-center gap-3 rounded-[16px] bg-[#f3f6fb] p-3 text-left text-(--ink)">
|
||||||
|
<span className="b-keep-bg grid size-11 shrink-0 place-items-center rounded-full bg-white text-(--orange)">
|
||||||
|
<svg viewBox="0 0 24 24" className="size-[22px]" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||||
|
<path d={WIDGET_ICON} />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0 flex-1 truncate text-[17px] font-extrabold">날씨 위젯 달기</span>
|
||||||
|
<span className="text-xl text-(--orange)" aria-hidden="true">
|
||||||
|
›
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-3.5 mb-0 text-[12px] font-semibold text-(--ink3)">날씨각은 주식회사 에이아이오투오가 만들어요</p>
|
<p className="mt-3.5 mb-0 text-[12px] font-semibold text-(--ink3)">날씨각은 주식회사 에이아이오투오가 만들어요</p>
|
||||||
<button type="button" onClick={onDone} className="mt-3 w-full cursor-pointer rounded-[14px] bg-(--orange) p-3 text-[15px] font-extrabold text-white">
|
<button type="button" onClick={onDone} className="mt-3 w-full cursor-pointer rounded-[14px] bg-(--orange) p-3 text-[15px] font-extrabold text-white">
|
||||||
@@ -1440,8 +1474,10 @@ const pageHref = (code: string) => {
|
|||||||
return p ? `/today/${p.path}` : '/'
|
return p ? `/today/${p.path}` : '/'
|
||||||
}
|
}
|
||||||
|
|
||||||
function RegionSheet({ onDone }: { onDone: () => void }) {
|
/** pick 이 있으면 '고르기만' 모드: 앱 지역을 바꾸지 않고(region_change 도 안 보냄) 고른 지역을 onPick 으로 넘긴다. 위치로 찾기·로그인 줄은 없다 */
|
||||||
|
function RegionSheet({ onDone, pick }: { onDone: () => void; pick?: RegionPick }) {
|
||||||
const { region, setRegion, locate, locateStatus } = useRegion()
|
const { region, setRegion, locate, locateStatus } = useRegion()
|
||||||
|
const current = pick ? pick.current : region.code
|
||||||
const { me, logout } = useAuth()
|
const { me, logout } = useAuth()
|
||||||
const { open } = useSheet()
|
const { open } = useSheet()
|
||||||
const alive = useRef(true)
|
const alive = useRef(true)
|
||||||
@@ -1459,12 +1495,16 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Body>
|
<Body>
|
||||||
|
{!pick && (
|
||||||
|
<>
|
||||||
<button type="button" onClick={() => locate(() => alive.current && onDone())} disabled={locateStatus === 'locating'} className="w-full cursor-pointer rounded-full bg-(--orange) p-3 font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
<button type="button" onClick={() => locate(() => alive.current && onDone())} disabled={locateStatus === 'locating'} className="w-full cursor-pointer rounded-full bg-(--orange) p-3 font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||||
지금 위치로 찾기
|
지금 위치로 찾기
|
||||||
</button>
|
</button>
|
||||||
<p className="mt-2 min-h-5 text-center text-[13px] font-bold text-(--ink2)" aria-live="polite">
|
<p className="mt-2 min-h-5 text-center text-[13px] font-bold text-(--ink2)" aria-live="polite">
|
||||||
{LOCATE_TEXT[locateStatus]}
|
{LOCATE_TEXT[locateStatus]}
|
||||||
</p>
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="구 이름으로 찾기 (예: 마포)" aria-label="구 이름으로 찾기" className="mt-1 w-full rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="구 이름으로 찾기 (예: 마포)" aria-label="구 이름으로 찾기" className="mt-1 w-full rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||||
{listLoad === 'loading' && <RegionsSkel />}
|
{listLoad === 'loading' && <RegionsSkel />}
|
||||||
{listLoad !== 'loading' && !regions.length && (listLoad === 'ready' ? <StateBox load={listLoad} empty="찾는 구가 없어요." className="mt-3" /> : <StateBox load={listLoad} onRetry={() => list.refetch()} hold={<RegionsSkel />} className="inset-x-0 top-2 bottom-0" />)}
|
{listLoad !== 'loading' && !regions.length && (listLoad === 'ready' ? <StateBox load={listLoad} empty="찾는 구가 없어요." className="mt-3" /> : <StateBox load={listLoad} onRetry={() => list.refetch()} hold={<RegionsSkel />} className="inset-x-0 top-2 bottom-0" />)}
|
||||||
@@ -1473,27 +1513,33 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
|||||||
<li key={r.code}>
|
<li key={r.code}>
|
||||||
<a
|
<a
|
||||||
href={pageHref(r.code)}
|
href={pageHref(r.code)}
|
||||||
aria-current={r.code === region.code ? 'true' : undefined}
|
aria-current={r.code === current ? 'true' : undefined}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
if (pick) {
|
||||||
|
pick.onPick(r)
|
||||||
|
} else {
|
||||||
setRegion(r)
|
setRegion(r)
|
||||||
track('region_change', { region_name: r.name, method: 'list' })
|
track('region_change', { region_name: r.name, method: 'list' })
|
||||||
|
}
|
||||||
onDone()
|
onDone()
|
||||||
}}
|
}}
|
||||||
className={cx('flex w-full cursor-pointer items-center justify-between border-b-[1.5px] border-(--line) px-1 py-3 text-left font-jua text-[17px]', r.code === region.code && 'text-(--orange)')}
|
className={cx('flex w-full cursor-pointer items-center justify-between border-b-[1.5px] border-(--line) px-1 py-3 text-left font-jua text-[17px]', r.code === current && 'text-(--orange)')}
|
||||||
>
|
>
|
||||||
{r.name}
|
{r.name}
|
||||||
{r.code === region.code && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
|
{r.code === current && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
{!pick && (
|
||||||
<p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)">
|
<p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)">
|
||||||
{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'}
|
{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'}
|
||||||
<button type="button" onClick={me ? logout : () => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--rain)">
|
<button type="button" onClick={me ? logout : () => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--rain)">
|
||||||
{me ? '로그아웃' : '로그인'}
|
{me ? '로그아웃' : '로그인'}
|
||||||
</button>
|
</button>
|
||||||
</p>
|
</p>
|
||||||
|
)}
|
||||||
</Body>
|
</Body>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -42,6 +42,9 @@ import { track } from '../lib/analytics'
|
|||||||
|
|
||||||
type Mode = 'now' | TimeKind
|
type Mode = 'now' | TimeKind
|
||||||
|
|
||||||
|
/** 1위 각이 이 점수(중요도 배율을 곱한 화면 점수) 이상이면 말풍선이 그 각을 권한다. 서버 feed_service.py HERO_BUBBLE_MIN_SCORE 와 같은 값 */
|
||||||
|
const BUBBLE_MIN_SCORE = 65
|
||||||
|
|
||||||
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
|
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
|
||||||
const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night']
|
const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night']
|
||||||
const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
|
const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
|
||||||
@@ -220,15 +223,9 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
|
|||||||
}, [tmr, tmrKind, setPreview])
|
}, [tmr, tmrKind, setPreview])
|
||||||
const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? []
|
const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? []
|
||||||
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad
|
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad
|
||||||
// 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
|
// 지금은 지금이 든 3시간 칸(17시면 15시 칸. 서버가 그 칸에 지금 시각 예보를 넣어 준다). 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
|
||||||
// 지금은 가장 가까운 3시간 칸(17시면 18시 칸). 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
|
|
||||||
const slotOf = (k: TimeKind | 'now') => {
|
const slotOf = (k: TimeKind | 'now') => {
|
||||||
if (k === 'now') {
|
const h = k === 'now' ? t.h : PREVIEW[k].hour
|
||||||
const known = slots.filter((x) => x.temp_c != null)
|
|
||||||
const at = t.h + t.mi / 60
|
|
||||||
return known.length ? known.reduce((a, b) => (Math.abs(kst(b.at).h - at) < Math.abs(kst(a.at).h - at) ? b : a)) : undefined
|
|
||||||
}
|
|
||||||
const h = PREVIEW[k].hour
|
|
||||||
const s = slots.length ? slotAt(slots, h) : undefined
|
const s = slots.length ? slotAt(slots, h) : undefined
|
||||||
return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s)
|
return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s)
|
||||||
}
|
}
|
||||||
@@ -255,12 +252,12 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
|
|||||||
const tmrWhen = mode === 'now' ? '내일' : `내일 ${PREVIEW[mode].label}`
|
const tmrWhen = mode === 'now' ? '내일' : `내일 ${PREVIEW[mode].label}`
|
||||||
const bubble = tmr
|
const bubble = tmr
|
||||||
? top1
|
? top1
|
||||||
? top1.score >= 70
|
? top1.score >= BUBBLE_MIN_SCORE
|
||||||
? `${tmrWhen}은 ${top1.name}!`
|
? `${tmrWhen}은 ${top1.name}!`
|
||||||
: `${tmrWhen}은 쉬어 가요`
|
: `${tmrWhen}은 쉬어 가요`
|
||||||
: null
|
: null
|
||||||
: slotTop
|
: slotTop
|
||||||
? slotTop.score >= 70
|
? slotTop.score >= BUBBLE_MIN_SCORE
|
||||||
? `${when}은 ${slotTop.name}!`
|
? `${when}은 ${slotTop.name}!`
|
||||||
: `${when}은 쉬어 가요`
|
: `${when}은 쉬어 가요`
|
||||||
: hero
|
: hero
|
||||||
@@ -322,7 +319,8 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
|
|||||||
)}
|
)}
|
||||||
<div className="relative z-[3] flex items-center justify-between">
|
<div className="relative z-[3] flex items-center justify-between">
|
||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
<span className="b-strip grid grid-cols-2 rounded-full p-[3px]" role="radiogroup" aria-label="오늘 또는 내일 날씨">
|
{/* 좁은 화면에서 줄어드는 건 옆의 날짜만(두 줄로). 스위치까지 줄면 '내일' 글자가 세로로 꺾인다 */}
|
||||||
|
<span className="b-strip grid shrink-0 grid-cols-2 rounded-full p-[3px] whitespace-nowrap" role="radiogroup" aria-label="오늘 또는 내일 날씨">
|
||||||
{(
|
{(
|
||||||
[
|
[
|
||||||
[false, '오늘'],
|
[false, '오늘'],
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||||
|
import { useLocation, useNavigate } from 'react-router'
|
||||||
|
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||||
|
import { SITE_URL } from '../api/setup'
|
||||||
|
import { track } from '../lib/analytics'
|
||||||
|
import { EMBED_BG_LABEL, EMBED_HEIGHT, EMBED_KIND_LABEL, EMBED_MAX_HEIGHT, EMBED_MAX_WIDTH, EMBED_MIN_WIDTH, EMBED_RATIO, embedCode, embedScript, embedSrc, type EmbedBg, type EmbedKind } from '../lib/embedWidget'
|
||||||
|
import { IS_TOSS } from '../lib/platform'
|
||||||
|
import { cx } from '../lib/utils'
|
||||||
|
import { ownPage, useRegion } from './regionContext'
|
||||||
|
import { useSheet } from './sheetContext'
|
||||||
|
import { TAP44 } from './ui'
|
||||||
|
|
||||||
|
type Method = 'script' | 'iframe'
|
||||||
|
const KINDS: EmbedKind[] = ['side', 'home']
|
||||||
|
const BGS: EmbedBg[] = ['sky', 'light', 'dark']
|
||||||
|
const METHODS: Method[] = ['script', 'iframe']
|
||||||
|
const METHOD_LABEL: Record<Method, string> = { script: '스크립트(권장)', iframe: 'iframe 코드' }
|
||||||
|
/** 배경 칩 글자는 짧게. 읽어 주는 이름은 EMBED_BG_LABEL 의 전체 이름 */
|
||||||
|
const BG_CHIP: Record<EmbedBg, string> = { sky: '기본형', light: '밝은', dark: '어두운' }
|
||||||
|
const STAGE_NOTE: Record<EmbedBg, string> = { sky: '', light: ' · 밝은 바탕', dark: ' · 어두운 바탕' }
|
||||||
|
const CHIP = 'min-w-0 flex-1 cursor-pointer rounded-[14px] border-[1.5px] px-1.5 py-2.5 text-center text-[13.5px] font-extrabold'
|
||||||
|
const CHIP_ON = 'border-(--ink) bg-(--ink) text-white'
|
||||||
|
const CHIP_OFF = 'border-(--line) bg-white text-(--ink)'
|
||||||
|
// 붙이는 방법 탭: 고르는 값(칩)과 달리 코드 상자 머리에 붙은 밑줄 탭
|
||||||
|
const TAB = "relative min-h-11 cursor-pointer px-3 text-[13.5px] after:absolute after:inset-x-3 after:bottom-0 after:h-[2.5px] after:rounded-full after:content-['']"
|
||||||
|
const TAB_ON = 'font-extrabold text-white after:bg-(--orange)'
|
||||||
|
const TAB_OFF = 'font-bold text-[#8f98c0] after:bg-transparent'
|
||||||
|
|
||||||
|
/** 다른 사이트에 날씨 카드(위젯)를 붙이는 방법 (/widget-guide). 미리보기를 맨 위에 두고, 고르면 미리보기와 코드가 같이 바뀐다 */
|
||||||
|
export function WidgetPage() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
|
||||||
|
const { state } = useLocation()
|
||||||
|
// 문의 창의 '날씨 위젯 달기'로 왔는지. 들어올 때 한 번만 본다
|
||||||
|
const [from] = useState<'contact' | 'direct'>(() => ((state as { from?: string } | null)?.from === 'contact' ? 'contact' : 'direct'))
|
||||||
|
// 지역은 이 페이지만의 값: 여기서 고르기 전까지는 앱 지역(처음 온 사람의 자동 위치 맞춤 포함)을 따라가고,
|
||||||
|
// 고르기만 하는 지역 창으로 한 번 고른 뒤에는 앱 지역이 바뀌어도 따라가지 않는다. 앱 지역은 바꾸지 않는다
|
||||||
|
const { region: appRegion } = useRegion()
|
||||||
|
const [picked, setPicked] = useState<RegionData | null>(null)
|
||||||
|
const region = picked ?? appRegion
|
||||||
|
const { open } = useSheet()
|
||||||
|
const [kind, setKind] = useState<EmbedKind>('side')
|
||||||
|
const [bg, setBg] = useState<EmbedBg>('sky')
|
||||||
|
const [method, setMethod] = useState<Method>('script')
|
||||||
|
const [copy, setCopy] = useState<'idle' | 'done' | 'failed'>('idle')
|
||||||
|
// 복사에 성공한 횟수: '복사했어요'에서 다시 눌러도 2초를 새로 세고 화면 낭독기가 다시 알리게
|
||||||
|
const [copies, setCopies] = useState(0)
|
||||||
|
const codeRef = useRef<HTMLPreElement>(null)
|
||||||
|
// 복사한 코드와 화면의 코드가 같게 둘 다 여기서 나온다
|
||||||
|
const codeFor = { origin: SITE_URL, region: region.code, regionName: region.short_name, kind, bg }
|
||||||
|
const code = method === 'script' ? embedScript({ ...codeFor, regionPath: ownPage(region.code)?.path ?? null }) : embedCode(codeFor)
|
||||||
|
// 미리보기는 지금 연 사이트의 카드 (도커·개발 서버에서도 보이게)
|
||||||
|
const src = embedSrc(window.location.origin, region.code, kind, bg)
|
||||||
|
|
||||||
|
useEffect(() => track('widget_guide_view', { from }), [from])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (copy !== 'done') return
|
||||||
|
const id = setTimeout(() => setCopy('idle'), 2000)
|
||||||
|
return () => clearTimeout(id)
|
||||||
|
}, [copy, copies])
|
||||||
|
|
||||||
|
// 코드가 바뀌면 지난 복사 결과('복사했어요'·직접 복사 안내)를 지운다. 앱 지역을 따라 지역이 바뀔 때도
|
||||||
|
const [shownRegion, setShownRegion] = useState(region.code)
|
||||||
|
if (region.code !== shownRegion) {
|
||||||
|
setShownRegion(region.code)
|
||||||
|
setCopy('idle')
|
||||||
|
}
|
||||||
|
// 같은 지역을 골라도 이제부터는 앱 지역을 따라가지 않는다
|
||||||
|
const pickRegion = (r: RegionData) => {
|
||||||
|
setPicked(r)
|
||||||
|
if (r.code === region.code) return
|
||||||
|
track('widget_option_select', { option: 'region', value: r.code })
|
||||||
|
}
|
||||||
|
const pickKind = (k: EmbedKind) => {
|
||||||
|
if (k === kind) return
|
||||||
|
setKind(k)
|
||||||
|
setCopy('idle')
|
||||||
|
track('widget_option_select', { option: 'kind', value: k })
|
||||||
|
}
|
||||||
|
const pickBg = (b: EmbedBg) => {
|
||||||
|
if (b === bg) return
|
||||||
|
setBg(b)
|
||||||
|
setCopy('idle')
|
||||||
|
track('widget_option_select', { option: 'bg', value: b })
|
||||||
|
}
|
||||||
|
const pickMethod = (m: Method) => {
|
||||||
|
if (m === method) return
|
||||||
|
setMethod(m)
|
||||||
|
setCopy('idle')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 클립보드를 못 쓰면 코드 글자를 전부 선택해 두고 직접 복사하게 한다 */
|
||||||
|
const selectCode = () => {
|
||||||
|
const box = codeRef.current
|
||||||
|
const sel = window.getSelection()
|
||||||
|
if (!box || !sel) return
|
||||||
|
const range = document.createRange()
|
||||||
|
range.selectNodeContents(box)
|
||||||
|
sel.removeAllRanges()
|
||||||
|
sel.addRange(range)
|
||||||
|
}
|
||||||
|
const copyCode = async () => {
|
||||||
|
try {
|
||||||
|
if (!navigator.clipboard) throw new Error('클립보드를 쓸 수 없는 브라우저')
|
||||||
|
await navigator.clipboard.writeText(code)
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[widget] 코드를 복사하지 못함', e)
|
||||||
|
selectCode()
|
||||||
|
setCopy('failed')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setCopy('done')
|
||||||
|
setCopies((n) => n + 1)
|
||||||
|
track('widget_code_copy', { kind, bg, region: region.code, method })
|
||||||
|
}
|
||||||
|
|
||||||
|
const notes = [
|
||||||
|
`놓은 자리 폭에 맞춰 자동으로 늘고 줄어요. (${EMBED_MIN_WIDTH[kind]}~${EMBED_MAX_WIDTH[kind]}px)`,
|
||||||
|
`높이는 폭에 맞춰 ${EMBED_HEIGHT[kind]}~${EMBED_MAX_HEIGHT[kind]}px 사이에서 자동으로 바뀌어요.`,
|
||||||
|
...(method === 'iframe' ? ['코드의 style은 지우지 말아 주세요.'] : []),
|
||||||
|
'무료이고 신청 없이 쓸 수 있어요. 날씨각 링크는 그대로 두어 주세요.',
|
||||||
|
'예고 없이 바뀌거나 중단될 수 있어요.',
|
||||||
|
'카드가 안 보이면 사이트 보안 설정에서 weather.o2o.kr 을 허용해 주세요.',
|
||||||
|
]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pb-8">
|
||||||
|
<div className="flex items-center gap-1 px-3 pt-1">
|
||||||
|
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
|
||||||
|
‹
|
||||||
|
</button>
|
||||||
|
<h2 className="m-0 px-1 font-batang text-[20px] font-bold">날씨 위젯</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-[18px]">
|
||||||
|
<p className="mt-1.5 mb-0 font-bold text-(--ink2)">내 사이트에 오늘 날씨 카드를 달아 보세요.</p>
|
||||||
|
|
||||||
|
{IS_TOSS ? (
|
||||||
|
// 토스 미니앱에서 주소로 열었을 때: 미리보기 대신 웹 주소 안내 (고르기·코드는 SITE_URL 기준이라 그대로 둔다)
|
||||||
|
<p className="mt-3 mb-0 rounded-[18px] border border-dashed border-[#c5d2e4] bg-white p-3.5 text-[13.5px] leading-[1.6] font-bold text-(--ink2)">
|
||||||
|
날씨 위젯은 웹에서 만들 수 있어요.{' '}
|
||||||
|
<a href={`${SITE_URL}/widget-guide`} target="_blank" rel="noopener" className="text-(--ink) underline">
|
||||||
|
weather.o2o.kr/widget-guide
|
||||||
|
</a>{' '}
|
||||||
|
에서 열어 주세요.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
// b-day: 밤 화면에서도 미리보기 바탕은 고른 배경 그대로 (흰색·어두운 색)
|
||||||
|
<div className={cx('b-day mt-3 rounded-[18px] p-3.5', bg === 'dark' ? 'bg-[#111318]' : 'border border-dashed border-[#c5d2e4] bg-white')}>
|
||||||
|
<p className={cx('m-0 mb-2 text-[12.5px] font-bold', bg === 'dark' ? 'text-[#aab0c4]' : 'text-(--ink3)')}>이렇게 보여요{STAGE_NOTE[bg]}</p>
|
||||||
|
<iframe key={src} src={src} title="미리보기" className="mx-auto block w-full border-0" style={{ maxWidth: EMBED_MAX_WIDTH[kind], aspectRatio: EMBED_RATIO[kind], minHeight: EMBED_HEIGHT[kind], maxHeight: EMBED_MAX_HEIGHT[kind], borderRadius: 28 }} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="mt-3 flex flex-col gap-2.5">
|
||||||
|
<Row label="지역">
|
||||||
|
<button type="button" onClick={() => open({ type: 'region', pick: { current: region.code, onPick: pickRegion } })} aria-label={`지역 바꾸기, 지금 ${region.name}`} className="flex w-full cursor-pointer items-center justify-between gap-2 rounded-[14px] border-[1.5px] border-(--line) bg-white px-3.5 py-2.5 text-left font-extrabold text-(--ink)">
|
||||||
|
<span className="min-w-0 truncate">{region.name}</span>
|
||||||
|
<span className="shrink-0 text-[13px] text-(--ink2)">바꾸기 ›</span>
|
||||||
|
</button>
|
||||||
|
</Row>
|
||||||
|
<Row label="모양">
|
||||||
|
<div role="group" aria-label="모양" className="flex gap-2">
|
||||||
|
{KINDS.map((k) => (
|
||||||
|
<button key={k} type="button" aria-pressed={k === kind} onClick={() => pickKind(k)} className={cx(CHIP, k === kind ? CHIP_ON : CHIP_OFF)}>
|
||||||
|
{EMBED_KIND_LABEL[k]}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
<Row label="배경">
|
||||||
|
<div role="group" aria-label="배경" className="flex gap-2">
|
||||||
|
{BGS.map((b) => (
|
||||||
|
<button key={b} type="button" aria-pressed={b === bg} aria-label={EMBED_BG_LABEL[b]} onClick={() => pickBg(b)} className={cx(CHIP, b === bg ? CHIP_ON : CHIP_OFF)}>
|
||||||
|
{BG_CHIP[b]}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 탭 → 코드 → 복사 버튼: 탭은 코드 상자 머리에 붙여 한 덩어리로 보이게 */}
|
||||||
|
<div className="mt-4 overflow-hidden rounded-[14px] bg-[#1d2440]">
|
||||||
|
<div role="tablist" aria-label="붙이는 방법" className="flex border-b border-white/10 px-1">
|
||||||
|
{METHODS.map((m) => (
|
||||||
|
<button key={m} type="button" role="tab" aria-selected={m === method} onClick={() => pickMethod(m)} className={cx(TAB, m === method ? TAB_ON : TAB_OFF)}>
|
||||||
|
{METHOD_LABEL[m]}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{method === 'iframe' && <p className="m-0 px-3 pt-2.5 text-[12.5px] font-bold text-[#aab3d9]">스크립트를 넣을 수 없는 곳이라면 이 코드를 쓰세요.</p>}
|
||||||
|
{/* 앱은 글자 선택을 막아 두어(body user-select: none) 이 상자만 선택·길게 눌러 복사할 수 있게 연다 */}
|
||||||
|
<pre ref={codeRef} className="m-0 p-3 font-mono text-[12px] leading-[1.55] break-all whitespace-pre-wrap text-[#e8ecff] select-text [-webkit-touch-callout:default]">
|
||||||
|
{code}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="button" onClick={copyCode} className="mt-2.5 block w-full cursor-pointer rounded-[14px] bg-(--orange) py-3.5 text-center text-[15.5px] font-extrabold text-white">
|
||||||
|
{copy === 'done' ? '복사했어요' : '코드 복사'}
|
||||||
|
</button>
|
||||||
|
<div aria-live="polite">
|
||||||
|
{copy === 'done' && (
|
||||||
|
<span key={copies} className="sr-only">
|
||||||
|
복사했어요
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{copy === 'failed' && <p className="mt-2 mb-0 text-center text-[13px] font-bold text-(--ink2)">코드를 길게 눌러 복사해 주세요</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ul className="mt-3 mb-0 flex list-none flex-col gap-1 p-0 text-[12.5px] font-semibold text-(--ink3)">
|
||||||
|
{notes.map((n) => (
|
||||||
|
<li key={n} className="before:content-['·_']">
|
||||||
|
{n}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 고르는 줄: 왼쪽에 이름, 오른쪽에 고르는 것 */
|
||||||
|
function Row({ label, children }: { label: string; children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2.5">
|
||||||
|
<span className="w-9 shrink-0 text-[13px] font-bold text-(--ink2)">{label}</span>
|
||||||
|
<div className="min-w-0 flex-1">{children}</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -120,6 +120,22 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 지역 버튼 아래 말풍선: 버튼 쪽(꼬리 자리)에서 톡 튀어나오듯 나타난다. 사라질 땐 opacity 전환(BLayout HINT_FADE) */
|
||||||
|
.b-hint {
|
||||||
|
transform-origin: calc(100% - 34px) 0;
|
||||||
|
animation: b-hint-in 0.4s cubic-bezier(0.2, 0.9, 0.3, 1.2) 0.3s backwards;
|
||||||
|
}
|
||||||
|
@keyframes b-hint-in {
|
||||||
|
0% {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-6px) scale(0.85);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* 아래 창은 불투명한 채로 화면 아래에서 끝까지 올라오고, 닫힐 땐 다시 내려간다 (반투명으로 올라오면 뒤 탭 바가 비쳐 깜빡여 보였다) */
|
/* 아래 창은 불투명한 채로 화면 아래에서 끝까지 올라오고, 닫힐 땐 다시 내려간다 (반투명으로 올라오면 뒤 탭 바가 비쳐 깜빡여 보였다) */
|
||||||
.b-sheet {
|
.b-sheet {
|
||||||
animation: b-up 0.28s cubic-bezier(0.2, 0.9, 0.3, 1);
|
animation: b-up 0.28s cubic-bezier(0.2, 0.9, 0.3, 1);
|
||||||
@@ -174,6 +190,7 @@
|
|||||||
.b-fall,
|
.b-fall,
|
||||||
.b-heart-pop,
|
.b-heart-pop,
|
||||||
.b-like-bit,
|
.b-like-bit,
|
||||||
|
.b-hint,
|
||||||
.b-sheet,
|
.b-sheet,
|
||||||
.b-sheet-dialog[open]::backdrop {
|
.b-sheet-dialog[open]::backdrop {
|
||||||
animation: none !important;
|
animation: none !important;
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
|
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||||
import type { MyGak } from './myGakState'
|
import type { MyGak } from './myGakState'
|
||||||
import type { WeatherWhyPayload } from './weatherWhy'
|
import type { WeatherWhyPayload } from './weatherWhy'
|
||||||
import { createContext, use } from 'react'
|
import { createContext, use } from 'react'
|
||||||
/** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides). url: 같이 보낼 링크 (없으면 사이트 주소) */
|
/** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides). url: 같이 보낼 링크 (없으면 사이트 주소) */
|
||||||
export type SharePayload = { title: string; slides: HTMLElement[]; square?: HTMLElement[]; url?: string }
|
export type SharePayload = { title: string; slides: HTMLElement[]; square?: HTMLElement[]; url?: string }
|
||||||
|
|
||||||
|
/** 지역 창 '고르기만' 모드: current 는 '지금 보는 곳'으로 표시할 지역 코드 */
|
||||||
|
export type RegionPick = { current: string; onPick: (r: RegionData) => void }
|
||||||
|
|
||||||
/** 댓글이 달린 곳: 운영 포스트 또는 사람 글 */
|
/** 댓글이 달린 곳: 운영 포스트 또는 사람 글 */
|
||||||
export type CommentTarget = { postId: number } | { talkId: number }
|
export type CommentTarget = { postId: number } | { talkId: number }
|
||||||
type CommentsState = { type: 'comments'; draft?: string } & CommentTarget
|
type CommentsState = { type: 'comments'; draft?: string } & CommentTarget
|
||||||
@@ -16,7 +20,8 @@ export type SheetState =
|
|||||||
| { type: 'seasonWeek' }
|
| { type: 'seasonWeek' }
|
||||||
| { type: 'login'; then?: CommentsState; why?: 'level' }
|
| { type: 'login'; then?: CommentsState; why?: 'level' }
|
||||||
| { type: 'me' }
|
| { type: 'me' }
|
||||||
| { type: 'region' }
|
/** pick: 앱 지역은 그대로 두고 고른 지역만 돌려받는 '고르기만' 모드 (위젯 페이지 미리보기). 창 상태는 방문 기록에 저장하지 않아 함수를 넣어도 된다 */
|
||||||
|
| { type: 'region'; pick?: RegionPick }
|
||||||
| { type: 'mix'; shared?: MyGak }
|
| { type: 'mix'; shared?: MyGak }
|
||||||
| { type: 'myGak'; gak: MyGak; shot?: HTMLElement | null }
|
| { type: 'myGak'; gak: MyGak; shot?: HTMLElement | null }
|
||||||
| { type: 'install' }
|
| { type: 'install' }
|
||||||
|
|||||||
@@ -53,6 +53,14 @@ export function PinIcon({ className }: P) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function ChevronDownIcon({ className }: P) {
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 24 24" {...line} strokeWidth="3" className={className} aria-hidden="true">
|
||||||
|
<path d="M6 9.5l6 6 6-6" />
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' | 'talk' }) {
|
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' | 'talk' }) {
|
||||||
return (
|
return (
|
||||||
<svg viewBox="0 0 24 24" {...line} className={className} aria-hidden="true">
|
<svg viewBox="0 0 24 24" {...line} className={className} aria-hidden="true">
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { IS_TOSS } from '../lib/platform'
|
import { IS_TOSS } from '../lib/platform'
|
||||||
import { Ic } from './ui'
|
import { Ic } from './ui'
|
||||||
import { track } from '../lib/analytics'
|
import { track } from '../lib/analytics'
|
||||||
@@ -19,11 +18,13 @@ function seen() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 토스판을 처음 열면 서비스 소개를 먼저 보여 준다 (앱인토스 검수: 로그인 전에 서비스 설명) */
|
/** 토스판을 처음 열어 소개 화면을 보여 줘야 하는지 */
|
||||||
export function TossIntro() {
|
export function tossIntroPending() {
|
||||||
const [open, setOpen] = useState(() => IS_TOSS && !seen())
|
return IS_TOSS && !seen()
|
||||||
if (!open) return null
|
}
|
||||||
|
|
||||||
|
/** 토스판을 처음 열면 서비스 소개를 먼저 보여 준다 (앱인토스 검수: 로그인 전에 서비스 설명). 띄울지는 부르는 쪽이 tossIntroPending 으로 정한다 */
|
||||||
|
export function TossIntro({ onStart }: { onStart: () => void }) {
|
||||||
const start = () => {
|
const start = () => {
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(KEY, '1')
|
localStorage.setItem(KEY, '1')
|
||||||
@@ -31,7 +32,7 @@ export function TossIntro() {
|
|||||||
console.warn('[intro] 본 기록을 저장하지 못함', e)
|
console.warn('[intro] 본 기록을 저장하지 못함', e)
|
||||||
}
|
}
|
||||||
track('toss_intro_start', {})
|
track('toss_intro_start', {})
|
||||||
setOpen(false)
|
onStart()
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/** 다른 사이트가 iframe 으로 붙이는 날씨 카드의 주소와 붙이는 코드(스크립트·iframe)를 만든다. 브라우저 API 를 쓰지 않아 테스트(node --test)에서도 돈다 */
|
||||||
|
export type EmbedKind = 'side' | 'home'
|
||||||
|
export type EmbedBg = 'sky' | 'light' | 'dark'
|
||||||
|
|
||||||
|
// 화면에 보이는 이름. 주소의 값(side·home, sky·light·dark)은 이미 붙인 코드가 깨지지 않게 그대로 둔다
|
||||||
|
export const EMBED_KIND_LABEL: Record<EmbedKind, string> = { side: '기본형', home: '상세형' }
|
||||||
|
export const EMBED_BG_LABEL: Record<EmbedBg, string> = { sky: '기본형 배경', light: '밝은 바탕용', dark: '어두운 바탕용' }
|
||||||
|
|
||||||
|
// 기본 높이(px): 카드가 넘치거나 스크롤이 생기지 않고 전부 보이는 최소 높이
|
||||||
|
export const EMBED_HEIGHT: Record<EmbedKind, number> = { side: 245, home: 400 }
|
||||||
|
// 최대 높이(px): 붙인 사이트가 높이를 늘려도 카드가 휑해 보이지 않는 데까지
|
||||||
|
export const EMBED_MAX_HEIGHT: Record<EmbedKind, number> = { side: 320, home: 520 }
|
||||||
|
// 최소 폭(px): 이름이 가장 긴 지역 '창원시 마산합포구'로도 제목·버튼이 다 보이는 폭
|
||||||
|
export const EMBED_MIN_WIDTH: Record<EmbedKind, number> = { side: 220, home: 280 }
|
||||||
|
// 최대 폭(px): 이보다 넓으면 카드가 늘어나 보기 나쁘다
|
||||||
|
export const EMBED_MAX_WIDTH: Record<EmbedKind, number> = { side: 440, home: 720 }
|
||||||
|
// 폭:높이 비율 = 최대 폭 ÷ 최대 높이: 높이가 폭에 맞춰 기본 높이~최대 높이 사이에서 바뀌고 최대 폭에서 최대 높이가 된다
|
||||||
|
export const EMBED_RATIO: Record<EmbedKind, string> = { side: '11/8', home: '18/13' }
|
||||||
|
|
||||||
|
/** iframe 의 style. 크기 범위를 모두 코드에 넣어 붙인 사이트의 다른 스타일에 밀리지 않게 한다.
|
||||||
|
* 높이는 aspect-ratio 로 폭을 따르고 min-height·max-height 안에 머문다. aspect-ratio 를 모르는 옛 브라우저는 min-height(기본 높이)로 보인다.
|
||||||
|
* border-radius 는 붙인 사이트가 color-scheme: dark 일 때 카드의 둥근 모서리 밖이 희게 칠해지는 것을 잘라 낸다 (두 모양 모두 28px 모서리).
|
||||||
|
* public/embed/widget.js 도 같은 값을 쓴다 (tests/embedLoader.test.mjs 가 둘이 같은지 본다) */
|
||||||
|
function embedStyle(kind: EmbedKind): string {
|
||||||
|
return `border:0;width:100%;height:auto;aspect-ratio:${EMBED_RATIO[kind]};min-width:${EMBED_MIN_WIDTH[kind]}px;max-width:${EMBED_MAX_WIDTH[kind]}px;min-height:${EMBED_HEIGHT[kind]}px;max-height:${EMBED_MAX_HEIGHT[kind]}px;border-radius:28px`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** HTML 속성 값 안에 넣어도 속성이 깨지지 않게 바꾼다 */
|
||||||
|
function escapeAttr(text: string): string {
|
||||||
|
return text.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 카드 화면 주소. region 은 지역 코드(숫자 10자리) */
|
||||||
|
export function embedSrc(origin: string, region: string, kind: EmbedKind, bg: EmbedBg): string {
|
||||||
|
return `${origin}/embed/card?region=${encodeURIComponent(region)}&type=${kind}&bg=${bg}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 다른 사이트에 붙여 넣을 iframe 코드 */
|
||||||
|
export function embedCode(p: { origin: string; region: string; regionName: string; kind: EmbedKind; bg: EmbedBg }): string {
|
||||||
|
const src = embedSrc(p.origin, p.region, p.kind, p.bg)
|
||||||
|
const title = escapeAttr(`${p.regionName} 날씨 - 날씨각`)
|
||||||
|
return `<iframe src="${src}" title="${title}" width="100%" height="${EMBED_HEIGHT[p.kind]}" style="${embedStyle(p.kind)}" loading="lazy" referrerpolicy="origin"></iframe>`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 다른 사이트에 붙여 넣을 스크립트 코드: 날씨각 링크 + widget.js. widget.js 가 링크 자리에 embedCode 와 같은 iframe 을 넣고,
|
||||||
|
* 스크립트가 막히거나 날씨각에 접속이 안 되면 링크가 그대로 남는다. regionPath 는 지역 페이지 주소 이름(없으면 링크는 날씨각 홈) */
|
||||||
|
export function embedScript(p: { origin: string; region: string; regionName: string; regionPath: string | null; kind: EmbedKind; bg: EmbedBg }): string {
|
||||||
|
const href = `${p.origin}${p.regionPath ? `/today/${p.regionPath}` : '/'}?utm_source=widget&utm_medium=embed&utm_campaign=fallback`
|
||||||
|
const text = escapeAttr(`${p.regionName} 날씨 - 날씨각`)
|
||||||
|
return (
|
||||||
|
`<a class="nalssigak-weather" href="${href}"\n` +
|
||||||
|
` data-region="${escapeAttr(p.region)}" data-type="${p.kind}" data-bg="${p.bg}">${text}</a>\n` +
|
||||||
|
`<script src="${p.origin}/embed/widget.js" async></script>`
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
// 다른 사이트에 붙이는 스크립트(public/embed/widget.js) 검증: 가짜 문서에서 돌려 링크 자리에 생긴 iframe 이
|
||||||
|
// embedCode 가 만드는 iframe 과 같은지 본다 (크기 상수가 두 파일에서 어긋나지 않게 묶는다). 실행: frontend 폴더에서 npm test
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import vm from 'node:vm'
|
||||||
|
import { embedCode } from '../src/lib/embedWidget.ts'
|
||||||
|
|
||||||
|
const SOURCE = readFileSync(new URL('../public/embed/widget.js', import.meta.url), 'utf8')
|
||||||
|
const SCRIPT_SRC = 'http://localhost:8080/embed/widget.js'
|
||||||
|
const ORIGIN = 'http://localhost:8080'
|
||||||
|
|
||||||
|
/** 가짜 요소: 속성·글자·부모만 */
|
||||||
|
function node(tag, attrs = {}, text = '') {
|
||||||
|
return {
|
||||||
|
tagName: tag.toUpperCase(),
|
||||||
|
attrs: { ...attrs },
|
||||||
|
textContent: text,
|
||||||
|
parentNode: null,
|
||||||
|
getAttribute(name) {
|
||||||
|
return Object.hasOwn(this.attrs, name) ? this.attrs[name] : null
|
||||||
|
},
|
||||||
|
setAttribute(name, value) {
|
||||||
|
this.attrs[name] = String(value)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 날씨각 링크 */
|
||||||
|
function link(attrs, text = '군산시 날씨 - 날씨각') {
|
||||||
|
return node('a', { class: 'nalssigak-weather', href: 'https://weather.o2o.kr/today/jeonbuk/gunsan', ...attrs }, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// widget.js 가 쓰는 선택자만 안다
|
||||||
|
const SELECTORS = {
|
||||||
|
'a.nalssigak-weather[data-region]': (n) => n.tagName === 'A' && (n.attrs.class ?? '').split(/\s+/).includes('nalssigak-weather') && Object.hasOwn(n.attrs, 'data-region'),
|
||||||
|
'script[src*="/embed/widget.js"]': (n) => n.tagName === 'SCRIPT' && (n.attrs.src ?? '').includes('/embed/widget.js'),
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 가짜 문서: body 아래에 링크들과 스크립트 태그가 나란히 있다 */
|
||||||
|
function fakeDoc(links, { scriptSrc = SCRIPT_SRC, current = true, readyState = 'complete' } = {}) {
|
||||||
|
const listeners = {}
|
||||||
|
const body = {
|
||||||
|
children: [],
|
||||||
|
replaceChild(next, old) {
|
||||||
|
const i = this.children.indexOf(old)
|
||||||
|
if (i < 0) throw new Error('없는 자식을 바꾸려 함')
|
||||||
|
this.children[i] = next
|
||||||
|
next.parentNode = this
|
||||||
|
old.parentNode = null
|
||||||
|
return old
|
||||||
|
},
|
||||||
|
}
|
||||||
|
const script = node('script', { src: scriptSrc, async: '' })
|
||||||
|
script.src = scriptSrc // 브라우저는 src 속성(프로퍼티)에 절대 주소를 준다
|
||||||
|
for (const n of [...links, script]) {
|
||||||
|
n.parentNode = body
|
||||||
|
body.children.push(n)
|
||||||
|
}
|
||||||
|
const doc = {
|
||||||
|
readyState,
|
||||||
|
currentScript: current ? script : null,
|
||||||
|
createElement: (tag) => node(tag),
|
||||||
|
querySelectorAll(sel) {
|
||||||
|
const match = SELECTORS[sel]
|
||||||
|
if (!match) throw new Error(`모르는 선택자 ${sel}`)
|
||||||
|
return body.children.filter(match)
|
||||||
|
},
|
||||||
|
addEventListener(type, fn) {
|
||||||
|
;(listeners[type] ??= []).push(fn)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
doc,
|
||||||
|
body,
|
||||||
|
fire: (type) => (listeners[type] ?? []).forEach((fn) => fn()),
|
||||||
|
frames: () => body.children.filter((n) => n.tagName === 'IFRAME'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 브라우저처럼 문서만 주고 widget.js 를 돌린다 (console·window 없음: 쓰면 오류로 드러난다) */
|
||||||
|
function run(doc) {
|
||||||
|
vm.runInNewContext(SOURCE, { document: doc })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** embedCode 문자열의 iframe 속성 (HTML 이스케이프를 푼 값) */
|
||||||
|
function attrsOf(html) {
|
||||||
|
const out = {}
|
||||||
|
for (const [, name, value] of html.matchAll(/([a-z]+)="([^"]*)"/g)) {
|
||||||
|
out[name] = value.replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&')
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
test('올바른 링크 → 그 자리에 iframe 하나, 속성은 embedCode 와 같다', () => {
|
||||||
|
for (const kind of ['side', 'home']) {
|
||||||
|
for (const bg of ['sky', 'light', 'dark']) {
|
||||||
|
const a = link({ 'data-region': '5213000000', 'data-type': kind, 'data-bg': bg })
|
||||||
|
const page = fakeDoc([a])
|
||||||
|
run(page.doc)
|
||||||
|
assert.equal(page.frames().length, 1)
|
||||||
|
assert.equal(page.body.children[0], page.frames()[0], '링크가 있던 자리')
|
||||||
|
assert.equal(a.parentNode, null, '링크는 빠진다')
|
||||||
|
assert.deepEqual(page.frames()[0].attrs, attrsOf(embedCode({ origin: ORIGIN, region: '5213000000', regionName: '군산시', kind, bg })))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('iframe 제목은 링크 글자 (특수문자도 그대로)', () => {
|
||||||
|
const page = fakeDoc([link({ 'data-region': '5213000000' }, 'A&B<C>"D 날씨 - 날씨각')])
|
||||||
|
run(page.doc)
|
||||||
|
assert.deepEqual(page.frames()[0].attrs, attrsOf(embedCode({ origin: ORIGIN, region: '5213000000', regionName: 'A&B<C>"D', kind: 'side', bg: 'sky' })))
|
||||||
|
})
|
||||||
|
|
||||||
|
test('data-type·data-bg 를 빼면 기본형(side)·기본형 배경(sky)', () => {
|
||||||
|
const page = fakeDoc([link({ 'data-region': '5213000000' })])
|
||||||
|
run(page.doc)
|
||||||
|
assert.equal(page.frames()[0].attrs.src, `${ORIGIN}/embed/card?region=5213000000&type=side&bg=sky`)
|
||||||
|
assert.equal(page.frames()[0].attrs.height, '245')
|
||||||
|
assert.equal(page.frames()[0].attrs.style, 'border:0;width:100%;height:auto;aspect-ratio:11/8;min-width:220px;max-width:440px;min-height:245px;max-height:320px;border-radius:28px')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('틀린 지역·모양·배경의 링크는 그대로 둔다', () => {
|
||||||
|
const bad = [
|
||||||
|
link({ 'data-region': '521300000' }),
|
||||||
|
link({ 'data-region': '52130000001' }),
|
||||||
|
link({ 'data-region': '52130000ab' }),
|
||||||
|
link({ 'data-region': '5213000000', 'data-type': 'wide' }),
|
||||||
|
link({ 'data-region': '5213000000', 'data-bg': 'red' }),
|
||||||
|
]
|
||||||
|
const page = fakeDoc(bad)
|
||||||
|
run(page.doc)
|
||||||
|
assert.equal(page.frames().length, 0)
|
||||||
|
assert.deepEqual(page.body.children.slice(0, bad.length), bad)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('두 번 실행해도 iframe 은 하나', () => {
|
||||||
|
const page = fakeDoc([link({ 'data-region': '5213000000' })])
|
||||||
|
run(page.doc)
|
||||||
|
run(page.doc)
|
||||||
|
assert.equal(page.frames().length, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('링크가 여러 개면 각각 생긴다', () => {
|
||||||
|
const page = fakeDoc([link({ 'data-region': '5213000000', 'data-type': 'home' }), link({ 'data-region': '1111000000', 'data-bg': 'dark' }, '종로구 날씨 - 날씨각')])
|
||||||
|
run(page.doc)
|
||||||
|
assert.deepEqual(
|
||||||
|
page.frames().map((f) => f.attrs.src),
|
||||||
|
[`${ORIGIN}/embed/card?region=5213000000&type=home&bg=sky`, `${ORIGIN}/embed/card?region=1111000000&type=side&bg=dark`],
|
||||||
|
)
|
||||||
|
assert.equal(page.frames()[1].attrs.title, '종로구 날씨 - 날씨각')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('날씨각 주소(origin)는 스크립트 주소에서 온다', () => {
|
||||||
|
const page = fakeDoc([link({ 'data-region': '5213000000' })], { scriptSrc: 'https://weather.o2o.kr/embed/widget.js' })
|
||||||
|
run(page.doc)
|
||||||
|
assert.equal(page.frames()[0].attrs.src, 'https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('currentScript 가 없으면 스크립트 태그를 찾아 주소를 얻는다', () => {
|
||||||
|
const page = fakeDoc([link({ 'data-region': '5213000000' })], { current: false })
|
||||||
|
run(page.doc)
|
||||||
|
assert.equal(page.frames()[0].attrs.src, `${ORIGIN}/embed/card?region=5213000000&type=side&bg=sky`)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('문서가 다 읽히기 전에 실행되면 다 읽힌 뒤에도 한 번 더 찾는다', () => {
|
||||||
|
const page = fakeDoc([], { readyState: 'loading' })
|
||||||
|
run(page.doc)
|
||||||
|
// 스크립트보다 아래에 있어 나중에 읽힌 링크
|
||||||
|
const late = link({ 'data-region': '5213000000' })
|
||||||
|
late.parentNode = page.body
|
||||||
|
page.body.children.push(late)
|
||||||
|
page.fire('DOMContentLoaded')
|
||||||
|
assert.equal(page.frames().length, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('옛 브라우저에서도 돌게 ES5 문법만 쓴다', () => {
|
||||||
|
const code = SOURCE.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')
|
||||||
|
assert.doesNotMatch(code, /=>|`|\b(?:let|const|class)\s/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
// 다른 사이트에 붙이는 날씨 카드의 iframe 주소·붙이는 코드 검증. 실행: frontend 폴더에서 npm test
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import { EMBED_HEIGHT, EMBED_MAX_HEIGHT, EMBED_MAX_WIDTH, EMBED_MIN_WIDTH, EMBED_RATIO, embedCode, embedScript, embedSrc } from '../src/lib/embedWidget.ts'
|
||||||
|
|
||||||
|
const ORIGIN = 'https://weather.o2o.kr'
|
||||||
|
|
||||||
|
test('iframe 주소', () => {
|
||||||
|
assert.equal(embedSrc(ORIGIN, '5213000000', 'side', 'sky'), 'https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('모양별 크기', () => {
|
||||||
|
assert.deepEqual(EMBED_HEIGHT, { side: 245, home: 400 })
|
||||||
|
assert.deepEqual(EMBED_MAX_HEIGHT, { side: 320, home: 520 })
|
||||||
|
assert.deepEqual(EMBED_MIN_WIDTH, { side: 220, home: 280 })
|
||||||
|
assert.deepEqual(EMBED_MAX_WIDTH, { side: 440, home: 720 })
|
||||||
|
assert.deepEqual(EMBED_RATIO, { side: '11/8', home: '18/13' })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('폭:높이 비율은 최대 폭 ÷ 최대 높이 (최대 폭에서 최대 높이가 되게)', () => {
|
||||||
|
for (const kind of ['side', 'home']) {
|
||||||
|
const [w, h] = EMBED_RATIO[kind].split('/').map(Number)
|
||||||
|
assert.equal(w * EMBED_MAX_HEIGHT[kind], h * EMBED_MAX_WIDTH[kind], kind)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('붙이는 코드(상세형): 배경·크기 범위·둥근 모서리·referrerpolicy 가 들어간다', () => {
|
||||||
|
assert.equal(
|
||||||
|
embedCode({ origin: ORIGIN, region: '5213000000', regionName: '군산시', kind: 'home', bg: 'dark' }),
|
||||||
|
'<iframe src="https://weather.o2o.kr/embed/card?region=5213000000&type=home&bg=dark" title="군산시 날씨 - 날씨각" width="100%" height="400" style="border:0;width:100%;height:auto;aspect-ratio:18/13;min-width:280px;max-width:720px;min-height:400px;max-height:520px;border-radius:28px" loading="lazy" referrerpolicy="origin"></iframe>',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('붙이는 코드(기본형): 크기 범위·둥근 모서리', () => {
|
||||||
|
assert.equal(
|
||||||
|
embedCode({ origin: ORIGIN, region: '5213000000', regionName: '군산시', kind: 'side', bg: 'sky' }),
|
||||||
|
'<iframe src="https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky" title="군산시 날씨 - 날씨각" width="100%" height="245" style="border:0;width:100%;height:auto;aspect-ratio:11/8;min-width:220px;max-width:440px;min-height:245px;max-height:320px;border-radius:28px" loading="lazy" referrerpolicy="origin"></iframe>',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('붙이는 코드: 지역 이름의 따옴표가 속성을 깨지 않는다', () => {
|
||||||
|
assert.ok(embedCode({ origin: ORIGIN, region: '5213000000', regionName: '가"짜', kind: 'side', bg: 'sky' }).includes('title="가"짜 날씨 - 날씨각"'))
|
||||||
|
})
|
||||||
|
|
||||||
|
test('붙이는 코드: 지역 이름의 & < > 도 이스케이프한다', () => {
|
||||||
|
assert.ok(embedCode({ origin: ORIGIN, region: '5213000000', regionName: 'A&B<C>', kind: 'side', bg: 'sky' }).includes('title="A&B<C> 날씨 - 날씨각"'))
|
||||||
|
})
|
||||||
|
|
||||||
|
test('붙이는 코드: 지역 코드는 주소에 맞게 인코딩한다', () => {
|
||||||
|
assert.ok(embedCode({ origin: ORIGIN, region: '52 13&x=1', kind: 'side', bg: 'sky', regionName: '군산시' }).includes('src="https://weather.o2o.kr/embed/card?region=52%2013%26x%3D1&type=side&bg=sky"'))
|
||||||
|
})
|
||||||
|
|
||||||
|
test('스크립트 코드: 지역 페이지 링크 + 스크립트', () => {
|
||||||
|
assert.equal(
|
||||||
|
embedScript({ origin: ORIGIN, region: '5213000000', regionName: '군산시', regionPath: 'jeonbuk/gunsan', kind: 'side', bg: 'sky' }),
|
||||||
|
'<a class="nalssigak-weather" href="https://weather.o2o.kr/today/jeonbuk/gunsan?utm_source=widget&utm_medium=embed&utm_campaign=fallback"\n' +
|
||||||
|
' data-region="5213000000" data-type="side" data-bg="sky">군산시 날씨 - 날씨각</a>\n' +
|
||||||
|
'<script src="https://weather.o2o.kr/embed/widget.js" async></script>',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('스크립트 코드: 지역 페이지가 없으면 링크는 날씨각 홈', () => {
|
||||||
|
assert.equal(
|
||||||
|
embedScript({ origin: ORIGIN, region: '1111000000', regionName: '어떤구', regionPath: null, kind: 'home', bg: 'dark' }),
|
||||||
|
'<a class="nalssigak-weather" href="https://weather.o2o.kr/?utm_source=widget&utm_medium=embed&utm_campaign=fallback"\n' +
|
||||||
|
' data-region="1111000000" data-type="home" data-bg="dark">어떤구 날씨 - 날씨각</a>\n' +
|
||||||
|
'<script src="https://weather.o2o.kr/embed/widget.js" async></script>',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('스크립트 코드: 지역 이름이 링크를 깨지 않는다', () => {
|
||||||
|
const code = embedScript({ origin: ORIGIN, region: '5213000000', regionName: '<b>A&"B', regionPath: null, kind: 'side', bg: 'sky' })
|
||||||
|
assert.ok(code.includes('><b>A&"B 날씨 - 날씨각</a>'))
|
||||||
|
assert.ok(!code.includes('<b>'))
|
||||||
|
})
|
||||||
@@ -101,6 +101,13 @@ const PAGES: { path: string; title: string; description: string; body: string; c
|
|||||||
keywords: '날씨 코디, 오늘의 코디, 이번 주 코디, 가을 코디, 날씨 쇼츠, 날씨각',
|
keywords: '날씨 코디, 오늘의 코디, 이번 주 코디, 가을 코디, 날씨 쇼츠, 날씨각',
|
||||||
body: '<h1>날씨각 · 날씨 쇼츠</h1><p>이번 주 날씨에 맞춘 20대·30대·40대 코디와 오늘 날씨 이야기를 짧은 영상으로 위아래로 넘겨 볼 수 있어요.</p>',
|
body: '<h1>날씨각 · 날씨 쇼츠</h1><p>이번 주 날씨에 맞춘 20대·30대·40대 코디와 오늘 날씨 이야기를 짧은 영상으로 위아래로 넘겨 볼 수 있어요.</p>',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'widget-guide',
|
||||||
|
title: '날씨 위젯 · 내 사이트에 날씨 카드 달기 | 날씨각',
|
||||||
|
description: '내 홈페이지·블로그에 우리 동네 오늘 날씨 카드를 달아 보세요. 무료이고 신청 없이 코드만 붙이면 돼요.',
|
||||||
|
keywords: '날씨 위젯, 홈페이지 날씨, 날씨 퍼가기, 날씨 iframe',
|
||||||
|
body: '<h1>날씨각 · 날씨 위젯</h1><p>내 홈페이지나 블로그에 고른 지역의 오늘 날씨 카드를 달 수 있어요. 지금 날씨 점수와 아침·낮·저녁·밤 하늘과 기온을 보여 주고, 카드의 자세히 보기 버튼을 누르면 날씨각에서 더 많은 날씨를 볼 수 있어요.</p><p>무료이고 신청 없이 바로 쓸 수 있어요. 지역을 고르고 코드를 복사해 붙이면 끝이에요.</p><p>붙이는 방법은 스크립트(권장)와 iframe 코드 두 가지예요. 모양은 기본형과 상세형, 배경은 기본형·밝은 바탕용·어두운 바탕용 3가지 가운데 고를 수 있어요.</p>',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'type',
|
path: 'type',
|
||||||
title: '날씨 유형 테스트 · 나는 무슨 날씨일까? | 날씨각',
|
title: '날씨 유형 테스트 · 나는 무슨 날씨일까? | 날씨각',
|
||||||
|
|||||||
+3
-3
@@ -25,9 +25,9 @@ Run lint and typecheck before declaring any task done.
|
|||||||
|
|
||||||
## Navigation & Routing
|
## Navigation & Routing
|
||||||
|
|
||||||
- Use **Expo Router** for all navigation. Routes live in `src/app/` — every file there is a screen, `_layout.tsx` files define navigators. Keep non-route code (components, hooks, utils) outside `src/app/`.
|
- The app is a WebView shell: `src/app/_layout.tsx` renders only `WebShell` (`src/components/web-shell.tsx`), which loads the 날씨각 web site. All screens and navigation live in the web app (`frontend/`), not here. Do not add native screens under `src/app/`.
|
||||||
- Import `Link`, `router`, and `useLocalSearchParams` from `expo-router`.
|
- Expo Router is kept only as the app entry point. `src/app/+native-intent.tsx` redirects every incoming link to `/` so the shell can open it in the WebView.
|
||||||
- Docs: https://docs.expo.dev/router/introduction.md
|
- Native features the web needs (Google sign-in, location, sharing) go through the bridge in `src/lib/web-bridge.ts`.
|
||||||
|
|
||||||
## Building with EAS
|
## Building with EAS
|
||||||
|
|
||||||
|
|||||||
+3
-12
@@ -2,7 +2,7 @@
|
|||||||
"expo": {
|
"expo": {
|
||||||
"name": "날씨각",
|
"name": "날씨각",
|
||||||
"slug": "nalssigak",
|
"slug": "nalssigak",
|
||||||
"version": "1.1.1",
|
"version": "1.1.2",
|
||||||
"orientation": "portrait",
|
"orientation": "portrait",
|
||||||
"icon": "./assets/images/icon.png",
|
"icon": "./assets/images/icon.png",
|
||||||
"scheme": "nalssigak",
|
"scheme": "nalssigak",
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"android": {
|
"android": {
|
||||||
"versionCode": 1002,
|
"versionCode": 1005,
|
||||||
"adaptiveIcon": {
|
"adaptiveIcon": {
|
||||||
"backgroundColor": "#bbeafd",
|
"backgroundColor": "#bbeafd",
|
||||||
"foregroundImage": "./assets/images/android-icon-foreground.png",
|
"foregroundImage": "./assets/images/android-icon-foreground.png",
|
||||||
@@ -55,7 +55,6 @@
|
|||||||
"imageWidth": 200
|
"imageWidth": 200
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"expo-secure-store",
|
|
||||||
"expo-sharing",
|
"expo-sharing",
|
||||||
[
|
[
|
||||||
"expo-location",
|
"expo-location",
|
||||||
@@ -63,15 +62,7 @@
|
|||||||
"locationWhenInUsePermission": "가장 가까운 동네 날씨를 보여 드리려고 위치를 써요."
|
"locationWhenInUsePermission": "가장 가까운 동네 날씨를 보여 드리려고 위치를 써요."
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"@react-native-google-signin/google-signin",
|
"@react-native-google-signin/google-signin"
|
||||||
[
|
|
||||||
"expo-image-picker",
|
|
||||||
{
|
|
||||||
"photosPermission": "동네 이야기에 사진을 붙이려고 사진 앨범을 써요.",
|
|
||||||
"cameraPermission": false,
|
|
||||||
"microphonePermission": false
|
|
||||||
}
|
|
||||||
]
|
|
||||||
],
|
],
|
||||||
"experiments": {
|
"experiments": {
|
||||||
"typedRoutes": true,
|
"typedRoutes": true,
|
||||||
|
|||||||
@@ -3,44 +3,29 @@
|
|||||||
"main": "expo-router/entry",
|
"main": "expo-router/entry",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@expo-google-fonts/bagel-fat-one": "^0.4.0",
|
|
||||||
"@expo-google-fonts/gowun-batang": "^0.4.1",
|
|
||||||
"@expo-google-fonts/jua": "^0.4.1",
|
|
||||||
"@expo/ui": "~57.0.23",
|
"@expo/ui": "~57.0.23",
|
||||||
"@nalssigak/shared": "*",
|
|
||||||
"@react-native-google-signin/google-signin": "^16.1.5",
|
"@react-native-google-signin/google-signin": "^16.1.5",
|
||||||
"@tanstack/react-query": "^5.104.2",
|
|
||||||
"expo": "~57.0.28",
|
"expo": "~57.0.28",
|
||||||
"expo-constants": "~57.0.21",
|
"expo-constants": "~57.0.21",
|
||||||
"expo-device": "~57.0.2",
|
|
||||||
"expo-file-system": "~57.0.7",
|
"expo-file-system": "~57.0.7",
|
||||||
"expo-font": "~57.0.4",
|
"expo-font": "~57.0.4",
|
||||||
"expo-glass-effect": "~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-linking": "~57.0.12",
|
||||||
"expo-location": "~57.0.21",
|
"expo-location": "~57.0.21",
|
||||||
"expo-router": "~57.0.26",
|
"expo-router": "~57.0.26",
|
||||||
"expo-secure-store": "~57.0.4",
|
|
||||||
"expo-sharing": "~57.0.23",
|
"expo-sharing": "~57.0.23",
|
||||||
"expo-splash-screen": "~57.0.10",
|
"expo-splash-screen": "~57.0.10",
|
||||||
"expo-status-bar": "~57.0.1",
|
"expo-status-bar": "~57.0.1",
|
||||||
"expo-symbols": "~57.0.3",
|
"expo-symbols": "~57.0.3",
|
||||||
"expo-system-ui": "~57.0.4",
|
"expo-system-ui": "~57.0.4",
|
||||||
"expo-web-browser": "~57.0.3",
|
|
||||||
"react": "19.2.3",
|
"react": "19.2.3",
|
||||||
"react-dom": "19.2.3",
|
"react-dom": "19.2.3",
|
||||||
"react-native": "0.86.3",
|
"react-native": "0.86.3",
|
||||||
"react-native-gesture-handler": "~2.32.0",
|
"react-native-gesture-handler": "~2.32.0",
|
||||||
"react-native-reanimated": "4.5.1",
|
|
||||||
"react-native-safe-area-context": "~5.7.0",
|
"react-native-safe-area-context": "~5.7.0",
|
||||||
"react-native-screens": "~4.26.0",
|
"react-native-screens": "~4.26.0",
|
||||||
"react-native-svg": "15.15.4",
|
|
||||||
"react-native-view-shot": "5.1.0",
|
|
||||||
"react-native-web": "~0.21.0",
|
"react-native-web": "~0.21.0",
|
||||||
"react-native-webview": "13.16.1",
|
"react-native-webview": "13.16.1",
|
||||||
"react-native-worklets": "0.10.1",
|
|
||||||
"tailwindcss": "^4.3.3",
|
"tailwindcss": "^4.3.3",
|
||||||
"uniwind": "^1.12.2"
|
"uniwind": "^1.12.2"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
import { listArticlesOptions, listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
||||||
import { ArticleCategory, IndexCategory } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { kst, loadOf, seasonOf } from '@nalssigak/shared/lib';
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { Pressable, RefreshControl, ScrollView, View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
|
|
||||||
import { GakGrid, GridSkel } from '@/components/gak/grid';
|
|
||||||
import { Podium, PodiumSkel } from '@/components/gak/podium';
|
|
||||||
import { Chips, Ic, Sec, StateBox } from '@/components/ui';
|
|
||||||
import { useRegion } from '@/lib/region';
|
|
||||||
import { useSheet } from '@/lib/sheet';
|
|
||||||
|
|
||||||
type Cat = 'all' | 'out' | 'food' | 'home' | 'life' | 'core';
|
|
||||||
|
|
||||||
// 마지막 칩은 지금 계절의 제철 각 (예: 가을 각)
|
|
||||||
const CATS: readonly (readonly [Cat, string])[] = [
|
|
||||||
['all', '전체'],
|
|
||||||
['out', '밖에서 놀기'],
|
|
||||||
['food', '먹고 마시기'],
|
|
||||||
['home', '집안일'],
|
|
||||||
['life', '생활 고민'],
|
|
||||||
['core', `${seasonOf(kst(new Date()).mo)[0]} 각`],
|
|
||||||
];
|
|
||||||
|
|
||||||
const CAT_PARAM: Partial<Record<Cat, IndexCategory>> = { out: IndexCategory.OUTSIDE, food: IndexCategory.FOOD, home: IndexCategory.HOME, life: IndexCategory.LIFE };
|
|
||||||
|
|
||||||
export default function GakScreen() {
|
|
||||||
const { region } = useRegion();
|
|
||||||
const { open } = useSheet();
|
|
||||||
const [cat, setCat] = useState<Cat>('all');
|
|
||||||
const q = useQuery(listIndicesOptions({ query: { region: region.code, category: CAT_PARAM[cat], core: cat === 'core' ? true : undefined } }));
|
|
||||||
const articles = useQuery(listArticlesOptions({ query: { category: ArticleCategory.GAK } }));
|
|
||||||
const top = q.data?.top3 ?? [];
|
|
||||||
const items = q.data?.items ?? [];
|
|
||||||
const day = q.data?.day?.split('-').map(Number);
|
|
||||||
const load = loadOf(q);
|
|
||||||
const howto = articles.data?.articles?.find((a) => a.code === 'howgak');
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={q.isRefetching && !q.isPlaceholderData} onRefresh={() => q.refetch()} />}>
|
|
||||||
<Sec title="오늘 1~3위" sub={`${day ? `${day[1]}월 ${day[2]}일 기준 · ` : ''}${region.name}`} />
|
|
||||||
{top.length === 3 ? <Podium top={top} dim={q.isPlaceholderData} /> : load === 'loading' ? <PodiumSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="오늘 1~3위를 아직 못 정했어요." hold={<PodiumSkel />} />}
|
|
||||||
<Chips items={CATS} value={cat} onChange={setCat} />
|
|
||||||
{load === 'loading' ? (
|
|
||||||
<GridSkel />
|
|
||||||
) : !items.length ? (
|
|
||||||
// 실패 안내·다시 시도는 위 받침대 자리에 한 번만
|
|
||||||
<StateBox load="ready" empty={load === 'ready' ? '이 분야는 오늘 계산된 각이 없어요.' : '각 목록을 불러오지 못했어요.'} hold={<GridSkel />} boxClassName="inset-3" />
|
|
||||||
) : (
|
|
||||||
<GakGrid items={items} dim={q.isPlaceholderData} />
|
|
||||||
)}
|
|
||||||
{howto && load !== 'loading' && (
|
|
||||||
<Pressable onPress={() => open({ type: 'article', articleId: howto.article_id })} className="mx-3 mt-1.5 flex-row items-center gap-3 rounded-[22px] bg-[#ece7ff] p-3.5">
|
|
||||||
<Ic name="bulb" size={44} />
|
|
||||||
<View className="flex-1">
|
|
||||||
<Text className="font-jua text-[17px] text-[#28304a]">각 점수는 어떻게 매길까?</Text>
|
|
||||||
<Text className="text-[12.5px] font-semibold text-[#5a6380]">기온·비·바람·습도·공기·시간대 6가지로 계산해요</Text>
|
|
||||||
</View>
|
|
||||||
</Pressable>
|
|
||||||
)}
|
|
||||||
</ScrollView>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
import { getSeasonWeekOptions, listArticlesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
||||||
import { ArticleCategory } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { loadOf } from '@nalssigak/shared/lib';
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { RefreshControl, ScrollView, View } from 'react-native';
|
|
||||||
|
|
||||||
import { ArticleRow, HeadSkel, RowsSkel, SeasonHead } from '@/components/season/parts';
|
|
||||||
import { Chips, StateBox } from '@/components/ui';
|
|
||||||
import { useSheet } from '@/lib/sheet';
|
|
||||||
|
|
||||||
const CATS = [
|
|
||||||
['all', '전체'],
|
|
||||||
['season', '계절 소식'],
|
|
||||||
['tip', '날씨 상식'],
|
|
||||||
['gak', '각 원리'],
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
const CAT_PARAM = { season: ArticleCategory.SEASON, tip: ArticleCategory.TIP, gak: ArticleCategory.GAK } as const;
|
|
||||||
|
|
||||||
export default function SeasonScreen() {
|
|
||||||
const { open } = useSheet();
|
|
||||||
const [cat, setCat] = useState<(typeof CATS)[number][0]>('all');
|
|
||||||
const week = useQuery(getSeasonWeekOptions());
|
|
||||||
const arts = useQuery(listArticlesOptions(cat === 'all' ? undefined : { query: { category: CAT_PARAM[cat] } }));
|
|
||||||
const w = week.data;
|
|
||||||
const list = arts.data?.articles ?? [];
|
|
||||||
const weekLoad = loadOf(week);
|
|
||||||
const artLoad = loadOf(arts);
|
|
||||||
const refresh = () => Promise.all([week.refetch(), arts.refetch()]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={(week.isRefetching || arts.isRefetching) && !arts.isPlaceholderData} onRefresh={refresh} />}>
|
|
||||||
{w?.headline ? <SeasonHead week={w} onPress={() => open({ type: 'seasonWeek' })} /> : weekLoad === 'loading' ? <HeadSkel /> : <StateBox load={weekLoad} onRetry={() => week.refetch()} empty="이번 주 특집이 아직 없어요." hold={<HeadSkel />} />}
|
|
||||||
<Chips items={CATS} value={cat} onChange={setCat} />
|
|
||||||
<View className="mt-1.5" style={{ opacity: arts.isPlaceholderData ? 0.6 : 1 }}>
|
|
||||||
{artLoad === 'loading' && <RowsSkel />}
|
|
||||||
{artLoad !== 'loading' && !list.length && <StateBox load={artLoad} onRetry={() => arts.refetch()} empty="읽을거리가 아직 없어요." hold={<RowsSkel />} boxClassName="inset-3" />}
|
|
||||||
{list.map((a) => (
|
|
||||||
<ArticleRow key={a.article_id} article={a} onPress={() => open({ type: 'article', articleId: a.article_id })} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
</ScrollView>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
import { getSkyOptions, getSkyRankingOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
||||||
import { loadOf } from '@nalssigak/shared/lib';
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { RefreshControl, ScrollView, View } from 'react-native';
|
|
||||||
|
|
||||||
import { DayTiles, Li, LiSkel, ScoreHelp, SkyHero, Timeline } from '@/components/sky/parts';
|
|
||||||
import { Sec, Skel, StateBox } from '@/components/ui';
|
|
||||||
import { useRegion } from '@/lib/region';
|
|
||||||
|
|
||||||
const THREE = [0, 1, 2];
|
|
||||||
const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i);
|
|
||||||
|
|
||||||
/** 히어로 글자 자리 (실패·빈 안내를 같은 높이로 띄우려고) */
|
|
||||||
function HeroHold() {
|
|
||||||
return (
|
|
||||||
<View>
|
|
||||||
<Skel className="h-7 w-[230px]" />
|
|
||||||
<Skel className="mt-2 w-[180px]" />
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function LiSkels({ n }: { n: number[] }) {
|
|
||||||
return (
|
|
||||||
<View className="mx-3 mt-1.5">
|
|
||||||
{n.map((i) => (
|
|
||||||
<LiSkel key={i} last={i === n.length - 1} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function SkyScreen() {
|
|
||||||
const { region } = useRegion();
|
|
||||||
const sky = useQuery(getSkyOptions({ query: { region: region.code } }));
|
|
||||||
const ranking = useQuery(getSkyRankingOptions());
|
|
||||||
const load = loadOf(sky);
|
|
||||||
const rankLoad = loadOf(ranking);
|
|
||||||
const plans = sky.data?.plans ?? [];
|
|
||||||
const [picked, setPicked] = useState<string>();
|
|
||||||
// 타일을 누르면 그날, 아니면 다음에 오는 날
|
|
||||||
const plan = plans.find((p) => p.day === picked) ?? sky.data?.plan ?? undefined;
|
|
||||||
const spots = (sky.data?.spots ?? []).slice(0, 3);
|
|
||||||
const items = (ranking.data?.items ?? []).slice(0, 8);
|
|
||||||
const rise = plan?.kind === 'sunrise';
|
|
||||||
const refresh = () => Promise.all([sky.refetch(), ranking.refetch()]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={sky.isRefetching && !sky.isPlaceholderData} onRefresh={refresh} />} style={{ opacity: sky.isPlaceholderData ? 0.6 : 1 }}>
|
|
||||||
{plan || load === 'loading' ? (
|
|
||||||
<SkyHero plan={plan} />
|
|
||||||
) : (
|
|
||||||
<SkyHero>
|
|
||||||
<StateBox load={load} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." hold={<HeroHold />} boxClassName="inset-x-0 top-1.5 bottom-0" />
|
|
||||||
</SkyHero>
|
|
||||||
)}
|
|
||||||
{plans.length > 1 && <DayTiles plans={plans} day={plan?.day} onPick={setPicked} />}
|
|
||||||
{plan && <ScoreHelp plan={plan} />}
|
|
||||||
<Sec title="언제 보면 좋을까" />
|
|
||||||
{plan?.timeline?.length || load === 'loading' ? <Timeline rows={plan?.timeline} kind={plan?.kind} /> : <StateBox load="ready" empty={load === 'ready' ? '노을 시간 정보가 없어요.' : '노을 시간을 불러오지 못했어요.'} hold={<Timeline />} />}
|
|
||||||
{!rise && <Sec title="가까운 노을 명소" sub="가까운 순 · 방향은 내 동네에서 본 쪽" />}
|
|
||||||
{rise ? null : spots.length ? (
|
|
||||||
<View className="mx-3 mt-1.5">
|
|
||||||
{spots.map((p, i) => (
|
|
||||||
<Li key={p.no} no={p.no} title={p.name} sub={p.direction ? `${p.direction}쪽` : null} right={`${p.distance_km}km`} place={p.name} last={i === 2} />
|
|
||||||
))}
|
|
||||||
{/* 3곳이 안 되면 빈 줄로 높이를 지켜 아래 순위가 밀리지 않게 */}
|
|
||||||
{THREE.slice(spots.length).map((i) => (
|
|
||||||
<LiSkel key={`ghost-${i}`} ghost last={i === 2} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
) : load === 'loading' ? (
|
|
||||||
<View className="mx-3 mt-1.5">
|
|
||||||
{THREE.map((i) => (
|
|
||||||
<LiSkel key={i} last={i === 2} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
) : (
|
|
||||||
// 실패 안내·다시 시도는 위 히어로에 한 번만
|
|
||||||
<StateBox load="ready" empty={load === 'ready' ? '근처에 등록된 노을 명소가 없어요.' : '명소 정보를 불러오지 못했어요.'} hold={<LiSkels n={THREE} />} />
|
|
||||||
)}
|
|
||||||
<Sec title="전국 노을 순위" sub={ranking.data?.summary ?? '오늘 기준'} />
|
|
||||||
{items.length ? (
|
|
||||||
<View className="mx-3 mt-1.5">
|
|
||||||
{items.map((r, i) => (
|
|
||||||
<Li key={r.region_code} no={r.rank} title={r.name} sub={[r.note, r.situation_label].filter(Boolean).join(' · ')} right={`${r.score}점`} mine={r.region_code === region.code} last={i === items.length - 1} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
) : rankLoad === 'loading' ? (
|
|
||||||
<View className="mx-3 mt-1.5">
|
|
||||||
{RANK_SKELS.map((i) => (
|
|
||||||
<LiSkel key={i} last={i === RANK_SKELS.length - 1} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
) : (
|
|
||||||
<StateBox load={rankLoad} onRetry={() => ranking.refetch()} empty="순위가 아직 없어요." hold={<LiSkels n={RANK_SKELS} />} boxClassName="inset-x-3 top-1.5 bottom-0" />
|
|
||||||
)}
|
|
||||||
</ScrollView>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,153 +0,0 @@
|
|||||||
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
||||||
import { loadOf, shortDay } from '@nalssigak/shared/lib';
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
import { useRef, useState } from 'react';
|
|
||||||
import { Pressable, RefreshControl, ScrollView, View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
|
|
||||||
import { DayStrip, EventRow, PickCard, PlaceCard, RankRow } from '@/components/week/sections';
|
|
||||||
import { DaysSkel, EventsSkel, PickSkel, PlacesSkel, RankSkel } from '@/components/week/skels';
|
|
||||||
import { Chips, Rail, Sec, Skel, StateBox } from '@/components/ui';
|
|
||||||
import { useRegion } from '@/lib/region';
|
|
||||||
import { useShare } from '@/lib/share-image';
|
|
||||||
import { SITE_URL } from '@/lib/site';
|
|
||||||
|
|
||||||
// 불러오는 동안에도 탭 줄 높이를 지키려고 같은 칩을 미리 그린다
|
|
||||||
const RANK_TABS_HOLD = [
|
|
||||||
['토', '토요일'],
|
|
||||||
['일', '일요일'],
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
export default function WeekScreen() {
|
|
||||||
const { region } = useRegion();
|
|
||||||
const week = useQuery(getWeekOptions({ query: { region: region.code } }));
|
|
||||||
const days = week.data?.days ?? [];
|
|
||||||
const [picked, setPicked] = useState<string | null>(null);
|
|
||||||
// 지역을 바꾸면 동네 고르기는 전체로 돌아간다
|
|
||||||
const [areaPick, setAreaPick] = useState({ region: region.code, area: '전체' });
|
|
||||||
const area = areaPick.region === region.code ? areaPick.area : '전체';
|
|
||||||
// 처음에는 이번 토요일을 고른다
|
|
||||||
const sel = days.find((d) => d.day === picked) ?? days.find((d) => d.weekday === '토') ?? days[0];
|
|
||||||
const places = useQuery({ ...listPlacesOptions({ query: { region: region.code, day: sel?.day, area: area === '전체' ? undefined : area } }), enabled: !!sel });
|
|
||||||
const events = useQuery(listEventsOptions({ query: { region: region.code } }));
|
|
||||||
const ranking = useQuery(getWeekRankingOptions());
|
|
||||||
const rankDays = ranking.data?.days ?? [];
|
|
||||||
const [rankPick, setRankPick] = useState<string | null>(null);
|
|
||||||
const rankDay = rankDays.find((d) => d.day === rankPick) ?? rankDays[0];
|
|
||||||
const rankItems = (rankDay?.items ?? []).slice(0, 10);
|
|
||||||
const rankLoad = loadOf(ranking);
|
|
||||||
const areas = places.data?.areas ?? [];
|
|
||||||
const rainy = places.data?.rainy ?? sel?.is_rainy;
|
|
||||||
const placeList = places.data?.places ?? [];
|
|
||||||
const eventList = events.data?.events ?? [];
|
|
||||||
const weekLoad = loadOf(week);
|
|
||||||
const eventLoad = loadOf(events);
|
|
||||||
// 날씨(고른 날)가 와야 명소를 부를 수 있다
|
|
||||||
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready';
|
|
||||||
const refresh = () => Promise.all([week.refetch(), events.refetch(), ranking.refetch(), sel ? places.refetch() : null]);
|
|
||||||
|
|
||||||
const shareView = useShare();
|
|
||||||
const pickShot = useRef<View>(null);
|
|
||||||
// 고른 날 추천 카드를 이미지로
|
|
||||||
const sendPlan = () => {
|
|
||||||
if (!sel) return;
|
|
||||||
const message = [`${sel.weekday}요일 일정 · ${region.name}`, sel.headline, sel.summary, sel.pick, `날씨각 ${SITE_URL}`].filter(Boolean).join('\n');
|
|
||||||
void shareView(pickShot, { title: `${sel.weekday}요일 일정`, message });
|
|
||||||
};
|
|
||||||
|
|
||||||
const placeSub = sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? undefined : '날씨에 맞춰 골라 보여 줘요';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ScrollView key={region.code} contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={week.isRefetching && !week.isPlaceholderData} onRefresh={refresh} />}>
|
|
||||||
<Sec title="열흘 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
|
|
||||||
{days.length ? (
|
|
||||||
<DayStrip days={days} selected={sel?.day} onPick={setPicked} dim={week.isPlaceholderData} />
|
|
||||||
) : weekLoad === 'loading' ? (
|
|
||||||
<>
|
|
||||||
<DaysSkel />
|
|
||||||
<PickSkel />
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<StateBox
|
|
||||||
load={weekLoad}
|
|
||||||
onRetry={() => week.refetch()}
|
|
||||||
empty="날씨가 아직 없어요."
|
|
||||||
hold={
|
|
||||||
<>
|
|
||||||
<DaysSkel />
|
|
||||||
<PickSkel />
|
|
||||||
</>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{sel && (
|
|
||||||
<View ref={pickShot} collapsable={false}>
|
|
||||||
<PickCard day={sel} />
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
{(sel || weekLoad !== 'ready') && (
|
|
||||||
<>
|
|
||||||
<Text className="mx-4 mt-3.5 text-[13.5px] font-bold text-ink2">30km 안 · 데이트 명소</Text>
|
|
||||||
<Chips items={['전체', ...areas].map((a) => [a, a] as const)} value={area} onChange={(a) => setAreaPick({ region: region.code, area: a })} disabled={!areas.length} />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{/* 명소 데이터가 없으면 칸 전체를 숨긴다 */}
|
|
||||||
{!(placeLoad === 'ready' && !placeList.length) && (
|
|
||||||
<>
|
|
||||||
<View className="-mt-2.5">
|
|
||||||
<Sec title="날씨 맞춤 데이트 명소" sub={placeSub} />
|
|
||||||
</View>
|
|
||||||
{!placeSub && <Skel className="mx-4 w-56" />}
|
|
||||||
{placeList.length ? (
|
|
||||||
<View style={{ opacity: places.isPlaceholderData ? 0.6 : 1 }}>
|
|
||||||
<Rail>
|
|
||||||
{placeList.map((p, i) => (
|
|
||||||
<PlaceCard key={p.place_id} place={p} index={i} />
|
|
||||||
))}
|
|
||||||
</Rail>
|
|
||||||
</View>
|
|
||||||
) : placeLoad === 'loading' ? (
|
|
||||||
<PlacesSkel />
|
|
||||||
) : (
|
|
||||||
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? '30km 안에 데이트 명소가 아직 없어요.' : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} />
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<Sec title="이번 주말 전국 날씨 순위" sub="낮 10~17시 나들이 날씨 · 대표 지역 30곳 중 10위까지" />
|
|
||||||
{rankDays.length ? (
|
|
||||||
<Chips items={rankDays.map((d) => [d.day, `${d.weekday}요일 ${shortDay(d.day)}`] as const)} value={rankDay?.day ?? ''} onChange={setRankPick} />
|
|
||||||
) : (
|
|
||||||
<Chips items={RANK_TABS_HOLD} value="토" onChange={() => undefined} disabled />
|
|
||||||
)}
|
|
||||||
{rankItems.length ? (
|
|
||||||
<View className="mx-3 mt-1.5" style={{ opacity: ranking.isPlaceholderData ? 0.6 : 1 }}>
|
|
||||||
{rankItems.map((r) => (
|
|
||||||
<RankRow key={r.region_code} item={r} mine={r.region_code === region.code} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
) : rankLoad === 'loading' ? (
|
|
||||||
<RankSkel />
|
|
||||||
) : (
|
|
||||||
<StateBox load={rankLoad} onRetry={() => ranking.refetch()} empty="주말 예보가 아직 없어요." hold={<RankSkel />} boxClassName="inset-x-3 top-1.5 bottom-0" />
|
|
||||||
)}
|
|
||||||
<Sec title="가까운 축제·행사" sub="30km 안 · 앞으로 30일 · 그날 날씨까지 같이 봐요" />
|
|
||||||
{eventList.length ? (
|
|
||||||
<View style={{ opacity: events.isPlaceholderData ? 0.6 : 1 }}>
|
|
||||||
{eventList.map((e, i) => (
|
|
||||||
<EventRow key={e.event_id} event={e} index={i} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
) : eventLoad === 'loading' ? (
|
|
||||||
<EventsSkel />
|
|
||||||
) : (
|
|
||||||
<StateBox load={eventLoad} onRetry={() => events.refetch()} empty="30km 안에 열리는 행사가 아직 없어요. 다른 지역을 골라 보세요." hold={<EventsSkel />} boxClassName="inset-x-3 top-2.5 bottom-0" />
|
|
||||||
)}
|
|
||||||
{/* 행사 수가 정해진 뒤에 붙여 목록이 늘어날 때 밀리지 않게 */}
|
|
||||||
{eventLoad !== 'loading' && (
|
|
||||||
<Pressable onPress={sendPlan} disabled={!sel} className="mx-3 mt-4 items-center rounded-full border-b-[5px] border-orange-deep bg-orange p-[13px] disabled:opacity-60">
|
|
||||||
<Text className="font-jua text-[17px] text-white">이번 주말 일정 보내기</Text>
|
|
||||||
</Pressable>
|
|
||||||
)}
|
|
||||||
</ScrollView>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* 화면은 _layout.tsx 의 웹 셸이 다 그린다. 이 파일은 Expo Router 가 '/' 경로를 알게 하려고 둔다.
|
||||||
|
* 경로 파일이 하나도 없으면 Expo Router 가 우리 _layout 대신 자기 안내 화면(_sitemap)을 띄우다 앱이 죽는다.
|
||||||
|
*/
|
||||||
|
export default function Index() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
// 아이콘 줄 '쇼츠'(/shorts)는 첫 영상부터
|
|
||||||
export { default } from './[id]';
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
import { useEffect, type ReactNode } from 'react';
|
|
||||||
import type { ViewStyle } from 'react-native';
|
|
||||||
import Animated, { cancelAnimation, Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
|
|
||||||
|
|
||||||
/** 하늘에서 떨어진 뒤 둥둥 (웹 b-fall: b-drop 1.05초 뒤 b-float 무한). d·f 는 밀리초 */
|
|
||||||
export function Fall({ d, f, amp = 9, style, children }: { d: number; f: number; amp?: number; style?: ViewStyle; children: ReactNode }) {
|
|
||||||
const reduce = useReducedMotion();
|
|
||||||
const drop = useSharedValue(reduce ? 1 : 0);
|
|
||||||
const float = useSharedValue(0);
|
|
||||||
useEffect(() => {
|
|
||||||
if (reduce) return;
|
|
||||||
drop.value = withDelay(d, withTiming(1, { duration: 1050, easing: Easing.bezier(0.22, 0.9, 0.3, 1) }));
|
|
||||||
float.value = withDelay(d + 1050, withRepeat(withTiming(1, { duration: f / 2, easing: Easing.inOut(Easing.ease) }), -1, true));
|
|
||||||
return () => {
|
|
||||||
cancelAnimation(drop);
|
|
||||||
cancelAnimation(float);
|
|
||||||
};
|
|
||||||
}, [reduce, d, f, drop, float]);
|
|
||||||
const anim = useAnimatedStyle(() => {
|
|
||||||
const p = drop.value;
|
|
||||||
const y = interpolate(p, [0, 0.72, 0.86, 1], [-400, 0, -10, 0]) - amp * float.value;
|
|
||||||
const rot = interpolate(p, [0, 0.72, 1], [-10, 2, 0]) + 1.2 * float.value;
|
|
||||||
return {
|
|
||||||
opacity: interpolate(p, [0, 0.55, 1], [0, 1, 1]),
|
|
||||||
transform: [{ translateY: y }, { rotate: `${rot}deg` }, { scaleX: interpolate(p, [0, 0.72, 0.86, 1], [1, 1.04, 1, 1]) }, { scaleY: interpolate(p, [0, 0.72, 0.86, 1], [1, 0.96, 1, 1]) }],
|
|
||||||
};
|
|
||||||
});
|
|
||||||
return <Animated.View style={[style, anim]}>{children}</Animated.View>;
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
import type { TimeKind } from '@nalssigak/shared/lib';
|
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
|
||||||
import { useEffect, useState } from 'react';
|
|
||||||
import { StyleSheet, View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withRepeat, withSequence, withTiming } from 'react-native-reanimated';
|
|
||||||
|
|
||||||
import { Ic } from '@/components/ui';
|
|
||||||
import { useSky } from '@/lib/sky';
|
|
||||||
|
|
||||||
// 덮개 색: 시간대별 하늘 맨 위 색을 반쯤 비치게
|
|
||||||
const COVER: Record<TimeKind, string> = {
|
|
||||||
morning: 'rgb(255 230 207 / 0.72)',
|
|
||||||
day: 'rgb(214 235 255 / 0.72)',
|
|
||||||
sunset: 'rgb(255 216 194 / 0.72)',
|
|
||||||
night: 'rgb(14 20 51 / 0.72)',
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 캐릭터가 통통 뛴다 (웹 b-hop) */
|
|
||||||
function Hop({ name }: { name: string }) {
|
|
||||||
const reduce = useReducedMotion();
|
|
||||||
const t = useSharedValue(0);
|
|
||||||
useEffect(() => {
|
|
||||||
if (reduce) return;
|
|
||||||
const ease = Easing.bezier(0.3, 0, 0.4, 1);
|
|
||||||
t.value = withRepeat(withSequence(withTiming(1, { duration: 405, easing: ease }), withTiming(0, { duration: 495, easing: ease })), -1);
|
|
||||||
return () => cancelAnimation(t);
|
|
||||||
}, [reduce, t]);
|
|
||||||
const style = useAnimatedStyle(() => ({
|
|
||||||
transform: [{ translateY: -22 * t.value }, { scaleX: 1.06 - 0.09 * t.value }, { scaleY: 0.94 + 0.09 * t.value }],
|
|
||||||
transformOrigin: 'bottom',
|
|
||||||
}));
|
|
||||||
return (
|
|
||||||
<Animated.View style={style}>
|
|
||||||
<Ic name={name} size={88} />
|
|
||||||
</Animated.View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 처음 들어올 때만: 첫 데이터를 다 받을 때까지 하늘 위에 캐릭터와 '날씨 불러오는 중…'. 한 번 사라지면 다시 안 뜬다 */
|
|
||||||
export function FirstLoad() {
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const { kind } = useSky();
|
|
||||||
const [done, setDone] = useState(false);
|
|
||||||
const [gone, setGone] = useState(false);
|
|
||||||
// 받기 시작했다가 받는 게 없어지면 끝. 느린 망에서도 10초 넘게 막지 않는다 (그 뒤는 화면 안 스켈레톤이 맡는다)
|
|
||||||
useEffect(() => {
|
|
||||||
let seen = false;
|
|
||||||
const unsubscribe = queryClient.getQueryCache().subscribe(() => {
|
|
||||||
if (queryClient.isFetching() > 0) seen = true;
|
|
||||||
else if (seen) setDone(true);
|
|
||||||
});
|
|
||||||
const id = setTimeout(() => setDone(true), 10000);
|
|
||||||
return () => {
|
|
||||||
unsubscribe();
|
|
||||||
clearTimeout(id);
|
|
||||||
};
|
|
||||||
}, [queryClient]);
|
|
||||||
const shown = useSharedValue(1);
|
|
||||||
useEffect(() => {
|
|
||||||
if (!done) return;
|
|
||||||
shown.value = withTiming(0, { duration: 400 });
|
|
||||||
const id = setTimeout(() => setGone(true), 400);
|
|
||||||
return () => clearTimeout(id);
|
|
||||||
}, [done, shown]);
|
|
||||||
const fade = useAnimatedStyle(() => ({ opacity: shown.value }));
|
|
||||||
if (gone) return null;
|
|
||||||
return (
|
|
||||||
<Animated.View pointerEvents={done ? 'none' : 'auto'} accessibilityRole="progressbar" accessibilityLabel="날씨 불러오는 중" style={[StyleSheet.absoluteFill, { zIndex: 50, backgroundColor: COVER[kind] }, fade]}>
|
|
||||||
<View className="flex-1 items-center justify-center gap-3">
|
|
||||||
<Hop name={kind === 'night' ? 'bear' : 'rabbit'} />
|
|
||||||
<Text className="font-jua text-[19px] text-ink">날씨 불러오는 중…</Text>
|
|
||||||
</View>
|
|
||||||
</Animated.View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,153 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,272 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
import type { IndexSummary } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
|
|
||||||
import { Ic, Skel } from '@/components/ui';
|
|
||||||
import { useSheet } from '@/lib/sheet';
|
|
||||||
|
|
||||||
const CELL = 'w-[32%] items-center rounded-[22px] border-b-[5px] border-shade bg-card px-1.5 pt-3 pb-2.5';
|
|
||||||
const SKELS = Array.from({ length: 9 }, (_, i) => i);
|
|
||||||
|
|
||||||
export function GridSkel() {
|
|
||||||
return (
|
|
||||||
<View className="flex-row flex-wrap justify-between gap-y-2 p-3">
|
|
||||||
{SKELS.map((i) => (
|
|
||||||
<View key={i} className={`${CELL} gap-1.5`}>
|
|
||||||
<View className="size-[50px] rounded-full bg-skel" />
|
|
||||||
<Skel className="w-14" />
|
|
||||||
<Skel className="h-5 w-8" />
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 3칸 바둑판. 지금 시간대가 아니거나 제철이 아닌 각은 흐리게 */
|
|
||||||
export function GakGrid({ items, dim }: { items: IndexSummary[]; dim: boolean }) {
|
|
||||||
const { open } = useSheet();
|
|
||||||
return (
|
|
||||||
<View className="flex-row flex-wrap gap-y-2 p-3" style={{ columnGap: '2%', opacity: dim ? 0.6 : 1 }}>
|
|
||||||
{items.map((g) => (
|
|
||||||
<Pressable
|
|
||||||
key={g.index_id}
|
|
||||||
onPress={() => open({ type: 'gak', indexId: g.index_id })}
|
|
||||||
accessibilityLabel={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, ${g.in_season === false ? '제철 아님' : '지금 시간대 아님'}`}
|
|
||||||
className={`${CELL} ${g.active ? '' : 'opacity-55'}`}
|
|
||||||
>
|
|
||||||
{g.active && <Text className="absolute top-[7px] left-[9px] font-jua text-[13px] text-ink3">{g.rank}</Text>}
|
|
||||||
{!!g.season && <Text className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">{g.season}</Text>}
|
|
||||||
<Ic name={g.icon} size={50} />
|
|
||||||
<Text numberOfLines={1} className="mt-1 font-jua text-[15px] text-ink">
|
|
||||||
{g.name}
|
|
||||||
</Text>
|
|
||||||
{g.active ? (
|
|
||||||
<Text className={`font-bagel text-[22px] leading-[24px] ${g.score < 50 ? 'text-ink3' : 'text-orange'}`}>{g.score}</Text>
|
|
||||||
) : (
|
|
||||||
<Text className="py-1 text-[12px] leading-[14px] font-extrabold text-ink3">{g.in_season === false ? '제철 아님' : '지금 아님'}</Text>
|
|
||||||
)}
|
|
||||||
</Pressable>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
import type { IndexSummary } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { MEDALS } from '@nalssigak/shared/lib';
|
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
|
|
||||||
import { Ic, Skel } from '@/components/ui';
|
|
||||||
import { useSheet } from '@/lib/sheet';
|
|
||||||
import { useSky } from '@/lib/sky';
|
|
||||||
|
|
||||||
// 가운데가 높은 3칸: 2위 · 1위 · 3위
|
|
||||||
const ORDER = [1, 0, 2] as const;
|
|
||||||
const FLEX = [1.15, 1, 1];
|
|
||||||
|
|
||||||
/** 1~3위 받침대와 같은 칸의 스켈레톤 */
|
|
||||||
export function PodiumSkel() {
|
|
||||||
return (
|
|
||||||
<View className="flex-row gap-1.5 px-3 pt-3">
|
|
||||||
{ORDER.map((k) => (
|
|
||||||
<View key={k} style={{ flex: FLEX[k] }} className={`items-center gap-1.5 rounded-3xl border-b-[6px] border-shade bg-card px-1.5 ${k === 0 ? 'py-4' : 'mt-6 py-3'}`}>
|
|
||||||
<View className={`aspect-square rounded-full bg-skel ${k === 0 ? 'w-20' : 'w-[62px]'}`} />
|
|
||||||
<Skel className="w-16" />
|
|
||||||
<Skel className="h-6 w-10" />
|
|
||||||
<Skel className="w-full" />
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function Podium({ top, dim }: { top: IndexSummary[]; dim: boolean }) {
|
|
||||||
const { open } = useSheet();
|
|
||||||
const { kind } = useSky();
|
|
||||||
return (
|
|
||||||
<View className="flex-row gap-1.5 px-3 pt-3" style={{ opacity: dim ? 0.6 : 1 }}>
|
|
||||||
{ORDER.map((k) => {
|
|
||||||
const g = top[k];
|
|
||||||
return (
|
|
||||||
<Pressable key={g.index_id} style={{ flex: FLEX[k] }} onPress={() => open({ type: 'gak', indexId: g.index_id })} className={`items-center overflow-hidden rounded-3xl border-b-[6px] border-shade bg-card px-1.5 ${k === 0 ? 'py-4' : 'mt-6 py-3'}`}>
|
|
||||||
{k === 0 && kind !== 'night' && <LinearGradient colors={['#fff1c4', '#ffffff']} style={{ position: 'absolute', inset: 0 }} />}
|
|
||||||
<View>
|
|
||||||
<Ic name={g.icon} size={k === 0 ? 80 : 62} />
|
|
||||||
<Ic name={MEDALS[k]} size={28} style={{ position: 'absolute', top: -6, left: -12 }} />
|
|
||||||
</View>
|
|
||||||
<View className="mt-1.5 flex-1 justify-center">
|
|
||||||
<Text className="text-center font-jua text-base text-ink">
|
|
||||||
{k + 1}위 {g.name}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
<Text className="font-bagel text-[30px] leading-[32px] text-orange">{g.score}</Text>
|
|
||||||
{!!g.summary && <Text className="text-center text-[11.5px] font-semibold text-ink2">{g.summary}</Text>}
|
|
||||||
</Pressable>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import { moonPath } from '@nalssigak/shared/lib/today';
|
|
||||||
import { useId } from 'react';
|
|
||||||
import Svg, { Circle, ClipPath, Defs, Ellipse, FeGaussianBlur, Filter, G, Path, RadialGradient, Stop } from 'react-native-svg';
|
|
||||||
|
|
||||||
// 앞면 바다(어두운 무늬) 자리: [x, y, 가로 반지름, 세로 반지름]. 실제 달 앞면 배치를 대강 따른다 (웹 frontend/src/b/moon.tsx 와 같다)
|
|
||||||
const MARIA: [number, number, number, number][] = [
|
|
||||||
[-0.32, -0.36, 0.3, 0.26],
|
|
||||||
[0.12, -0.36, 0.17, 0.15],
|
|
||||||
[0.3, -0.06, 0.2, 0.17],
|
|
||||||
[-0.56, 0.06, 0.26, 0.42],
|
|
||||||
[0.66, -0.26, 0.1, 0.12],
|
|
||||||
[0.52, 0.22, 0.13, 0.15],
|
|
||||||
[-0.14, 0.44, 0.18, 0.13],
|
|
||||||
[-0.46, 0.5, 0.1, 0.09],
|
|
||||||
];
|
|
||||||
// 작은 크레이터: [x, y, 반지름]
|
|
||||||
const CRATERS: [number, number, number][] = [
|
|
||||||
[0.1, 0.72, 0.07],
|
|
||||||
[0.42, 0.52, 0.05],
|
|
||||||
[-0.66, -0.5, 0.05],
|
|
||||||
[0.62, 0.52, 0.04],
|
|
||||||
[-0.2, 0.08, 0.04],
|
|
||||||
];
|
|
||||||
// 저녁(노을)엔 노을빛이 도는 달, 밤엔 하얀 달
|
|
||||||
const TONES = {
|
|
||||||
night: { body: ['#fffcf2', '#f6ebcb', '#e0cc98'], shade: '#1a2050' },
|
|
||||||
dusk: { body: ['#fff8ee', '#ffe2cc', '#f2b9a2'], shade: '#4a2a63' },
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 오늘 밤 실제 모양대로 그린 달. pct 는 빛나는 면의 비율 0~100, 기우는 달은 왼쪽이 밝다. 빛 번짐까지 그려서 달 지름은 size 의 2/3 */
|
|
||||||
export function MoonArt({ pct, waxing, tone = 'night', size }: { pct: number; waxing: boolean; tone?: keyof typeof TONES; size: number }) {
|
|
||||||
const id = useId().replace(/[^a-zA-Z0-9]/g, '');
|
|
||||||
const t = TONES[tone];
|
|
||||||
const k = pct / 100;
|
|
||||||
const full = pct >= 99;
|
|
||||||
const hidden = pct <= 1;
|
|
||||||
return (
|
|
||||||
<Svg viewBox="-1.5 -1.5 3 3" width={size} height={size} pointerEvents="none">
|
|
||||||
<Defs>
|
|
||||||
<RadialGradient id={`${id}glow`} cx="0" cy="0" r="1.5" gradientUnits="userSpaceOnUse">
|
|
||||||
<Stop offset="0.6" stopColor="#fff4cf" stopOpacity={0.55} />
|
|
||||||
<Stop offset="0.8" stopColor="#ffe9a8" stopOpacity={0.16} />
|
|
||||||
<Stop offset="1" stopColor="#ffe9a8" stopOpacity={0} />
|
|
||||||
</RadialGradient>
|
|
||||||
<RadialGradient id={`${id}body`} cx="-0.2" cy="-0.28" r="1.44" gradientUnits="userSpaceOnUse">
|
|
||||||
<Stop offset="0" stopColor={t.body[0]} />
|
|
||||||
<Stop offset="0.6" stopColor={t.body[1]} />
|
|
||||||
<Stop offset="1" stopColor={t.body[2]} />
|
|
||||||
</RadialGradient>
|
|
||||||
<RadialGradient id={`${id}limb`} cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse">
|
|
||||||
<Stop offset="0.72" stopColor="#8a6f3c" stopOpacity={0} />
|
|
||||||
<Stop offset="1" stopColor="#8a6f3c" stopOpacity={0.28} />
|
|
||||||
</RadialGradient>
|
|
||||||
<ClipPath id={`${id}disc`}>
|
|
||||||
<Circle r="1" />
|
|
||||||
</ClipPath>
|
|
||||||
<Filter id={`${id}soft`} x="-0.2" y="-0.2" width="1.4" height="1.4">
|
|
||||||
<FeGaussianBlur stdDeviation="0.035" />
|
|
||||||
</Filter>
|
|
||||||
</Defs>
|
|
||||||
{!hidden && <Circle r="1.5" fill={`url(#${id}glow)`} opacity={full ? 1 : 0.12 + 0.8 * k} />}
|
|
||||||
<G clipPath={`url(#${id}disc)`}>
|
|
||||||
<Circle r="1" fill={`url(#${id}body)`} />
|
|
||||||
<G filter={`url(#${id}soft)`} fill="#c4b287" opacity={0.55}>
|
|
||||||
{MARIA.map(([x, y, rx, ry]) => (
|
|
||||||
<Ellipse key={`${x},${y}`} cx={x} cy={y} rx={rx} ry={ry} />
|
|
||||||
))}
|
|
||||||
</G>
|
|
||||||
{CRATERS.map(([x, y, r]) => (
|
|
||||||
<Circle key={`${x},${y}`} cx={x} cy={y} r={r} fill="#efe2bd" stroke="#cdbb8c" strokeWidth={0.018} opacity={0.8} />
|
|
||||||
))}
|
|
||||||
<Circle r="1" fill={`url(#${id}limb)`} />
|
|
||||||
{/* 안 보이는 쪽: 흐릿한 경계로 덮고, 땅빛(지구조) 정도만 비치게 */}
|
|
||||||
{!full && <Path d={moonPath(pct, 1.04, false)} fill={t.shade} opacity={0.94} filter={`url(#${id}soft)`} transform={waxing ? undefined : 'scale(-1,1)'} />}
|
|
||||||
</G>
|
|
||||||
{hidden && <Circle r="1" fill="none" stroke="#fff" strokeOpacity={0.18} strokeWidth={0.025} />}
|
|
||||||
</Svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,362 +0,0 @@
|
|||||||
import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
|
||||||
import { useRef, useState, type ReactNode } from 'react';
|
|
||||||
import { Pressable, ScrollView, TextInput, View } from 'react-native';
|
|
||||||
|
|
||||||
import { Body, useSoft } from '@/components/sheets/parts';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import { Ic, Rail, Sec } from '@/components/ui';
|
|
||||||
import { gakName, MY_GAK_ICON, shareUrl, SLOT_WORD, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from '@/lib/my-gak';
|
|
||||||
import { useRegion } from '@/lib/region';
|
|
||||||
import { useShare } from '@/lib/share-image';
|
|
||||||
import { useSheet } from '@/lib/sheet';
|
|
||||||
|
|
||||||
function Score({ s, big }: { s?: MyGakScore; big?: boolean }) {
|
|
||||||
const v = s?.score;
|
|
||||||
return <Text className={`ml-auto font-bagel ${big ? 'text-[36px] leading-[38px]' : 'text-[28px] leading-[30px]'} ${v == null || v < 50 ? 'text-ink3' : 'text-orange'}`}>{v ?? '–'}</Text>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function Reasons({ s }: { s?: MyGakScore }) {
|
|
||||||
if (!s?.slot) return <Text className="text-[12.5px] font-semibold text-ink3">예보를 불러오는 중이에요</Text>;
|
|
||||||
return (
|
|
||||||
<Text className="text-[12.5px] leading-snug font-semibold text-ink2">
|
|
||||||
<Text className="font-extrabold text-ink">{SLOT_WORD[s.slot as Slot]} </Text>
|
|
||||||
{s.reasons?.join(' · ')}
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 조건 이름. 점수 응답의 factors 와 reasons 는 같은 순서다
|
|
||||||
const AXIS_NAME: Record<string, string> = { temp: '기온', rain: '비', wind: '바람', air: '미세먼지', humidity: '습도' };
|
|
||||||
// 조건 점수가 이보다 낮으면 '아쉬운 조건'으로 카드에 칩을 단다
|
|
||||||
const SHORT = 70;
|
|
||||||
|
|
||||||
/** 조건마다 이름·점수·실제 값 (실제 값은 근거 문구의 첫 마디: 체감 15°) */
|
|
||||||
function conditions(s?: MyGakScore) {
|
|
||||||
const notes = s?.reasons ?? [];
|
|
||||||
return Object.entries(s?.factors ?? {}).map(([axis, value], i) => ({ axis, label: AXIS_NAME[axis] ?? axis, value, note: notes[i] ?? '', short: (notes[i] ?? '').split(', ')[0] }));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 오늘 탭의 내 각 줄: 카드엔 아이콘·이름·점수·아쉬운 조건만, 누르면 상세 창 */
|
|
||||||
export function MyGakRow() {
|
|
||||||
const { open } = useSheet();
|
|
||||||
const { items } = useMyGak();
|
|
||||||
const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? [];
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
|
|
||||||
<Rail>
|
|
||||||
{items.map((g, i) => {
|
|
||||||
const s = scores[i];
|
|
||||||
const miss = conditions(s)
|
|
||||||
.filter((c) => c.value < SHORT)
|
|
||||||
.slice(0, 2);
|
|
||||||
return (
|
|
||||||
<Pressable key={g.id ?? 'local'} onPress={() => open({ type: 'myGak', gak: g })} accessibilityLabel={`${g.name} ${s?.score ?? ''}점 자세히`} className="w-[200px] gap-2 rounded-[22px] border-b-[5px] border-shade bg-card p-3">
|
|
||||||
<View className="flex-row items-start justify-between">
|
|
||||||
<Ic name={g.icon ?? MY_GAK_ICON} size={40} />
|
|
||||||
<Score s={s} big />
|
|
||||||
</View>
|
|
||||||
<View>
|
|
||||||
<Text className="font-jua text-[17px] leading-tight text-ink">{g.name}</Text>
|
|
||||||
<Text className="text-xs font-bold text-ink3">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준` : '예보를 불러오는 중이에요'}</Text>
|
|
||||||
</View>
|
|
||||||
{!!s?.slot && (
|
|
||||||
<View className="flex-row flex-wrap gap-1">
|
|
||||||
{miss.length ? (
|
|
||||||
miss.map((c) => (
|
|
||||||
<Text key={c.axis} className="overflow-hidden rounded-full bg-[#ffe8dc] px-2 py-0.5 text-[11.5px] font-extrabold text-[#c2471b]">
|
|
||||||
{c.short}
|
|
||||||
</Text>
|
|
||||||
))
|
|
||||||
) : (
|
|
||||||
<Text className="overflow-hidden rounded-full bg-[#dff5ea] px-2 py-0.5 text-[11.5px] font-extrabold text-[#1f7a4f]">조건 다 맞아요</Text>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</Pressable>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
<Pressable onPress={() => open({ type: 'mix' })} accessibilityRole="button" className="w-[120px] items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-line p-3">
|
|
||||||
<Text className="font-jua text-[26px] leading-[28px] text-ink2">+</Text>
|
|
||||||
<Text className="font-jua text-[15px] text-ink2">내 각 만들기</Text>
|
|
||||||
</Pressable>
|
|
||||||
</Rail>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 내 각 상세: 시간대별 점수, 조건별 점수와 실제 값, 공유하기·지우기 */
|
|
||||||
export function MyGakSheet({ gak, onDone }: { gak: MyGak; onDone: () => void }) {
|
|
||||||
const { remove } = useMyGak();
|
|
||||||
const s = useMyGakScores([gak.rule]).data?.scores?.[0];
|
|
||||||
const soft = useSoft();
|
|
||||||
const shareView = useShare();
|
|
||||||
const shot = useRef<View>(null);
|
|
||||||
const [confirm, setConfirm] = useState(false);
|
|
||||||
const rows = conditions(s);
|
|
||||||
// 받은 사람이 자기 동네 점수로 볼 수 있게 링크를 같이 보낸다
|
|
||||||
const share = () => void shareView(shot, { title: gak.name, message: `${gak.name} ${s?.score ?? ''}점 · 내 동네 점수 보기 ${shareUrl(gak)}` });
|
|
||||||
return (
|
|
||||||
<Body>
|
|
||||||
<View ref={shot} collapsable={false} className="bg-card">
|
|
||||||
<View className="flex-row items-center gap-3">
|
|
||||||
<Ic name={gak.icon ?? MY_GAK_ICON} size={56} />
|
|
||||||
<View className="min-w-0 flex-1">
|
|
||||||
<Text className="font-jua text-[22px] leading-tight text-ink">{gak.name}</Text>
|
|
||||||
<Text className="text-[12.5px] font-bold text-ink3">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준 점수` : '예보를 불러오는 중이에요'}</Text>
|
|
||||||
</View>
|
|
||||||
<Score s={s} big />
|
|
||||||
</View>
|
|
||||||
<View className="mt-3 flex-row gap-1.5" accessibilityLabel="시간대별 점수">
|
|
||||||
{SLOTS.map(([k, word]) => {
|
|
||||||
const v = s?.slots?.[k];
|
|
||||||
return (
|
|
||||||
<View key={k} className="flex-1 items-center rounded-2xl px-1 py-2" style={{ backgroundColor: s?.slot === k ? soft.warm : soft.soft }}>
|
|
||||||
<Text className="text-xs font-extrabold text-ink2">{word}</Text>
|
|
||||||
<Text className={`font-bagel text-xl ${v != null ? 'text-orange' : 'text-ink3'}`}>{v ?? '–'}</Text>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</View>
|
|
||||||
<View className="mt-3.5 gap-2.5">
|
|
||||||
{rows.map((c) => (
|
|
||||||
<View key={c.axis}>
|
|
||||||
<View className="flex-row items-center gap-2.5">
|
|
||||||
<Text className="w-16 text-[13.5px] font-bold text-ink">{c.label}</Text>
|
|
||||||
<View className="h-[9px] flex-1 overflow-hidden rounded-full" style={{ backgroundColor: soft.bar }}>
|
|
||||||
<LinearGradient colors={['#ffc86e', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${c.value}%` }} />
|
|
||||||
</View>
|
|
||||||
<Text className="w-8 text-right text-xs font-bold text-ink2">{c.value}</Text>
|
|
||||||
</View>
|
|
||||||
<Text className="ml-[74px] text-[12.5px] font-semibold text-ink2">{c.note}</Text>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
<View className="mt-4 flex-row gap-2">
|
|
||||||
<Pressable onPress={share} className="flex-1 rounded-2xl bg-orange py-3">
|
|
||||||
<Text className="text-center font-jua text-[16px] text-white">공유하기</Text>
|
|
||||||
</Pressable>
|
|
||||||
{confirm ? (
|
|
||||||
<>
|
|
||||||
<Pressable
|
|
||||||
onPress={() => {
|
|
||||||
remove(gak);
|
|
||||||
onDone();
|
|
||||||
}}
|
|
||||||
className="rounded-2xl bg-[#fdecec] px-4 py-3"
|
|
||||||
>
|
|
||||||
<Text className="font-jua text-[16px] text-heart">지우기</Text>
|
|
||||||
</Pressable>
|
|
||||||
<Pressable onPress={() => setConfirm(false)} className="rounded-2xl bg-[#eef4fc] px-4 py-3">
|
|
||||||
<Text className="font-jua text-[16px] text-[#5a6380]">취소</Text>
|
|
||||||
</Pressable>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Pressable onPress={() => setConfirm(true)} className="rounded-2xl bg-[#eef4fc] px-4 py-3">
|
|
||||||
<Text className="font-jua text-[16px] text-[#5a6380]">지우기</Text>
|
|
||||||
</Pressable>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
{confirm && <Text className="mt-1.5 text-right text-[12.5px] font-bold text-ink2">지울까요?</Text>}
|
|
||||||
</Body>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Row({ label, on, onToggle, disabled, children }: { label: string; on: boolean; onToggle: () => void; disabled?: boolean; children: ReactNode }) {
|
|
||||||
return (
|
|
||||||
<View className={`min-h-[44px] flex-row flex-wrap items-center gap-2 border-b border-line py-2 ${on ? '' : 'opacity-60'}`}>
|
|
||||||
<Pressable onPress={onToggle} disabled={disabled} accessibilityRole="checkbox" accessibilityState={{ checked: on }} className="w-[84px] flex-row items-center gap-1.5">
|
|
||||||
<View className={`size-4 items-center justify-center rounded-[4px] border-2 ${on ? 'border-orange bg-orange' : 'border-ink3'}`}>{on && <Text className="text-[10px] leading-3 font-extrabold text-white">✓</Text>}</View>
|
|
||||||
<Text className="text-[14px] font-extrabold text-ink">{label}</Text>
|
|
||||||
</Pressable>
|
|
||||||
{on ? <View className="min-w-0 flex-1 flex-row flex-wrap items-center gap-1.5">{children}</View> : <Text className="text-[13px] font-semibold text-ink3">상관없음</Text>}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 숫자: 휴대폰 숫자 자판엔 '-'가 없을 때가 있어 −/+ 버튼으로 바꾼다 */
|
|
||||||
function Num({ value, onChange, min, max, step = 1, label, disabled }: { value: number; onChange: (v: number) => void; min: number; max: number; step?: number; label: string; disabled?: boolean }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
const set = (v: number) => onChange(Math.min(max, Math.max(min, v)));
|
|
||||||
return (
|
|
||||||
<View className="flex-row items-center overflow-hidden rounded-xl" style={{ backgroundColor: soft.soft }} accessibilityLabel={label}>
|
|
||||||
<Pressable onPress={() => set(value - step)} disabled={disabled || value <= min} hitSlop={4} accessibilityLabel={`${label} 내리기`} className="px-2 py-1.5 disabled:opacity-30">
|
|
||||||
<Text className="text-[15px] font-extrabold text-ink2">−</Text>
|
|
||||||
</Pressable>
|
|
||||||
<Text className="min-w-[28px] text-center text-[13.5px] font-bold text-ink">{value}</Text>
|
|
||||||
<Pressable onPress={() => set(value + step)} disabled={disabled || value >= max} hitSlop={4} accessibilityLabel={`${label} 올리기`} className="px-2 py-1.5 disabled:opacity-30">
|
|
||||||
<Text className="text-[15px] font-extrabold text-ink2">+</Text>
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Choice<T extends string>({ value, options, onChange, label, disabled }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string; disabled?: boolean }) {
|
|
||||||
return (
|
|
||||||
<View className="flex-row gap-1" accessibilityRole="radiogroup" accessibilityLabel={label}>
|
|
||||||
{options.map(([k, word]) => (
|
|
||||||
<Pressable key={k} onPress={() => onChange(k)} disabled={disabled} accessibilityRole="radio" accessibilityState={{ checked: value === k }} className={`rounded-full px-3 py-1.5 ${value === k ? 'bg-orange' : 'bg-[#eef4fc]'}`}>
|
|
||||||
<Text className={`text-[13.5px] font-bold ${value === k ? 'text-white' : 'text-[#28304a]'}`}>{word}</Text>
|
|
||||||
</Pressable>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
type Filled<T> = { [K in keyof T]-?: NonNullable<T[K]> };
|
|
||||||
const DEFAULT_RULE: Filled<MyGakRule> = { temp: [15, 25], rain: 'dry', wind_max: 4, air: 'normal', humidity: [30, 60], slots: ['morning', 'day', 'evening', 'night'] };
|
|
||||||
type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity';
|
|
||||||
|
|
||||||
const condsOf = (r: MyGakRule): Record<Cond, boolean> => ({ temp: !!r.temp, rain: !!r.rain, wind_max: r.wind_max != null, air: !!r.air, humidity: !!r.humidity });
|
|
||||||
|
|
||||||
/** 내 각 아이콘 고르기: 있는 각 아이콘 그대로 */
|
|
||||||
function IconPicker({ value, onPick }: { value: string; onPick: (icon: string) => void }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
const icons = [...new Set([MY_GAK_ICON, ...(usePresets().data ?? []).map((p) => p.icon)])];
|
|
||||||
return (
|
|
||||||
<View className="mt-3">
|
|
||||||
<Text className="font-jua text-[19px] text-ink">아이콘</Text>
|
|
||||||
<ScrollView horizontal showsHorizontalScrollIndicator={false} className="-mx-4" contentContainerClassName="gap-1.5 px-4 pt-2 pb-1">
|
|
||||||
{icons.map((icon) => (
|
|
||||||
<Pressable key={icon} onPress={() => onPick(icon)} accessibilityRole="button" accessibilityState={{ selected: value === icon }} accessibilityLabel={`아이콘 ${icon}`} className={`size-12 items-center justify-center rounded-2xl ${value === icon ? 'bg-orange' : ''}`} style={value === icon ? undefined : { backgroundColor: soft.soft }}>
|
|
||||||
<Ic name={icon} size={32} />
|
|
||||||
</Pressable>
|
|
||||||
))}
|
|
||||||
</ScrollView>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 있는 각을 골라 그 각 조건으로 채운다 */
|
|
||||||
function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
const items = usePresets().data ?? [];
|
|
||||||
if (!items.length) return null;
|
|
||||||
return (
|
|
||||||
<View className="mb-3">
|
|
||||||
<Text className="font-jua text-[19px] text-ink">있는 각에서 불러오기</Text>
|
|
||||||
<ScrollView horizontal showsHorizontalScrollIndicator={false} className="-mx-4" contentContainerClassName="gap-2.5 px-4 pt-2 pb-1">
|
|
||||||
{items.map((p) => (
|
|
||||||
<Pressable key={p.code} onPress={() => onPick(p)} accessibilityRole="button" accessibilityState={{ selected: picked === p.code }} className={`w-[68px] items-center gap-1 rounded-2xl px-1 py-2 ${picked === p.code ? 'bg-orange' : ''}`} style={picked === p.code ? undefined : { backgroundColor: soft.soft }}>
|
|
||||||
<Ic name={p.icon} size={36} />
|
|
||||||
<Text numberOfLines={1} className={`text-[12px] leading-tight font-extrabold ${picked === p.code ? 'text-white' : 'text-ink2'}`}>
|
|
||||||
{p.name}
|
|
||||||
</Text>
|
|
||||||
</Pressable>
|
|
||||||
))}
|
|
||||||
</ScrollView>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */
|
|
||||||
export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) {
|
|
||||||
const { region } = useRegion();
|
|
||||||
const soft = useSoft();
|
|
||||||
const { create, pending, failed } = useMyGak();
|
|
||||||
const [name, setName] = useState(shared?.name ?? '');
|
|
||||||
const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE);
|
|
||||||
const [on, setOn] = useState<Record<Cond, boolean>>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false });
|
|
||||||
const [picked, setPicked] = useState<string | null>(null);
|
|
||||||
const [icon, setIcon] = useState(shared?.icon ?? MY_GAK_ICON);
|
|
||||||
const lock = !!shared;
|
|
||||||
const pick = (p: MyGakPreset) => {
|
|
||||||
setPicked(p.code);
|
|
||||||
setName(p.name);
|
|
||||||
setIcon(p.icon);
|
|
||||||
setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE);
|
|
||||||
setOn(condsOf(p.rule));
|
|
||||||
};
|
|
||||||
const set = <K extends keyof typeof vals>(k: K, v: (typeof vals)[K]) => setVals((x) => ({ ...x, [k]: v }));
|
|
||||||
const toggle = (k: Cond) => setOn((x) => ({ ...x, [k]: !x[k] }));
|
|
||||||
const rule: MyGakRule = { slots: vals.slots, ...(Object.fromEntries((Object.keys(on) as Cond[]).filter((k) => on[k]).map((k) => [k, vals[k]])) as Partial<MyGakRule>) };
|
|
||||||
const valid = Object.values(on).some(Boolean) && vals.slots.length > 0 && (!on.temp || vals.temp[0] < vals.temp[1]) && (!on.humidity || vals.humidity[0] < vals.humidity[1]);
|
|
||||||
const score = useMyGakScores(valid ? [rule] : []).data?.scores?.[0];
|
|
||||||
const title = gakName(name) || '이름 없는 각';
|
|
||||||
const toggleSlot = (s: Slot) =>
|
|
||||||
set(
|
|
||||||
'slots',
|
|
||||||
vals.slots.includes(s)
|
|
||||||
? vals.slots.filter((x) => x !== s)
|
|
||||||
: SLOTS.map(([k]) => k).filter((k) => k === s || vals.slots.includes(k)),
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Body>
|
|
||||||
{shared ? (
|
|
||||||
<Text className="text-[13px] font-bold text-ink2">친구가 보낸 각이에요. {region.name} 기준 점수예요</Text>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<PresetPicker picked={picked} onPick={pick} />
|
|
||||||
<Text className="font-jua text-[19px] text-ink">이름</Text>
|
|
||||||
<TextInput value={name} onChangeText={setName} maxLength={11} placeholder="소맥, 야독, 새우깡" placeholderTextColor={soft.placeholder} accessibilityLabel="이름" className="mt-1.5 rounded-2xl px-3.5 py-2.5 text-[15px] text-ink" style={{ backgroundColor: soft.soft }} />
|
|
||||||
<IconPicker value={icon} onPick={setIcon} />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<Text className="mt-3 font-jua text-[19px] text-ink">조건</Text>
|
|
||||||
<Row label="기온" on={on.temp} onToggle={() => toggle('temp')} disabled={lock}>
|
|
||||||
<Num label="최저 기온" value={vals.temp[0]} min={-20} max={40} disabled={lock} onChange={(v) => set('temp', [v, vals.temp[1]])} />
|
|
||||||
<Text className="text-[13.5px] font-bold text-ink">~</Text>
|
|
||||||
<Num label="최고 기온" value={vals.temp[1]} min={-20} max={40} disabled={lock} onChange={(v) => set('temp', [vals.temp[0], v])} />
|
|
||||||
<Text className="text-[13.5px] font-bold text-ink">° 체감</Text>
|
|
||||||
</Row>
|
|
||||||
<Row label="비" on={on.rain} onToggle={() => toggle('rain')} disabled={lock}>
|
|
||||||
<Choice
|
|
||||||
label="비"
|
|
||||||
value={vals.rain}
|
|
||||||
disabled={lock}
|
|
||||||
onChange={(v) => set('rain', v)}
|
|
||||||
options={[
|
|
||||||
['dry', '안 와야'],
|
|
||||||
['wet', '와야'],
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
</Row>
|
|
||||||
<Row label="바람" on={on.wind_max} onToggle={() => toggle('wind_max')} disabled={lock}>
|
|
||||||
<Text className="text-[13.5px] font-bold text-ink">초속</Text>
|
|
||||||
<Num label="바람 상한" value={vals.wind_max} min={1} max={20} disabled={lock} onChange={(v) => set('wind_max', v)} />
|
|
||||||
<Text className="text-[13.5px] font-bold text-ink">m 이하</Text>
|
|
||||||
</Row>
|
|
||||||
<Row label="미세먼지" on={on.air} onToggle={() => toggle('air')} disabled={lock}>
|
|
||||||
<Choice
|
|
||||||
label="미세먼지"
|
|
||||||
value={vals.air}
|
|
||||||
disabled={lock}
|
|
||||||
onChange={(v) => set('air', v)}
|
|
||||||
options={[
|
|
||||||
['good', '좋음만'],
|
|
||||||
['normal', '보통까지'],
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
</Row>
|
|
||||||
<Row label="습도" on={on.humidity} onToggle={() => toggle('humidity')} disabled={lock}>
|
|
||||||
<Num label="최저 습도" value={vals.humidity[0]} min={0} max={100} step={5} disabled={lock} onChange={(v) => set('humidity', [v, vals.humidity[1]])} />
|
|
||||||
<Text className="text-[13.5px] font-bold text-ink">~</Text>
|
|
||||||
<Num label="최고 습도" value={vals.humidity[1]} min={0} max={100} step={5} disabled={lock} onChange={(v) => set('humidity', [vals.humidity[0], v])} />
|
|
||||||
<Text className="text-[13.5px] font-bold text-ink">%</Text>
|
|
||||||
</Row>
|
|
||||||
<View className="flex-row flex-wrap items-center gap-1.5 py-2.5">
|
|
||||||
<Text className="w-[84px] text-[14px] font-extrabold text-ink">시간대</Text>
|
|
||||||
{SLOTS.map(([k, word]) => (
|
|
||||||
<Pressable key={k} onPress={() => toggleSlot(k)} disabled={lock} accessibilityRole="button" accessibilityState={{ selected: vals.slots.includes(k) }} className={`rounded-full px-3 py-1.5 ${vals.slots.includes(k) ? 'bg-orange' : 'bg-[#eef4fc]'}`}>
|
|
||||||
<Text className={`text-[13.5px] font-bold ${vals.slots.includes(k) ? 'text-white' : 'text-[#28304a]'}`}>{word}</Text>
|
|
||||||
</Pressable>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
<View className="mt-2 gap-1.5 rounded-[20px] p-3.5" style={{ backgroundColor: soft.soft }}>
|
|
||||||
<View className="flex-row items-center gap-2">
|
|
||||||
<Ic name={icon} size={32} />
|
|
||||||
<Text className="font-jua text-[20px] text-ink">{title}</Text>
|
|
||||||
<Score s={valid ? score : undefined} big />
|
|
||||||
</View>
|
|
||||||
{valid ? <Reasons s={score} /> : <Text className="text-[12.5px] font-semibold text-ink3">조건과 시간대를 하나 이상 골라요</Text>}
|
|
||||||
</View>
|
|
||||||
{failed && <Text className="mt-2 text-xs font-bold text-heart">저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요</Text>}
|
|
||||||
<Pressable disabled={!valid || !gakName(name) || pending} onPress={() => create({ name, icon, rule }, onDone)} className="mt-3.5 rounded-2xl bg-orange py-3 disabled:opacity-45">
|
|
||||||
<Text className="text-center font-jua text-[17px] text-white">{shared ? '내 각으로 가져오기' : '내 각으로 저장'}</Text>
|
|
||||||
</Pressable>
|
|
||||||
</Body>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
import Svg, { Circle, Path } from 'react-native-svg';
|
|
||||||
|
|
||||||
export const HEART = 'M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z';
|
|
||||||
|
|
||||||
type P = { size: number; color: string };
|
|
||||||
|
|
||||||
export function HeartIcon({ size, color, filled }: P & { filled: boolean }) {
|
|
||||||
return (
|
|
||||||
<Svg viewBox="0 0 24 24" width={size} height={size} fill={filled ? color : 'none'} stroke={color} strokeWidth={1.9}>
|
|
||||||
<Path d={HEART} />
|
|
||||||
</Svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function CommentIcon({ size, color }: P) {
|
|
||||||
return (
|
|
||||||
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={1.9} strokeLinejoin="round">
|
|
||||||
<Path d="M20.5 12a8.5 8.5 0 0 1-12.6 7.4L3.5 20.5l1.2-4.2A8.5 8.5 0 1 1 20.5 12z" />
|
|
||||||
</Svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SendIcon({ size, color }: P) {
|
|
||||||
return (
|
|
||||||
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<Path d="M21 3 10 14M21 3l-6.5 18-4-7.5L3 9.5z" />
|
|
||||||
</Svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function CameraIcon({ size, color }: P) {
|
|
||||||
return (
|
|
||||||
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<Path d="M4 8.5A1.5 1.5 0 0 1 5.5 7h2.2l1.5-2h5.6l1.5 2h2.2A1.5 1.5 0 0 1 20 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 17.5z" />
|
|
||||||
<Circle cx={12} cy={13} r={3.5} />
|
|
||||||
</Svg>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
import { useEffect } from 'react';
|
|
||||||
import { View } from 'react-native';
|
|
||||||
import Animated, { Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withTiming } from 'react-native-reanimated';
|
|
||||||
import Svg, { Path } from 'react-native-svg';
|
|
||||||
|
|
||||||
import { HEART } from '@/components/post/icons';
|
|
||||||
|
|
||||||
// 튀어 나가는 작은 하트: x·y 이동, 회전, 색 (웹 BURST)
|
|
||||||
const BURST: [number, number, number, string][] = [
|
|
||||||
[-86, -60, -24, '#ff3b5c'],
|
|
||||||
[84, -66, 22, '#ff8e4e'],
|
|
||||||
[-104, 18, -40, '#ffc86e'],
|
|
||||||
[102, 24, 36, '#ff3b5c'],
|
|
||||||
[-48, -104, -8, '#ff8aa0'],
|
|
||||||
[52, -100, 12, '#ffc86e'],
|
|
||||||
];
|
|
||||||
|
|
||||||
function Bit({ dx, dy, rot, color }: { dx: number; dy: number; rot: number; color: string }) {
|
|
||||||
const p = useSharedValue(0);
|
|
||||||
useEffect(() => {
|
|
||||||
p.value = withDelay(80, withTiming(1, { duration: 900, easing: Easing.bezier(0.2, 0.8, 0.3, 1) }));
|
|
||||||
}, [p]);
|
|
||||||
const style = useAnimatedStyle(() => ({
|
|
||||||
opacity: interpolate(p.value, [0, 0.25, 1], [0, 1, 0]),
|
|
||||||
transform: [{ translateX: dx * p.value }, { translateY: dy * p.value }, { scale: interpolate(p.value, [0, 1], [0.4, 1.1]) }, { rotate: `${rot * p.value}deg` }],
|
|
||||||
}));
|
|
||||||
return (
|
|
||||||
<Animated.View style={[{ position: 'absolute' }, style]}>
|
|
||||||
<Svg viewBox="0 0 24 24" width={20} height={20} fill={color}>
|
|
||||||
<Path d={HEART} />
|
|
||||||
</Svg>
|
|
||||||
</Animated.View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Toast() {
|
|
||||||
const p = useSharedValue(0);
|
|
||||||
useEffect(() => {
|
|
||||||
p.value = withTiming(1, { duration: 1300, easing: Easing.bezier(0.2, 0.9, 0.3, 1) });
|
|
||||||
}, [p]);
|
|
||||||
const style = useAnimatedStyle(() => ({
|
|
||||||
opacity: interpolate(p.value, [0, 0.18, 0.78, 1], [0, 1, 1, 0]),
|
|
||||||
transform: [{ translateY: interpolate(p.value, [0, 0.18, 0.78, 1], [14, 0, 0, -8]) }, { scale: interpolate(p.value, [0, 0.18, 0.3, 1], [0.85, 1.06, 1, 1]) }],
|
|
||||||
}));
|
|
||||||
return (
|
|
||||||
<Animated.View className="absolute top-[58%] rounded-full bg-white px-4 py-2" style={[{ boxShadow: '0 8px 18px rgb(40 48 74 / 0.18)' }, style]}>
|
|
||||||
<Animated.Text className="font-jua text-[17px] text-heart">좋아요했어요!</Animated.Text>
|
|
||||||
</Animated.View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 좋아요 때 하트 조각이 튀어 나가고 '좋아요했어요!' 가 떴다 사라진다 */
|
|
||||||
export function LikeBurst() {
|
|
||||||
const reduce = useReducedMotion();
|
|
||||||
if (reduce) return null;
|
|
||||||
return (
|
|
||||||
<View pointerEvents="none" className="absolute inset-0 items-center justify-center" accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
|
|
||||||
{BURST.map(([dx, dy, rot, color], k) => (
|
|
||||||
<Bit key={k} dx={dx} dy={dy} rot={rot} color={color} />
|
|
||||||
))}
|
|
||||||
<Toast />
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
import type { ReactNode } from 'react';
|
|
||||||
import { ScrollView, View, type NativeScrollEvent, type NativeSyntheticEvent } from 'react-native';
|
|
||||||
|
|
||||||
/** 옆으로 한 장씩 넘기는 슬라이드 (웹 Embla 캐러셀 대신 가로 paging ScrollView) */
|
|
||||||
export function Pager({ width, height, onIndex, children }: { width: number; height: number; onIndex: (i: number) => void; children: ReactNode[] }) {
|
|
||||||
const onEnd = (e: NativeSyntheticEvent<NativeScrollEvent>) => onIndex(Math.round(e.nativeEvent.contentOffset.x / width));
|
|
||||||
return (
|
|
||||||
<ScrollView horizontal pagingEnabled showsHorizontalScrollIndicator={false} scrollEnabled={children.length > 1} onMomentumScrollEnd={onEnd} style={{ width, height }}>
|
|
||||||
{children.map((c, i) => (
|
|
||||||
<View key={i} style={{ width, height }}>
|
|
||||||
{c}
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</ScrollView>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 슬라이드 위치 점 */
|
|
||||||
export function Dots({ n, index }: { n: number; index: number }) {
|
|
||||||
if (n < 2) return null;
|
|
||||||
const items = Array.from({ length: n }, (_, i) => i);
|
|
||||||
return (
|
|
||||||
<View className="flex-row justify-center gap-1.5 pt-2" accessibilityElementsHidden>
|
|
||||||
{items.map((i) => (
|
|
||||||
<View key={i} className={`h-1.5 rounded-full ${i === index ? 'w-4 bg-orange' : 'w-1.5 bg-ink3/40'}`} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,240 +0,0 @@
|
|||||||
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
||||||
import { PostType, type PostData, type ResFeed } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query';
|
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
|
||||||
import { useEffect, useRef, useState } from 'react';
|
|
||||||
import { Animated, Pressable, View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import Svg, { Path } from 'react-native-svg';
|
|
||||||
import { useCSSVariable } from 'uniwind';
|
|
||||||
|
|
||||||
import { CommentIcon, HEART, HeartIcon, SendIcon } from '@/components/post/icons';
|
|
||||||
import { LikeBurst } from '@/components/post/like-burst';
|
|
||||||
import { Dots, Pager } from '@/components/post/pager';
|
|
||||||
import { slideBg, SlideView, type Slide } from '@/components/post/slides';
|
|
||||||
import { Ic, Skel } from '@/components/ui';
|
|
||||||
import { track } from '@/lib/analytics';
|
|
||||||
import { useSheet } from '@/lib/sheet';
|
|
||||||
import { useShare } from '@/lib/share-image';
|
|
||||||
import { SITE_URL } from '@/lib/site';
|
|
||||||
|
|
||||||
const ACCOUNTS: Partial<Record<PostType, readonly [string, string]>> = {
|
|
||||||
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
|
|
||||||
[PostType.GAK]: ['오늘의 각', 'rabbit'],
|
|
||||||
[PostType.SUNSET]: ['노을', 'sunset'],
|
|
||||||
[PostType.SEASON]: ['계절 소식', 'maple'],
|
|
||||||
[PostType.EVENT]: ['가까운 행사', 'fireworks'],
|
|
||||||
[PostType.TIP]: ['날씨 상식', 'bulb'],
|
|
||||||
[PostType.WEEK]: ['주말 예보', 'calendar'],
|
|
||||||
[PostType.ALERT]: ['생활 알림', 'umbrella'],
|
|
||||||
[PostType.TOMORROW]: ['내일 미리보기', 'moon'],
|
|
||||||
[PostType.QUOTE]: ['오늘의 한 문장', 'letter'],
|
|
||||||
[PostType.WEEKEND_PLAN]: ['주말 플랜', 'calendar'],
|
|
||||||
[PostType.AIR]: ['미세먼지', 'vent'],
|
|
||||||
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
|
|
||||||
[PostType.MOON]: ['오늘 밤 달', 'moon'],
|
|
||||||
[PostType.UV]: ['자외선', 'glasses'],
|
|
||||||
[PostType.CARD]: ['날씨각 카드', 'stars'],
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 앱이 그릴 줄 아는 글 종류만 (히어로·띠처럼 피드 반응 칸으로만 오는 종류는 뺀다) */
|
|
||||||
export const isAppPost = (p: PostData) => p.post_type in ACCOUNTS;
|
|
||||||
|
|
||||||
type PostProps = { post: PostData };
|
|
||||||
|
|
||||||
/** 받아 둔 피드 데이터에도 좋아요를 반영한다. 안 하면 다른 탭에 다녀왔을 때 예전 값으로 다시 그려진다 */
|
|
||||||
function patchFeed(queryClient: QueryClient, postId: number, patch: Partial<PostData>) {
|
|
||||||
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
|
|
||||||
feed?.posts ? { ...feed, posts: feed.posts.map((p) => (p.post_id === postId ? { ...p, ...patch } : p)) } : feed,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 한 줄 카드 (흐린 날 노을처럼 큰 그림이 필요 없는 소식) */
|
|
||||||
function LineCard({ post }: PostProps) {
|
|
||||||
const [account, avatar] = ACCOUNTS[post.post_type] ?? ['날씨각', 'sun'];
|
|
||||||
return (
|
|
||||||
<View className="mx-3 mt-3.5 flex-row items-center gap-3 rounded-[22px] border-b-4 border-shade bg-card px-4 py-3" accessibilityLabel={post.title}>
|
|
||||||
<Ic name={post.icon || avatar} size={40} />
|
|
||||||
<View className="flex-1">
|
|
||||||
<Text className="text-xs font-bold text-ink3">{account}</Text>
|
|
||||||
<Text className="text-sm text-ink2">
|
|
||||||
<Text className="font-jua text-base text-ink">{post.title}</Text> {post.caption}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */
|
|
||||||
export function PostCard({ post }: PostProps) {
|
|
||||||
return post.size === 'line' ? <LineCard post={post} /> : <FullCard post={post} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** FullCard 와 같은 틀(머리줄·4:5 그림·버튼줄·글 한 줄)의 스켈레톤 */
|
|
||||||
export function PostCardSkel() {
|
|
||||||
return (
|
|
||||||
<View className="mt-3.5 border-y border-line bg-card" accessibilityElementsHidden>
|
|
||||||
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
|
|
||||||
<View className="size-[34px] rounded-full bg-skel" />
|
|
||||||
<View className="gap-1.5">
|
|
||||||
<Skel className="w-12" />
|
|
||||||
<Skel className="w-16" />
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
<View className="aspect-[4/5] bg-skel" />
|
|
||||||
<View className="flex-row gap-3.5 px-3 pt-2.5 pb-1">
|
|
||||||
<View className="size-7 rounded-full bg-skel" />
|
|
||||||
<View className="size-7 rounded-full bg-skel" />
|
|
||||||
<View className="size-7 rounded-full bg-skel" />
|
|
||||||
</View>
|
|
||||||
<View className="gap-2 px-3 pt-1 pb-3">
|
|
||||||
<Skel className="w-20" />
|
|
||||||
<Skel className="w-4/5" />
|
|
||||||
<Skel className="w-32" />
|
|
||||||
<Skel className="w-8" />
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 좋아요 때 가운데에 커졌다 사라지는 하트 */
|
|
||||||
function HeartPop() {
|
|
||||||
const [v] = useState(() => new Animated.Value(0));
|
|
||||||
useEffect(() => {
|
|
||||||
Animated.timing(v, { toValue: 1, duration: 800, useNativeDriver: true }).start();
|
|
||||||
}, [v]);
|
|
||||||
const opacity = v.interpolate({ inputRange: [0, 0.25, 0.6, 1], outputRange: [0, 1, 1, 0] });
|
|
||||||
const scale = v.interpolate({ inputRange: [0, 0.25, 0.6, 1], outputRange: [0.3, 1.1, 1, 1] });
|
|
||||||
return (
|
|
||||||
<Animated.View pointerEvents="none" className="absolute inset-0 items-center justify-center" style={{ opacity, transform: [{ scale }] }}>
|
|
||||||
<Svg viewBox="0 0 24 24" width={112} height={112} fill="#ff3b5c">
|
|
||||||
<Path d={HEART} />
|
|
||||||
</Svg>
|
|
||||||
</Animated.View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FullCard({ post }: PostProps) {
|
|
||||||
const { open } = useSheet();
|
|
||||||
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
|
|
||||||
const liked = !!post.liked;
|
|
||||||
const likeCount = post.like_count;
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const like = useMutation(likePostMutation());
|
|
||||||
const unlike = useMutation(unlikePostMutation());
|
|
||||||
const [width, setWidth] = useState(0);
|
|
||||||
const [index, setIndex] = useState(0);
|
|
||||||
const [pop, setPop] = useState(0);
|
|
||||||
const [likeFailed, setLikeFailed] = useState(0);
|
|
||||||
const lastTap = useRef(0);
|
|
||||||
const [account, avatar] = ACCOUNTS[post.post_type] ?? ['날씨각', 'sun'];
|
|
||||||
const n = post.slides.length;
|
|
||||||
const patch = (values: Partial<PostData>) => patchFeed(queryClient, post.post_id, values);
|
|
||||||
const comments = () => open({ type: 'comments', postId: post.post_id });
|
|
||||||
const shot = useRef<View>(null);
|
|
||||||
// 지금 보고 있는 슬라이드를 이미지로
|
|
||||||
const shareView = useShare();
|
|
||||||
const share = () => void shareView(shot, { title: post.title, message: `${post.title} · 날씨각 ${SITE_URL}` });
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!likeFailed) return;
|
|
||||||
const t = setTimeout(() => setLikeFailed(0), 2500);
|
|
||||||
return () => clearTimeout(t);
|
|
||||||
}, [likeFailed]);
|
|
||||||
|
|
||||||
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
|
|
||||||
// 좋아요는 로그인 없이 된다 (웹과 같이)
|
|
||||||
const setLike = (on: boolean) => {
|
|
||||||
if (on === liked || like.isPending || unlike.isPending) return;
|
|
||||||
if (on) setPop((p) => p + 1);
|
|
||||||
setLikeFailed(0);
|
|
||||||
patch({ liked: on, like_count: likeCount + (on ? 1 : -1) });
|
|
||||||
const revert = () => {
|
|
||||||
patch({ liked, like_count: likeCount });
|
|
||||||
setLikeFailed(Date.now());
|
|
||||||
};
|
|
||||||
(on ? like : unlike).mutate(
|
|
||||||
{ path: { post_id: post.post_id } },
|
|
||||||
{
|
|
||||||
onSuccess: (res) => {
|
|
||||||
if (!res.result?.success) return revert();
|
|
||||||
patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) });
|
|
||||||
if (on) track('like', { content_type: 'post', item_id: post.post_id });
|
|
||||||
},
|
|
||||||
onError: revert,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const onTap = () => {
|
|
||||||
const now = Date.now();
|
|
||||||
if (now - lastTap.current < 320) {
|
|
||||||
if (liked) setPop((p) => p + 1);
|
|
||||||
else setLike(true);
|
|
||||||
}
|
|
||||||
lastTap.current = now;
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={post.title}>
|
|
||||||
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
|
|
||||||
<View className="size-[34px] rounded-full p-0.5">
|
|
||||||
<LinearGradient colors={['#ff7a45', '#ffc86e', '#8fcaff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={{ position: 'absolute', inset: 0, borderRadius: 17 }} />
|
|
||||||
<View className="flex-1 items-center justify-center rounded-full bg-card">
|
|
||||||
<Ic name={avatar} size={22} />
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
<View>
|
|
||||||
<Text className="text-sm leading-tight font-extrabold text-ink">날씨각</Text>
|
|
||||||
<Text className="text-xs font-semibold text-ink2">{account}</Text>
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
<Pressable onPress={onTap} onLayout={(e) => setWidth(e.nativeEvent.layout.width)} className="aspect-[4/5] overflow-hidden" accessibilityLabel={n > 1 ? `슬라이드 ${n}장, 옆으로 넘겨 보세요` : undefined}>
|
|
||||||
<View ref={shot} collapsable={false}>
|
|
||||||
{width > 0 && (
|
|
||||||
<Pager width={width} height={(width * 5) / 4} onIndex={setIndex}>
|
|
||||||
{post.slides.map((s: Slide, i) => (
|
|
||||||
<SlideView key={i} slide={s} bg={slideBg(post, s)} />
|
|
||||||
))}
|
|
||||||
</Pager>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
{n > 1 && (
|
|
||||||
<View pointerEvents="none" className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px]">
|
|
||||||
<Text className="text-xs font-extrabold text-white">
|
|
||||||
{index + 1}/{n}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
{pop > 0 && <HeartPop key={pop} />}
|
|
||||||
{pop > 0 && <LikeBurst key={`b${pop}`} />}
|
|
||||||
{likeFailed > 0 && (
|
|
||||||
<View pointerEvents="none" className="absolute inset-x-0 bottom-4 items-center px-4" accessibilityRole="alert">
|
|
||||||
<Text className="overflow-hidden rounded-full bg-[rgb(30_36_56/0.82)] px-3.5 py-2 text-[13px] font-bold text-white">{liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요.</Text>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</Pressable>
|
|
||||||
<Dots n={n} index={index} />
|
|
||||||
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
|
|
||||||
<Pressable onPress={() => setLike(!liked)} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요">
|
|
||||||
<HeartIcon size={26} color={liked ? heart : ink} filled={liked} />
|
|
||||||
</Pressable>
|
|
||||||
<Pressable onPress={comments} hitSlop={8} accessibilityRole="button" accessibilityLabel="댓글 보기">
|
|
||||||
<CommentIcon size={26} color={ink} />
|
|
||||||
</Pressable>
|
|
||||||
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="보내기">
|
|
||||||
<SendIcon size={26} color={ink} />
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
<Text className="px-3 py-0.5 text-sm font-extrabold text-ink">좋아요 {likeCount.toLocaleString()}개</Text>
|
|
||||||
<Text className="px-3 py-0.5 text-sm text-ink">
|
|
||||||
<Text className="font-extrabold">날씨각 </Text>
|
|
||||||
{post.caption}
|
|
||||||
</Text>
|
|
||||||
<Pressable onPress={comments}>
|
|
||||||
<Text className="px-3 pt-[3px] text-sm font-semibold text-ink3">{post.comment_count ? `댓글 ${post.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
|
|
||||||
</Pressable>
|
|
||||||
<Text className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-ink3">오늘</Text>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import type { PinnedKey } from '@nalssigak/shared/lib/analytics';
|
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
|
||||||
import { useRef, type ReactNode } from 'react';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
import { useCSSVariable } from 'uniwind';
|
|
||||||
|
|
||||||
import { CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import { Ic } from '@/components/ui';
|
|
||||||
import { usePinnedLike } from '@/lib/pinned-like';
|
|
||||||
import { useSheet } from '@/lib/sheet';
|
|
||||||
import { useShare } from '@/lib/share-image';
|
|
||||||
import { SITE_URL } from '@/lib/site';
|
|
||||||
|
|
||||||
type Props = { title: string; account: string; avatar: string; caption?: string; more?: ReactNode; pinned?: { key: PinnedKey; post?: PostReaction | null }; children: ReactNode };
|
|
||||||
|
|
||||||
/** 오늘의 각처럼 포스트 틀(머리줄·버튼줄·글 한 줄)만 빌려 쓰는 카드 (웹 PostFrame). 좋아요·댓글은 피드의 반응 칸(pinned)에 붙는다 */
|
|
||||||
export function PostFrame({ title, account, avatar, caption, more, pinned, children }: Props) {
|
|
||||||
const { open } = useSheet();
|
|
||||||
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
|
|
||||||
const like = usePinnedLike(pinned?.key ?? 'gak_post', pinned?.post);
|
|
||||||
const postId = pinned?.post?.post_id;
|
|
||||||
const shot = useRef<View>(null);
|
|
||||||
const shareView = useShare();
|
|
||||||
const share = () => void shareView(shot, { title, message: `${title} · 날씨각 ${SITE_URL}` });
|
|
||||||
|
|
||||||
return (
|
|
||||||
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={title}>
|
|
||||||
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
|
|
||||||
<View className="size-[34px] rounded-full p-0.5">
|
|
||||||
<LinearGradient colors={['#ff7a45', '#ffc86e', '#8fcaff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={{ position: 'absolute', inset: 0, borderRadius: 17 }} />
|
|
||||||
<View className="flex-1 items-center justify-center rounded-full bg-card">
|
|
||||||
<Ic name={avatar} size={22} />
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
<View>
|
|
||||||
<Text className="text-sm leading-tight font-extrabold text-ink">날씨각</Text>
|
|
||||||
<Text className="text-xs font-semibold text-ink2">{account}</Text>
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
<View ref={shot} collapsable={false}>
|
|
||||||
{children}
|
|
||||||
</View>
|
|
||||||
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
|
|
||||||
{postId != null && (
|
|
||||||
<>
|
|
||||||
<Pressable onPress={like.toggle} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: like.liked }} accessibilityLabel="좋아요">
|
|
||||||
<HeartIcon size={26} color={like.liked ? heart : ink} filled={like.liked} />
|
|
||||||
</Pressable>
|
|
||||||
<Pressable onPress={() => open({ type: 'comments', postId })} hitSlop={8} accessibilityRole="button" accessibilityLabel="댓글 보기">
|
|
||||||
<CommentIcon size={26} color={ink} />
|
|
||||||
</Pressable>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="보내기">
|
|
||||||
<SendIcon size={26} color={ink} />
|
|
||||||
</Pressable>
|
|
||||||
{more != null && <View className="ml-auto">{more}</View>}
|
|
||||||
</View>
|
|
||||||
{postId != null && (
|
|
||||||
<Text className={`px-3 py-0.5 text-sm font-extrabold ${like.failed ? 'text-heart' : 'text-ink'}`} accessibilityRole={like.failed ? 'alert' : undefined}>
|
|
||||||
{like.failed ? '좋아요를 반영하지 못했어요. 다시 해 주세요.' : `좋아요 ${like.count.toLocaleString()}개`}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
{!!caption && (
|
|
||||||
<Text className="px-3 pt-0.5 pb-3 text-sm text-ink">
|
|
||||||
<Text className="font-extrabold">날씨각 </Text>
|
|
||||||
{caption}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
{postId != null && (
|
|
||||||
<Pressable onPress={() => open({ type: 'comments', postId })}>
|
|
||||||
<Text className="px-3 pb-3 text-sm font-semibold text-ink3">{pinned?.post?.comment_count ? `댓글 ${pinned.post.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
|
|
||||||
</Pressable>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,285 +0,0 @@
|
|||||||
import type { GakSlide, HoursSlide, ImageSlide, PlanSlide, PostData, RowsSlide, SunsetSlide, WeekSlide } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { PostType, SlotTone } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { cardBg, clockShort } from '@nalssigak/shared/lib';
|
|
||||||
import type { SlideBg } from '@nalssigak/shared/lib/types';
|
|
||||||
import { deg } from '@nalssigak/shared/lib/weatherText';
|
|
||||||
import { Image } from 'expo-image';
|
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
|
||||||
import { useState, type ReactNode } from 'react';
|
|
||||||
import { Pressable, StyleSheet, View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import Svg, { Polygon } from 'react-native-svg';
|
|
||||||
|
|
||||||
import { MoonArt } from '@/components/moon';
|
|
||||||
import { Credit, Ic, Rows, Thumb } from '@/components/ui';
|
|
||||||
import { CARD_BG } from '@/lib/colors';
|
|
||||||
import { useSheet } from '@/lib/sheet';
|
|
||||||
import { apiUri, imageUri } from '@/lib/site';
|
|
||||||
import { useSky } from '@/lib/sky';
|
|
||||||
|
|
||||||
export type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide | ImageSlide;
|
|
||||||
|
|
||||||
type Stops = readonly [string, string, ...string[]];
|
|
||||||
|
|
||||||
const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac'];
|
|
||||||
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac', glasses: 'butter' };
|
|
||||||
const DARK = new Set<SlideBg>(['dusk', 'night']);
|
|
||||||
|
|
||||||
const chunk = <T,>(items: T[], n: number) => Array.from({ length: Math.ceil(items.length / n) }, (_, i) => items.slice(i * n, i * n + n));
|
|
||||||
|
|
||||||
// 노을 하늘 상황(1 가려짐 2 낮은 구름 3 물들 구름 적음 4 넓게 물듦 5 두꺼움)별 하늘, 시간 칸 색 (웹 .b-sit-*, .b-cut-*)
|
|
||||||
const SIT_BG: Record<number, { colors: Stops; locations: readonly [number, number, ...number[]] }> = {
|
|
||||||
1: { colors: ['#6f7690', '#9aa0b4', '#b9b4c0'], locations: [0, 0.55, 1] },
|
|
||||||
2: { colors: ['#7a7f9c', '#a7a3bb', '#c9b8b8'], locations: [0, 0.55, 1] },
|
|
||||||
3: { colors: ['#4b5aa8', '#7f86c6', '#e9b9a8', '#ffb27a', '#ff8a4c'], locations: [0, 0.38, 0.68, 0.86, 1] },
|
|
||||||
4: { colors: ['#5b3f9e', '#c2559a', '#ff7a6a', '#ffb35c'], locations: [0, 0.4, 0.68, 1] },
|
|
||||||
5: { colors: ['#6a6aa0', '#a98fb4', '#e3b1a0'], locations: [0, 0.55, 1] },
|
|
||||||
};
|
|
||||||
const CUT_BG: Stops[] = [
|
|
||||||
['#9fd0ff', '#ffd79a', '#ff9a5c'],
|
|
||||||
['#8f7cf0', '#ff6f8e', '#ff8a4c'],
|
|
||||||
['#34306e', '#7a5cc8'],
|
|
||||||
];
|
|
||||||
// 건물 실루엣 (웹 .b-skyline clip-path)
|
|
||||||
const SKYLINE = '0,55 8,55 8,30 15,30 15,50 22,50 22,10 28,10 28,45 36,45 36,25 44,25 44,55 52,55 52,35 60,35 60,5 66,5 66,40 74,40 74,20 82,20 82,50 90,50 90,30 100,30 100,100 0,100';
|
|
||||||
|
|
||||||
const HOUR_TONE: Record<string, { bg: string; edge: string }> = {
|
|
||||||
[SlotTone.NIGHT]: { bg: '#e3e7ff', edge: '#c7cff5' },
|
|
||||||
[SlotTone.SUNSET]: { bg: '#ffe3d2', edge: '#ffc19f' },
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 배경색은 API에 없어 글 종류·아이콘으로 고른다 */
|
|
||||||
export function slideBg(post: PostData, slide: Slide): SlideBg {
|
|
||||||
if (slide.kind === 'hours' || slide.kind === 'image') return 'sky';
|
|
||||||
if (slide.kind === 'sunset') return 'dusk';
|
|
||||||
if (slide.kind === 'week') return 'mint';
|
|
||||||
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter';
|
|
||||||
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length];
|
|
||||||
if (post.post_type === PostType.EVENT || post.post_type === PostType.MOON) return 'night';
|
|
||||||
if (post.post_type === PostType.TIP) return 'sky';
|
|
||||||
if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac';
|
|
||||||
if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint';
|
|
||||||
return (ROW_ICON_BG[slide.icon] ?? cardBg(slide.icon, post.post_id)) as SlideBg;
|
|
||||||
}
|
|
||||||
|
|
||||||
function Base({ colors, locations, children }: { colors: Stops; locations?: readonly [number, number, ...number[]]; children: ReactNode }) {
|
|
||||||
return (
|
|
||||||
<View className="flex-1 px-5 py-[22px]">
|
|
||||||
<LinearGradient colors={colors} locations={locations} style={StyleSheet.absoluteFill} />
|
|
||||||
{children}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Eyebrow({ children, light, className }: { children: ReactNode; light?: boolean; className?: string }) {
|
|
||||||
return <Text className={`text-[13px] font-extrabold opacity-75 ${light ? 'text-white' : 'text-ink'} ${className ?? ''}`}>{children}</Text>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function Big({ children, light, className }: { children: ReactNode; light?: boolean; className?: string }) {
|
|
||||||
return <Text className={`mt-1.5 font-jua text-[29px] leading-tight ${light ? 'text-white' : 'text-ink'} ${className ?? ''}`}>{children}</Text>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function Pic({ name, widthPct = 42 }: { name: string; widthPct?: number }) {
|
|
||||||
return (
|
|
||||||
<View pointerEvents="none" className="absolute top-[30%] right-3.5 aspect-square" style={{ width: `${widthPct}%` }}>
|
|
||||||
<Ic name={name} size={0} style={{ width: '100%', height: '100%' }} />
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 달 포스트 밤하늘 별: [left %, top %, 크기]
|
|
||||||
const STARS: [number, number, number][] = [
|
|
||||||
[8, 34, 2], [18, 52, 1.5], [30, 40, 2.5], [44, 30, 1.5], [52, 58, 2], [62, 22, 1.5], [90, 18, 2], [94, 44, 1.5], [12, 70, 1.5], [38, 66, 2], [76, 74, 1.5], [86, 64, 2], [24, 12, 1.5], [70, 10, 2.5],
|
|
||||||
];
|
|
||||||
|
|
||||||
/** 달 포스트 그림: 아이콘 대신 오늘 밤 실제 모양의 달과 별 */
|
|
||||||
function MoonPic({ pct, waxing }: { pct: number; waxing: boolean }) {
|
|
||||||
const [w, setW] = useState(0);
|
|
||||||
return (
|
|
||||||
<View pointerEvents="none" style={StyleSheet.absoluteFill} onLayout={(e) => setW(e.nativeEvent.layout.width)}>
|
|
||||||
{STARS.map(([x, y, s]) => (
|
|
||||||
<View key={`${x},${y}`} className="absolute rounded-full bg-white opacity-80" style={{ left: `${x}%`, top: `${y}%`, width: s, height: s }} />
|
|
||||||
))}
|
|
||||||
{w > 0 && (
|
|
||||||
<View className="absolute top-[22%] right-0">
|
|
||||||
<MoonArt pct={pct} waxing={waxing} size={w * 0.6} />
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
|
||||||
const { open } = useSheet();
|
|
||||||
const { kind } = useSky();
|
|
||||||
const palette = CARD_BG[kind === 'night' ? 'night' : 'day'];
|
|
||||||
const colors = palette[bg] ?? palette.sky;
|
|
||||||
const light = DARK.has(bg);
|
|
||||||
|
|
||||||
if (slide.kind === 'hours') {
|
|
||||||
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]));
|
|
||||||
const lo = Math.min(...temps);
|
|
||||||
const span = Math.max(...temps) - lo || 1;
|
|
||||||
return (
|
|
||||||
<Base colors={palette.sky}>
|
|
||||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
|
||||||
<Big>{slide.line}</Big>
|
|
||||||
{/* 웹 grid-cols-4: 4칸씩 줄을 나눈다 */}
|
|
||||||
<View className="mt-3.5 flex-1 gap-2">
|
|
||||||
{chunk(slide.hours, 4).map((row) => (
|
|
||||||
<View key={row[0].label} className="flex-1 flex-row gap-2">
|
|
||||||
{row.map((h) => {
|
|
||||||
const tone = HOUR_TONE[h.tone ?? ''];
|
|
||||||
return (
|
|
||||||
<View key={h.label} className={`flex-1 items-center justify-between overflow-hidden rounded-[18px] px-1 pt-2.5 pb-[9px] ${tone ? '' : 'border-b-[5px] border-shade bg-card'}`} style={tone ? { backgroundColor: tone.bg, borderBottomWidth: 5, borderColor: tone.edge } : undefined}>
|
|
||||||
{h.temp_c != null && <LinearGradient colors={['rgba(255,122,69,0.1)', 'rgba(255,122,69,0.34)']} style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: `${20 + ((h.temp_c - lo) / span) * 70}%` }} />}
|
|
||||||
<Text className={`text-xs font-bold ${tone ? 'text-[#5a6380]' : 'text-ink2'}`}>{h.label}</Text>
|
|
||||||
<Ic name={h.icon} size={34} />
|
|
||||||
<Text className={`font-bagel text-[21px] ${tone ? 'text-[#28304a]' : 'text-ink'}`}>{deg(h.temp_c)}</Text>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
{/* 마지막 줄이 모자라면 빈 칸으로 너비를 맞춘다 */}
|
|
||||||
{Array.from({ length: 4 - row.length }, (_, i) => (
|
|
||||||
<View key={`pad${i}`} className="flex-1" />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
</Base>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (slide.kind === 'gak')
|
|
||||||
return (
|
|
||||||
<Base colors={colors}>
|
|
||||||
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
|
|
||||||
<Big>{slide.line}</Big>
|
|
||||||
<Pic name={slide.code} />
|
|
||||||
<Text className="mt-auto font-bagel text-[82px] leading-[82px] text-orange">{slide.score}</Text>
|
|
||||||
<Text className="font-jua text-[29px] leading-tight text-ink">{slide.name}</Text>
|
|
||||||
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
|
|
||||||
<Pressable onPress={() => open({ type: 'gak', indexId: slide.index_id })} className="mt-3 self-start rounded-full border-b-[5px] border-orange-deep bg-orange px-4 py-[9px]">
|
|
||||||
<Text className="font-jua text-[15px] text-white">계산 근거 보기</Text>
|
|
||||||
</Pressable>
|
|
||||||
</Base>
|
|
||||||
);
|
|
||||||
if (slide.kind === 'sunset') {
|
|
||||||
const sit = slide.situation ? SIT_BG[slide.situation] : undefined;
|
|
||||||
return (
|
|
||||||
<Base colors={sit?.colors ?? palette.dusk} locations={sit?.locations}>
|
|
||||||
<Eyebrow light>{slide.eyebrow}</Eyebrow>
|
|
||||||
{/* 노을 탭 히어로와 같은 순서: 결론 → 가장 붉을 때 → 쉬운 이유 */}
|
|
||||||
<Big light>{slide.headline ?? slide.grade_label}</Big>
|
|
||||||
{!!slide.line && <Text className="mt-0.5 font-jua text-[18px] text-white">{slide.line}</Text>}
|
|
||||||
<View className="mt-3 flex-1 gap-2">
|
|
||||||
{slide.cuts.map((c, i) => (
|
|
||||||
<View key={c.kind} className="flex-1 overflow-hidden rounded-2xl px-3 py-2">
|
|
||||||
<LinearGradient colors={CUT_BG[Math.min(i, 2)]} style={StyleSheet.absoluteFill} />
|
|
||||||
<Svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: '32%' }}>
|
|
||||||
<Polygon points={SKYLINE} fill="#2d2440" />
|
|
||||||
</Svg>
|
|
||||||
<Text className="font-bagel text-[21px] text-white">
|
|
||||||
{clockShort(c.at)}
|
|
||||||
<Text className="font-jua text-sm"> {c.label}</Text>
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
</Base>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (slide.kind === 'week')
|
|
||||||
return (
|
|
||||||
<Base colors={palette.mint}>
|
|
||||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
|
||||||
<Big>{slide.line}</Big>
|
|
||||||
{/* 칸은 제목 바로 아래, 팁만 맨 아래로 */}
|
|
||||||
<View className="mt-4 flex-row flex-wrap gap-2.5">
|
|
||||||
{slide.days.map((d) => (
|
|
||||||
<View key={d.day} className="grow basis-[45%] gap-0.5 rounded-[18px] border-b-[5px] border-shade bg-card/85 px-3 py-2.5">
|
|
||||||
<Ic name={d.icon} size={34} />
|
|
||||||
<Text className="font-jua text-lg text-ink">
|
|
||||||
{d.weekday} {d.day.split('-').slice(1).map(Number).join('.')}
|
|
||||||
</Text>
|
|
||||||
<Text className="font-jua text-[22px] text-ink">
|
|
||||||
<Text className="text-rain">{deg(d.temp_min_c)}</Text> → <Text className="text-orange">{deg(d.temp_max_c)}</Text>
|
|
||||||
</Text>
|
|
||||||
<Text className="text-xs font-bold text-ink2">
|
|
||||||
비 {d.rain_prob ?? '?'}%{d.temp_min_c != null && d.temp_max_c != null && ` · 일교차 ${Math.round(d.temp_max_c - d.temp_min_c)}°`}
|
|
||||||
</Text>
|
|
||||||
{d.gaks && d.gaks.length > 0 && (
|
|
||||||
<View className="mt-2 gap-1.5 border-t border-shade pt-2" accessibilityLabel={`${d.weekday}요일 대표 각`}>
|
|
||||||
<Text className="text-[11px] font-extrabold text-ink2">이날 할 만한 각</Text>
|
|
||||||
{d.gaks.map((g) => (
|
|
||||||
<View key={g.index_id} className="flex-row items-center gap-1.5">
|
|
||||||
<Ic name={g.icon} size={26} />
|
|
||||||
<Text numberOfLines={1} className="flex-1 text-[14px] font-bold text-ink">
|
|
||||||
{g.name}
|
|
||||||
</Text>
|
|
||||||
<Text className="font-bagel text-[16px] text-orange">{g.score}</Text>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
{!!slide.tip && <Text className="mt-auto overflow-hidden rounded-[14px] bg-ink-btn px-3 py-2.5 text-[13px] leading-snug font-bold text-white">{slide.tip}</Text>}
|
|
||||||
</Base>
|
|
||||||
);
|
|
||||||
if (slide.kind === 'plan') {
|
|
||||||
const credits = [...new Set(slide.steps.flatMap((st) => (st.image && st.image_credit ? [st.image_credit] : [])))];
|
|
||||||
return (
|
|
||||||
<Base colors={colors}>
|
|
||||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
|
||||||
<Big className="text-[24px]">{slide.line}</Big>
|
|
||||||
<View className="mt-auto gap-2">
|
|
||||||
{slide.steps.map((st, i) => (
|
|
||||||
<View key={i} className="flex-row items-center gap-1.5 rounded-[14px] bg-card/80 px-2 py-1.5">
|
|
||||||
<Text className="w-[52px] font-jua text-sm text-ink2">{st.time}</Text>
|
|
||||||
<Ic name={st.icon} size={22} />
|
|
||||||
<View className="ml-1 flex-1">
|
|
||||||
<Text numberOfLines={1} className="text-[13.5px] font-bold text-ink">
|
|
||||||
{st.title}
|
|
||||||
</Text>
|
|
||||||
<Text numberOfLines={1} className="text-[11.5px] font-semibold text-ink2">
|
|
||||||
{st.sub}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
{!!st.image && <Thumb image={st.image} icon={st.icon} iconSize={26} className="size-[46px] rounded-[10px]" />}
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
{credits.length > 0 && <Text className="mt-1.5 text-right text-[10px] font-semibold text-ink2">사진 {credits.join(' · ')}</Text>}
|
|
||||||
</Base>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// 카드뉴스: 관리자가 만든 4:5 그림 한 장 (/v1/card/... 는 API 서버 경로)
|
|
||||||
if (slide.kind === 'image') return <Image source={{ uri: apiUri(slide.url) }} accessibilityLabel={slide.alt ?? undefined} style={{ flex: 1 }} contentFit="cover" />;
|
|
||||||
if (slide.kind === 'rows' && slide.image)
|
|
||||||
return (
|
|
||||||
<View className="flex-1 justify-end">
|
|
||||||
<Image source={{ uri: imageUri(slide.image) }} style={StyleSheet.absoluteFill} contentFit="cover" />
|
|
||||||
{!!slide.image_credit && <Credit text={slide.image_credit} className="top-2.5 right-2.5" />}
|
|
||||||
<View className="px-5 pt-20 pb-3.5">
|
|
||||||
<LinearGradient colors={['rgba(16,20,34,0)', 'rgba(16,20,34,0.55)', 'rgba(16,20,34,0.85)']} locations={[0, 0.35, 1]} style={StyleSheet.absoluteFill} />
|
|
||||||
<Eyebrow light>{slide.eyebrow}</Eyebrow>
|
|
||||||
<Big light>{slide.line}</Big>
|
|
||||||
<Rows rows={slide.rows ?? []} dark />
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
return (
|
|
||||||
<Base colors={colors}>
|
|
||||||
{slide.moon_pct != null && <MoonPic pct={slide.moon_pct} waxing={!!slide.moon_waxing} />}
|
|
||||||
<Eyebrow light={light} className={light ? 'opacity-85' : undefined}>
|
|
||||||
{slide.eyebrow}
|
|
||||||
</Eyebrow>
|
|
||||||
<Big light={light} className="z-[1]">
|
|
||||||
{slide.line}
|
|
||||||
</Big>
|
|
||||||
{slide.moon_pct == null && <Pic name={slide.icon} widthPct={36} />}
|
|
||||||
<Rows rows={slide.rows ?? []} dark={light} />
|
|
||||||
</Base>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
import { useState } from 'react';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import { Ic } from '@/components/ui';
|
|
||||||
import { track } from '@/lib/analytics';
|
|
||||||
import { useAuth } from '@/lib/auth';
|
|
||||||
import { BIRTH_PLACES, placeName, useSaveBirth, validBirth, type Birth } from '@/lib/saju-birth';
|
|
||||||
|
|
||||||
import { Box, ChipGrid, DatePick, Stepper, type Ymd } from './pick';
|
|
||||||
|
|
||||||
const HOURS: [number, string][] = [[-1, '모름'], ...Array.from({ length: 24 }, (_, i): [number, string] => [i, `${i}시`])];
|
|
||||||
const PLACES: [string, string][] = BIRTH_PLACES.map(([k, n]) => [k, n]);
|
|
||||||
|
|
||||||
function Label({ children }: { children: string }) {
|
|
||||||
return <Text className="mb-1.5 text-[13px] font-extrabold text-ink2">{children}</Text>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 생년월일·태어난 시각·지역 넣기 (웹 SajuPage BirthForm) */
|
|
||||||
export function BirthForm({ initial, onDone, onCancel }: { initial: Birth | null; onDone: () => void; onCancel?: () => void }) {
|
|
||||||
const { loggedIn } = useAuth();
|
|
||||||
const save = useSaveBirth();
|
|
||||||
const [date, setDate] = useState<Ymd>({ y: initial?.y ?? null, m: initial?.m ?? null, d: initial?.d ?? null });
|
|
||||||
const [hour, setHour] = useState<number | null>(initial?.hour ?? null);
|
|
||||||
const [minute, setMinute] = useState(initial?.minute ?? 0);
|
|
||||||
const [place, setPlace] = useState(initial?.place ?? 'seoul');
|
|
||||||
const [open, setOpen] = useState<'hour' | 'place' | null>(null);
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const toggle = (k: 'hour' | 'place') => setOpen((o) => (o === k ? null : k));
|
|
||||||
|
|
||||||
const submit = () => {
|
|
||||||
const { y, m, d } = date;
|
|
||||||
if (y == null || m == null || d == null) return setError('생년월일을 모두 넣어 주세요');
|
|
||||||
if (!validBirth(y, m, d)) return setError('없는 날짜예요. 다시 확인해 주세요');
|
|
||||||
void save({ y, m, d, hour, minute: hour == null ? null : minute, place, gender: initial?.gender ?? null });
|
|
||||||
track('saju_input', { with_time: hour != null });
|
|
||||||
onDone();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<View className="mx-4 mt-4 gap-4 rounded-[24px] border-b-[5px] border-shade bg-card p-5">
|
|
||||||
<View className="items-center">
|
|
||||||
<Ic name="yin_yang" size={56} />
|
|
||||||
<Text className="mt-2 text-center font-jua text-[20px] leading-snug text-ink">{'내 사주와 오늘 날씨로\n오늘 하루를 봐요'}</Text>
|
|
||||||
</View>
|
|
||||||
<View>
|
|
||||||
<Label>생년월일 (양력)</Label>
|
|
||||||
<DatePick
|
|
||||||
value={date}
|
|
||||||
onChange={(v) => {
|
|
||||||
setDate(v);
|
|
||||||
setError('');
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</View>
|
|
||||||
<View>
|
|
||||||
<Label>{"태어난 시각 (모르면 '모름')"}</Label>
|
|
||||||
<View className="flex-row gap-1.5">
|
|
||||||
<Box label="시" value={hour == null ? '모름' : `${hour}시`} placeholder="모름" open={open === 'hour'} onPress={() => toggle('hour')} />
|
|
||||||
<Stepper label="분" value={minute} onChange={setMinute} min={0} max={59} unit="분" disabled={hour == null} />
|
|
||||||
</View>
|
|
||||||
{open === 'hour' && (
|
|
||||||
<View className="mt-1.5">
|
|
||||||
<ChipGrid
|
|
||||||
label="태어난 시"
|
|
||||||
items={HOURS}
|
|
||||||
value={hour ?? -1}
|
|
||||||
onPick={(h) => {
|
|
||||||
setHour(h < 0 ? null : h);
|
|
||||||
setOpen(null);
|
|
||||||
}}
|
|
||||||
wide
|
|
||||||
/>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
<View>
|
|
||||||
<Label>태어난 지역</Label>
|
|
||||||
<Box label="태어난 지역" value={placeName(place)} placeholder="서울" open={open === 'place'} onPress={() => toggle('place')} />
|
|
||||||
{open === 'place' && (
|
|
||||||
<View className="mt-1.5">
|
|
||||||
<ChipGrid
|
|
||||||
label="태어난 지역"
|
|
||||||
items={PLACES}
|
|
||||||
value={place}
|
|
||||||
onPick={(p) => {
|
|
||||||
setPlace(p);
|
|
||||||
setOpen(null);
|
|
||||||
}}
|
|
||||||
wide
|
|
||||||
/>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
<Text className="mt-1.5 text-xs font-semibold text-ink3">지역마다 해가 뜨는 시각이 달라 태어난 시각을 그만큼 고쳐서 봐요.</Text>
|
|
||||||
</View>
|
|
||||||
{!!error && <Text className="text-center text-[13px] font-bold text-[#d9442f]">{error}</Text>}
|
|
||||||
<Pressable onPress={submit} accessibilityRole="button" className="rounded-full bg-orange py-3.5">
|
|
||||||
<Text className="text-center text-[15px] font-extrabold text-white">오늘 날씨 사주 보기</Text>
|
|
||||||
</Pressable>
|
|
||||||
{!!onCancel && (
|
|
||||||
<Pressable onPress={onCancel} accessibilityRole="button" className="-mt-2 py-1">
|
|
||||||
<Text className="text-center text-[13px] font-extrabold text-ink3">취소</Text>
|
|
||||||
</Pressable>
|
|
||||||
)}
|
|
||||||
<Text className="text-center text-xs font-semibold text-ink3">{loggedIn ? '내 계정에 저장돼요. 내 정보에서 언제든 지울 수 있어요.' : '이 기기에만 저장돼요. 로그인하면 계정에 저장해 어느 기기에서든 바로 볼 수 있어요.'}</Text>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
import { matchMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
||||||
import type { ResSajuMatch } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { useMutation } from '@tanstack/react-query';
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
|
|
||||||
import { useSoft } from '@/components/sheets/parts';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import { useRegion } from '@/lib/region';
|
|
||||||
import { toBody, validBirth, type Birth } from '@/lib/saju-birth';
|
|
||||||
|
|
||||||
import { dayWord, Panel } from './parts';
|
|
||||||
import { DatePick, type Ymd } from './pick';
|
|
||||||
|
|
||||||
const pad = (n: number) => String(n).padStart(2, '0');
|
|
||||||
|
|
||||||
/** 궁합 (Lv.5): 상대 생년월일로 두 사주가 맞는 정도와 같이 나가기 좋은 날. 상대 생년월일은 저장하지 않는다 */
|
|
||||||
export function Match({ birth }: { birth: Birth }) {
|
|
||||||
const { region } = useRegion();
|
|
||||||
const soft = useSoft();
|
|
||||||
const [date, setDate] = useState<Ymd>({ y: null, m: null, d: null });
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const run = useMutation({ ...matchMutation() });
|
|
||||||
const res: ResSajuMatch | undefined = run.data?.result?.success ? run.data : undefined;
|
|
||||||
const go = () => {
|
|
||||||
const { y, m, d } = date;
|
|
||||||
if (y == null || m == null || d == null) return setError('상대 생년월일을 모두 넣어 주세요');
|
|
||||||
if (!validBirth(y, m, d)) return setError('없는 날짜예요. 다시 확인해 주세요');
|
|
||||||
setError('');
|
|
||||||
run.mutate({ body: { region_code: region.code, me: toBody(birth), friend: { birth_date: `${y}-${pad(m)}-${pad(d)}`, longitude: 126.98 } } });
|
|
||||||
};
|
|
||||||
return (
|
|
||||||
<Panel id="saju_match" icon="two_hearts" title="궁합">
|
|
||||||
{res ? (
|
|
||||||
<>
|
|
||||||
<View className="mb-1 flex-row items-center justify-between">
|
|
||||||
<Text className="text-xs font-bold text-ink3">
|
|
||||||
상대 {date.y}.{date.m}.{date.d}생
|
|
||||||
</Text>
|
|
||||||
<Pressable onPress={() => run.reset()} hitSlop={8} accessibilityRole="button">
|
|
||||||
<Text className="text-xs font-extrabold text-orange">다른 사람 보기</Text>
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
<Text className="font-jua text-[19px] text-ink">
|
|
||||||
{res.title ?? ''} <Text className="font-bagel text-[17px] text-orange">{res.score ?? ''}점</Text>
|
|
||||||
</Text>
|
|
||||||
{res.lines?.map((l) => (
|
|
||||||
<Text key={l} className="mt-1 text-[13.5px] font-semibold text-ink">
|
|
||||||
{l}
|
|
||||||
</Text>
|
|
||||||
))}
|
|
||||||
{!!res.day && (
|
|
||||||
<Text className="mt-2 overflow-hidden rounded-xl px-3 py-2 text-[13.5px] font-bold text-ink" style={{ backgroundColor: soft.warm }}>
|
|
||||||
앞으로 7일 중 같이 나가기 좋은 날: {dayWord(res.day.day, res.day.weekday)}
|
|
||||||
{res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
<Text className="mt-1.5 text-xs font-semibold text-ink3">상대 기운: {res.friend_scene ?? ''}</Text>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Text className="mb-2 text-[13px] font-semibold text-ink2">상대 생년월일(양력)을 넣으면 두 사람 사주가 어떻게 맞는지와 앞으로 7일 중 같이 나가기 좋은 날을 봐요.</Text>
|
|
||||||
<DatePick
|
|
||||||
label="상대 "
|
|
||||||
value={date}
|
|
||||||
onChange={(v) => {
|
|
||||||
setDate(v);
|
|
||||||
setError('');
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Pressable onPress={go} disabled={run.isPending} accessibilityRole="button" className="mt-2 rounded-xl bg-orange py-3 disabled:opacity-45">
|
|
||||||
<Text className="text-center text-[14px] font-extrabold text-white">보기</Text>
|
|
||||||
</Pressable>
|
|
||||||
{!!error && <Text className="mt-1.5 text-xs font-bold text-[#d9442f]">{error}</Text>}
|
|
||||||
{(run.isError || (!!run.data && !run.data.result?.success)) && <Text className="mt-1.5 text-xs font-bold text-[#d9442f]">궁합을 불러오지 못했어요. 다시 눌러 주세요.</Text>}
|
|
||||||
<Text className="mt-1.5 text-xs font-semibold text-ink3">상대 생년월일은 저장하지 않아요.</Text>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Panel>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,139 +0,0 @@
|
|||||||
import type { ResSaju } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { Image } from 'expo-image';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
|
|
||||||
import { useSoft } from '@/components/sheets/parts';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
|
|
||||||
import { EL_ART, EL_COLOR, EL_WORD, Panel } from './parts';
|
|
||||||
|
|
||||||
const POS_WORD: Record<string, string> = { hour: '시', day: '일', month: '월', year: '연' };
|
|
||||||
const STRENGTH_WORD: Record<string, string> = {
|
|
||||||
신강: '나를 돕는 기운이 센 사주. 태어난 달(월령)의 힘을 먼저 봐요',
|
|
||||||
중화: '나를 돕는 기운과 다른 기운이 비슷한 사주',
|
|
||||||
신약: '나를 돕는 기운이 약한 사주',
|
|
||||||
};
|
|
||||||
const TEN_GOD_WORD: Record<string, string> = {
|
|
||||||
비견: '나와 같은 기운',
|
|
||||||
겁재: '나와 같지만 겨루는 기운',
|
|
||||||
식신: '내가 만들어 내는 기운',
|
|
||||||
상관: '내가 드러내는 기운',
|
|
||||||
편재: '내가 크게 굴리는 재물',
|
|
||||||
정재: '내가 차곡차곡 모으는 재물',
|
|
||||||
편관: '나를 세게 다잡는 기운',
|
|
||||||
정관: '나를 바르게 이끄는 기운',
|
|
||||||
편인: '나를 돕는 남다른 지혜',
|
|
||||||
정인: '나를 돕는 배움·도움',
|
|
||||||
};
|
|
||||||
|
|
||||||
function Art({ el, size }: { el: string; size: number }) {
|
|
||||||
const src = EL_ART[el];
|
|
||||||
return src != null ? <Image source={src} style={{ width: size, height: size }} contentFit="contain" /> : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function Char({ c, ko, el, me }: { c: string; ko: string; el: string; me?: boolean }) {
|
|
||||||
const [fg, bg] = EL_COLOR[el] ?? ['#28304a', '#f3f6fb'];
|
|
||||||
return (
|
|
||||||
<View className="items-center rounded-xl py-1.5" style={{ backgroundColor: bg, borderWidth: me ? 2 : 0, borderColor: '#ff7a45' }}>
|
|
||||||
<Text className="font-batang text-[22px] leading-tight" style={{ color: fg }}>
|
|
||||||
{c}
|
|
||||||
</Text>
|
|
||||||
<Text className="text-[10.5px] font-extrabold" style={{ color: fg }}>
|
|
||||||
{ko}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Note({ term, word }: { term: string; word: string }) {
|
|
||||||
return (
|
|
||||||
<Text className="text-[12.5px] leading-relaxed font-semibold text-ink2">
|
|
||||||
<Text className="font-extrabold text-ink">{term}</Text> = {word}
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 사주 명식: 가장 센 기운, 오행 막대, 네 기둥, 용어 풀이 */
|
|
||||||
export function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
const me = r.me!;
|
|
||||||
const cols = [...me.pillars].reverse();
|
|
||||||
const els = Object.entries(me.elements ?? {});
|
|
||||||
const total = els.reduce((a, [, v]) => a + v, 0);
|
|
||||||
const gods = [...new Set(me.pillars.flatMap((p) => [p.stem_ten_god, p.branch_ten_god]).filter((g): g is string => !!g && g in TEN_GOD_WORD))];
|
|
||||||
const strength = me.strength ?? (me.strong == null ? null : me.strong ? '신강' : '신약');
|
|
||||||
const top = me.top_element;
|
|
||||||
return (
|
|
||||||
<Panel
|
|
||||||
icon={me.scene_icon}
|
|
||||||
title="사주 명식"
|
|
||||||
right={
|
|
||||||
<Pressable onPress={onEdit} hitSlop={8} accessibilityRole="button">
|
|
||||||
<Text className="text-xs font-extrabold text-orange">생년월일 바꾸기</Text>
|
|
||||||
</Pressable>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{!!top && !!strength && (
|
|
||||||
<View className="flex-row items-center gap-3">
|
|
||||||
<Art el={top} size={64} />
|
|
||||||
<View className="min-w-0 flex-1">
|
|
||||||
<Text className="font-jua text-[18px] leading-snug text-ink">
|
|
||||||
{EL_WORD[top]}({top}) 기운이 가장 센 {strength} 사주
|
|
||||||
</Text>
|
|
||||||
<Text className="mt-0.5 text-[13px] font-semibold text-ink2">
|
|
||||||
나를 돕는 기운 {Math.round((me.support ?? 0) * 100)}% · {me.scene}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
{total > 0 && (
|
|
||||||
<>
|
|
||||||
<View className="mt-2.5 h-2.5 flex-row overflow-hidden rounded-full" accessibilityRole="image" accessibilityLabel={els.map(([k, v]) => `${k} ${Math.round(v)}`).join(', ')}>
|
|
||||||
{els.map(([k, v]) => (
|
|
||||||
<View key={k} style={{ width: `${(v / total) * 100}%`, backgroundColor: EL_COLOR[k]?.[0] }} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
<View className="mt-1.5 flex-row justify-between">
|
|
||||||
{els.map(([k, v]) => (
|
|
||||||
<View key={k} className="flex-row items-center gap-0.5">
|
|
||||||
<Art el={k} size={20} />
|
|
||||||
<Text className="text-[12px] font-extrabold" style={{ color: EL_COLOR[k]?.[0] }}>
|
|
||||||
{k} {Math.round(v)}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<View className="mt-3 flex-row gap-1.5">
|
|
||||||
{(me.hour_known ? cols : [null, ...cols]).map((p, i) => (
|
|
||||||
<View key={p?.position ?? `none-${i}`} className="flex-1 gap-1">
|
|
||||||
<Text className="text-center text-[11px] font-extrabold text-ink3">{p ? `${POS_WORD[p.position]}주` : '시주'}</Text>
|
|
||||||
{p ? (
|
|
||||||
<>
|
|
||||||
<Text className={`text-center text-[11.5px] font-extrabold ${p.position === 'day' ? 'text-orange' : 'text-ink2'}`}>{p.position === 'day' ? '나' : (p.stem_ten_god ?? '')}</Text>
|
|
||||||
<Char c={p.stem} ko={p.stem_ko} el={p.stem_element} me={p.position === 'day'} />
|
|
||||||
<Char c={p.branch} ko={p.branch_ko} el={p.branch_element} />
|
|
||||||
<Text className="text-center text-[11.5px] font-extrabold text-ink2">{p.branch_ten_god}</Text>
|
|
||||||
{p.position === 'month' && <Text className="text-center text-[10.5px] font-extrabold text-ink3">월령</Text>}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<View className="flex-1 items-center justify-center rounded-xl px-1" style={{ backgroundColor: soft.soft }}>
|
|
||||||
<Text className="text-center text-[12px] font-extrabold text-ink3">시각 모름</Text>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
<View className="mt-3 border-t border-line pt-2.5">
|
|
||||||
{!!strength && <Note term={strength} word={STRENGTH_WORD[strength] ?? ''} />}
|
|
||||||
{gods.map((g) => (
|
|
||||||
<Note key={g} term={g} word={TEN_GOD_WORD[g]} />
|
|
||||||
))}
|
|
||||||
<Note term="월령" word="태어난 달의 계절 기운. 명식에서 가장 크게 봐요" />
|
|
||||||
</View>
|
|
||||||
{(me.need?.length ?? 0) > 0 && <Text className="mt-2 text-[13px] font-bold text-ink">내 기운에 좋은 날씨: {me.need!.join(' · ')}</Text>}
|
|
||||||
{me.jeol_warning && <Text className="mt-1 text-xs font-semibold text-warn">태어난 날에 절기가 바뀌어요. 태어난 시각을 넣어야 달 기둥이 정확해요.</Text>}
|
|
||||||
</Panel>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
import type { ResSaju, SajuLock } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
|
|
||||||
import { useSoft } from '@/components/sheets/parts';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import { Ic } from '@/components/ui';
|
|
||||||
import { useAuth } from '@/lib/auth';
|
|
||||||
import { progress, useLevel } from '@/lib/level';
|
|
||||||
import { useSaveBirth, type Birth } from '@/lib/saju-birth';
|
|
||||||
import { useSheet } from '@/lib/sheet';
|
|
||||||
|
|
||||||
import { dayWord, Panel } from './parts';
|
|
||||||
|
|
||||||
/** 앞으로 7일 흐름 (Lv.2) */
|
|
||||||
export function Week({ days }: { days: NonNullable<ResSaju['week']> }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
return (
|
|
||||||
<Panel id="saju_week" icon="spiral_calendar" title="앞으로 7일 흐름">
|
|
||||||
<View className="gap-1">
|
|
||||||
{days.map((d) => (
|
|
||||||
<View key={d.day} className="flex-row items-center gap-2 rounded-xl px-2 py-1.5" style={d.best ? { backgroundColor: soft.warm } : undefined}>
|
|
||||||
<Text numberOfLines={1} className="w-[66px] text-[13px] font-bold text-ink">
|
|
||||||
{dayWord(d.day, d.weekday)}
|
|
||||||
</Text>
|
|
||||||
{d.icon ? <Ic name={d.icon} size={24} /> : <View className="size-6" />}
|
|
||||||
<Text numberOfLines={1} className="w-[52px] text-[13px] font-bold text-ink2">
|
|
||||||
{d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''}
|
|
||||||
</Text>
|
|
||||||
<Text numberOfLines={1} className="min-w-0 flex-1 text-[12.5px] font-bold text-ink2">
|
|
||||||
{d.title}
|
|
||||||
</Text>
|
|
||||||
<Text className={`font-bagel text-[15px] ${d.best ? 'text-orange' : 'text-ink'}`}>{d.score}</Text>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
<Text className="mt-1.5 text-xs font-semibold text-ink3">점수는 그날 사주와 예보로 계산해요. 주황색은 7일 중 점수가 가장 높은 날이에요.</Text>
|
|
||||||
</Panel>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 금전운·일운 (Lv.3) */
|
|
||||||
export function Money({ money, work }: { money: string[]; work: string[] }) {
|
|
||||||
const lines = [...money.map((l) => ['money_bag', l]), ...work.map((l) => ['briefcase', l])];
|
|
||||||
return (
|
|
||||||
<Panel id="saju_money" icon="money_bag" title="금전운 · 일운">
|
|
||||||
<View className="gap-1.5">
|
|
||||||
{lines.map(([icon, l]) => (
|
|
||||||
<View key={l} className="flex-row gap-2">
|
|
||||||
<Ic name={icon} size={20} />
|
|
||||||
<Text className="min-w-0 flex-1 text-[14px] font-semibold text-ink">{l}</Text>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
</Panel>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 앞으로 7일 연애운 (Lv.4). 성별을 고르면 이성 인연까지 */
|
|
||||||
export function Love({ love, birth }: { love: NonNullable<ResSaju['love']>; birth: Birth }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
const save = useSaveBirth();
|
|
||||||
const pick = (g: 'M' | 'F' | null) => void save({ ...birth, gender: g });
|
|
||||||
return (
|
|
||||||
<Panel id="saju_love" icon="red_heart" title="앞으로 7일 연애운">
|
|
||||||
{love.good ? (
|
|
||||||
<View className="rounded-xl px-3 py-2.5" style={{ backgroundColor: soft.warm }}>
|
|
||||||
<Text className="text-xs font-extrabold text-heart">연애 기운이 좋은 날</Text>
|
|
||||||
<Text className="font-jua text-[17px] text-ink">
|
|
||||||
{dayWord(love.good.day, love.good.weekday)}
|
|
||||||
{love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''}
|
|
||||||
</Text>
|
|
||||||
<Text className="text-[13px] font-semibold text-ink">{love.good.body}</Text>
|
|
||||||
<Text className="text-[11.5px] font-semibold text-ink3">{love.good.why}</Text>
|
|
||||||
</View>
|
|
||||||
) : (
|
|
||||||
<Text className="text-[13px] font-semibold text-ink2">앞으로 7일 중엔 연애 기운이 두드러지는 날이 없어요.</Text>
|
|
||||||
)}
|
|
||||||
{!!love.caution && (
|
|
||||||
<Text className="mt-2 text-[13px] font-semibold text-ink">
|
|
||||||
조심할 날 {dayWord(love.caution.day, love.caution.weekday)}: {love.caution.body} <Text className="text-ink3">· {love.caution.why}</Text>
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
{love.gender_known ? (
|
|
||||||
<Text className="mt-2.5 text-xs font-bold text-ink3">
|
|
||||||
{birth.gender === 'M' ? '남성' : '여성'} 기준으로 이성 인연(재성·관성)까지 봤어요 ·{' '}
|
|
||||||
<Text onPress={() => pick(null)} accessibilityRole="button" className="font-extrabold text-orange">
|
|
||||||
빼고 보기
|
|
||||||
</Text>
|
|
||||||
</Text>
|
|
||||||
) : (
|
|
||||||
<View className="mt-2.5 flex-row flex-wrap items-center gap-1.5">
|
|
||||||
<Text className="text-xs font-bold text-ink2">성별을 고르면 이성 인연(재성·관성)까지 봐요</Text>
|
|
||||||
{(
|
|
||||||
[
|
|
||||||
['M', '남성'],
|
|
||||||
['F', '여성'],
|
|
||||||
] as const
|
|
||||||
).map(([g, word]) => (
|
|
||||||
<Pressable key={g} onPress={() => pick(g)} accessibilityRole="button" className="rounded-full px-2.5 py-1" style={{ backgroundColor: soft.soft }}>
|
|
||||||
<Text className="text-xs font-bold text-ink2">{word}</Text>
|
|
||||||
</Pressable>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</Panel>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 이달·올해 (Lv.6·7) */
|
|
||||||
export function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable<ResSaju['month']> }) {
|
|
||||||
return (
|
|
||||||
<Panel id={id} icon={icon} title={p.label}>
|
|
||||||
<Text className="font-jua text-[17px] text-ink">
|
|
||||||
{p.title} <Text className="text-[13px] text-ink3">({p.ten_god})</Text>
|
|
||||||
</Text>
|
|
||||||
<Text className="mt-0.5 text-[13.5px] font-semibold text-ink">{p.body}</Text>
|
|
||||||
{(p.months?.length ?? 0) > 0 && (
|
|
||||||
<Text className="mt-1.5 text-[13.5px] font-bold text-ink">
|
|
||||||
{p.label.includes('미리') ? '내 사주와 잘 맞는 달' : '남은 달 중 잘 맞는 달'}: {p.months!.map((m) => `${m}월`).join(' · ')}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
{p.notes?.map((n) => (
|
|
||||||
<Text key={n} className="mt-1 text-xs font-semibold text-ink3">
|
|
||||||
{n}
|
|
||||||
</Text>
|
|
||||||
))}
|
|
||||||
</Panel>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 아직 안 열린 것: 다음에 열릴 하나를 크게, 나머지는 한 줄로. 로그인 전이면 로그인부터 */
|
|
||||||
export function Locked({ locks }: { locks: SajuLock[] }) {
|
|
||||||
const { loggedIn } = useAuth();
|
|
||||||
const { open } = useSheet();
|
|
||||||
const soft = useSoft();
|
|
||||||
const level = useLevel().data;
|
|
||||||
if (!locks.length) return null;
|
|
||||||
const [next, ...rest] = [...locks].sort((a, b) => a.level - b.level);
|
|
||||||
const close = loggedIn && !!level && level.next_points != null && level.level + 1 === next.level;
|
|
||||||
return (
|
|
||||||
<View className="mx-4 rounded-[22px] px-4 py-3.5" style={{ backgroundColor: soft.soft }}>
|
|
||||||
<View className="flex-row items-center gap-3">
|
|
||||||
<Ic name="locked" size={32} />
|
|
||||||
<View className="min-w-0 flex-1">
|
|
||||||
<Text className="font-jua text-[16px] text-ink">{loggedIn ? `다음은 ${next.name}` : '각을 모으면 더 볼 수 있어요'}</Text>
|
|
||||||
<Text className="text-xs font-bold text-ink2">
|
|
||||||
{loggedIn ? (close && level ? `${level.next_points! - level.points}각 더 모으면 열려요` : `Lv.${next.level}이 되면 열려요`) : "로그인하고 출석·사주 보기·좋아요를 하면 활동 포인트 '각'이 쌓여요"}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
<Pressable onPress={() => open(loggedIn ? { type: 'level' } : { type: 'login', why: 'level' })} accessibilityRole="button" className="rounded-full bg-ink-btn px-3 py-1.5">
|
|
||||||
<Text className="text-xs font-extrabold text-white">{loggedIn ? '각 모으는 법' : '로그인'}</Text>
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
{close && !!level && (
|
|
||||||
<View className="mt-2.5 h-1.5 overflow-hidden rounded-full bg-card">
|
|
||||||
<LinearGradient colors={['#ffb27a', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${Math.round(progress(level) * 100)}%`, borderRadius: 999 }} />
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
<View className="mt-2.5 flex-row flex-wrap gap-1.5">
|
|
||||||
{(loggedIn ? rest : [next, ...rest]).map((l) => (
|
|
||||||
<View key={l.key} className="rounded-full bg-card px-2.5 py-1">
|
|
||||||
<Text className="text-[11.5px] font-extrabold text-ink2">
|
|
||||||
Lv.{l.level} {l.name}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
import { createContext, use, type ReactNode } from 'react';
|
|
||||||
import { View } from 'react-native';
|
|
||||||
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import { Ic } from '@/components/ui';
|
|
||||||
|
|
||||||
export const EL_COLOR: Record<string, [string, string]> = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] };
|
|
||||||
export const EL_WORD: Record<string, string> = { 木: '나무', 火: '불', 土: '흙', 金: '쇠', 水: '물' };
|
|
||||||
// 오행 그림 (웹 public/saju). Metro 는 정적 require 만 묶을 수 있어 하나씩 적는다
|
|
||||||
export const EL_ART: Record<string, number> = {
|
|
||||||
木: require('../../../../frontend/public/saju/wood.webp'),
|
|
||||||
火: require('../../../../frontend/public/saju/fire.webp'),
|
|
||||||
土: require('../../../../frontend/public/saju/earth.webp'),
|
|
||||||
金: require('../../../../frontend/public/saju/metal.webp'),
|
|
||||||
水: require('../../../../frontend/public/saju/water.webp'),
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 2026-11-04 + 수 → 11/4(수) */
|
|
||||||
export const dayWord = (iso: string, weekday: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}(${weekday})`;
|
|
||||||
|
|
||||||
/** ?open= 으로 연 칸: 그 칸이 자리를 잡으면 화면이 그 위치로 내려간다 (웹 #hash 스크롤) */
|
|
||||||
export const OpenTarget = createContext<{ id?: string; onLayout: (y: number) => void }>({ onLayout: () => {} });
|
|
||||||
|
|
||||||
/** 흰 판: 아이콘·제목·오른쪽 버튼 */
|
|
||||||
export function Panel({ id, icon, title, right, children }: { id?: string; icon: string; title: string; right?: ReactNode; children: ReactNode }) {
|
|
||||||
const target = use(OpenTarget);
|
|
||||||
const mine = !!id && target.id === id;
|
|
||||||
return (
|
|
||||||
<View onLayout={mine ? (e) => target.onLayout(e.nativeEvent.layout.y) : undefined} className="mx-4 rounded-[22px] border-b-4 border-shade bg-card px-4 py-3.5">
|
|
||||||
<View className="mb-2 flex-row items-center gap-2">
|
|
||||||
<Ic name={icon} size={28} />
|
|
||||||
<Text className="font-jua text-[17px] text-ink">{title}</Text>
|
|
||||||
{right != null && <View className="ml-auto">{right}</View>}
|
|
||||||
</View>
|
|
||||||
{children}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
import { useState } from 'react';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
|
|
||||||
import { useSoft } from '@/components/sheets/parts';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
|
|
||||||
/** 고르는 칸: 누르면 아래에 칩이 펼쳐진다 (웹 input·select 대신. 숫자 자판 없이 눌러서 고른다) */
|
|
||||||
export function Box({ label, value, placeholder, open, onPress, disabled, flex = 1 }: { label: string; value: string | null; placeholder: string; open: boolean; onPress: () => void; disabled?: boolean; flex?: number }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
return (
|
|
||||||
<Pressable
|
|
||||||
onPress={onPress}
|
|
||||||
disabled={disabled}
|
|
||||||
accessibilityRole="button"
|
|
||||||
accessibilityLabel={`${label} ${value ?? placeholder}`}
|
|
||||||
accessibilityState={{ expanded: open, disabled }}
|
|
||||||
className={`min-h-[48px] min-w-0 flex-row items-center justify-center gap-1 rounded-2xl px-2 py-2.5 ${disabled ? 'opacity-45' : ''}`}
|
|
||||||
style={{ flex, backgroundColor: soft.field, borderWidth: 1.5, borderColor: open ? '#ff7a45' : soft.fieldBorder }}
|
|
||||||
>
|
|
||||||
<Text numberOfLines={1} className={`text-[17px] font-bold ${value != null ? 'text-ink' : 'text-ink3'}`}>
|
|
||||||
{value ?? placeholder}
|
|
||||||
</Text>
|
|
||||||
<Text className="text-[11px] text-ink3">{open ? '▲' : '▼'}</Text>
|
|
||||||
</Pressable>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 칩 여러 개 중 하나 고르기 */
|
|
||||||
export function ChipGrid<K extends string | number>({ items, value, onPick, label, wide }: { items: [K, string][]; value: K | null; onPick: (k: K) => void; label: string; wide?: boolean }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
return (
|
|
||||||
<View accessibilityRole="radiogroup" accessibilityLabel={label} className="flex-row flex-wrap gap-1.5 rounded-2xl p-2" style={{ backgroundColor: soft.soft }}>
|
|
||||||
{items.map(([k, word]) => {
|
|
||||||
const on = value === k;
|
|
||||||
return (
|
|
||||||
<Pressable key={String(k)} onPress={() => onPick(k)} accessibilityRole="radio" accessibilityState={{ checked: on }} className={`min-h-[40px] items-center justify-center rounded-xl px-1 ${wide ? 'w-[64px]' : 'w-[44px]'} ${on ? 'bg-orange' : 'bg-card'}`}>
|
|
||||||
<Text className={`text-[14px] font-bold ${on ? 'text-white' : 'text-ink'}`}>{word}</Text>
|
|
||||||
</Pressable>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 연도: 먼저 10년 단위를 고르고 그 안에서 연도 */
|
|
||||||
function YearGrid({ value, onPick, label }: { value: number | null; onPick: (y: number) => void; label: string }) {
|
|
||||||
const thisYear = new Date().getFullYear();
|
|
||||||
const [decade, setDecade] = useState(value != null ? Math.floor(value / 10) * 10 : 1990);
|
|
||||||
const decades: [number, string][] = [];
|
|
||||||
for (let d = 1900; d <= thisYear; d += 10) decades.push([d, `${String(d).slice(2)}년대`]);
|
|
||||||
const years: [number, string][] = [];
|
|
||||||
for (let y = decade; y < decade + 10 && y <= thisYear; y++) years.push([y, String(y)]);
|
|
||||||
return (
|
|
||||||
<View className="gap-1.5">
|
|
||||||
<ChipGrid label={`${label} 10년 단위`} items={decades} value={decade} onPick={setDecade} wide />
|
|
||||||
<ChipGrid label={label} items={years} value={value} onPick={onPick} wide />
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const MONTHS: [number, string][] = Array.from({ length: 12 }, (_, i) => [i + 1, `${i + 1}월`]);
|
|
||||||
const daysIn = (y: number | null, m: number | null) => (m == null ? 31 : new Date(y ?? 2000, m, 0).getDate());
|
|
||||||
|
|
||||||
export type Ymd = { y: number | null; m: number | null; d: number | null };
|
|
||||||
|
|
||||||
/** 생년월일(양력) 고르기: 연도 → 월 → 일 순서로 이어서 펼친다 */
|
|
||||||
export function DatePick({ value, onChange, label = '' }: { value: Ymd; onChange: (v: Ymd) => void; label?: string }) {
|
|
||||||
const [open, setOpen] = useState<'y' | 'm' | 'd' | null>(null);
|
|
||||||
const toggle = (k: 'y' | 'm' | 'd') => setOpen((o) => (o === k ? null : k));
|
|
||||||
const days: [number, string][] = Array.from({ length: daysIn(value.y, value.m) }, (_, i) => [i + 1, String(i + 1)]);
|
|
||||||
return (
|
|
||||||
<View className="gap-1.5">
|
|
||||||
<View className="flex-row gap-1.5">
|
|
||||||
<Box label={`${label}년`} value={value.y != null ? `${value.y}년` : null} placeholder="연도" open={open === 'y'} onPress={() => toggle('y')} flex={1.5} />
|
|
||||||
<Box label={`${label}월`} value={value.m != null ? `${value.m}월` : null} placeholder="월" open={open === 'm'} onPress={() => toggle('m')} />
|
|
||||||
<Box label={`${label}일`} value={value.d != null ? `${value.d}일` : null} placeholder="일" open={open === 'd'} onPress={() => toggle('d')} />
|
|
||||||
</View>
|
|
||||||
{open === 'y' ? (
|
|
||||||
<YearGrid
|
|
||||||
label={`${label}년`}
|
|
||||||
value={value.y}
|
|
||||||
onPick={(y) => {
|
|
||||||
onChange({ ...value, y });
|
|
||||||
setOpen(value.m == null ? 'm' : null);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : open === 'm' ? (
|
|
||||||
<ChipGrid
|
|
||||||
label={`${label}월`}
|
|
||||||
items={MONTHS}
|
|
||||||
value={value.m}
|
|
||||||
onPick={(m) => {
|
|
||||||
onChange({ ...value, m });
|
|
||||||
setOpen(value.d == null ? 'd' : null);
|
|
||||||
}}
|
|
||||||
wide
|
|
||||||
/>
|
|
||||||
) : open === 'd' ? (
|
|
||||||
<ChipGrid
|
|
||||||
label={`${label}일`}
|
|
||||||
items={days}
|
|
||||||
value={value.d}
|
|
||||||
onPick={(d) => {
|
|
||||||
onChange({ ...value, d });
|
|
||||||
setOpen(null);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 숫자: −/+ 버튼 (분) */
|
|
||||||
export function Stepper({ value, onChange, min, max, label, unit, disabled }: { value: number; onChange: (v: number) => void; min: number; max: number; label: string; unit: string; disabled?: boolean }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
const set = (v: number) => onChange(Math.min(max, Math.max(min, v)));
|
|
||||||
return (
|
|
||||||
<View className={`min-h-[48px] flex-1 flex-row items-center justify-between rounded-2xl ${disabled ? 'opacity-45' : ''}`} style={{ backgroundColor: soft.field, borderWidth: 1.5, borderColor: soft.fieldBorder }} accessibilityLabel={label}>
|
|
||||||
<Pressable onPress={() => set(value - 1)} onLongPress={() => set(value - 10)} disabled={disabled || value <= min} hitSlop={4} accessibilityLabel={`${label} 내리기`} className="px-3.5 py-2">
|
|
||||||
<Text className="text-[18px] font-extrabold text-ink2">−</Text>
|
|
||||||
</Pressable>
|
|
||||||
<Text className="text-[17px] font-bold text-ink">
|
|
||||||
{value}
|
|
||||||
{unit}
|
|
||||||
</Text>
|
|
||||||
<Pressable onPress={() => set(value + 1)} onLongPress={() => set(value + 10)} disabled={disabled || value >= max} hitSlop={4} accessibilityLabel={`${label} 올리기`} className="px-3.5 py-2">
|
|
||||||
<Text className="text-[18px] font-extrabold text-ink2">+</Text>
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,172 +0,0 @@
|
|||||||
import { myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
||||||
import { reading } from '@nalssigak/shared/api/client/sdk.gen';
|
|
||||||
import type { SajuCard } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
|
||||||
import { useEffect, useRef } from 'react';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
import Svg, { Circle } from 'react-native-svg';
|
|
||||||
import { useCSSVariable } from 'uniwind';
|
|
||||||
|
|
||||||
import { useSoft } from '@/components/sheets/parts';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import { Ic } from '@/components/ui';
|
|
||||||
import { track } from '@/lib/analytics';
|
|
||||||
import { useAuth } from '@/lib/auth';
|
|
||||||
import { useLevel } from '@/lib/level';
|
|
||||||
import { useRegion } from '@/lib/region';
|
|
||||||
import { markSajuSeen, toBody, type Birth } from '@/lib/saju-birth';
|
|
||||||
import { useShare } from '@/lib/share-image';
|
|
||||||
import { SITE_URL } from '@/lib/site';
|
|
||||||
|
|
||||||
import { Match } from './match';
|
|
||||||
import { MeCard } from './me-card';
|
|
||||||
import { Locked, Love, Money, Period, Week } from './panels';
|
|
||||||
|
|
||||||
const CARD_ICON: Record<string, string> = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' };
|
|
||||||
|
|
||||||
function DecisionCard({ c }: { c: SajuCard }) {
|
|
||||||
return (
|
|
||||||
<View className="flex-row gap-3 rounded-[20px] border-b-4 border-shade bg-card px-4 py-3">
|
|
||||||
<Ic name={CARD_ICON[c.kind] ?? 'sparkles'} size={32} />
|
|
||||||
<View className="min-w-0 flex-1">
|
|
||||||
<Text className="text-[12px] font-extrabold text-orange">{c.kind === 'when' ? '내 기운에 맞는 시간' : c.title}</Text>
|
|
||||||
<Text className="font-jua text-[17px] leading-snug text-ink">{c.kind === 'when' ? `${c.title} · ${c.sub ?? ''}` : c.body}</Text>
|
|
||||||
<Text className="mt-0.5 text-[12px] leading-snug font-semibold text-ink3">{(c.kind === 'when' ? c.body : c.sub) ?? ''}</Text>
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const RING_R = 46;
|
|
||||||
const RING_LEN = 2 * Math.PI * RING_R;
|
|
||||||
|
|
||||||
function ScoreRing({ score }: { score: number }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
return (
|
|
||||||
<View className="size-[116px] items-center justify-center" accessibilityLabel={`오늘의 점수 ${score}점`}>
|
|
||||||
<Svg viewBox="0 0 116 116" width={116} height={116} style={{ position: 'absolute', transform: [{ rotate: '-90deg' }] }}>
|
|
||||||
<Circle cx={58} cy={58} r={RING_R} fill="none" stroke={soft.bar} strokeWidth={11} />
|
|
||||||
<Circle cx={58} cy={58} r={RING_R} fill="none" stroke="#ff7a45" strokeWidth={11} strokeLinecap="round" strokeDasharray={`${(RING_LEN * score) / 100} ${RING_LEN}`} />
|
|
||||||
</Svg>
|
|
||||||
<Text className="font-bagel text-[40px] leading-[44px] text-ink">{score}</Text>
|
|
||||||
<Text className="text-[11px] font-extrabold text-ink3">오늘의 점수</Text>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ScoreBar({ label, value, width, color, signed }: { label: string; value: number; width: number; color: string; signed?: boolean }) {
|
|
||||||
const soft = useSoft();
|
|
||||||
return (
|
|
||||||
<View className="mt-2">
|
|
||||||
<View className="flex-row justify-between">
|
|
||||||
<Text className="text-[12.5px] font-extrabold" style={{ color }}>
|
|
||||||
{label}
|
|
||||||
</Text>
|
|
||||||
<Text className="text-[12.5px] font-extrabold" style={{ color }}>
|
|
||||||
{`${signed ? (value >= 0 ? '+' : '−') : ''}${Math.abs(value)}점`}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
<View className="mt-1 h-2 overflow-hidden rounded-full" style={{ backgroundColor: soft.bar }}>
|
|
||||||
<View className="h-full rounded-full" style={{ width: `${width}%`, backgroundColor: color }} />
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 오늘 점수와 할 일, 내 기운, 레벨로 열리는 이번 주·금전·연애·궁합·이달·올해 (웹 SajuPage Reading) */
|
|
||||||
export function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
|
|
||||||
const { region } = useRegion();
|
|
||||||
const { loggedIn } = useAuth();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const soft = useSoft();
|
|
||||||
const ink = String(useCSSVariable('--color-ink'));
|
|
||||||
const share = useShare();
|
|
||||||
const level = useLevel().data?.level;
|
|
||||||
const body = { ...toBody(birth), region_code: region.code, gender: birth.gender === 'M' ? ('male' as const) : birth.gender === 'F' ? ('female' as const) : undefined };
|
|
||||||
// 레벨이 오르면 키가 바뀌어 새로 열린 칸까지 다시 받는다. 사주를 보면 각이 쌓이니 레벨도 새로 받는다
|
|
||||||
const q = useQuery({
|
|
||||||
queryKey: ['saju', body, loggedIn, level],
|
|
||||||
staleTime: 10 * 60_000,
|
|
||||||
queryFn: async () => {
|
|
||||||
const { data } = await reading({ body });
|
|
||||||
if (!data.result?.success) throw new Error(data.result?.desc ?? 'saju');
|
|
||||||
if (loggedIn) void queryClient.invalidateQueries({ queryKey: myLevelQueryKey() });
|
|
||||||
return data;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const shot = useRef<View>(null);
|
|
||||||
const r = q.data;
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!r?.today) return;
|
|
||||||
markSajuSeen();
|
|
||||||
track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score, strength: r.me?.strength ?? '', top_element: r.me?.top_element ?? '' });
|
|
||||||
}, [r]);
|
|
||||||
|
|
||||||
if (q.isPending) return <Text className="px-4 py-16 text-center font-semibold text-ink2">사주를 풀고 있어요…</Text>;
|
|
||||||
if (!r?.today || !r.me)
|
|
||||||
return (
|
|
||||||
<View className="items-center px-4 py-16">
|
|
||||||
<Text className="text-center font-semibold text-ink2">결과를 불러오지 못했어요.</Text>
|
|
||||||
<Pressable onPress={() => void q.refetch()} accessibilityRole="button" className="mt-3 rounded-full bg-ink-btn px-4 py-2">
|
|
||||||
<Text className="text-[13px] font-extrabold text-white">다시 시도</Text>
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
const t = r.today;
|
|
||||||
const matchOpen = !!r.locks?.find((l) => l.key === 'saju_match')?.unlocked;
|
|
||||||
const title = `오늘 내 날씨 사주 ${t.score}점 · ${t.title}`;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<View className="gap-3">
|
|
||||||
<View ref={shot} collapsable={false} className="mx-4 mt-3 rounded-[26px] border-b-[5px] border-shade bg-card p-4">
|
|
||||||
<Text className="text-[12.5px] font-extrabold text-ink3">
|
|
||||||
{Number(t.day.slice(5, 7))}월 {Number(t.day.slice(8, 10))}일 {t.pillar}일 · 오늘의 점수
|
|
||||||
</Text>
|
|
||||||
<View className="mt-2 flex-row items-center gap-4">
|
|
||||||
<ScoreRing score={t.score} />
|
|
||||||
<View className="min-w-0 flex-1">
|
|
||||||
<Text className="font-jua text-[21px] leading-tight text-ink">{t.title}</Text>
|
|
||||||
<ScoreBar label="사주" value={t.saju_score} width={t.saju_score} color={ink} />
|
|
||||||
{t.weather_points != null && <ScoreBar label="날씨 영향" value={t.weather_points} width={Math.min(100, Math.abs(t.weather_points) * 3)} color={t.weather_points >= 0 ? '#1f7a4f' : '#e8663a'} signed />}
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
{(t.why?.length ?? 0) > 0 && (
|
|
||||||
<View className="mt-3 gap-1.5">
|
|
||||||
{t.why!.map((w) => {
|
|
||||||
const down = w.startsWith('↓');
|
|
||||||
return (
|
|
||||||
<Text key={w} className={`overflow-hidden rounded-xl px-3 py-2 text-[13px] leading-snug font-bold ${down ? 'text-warn' : 'text-ink'}`} style={{ backgroundColor: down ? soft.warm : soft.soft }}>
|
|
||||||
{w}
|
|
||||||
</Text>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
|
|
||||||
<View className="mx-4 gap-2">
|
|
||||||
{t.cards.map((c) => (
|
|
||||||
<DecisionCard key={c.kind} c={c} />
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
|
|
||||||
<MeCard r={r} onEdit={onEdit} />
|
|
||||||
|
|
||||||
{!!r.week && <Week days={r.week} />}
|
|
||||||
{!!r.money && <Money money={r.money} work={r.work ?? []} />}
|
|
||||||
{!!r.love && <Love love={r.love} birth={birth} />}
|
|
||||||
{matchOpen && <Match birth={birth} />}
|
|
||||||
{!!r.month && <Period id="saju_month" icon="spiral_calendar" p={r.month} />}
|
|
||||||
{!!r.year && <Period id="saju_year" icon="sunrise" p={r.year} />}
|
|
||||||
<Locked locks={(r.locks ?? []).filter((l) => !l.unlocked)} />
|
|
||||||
|
|
||||||
<View className="mx-4 flex-row items-center justify-between">
|
|
||||||
<Text className="text-xs font-semibold text-ink3">재미로 보는 날씨 사주</Text>
|
|
||||||
<Pressable onPress={() => void share(shot, { title, message: `${title} ${SITE_URL}/saju` })} accessibilityRole="button" className="rounded-full bg-ink-btn px-4 py-2">
|
|
||||||
<Text className="text-[13px] font-extrabold text-white">공유</Text>
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { router } from 'expo-router';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
|
||||||
import Svg, { Path } from 'react-native-svg';
|
|
||||||
import { useCSSVariable } from 'uniwind';
|
|
||||||
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import { useSky } from '@/lib/sky';
|
|
||||||
|
|
||||||
/** 탭 밖 화면(사주·이야기·게임 등) 머리줄: 뒤로 가기와 제목. 뒤로 갈 곳이 없으면(링크로 바로 열림) 오늘 탭으로 */
|
|
||||||
export function ScreenHeader({ title, right }: { title: string; right?: React.ReactNode }) {
|
|
||||||
const { top } = useSafeAreaInsets();
|
|
||||||
const { kind } = useSky();
|
|
||||||
const ink = String(useCSSVariable('--color-ink'));
|
|
||||||
const back = () => (router.canGoBack() ? router.back() : router.replace('/'));
|
|
||||||
return (
|
|
||||||
<View style={{ paddingTop: top, backgroundColor: kind === 'night' ? 'rgb(14 20 51 / 0.35)' : 'rgb(255 255 255 / 0.18)' }}>
|
|
||||||
<View className="h-[54px] flex-row items-center gap-1 px-2">
|
|
||||||
<Pressable onPress={back} hitSlop={8} accessibilityRole="button" accessibilityLabel="뒤로" className="size-10 items-center justify-center">
|
|
||||||
<Svg viewBox="0 0 24 24" width={24} height={24} fill="none" stroke={ink} strokeWidth={2.2} strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<Path d="M15 5l-7 7 7 7" />
|
|
||||||
</Svg>
|
|
||||||
</Pressable>
|
|
||||||
<Text numberOfLines={1} className="flex-1 font-jua text-[21px] text-ink">
|
|
||||||
{title}
|
|
||||||
</Text>
|
|
||||||
{right}
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
import type { ArticleSummary, ResSeasonWeek } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { ARTICLE_LABEL, cardBg, dateRange, shortDay } from '@nalssigak/shared/lib';
|
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
|
|
||||||
import { Fall } from '@/components/fall';
|
|
||||||
import { Credit, Ic, Skel, Thumb } from '@/components/ui';
|
|
||||||
import { CARD_BG } from '@/lib/colors';
|
|
||||||
import { useSky } from '@/lib/sky';
|
|
||||||
|
|
||||||
const HEAD_BOX = 'mx-3 mt-3 min-h-[250px] overflow-hidden rounded-[28px] p-5';
|
|
||||||
const ROW = 'flex-row items-center gap-3 border-b-[1.5px] border-line px-4 py-3.5';
|
|
||||||
const ROW_SKELS = [0, 1, 2, 3];
|
|
||||||
|
|
||||||
// 분류 글자색 (웹 ARTICLE_CAT). 밤엔 밝게
|
|
||||||
const CAT_COLOR: Record<number, [string, string]> = { 1: ['#1f9d62', '#4fd39a'], 2: ['#7a5cd6', '#b9a6ff'], 3: ['#ff7a45', '#ff8a57'] };
|
|
||||||
|
|
||||||
/** 특집 상자와 같은 틀: 머리말 · 제목 두 줄 · 시 한 줄 · 절기 막대 */
|
|
||||||
export function HeadSkel() {
|
|
||||||
return (
|
|
||||||
<View className={`${HEAD_BOX} gap-1.5 bg-card`}>
|
|
||||||
<Skel className="w-36" />
|
|
||||||
<Skel className="mt-1 h-7 w-[62%]" />
|
|
||||||
<Skel className="h-7 w-[40%]" />
|
|
||||||
<Skel className="mt-auto h-5 w-[72%]" />
|
|
||||||
<Skel className="mt-2.5 w-[70%]" />
|
|
||||||
<View className="h-[7px] w-[70%] rounded-full bg-skel" />
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function RowsSkel() {
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{ROW_SKELS.map((i) => (
|
|
||||||
<View key={i} className={ROW}>
|
|
||||||
<View className="flex-1 gap-1.5">
|
|
||||||
<Skel className="w-12" />
|
|
||||||
<Skel className="h-4 w-48" />
|
|
||||||
<Skel className="w-14" />
|
|
||||||
</View>
|
|
||||||
<View className="h-[84px] w-[84px] rounded-[18px] bg-skel" />
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 이번 주 특집: 제목·시·절기 막대. 누르면 이번 주 절기 창 */
|
|
||||||
export function SeasonHead({ week: w, onPress }: { week: ResSeasonWeek; onPress: () => void }) {
|
|
||||||
const { kind } = useSky();
|
|
||||||
const night = kind === 'night';
|
|
||||||
const progress = Math.round((w.progress ?? 0) * 100);
|
|
||||||
const poem = w.poem_lines ?? [];
|
|
||||||
return (
|
|
||||||
<Pressable onPress={onPress} className={HEAD_BOX}>
|
|
||||||
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'].peach} style={{ position: 'absolute', inset: 0 }} />
|
|
||||||
<Fall d={100} f={4800} style={{ position: 'absolute', top: '18%', right: 14, width: '38%', alignItems: 'center' }}>
|
|
||||||
<Ic name="maple" size={140} />
|
|
||||||
</Fall>
|
|
||||||
<Text className="text-[13px] font-extrabold text-ink opacity-75">이번 주 특집{w.start && w.end ? ` · ${dateRange(w.start, w.end)}` : ''}</Text>
|
|
||||||
<Text className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight text-ink">{w.headline}</Text>
|
|
||||||
{poem.length > 0 && <Text className="mt-auto max-w-[72%] pt-3 font-batang text-[22px] leading-[37px] text-ink">{poem.join('\n')}</Text>}
|
|
||||||
{!!w.term_now && !!w.term_next && (
|
|
||||||
<View className={`max-w-[70%] ${poem.length ? 'mt-2.5' : 'mt-auto'}`}>
|
|
||||||
<View className="flex-row justify-between">
|
|
||||||
<Text className="text-xs font-extrabold text-ink2">
|
|
||||||
{w.term_now.name} {shortDay(w.term_now.day)}
|
|
||||||
</Text>
|
|
||||||
<Text className="text-xs font-extrabold text-ink2">
|
|
||||||
{w.term_next.name} {shortDay(w.term_next.day)}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
<View className="mt-1 h-[7px] overflow-hidden rounded-full bg-[rgb(40_48_74/0.1)]" accessibilityRole="image" accessibilityLabel={`다음 절기까지 ${progress}% 지났어요`}>
|
|
||||||
<View className="h-full bg-orange" style={{ width: `${progress}%` }} />
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</Pressable>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ArticleRow({ article: a, onPress }: { article: ArticleSummary; onPress: () => void }) {
|
|
||||||
const { kind } = useSky();
|
|
||||||
const night = kind === 'night';
|
|
||||||
const color = CAT_COLOR[a.category]?.[night ? 1 : 0];
|
|
||||||
return (
|
|
||||||
<Pressable onPress={onPress} className={ROW}>
|
|
||||||
<View className="flex-1">
|
|
||||||
{!!ARTICLE_LABEL[a.category] && (
|
|
||||||
<Text className="text-xs font-extrabold" style={{ color }}>
|
|
||||||
{ARTICLE_LABEL[a.category]}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
<Text className="mt-0.5 font-jua text-[17.5px] leading-snug text-ink">{a.title}</Text>
|
|
||||||
<Text className="mt-1 text-xs font-semibold text-ink3">{a.read_minutes}분 읽기</Text>
|
|
||||||
</View>
|
|
||||||
<Thumb image={a.image} icon={a.icon} iconSize={54} className="h-[84px] w-[84px] rounded-[18px]">
|
|
||||||
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'][cardBg(a.icon, a.article_id)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
|
|
||||||
{!!a.image && !!a.image_credit && <Credit text={a.image_credit} />}
|
|
||||||
</Thumb>
|
|
||||||
</Pressable>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
import { getArticleOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
||||||
import { ARTICLE_LABEL, articleMeta, cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib';
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
|
||||||
import { useEffect, useRef } from 'react';
|
|
||||||
import { Pressable, View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
|
|
||||||
import { Credit, Ic, StateBox, Thumb } from '@/components/ui';
|
|
||||||
import { track } from '@/lib/analytics';
|
|
||||||
import { CARD_BG } from '@/lib/colors';
|
|
||||||
import { useSheet } from '@/lib/sheet';
|
|
||||||
import { useSky } from '@/lib/sky';
|
|
||||||
|
|
||||||
import { ArticleSkel, Body } from './parts';
|
|
||||||
|
|
||||||
export function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t: string) => void }) {
|
|
||||||
const q = useQuery(getArticleOptions({ path: { article_id: articleId } }));
|
|
||||||
const a = q.data?.article;
|
|
||||||
const night = useSky().kind === 'night';
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
onTitle(a ? (ARTICLE_LABEL[a.category] ?? '') : '');
|
|
||||||
}, [a, onTitle]);
|
|
||||||
|
|
||||||
const tracked = useRef(0);
|
|
||||||
useEffect(() => {
|
|
||||||
if (!a || tracked.current === a.article_id) return;
|
|
||||||
tracked.current = a.article_id;
|
|
||||||
track('select_content', { content_type: 'article', item_id: a.article_id, category: ARTICLE_LABEL[a.category] ?? a.category });
|
|
||||||
}, [a]);
|
|
||||||
|
|
||||||
const load = loadOf(q);
|
|
||||||
if (!a) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." hold={<ArticleSkel />} boxClassName="inset-0" />}</Body>;
|
|
||||||
return (
|
|
||||||
<Body>
|
|
||||||
<Thumb image={a.image} icon={a.icon} iconSize={96} className="mb-3.5 h-[150px] rounded-[20px]">
|
|
||||||
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'][cardBg(a.icon, a.article_id)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
|
|
||||||
{!!a.image && !!a.image_credit && <Credit text={a.image_credit} />}
|
|
||||||
</Thumb>
|
|
||||||
<Text className="text-[13px] font-extrabold text-ink2">{articleMeta(a)}</Text>
|
|
||||||
<Text className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight text-ink">{a.title}</Text>
|
|
||||||
{(q.data?.body ?? []).map((t) => (
|
|
||||||
<Text key={t} className="mb-2.5 text-[15px] leading-[1.7] text-ink">
|
|
||||||
{t}
|
|
||||||
</Text>
|
|
||||||
))}
|
|
||||||
</Body>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SeasonWeekSheet() {
|
|
||||||
const { open } = useSheet();
|
|
||||||
const night = useSky().kind === 'night';
|
|
||||||
const q = useQuery(getSeasonWeekOptions());
|
|
||||||
const w = q.data;
|
|
||||||
const load = loadOf(q);
|
|
||||||
if (!w?.headline) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이번 주 특집이 아직 없어요." hold={<ArticleSkel />} boxClassName="inset-0" />}</Body>;
|
|
||||||
return (
|
|
||||||
<Body>
|
|
||||||
<View className="mb-3.5 h-[150px] items-center justify-center overflow-hidden rounded-[20px]">
|
|
||||||
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'].peach} style={{ position: 'absolute', inset: 0 }} />
|
|
||||||
<Ic name="maple" size={96} />
|
|
||||||
</View>
|
|
||||||
<Text className="text-[13px] font-extrabold text-ink2">{w.start && w.end ? dateRange(w.start, w.end) : '이번 주'}</Text>
|
|
||||||
<Text className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight text-ink">{w.headline}</Text>
|
|
||||||
{(w.poem_lines ?? []).length > 0 && (
|
|
||||||
<View className="mb-2.5">
|
|
||||||
<Text className="font-batang text-[17px] leading-[29px] text-ink">
|
|
||||||
{w.poem_lines?.join(' ')}
|
|
||||||
</Text>
|
|
||||||
{!!w.author && <Text className="text-xs font-semibold text-ink3">{w.author}</Text>}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
{!!w.term_now && !!w.term_next && (
|
|
||||||
<Text className="mb-2.5 text-[15px] leading-[1.7] text-ink">
|
|
||||||
지금 절기는 {w.term_now.name}({shortDay(w.term_now.day)}), 다음 절기는 {w.term_next.name}({shortDay(w.term_next.day)})예요.
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
{(w.news ?? []).map((n) => (
|
|
||||||
<Pressable key={n.code} onPress={() => open({ type: 'article', articleId: n.article_id })} className="flex-row items-center gap-2.5 border-b-[1.5px] border-line py-2.5">
|
|
||||||
<Ic name={n.icon} size={32} />
|
|
||||||
<Text className="flex-1 font-jua text-base text-ink">{n.title}</Text>
|
|
||||||
</Pressable>
|
|
||||||
))}
|
|
||||||
</Body>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,393 +0,0 @@
|
|||||||
import {
|
|
||||||
addCommentMutation,
|
|
||||||
addTalkCommentMutation,
|
|
||||||
agreeTermsMutation,
|
|
||||||
blockAuthorMutation,
|
|
||||||
deleteCommentMutation,
|
|
||||||
getFeedQueryKey,
|
|
||||||
likeCommentMutation,
|
|
||||||
listBlockedQueryKey,
|
|
||||||
listCommentsInfiniteOptions,
|
|
||||||
listCommentsInfiniteQueryKey,
|
|
||||||
listTalkCommentsInfiniteOptions,
|
|
||||||
listTalkCommentsInfiniteQueryKey,
|
|
||||||
meQueryKey,
|
|
||||||
reportCommentMutation,
|
|
||||||
unlikeCommentMutation,
|
|
||||||
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
||||||
import { ReportReason, type CommentData, type ResCommentList } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { ago, loadOf } from '@nalssigak/shared/lib';
|
|
||||||
import { useInfiniteQuery, useMutation, useQueryClient, type InfiniteData } from '@tanstack/react-query';
|
|
||||||
import { useEffect, useRef, useState } from 'react';
|
|
||||||
import { Linking, Pressable, TextInput, View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import { useCSSVariable } from 'uniwind';
|
|
||||||
|
|
||||||
import { Avatar, Skel, StateBox } from '@/components/ui';
|
|
||||||
import { track } from '@/lib/analytics';
|
|
||||||
import { useAuth } from '@/lib/auth';
|
|
||||||
import { useRegion } from '@/lib/region';
|
|
||||||
import { useSheet, type CommentTarget } from '@/lib/sheet';
|
|
||||||
import { SITE_URL } from '@/lib/site';
|
|
||||||
|
|
||||||
import { Body, ErrorLine, Field, HeartIcon, useSoft } from './parts';
|
|
||||||
|
|
||||||
const NOT_FOUND = 3001; // 서버 ErrorType.NOT_FOUND
|
|
||||||
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍'];
|
|
||||||
const N3 = [0, 1, 2];
|
|
||||||
const REPORT_REASONS = [
|
|
||||||
[ReportReason.ABUSE, '욕설·비하'],
|
|
||||||
[ReportReason.AD, '광고'],
|
|
||||||
[ReportReason.PRIVACY, '개인정보 노출'],
|
|
||||||
[ReportReason.OTHER, '기타'],
|
|
||||||
] as const;
|
|
||||||
export const isCommentList = (q: { queryKey: readonly unknown[] }) => ['listComments', 'listTalkComments'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '');
|
|
||||||
const isTalkList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listTalks';
|
|
||||||
|
|
||||||
/** 댓글 목록 캐시 키: 지우기·신고 뒤 다시 받을 때 쓴다 */
|
|
||||||
function commentListKey(to: CommentTarget) {
|
|
||||||
return 'talkId' in to ? listTalkCommentsInfiniteQueryKey({ path: { talk_id: to.talkId } }) : listCommentsInfiniteQueryKey({ path: { post_id: to.postId } });
|
|
||||||
}
|
|
||||||
|
|
||||||
function Chip({ label, onPress, disabled, danger }: { label: string; onPress: () => void; disabled?: boolean; danger?: boolean }) {
|
|
||||||
const s = useSoft();
|
|
||||||
return (
|
|
||||||
<Pressable onPress={onPress} disabled={disabled} className={`rounded-[12px] px-3 py-2 disabled:opacity-50 ${danger ? 'bg-heart' : ''}`} style={danger ? undefined : { backgroundColor: s.soft }}>
|
|
||||||
<Text className={`text-[13px] font-extrabold ${danger ? 'text-white' : 'text-ink'}`}>{label}</Text>
|
|
||||||
</Pressable>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
|
|
||||||
function CommentMenu({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
|
|
||||||
const { loggedIn } = useAuth();
|
|
||||||
const { open } = useSheet();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const [step, setStep] = useState<'closed' | 'menu' | 'report' | 'block'>('closed');
|
|
||||||
const [failed, setFailed] = useState(false);
|
|
||||||
const report = useMutation(reportCommentMutation());
|
|
||||||
const block = useMutation(blockAuthorMutation());
|
|
||||||
const pending = report.isPending || block.isPending;
|
|
||||||
|
|
||||||
const finish = (notice: string, done: () => void) => ({
|
|
||||||
onSuccess: (res: { result?: { success?: boolean } }) => {
|
|
||||||
if (!res.result?.success) return setFailed(true);
|
|
||||||
done();
|
|
||||||
setStep('closed');
|
|
||||||
onNotice(notice);
|
|
||||||
queryClient.invalidateQueries({ predicate: isCommentList });
|
|
||||||
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() });
|
|
||||||
},
|
|
||||||
onError: () => setFailed(true),
|
|
||||||
});
|
|
||||||
const go = (next: typeof step) => {
|
|
||||||
setFailed(false);
|
|
||||||
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', ...to } });
|
|
||||||
setStep(next);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Pressable onPress={() => go(step === 'closed' ? 'menu' : 'closed')} hitSlop={10} accessibilityRole="button" accessibilityState={{ expanded: step !== 'closed' }} accessibilityLabel="댓글 메뉴" className="px-1">
|
|
||||||
<Text className="text-sm font-extrabold text-ink3">⋯</Text>
|
|
||||||
</Pressable>
|
|
||||||
{step !== 'closed' && (
|
|
||||||
<View className="mt-2 w-full flex-row flex-wrap items-center gap-1.5" accessibilityLabel="댓글 메뉴">
|
|
||||||
{step === 'menu' && (
|
|
||||||
<>
|
|
||||||
<Chip label="신고하기" onPress={() => go('report')} />
|
|
||||||
<Chip label="이 사람 차단하기" onPress={() => go('block')} />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{step === 'report' &&
|
|
||||||
REPORT_REASONS.map(([reason, label]) => (
|
|
||||||
<Chip key={reason} label={label} disabled={pending} onPress={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.', () => track('report', { content_type: 'comment', reason })))} />
|
|
||||||
))}
|
|
||||||
{step === 'block' && (
|
|
||||||
<>
|
|
||||||
<Text className="w-full text-[13px] font-bold text-ink">{c.nickname}님 댓글을 더는 안 볼까요?</Text>
|
|
||||||
<Chip label="차단하기" danger disabled={pending} onPress={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.', () => track('block', { content_type: 'comment' })))} />
|
|
||||||
<Chip label="취소" disabled={pending} onPress={() => go('closed')} />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{failed && (
|
|
||||||
<Text className="w-full text-[13px] font-bold text-heart" accessibilityRole="alert">
|
|
||||||
잠시 뒤에 다시 해 주세요.
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommentsSkel() {
|
|
||||||
return (
|
|
||||||
<View>
|
|
||||||
{N3.map((i) => (
|
|
||||||
<View key={i} className="flex-row items-start gap-2.5 py-2">
|
|
||||||
<View className="size-[34px] rounded-full bg-skel" />
|
|
||||||
<View className="flex-1 gap-1.5">
|
|
||||||
<Skel className="w-3/4" />
|
|
||||||
<Skel className="w-24" />
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommentRow({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
|
|
||||||
const { region } = useRegion();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const [heart, ink3] = useCSSVariable(['--color-heart', '--color-ink3']).map(String);
|
|
||||||
const [liked, setLiked] = useState(c.liked);
|
|
||||||
const [count, setCount] = useState(c.like_count);
|
|
||||||
const like = useMutation(likeCommentMutation());
|
|
||||||
const unlike = useMutation(unlikeCommentMutation());
|
|
||||||
const remove = useMutation(deleteCommentMutation());
|
|
||||||
const [removeFailed, setRemoveFailed] = useState(false);
|
|
||||||
const [likeFailed, setLikeFailed] = useState(false);
|
|
||||||
|
|
||||||
// 좋아요는 로그인 없이 된다 (웹과 같이)
|
|
||||||
const toggle = () => {
|
|
||||||
if (like.isPending || unlike.isPending) return;
|
|
||||||
const next = !liked;
|
|
||||||
setLikeFailed(false);
|
|
||||||
setLiked(next);
|
|
||||||
setCount((n) => n + (next ? 1 : -1));
|
|
||||||
const revert = () => {
|
|
||||||
setLiked(!next);
|
|
||||||
setCount(c.like_count);
|
|
||||||
};
|
|
||||||
(next ? like : unlike).mutate(
|
|
||||||
{ path: { comment_id: c.comment_id } },
|
|
||||||
{
|
|
||||||
onSuccess: (res) => {
|
|
||||||
if (res.result?.success) {
|
|
||||||
setLiked(!!res.liked);
|
|
||||||
if (res.like_count != null) setCount(res.like_count);
|
|
||||||
if (next) track('like', { content_type: 'comment', item_id: c.comment_id });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
revert();
|
|
||||||
// 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다
|
|
||||||
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: commentListKey(to) });
|
|
||||||
else setLikeFailed(true);
|
|
||||||
},
|
|
||||||
onError: () => {
|
|
||||||
revert();
|
|
||||||
setLikeFailed(true);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
// 지우는 동안은 흐리게 두고, 성공하면 다시 받기 전에 목록 캐시에서 바로 뺀다
|
|
||||||
const del = () => {
|
|
||||||
setRemoveFailed(false);
|
|
||||||
remove.mutate(
|
|
||||||
{ path: { comment_id: c.comment_id } },
|
|
||||||
{
|
|
||||||
onSuccess: async (res) => {
|
|
||||||
if (!res.result?.success) return setRemoveFailed(true);
|
|
||||||
const key = commentListKey(to);
|
|
||||||
await queryClient.cancelQueries({ queryKey: key });
|
|
||||||
queryClient.setQueryData<InfiniteData<ResCommentList>>(key, (data) =>
|
|
||||||
data ? { ...data, pages: data.pages.map((p) => ({ ...p, comments: p.comments?.filter((x) => x.comment_id !== c.comment_id) })) } : data,
|
|
||||||
);
|
|
||||||
queryClient.invalidateQueries({ queryKey: key });
|
|
||||||
if ('talkId' in to) queryClient.invalidateQueries({ predicate: isTalkList });
|
|
||||||
else queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
|
|
||||||
},
|
|
||||||
onError: () => setRemoveFailed(true),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<View className={`flex-row items-start gap-2.5 py-2 ${remove.isPending ? 'opacity-50' : ''}`}>
|
|
||||||
<Avatar character={c.character} color={c.color} mood={c.mood} />
|
|
||||||
<View className="flex-1">
|
|
||||||
<Text className="text-sm text-ink">
|
|
||||||
<Text className="font-extrabold">{c.nickname} </Text>
|
|
||||||
{c.official && (
|
|
||||||
<>
|
|
||||||
<Text className="bg-orange text-[10.5px] font-extrabold text-white">{' 날씨각 '}</Text>{' '}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{c.body}
|
|
||||||
</Text>
|
|
||||||
<View className="mt-0.5 flex-row flex-wrap items-center">
|
|
||||||
<Text className="text-xs font-bold text-ink3">
|
|
||||||
{ago(c.created_at)} · {likeFailed ? <Text className="text-heart">좋아요를 못 했어요. 잠시 뒤에 다시 눌러 주세요</Text> : `좋아요 ${count}개`}
|
|
||||||
{c.mine && (
|
|
||||||
<>
|
|
||||||
{' · '}
|
|
||||||
<Text onPress={remove.isPending ? undefined : del} className={removeFailed && !remove.isPending ? 'text-heart' : 'text-ink3'}>
|
|
||||||
{remove.isPending ? '지우는 중…' : removeFailed ? '못 지웠어요 · 다시' : '지우기'}
|
|
||||||
</Text>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Text>
|
|
||||||
{/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
|
|
||||||
{!c.mine && !c.official && <CommentMenu c={c} to={to} onNotice={onNotice} />}
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="댓글 좋아요" className="pt-1">
|
|
||||||
<HeartIcon size={16} fill={liked ? heart : 'none'} stroke={liked ? heart : ink3} />
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 포스트 댓글, 또는 사람 글 댓글(로그인한 사람만 쓴다) */
|
|
||||||
export function CommentsSheet({ to, draft }: { to: CommentTarget; draft?: string }) {
|
|
||||||
const { region } = useRegion();
|
|
||||||
const { me } = useAuth();
|
|
||||||
const { open } = useSheet();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const talkId = 'talkId' in to ? to.talkId : undefined;
|
|
||||||
const postId = 'postId' in to ? to.postId : undefined;
|
|
||||||
// 둘 중 하나만 받는다
|
|
||||||
const postList = useInfiniteQuery({
|
|
||||||
...listCommentsInfiniteOptions({ path: { post_id: postId ?? 0 } }),
|
|
||||||
initialPageParam: { path: { post_id: postId ?? 0 } },
|
|
||||||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
|
||||||
enabled: postId != null,
|
|
||||||
});
|
|
||||||
const talkList = useInfiniteQuery({
|
|
||||||
...listTalkCommentsInfiniteOptions({ path: { talk_id: talkId ?? 0 } }),
|
|
||||||
initialPageParam: { path: { talk_id: talkId ?? 0 } },
|
|
||||||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
|
||||||
enabled: talkId != null,
|
|
||||||
});
|
|
||||||
const list = talkId != null ? talkList : postList;
|
|
||||||
const addPost = useMutation(addCommentMutation());
|
|
||||||
const addTalk = useMutation(addTalkCommentMutation());
|
|
||||||
const add = { isPending: addPost.isPending || addTalk.isPending };
|
|
||||||
const agree = useMutation(agreeTermsMutation());
|
|
||||||
const s = useSoft();
|
|
||||||
const [addFailed, setAddFailed] = useState(false);
|
|
||||||
const [askTerms, setAskTerms] = useState(false);
|
|
||||||
const [notice, setNotice] = useState('');
|
|
||||||
const [text, setText] = useState(draft ?? '');
|
|
||||||
const inputRef = useRef<TextInput>(null);
|
|
||||||
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? [];
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!notice) return;
|
|
||||||
const t = setTimeout(() => setNotice(''), 3000);
|
|
||||||
return () => clearTimeout(t);
|
|
||||||
}, [notice]);
|
|
||||||
|
|
||||||
const send = () => {
|
|
||||||
const body = text.trim();
|
|
||||||
if (!body || add.isPending) return;
|
|
||||||
setAddFailed(false);
|
|
||||||
const handlers = {
|
|
||||||
onSuccess: (res: { result?: { success?: boolean; desc?: string } }) => {
|
|
||||||
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true);
|
|
||||||
setAddFailed(!res.result?.success);
|
|
||||||
if (!res.result?.success) return;
|
|
||||||
setText('');
|
|
||||||
queryClient.invalidateQueries({ queryKey: commentListKey(to) });
|
|
||||||
if (talkId != null) {
|
|
||||||
track('talk_comment', { talk_id: talkId });
|
|
||||||
queryClient.invalidateQueries({ predicate: isTalkList });
|
|
||||||
} else if (postId != null) {
|
|
||||||
track('comment', { post_id: postId });
|
|
||||||
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onError: () => setAddFailed(true),
|
|
||||||
};
|
|
||||||
if (talkId != null) addTalk.mutate({ path: { talk_id: talkId }, body: { body } }, handlers);
|
|
||||||
else if (postId != null) addPost.mutate({ path: { post_id: postId }, body: { body, region: region.code } }, handlers);
|
|
||||||
};
|
|
||||||
|
|
||||||
// 댓글은 로그인 없이 '○○구 익명'으로 쓴다. 로그인했으면 약관에 동의해야 쓸 수 있고, 동의하면 쓰던 댓글을 바로 올린다
|
|
||||||
const submit = () => {
|
|
||||||
if (talkId != null && !me) return open({ type: 'login', then: { type: 'comments', ...to, draft: text } });
|
|
||||||
if (me && !me.terms_agreed) return setAskTerms(true);
|
|
||||||
send();
|
|
||||||
};
|
|
||||||
const agreeAndSend = () => {
|
|
||||||
setAddFailed(false);
|
|
||||||
agree.mutate(
|
|
||||||
{},
|
|
||||||
{
|
|
||||||
onSuccess: (res) => {
|
|
||||||
if (!res.result?.success) return setAddFailed(true);
|
|
||||||
queryClient.setQueryData(meQueryKey(), res);
|
|
||||||
track('terms_agree', {});
|
|
||||||
setAskTerms(false);
|
|
||||||
send();
|
|
||||||
},
|
|
||||||
onError: () => setAddFailed(true),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Body>
|
|
||||||
{comments.length ? (
|
|
||||||
<>
|
|
||||||
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
|
|
||||||
{comments.map((c) => (
|
|
||||||
<CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} to={to} onNotice={setNotice} />
|
|
||||||
))}
|
|
||||||
{list.hasNextPage && (
|
|
||||||
<Pressable onPress={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 disabled:opacity-50">
|
|
||||||
<Text className="text-center text-sm font-bold text-ink3">{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}</Text>
|
|
||||||
</Pressable>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
) : loadOf(list) === 'loading' ? (
|
|
||||||
<CommentsSkel />
|
|
||||||
) : (
|
|
||||||
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} boxClassName="inset-0" />
|
|
||||||
)}
|
|
||||||
</Body>
|
|
||||||
{askTerms ? (
|
|
||||||
<View className="mx-3 gap-2 rounded-[16px] p-3" style={{ backgroundColor: s.soft }} accessibilityLabel="이용약관 동의">
|
|
||||||
<Text className="text-[13px] font-bold text-ink">댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요.</Text>
|
|
||||||
<View className="flex-row gap-2">
|
|
||||||
<Pressable onPress={() => void Linking.openURL(`${SITE_URL}/terms.html`)} accessibilityRole="link" className="flex-1 rounded-[12px] bg-card p-2.5">
|
|
||||||
<Text className="text-center text-[13px] font-extrabold text-ink">이용약관 보기</Text>
|
|
||||||
</Pressable>
|
|
||||||
<Pressable onPress={agreeAndSend} disabled={agree.isPending || add.isPending} className="flex-1 rounded-[12px] bg-orange p-2.5 disabled:opacity-60">
|
|
||||||
<Text className="text-center text-[13px] font-extrabold text-white">동의하고 쓰기</Text>
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
) : (
|
|
||||||
<View className="flex-row justify-around pt-1" accessibilityLabel="빠른 이모지">
|
|
||||||
{EMOJIS.map((e) => (
|
|
||||||
<Pressable
|
|
||||||
key={e}
|
|
||||||
disabled={add.isPending}
|
|
||||||
className="disabled:opacity-40"
|
|
||||||
onPress={() => {
|
|
||||||
setText((t) => (t + e).slice(0, 60));
|
|
||||||
inputRef.current?.focus();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Text className="text-[22px]">{e}</Text>
|
|
||||||
</Pressable>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
{addFailed ? <ErrorLine className="h-4 text-xs leading-4" text="댓글을 올리지 못했어요. 다시 해 주세요." /> : <Text className="h-4 text-center text-xs leading-4 font-bold text-ink2">{notice}</Text>}
|
|
||||||
<View className="flex-row items-center gap-2.5 border-t border-line px-3 py-2.5">
|
|
||||||
<View className="flex-1">
|
|
||||||
<Field ref={inputRef} round value={text} onChangeText={setText} editable={!add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : talkId != null ? '로그인하고 댓글 달기…' : '댓글 달기…'} accessibilityLabel="댓글" returnKeyType="send" onSubmitEditing={submit} />
|
|
||||||
</View>
|
|
||||||
<Pressable onPress={submit} disabled={add.isPending || !text.trim()} className="disabled:opacity-40">
|
|
||||||
<Text className="font-extrabold text-rain">{add.isPending ? '올리는 중…' : '게시'}</Text>
|
|
||||||
</Pressable>
|
|
||||||
</View>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,229 +0,0 @@
|
|||||||
import { getIndexOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
|
||||||
import type { Factor, ResIndexDetail } from '@nalssigak/shared/api/client/types.gen';
|
|
||||||
import { loadOf } from '@nalssigak/shared/lib';
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
|
||||||
import { useEffect, useRef } from 'react';
|
|
||||||
import { View } from 'react-native';
|
|
||||||
import { Text } from '@/components/text';
|
|
||||||
import Svg, { Circle, Line, Polygon, Text as SvgText, TSpan } from 'react-native-svg';
|
|
||||||
|
|
||||||
import { Ic, Skel, StateBox } from '@/components/ui';
|
|
||||||
import { track } from '@/lib/analytics';
|
|
||||||
import { useRegion } from '@/lib/region';
|
|
||||||
import { useSky } from '@/lib/sky';
|
|
||||||
|
|
||||||
import { Body, useSoft } from './parts';
|
|
||||||
|
|
||||||
const SLOT_KEYS = ['morning', 'day', 'evening', 'night'] as const;
|
|
||||||
const SLOT_NAMES = { morning: '아침', day: '낮', evening: '저녁', night: '밤' } as const;
|
|
||||||
const N4 = [0, 1, 2, 3];
|
|
||||||
const N6 = [0, 1, 2, 3, 4, 5];
|
|
||||||
|
|
||||||
const labelLines = (label: string) => {
|
|
||||||
const cut = label.indexOf(' ');
|
|
||||||
return cut < 0 ? [label] : [label.slice(0, cut), label.slice(cut + 1)];
|
|
||||||
};
|
|
||||||
|
|
||||||
function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[]; size?: number }) {
|
|
||||||
const night = useSky().kind === 'night';
|
|
||||||
const c = size / 2;
|
|
||||||
const r = size / 2 - 40;
|
|
||||||
const n = factors.length;
|
|
||||||
const pt = (i: number, v: number) => {
|
|
||||||
const a = -Math.PI / 2 + (i * 2 * Math.PI) / n;
|
|
||||||
return [c + Math.cos(a) * r * v, c + Math.sin(a) * r * v] as const;
|
|
||||||
};
|
|
||||||
const ring = (v: number) => factors.map((_, i) => pt(i, v).join(',')).join(' ');
|
|
||||||
return (
|
|
||||||
<View className="mt-2 items-center" accessibilityRole="image" accessibilityLabel={`${name} 요소별 점수`}>
|
|
||||||
<Svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
|
|
||||||
{[0.25, 0.5, 0.75, 1].map((v) => (
|
|
||||||
<Polygon key={v} points={ring(v)} fill={v === 1 ? (night ? '#222a5c' : '#f7f9fc') : 'none'} stroke={night ? 'rgba(255,255,255,0.18)' : '#d9e2ef'} strokeWidth={1.5} />
|
|
||||||
))}
|
|
||||||
{factors.map((f, i) => (
|
|
||||||
<Line key={f.axis} x1={c} y1={c} x2={pt(i, 1)[0]} y2={pt(i, 1)[1]} stroke={night ? 'rgba(255,255,255,0.12)' : '#e3e9f2'} strokeWidth={1.5} />
|
|
||||||
))}
|
|
||||||
<Polygon points={factors.map((f, i) => pt(i, f.value / 100).join(',')).join(' ')} fill="rgba(255,122,69,0.38)" stroke="#ff7a45" strokeWidth={3} strokeLinejoin="round" />
|
|
||||||
{factors.map((f, i) => (
|
|
||||||
<Circle key={f.axis} cx={pt(i, f.value / 100)[0]} cy={pt(i, f.value / 100)[1]} r={4.5} fill="#fff" stroke="#ff7a45" strokeWidth={2.5} />
|
|
||||||
))}
|
|
||||||
{factors.map((f, i) => {
|
|
||||||
const lines = labelLines(f.label);
|
|
||||||
const [x, y] = pt(i, 1.24);
|
|
||||||
return (
|
|
||||||
<SvgText key={f.axis} x={x} y={y - (lines.length - 1) * 7} textAnchor="middle" fontFamily="Jua_400Regular" fontSize={13} fill={night ? '#eef1ff' : '#28304a'}>
|
|
||||||
{lines.map((line, k) => (
|
|
||||||
<TSpan key={k} x={x} dy={k === 0 ? 4 : 14}>
|
|
||||||
{line}
|
|
||||||
</TSpan>
|
|
||||||
))}
|
|
||||||
</SvgText>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Svg>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function GakSkel() {
|
|
||||||
const s = useSoft();
|
|
||||||
return (
|
|
||||||
<View>
|
|
||||||
<View className="flex-row items-center gap-3">
|
|
||||||
<View className="size-[58px] rounded-full bg-skel" />
|
|
||||||
<View className="flex-1 gap-1.5">
|
|
||||||
<Skel className="h-6 w-28" />
|
|
||||||
<Skel className="w-4/5" />
|
|
||||||
</View>
|
|
||||||
<Skel className="h-10 w-14" />
|
|
||||||
</View>
|
|
||||||
<View className="mt-2 aspect-square w-full max-w-[250px] self-center rounded-full bg-skel" />
|
|
||||||
<View className="mt-2.5 flex-row gap-1.5">
|
|
||||||
{N4.map((i) => (
|
|
||||||
<View key={i} className="flex-1 items-center gap-1.5 rounded-2xl px-1 py-2.5" style={{ backgroundColor: s.soft }}>
|
|
||||||
<Skel className="w-8" />
|
|
||||||
<Skel className="h-6 w-9" />
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
<View className="mt-3.5 gap-3">
|
|
||||||
{N6.map((i) => (
|
|
||||||
<View key={i} className="flex-row items-center gap-2.5">
|
|
||||||
<Skel className="w-[70px]" />
|
|
||||||
<View className="h-[9px] flex-1 rounded-full bg-skel" />
|
|
||||||
<Skel className="w-10" />
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) => void }) {
|
|
||||||
const { region } = useRegion();
|
|
||||||
const s = useSoft();
|
|
||||||
const q = useQuery(getIndexOptions({ path: { index_id: indexId }, query: { region: region.code } }));
|
|
||||||
const d: ResIndexDetail | undefined = q.data;
|
|
||||||
const g = d?.index;
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
onTitle(g ? `${g.rank}위 ${g.name}` : '계산 근거');
|
|
||||||
}, [g, onTitle]);
|
|
||||||
|
|
||||||
// 지역이 바뀌어 다시 받아도 한 번만 보낸다
|
|
||||||
const tracked = useRef(0);
|
|
||||||
useEffect(() => {
|
|
||||||
if (!g || tracked.current === g.index_id) return;
|
|
||||||
tracked.current = g.index_id;
|
|
||||||
track('view_gak', { index_id: g.index_id, gak_name: g.name, score: g.score, rank: g.rank });
|
|
||||||
}, [g]);
|
|
||||||
|
|
||||||
const load = loadOf(q);
|
|
||||||
if (!g) return <Body>{load === 'loading' ? <GakSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={<GakSkel />} boxClassName="inset-0" />}</Body>;
|
|
||||||
const factors = d.factors ?? [];
|
|
||||||
const bands = d.bands ?? [];
|
|
||||||
const now = bands.find((b) => b.current);
|
|
||||||
return (
|
|
||||||
<Body>
|
|
||||||
<View className="flex-row items-center gap-3">
|
|
||||||
<Ic name={g.icon} size={58} />
|
|
||||||
<View className="flex-1">
|
|
||||||
<Text className="font-jua text-[22px] text-ink">{g.name}</Text>
|
|
||||||
{!!d.description && <Text className="mt-0.5 text-[13.5px] font-semibold text-ink2">{d.description}</Text>}
|
|
||||||
</View>
|
|
||||||
<Text className={`font-bagel text-[42px] ${g.active ? 'text-orange' : 'text-ink3'}`}>{g.score}</Text>
|
|
||||||
</View>
|
|
||||||
{!g.active && <Text className="mt-2 text-[13px] font-bold text-ink2">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</Text>}
|
|
||||||
{now && (
|
|
||||||
<Text className="mt-3 overflow-hidden rounded-2xl px-3.5 py-2.5 text-[14.5px] font-bold text-ink" style={{ backgroundColor: s.warm }}>
|
|
||||||
<Text className="font-jua text-orange">
|
|
||||||
{now.low}~{now.high}점{' '}
|
|
||||||
</Text>
|
|
||||||
{now.text}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
{factors.length > 2 && <Radar name={g.name} factors={factors} />}
|
|
||||||
{g.slots && g.slots.length > 0 && (
|
|
||||||
<View className="mt-2.5 flex-row gap-1.5" accessibilityLabel="오늘 시간대별 점수">
|
|
||||||
{SLOT_KEYS.map((k) => {
|
|
||||||
const sl = g.slots?.find((x) => x.slot === k);
|
|
||||||
const cur = g.active && g.slot === k;
|
|
||||||
return (
|
|
||||||
<View key={k} className="flex-1 items-center rounded-2xl px-1 py-2" style={{ backgroundColor: cur ? s.warm : s.soft }}>
|
|
||||||
<Text className="text-xs font-extrabold text-ink2">
|
|
||||||
{SLOT_NAMES[k]}
|
|
||||||
{cur && ' · 지금'}
|
|
||||||
</Text>
|
|
||||||
<Text className={`font-bagel text-xl ${sl ? 'text-orange' : 'text-ink3'}`}>{sl ? sl.score : '–'}</Text>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
{g.trend && g.trend.length > 0 && (
|
|
||||||
<View className="mt-2.5 flex-row gap-1.5">
|
|
||||||
{g.trend.map((t) => (
|
|
||||||
<View key={t.day} className="flex-1 items-center rounded-2xl px-1 py-2.5" style={{ backgroundColor: s.soft }}>
|
|
||||||
<Text numberOfLines={1} className="text-xs font-extrabold text-ink2">
|
|
||||||
{t.label}
|
|
||||||
</Text>
|
|
||||||
<Text className="font-bagel text-2xl text-orange">{t.score}</Text>
|
|
||||||
<Text className={`text-[11px] leading-4 font-extrabold text-ink2 ${t.estimated ? '' : 'opacity-0'}`}>예상</Text>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
{bands.length > 0 && (
|
|
||||||
<View className="mt-3.5 gap-1.5" accessibilityLabel="점수 구간별 설명">
|
|
||||||
{bands.map((b) => (
|
|
||||||
<View key={b.low} className={`flex-row items-start gap-2 ${b.current ? '' : 'opacity-45'}`}>
|
|
||||||
<View className={`w-[62px] items-center rounded-full py-px ${b.current ? 'bg-orange' : 'bg-ink3'}`}>
|
|
||||||
<Text className="font-jua text-xs text-white">
|
|
||||||
{b.low}~{b.high}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
<Text className="flex-1 text-[13px] font-semibold text-ink">{b.text}</Text>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
<View className="mt-3.5 gap-2.5">
|
|
||||||
{factors.map((f) => (
|
|
||||||
<View key={f.axis}>
|
|
||||||
<View className="flex-row items-center gap-2.5">
|
|
||||||
<Text className="w-[84px] text-[13.5px] font-bold text-ink">{f.label}</Text>
|
|
||||||
<View className="h-[9px] flex-1 overflow-hidden rounded-full" style={{ backgroundColor: s.bar }}>
|
|
||||||
<LinearGradient colors={['#ffc86e', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${f.value}%` }} />
|
|
||||||
</View>
|
|
||||||
<Text className="w-[52px] text-right text-xs text-ink2">비중 {f.weight}%</Text>
|
|
||||||
</View>
|
|
||||||
<Text className="mt-0.5 ml-[94px] text-[12.5px] font-semibold text-ink2">{f.note}</Text>
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
<View className="mt-3.5 gap-1.5">
|
|
||||||
{!!d.zero_reason && (
|
|
||||||
<Text className="text-[13px] font-semibold text-ink2">
|
|
||||||
<Text className="font-bold text-heart">오늘 걸린 조건:</Text> {d.zero_reason}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
{factors.length > 0 && (
|
|
||||||
<Text className="text-[13px] font-semibold text-ink2">
|
|
||||||
<Text className="font-bold text-ink">계산 방법:</Text> 요소 점수에 비중을 곱해 더하고, 가장 낮은 요소가 낮을수록 최대 25%까지 더 깎아요
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
{!!d.zero_rules && (
|
|
||||||
<Text className="text-[13px] font-semibold text-ink2">
|
|
||||||
<Text className="font-bold text-ink">점수 깎이는 조건:</Text> {d.zero_rules}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
{!!d.limit && (
|
|
||||||
<Text className="text-[13px] font-semibold text-ink2">
|
|
||||||
<Text className="font-bold text-ink">반영 못 한 것:</Text> {d.limit}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
</Body>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user