feat: 오늘 히어로 D4-2 — 해 안 점수, 상태 한 줄(습도·불쾌지수·자외선·미세먼지 단계), 하루 흐름 칸이 미리보기 탭, 구름·비·눈 연출 / 각 시간대별 점수·순위 미리보기 / 자외선 시간표 단계 색 칩 / 밤 화면 어두운 아이콘 빛

This commit is contained in:
minaChoi committed 2026-10-12 15:35:34 +09:00
1 parent 4cdc8b274f
commit aa774c2a44
13 files changed
+367 -155

No files matched your search

+2 -1
View File
@@ -94,7 +94,8 @@
| [ ] | 행사 수집이 사용자 한 명당 주변 시도 2~4곳으로 늘어 TourAPI·문화정보 API 호출이 시도 수만큼 늘어남(시도별 하루 1회 캐시) — 운영 배포 때 일일 호출 한도 확인 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`_ensure_events`), `backend/docs/load-estimate.md` |
| [ ] | 다른 문서의 포스트 종류 목록·행사 시도 기준 설명 갱신 (`PostType` 12 미세먼지, 30km 행사) — `docs/포스트_종류별_내용.html`만 고침 | 문서 점검 | `backend/docs/`, `docs/화면별_데이터_출처.html`, `docs/데이터_흐름.html`, `docs/콘텐츠_설계서.md` |
| [ ] | **[결정 필요]** 스켈레톤 작업에서 바뀐 디자인 — 댓글 없음 안내가 글자 두 줄 → 상자(스켈레톤 3줄 크기) | 스켈레톤 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`) |
| [ ] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
| [x] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 → 10/12 D4-2로 결정(해 안 점수 + 문장 두 줄은 서버 값 그대로 + 상태 한 줄 + 하루 흐름 칸, 높이는 지금 그대로 약 400px) | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` |
| [x] | **[결정 필요]** 히어로 D4-2 상태 한 줄 — ① 습도는 서버가 %만 줘서 단계 기준을 새로 정해야 함 ② 불쾌지수 '불쾌'처럼 판정 이름을 그대로 쓸지 ③ 미세먼지·자외선은 늘 보일지, 조심할 때만 보일지 → 10/12 결정: 습도 건조(30% 미만)·보통(60% 이하)·습함, 불쾌지수 단계 이름 그대로, 늘 4개(밤엔 자외선 빼기) | 히어로 D4-2 시안 | `backend/services/hero_stats.py`, `backend/services/feed_service.py`, `frontend/src/b/TodayPage.tsx` |
| [x] | 댓글 좋아요 실패 시 알림 없음 (연결·서버 오류면 줄에 안내, 지워진 댓글이면 목록 새로고침) (화면은 되돌아감) | 댓글 대기 표시 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentRow`) |
| [x] | **[결정 필요]** 노을 탭 재정리에서 정한 것 — ① 노을 등급 '흐림' → '잿빛'(피드 노을 포스트 문구도 같이 바뀜) ② 히어로에 '가장 붉을 때' 시각 하나는 결론('몇 시에')으로 남기고 나머지 시각은 시간표 한 곳에만 ③ '나가 볼 만해요/애매해요/쉬어요' 기준 60·40점, 내일·모레는 10점 넘게 높을 때만 '더 나아요' ④ '쉬어요'면 명소 추천 안 함 ⑤ 블루아워 시각은 시민박명 끝(-6°), 골든아워는 해 고도 6° → 10/7 노을 탭 다시 기획으로 대체: 점수 대신 하늘 상황 5가지, 결론은 상황 기준 | 노을 탭 재정리 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py`, `frontend/src/b/SkyPage.tsx` |
| [x] | 노을 히어로 맨 윗줄("오늘 노을 · 구")이 보라 배경 위 흰 13px라 대비 약 3.9:1 (AA 4.5 미달) — 결론·근거·시각·점수는 어두운 상자 안으로 옮김, → 어두운 바탕을 깔아 6.7:1 | 노을 탭 재정리 중 발견 | `frontend/src/b/SkyPage.tsx` |
+5
View File
@@ -11,6 +11,7 @@ class Row(WebPacketProtocol):
label: str
value: str
place: Optional[str] = Field(default=None, description="위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)")
level: Optional[int] = Field(default=None, description="자외선 단계 1 낮음 ~ 5 위험. 있으면 앱이 값을 단계 색 칩으로 그린다")
class HourCell(WebPacketProtocol):
@@ -142,6 +143,8 @@ class TopIndex(WebPacketProtocol):
rank: int
summary: Optional[str] = None
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음")
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음")
class HeroStat(WebPacketProtocol):
@@ -162,11 +165,13 @@ class Hero(WebPacketProtocol):
rain_2h_text: Optional[str] = None
will_rain_2h: Optional[bool] = None
weather_score: Optional[int] = None
weather_slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}")
top1: Optional[TopIndex] = None
bubble: Optional[str] = None
moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달")
moon_pct: Optional[int] = Field(default=None, description="달에서 빛나는 면의 비율 0~100 (모양 그림용, 밝기 아님)")
stats: list[HeroStat] = Field(default_factory=list, description="히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저")
status: list[HeroStat] = Field(default_factory=list, description="히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)")
class BandEvent(WebPacketProtocol):
+20 -22
View File
@@ -30,7 +30,7 @@ from services.calc.index_calc import rank_score
from services.calc.moon import MoonNight, nearest, night, view_line
from services.calc.sky_score import GRADE_LABEL, sky_title
from services.calc.sun import sun_times
from services.hero_stats import UV_HIGH, HeroInput, hero_stats, uv_label
from services.hero_stats import UV_HIGH, HeroInput, discomfort_label, hero_stats, hero_status, uv_label, uv_level
from services.index_service import IndexBoard, IndexItem, IndexService
from services.now_service import NowService, NowWeather
from services.season_service import SeasonService
@@ -130,10 +130,6 @@ def _pick(articles: list[Article], day: date) -> Optional[Article]:
return articles[day.toordinal() % len(articles)] if articles else None
def _discomfort_label(v: int) -> str:
return "쾌적" if v < 68 else "보통" if v < 75 else "불쾌" if v < 80 else "매우 불쾌"
def _hero_input(
now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float], moon: Optional[str],
) -> HeroInput:
@@ -147,7 +143,7 @@ def _hero_input(
air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv,
temp_min=min(temps, default=None), temp_max=max(temps, default=None),
temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None,
moon=moon,
moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None,
)
@@ -238,7 +234,8 @@ def _by_position(posts: list[Post]) -> list[Post]:
def _top(i: IndexItem) -> TopIndex:
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,
slots=i.slots, slot_ranks=i.slot_ranks)
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType:
@@ -418,10 +415,10 @@ class FeedService:
return [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
async def _uv(self, region_code: str, hour: datetime) -> Optional[float]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour, hour))
if err is not ErrorType.SUCCESS or not rows or rows[0].uv_index is None:
return None
return float(rows[0].uv_index)
"""지금 칸의 자외선. Open-Meteo 는 3시간 칸이라 지금 시각을 넘지 않는 마지막 칸을 쓴다."""
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour - timedelta(hours=2), hour))
rows = [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else []
return float(max(rows, key=lambda r: r.forecast_at).uv_index) if rows else None
def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard],
today: Optional[TodayWeather] = None, uv: Optional[float] = None, moon: Optional[tuple[MoonNight, str]] = None) -> Hero:
@@ -429,16 +426,18 @@ class FeedService:
bubble = None
if top is not None:
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요"
x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None)
return Hero(
now_at=now, sky_mode=_SKY_MODE[slot],
temp_c=float(cur.temp_c) if cur else None, feels_c=float(cur.feels_c) if cur else None,
humidity=cur.humidity if cur else None,
discomfort=cur.discomfort_index if cur else None, discomfort_label=_discomfort_label(cur.discomfort_index) if cur else None,
discomfort=cur.discomfort_index if cur else None, discomfort_label=discomfort_label(cur.discomfort_index) if cur else None,
rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None,
weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble,
weather_score=board.weather_score if board else None, weather_slots=board.weather_slots if board else {},
top1=_top(top) if top else None, bubble=bubble,
moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None,
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone)
for x in hero_stats(_hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None))],
stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)],
status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_status(x_in)],
)
@staticmethod
@@ -627,14 +626,13 @@ class FeedService:
return None
label = uv_label(top)
at = peak.forecast_at.astimezone(KST)
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=f"{round(float(r.uv_index))} · {uv_label(float(r.uv_index))}") for r in c.uv]
high = top >= UV_HIGH
if high:
rows.append(Row(label="이렇게 해요", value="선크림 바르고, 모자·선글라스 챙겨요"))
line = f"{hour_label(at.hour)} 무렵 자외선 {label},\n" + ("선크림 꼭 챙겨요" if high else "오래 밖에 있으면 선크림")
return PostData(**base, title=f"자외선 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)} · {round(top)}",
rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=uv_label(float(r.uv_index)), level=uv_level(float(r.uv_index))) for r in c.uv]
when = "점심때" if at.hour == 12 else f"{hour_label(at.hour)} 무렵"
todo = "선크림·모자·선글라스 챙기고 그늘로 다녀요" if top >= UV_HIGH else "선크림·모자 챙겨요"
line = f"오늘 자외선 지수 {label}\n{when} 나가면 {todo}"
return PostData(**base, title=f"자외선 지수 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)}",
slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)],
share_messages=[f"오늘 자외선 {label}, 선크림 챙겨!"])
share_messages=[f"오늘 자외선 지수 {label}, 선크림 챙겨!"])
def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]:
"""가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다."""
+35 -1
View File
@@ -10,6 +10,8 @@ from services.air_service import GRADE_LABEL
Tone = Literal["normal", "warn", "rain"]
UV_HIGH = 6.0
MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값
HUMID_DRY, HUMID_WET = 30, 60 # 습도 % : 이 아래 건조, 이 위 습함
TEMP_SWING_C = 10.0
WIND_CHILL_C = 3.0
SHOWN = 1
@@ -38,10 +40,42 @@ class HeroInput:
temp: Optional[float] = None
feels: Optional[float] = None
moon: Optional[str] = None
humidity: Optional[int] = None
discomfort: Optional[int] = None
_UV_LABELS = ("낮음", "보통", "높음", "매우 높음", "위험")
def uv_level(uv: float) -> int:
"""기상청 자외선 단계 1 낮음 ~ 5 위험."""
return 1 if uv < 3 else 2 if uv < 6 else 3 if uv < 8 else 4 if uv < 11 else 5
def uv_label(uv: float) -> str:
return "낮음" if uv < 3 else "보통" if uv < 6 else "높음" if uv < 8 else "매우 높음" if uv < 11 else "위험"
return _UV_LABELS[uv_level(uv) - 1]
def discomfort_label(v: int) -> str:
return "쾌적" if v < 68 else "보통" if v < MUGGY_DI else "불쾌" if v < 80 else "매우 불쾌"
def humidity_label(h: int) -> str:
return "건조" if h < HUMID_DRY else "보통" if h <= HUMID_WET else "습함"
def hero_status(x: HeroInput) -> list[HeroStatItem]:
"""히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
out: list[HeroStatItem] = []
if x.humidity is not None:
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity)))
if x.discomfort is not None:
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal"))
if not x.night and x.uv is not None:
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal"))
if x.air is not None:
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal"))
return out
def _rain_value(now: datetime, at: datetime) -> str:
+24 -10
View File
@@ -50,6 +50,7 @@ class IndexItem:
trend: list[IndexScore]
slot: Optional[str] = None
slots: dict[str, int] = field(default_factory=dict)
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다
@@ -59,6 +60,7 @@ class IndexBoard:
day: date
weather_score: Optional[int]
items: list[IndexItem]
weather_slots: dict[str, int] = field(default_factory=dict)
@property
def ranked(self) -> list[IndexItem]:
@@ -161,6 +163,12 @@ def shown_slot(key: str) -> str:
return "night" if key == EARLY else key
def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
"""구간 점수를 아침·낮·저녁·밤 순으로. 0~5시면 밤은 전날 밤 구간을 쓴다."""
shown = {shown_slot(k): v for k, v in parts.items() if k != ("night" if cur == EARLY else EARLY)}
return {k: shown[k] for k in SLOTS if k in shown}
def slot_results(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
) -> dict[str, Result]:
@@ -253,7 +261,7 @@ class IndexService:
if region is None:
return ErrorType.NOT_FOUND, None
now = now_kst()
err, weather_score = await self.ensure(region, now)
err, weather_parts = await self.ensure(region, now)
if err is not ErrorType.SUCCESS:
return err, None
today = now.date()
@@ -278,11 +286,11 @@ class IndexService:
items = []
for i, d in enumerate(ranked):
row = by_key[(d.index_id, today)]
parts = {shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}
parts = _shown_parts({k: v["score"] for k, v in row.slots.items()}, cur)
items.append(IndexItem(
definition=d, score=now_score[d.index_id], rank=i + 1,
trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
slot=shown_slot(cur), slots={k: parts[k] for k in SLOTS if k in parts},
slot=shown_slot(cur), slots=parts,
))
off = sorted(
(d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key),
@@ -293,12 +301,18 @@ class IndexService:
items.append(IndexItem(
definition=d, score=row, rank=len(items) + 1,
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
slots={shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}, active=False,
slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False,
))
return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items)
for k in SLOTS:
in_slot = sorted((i for i in items if k in i.slots), key=lambda i: rank_score(i.slots[k], i.definition.priority), reverse=True)
for n, i in enumerate(in_slot):
i.slot_ranks[k] = n + 1
return ErrorType.SUCCESS, IndexBoard(
region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur),
)
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]:
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 날씨 점수도 같이 낸다."""
async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]:
"""재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다."""
_, _, _, warnings = await asyncio.gather(
self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now),
self.warning_service.for_region(region, now),
@@ -328,7 +342,7 @@ class IndexService:
)
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
weather_result = slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).get(current_slot(now, sunset_at))
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).items()}
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
inputs_at = max(issued, air.measured_at) if air else issued
@@ -339,7 +353,7 @@ class IndexService:
_, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today))
wanted = {d for d in days if d >= today + timedelta(days=DAYS) and d in daily and None not in (daily[d].temp_min_c, daily[d].temp_max_c)}
if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()) and unslotted is False:
return ErrorType.SUCCESS, weather_result.score if weather_result else None
return ErrorType.SUCCESS, weather_parts
err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s))
_, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1]))
@@ -366,4 +380,4 @@ class IndexService:
"slots": {k: _slot_json(r) for k, r in parts.items()},
})
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_scores(s, out)])
return err, weather_result.score if weather_result else None
return err, weather_parts
+7 -1
View File
@@ -5,7 +5,7 @@ from common.enums import RainType, Sky
from common.utils.kma_time import KST, kst_midnight
from services.calc.day_slot import slot_hours
from services.calc.index_calc import Context
from services.index_service import EARLY, WEATHER_SCORE_DEF, current_slot, slot_results
from services.index_service import EARLY, WEATHER_SCORE_DEF, _shown_parts, current_slot, slot_results
DAY = date(2026, 10, 8)
SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST)
@@ -61,3 +61,9 @@ def test_rain_in_evening_lowers_only_later_slots():
def test_weather_score_covers_every_slot():
parts = slot_results(WEATHER_SCORE_DEF, DAY, REGION, _rows(), {}, CTX, SUNSET)
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
def test_shown_parts_uses_last_night_before_five():
parts = {"morning": 1, "day": 2, "evening": 3, "night": 4, EARLY: 5}
assert _shown_parts(parts, "day") == {"morning": 1, "day": 2, "evening": 3, "night": 4}
assert _shown_parts(parts, EARLY) == {"morning": 1, "day": 2, "evening": 3, "night": 5}
+6 -1
View File
@@ -62,6 +62,8 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
assert body["result"]["success"] is True
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
assert len(body["stories"]) == 34
assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]]
assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"])
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
assert len(weather["slides"][0]["hours"]) == 8
@@ -367,6 +369,9 @@ def test_uv_post_only_when_moderate_or_higher():
base = dict(post_id=1, post_type=PostType.UV, like_count=0, comment_count=0, published_at=at(9))
ctx = lambda vals: SimpleNamespace(region=SimpleNamespace(short_name="분당구"), uv=[SimpleNamespace(forecast_at=at(h), uv_index=v) for h, v in vals]) # noqa: E731
post = FeedService._uv_post(None, base, ctx([(9, 2.0), (12, 6.4), (15, 4.0)]))
assert post.title == "자외선 높음" and post.caption == "가장 셀 때 낮 12시 · 6" and post.slides[0].rows[-1].label == "이렇게 해요"
assert post.title == "자외선 지수 높음" and post.caption == "가장 셀 때 낮 12시"
assert post.slides[0].line == "오늘 자외선 지수 높음\n점심때 나가면 선크림·모자·선글라스 챙기고 그늘로 다녀요"
assert [(r.label, r.value, r.level) for r in post.slides[0].rows] == [("9시", "낮음", 1), ("12시", "높음", 3), ("15시", "보통", 2)]
assert FeedService._uv_post(None, base, ctx([(12, 2.0), (15, 3.4)])).slides[0].line == "오늘 자외선 지수 보통\n오후 3시 무렵 나가면 선크림·모자 챙겨요"
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
assert FeedService._uv_post(None, base, ctx([])) is None
+17 -1
View File
@@ -2,7 +2,7 @@ from datetime import datetime, timedelta
from common.enums import AirGrade
from common.utils.kma_time import KST
from services.hero_stats import HeroInput, hero_stats
from services.hero_stats import HeroInput, hero_stats, hero_status
NOW = datetime(2026, 10, 7, 14, 20, tzinfo=KST)
@@ -46,3 +46,19 @@ def test_one_coldwind_card_only():
def test_nothing_known_gives_nothing():
assert hero_stats(HeroInput(now=NOW, night=False)) == []
def _status(x: HeroInput) -> list[tuple[str, str, str]]:
return [(s.label, s.value, s.tone) for s in hero_status(x)]
def test_status_line_has_four_by_day_and_warns_only_caution():
x = HeroInput(now=NOW, night=False, humidity=55, discomfort=75, uv=4.2, air=AirGrade.GOOD)
assert _status(x) == [("습도", "보통", "normal"), ("불쾌지수", "불쾌", "warn"), ("자외선", "보통", "normal"), ("미세먼지", "좋음", "normal")]
x = HeroInput(now=NOW, night=False, humidity=72, discomfort=60, uv=6.0, air=AirGrade.BAD)
assert _status(x) == [("습도", "습함", "normal"), ("불쾌지수", "쾌적", "normal"), ("자외선", "높음", "warn"), ("미세먼지", "나쁨", "warn")]
def test_status_line_drops_uv_at_night_and_missing_values():
assert _status(HeroInput(now=NOW, night=True, humidity=25, uv=3.0, air=AirGrade.NORMAL)) == [("습도", "건조", "normal"), ("미세먼지", "보통", "normal")]
assert _status(HeroInput(now=NOW, night=False)) == []
+21 -1
View File
@@ -130,13 +130,33 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, 50)))
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
err, board = await service.board(REGION)
assert err is ErrorType.SUCCESS
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
@pytest.mark.anyio
async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
today = now_kst().date()
defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)]
every = ("morning", "day", "evening", "night", "early")
slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every},
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every if k not in ("night", "early")}}
scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)]
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {k: 50 for k in every})))
monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"]))
_, board = await service.board(REGION)
ranks = {i.definition.code: i.slot_ranks for i in board.items}
# 아침: 하 90(63) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다
assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2
assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2
assert "night" not in ranks["high"]
def _om_row(at, **over):
row = {
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
+30
View File
@@ -595,6 +595,14 @@ export type Hero = {
* Weather Score
*/
weather_score?: number | null;
/**
* Weather Slots
*
* 오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}
*/
weather_slots?: {
[key: string]: number;
};
top1?: TopIndex | null;
/**
* Bubble
@@ -618,6 +626,12 @@ export type Hero = {
* 히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저
*/
stats?: Array<HeroStat>;
/**
* Status
*
* 히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)
*/
status?: Array<HeroStat>;
};
/**
@@ -2409,6 +2423,22 @@ export type TopIndex = {
* 지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수
*/
active?: boolean;
/**
* Slots
*
* 오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음
*/
slots?: {
[key: string]: number;
};
/**
* Slot Ranks
*
* 오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음
*/
slot_ranks?: {
[key: string]: number;
};
};
/**
+119 -83
View File
@@ -2,7 +2,7 @@ import { Fragment, useEffect, useState, type ReactNode } from 'react'
import { Link } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
import type { BandArticle, BandEvent, Hero as HeroData, HeroStat as HeroStatData, ResWeatherToday, TopIndex } from '../api/client/types.gen'
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
import { PostCard, PostCardSkel } from './Post'
@@ -10,29 +10,22 @@ import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { useSky } from './skyContext'
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
import { deg, skyText, slotAt } from './weatherText'
import { deg, slotAt } from './weatherText'
type Mode = 'now' | TimeKind
const MODES: [Mode, string][] = [
['now', '지금'],
['morning', '아침'],
['day', '낮'],
['sunset', '저녁'],
['night', '밤'],
]
// 미리보기 시간대마다 보여 줄 시계와 그 시각의 예보 칸
const PREVIEW: Record<TimeKind, { label: string; clock: string; hour: number }> = {
morning: { label: '아침', clock: '07:40', hour: 7 },
day: { label: '낮', clock: '13:20', hour: 13 },
sunset: { label: '저녁', clock: '18:25', hour: 18 },
night: { label: '밤', clock: '22:10', hour: 22 },
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night']
const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
morning: { label: '아침', hour: 7 },
day: { label: '낮', hour: 13 },
sunset: { label: '저녁', hour: 18 },
night: { label: '밤', hour: 22 },
}
// 히어로 칸을 받아 오는 동안 자리만 잡아 둔다
const STAT_HOLD = ['a']
const MUGGY = 75 // 불쾌지수 이 이상이면 경고 색
// 비·눈 줄기: 위치·주기를 엇갈려 고르게
const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, '--top': `${(i * 29) % 90}%`, '--dl': `${((i * 37) % 100) / 100}s`, '--dur': `${0.55 + ((i * 13) % 5) / 10}s` }))
const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, '--top': `${(i * 31) % 90}%`, '--dl': `${((i * 53) % 100) / 25}s`, '--dur': `${3.2 + ((i * 7) % 5) / 2}s` }))
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
@@ -71,33 +64,74 @@ function heroVal(load: Load, v: ReactNode, skel: string) {
const failed = (load: Load) => load === 'error' || load === 'retrying'
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; feedLoad: Load; todayLoad: Load }
// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간
const SLOT_KEY: Record<TimeKind, string> = { morning: 'morning', day: 'day', sunset: 'evening', night: 'night' }
function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */
function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
const k = kind && SLOT_KEY[kind]
if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items
const on = items.filter((g) => g.slot_ranks?.[k] != null && g.slots?.[k] != null)
return [
...on.map((g) => ({ ...g, score: g.slots![k], rank: g.slot_ranks![k], active: true })).sort((a, b) => a.rank - b.rank),
...items.filter((g) => !on.includes(g)).map((g) => ({ ...g, active: false })),
]
}
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load }
type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet'
/** 예보 칸 하나의 하늘: 비·눈이 오면 그걸, 아니면 구름 양 */
function weatherOf(slot?: WeatherSlot): Weather {
const r = slot?.rain_type
if (r === RainType.RAIN || r === RainType.SHOWER) return 'rain'
if (r === RainType.SNOW) return 'snow'
if (r === RainType.SLEET) return 'sleet'
return slot?.sky === Sky.CLOUDY ? 'cloudy' : slot?.sky === Sky.PARTLY ? 'partly' : 'clear'
}
const WEATHER_ICON: Record<Weather, string> = { clear: 'sun', partly: 'sun_cloud', cloudy: 'cloud', rain: 'rain', snow: 'snow', sleet: 'snow' }
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋
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' },
{ cls: 'top-[30px] left-[72%] h-7 w-[64px]', d: '.4s', f: '5.4s' },
]
const CLOUD_N: Record<Weather, number> = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3 }
function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
const { open } = useSheet()
const { preview, setServerKind, setPreview } = useSky()
const mode: Mode = preview ?? 'now'
const setMode = (m: Mode) => setPreview(m === 'now' ? null : m)
const clock = useNow()
const t = kst(clock)
const kind = mode === 'now' ? (hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)) : mode
const nowKind = hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)
const kind = mode === 'now' ? nowKind : mode
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind])
const slots = today?.slots ?? []
const slot = slots.length ? slotAt(slots, mode === 'now' ? t.h : PREVIEW[mode].hour) : undefined
// 지금은 /v1/feed hero 값을, 미리보기는 그 시각의 예보 칸을 쓴다
const temp = mode === 'now' && hero ? hero.temp_c : slot?.temp_c
const top1 = hero?.top1
const who = kind === 'night' ? 'bear' : 'rabbit'
// 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
const slotOf = (k: TimeKind | 'now') => {
const h = k === 'now' ? t.h : PREVIEW[k].hour
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)
}
const weather = weatherOf(slotOf(mode))
const slotScore = mode === 'now' ? undefined : hero?.weather_slots?.[SLOT_KEY[mode]]
const score = slotScore ?? hero?.weather_score
const slotTop = mode === 'now' ? undefined : ranked.find((g) => g.active)
const top1 = slotTop ?? hero?.top1
// 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다
const moon = (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null ? { name: hero.moon_name, pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null
const tempLoad = mode === 'now' ? feedLoad : todayLoad
const tempChip = temp != null ? `${deg(temp)}${slot ? ` ${skyText(slot)}` : ''}` : null
const bubble = hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
const bubble = slotTop ? (slotTop.score >= 70 ? `오늘은 ${slotTop.name}!` : '오늘은 쉬어 가요') : hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
const status = hero?.status ?? []
const rain = weather === 'rain' || weather === 'sleet'
const snow = weather === 'snow' || weather === 'sleet'
// 시안 A: 점수 해가 주인공. 위에 시간대 탭과 날짜, 가운데 큰 해, 아래 칩 한 줄과 캐릭터 말풍선(1위 각)
// 시안 D4-2: 가운데 해(점수)와 하늘 날씨, 결론 두 줄, 상태 한 줄, 아래 하루 흐름 칸(누르면 그 시간대 하늘로)
return (
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3" data-t={kind}>
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3" data-t={kind} data-sky={weather}>
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
{STARS.map((s, i) => (
<i key={i} className="absolute size-[3px] rounded-full shadow-[0_0_6px_#fff]" style={s} />
@@ -106,19 +140,20 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
<span key={i} className="b-shoot" style={s} />
))}
</div>
<div className="relative z-[3] grid grid-cols-5 rounded-full bg-white/45 p-1" role="tablist" aria-label="시간대 배경 미리보기">
{MODES.map(([m, l]) => (
<button key={m} type="button" role="tab" aria-selected={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full py-[5px] text-[13px] font-bold', mode === m ? 'bg-white text-(--ink) shadow-[0_2px_6px_rgb(40_48_74/0.12)]' : 'text-(--ink) opacity-70')}>
{l}
</button>
))}
</div>
<p className="relative z-[3] mt-2 mb-0 text-[14px] font-bold opacity-90">
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]} · <b className="font-bagel text-[19px] font-normal">{mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock}</b>
{(rain || snow) && (
<div className="pointer-events-none absolute inset-0 z-[2]" aria-hidden="true">
{rain && DROPS.map((s, i) => <i key={i} className="b-drop" style={s} />)}
{snow && FLAKES.map((s, i) => <i key={i} className="b-flake" style={s} />)}
</div>
)}
<p className="relative z-[3] m-0 text-[14px] font-bold opacity-80">
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</p>
<div className="relative h-[196px]">
<span className="b-cloud b-fall top-3 left-[4%] h-8 w-[84px]" style={fall('.1s', '6s')} aria-hidden="true" />
<div className="b-sun b-fall absolute top-2 left-1/2 -ml-[90px] grid aspect-square w-[180px] place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
<div className="relative h-[146px]">
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
<span key={c.cls} className={cx('b-cloud b-fall z-[1]', c.cls)} style={fall(c.d, c.f)} aria-hidden="true" />
))}
<div className="b-sun b-fall absolute top-2 left-1/2 -ml-16 grid aspect-square w-32 place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
{moon && (
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
@@ -126,53 +161,52 @@ function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) {
</svg>
)}
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
<small className="block font-jua text-[13px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : '지금 날씨 점수'}</small>
<b className="block font-bagel text-[74px] leading-[0.95] font-normal">{heroVal(feedLoad, hero?.weather_score, 'w-[120px]')}</b>
<small className="block font-jua text-[12px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}</small>
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
</span>
</div>
<span className="b-cloud b-fall top-[140px] left-[58%] h-9 w-[96px]" style={fall('.25s', '6.4s')} aria-hidden="true" />
</div>
{/* 기온·습도·불쾌지수 + 서버가 고른 챙길 것(비·미세먼지·자외선·일교차 등) 한 칸을 한 줄 네 칸으로. 휴대폰에서 두 줄로 넘치지 않게 칸 안에서 위아래로 */}
<div className="relative z-[3] mt-1 grid auto-cols-fr grid-flow-col gap-1.5">
<Stat label={mode === 'now' ? '지금' : PREVIEW[mode].label}>{heroVal(tempLoad, tempChip, 'w-12')}</Stat>
<Stat label="습도">{heroVal(feedLoad, hero?.humidity != null ? `${hero.humidity}%` : null, 'w-10')}</Stat>
<Stat label="불쾌지수" tone={hero?.discomfort != null && hero.discomfort >= MUGGY ? 'warn' : 'normal'}>
{heroVal(feedLoad, hero?.discomfort != null ? `${hero.discomfort} ${hero.discomfort_label ?? ''}`.trim() : null, 'w-10')}
</Stat>
{hero?.stats?.length
? hero.stats.map((s) => (
<Stat key={s.label} label={s.label} tone={s.tone}>
{s.value}
</Stat>
))
: feedLoad === 'loading' && STAT_HOLD.map((k) => <Stat key={k} label="">{heroVal(feedLoad, null, 'w-12')}</Stat>)}
</div>
<div className="relative z-[3] mt-2 flex items-center gap-2">
<Ic name={who} alt={who === 'rabbit' ? '토끼' : '곰'} className="w-[44px] shrink-0 drop-shadow-[0_8px_10px_rgb(40_48_74/0.15)]" />
<div className="relative z-[3] text-center">
{top1 ? (
<button type="button" onClick={() => open({ type: 'gak', indexId: top1.index_id })} aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`} className="b-bubble flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-[18px] px-3 py-2 text-left">
<span className="min-w-0 flex-1 truncate font-jua text-[16px]">{bubble}</span>
<Ic name={top1.icon} className="w-7 shrink-0" />
<em className="font-bagel text-[17px] text-(--orange) not-italic">{top1.score}</em>
<button type="button" onClick={() => open({ type: 'gak', indexId: top1.index_id })} aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`} className="cursor-pointer font-jua text-[24px] leading-tight">
{bubble}
</button>
) : (
<span className="b-bubble min-w-0 flex-1 rounded-[18px] px-3 py-2 font-jua text-[16px]">{bubble ?? <Skel className="w-[120px]" />}</span>
<p className="m-0 font-jua text-[24px] leading-tight">{bubble ?? <Skel className="w-[160px]" />}</p>
)}
<p className="m-0 mt-0.5 text-[15px] font-bold opacity-80">{top1?.summary ?? (feedLoad === 'loading' ? <Skel className="w-[140px]" /> : null)}</p>
{/* 상태 한 줄: 습도·불쾌지수·자외선·미세먼지 단계 이름. 조심할 것만 색 */}
{status.length > 0 && (
<p className="m-0 mt-1.5 flex flex-wrap justify-center gap-x-1.5 font-jua text-[14px]">
{status.map((x, i) => (
<Fragment key={x.label}>
{i > 0 && <span className="opacity-30" aria-hidden="true">·</span>}
<span className={cx('whitespace-nowrap', x.tone === 'warn' && 'b-warn')}>
<span className={cx(x.tone !== 'warn' && 'opacity-75')}>{x.label}</span> <b className="font-normal">{x.value}</b>
</span>
</Fragment>
))}
</p>
)}
</div>
<div className="b-strip relative z-[3] mt-2.5 grid grid-cols-4 gap-1 rounded-[18px] p-[3px]" role="tablist" aria-label="하루 흐름, 누르면 그 시간대 하늘로">
{KINDS.map((k) => {
const s = slotOf(k)
const on = k === kind
const isNow = k === nowKind
return (
<button key={k} type="button" role="tab" aria-selected={on} onClick={() => setPreview(isNow ? null : k)} className={cx('flex cursor-pointer flex-col items-center rounded-[14px] py-1.5', on && 'b-strip-on')}>
<span className={cx('text-[13px] font-bold', on ? 'text-(--orange-deep)' : 'opacity-75')}>{isNow ? '지금' : PREVIEW[k].label}</span>
<Ic name={k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)]} className="my-0.5 h-[22px] w-[22px] object-contain" />
<b className="font-jua text-[15px] font-normal">{heroVal(todayLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</b>
</button>
)
})}
</div>
</div>
)
}
/** 히어로 아래 한 칸: 작은 이름 위, 값 아래. tone 은 서버가 정한 상태(비·경고)로 색을 바꾼다 */
function Stat({ label, tone = 'normal', children }: { label: string; tone?: HeroStatData['tone']; children: ReactNode }) {
return (
<span className="b-stat flex min-w-0 flex-col items-center rounded-2xl px-1.5 pt-1.5 pb-2 text-center break-keep" data-tone={tone}>
<small className="text-[11.5px] font-bold opacity-75">{label}</small>
<b className="font-jua text-[14.5px] leading-tight font-normal">{children}</b>
</span>
)
}
const WANING = ['기우는 달', '하현달', '그믐달']
/**
@@ -309,9 +343,11 @@ export function TodayPage() {
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 ?? []
const stories = f?.stories ?? []
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)
@@ -323,14 +359,14 @@ export function TodayPage() {
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
[6, bands?.top5?.length ? <TopBand key="top5" items={bands.top5} sub={nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
[6, bands?.top5?.length ? <TopBand key="top5" items={sloted ? stories.filter((g) => g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
]
return (
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<Hero hero={f?.hero} today={today.data} feedLoad={load} todayLoad={loadOf(today)} />
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} className="inset-x-3 top-3 bottom-1" />}
+67 -30
View File
@@ -170,39 +170,72 @@
.b-stars i {
background: #fff;
}
.b-stat {
background: rgb(255 255 255 / 0.72);
color: var(--ink);
box-shadow: inset 0 -5px 0 rgb(217 229 244 / 0.9);
/* 히어로 하루 흐름 칸: 한 판 위에 고른 칸만 흰 바탕 */
.b-strip {
background: rgb(255 255 255 / 0.42);
}
.b-hero[data-t='night'] .b-stat,
.b-hero[data-t='sunset'] .b-stat {
background: rgb(255 255 255 / 0.18);
color: #fff;
box-shadow: inset 0 -5px 0 rgb(255 255 255 / 0.12);
.b-hero[data-t='sunset'] .b-strip,
.b-hero[data-t='night'] .b-strip {
background: rgb(255 255 255 / 0.14);
}
.b-hero[data-t='sunset'] .b-stat {
background: rgb(30 16 80 / 0.2);
}
/* 히어로 칸 강조: 조심(노랑)·비(파랑). 시간대 배경과 상관없이 같은 색 */
.b-hero .b-stat[data-tone='warn'] {
background: #fff3d6;
color: var(--ink);
box-shadow: inset 0 -5px 0 #ffd98a;
}
.b-hero .b-stat[data-tone='rain'] {
background: #dcecff;
color: var(--ink);
box-shadow: inset 0 -5px 0 #a9cdf5;
}
.b-bubble {
.b-strip-on {
background: #fff;
color: var(--ink);
box-shadow: 0 8px 16px rgb(40 48 74 / 0.1);
color: #28304a; /* 밤엔 --ink 가 밝은 색이라 고정 */
box-shadow: 0 4px 12px rgb(40 48 74 / 0.1);
}
.b-hero[data-t='night'] .b-bubble {
background: rgb(30 34 70 / 0.85);
color: #fff;
/* 상태 한 줄에서 조심할 것. 밤·노을 배경에선 밝은 주황 */
.b-warn {
color: var(--orange-deep);
}
.b-hero[data-t='sunset'] .b-warn,
.b-hero[data-t='night'] .b-warn {
color: #ffb38a;
}
/* 흐리거나 비·눈 오는 아침·낮은 하늘을 잿빛으로 */
.b-hero[data-t='morning']:is([data-sky='cloudy'], [data-sky='rain'], [data-sky='snow'], [data-sky='sleet']),
.b-hero[data-t='day']:is([data-sky='cloudy'], [data-sky='rain'], [data-sky='snow'], [data-sky='sleet']) {
background: linear-gradient(180deg, #a9bbd0, #cbd7e4 55%, #eef2f7);
}
.b-hero:is([data-sky='cloudy'], [data-sky='rain'], [data-sky='snow'], [data-sky='sleet']) .b-sun {
filter: saturate(0.7) brightness(0.96);
}
.b-drop,
.b-flake {
position: absolute;
top: -24px;
animation: b-fallsky var(--dur) linear var(--dl) infinite;
}
.b-drop {
width: 2px;
height: 18px;
border-radius: 2px;
background: linear-gradient(transparent, rgb(80 130 200 / 0.7));
}
.b-hero[data-t='sunset'] .b-drop,
.b-hero[data-t='night'] .b-drop {
background: linear-gradient(transparent, rgb(220 230 255 / 0.7));
}
.b-flake {
width: 7px;
height: 7px;
border-radius: 50%;
background: #fff;
box-shadow: 0 0 4px rgb(120 150 200 / 0.5);
}
@keyframes b-fallsky {
to {
transform: translate(var(--drift, -8px), 440px);
}
}
.b-flake {
--drift: 18px;
}
@media (prefers-reduced-motion: reduce) {
.b-drop,
.b-flake {
animation: none;
top: var(--top);
}
}
.b-orb-label {
text-shadow: 0 2px 0 rgb(255 255 255 / 0.7);
@@ -536,7 +569,7 @@
.b-app[data-t='night'] [class*='bg-white/'] {
background-color: rgb(34 42 92 / 0.85);
}
.b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']) {
.b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']):not(.b-keep-bg) {
background: var(--chip);
}
.b-app[data-t='night'] [class*='border-[#dfe5ee]'] {
@@ -595,6 +628,10 @@
background: linear-gradient(180deg, rgb(110 230 180 / 0.12), rgb(255 255 255 / 0));
}
.b-app[data-t='night'] img[data-dark] {
filter: drop-shadow(0 0 1px rgb(255 255 255 / 0.9)) drop-shadow(0 0 6px rgb(255 255 255 / 0.3));
}
/* 밤엔 메인 탭 동그라미 테두리를 막대 색에 맞춘다 */
.b-app[data-t='night'] .b-tab-main > span {
--tw-ring-color: rgb(18 24 60 / 0.9);
+14 -4
View File
@@ -6,10 +6,13 @@ import { AVATAR_COLORS, iconSrc, moodEmoji, naverMap, type Load } from './lib'
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
// 거의 검은 아이콘. 밤 화면에선 테두리 빛을 둘러 보이게 한다
const DARK_ICONS = new Set(['walk', 'dog'])
export function Ic({ name, className, alt = '', style }: IcProps) {
const src = iconSrc(name)
if (!src) return <span aria-hidden className={cx('block', className)} style={style} />
return <img src={src} alt={alt} className={cx('block', className)} style={style} decoding="async" />
return <img src={src} alt={alt} className={cx('block', className)} style={style} decoding="async" data-dark={DARK_ICONS.has(name) || undefined} />
}
/** 사진 출처 표기 (공공누리 조건). 사진 위에서도 읽히게 반투명 배경. 위치는 className 으로 */
@@ -206,13 +209,20 @@ export function MapLink({ place, children, className }: { place: string; childre
)
}
export function Rows({ rows, dark = false }: { rows: { label: string; value: string; place?: string | null }[]; dark?: boolean }) {
/** 자외선 단계(1 낮음 ~ 5 위험) 칩 색 */
const LEVEL_CHIP = ['bg-[#1f9d62] text-white', 'bg-[#ffc21a] text-[#3a2a00]', 'bg-[#f0700a] text-white', 'bg-[#e03131] text-white', 'bg-[#8e3bc4] text-white']
export function Rows({ rows, dark = false }: { rows: { label: string; value: string; place?: string | null; level?: number | null }[]; dark?: boolean }) {
return (
<div className="mt-auto flex flex-col">
{rows.map((r) => (
<div key={r.label} className={cx('flex justify-between gap-2.5 border-b-2 py-2.5 font-bold last:border-b-0', dark ? 'border-white/18' : 'border-[rgb(40_48_74/0.08)]')}>
<div key={r.label} className={cx('flex items-center justify-between gap-2.5 border-b-2 py-2.5 font-bold last:border-b-0', dark ? 'border-white/18' : 'border-[rgb(40_48_74/0.08)]')}>
<span>{r.label}</span>
<b className="text-right font-jua text-[17px] font-normal">{r.place ? <MapLink place={r.place}>{r.value}</MapLink> : r.value}</b>
{r.level ? (
<b className={cx('rounded-full px-2.5 py-[3px] font-jua text-[15px] font-normal', LEVEL_CHIP[r.level - 1])}>{r.value}</b>
) : (
<b className="text-right font-jua text-[17px] font-normal">{r.place ? <MapLink place={r.place}>{r.value}</MapLink> : r.value}</b>
)}
</div>
))}
</div>