Compare commits

...
Author SHA1 Message Date
minaChoi 117de90c3e fix: 아래 창(로그인 등)이 열리고 닫힐 때 버벅여 보이던 것 — 반투명으로 40px만 올라와 뒤 탭 바가 비쳤고 닫힐 땐 툭 사라지며 쓰기 칸 테두리가 번쩍였음, 불투명하게 아래에서 끝까지 올라오고 내려가며 닫히게 2026-10-27 15:08:40 +09:00
minaChoi be60551f49 Merge branch 'fix/composer-login-no-keyboard' — 로그인 전 쓰기 칸은 키보드 없이 로그인 창 2026-10-27 14:55:46 +09:00
minaChoi dcf2fe5a53 fix: 로그인 안 한 채 쓰기 칸을 누르면 로그인 창이 버벅이던 것 — 칸에 포커스가 가며 키보드가 떴다 내려갔음, 로그인 전엔 읽기 전용으로 두고 누르면 로그인 창 2026-10-27 14:55:46 +09:00
minaChoi 132301dc28 Merge branch 'fix/google-button-skeleton' — 로그인 창 구글 버튼 스켈레톤 2026-10-27 14:49:42 +09:00
minaChoi dd133c9d52 fix: 로그인 창 구글 버튼 자리에 스켈레톤 — 빈칸에 버튼이 늦게 툭 튀어나와 버벅이는 것처럼 보이던 것, 다 그려지면 부드럽게 바꿔 보임 2026-10-27 14:49:41 +09:00
minaChoi 5459b97ba0 Merge branch 'fix/foliage-card-slide2' — 단풍 카드 2번째 장 가림, 히어로 아이콘 간격, 로그인 창 첫 열기 버벅임, 토스 글 종류 필터 되돌림 2026-10-27 14:40:33 +09:00
minaChoi 1908433e46 fix: 토스에서 가리던 글 종류(카드뉴스 등) 다시 보이게 — 토스 번들이 업데이트돼 d3d872b 필터를 되돌림 2026-10-27 14:40:33 +09:00
minaChoi 7dcd6c6a4c fix: 로그인 창을 처음 열 때 버벅이던 것 줄임 — 구글 로그인 스크립트는 한가할 때 미리 받고, 구글 버튼과 뒤 화면 멈추기는 창이 다 올라온 뒤에 2026-10-27 14:39:41 +09:00
minaChoi 7d84226105 fix: 히어로 하트·댓글·보내기 간격이 숫자가 붙으면 어긋나던 문제 — 버튼마다 좌우 여백을 같게 2026-10-27 14:39:41 +09:00
minaChoi c45940c358 fix: 피드 단풍 지도 카드 2번째 장(지금 가기 좋은 곳) 왼쪽이 가려지던 문제 — 가운데 맞추려 민 지도가 옆 장을 덮었음, 1번째 장 밖은 자름 2026-10-27 14:29:34 +09:00
minaChoi 09e8b4734a Merge branch 'feat/app-moon-bot' — 앱 히어로·달 포스트 실제 달 모양, 캐릭터 댓글 표시 2026-10-27 14:05:03 +09:00
minaChoi a87f245547 feat: 앱도 웹과 같이 — 히어로·달 포스트를 오늘 밤 실제 달 모양으로(저녁엔 노을빛, 어두운 달이면 흰 점수), 캐릭터 댓글에 '날씨각' 표시·신고 메뉴 없음 2026-10-27 14:05:03 +09:00
minaChoi 197fafdc02 Merge branch 'fix/login-sheet-loop' — 로그인 안 한 채 쓰기 칸 누르면 로그인 창이 닫혀도 다시 열리던 문제 2026-10-27 13:25:43 +09:00
minaChoi 65fd9b8fb1 fix: 로그인 안 한 채 동네 이야기 쓰기 칸을 누르면 로그인 창이 닫혀도 다시 열리던 문제 — 창이 포커스를 쓰기 칸으로 돌려놓아 반복됐음, 열기 전에 포커스를 뺌 2026-10-27 13:20:14 +09:00
minaChoi 668377660c Merge branch 'feat/moon-bot-comments' — 달 포스트·히어로 실제 달 모양, 날씨각 캐릭터 댓글, 홈 화면 추가 띠, 남이섬 중복·날짜 테스트 2026-10-27 13:17:34 +09:00
minaChoi 98b5c0cbe3 feat: 포스트를 만들 때 날씨각 캐릭터(해님·구름·달님) 댓글 1~2개 — '날씨각' 표시, 신고·차단 메뉴 없음, 이미 만든 날은 scripts/fill_bot_comments.py 2026-10-27 13:14:30 +09:00
minaChoi d32e24a5ab feat: 달 포스트·히어로 달을 오늘 밤 실제 모양으로 — 표면 무늬·빛 번짐, 보름엔 가장 밝게, 저녁엔 노을빛, 달 포스트는 밤하늘·별 배경 2026-10-27 13:14:30 +09:00
minaChoi fcc4163e15 feat: 홈 화면 추가 배너를 포스트 사이 한 줄 띠로 — 버튼 하나(추가)·닫기는 ×, 설명 한 줄로 줄임 2026-10-27 13:14:29 +09:00
minaChoi 882c7f06dc fix: 단풍 지도 남이섬 중복 제거(67곳), 날짜 따라 깨지던 노을 칸·방위각 테스트를 계절과 상관없이 맞게 2026-10-27 13:14:29 +09:00
43 changed files with 1343 additions and 170 deletions

No files matched your search

+3
View File
@@ -63,6 +63,9 @@
| [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` |
| [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` |
| [ ] | 쇼츠 자동재생 아이폰 사파리 실기기 확인 — 소리 꺼도 자동재생을 막는다는 보고 있음 | 헤드리스 크롬에서만 확인 | `frontend/src/b/Shorts.tsx` |
| [x] | 단풍 명소 `남이섬`이 두 번 들어감(절정 10-25·10-27) — 10-27(화목원) 쪽 지움, 67곳 | 10/27 전체 점검 | `frontend/seo/foliage_2026.json` |
| [x] | 날짜 따라 깨지던 테스트 2개 — 노을 칸은 그날 해 지는 시각으로, 방위각은 한 해 범위(240~300°)로 확인 | 10/27 전체 점검 | `backend/tests/test_weather_today.py`, `backend/tests/test_sky_api.py` |
| [x] | 빈 댓글 보완 — 포스트마다 날씨각 캐릭터(해님·구름·달님) 댓글 1~2개, '날씨각' 표시. 사람인 척하는 가짜 계정·부풀린 숫자는 안 함 | 10/27 결정 | `backend/services/bot_comment.py`, `backend/services/bot_comment.json` |
| [ ] | 인스타 운영 관리자 페이지(자동 게시 전 승인 메일) + 초기 이야기형 피드(각 100개·빨래각·소맥각·점수 산정법) | 10/21 회의 | |
| [ ] | 레이어 공유 아이디어 — 사용자 사진 위에 날씨각 정보를 얹어 공유(캐시워크식), 앱 기능으로 | 10/21 회의 (황 본부장 의견, 대표 방향) | |
| [ ] | iOS 개발자 계정 — 소장에게 기존 계정 확인, 어려우면 회사 계정 새로 만들기. 안드로이드 앱 계속 준비 | 10/21 회의 결정 | |
+1
View File
@@ -399,6 +399,7 @@ class Comment(Base):
user_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), nullable=True)
ip_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
bot: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)
body: Mapped[str] = mapped_column(String(60))
like_count: Mapped[int] = mapped_column(Integer, default=0)
report_count: Mapped[int] = mapped_column(Integer, default=0)
+18 -2
View File
@@ -1,11 +1,11 @@
from datetime import date
from typing import Optional
from sqlalchemy import select
from sqlalchemy import exists, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Post
from common.database.model.models import Comment, Post
class FeedCRUD:
@@ -21,6 +21,22 @@ class FeedCRUD:
if rows:
await s.execute(insert(Post).values(rows).on_conflict_do_nothing())
async def without_bot(self, s: AsyncSession, day: date) -> list[Post]:
"""그날 포스트 중 캐릭터 댓글이 아직 없는 것."""
has_bot = exists().where(Comment.post_id == Post.post_id, Comment.bot.is_not(None))
return list((await s.scalars(select(Post).where(Post.feed_date == day, Post.deleted.is_(False), ~has_bot))).all())
async def add_bot_comments(self, s: AsyncSession, lines: dict[int, list[tuple[str, str]]]) -> None:
"""캐릭터 댓글을 넣고 포스트 댓글 수를 늘린다. 같은 포스트·캐릭터는 한 번만 (동시에 불려도 겹치지 않게)."""
rows = [{"post_id": post_id, "bot": bot, "body": body} for post_id, x in lines.items() for bot, body in x]
if not rows:
return
added = (await s.execute(insert(Comment).values(rows).on_conflict_do_nothing().returning(Comment.post_id))).scalars().all()
for n in (1, 2):
ids = [post_id for post_id in set(added) if added.count(post_id) == n]
if ids:
await s.execute(update(Post).where(Post.post_id.in_(ids)).values(comment_count=Post.comment_count + n))
async def get(self, s: AsyncSession, post_id: int) -> Optional[Post]:
post = await s.get(Post, post_id)
return post if post is not None and not post.deleted else None
+3
View File
@@ -266,6 +266,9 @@ ALTER TABLE public.comment ALTER COLUMN user_id DROP NOT NULL;
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS ip_hash VARCHAR(64) NULL;
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS region_name VARCHAR(20) NULL;
CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL;
-- 날씨각 캐릭터(해님 sun·구름 cloud·달님 moon)가 포스트를 만들 때 단 댓글. user_id·ip_hash 는 비고 화면엔 '날씨각' 표시가 붙는다
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS bot VARCHAR(10) NULL;
CREATE UNIQUE INDEX IF NOT EXISTS uq_comment_bot ON public.comment (post_id, bot) WHERE bot IS NOT NULL;
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS terms_agreed_at TIMESTAMPTZ NULL;
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS report_count INTEGER NOT NULL DEFAULT 0;
+3
View File
@@ -13,7 +13,9 @@ from common.logger import LOG
from common.models.errors import error_info
from common.utils.kma_time import KST, kst_midnight, now_kst
from crud.card_crud import CardCRUD
from crud.feed_crud import FeedCRUD
from router.v1.card.protocol import CardItem, Req_CardCreate, Res_Card, Res_CardList
from services.bot_comment import fill_bot_comments
from services.external import instagram
from services.feed_service import _FEED_DAY_START, clear_feed_cache, feed_day
@@ -59,6 +61,7 @@ async def _publish(card_id: int) -> tuple[ErrorType, Res_Card]:
return err, Res_Card(result=error_info(err))
if card is None:
return ErrorType.NOT_FOUND, Res_Card(result=error_info(ErrorType.NOT_FOUND))
await fill_bot_comments(day, FeedCRUD())
await clear_feed_cache()
LOG.info(f"[card] publish {card_id} → post {card.post_id}")
return ErrorType.SUCCESS, Res_Card(card_id=card.card_id, status=CardStatus(card.status), post_id=card.post_id)
+2 -13
View File
@@ -1,10 +1,10 @@
from typing import Optional
from fastapi import APIRouter, Depends, Path, Query, Request
from fastapi import APIRouter, Depends, Path, Query
from common.auth import optional_user
from common.database.model.models import User
from common.enums import ErrorType, PostType
from common.enums import ErrorType
from common.liker import Liker, liker
from common.models.errors import error_info
from router.v1.feed.protocol import Res_Feed, Res_Post
@@ -13,26 +13,15 @@ from services.reaction_service import ReactionService
router = APIRouter(prefix="/v1/feed", tags=["feed"])
# 토스에 올라간 10/13 번들은 UV 까지만 알아서, 그 뒤에 생긴 글 종류(카드뉴스 등)가 오면 흰 화면이 된다
TOSS_KNOWN_MAX = PostType.UV.value
def _from_toss(request: Request) -> bool:
ref = request.headers.get("origin") or request.headers.get("referer") or ""
return "AppsInToss" in request.headers.get("user-agent", "") or ".tossmini.com" in ref
@router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠")
async def get_feed(
request: Request,
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
service: FeedService = Depends(), reactions: ReactionService = Depends(),
) -> Res_Feed:
err, feed = await service.feed(region)
if err is not ErrorType.SUCCESS:
return Res_Feed(result=error_info(err))
if _from_toss(request):
feed = feed.model_copy(update={"posts": [p for p in feed.posts if p.post_type.value <= TOSS_KNOWN_MAX]})
pinned = [x for x in (feed.hero_post, feed.gak_post, feed.foliage_post, feed.events_post, feed.season_post) if x is not None]
ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned]
counts = await reactions.counts(ids)
+2
View File
@@ -38,6 +38,8 @@ class RowsSlide(WebPacketProtocol):
rows: list[Row] = []
image: Optional[str] = None # 있으면 아이콘 대신 카드 전체에 사진
image_credit: Optional[str] = None # 사진 출처 표기 ("ⓒ한국관광공사")
moon_pct: Optional[int] = Field(default=None, description="달 포스트만: 빛나는 면의 비율 0~100 (아이콘 대신 이 모양으로 달을 그린다)")
moon_waxing: Optional[bool] = Field(default=None, description="달 포스트만: 차오르는 달이면 true (오른쪽이 밝음)")
class GakSlide(WebPacketProtocol):
+1
View File
@@ -39,6 +39,7 @@ class CommentData(WebPacketProtocol):
like_count: int
liked: bool
mine: bool
official: bool = Field(default=False, description="날씨각 캐릭터(해님·구름·달님)가 단 댓글. 이름 옆에 '날씨각' 표시")
created_at: datetime
+1 -1
View File
@@ -21,7 +21,7 @@ router = APIRouter(prefix="/v1/reaction", tags=["reaction"])
def _comment(v: CommentView) -> CommentData:
c = v.comment
return CommentData(comment_id=c.comment_id, nickname=v.nickname, character=v.character, color=v.color, mood=v.mood, body=c.body, like_count=c.like_count, liked=v.liked, mine=v.mine, created_at=c.created_at.astimezone(KST))
return CommentData(comment_id=c.comment_id, nickname=v.nickname, character=v.character, color=v.color, mood=v.mood, body=c.body, like_count=c.like_count, liked=v.liked, mine=v.mine, official=v.official, created_at=c.created_at.astimezone(KST))
async def _like(post_id: int, who: Liker, on: bool, service: ReactionService) -> Res_PostLike:
+26
View File
@@ -0,0 +1,26 @@
"""이미 만든 그날 포스트에 캐릭터 댓글을 단다 (기능을 넣은 날 한 번). 이미 달린 포스트는 건너뛴다.
python scripts/fill_bot_comments.py 2026-10-27"""
import asyncio
import os
import sys
from datetime import date
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
from common.enums import ErrorType # noqa: E402
from crud.feed_crud import FeedCRUD # noqa: E402
from services.bot_comment import fill_bot_comments # noqa: E402
from services.feed_service import clear_feed_cache # noqa: E402
async def main(day: date) -> int:
err = await fill_bot_comments(day, FeedCRUD())
await clear_feed_cache()
await DB_SESSION_MNG.stop()
print(f"bot comments {day}: {err.name}")
return 0 if err is ErrorType.SUCCESS else 1
if __name__ == "__main__":
sys.exit(asyncio.run(main(date.fromisoformat(sys.argv[1]))))
+648
View File
@@ -0,0 +1,648 @@
{
"WEATHER": [
[
[
"sun",
"옷차림 정하기 전에 한 번 보고 가요 ☀️"
],
[
"cloud",
"저는 하루 종일 하늘에서 구경할게요"
]
],
[
[
"cloud",
"시간마다 기온 보고 겉옷 챙길지 정해요"
],
[
"sun",
"아침이랑 낮 차이를 꼭 보세요!"
]
],
[
[
"sun",
"좋은 하루 시작해요! 오늘도 날씨각이 챙길게요"
],
[
"moon",
"저는 밤에 다시 올게요 🌙"
]
]
],
"ALERT": [
[
[
"cloud",
"나가기 전에 꼭 한 번 보고 가요"
],
[
"sun",
"다들 조심히 다녀요"
]
],
[
[
"cloud",
"챙길 것 미리 챙겨 두면 든든해요"
],
[
"moon",
"퇴근길도 조심히 오세요"
]
],
[
[
"sun",
"오늘은 실내 일정도 같이 생각해 봐요"
],
[
"cloud",
"무리하지 말아요"
]
]
],
"GAK": [
[
[
"sun",
"오늘 이거 할 사람 손! 🙋"
],
[
"cloud",
"저는 구경만 할게요"
]
],
[
[
"sun",
"계산 근거 누르면 왜 이 점수인지 나와요"
],
[
"moon",
"저녁엔 순위가 바뀌기도 해요 🌙"
]
],
[
[
"cloud",
"오늘 뭐 할지 고민될 땐 여기부터 봐요"
],
[
"sun",
"같이 갈 사람한테 보내 봐요!"
]
]
],
"SUNSET": [
[
[
"moon",
"노을 지면 제가 나올 차례예요 🌙"
],
[
"sun",
"저 퇴근할 때 손 흔들어 주세요 🌇"
]
],
[
[
"sun",
"해 지는 시간 맞춰 나가 봐요"
],
[
"cloud",
"구름이 조금 있어야 더 붉게 물든대요"
]
],
[
[
"moon",
"노을 사진 찍으면 저도 보여 주세요 📸"
],
[
"sun",
"저도요!"
]
]
],
"TOMORROW": [
[
[
"moon",
"내일 입을 옷은 미리 꺼내 두고 자요 🌙"
],
[
"sun",
"내일 아침에 봬요!"
]
],
[
[
"sun",
"내일 일정 잡기 전에 한 번 보고 가요"
],
[
"cloud",
"저도 내일 계획 세우는 중이에요"
]
],
[
[
"moon",
"오늘도 수고했어요. 내일 날씨는 여기 있어요"
],
[
"cloud",
"푹 자요"
]
]
],
"WEEK": [
[
[
"sun",
"이번 주 빨래할 날 미리 찍어 둬요 ☀️"
],
[
"cloud",
"제가 오는 날은 피해 주세요"
]
],
[
[
"cloud",
"주중 약속 잡을 때 참고하세요"
],
[
"sun",
"주말까지 쭉 봐 두면 편해요"
]
],
[
[
"sun",
"이번 주도 힘내요!"
],
[
"moon",
"밤마다 응원할게요 🌙"
]
]
],
"EVENT": [
[
[
"sun",
"같이 갈 사람한테 보내 봐요 🎉"
],
[
"moon",
"밤에 하는 거면 저도 갈게요 🌙"
]
],
[
[
"cloud",
"가기 전에 그날 날씨 한 번 더 봐요"
],
[
"sun",
"날씨 맞으면 바로 가요!"
]
],
[
[
"sun",
"이번 주에 하나쯤은 가 봐요"
],
[
"cloud",
"실내 행사면 제가 와도 괜찮아요"
]
]
],
"SEASON": [
[
[
"sun",
"이맘때만 볼 수 있는 이야기예요"
],
[
"cloud",
"놓치기 전에 한 번 가 봐요"
]
],
[
[
"moon",
"계절이 바뀌는 게 느껴져요"
],
[
"sun",
"그러게요!"
]
],
[
[
"sun",
"읽고 나면 나가 보고 싶어져요"
],
[
"cloud",
"저도요"
]
]
],
"TIP": [
[
[
"cloud",
"오, 이건 몰랐어요"
],
[
"sun",
"친구한테 아는 척하기 좋아요 ☀️"
]
],
[
[
"moon",
"알아 두면 쓸모 있는 이야기예요"
],
[
"cloud",
"저장해 둘게요"
]
],
[
[
"sun",
"오늘의 상식 하나 챙겨 가요!"
],
[
"moon",
"내일 또 하나 알려 줄게요"
]
]
],
"QUOTE": [
[
[
"moon",
"오늘 마음에 남는 말이네요 🌙"
],
[
"sun",
"저장해 두고 또 봐요"
]
],
[
[
"sun",
"이 말 들고 하루 시작해요"
],
[
"cloud",
"좋다…"
]
],
[
[
"cloud",
"천천히 한 번 더 읽어 봤어요"
],
[
"moon",
"저도요"
]
]
],
"WEEKEND_PLAN": [
[
[
"sun",
"주말 약속 정할 때 이거 보여 줘요"
],
[
"cloud",
"제가 오는 날은 실내로 가요"
]
],
[
[
"sun",
"벌써 주말이 기다려져요 ☀️"
],
[
"moon",
"저도요 🌙"
]
],
[
[
"moon",
"계획 세워 두면 주말이 더 길어요"
],
[
"sun",
"맞아요!"
]
]
],
"AIR": [
[
[
"cloud",
"창문 열기 전에 한 번 보고 가요"
],
[
"sun",
"환기는 공기 좋을 때 짧게!"
]
],
[
[
"sun",
"마스크 챙길지 여기서 정해요 😷"
],
[
"cloud",
"챙겨서 손해 볼 건 없어요"
]
],
[
[
"cloud",
"바람이 불면 공기가 좀 나아져요"
],
[
"moon",
"밤에 한 번 더 확인해 봐요"
]
]
],
"DAY_TRIP": [
[
[
"sun",
"주말에 훌쩍 떠나 볼까요? 🚗"
],
[
"cloud",
"저 없는 곳으로 가면 딱이에요"
]
],
[
[
"moon",
"돌아오는 길 노을도 챙겨 봐요 🌇"
],
[
"sun",
"좋아요!"
]
],
[
[
"sun",
"같이 갈 사람한테 보내 봐요!"
],
[
"cloud",
"운전 조심해요"
]
]
],
"MOON_FULL": [
[
[
"moon",
"오늘은 제가 제일 동그란 날이에요 🌕"
],
[
"sun",
"소원 하나씩 빌어요!"
]
],
[
[
"moon",
"고개 들어 한 번 봐 주세요"
],
[
"cloud",
"오늘은 안 가릴게요… 아마도"
]
]
],
"MOON_NEW": [
[
[
"moon",
"오늘은 제가 쉬는 날이에요. 별 구경 하세요 ✨"
],
[
"sun",
"별 사진 찍으면 보여 주세요!"
]
],
[
[
"moon",
"제가 없는 밤이라 별이 더 잘 보여요"
],
[
"cloud",
"저도 오늘은 얌전히 있을게요"
]
]
],
"MOON": [
[
[
"moon",
"오늘 밤 저 한 번 올려다봐 주세요 🌙"
],
[
"cloud",
"제가 가리면 미안해요"
]
],
[
[
"moon",
"하루하루 모양이 바뀌는 걸 보는 재미가 있어요"
],
[
"sun",
"내일은 또 다르겠네요"
]
],
[
[
"moon",
"다음 보름까지 같이 세어 봐요"
],
[
"sun",
"좋아요!"
]
]
],
"UV": [
[
[
"sun",
"오늘은 제가 좀 세요. 선크림 꼭 바르세요 ☀️"
],
[
"cloud",
"모자도 챙기면 좋아요"
]
],
[
[
"sun",
"낮에 나가면 그늘로 다녀요"
],
[
"cloud",
"물도 자주 마시고요"
]
],
[
[
"cloud",
"흐려도 자외선은 와요. 선크림 잊지 마세요"
],
[
"sun",
"맞아요!"
]
]
],
"HERO": [
[
[
"sun",
"오늘 날씨 어때요? ☀️"
],
[
"cloud",
"창밖 한 번 보고 와요"
]
],
[
[
"moon",
"오늘도 날씨각이 먼저 챙겨 볼게요"
],
[
"sun",
"같이 봐요!"
]
],
[
[
"sun",
"출근길 날씨 같이 봐요!"
],
[
"cloud",
"우산은 여기서 확인해요"
]
]
],
"TODAY_GAK": [
[
[
"sun",
"오늘 1위 해 본 사람? 🙋"
],
[
"cloud",
"저는 집콕이 좋아요"
]
],
[
[
"sun",
"누르면 왜 이 점수인지 나와요"
],
[
"moon",
"저녁엔 순위가 바뀌기도 해요 🌙"
]
]
],
"FOLIAGE": [
[
[
"sun",
"단풍 보러 어디 가세요? 🍁"
],
[
"cloud",
"위에서 보면 정말 예뻐요"
]
],
[
[
"moon",
"절정 지나기 전에 꼭 가 봐요"
],
[
"sun",
"가까운 곳부터 찾아봐요"
]
]
],
"EVENTS_BAND": [
[
[
"sun",
"이번 주 뭐 하고 놀지 여기서 골라요 🎉"
],
[
"cloud",
"가기 전에 날씨도 같이 봐요"
]
]
],
"SEASON_BAND": [
[
[
"moon",
"예년 이맘때 이야기 읽는 재미가 있어요"
],
[
"sun",
"계절 바뀌는 거 같이 느껴 봐요"
]
]
],
"CARD": [
[
[
"sun",
"오늘 카드 저장해 두고 또 봐요 ✨"
],
[
"cloud",
"저는 두 번째 장이 좋아요"
]
],
[
[
"moon",
"친구한테도 보내 줘요"
],
[
"sun",
"같이 보면 더 재밌어요!"
]
]
]
}
+50
View File
@@ -0,0 +1,50 @@
"""날씨각 캐릭터(해님·구름·달님)가 포스트를 만들 때 다는 댓글. 문구는 bot_comment.json 에 글 종류마다 1~2줄 세트로 있다.
포스트는 시도마다 하나라 구마다 내용이 달라, 문구엔 숫자나 그날 날씨를 단정하는 말을 넣지 않는다."""
import json
import random
from datetime import date, datetime, time, timedelta
from pathlib import Path
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import ErrorType, PostType
from common.logger import LOG
from common.utils.kma_time import KST
from crud.feed_crud import FeedCRUD
from services.calc.moon import nearest
BOT_NAMES = {"sun": "해님", "cloud": "구름", "moon": "달님"}
BOT_COLORS = {"sun": "orange", "cloud": "blue", "moon": "purple"}
_COPY: dict[str, list[list[list[str]]]] = json.loads((Path(__file__).parent / "bot_comment.json").read_text(encoding="utf-8"))
def _moon_key(day: date) -> str:
"""그날 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기. 달 포스트(FeedService._moon)와 같은 기준."""
start = datetime.combine(day, time(12), tzinfo=KST)
tonight = start + timedelta(hours=10)
if start <= nearest(tonight, True) < start + timedelta(days=1):
return "MOON_FULL"
if start <= nearest(tonight, False) < start + timedelta(days=1):
return "MOON_NEW"
return "MOON"
def bot_lines(post_type: PostType, day: date, seed: int) -> list[tuple[str, str]]:
"""포스트에 달 (캐릭터, 문구) 1~2줄. 세트 하나를 고르고 1줄이면 첫 줄만, 2줄이면 둘째 줄이 첫 줄에 답한다. 같은 seed 면 늘 같다."""
sets = _COPY.get(_moon_key(day) if post_type is PostType.MOON else post_type.name)
if not sets:
return []
rng = random.Random(seed)
pick = rng.choice(sets)
return [(bot, body) for bot, body in pick[: rng.randint(1, len(pick))]]
async def fill_bot_comments(day: date, crud: FeedCRUD) -> ErrorType:
"""그날 포스트 중 캐릭터 댓글이 없는 것에 단다. 여러 번 불러도 한 번만 달린다."""
err, posts = await DB_SESSION_MNG.execute_lambda(lambda s: crud.without_bot(s, day))
if err is not ErrorType.SUCCESS:
return err
lines = {p.post_id: bot_lines(PostType(p.post_type), p.feed_date, p.post_id) for p in posts or []}
lines = {post_id: x for post_id, x in lines.items() if x}
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: crud.add_bot_comments(s, lines)])
LOG.info(f"[feed] bot comments {day} posts {len(lines)}: {err.name}")
return err
+6 -3
View File
@@ -27,6 +27,7 @@ from router.v1.feed.protocol import (
)
from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL
from services.air_service import pm10_grade, pm25_grade
from services.bot_comment import fill_bot_comments
from services.calc.day_slot import NIGHT_AFTER_SUNSET, slot_of
from services.calc.index_calc import rank_score
from services.calc.moon import MoonNight, nearest, night, view_line
@@ -315,6 +316,8 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, reg
})
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: crud.insert_day(s, rows)])
LOG.info(f"[feed] build {day} posts {len(rows)}: {err.name}")
if err is ErrorType.SUCCESS:
err = await fill_bot_comments(day, crud)
return err
@@ -600,7 +603,7 @@ class FeedService:
else "구름 사이로 잠깐씩 보일 수도 있어요." if view.startswith("흐려서")
else "하루하루 차오르는 중이에요. 보름까지 같이 세어 봐요 🌙" if waxing else "조금씩 기우는 중이에요. 그만큼 별은 더 잘 보여요 ✨")
return PostData(**base, title=f"오늘 밤 {name}", icon="moon", caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n{view}", icon="moon",
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=f"오늘 밤은 {name},\n{view}", icon="moon", moon_pct=round(m.lit * 100), moon_waxing=m.waxing,
rows=[*rows, Row(label="다음 보름", value=f"{nxt.month}.{nxt.day:02d} ({_WEEKDAY_KO[nxt.weekday()]})")])],
share_messages=[f"오늘 밤은 {name}이래 🌙"])
when = f"{'내일 ' if at.date() > tonight.date() else ''}{at:%H:%M}"
@@ -608,14 +611,14 @@ class FeedService:
line = f"오늘 밤 보름달,\n{when}에 가장 둥글어요"
caption = "구름 사이로 잠깐씩 보일 수 있어요." if view.startswith("흐려서") else "소원 빌기 딱 좋은 밤이에요 🌕"
return PostData(**base, title="오늘 밤 보름달", icon="moon", caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", rows=[Row(label="보이는지", value=view), *rows])],
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line=line, icon="moon", moon_pct=100, moon_waxing=False, rows=[Row(label="보이는지", value=view), *rows])],
share_messages=["오늘 밤 보름달이래 🌕 같이 볼래?"])
stars = next((i for i in (c.board.items if c.board else []) if i.definition.code == "stars"), None)
if stars is not None:
rows.append(Row(label="별보기각", value=f"{stars.score.score}점"))
caption = "구름이 많아 별은 아쉬워요." if sky is Sky.CLOUDY else "불빛 적은 곳으로 조금만 나가 봐요 ✨"
return PostData(**base, title="오늘 밤 달 없는 밤", icon="moon", caption=caption,
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line="달이 숨는 밤,\n별이 제일 잘 보여요", icon="moon", rows=rows)],
slides=[RowsSlide(kind="rows", eyebrow=eyebrow, line="달이 숨는 밤,\n별이 제일 잘 보여요", icon="moon", moon_pct=0, moon_waxing=True, rows=rows)],
share_messages=["오늘 밤 달이 없어서 별 보기 좋대 ✨"])
def _day_trip(self, base: dict, pick: TripPick, events: list[EventItem]) -> PostData:
+4
View File
@@ -13,6 +13,7 @@ from common.utils.kma_time import kst_midnight, now_kst
from crud.feed_crud import FeedCRUD
from crud.reaction_crud import ReactionCRUD
from crud.region_crud import RegionCRUD
from services.bot_comment import BOT_COLORS, BOT_NAMES
from services.talk_service import _LINK, _PHONE
COMMENT_MAX = 60
@@ -31,6 +32,7 @@ class CommentView:
mood: Optional[str]
liked: bool
mine: bool
official: bool = False
@dataclass
@@ -87,6 +89,8 @@ class ReactionService:
@staticmethod
def _view(c: Comment, nickname: Optional[str], character: Optional[str], color: Optional[str], mood: Optional[str], liked: bool, who: Liker) -> CommentView:
if c.bot is not None:
return CommentView(comment=c, nickname=BOT_NAMES.get(c.bot, "날씨각"), character=c.bot, color=BOT_COLORS.get(c.bot, ANON_COLOR), mood=None, liked=liked, mine=False, official=True)
if c.user_id is None:
mine = who.user_id is None and c.ip_hash == who.ip_hash
return CommentView(comment=c, nickname=f"{c.region_name} 익명" if c.region_name else "익명", character=ANON_CHARACTER, color=ANON_COLOR, mood=None, liked=liked, mine=mine)
+9
View File
@@ -73,6 +73,15 @@ def _no_seoul_crawl(monkeypatch):
monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([]))
@pytest.fixture
def no_bot_comments(monkeypatch):
"""사람이 단 댓글·좋아요만 세는 테스트용: 포스트를 만들 때 캐릭터 댓글을 달지 않는다 (캐릭터 댓글은 test_bot_comment)."""
import services.feed_service as feed_service
from common.enums import ErrorType
monkeypatch.setattr(feed_service, "fill_bot_comments", lambda *a: _async(ErrorType.SUCCESS))
@pytest.fixture
def offline(monkeypatch):
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
+1
View File
@@ -4,6 +4,7 @@ from httpx import ASGITransport, AsyncClient
from router.router import app
REGION = "1144000000"
pytestmark = pytest.mark.usefixtures("no_bot_comments")
IP_A = {"X-Forwarded-For": "203.0.113.10"}
IP_B = {"X-Forwarded-For": "203.0.113.20"}
+1
View File
@@ -4,6 +4,7 @@ from httpx import ASGITransport, AsyncClient
from router.router import app
REGION = "1144000000"
pytestmark = pytest.mark.usefixtures("no_bot_comments")
def client():
+82
View File
@@ -0,0 +1,82 @@
from datetime import date, datetime
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import text
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import PostType
from common.utils.kma_time import KST
from crud.feed_crud import FeedCRUD
from router.router import app
from services.bot_comment import _COPY, BOT_NAMES, _moon_key, bot_lines, fill_bot_comments
from services.feed_service import LINEUP
DAY = date(2001, 1, 2)
def test_every_post_type_has_lines_from_known_characters():
for t in {x[1] for x in LINEUP} | {PostType.CARD}:
assert bot_lines(t, DAY, 1), t
for sets in _COPY.values():
for s in sets:
assert 1 <= len(s) <= 2 and len({bot for bot, _ in s}) == len(s)
assert all(bot in BOT_NAMES and 0 < len(body) <= 60 for bot, body in s)
def test_lines_are_one_or_two_and_same_for_same_post():
counts = {len(bot_lines(PostType.GAK, DAY, post_id)) for post_id in range(40)}
assert counts == {1, 2}
assert bot_lines(PostType.GAK, DAY, 7) == bot_lines(PostType.GAK, DAY, 7)
def test_moon_lines_follow_full_and_new_moon_nights():
assert _moon_key(date(2025, 10, 7)) == "MOON_FULL" # 보름 10.07 12:47
assert _moon_key(date(2024, 4, 8)) == "MOON_NEW" # 삭 04.09 03:21, 그 전날 밤
assert _moon_key(date(2025, 10, 4)) == "MOON"
full = {body for s in _COPY["MOON_FULL"] for _, body in s}
assert bot_lines(PostType.MOON, date(2025, 10, 7), 3)[0][1] in full
@pytest.fixture
async def day_posts():
async def wipe():
await DB_SESSION_MNG.execute_lambda_run([
lambda s: s.execute(text(f"DELETE FROM comment WHERE post_id IN (SELECT post_id FROM post WHERE feed_date = '{DAY}')")),
lambda s: s.execute(text(f"DELETE FROM post WHERE feed_date = '{DAY}'")),
])
await wipe()
rows = [{"feed_date": DAY, "position": i, "scope": "00", "post_type": t.value, "ref_type": 1, "published_at": datetime(2001, 1, 2, 3, tzinfo=KST)}
for i, t in enumerate([PostType.WEATHER, PostType.GAK, PostType.MOON, PostType.SUNSET], 1)]
await DB_SESSION_MNG.execute_lambda_run([lambda s: FeedCRUD().insert_day(s, rows)])
yield
await wipe()
async def _counts():
sql = f"""SELECT p.post_id, p.comment_count, count(c.comment_id) FROM post p LEFT JOIN comment c ON c.post_id = p.post_id AND c.bot IS NOT NULL
WHERE p.feed_date = '{DAY}' GROUP BY p.post_id, p.comment_count ORDER BY p.post_id"""
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(sql)))
return [tuple(r) for r in rows.all()]
@pytest.mark.anyio
async def test_fill_adds_one_or_two_comments_once_and_counts_them(day_posts):
await fill_bot_comments(DAY, FeedCRUD())
first = await _counts()
assert len(first) == 4 and all(1 <= n <= 2 and count == n for _, count, n in first)
await fill_bot_comments(DAY, FeedCRUD())
assert await _counts() == first
post_id = first[0][0]
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
comments = (await c.get(f"/v1/reaction/post/{post_id}/comment/list")).json()["comments"]
assert comments and all(x["official"] and x["nickname"] in BOT_NAMES.values() and not x["mine"] for x in comments)
@pytest.mark.anyio
async def test_feed_build_puts_character_comments_on_new_posts(offline):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
feed = (await c.get("/v1/feed", params={"region": "1144000000"})).json()
assert feed["hero_post"]["comment_count"] >= 1
assert all(p["comment_count"] >= 1 for p in feed["posts"])
-18
View File
@@ -1,18 +0,0 @@
from starlette.requests import Request
from common.enums import PostType
from router.v1.feed.feed import TOSS_KNOWN_MAX, _from_toss
def _req(headers: dict) -> Request:
return Request({"type": "http", "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()]})
def test_from_toss_by_referer_or_user_agent():
assert _from_toss(_req({"referer": "https://nalssigak.apps.tossmini.com/"}))
assert _from_toss(_req({"user-agent": "Mozilla/5.0 ... AppsInToss TossApp/5.282.1"}))
assert not _from_toss(_req({"referer": "https://weather.o2o.kr/", "user-agent": "Mozilla/5.0 Safari"}))
def test_card_is_hidden_from_old_toss_bundle():
assert PostType.CARD.value > TOSS_KNOWN_MAX >= PostType.UV.value
+11
View File
@@ -41,6 +41,17 @@ def test_moon_post_every_night_with_full_and_new_moon_stories():
assert plain.title == "오늘 밤 차오르는 달" and plain.slides[0].rows[-1].label == "다음 보름" and plain.slides[0].rows[-1].value.startswith("10.07")
def test_moon_post_slide_carries_shape_for_drawing():
full = _moon_post(datetime(2025, 10, 7, 20, 0, tzinfo=KST)).slides[0]
assert full.moon_pct == 100
new = _moon_post(datetime(2024, 4, 9, 1, 0, tzinfo=KST)).slides[0]
assert new.moon_pct == 0
waxing = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)).slides[0]
assert 70 < waxing.moon_pct < 97 and waxing.moon_waxing is True
waning = _moon_post(datetime(2025, 10, 10, 20, 0, tzinfo=KST)).slides[0]
assert 70 < waning.moon_pct < 97 and waning.moon_waxing is False
SEOUL = (37.57, 126.98)
+1
View File
@@ -17,6 +17,7 @@ from router.router import app
from services.feed_service import LINEUP, NATIONAL_SCOPE, NATIONAL_TYPES, build_feed_day, feed_day, sido_of
SEOUL_A, SEOUL_B, BUSAN = "1111000000", "1114000000", "2611000000"
pytestmark = pytest.mark.usefixtures("no_bot_comments")
REGION_CSV = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "region.csv")
+2 -1
View File
@@ -49,7 +49,8 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
assert body["sunset"]["confidence"] == 1
assert len(body["days"]) == 3
assert [s["name"] for s in body["spots"]] == ["망원한강공원", "선유도공원", "하늘공원"]
assert 255 <= body["sunset_azimuth"] <= 280
# 서울 해 지는 방위는 한 해 동안 240°(동지)~300°(하지) 사이
assert 240 <= body["sunset_azimuth"] <= 300
plan = body["plan"]
assert plan["verdict"] == "go" and plan["headline"] == "나가 볼 만해요" and plan["when"] in ("오늘", "내일")
assert "적당히" in plan["reason"]
+8 -2
View File
@@ -8,7 +8,9 @@ from sqlalchemy import text
import services.weather_service as weather_service
from common.cache.redis_client import REDIS
from common.database.db_session_manager import DB_SESSION_MNG
from common.utils.kma_time import kst_midnight, latest_vilage_base, now_kst
from common.utils.kma_time import KST, kst_midnight, latest_vilage_base, now_kst
from crud.region_crud import RegionCRUD
from services.calc.sun import sun_times
from services.external.kma import day_start_base
from router.router import app
@@ -57,7 +59,11 @@ async def test_today_fetches_stores_and_returns_8_slots(monkeypatch, clean_regio
assert [s["label"] for s in body["slots"]] == ["0시", "3시", "6시", "9시", "12시", "15시", "18시", "21시"]
assert all(s["temp_c"] == 18 for s in body["slots"])
assert body["slots"][0]["icon"] == "moon"
assert body["slots"][6]["icon"] == "sunset" and body["slots"][6]["note"] == "노을"
# 해 지는 시각이 든 3시간 칸이 노을 (여름엔 18시 칸, 늦가을·겨울엔 15시 칸)
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().get(s, REGION))
at = sun_times(now_kst().date(), float(region.lat), float(region.lon)).sunset_at.astimezone(KST)
dusk = body["slots"][at.hour // 3]
assert dusk["icon"] == "sunset" and dusk["note"] == "노을"
assert len(calls) == 2
-10
View File
@@ -547,16 +547,6 @@
"basis": "가장 가까운 산림청 예측 지점(수리산, 단풍나무류) 날짜",
"coord_point": "경복궁"
},
{
"name": "남이섬",
"kind": "ginkgo",
"region": "강원 춘천",
"lat": 37.79627,
"lon": 127.52549,
"peak": "2026-10-27",
"basis": "가장 가까운 산림청 예측 지점(강원도립화목원, 은행나무) 날짜",
"coord_point": "남이섬"
},
{
"name": "덕수궁 돌담길",
"kind": "ginkgo",
+12 -2
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
import { useIsFetching, useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { useIsFetching, useQuery, useQueryClient } from '@tanstack/react-query'
import { authConfigOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils'
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
@@ -9,6 +9,7 @@ import './b.css'
import { AuthProvider } from './auth'
import { RegionProvider } from './region'
import { useAuth } from './authContext'
import { preloadGoogle } from './googleScript'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { SheetProvider } from './Sheets'
@@ -47,7 +48,16 @@ function TopBar() {
const { region, locateStatus } = useRegion()
const { open } = useSheet()
const { me, mePending } = useAuth()
const queryClient = useQueryClient()
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
const loggedOut = !IS_TOSS && !mePending && !me
// 로그인 창을 처음 열 때 버벅이지 않게 구글 로그인 준비물을 미리 받아 둔다
useEffect(() => {
if (!loggedOut) return
void queryClient.prefetchQuery({ ...authConfigOptions(), staleTime: Infinity })
return preloadGoogle()
}, [loggedOut, queryClient])
return (
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
+1 -1
View File
@@ -52,7 +52,7 @@ function Marker({ p, sel }: { p: Pt; sel: boolean }) {
)
}
/** 단풍 지도 페이지: 명소 68곳을 지도에서 확대해 보고 목록으로 고른다. 한 손가락은 확대 전엔 페이지 스크롤, 확대 뒤엔 지도 이동 */
/** 단풍 지도 페이지: 명소 67곳을 지도에서 확대해 보고 목록으로 고른다. 한 손가락은 확대 전엔 페이지 스크롤, 확대 뒤엔 지도 이동 */
export function FoliagePage() {
const navigate = useNavigate()
const [params] = useSearchParams()
+25 -3
View File
@@ -13,6 +13,7 @@ import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { useSheet } from './sheetContext'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { useCarousel } from './carousel'
import { MoonArt } from './moon'
import { Arrows, Credit, Ic, Rows, Skel, TAP44, Thumb } from './ui'
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
@@ -52,7 +53,7 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter'
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length]
if (slide.kind === 'image') return 'sky'
if (post.post_type === PostType.EVENT) return 'night'
if (post.post_type === PostType.EVENT || post.post_type === PostType.MOON) return 'night'
if (post.post_type === PostType.TIP) return 'sky'
if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac'
if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint'
@@ -104,6 +105,27 @@ function Pic({ name, className }: { name: string; className?: string }) {
const slideBase = 'relative flex h-full w-full shrink-0 flex-col px-5 py-[22px]'
// 달 포스트 밤하늘 별: [left %, top %, 크기 px]
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 }) {
return (
<>
<span className="pointer-events-none absolute inset-0 -z-10" aria-hidden="true">
{STARS.map(([x, y, s]) => (
<i key={`${x},${y}`} className="absolute rounded-full bg-white opacity-80 shadow-[0_0_6px_rgb(255_255_255/0.8)]" style={{ left: `${x}%`, top: `${y}%`, width: s, height: s }} />
))}
</span>
<span className="b-fall pointer-events-none absolute top-[22%] right-0 w-[60%]" style={fall('.1s', '5s')}>
<MoonArt pct={pct} waxing={waxing} className="b-bob w-full" />
</span>
</>
)
}
function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
const { open } = useSheet()
if (slide.kind === 'hours') {
@@ -258,12 +280,12 @@ function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSPro
</div>
)
return (
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<div className={cx(slideBase, `b-bg-${bg}`, slide.moon_pct != null && 'isolate')} style={img}>
<Eyebrow className={DARK.has(bg) ? 'opacity-85' : undefined}>{slide.eyebrow}</Eyebrow>
<Big className="relative z-[1]">
<Lines text={slide.line} />
</Big>
<Pic name={slide.icon} className="w-[36%]" />
{slide.moon_pct != null ? <MoonPic pct={slide.moon_pct} waxing={!!slide.moon_waxing} /> : <Pic name={slide.icon} className="w-[36%]" />}
<Rows rows={slide.rows ?? []} dark={DARK.has(bg)} />
</div>
)
+45 -22
View File
@@ -34,7 +34,7 @@ import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf,
import { GoogleButton } from './googleLogin'
import { useInstall, useInstallable } from './install'
import { InstallSheet } from './installBanner'
import { ARTICLE_CAT } from './lib'
import { ARTICLE_CAT, SHEET_CLOSE_MS, SHEET_OPEN_MS } from './lib'
import { MixSheet } from './myGak'
import { ownPage, useRegion } from './regionContext'
import { WeatherWhySheet } from './weatherWhy'
@@ -95,11 +95,25 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const [gakTitle, setGakTitle] = useState('')
const [articleTitle, setArticleTitle] = useState('')
// 닫히는 동안에도 내려가는 창에 내용이 남아 있게, 마지막으로 연 창을 들고 있는다
const [shown, setShown] = useState<SheetState>(state)
if (state && state !== shown) setShown(state)
const closing = !state && shown != null
useEffect(() => {
const el = ref.current
if (!el) return
if (state && !el.open) el.showModal()
if (!state && el.open) el.close()
if (state) {
if (!el.open) el.showModal()
return
}
if (!el.open) return
// 내려가는 애니메이션이 끝난 뒤에 실제로 닫는다
const t = setTimeout(() => {
el.close()
setShown(null)
}, SHEET_CLOSE_MS)
return () => clearTimeout(t)
}, [state])
// 창이 열려 있는 동안 뒤 페이지는 스크롤되지 않게 잠근다
@@ -109,15 +123,17 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const root = document.documentElement
const before = root.style.overflow
root.style.overflow = 'hidden'
root.classList.add('b-sheet-open')
// 뒤 화면 움직임 멈추기는 페이지 전체 스타일을 다시 계산하게 해서, 창이 다 올라온 뒤에 한다
const pause = setTimeout(() => root.classList.add('b-sheet-open'), SHEET_OPEN_MS)
return () => {
clearTimeout(pause)
root.style.overflow = before
root.classList.remove('b-sheet-open')
}
}, [isOpen])
const then = state?.type === 'login' ? state.then : undefined
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type]
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 ? '받은 각' : '내 각 만들기') : TITLES[shown.type]
return (
<dialog
@@ -125,12 +141,17 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
aria-label={title}
data-t={kind}
onClose={onClose}
// ESC 도 바로 닫지 않고 내려가며 닫히게
onCancel={(e) => {
e.preventDefault()
onClose()
}}
onClick={(e) => {
if (e.target === e.currentTarget) onClose()
}}
className="b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)"
className={cx('b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)', closing && 'b-sheet-closing')}
>
{state && (
{shown && (
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white pb-[env(safe-area-inset-bottom,0px)]">
<div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center">
<div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-(--line)" aria-hidden="true" />
@@ -139,21 +160,21 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
×
</button>
</div>
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
{state.type === 'share' && <ShareSheet share={state.share} />}
{state.type === 'comments' && <CommentsSheet postId={state.postId} draft={state.draft} />}
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />}
{state.type === 'install' && <InstallSheet />}
{state.type === 'weatherWhy' && <WeatherWhySheet d={state.why} />}
{state.type === 'talk' && <TalkSheet talk={state.talk} />}
{shown.type === 'gak' && <GakSheet indexId={shown.indexId} onTitle={setGakTitle} />}
{shown.type === 'article' && <ArticleSheet articleId={shown.articleId} onTitle={setArticleTitle} />}
{shown.type === 'seasonWeek' && <SeasonWeekSheet />}
{shown.type === 'share' && <ShareSheet share={shown.share} />}
{shown.type === 'comments' && <CommentsSheet postId={shown.postId} draft={shown.draft} />}
{shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{shown.type === 'me' && <MeSheet onDone={onClose} />}
{shown.type === 'region' && <RegionSheet onDone={onClose} />}
{shown.type === 'mix' && <MixSheet shared={shown.shared} onDone={onClose} />}
{shown.type === 'install' && <InstallSheet />}
{shown.type === 'weatherWhy' && <WeatherWhySheet d={shown.why} />}
{shown.type === 'talk' && <TalkSheet talk={shown.talk} />}
</div>
)}
{!state && <RegionLinks />}
{!shown && <RegionLinks />}
</dialog>
)
}
@@ -801,6 +822,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
<div>
<p className="m-0 text-sm">
<b className="mr-1.5 font-extrabold">{c.nickname}</b>
{c.official && <span className="mr-1.5 inline-block -translate-y-px rounded-md bg-(--orange) px-1.5 py-px align-middle text-[10.5px] font-extrabold text-white">날씨각</span>}
{c.body}
</p>
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
@@ -813,7 +835,8 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
</button>
</>
)}
{!c.mine && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
{/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
{!c.mine && !c.official && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
</small>
</div>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
+8 -19
View File
@@ -21,6 +21,7 @@ import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEK
import { fall } from './lib'
import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner'
import { MoonArt } from './moon'
import { MyGakRow } from './myGak'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
@@ -159,7 +160,8 @@ const WEATHER_ICON: Record<Weather, string> = {
}
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋
// 히어로 오른쪽 위 좋아요·댓글·보내기: 셋 다 같은 32px 칸에 아이콘 가운데, 수는 아이콘 옆
const HERO_ACT = 'relative flex h-8 min-w-8 cursor-pointer items-center justify-center gap-1 text-[13px] font-extrabold'
// 아이콘마다 좌우 여백을 같게: 숫자가 붙어도 아이콘 사이 간격이 그대로
const HERO_ACT = 'relative flex h-8 cursor-pointer items-center justify-center gap-1 px-[5px] text-[13px] leading-none font-extrabold tabular-nums'
const CLOUDS = [
{ cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' },
{ cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' },
@@ -372,13 +374,9 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
</span>
))}
<div className={'b-fall absolute top-2 left-1/2 -ml-16 aspect-square w-32'} style={fall('0s', '5.6s')}>
<div className="b-sun b-bob relative grid size-full place-items-center rounded-full text-center">
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
{moon && (
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
<path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} />
</svg>
)}
<div className={cx('b-sun b-bob relative grid size-full place-items-center rounded-full text-center', moon && 'b-moon')}>
{/* 오늘 밤 실제 모양의 달 (빛 번짐까지 그려서 공보다 크게) */}
{moon && <MoonArt pct={moon.pct} waxing={!moon.waning} tone={kind === 'sunset' ? 'dusk' : 'night'} className="pointer-events-none absolute -top-1/4 -left-1/4 size-[150%] max-w-none" />}
{/* 점수 근거가 있으면 해를 눌러도 근거 창: 구석 버튼은 구름에 가려져서 상태 줄 끝으로 옮김 */}
{(() => {
const body = (
@@ -389,7 +387,8 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
</>
)
const cls = cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')
// 가운데가 밝은 달이면 진한 글씨에 흰 번짐, 가운데가 어두운 달(초승·그믐)이면 흰 글씨
const cls = cx('relative', moon && (moon.pct >= 50 ? '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]' : 'text-white [text-shadow:0_1px_8px_rgb(10_14_40/0.6)]'))
if (!why || score == null) return <span className={cls}>{body}</span>
return (
<button
@@ -470,16 +469,6 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
const WANING = ['기우는 달', '하현달', '그믐달']
/**
* 반지름 r 인 달에서 밝은 쪽(lit) 또는 어두운 쪽 경로. 차오르는 달 기준(오른쪽이 밝음), 기우는 달은 좌우를 뒤집어 쓴다.
* 바깥 반원과 명암 경계(가로 반지름 r·|1-2k| 인 타원 호)로 이루어진다.
*/
function moonPath(pct: number, r: number, lit: boolean) {
const k = pct / 100
const edge = `A${r * Math.abs(1 - 2 * k)},${r} 0 0 ${k < 0.5 ? 0 : 1} 0,${-r}`
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
}
function GakCard({ items, post, place, at }: { items: TopIndex[]; post?: PostReaction | null; place: string; at: string }) {
const { open } = useSheet()
const tplRef = useRef<HTMLDivElement>(null)
+36 -5
View File
@@ -120,13 +120,37 @@
}
}
/* 아래 창은 불투명한 채로 화면 아래에서 끝까지 올라오고, 닫힐 땐 다시 내려간다 (반투명으로 올라오면 뒤 탭 바가 비쳐 깜빡여 보였다) */
.b-sheet {
animation: b-up 0.26s cubic-bezier(0.2, 0.9, 0.3, 1);
animation: b-up 0.28s cubic-bezier(0.2, 0.9, 0.3, 1);
}
.b-sheet-dialog[open]::backdrop {
animation: b-fade-in 0.2s ease-out;
}
.b-sheet-closing .b-sheet {
animation: b-down 0.2s ease-in forwards;
}
.b-sheet-closing::backdrop {
animation: b-fade-out 0.2s ease-in forwards;
}
@keyframes b-up {
from {
transform: translateY(40px);
opacity: 0.4;
transform: translateY(100%);
}
}
@keyframes b-down {
to {
transform: translateY(100%);
}
}
@keyframes b-fade-in {
from {
opacity: 0;
}
}
@keyframes b-fade-out {
to {
opacity: 0;
}
}
@@ -150,11 +174,13 @@
.b-fall,
.b-heart-pop,
.b-like-bit,
.b-sheet {
.b-sheet,
.b-sheet-dialog[open]::backdrop {
animation: none !important;
}
.b-heart-pop,
.b-like-bit {
.b-like-bit,
.b-sheet-closing .b-sheet {
opacity: 0;
}
}
@@ -287,6 +313,11 @@
inset 16px 18px 28px rgb(255 255 255 / 0.6),
0 0 60px rgb(190 180 255 / 0.45);
}
/* 달 그림(MoonArt)이 빛까지 그리므로 공 바탕·그림자는 뺀다 */
.b-hero .b-sun.b-moon {
background: none;
box-shadow: none;
}
.b-cloud {
position: absolute;
+1 -1
View File
@@ -52,7 +52,7 @@ export const PROVINCES = (
export const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
const province = (m: Spot) => m.region.split(' ')[0].split('·')
/** 오늘(한국 시각) 기준 명소 68곳과 단계. 단풍철이 아니면 inSeason 이 false */
/** 오늘(한국 시각) 기준 명소 67곳과 단계. 단풍철이 아니면 inSeason 이 false */
export function useFoliage() {
const [today] = useState(() => {
const t = kst(new Date())
+2 -1
View File
@@ -66,7 +66,8 @@ export function FoliageCard({ post }: { post?: PostReaction | null }) {
</span>
<div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
<div className="flex">
<div className="min-w-0 shrink-0 grow-0 basis-full">
{/* 밀어 낸 지도가 옆 장(가기 좋은 곳)을 덮지 않게 이 장 밖은 자른다 */}
<div className="min-w-0 shrink-0 grow-0 basis-full overflow-hidden">
{/* 지도 그림은 땅이 왼쪽에 치우쳐 있어 오른쪽(빈 바다)으로 밀어 가운데에 맞춘다 */}
<div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full translate-x-[7%] bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={MAP_IMG} />
+20 -34
View File
@@ -2,43 +2,20 @@ import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'
type GoogleId = {
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 로그인 창을 처음 열 때 한 번만 받는다 */
function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
import { cx } from '../lib/utils'
import { loadGoogle } from './googleScript'
import { SHEET_OPEN_MS } from './lib'
import { Skel } from './ui'
/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id
const config = useQuery({ ...authConfigOptions(), staleTime: Infinity })
const clientId = config.data?.google_client_id
const login = useMutation(googleLoginMutation())
const box = useRef<HTMLDivElement>(null)
const [broken, setBroken] = useState(false)
// 구글 버튼(iframe)이 다 그려지기 전엔 같은 크기의 스켈레톤을 보여 준다. 빈칸에 버튼이 툭 튀어나오면 버벅이는 것처럼 보여서
const [ready, setReady] = useState(false)
const { mutate } = login
// 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다
const cb = useRef({ onResult, onFail })
@@ -49,8 +26,10 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
useEffect(() => {
if (!clientId || !box.current) return
let alive = true
loadGoogle().then(
(g) => {
// 버튼(iframe)을 만드는 일이 무거워, 로그인 창이 다 올라온 뒤에 만든다. 자리는 min-h 로 잡아 둬서 밀리지 않는다
const wait = new Promise((r) => setTimeout(r, SHEET_OPEN_MS))
Promise.all([loadGoogle(), wait]).then(
([g]) => {
if (!alive || !box.current) return
g.initialize({
client_id: clientId,
@@ -61,6 +40,9 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
},
})
g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth })
const frame = box.current.querySelector('iframe')
if (frame) frame.addEventListener('load', () => alive && setReady(true), { once: true })
else setReady(true)
},
(e: unknown) => {
console.error('[google] script', e)
@@ -72,10 +54,14 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
}
}, [clientId, mutate])
if (config.isPending) return <Skel shape className="mx-auto h-[44px] w-full max-w-[400px] rounded-full" />
if (!clientId) return null
return (
<div className="flex flex-col gap-2">
<div ref={box} className="flex min-h-[44px] justify-center" aria-busy={login.isPending} />
<div className="relative">
{!ready && !broken && <Skel shape className="absolute inset-x-0 top-0 mx-auto h-[44px] w-full max-w-[400px] rounded-full" />}
<div ref={box} className={cx('flex min-h-[44px] justify-center transition-opacity duration-200', ready ? 'opacity-100' : 'opacity-0')} aria-busy={login.isPending || !ready} />
</div>
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
</div>
)
+40
View File
@@ -0,0 +1,40 @@
export type GoogleId = {
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 한 번만 받는다. 실패하면 다음에 다시 받는다 */
export function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
/** 로그인 안 한 사람은 화면이 한가할 때 스크립트를 미리 받아 둔다. 로그인 창이 올라오는 도중에 스크립트를 실행하느라 화면이 멈추지 않게. 돌려준 함수로 취소 */
export function preloadGoogle(): () => void {
const run = () => void loadGoogle().catch((e: unknown) => console.error('[google] preload', e))
if ('requestIdleCallback' in window) {
const id = requestIdleCallback(run, { timeout: 4000 })
return () => cancelIdleCallback(id)
}
const id = setTimeout(run, 2500)
return () => clearTimeout(id)
}
+20 -19
View File
@@ -1,6 +1,8 @@
import { useEffect, useState, type ReactNode } from 'react'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { dismiss, dismissed, platform, promptInstall, useCanPrompt, useInstall, useInstallable } from './install'
import { TAP44 } from './ui'
const SITE = 'https://weather.o2o.kr'
@@ -17,27 +19,26 @@ export function InstallBanner() {
if (hidden) return null
return (
<aside aria-label="홈 화면에 추가" className="mx-3 mt-3.5 flex items-center gap-3 rounded-[22px] bg-white p-3.5 shadow-[inset_0_-5px_0_var(--shade)]">
<img src="/app/icon-192.png" alt="" className="size-12 shrink-0 rounded-[14px]" />
<aside aria-label="홈 화면에 추가" className="mt-3.5 flex items-center gap-2.5 border-y border-(--line) bg-white py-2.5 pr-1.5 pl-3">
<img src="/app/icon-192.png" alt="" className="size-10 shrink-0 rounded-[11px]" />
<div className="min-w-0 flex-1">
<p className="m-0 font-jua text-[16.5px] leading-snug">내일도 우산각·빨래각, 바로 확인하세요</p>
<p className="m-0 mt-0.5 text-[12.5px] font-semibold text-(--ink2)">날씨각을 홈 화면에 추가하고 한 번에 열어보세요.</p>
<div className="mt-2 flex gap-1.5">
<button type="button" onClick={() => install('banner')} className="cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">
📲 홈 화면에 추가
</button>
<button
type="button"
onClick={() => {
dismiss()
setClosed(true)
}}
className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2)"
>
닫기
</button>
</div>
<p className="m-0 font-jua text-[15px] leading-snug">내일도 우산각·빨래각, 바로 확인하세요</p>
<p className="m-0 text-xs leading-snug font-semibold text-(--ink2)">홈 화면에서 바로 열어 보세요.</p>
</div>
<button type="button" onClick={() => install('banner')} className="shrink-0 cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">
추가
</button>
<button
type="button"
onClick={() => {
dismiss()
setClosed(true)
}}
aria-label="닫기"
className={cx('relative grid size-[30px] shrink-0 cursor-pointer place-items-center text-xl text-(--ink3)', TAP44)}
>
×
</button>
</aside>
)
}
+5
View File
@@ -14,3 +14,8 @@ export function iconSrc(name: string) {
export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: [ARTICLE_LABEL[1], 'text-[#1f9d62]'], 2: [ARTICLE_LABEL[2], 'text-[#7a5cd6]'], 3: [ARTICLE_LABEL[3], 'text-(--orange)'] }
/** 아래 창이 다 올라오는 시간(.b-sheet 0.26s). 무거운 일은 이 뒤로 미뤄 올라오는 동안 버벅이지 않게 */
export const SHEET_OPEN_MS = 280
/** 아래 창이 내려가며 닫히는 시간(.b-sheet-closing 0.2s). 이 뒤에 실제로 닫는다 */
export const SHEET_CLOSE_MS = 200
+79
View File
@@ -0,0 +1,79 @@
import { useId } from 'react'
import { moonPath } from '@nalssigak/shared/lib/today'
// 앞면 바다(어두운 무늬) 자리: [x, y, 가로 반지름, 세로 반지름]. 실제 달 앞면 배치를 대강 따른다
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, 기우는 달은 왼쪽이 밝다 */
export function MoonArt({ pct, waxing, tone = 'night', className }: { pct: number; waxing: boolean; tone?: keyof typeof TONES; className?: string }) {
const id = useId()
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" className={className} aria-hidden="true">
<defs>
<radialGradient id={`${id}glow`}>
<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.4" cy="0.36" r="0.72">
<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`}>
<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>
)
}
+16 -2
View File
@@ -130,8 +130,19 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
id={COMPOSE_ID}
value={text}
onChange={(e) => setText(e.target.value)}
onFocus={() => !loggedIn && open({ type: 'login' })}
readOnly={busy}
// 로그인 전엔 읽기 전용이라 눌러도 키보드가 안 올라온다 (키보드가 떴다 내려가며 로그인 창이 버벅이던 것). 누르거나 Enter 면 로그인 창
onClick={(e) => {
if (loggedIn) return
// 창이 닫힐 때 포커스가 이 칸으로 돌아와 테두리가 번쩍이지 않게
e.currentTarget.blur()
open({ type: 'login' })
}}
onKeyDown={(e) => {
if (loggedIn || (e.key !== 'Enter' && e.key !== ' ')) return
e.preventDefault()
open({ type: 'login' })
}}
readOnly={busy || !loggedIn}
maxLength={BODY_MAX}
rows={2}
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
@@ -355,7 +366,10 @@ export function TalkGroup({ title, topic, talks }: { title: string; topic?: numb
export function FirstTalkCard() {
const { region } = useRegion()
const place = region.name.split(' ').at(-1)
const { loggedIn } = useAuth()
const { open } = useSheet()
const go = () => {
if (!loggedIn) return open({ type: 'login' })
const el = document.getElementById(COMPOSE_ID)
el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
el?.focus({ preventScroll: true })
+79
View File
@@ -0,0 +1,79 @@
import { moonPath } from '@nalssigak/shared/lib/today';
import { useId } from 'react';
import Svg, { Circle, ClipPath, Defs, Ellipse, FeGaussianBlur, Filter, G, Path, RadialGradient, Stop } from 'react-native-svg';
// 앞면 바다(어두운 무늬) 자리: [x, y, 가로 반지름, 세로 반지름]. 실제 달 앞면 배치를 대강 따른다 (웹 frontend/src/b/moon.tsx 와 같다)
const MARIA: [number, number, number, number][] = [
[-0.32, -0.36, 0.3, 0.26],
[0.12, -0.36, 0.17, 0.15],
[0.3, -0.06, 0.2, 0.17],
[-0.56, 0.06, 0.26, 0.42],
[0.66, -0.26, 0.1, 0.12],
[0.52, 0.22, 0.13, 0.15],
[-0.14, 0.44, 0.18, 0.13],
[-0.46, 0.5, 0.1, 0.09],
];
// 작은 크레이터: [x, y, 반지름]
const CRATERS: [number, number, number][] = [
[0.1, 0.72, 0.07],
[0.42, 0.52, 0.05],
[-0.66, -0.5, 0.05],
[0.62, 0.52, 0.04],
[-0.2, 0.08, 0.04],
];
// 저녁(노을)엔 노을빛이 도는 달, 밤엔 하얀 달
const TONES = {
night: { body: ['#fffcf2', '#f6ebcb', '#e0cc98'], shade: '#1a2050' },
dusk: { body: ['#fff8ee', '#ffe2cc', '#f2b9a2'], shade: '#4a2a63' },
};
/** 오늘 밤 실제 모양대로 그린 달. pct 는 빛나는 면의 비율 0~100, 기우는 달은 왼쪽이 밝다. 빛 번짐까지 그려서 달 지름은 size 의 2/3 */
export function MoonArt({ pct, waxing, tone = 'night', size }: { pct: number; waxing: boolean; tone?: keyof typeof TONES; size: number }) {
const id = useId().replace(/[^a-zA-Z0-9]/g, '');
const t = TONES[tone];
const k = pct / 100;
const full = pct >= 99;
const hidden = pct <= 1;
return (
<Svg viewBox="-1.5 -1.5 3 3" width={size} height={size} pointerEvents="none">
<Defs>
<RadialGradient id={`${id}glow`} cx="0" cy="0" r="1.5" gradientUnits="userSpaceOnUse">
<Stop offset="0.6" stopColor="#fff4cf" stopOpacity={0.55} />
<Stop offset="0.8" stopColor="#ffe9a8" stopOpacity={0.16} />
<Stop offset="1" stopColor="#ffe9a8" stopOpacity={0} />
</RadialGradient>
<RadialGradient id={`${id}body`} cx="-0.2" cy="-0.28" r="1.44" gradientUnits="userSpaceOnUse">
<Stop offset="0" stopColor={t.body[0]} />
<Stop offset="0.6" stopColor={t.body[1]} />
<Stop offset="1" stopColor={t.body[2]} />
</RadialGradient>
<RadialGradient id={`${id}limb`} cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse">
<Stop offset="0.72" stopColor="#8a6f3c" stopOpacity={0} />
<Stop offset="1" stopColor="#8a6f3c" stopOpacity={0.28} />
</RadialGradient>
<ClipPath id={`${id}disc`}>
<Circle r="1" />
</ClipPath>
<Filter id={`${id}soft`} x="-0.2" y="-0.2" width="1.4" height="1.4">
<FeGaussianBlur stdDeviation="0.035" />
</Filter>
</Defs>
{!hidden && <Circle r="1.5" fill={`url(#${id}glow)`} opacity={full ? 1 : 0.12 + 0.8 * k} />}
<G clipPath={`url(#${id}disc)`}>
<Circle r="1" fill={`url(#${id}body)`} />
<G filter={`url(#${id}soft)`} fill="#c4b287" opacity={0.55}>
{MARIA.map(([x, y, rx, ry]) => (
<Ellipse key={`${x},${y}`} cx={x} cy={y} rx={rx} ry={ry} />
))}
</G>
{CRATERS.map(([x, y, r]) => (
<Circle key={`${x},${y}`} cx={x} cy={y} r={r} fill="#efe2bd" stroke="#cdbb8c" strokeWidth={0.018} opacity={0.8} />
))}
<Circle r="1" fill={`url(#${id}limb)`} />
{/* 안 보이는 쪽: 흐릿한 경계로 덮고, 땅빛(지구조) 정도만 비치게 */}
{!full && <Path d={moonPath(pct, 1.04, false)} fill={t.shade} opacity={0.94} filter={`url(#${id}soft)`} transform={waxing ? undefined : 'scale(-1,1)'} />}
</G>
{hidden && <Circle r="1" fill="none" stroke="#fff" strokeOpacity={0.18} strokeWidth={0.025} />}
</Svg>
);
}
+27 -3
View File
@@ -5,11 +5,12 @@ import type { SlideBg } from '@nalssigak/shared/lib/types';
import { deg } from '@nalssigak/shared/lib/weatherText';
import { Image } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import type { ReactNode } from 'react';
import { useState, type ReactNode } from 'react';
import { Pressable, StyleSheet, View } from 'react-native';
import { 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';
@@ -54,7 +55,7 @@ export function slideBg(post: PostData, slide: Slide): SlideBg {
if (slide.kind === 'week') return 'mint';
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter';
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length];
if (post.post_type === PostType.EVENT) return 'night';
if (post.post_type === PostType.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';
@@ -86,6 +87,28 @@ function Pic({ name, widthPct = 42 }: { name: string; widthPct?: number }) {
);
}
// 달 포스트 밤하늘 별: [left %, top %, 크기]
const STARS: [number, number, number][] = [
[8, 34, 2], [18, 52, 1.5], [30, 40, 2.5], [44, 30, 1.5], [52, 58, 2], [62, 22, 1.5], [90, 18, 2], [94, 44, 1.5], [12, 70, 1.5], [38, 66, 2], [76, 74, 1.5], [86, 64, 2], [24, 12, 1.5], [70, 10, 2.5],
];
/** 달 포스트 그림: 아이콘 대신 오늘 밤 실제 모양의 달과 별 */
function MoonPic({ pct, waxing }: { pct: number; waxing: boolean }) {
const [w, setW] = useState(0);
return (
<View pointerEvents="none" style={StyleSheet.absoluteFill} onLayout={(e) => setW(e.nativeEvent.layout.width)}>
{STARS.map(([x, y, s]) => (
<View key={`${x},${y}`} className="absolute rounded-full bg-white opacity-80" style={{ left: `${x}%`, top: `${y}%`, width: s, height: s }} />
))}
{w > 0 && (
<View className="absolute top-[22%] right-0">
<MoonArt pct={pct} waxing={waxing} size={w * 0.6} />
</View>
)}
</View>
);
}
export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
const { open } = useSheet();
const { kind } = useSky();
@@ -246,13 +269,14 @@ export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
);
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>
<Pic name={slide.icon} widthPct={36} />
{slide.moon_pct == null && <Pic name={slide.icon} widthPct={36} />}
<Rows rows={slide.rows ?? []} dark={light} />
</Base>
);
+7 -1
View File
@@ -200,6 +200,11 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
<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">
@@ -214,7 +219,8 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
</>
)}
</Text>
{!c.mine && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
{/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
{!c.mine && !c.official && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
</View>
</View>
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="댓글 좋아요" className="pt-1">
+19 -7
View File
@@ -1,15 +1,16 @@
import type { Hero as HeroData, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { kindOfHour, kst, type Load, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib';
import { KINDS, moonPath, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today';
import { KINDS, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today';
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText';
import { useEffect, useState, type ReactNode } from 'react';
import { Pressable, View, type DimensionValue, type ViewStyle } from 'react-native';
import { Text } from '@/components/text';
import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
import { LinearGradient } from 'expo-linear-gradient';
import Svg, { Defs, Path, RadialGradient, Rect, Stop } from 'react-native-svg';
import Svg, { Defs, RadialGradient, Rect, Stop } from 'react-native-svg';
import { Fall } from '@/components/fall';
import { MoonArt } from '@/components/moon';
import { Shoot, type ShootSpec } from '@/components/sky-bg';
import { Ic, Skel } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
@@ -140,6 +141,12 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
const snow = weather === 'snow' || weather === 'sleet';
const orb = ORB[kind === 'sunset' ? 'sunset' : kind === 'night' ? 'night' : 'sun'];
const text = dark ? 'text-white' : 'text-[#28304a]';
// 가운데가 밝은 달이면 진한 글씨에 흰 번짐, 가운데가 어두운 달(초승·그믐·삭)이면 흰 글씨
const orbText: { color: string; textShadowColor?: string; textShadowRadius?: number } = !moon
? { color: orb.text }
: moon.pct >= 50
? { color: orb.text, textShadowColor: '#fff', textShadowRadius: 8 }
: { color: '#fff', textShadowColor: 'rgba(10,14,40,0.6)', textShadowRadius: 8 };
return (
<View className="mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3">
@@ -157,7 +164,13 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
</Text>
<View className="h-[146px] items-center">
<Fall d={0} f={5600} amp={8}>
<View className="mt-2 size-32 items-center justify-center" style={{ boxShadow: `0 20px 40px ${kind === 'night' ? 'rgb(190 180 255 / 0.35)' : kind === 'sunset' ? 'rgb(255 150 110 / 0.4)' : 'rgb(240 106 58 / 0.32)'}`, borderRadius: 64 }}>
<View className="mt-2 size-32 items-center justify-center" style={moon ? undefined : { boxShadow: `0 20px 40px ${kind === 'night' ? 'rgb(190 180 255 / 0.35)' : kind === 'sunset' ? 'rgb(255 150 110 / 0.4)' : 'rgb(240 106 58 / 0.32)'}`, borderRadius: 64 }}>
{/* 저녁·밤엔 오늘 밤 실제 모양의 달 (빛 번짐까지 그려서 공보다 크게) */}
{moon ? (
<View pointerEvents="none" style={{ position: 'absolute', top: -32, left: -32 }}>
<MoonArt pct={moon.pct} waxing={!moon.waning} tone={kind === 'sunset' ? 'dusk' : 'night'} size={192} />
</View>
) : (
<Svg viewBox="-1 -1 2 2" width={128} height={128} style={{ position: 'absolute' }}>
<Defs>
<RadialGradient id="orb" cx="-0.32" cy="-0.4" r="1.4" gradientUnits="userSpaceOnUse">
@@ -168,13 +181,12 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
</RadialGradient>
</Defs>
<Rect x="-1" y="-1" width="2" height="2" rx="1" fill="url(#orb)" opacity={gray ? 0.85 : 1} />
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
{moon && <Path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} />}
</Svg>
<Text className="font-jua text-[12px]" style={{ color: orb.text }}>
)}
<Text className="font-jua text-[12px]" style={orbText}>
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</Text>
<Text className="font-bagel text-[52px] leading-[52px]" style={{ color: orb.text }}>
<Text className="font-bagel text-[52px] leading-[52px]" style={orbText}>
{heroVal(feedLoad, score, 'w-[84px] h-10')}
</Text>
</View>
+18
View File
@@ -383,6 +383,12 @@ export type CommentData = {
* Mine
*/
mine: boolean;
/**
* Official
*
* 날씨각 캐릭터(해님·구름·달님)가 단 댓글. 이름 옆에 '날씨각' 표시
*/
official?: boolean;
/**
* Created At
*/
@@ -2896,6 +2902,18 @@ export type RowsSlide = {
* Image Credit
*/
image_credit?: string | null;
/**
* Moon Pct
*
* 달 포스트만: 빛나는 면의 비율 0~100 (아이콘 대신 이 모양으로 달을 그린다)
*/
moon_pct?: number | null;
/**
* Moon Waxing
*
* 달 포스트만: 차오르는 달이면 true (오른쪽이 밝음)
*/
moon_waxing?: boolean | null;
};
/**