chore: main 병합 — 지금 날씨 점수 보정을 바꾸기 표로 통일

- index_service.py 충돌: main 의 오늘·내일 날씨 점수 계산은 그대로 쓰고, 보정만 strict_weather 에서 구간별 바꾸기 표(weather_slot_scores)로 바꿈
- weather_slot_scores 는 main 의 weather_why 가 쓰는 점수 근거(factors)를 그대로 둔 Result 를 돌려줌
- strict_weather 와 그 테스트(test_weather_score_is_strict_near_top) 삭제 (바꾸기 표로 통일하기로 정함)
- test_board_activates_gak_outside_its_time_window 의 ensure 스텁을 main 의 {날짜: {구간: Result}} 모양으로 맞춤
This commit is contained in:
skkim committed 2026-10-22 13:58:36 +09:00
commit 621a0cf90d
133 files changed
+8963 -489

No files matched your search

+1 -1
View File
@@ -232,7 +232,7 @@ function Shell() {
{TABS.map((t) =>
t.key === 'today' ? (
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
<NavLink key={t.key} to={t.to} end onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') ? 'text-(--orange)' : 'text-(--ink3)')}>
<NavLink key={t.key} to={t.to} end onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') || pathname.startsWith('/tomorrow/') ? 'text-(--orange)' : 'text-(--ink3)')}>
<span className="b-keep-bg grid size-[60px] place-items-center rounded-full bg-[linear-gradient(160deg,#ffb067,var(--orange)_55%,var(--orange-deep))] text-white shadow-[0_8px_18px_rgb(255_122_69/0.45),inset_0_-4px_0_rgb(0_0_0/0.12)] ring-4 ring-white/85 [&_svg]:stroke-[2.6]">
<TabIcon name={t.key} className="size-[30px]" />
</span>
+105 -11
View File
@@ -1,13 +1,13 @@
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react'
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode, type RefObject } from 'react'
import { createPortal } from 'react-dom'
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type PostReaction, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, clockShort, fall } from './lib'
import type { SlideBg } from './types'
import { deg } from './weatherText'
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
import { useAuth } from './authContext'
import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { useSheet } from './sheetContext'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { useCarousel } from './carousel'
@@ -29,6 +29,8 @@ const ACCOUNTS: Record<PostType, readonly [string, string]> = {
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
[PostType.MOON]: ['오늘 밤 달', 'moon'],
[PostType.UV]: ['자외선', 'glasses'],
[PostType.HERO]: ['오늘 날씨', 'sun'],
[PostType.TODAY_GAK]: ['오늘의 각', 'rabbit'],
}
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide
@@ -52,6 +54,22 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
const DARK = new Set<SlideBg>(['dusk', 'night'])
// 그림 배경이 있는 각(code)과 장 수. 여러 장이면 글마다 돌려 쓴다
const BG_IMAGES: Record<string, number> = { bike: 4, picnic: 1, hiking: 1, camping: 1, stars: 1, walk: 1, hangang: 1 }
const EVENT_BG_N = 4
function bgImage(name: string, n: number, seed: number): CSSProperties {
const file = n > 1 ? `${name}-${'abcd'[seed % n]}` : name
return { backgroundImage: `url(/post-bg/${file}.webp)`, backgroundSize: 'cover', backgroundPosition: 'center' }
}
/** 그림 배경: 각은 각마다, 사진 없는 행사는 행사용. 없으면 색 배경만 */
function slideImage(post: PostData, slide: Slide): CSSProperties | undefined {
if (slide.kind === 'gak') return BG_IMAGES[slide.code] ? bgImage(slide.code, BG_IMAGES[slide.code], post.post_id) : undefined
if (post.post_type === PostType.EVENT && slide.kind === 'rows' && !slide.image) return bgImage('event', EVENT_BG_N, post.post_id)
return undefined
}
function Lines({ text }: { text: string }) {
return text.split('\n').map((t, i) => (
<span key={i}>
@@ -72,14 +90,14 @@ function Big({ children, className }: { children: ReactNode; className?: string
function Pic({ name, className }: { name: string; className?: string }) {
return (
<span className={cx('b-fall pointer-events-none absolute top-[30%] right-3.5 w-[42%]', className)} style={fall('.1s', '5s')}>
<Ic name={name} className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
<Ic name={name} className="b-bob w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
</span>
)
}
const slideBase = 'relative flex h-full w-full shrink-0 flex-col px-5 py-[22px]'
function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
const { open } = useSheet()
if (slide.kind === 'hours') {
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]))
@@ -114,10 +132,17 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
}
if (slide.kind === 'gak')
return (
<div className={cx(slideBase, `b-bg-${bg}`)}>
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
<Big>{slide.line}</Big>
<Pic name={slide.code} />
{slide.say && <p className="relative z-[1] m-0 mt-2.5 w-[56%] rounded-[16px] rounded-tl-[4px] bg-white/80 px-3 py-2 text-[14px] leading-snug font-bold">{slide.say}</p>}
{/* 점수 근거: 비중 큰 조건과 지금 값. 오른쪽 아이콘과 겹치지 않게 왼쪽 반만 */}
{!!slide.rows?.length && (
<div className="relative z-[1] mt-2 w-[56%] rounded-[16px] bg-white/70 px-3 text-[14px] [&_b]:text-[15px] [&>div>div]:py-1.5 [&>div]:mt-0">
<Rows rows={slide.rows} />
</div>
)}
<b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b>
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
@@ -223,7 +248,7 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
</div>
)
return (
<div className={cx(slideBase, `b-bg-${bg}`)}>
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<Eyebrow className={DARK.has(bg) ? 'opacity-85' : undefined}>{slide.eyebrow}</Eyebrow>
<Big className="relative z-[1]">
<Lines text={slide.line} />
@@ -312,7 +337,6 @@ export function PostCardSkel() {
function FullCard({ post }: PostProps) {
const { open } = useSheet()
const { loggedIn } = useAuth()
const liked = !!post.liked
const likeCount = post.like_count
const queryClient = useQueryClient()
@@ -338,7 +362,6 @@ function FullCard({ post }: PostProps) {
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
const setLike = (on: boolean) => {
if (!loggedIn) return open({ type: 'login' })
if (on === liked || like.isPending || unlike.isPending) return
if (on) setPop((p) => p + 1)
setLikeFailed(0)
@@ -363,7 +386,7 @@ function FullCard({ post }: PostProps) {
if ((e.target as HTMLElement).closest('button')) return
const now = Date.now()
if (now - lastTap.current < 320) {
if (liked && loggedIn) setPop((p) => p + 1)
if (liked) setPop((p) => p + 1)
else setLike(true)
}
lastTap.current = now
@@ -401,7 +424,7 @@ function FullCard({ post }: PostProps) {
>
<div ref={trackRef} className="flex h-full">
{post.slides.map((s, i) => (
<SlideView key={i} slide={s} bg={bgs[i]} />
<SlideView key={i} slide={s} bg={bgs[i]} img={slideImage(post, s)} />
))}
</div>
</div>
@@ -457,3 +480,74 @@ function FullCard({ post }: PostProps) {
</article>
)
}
type FrameProps = {
title: string
account: string
avatar: string
caption?: ReactNode
more?: ReactNode
shot?: RefObject<HTMLDivElement | null>
pinned?: { key: PinnedKey; post?: PostReaction | null }
children: ReactNode
}
/** 피드 글과 같은 틀(계정 줄·본문·보내기 줄)에 날씨·각 같은 화면 조각을 담는다. 보내기는 shot(공유용 틀)이 있으면 그것을, 없으면 본문을 이미지로 */
export function PostFrame({ title, account, avatar, caption, more, shot, pinned, children }: FrameProps) {
const { open } = useSheet()
const bodyRef = useRef<HTMLDivElement>(null)
const like = usePinnedLike(pinned?.key ?? 'gak_post', pinned?.post)
const postId = pinned?.post?.post_id
const share = () => {
const el = shot?.current ?? bodyRef.current
if (el) open({ type: 'share', share: { title, slides: [el] } })
}
return (
<article className="mt-3.5 border-y border-(--line) bg-white first:mt-1" aria-label={title}>
<div className="flex items-center gap-2.5 px-3 py-2.5">
<span className="b-ring size-[34px] shrink-0 rounded-full p-0.5">
<i className="grid size-full place-items-center rounded-full bg-white">
<Ic name={avatar} className="w-[22px]" />
</i>
</span>
<span>
<b className="block text-sm leading-tight font-extrabold">날씨각</b>
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span>
</div>
<div ref={bodyRef}>{children}</div>
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
{postId != null && (
<>
<button type="button" onClick={like.toggle} aria-pressed={like.liked} aria-label="좋아요" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
<HeartIcon className={like.liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink)'} />
</button>
<button type="button" onClick={() => open({ type: 'comments', postId })} aria-label="댓글 보기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
<CommentIcon className="fill-none stroke-(--ink) [stroke-linejoin:round]" />
</button>
</>
)}
<button type="button" onClick={share} aria-label="보내기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
</button>
{more && <span className="ml-auto text-[13px] font-bold text-(--ink2)">{more}</span>}
</div>
{postId != null && (
<p className="px-3 py-0.5 text-sm font-extrabold">
{like.failed ? <span className="text-(--heart)" role="alert">좋아요를 반영하지 못했어요. 다시 해 주세요.</span> : `좋아요 ${like.count.toLocaleString()}개`}
</p>
)}
{caption && (
<p className="px-3 pt-0.5 pb-3 text-sm">
<b className="mr-[5px] font-extrabold">날씨각</b>
{caption}
</p>
)}
{postId != null && (
<button type="button" onClick={() => open({ type: 'comments', postId })} className="block cursor-pointer px-3 pb-3 text-sm font-semibold text-(--ink3)">
{pinned?.post?.comment_count ? `댓글 ${pinned.post.comment_count}개 모두 보기` : '첫 댓글 남기기'}
</button>
)}
</article>
)
}
+1 -1
View File
@@ -82,7 +82,7 @@ export function SeasonPage() {
<p className="m-0 text-[13px] font-extrabold opacity-75">이번 주 특집{w.start && w.end ? ` · ${dateRange(w.start, w.end)}` : ''}</p>
<p className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight">{w.headline}</p>
<span className="b-fall pointer-events-none absolute top-[18%] right-3.5 w-[38%]" style={fall('.1s')}>
<Ic name="maple" className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
<Ic name="maple" className="b-bob w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
</span>
{(w.poem_lines ?? []).length > 0 && (
<p className="mt-auto max-w-[72%] pt-3 font-batang text-[22px] leading-[1.7]">
+55 -68
View File
@@ -14,22 +14,26 @@ import {
listCommentsInfiniteOptions,
listCommentsInfiniteQueryKey,
listRegionsOptions,
loginMutation,
meQueryKey,
signupMutation,
unlikeCommentMutation,
updateMeMutation,
} from '../api/client/@tanstack/react-query.gen'
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen'
import { AuthProvider, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '../api/client/types.gen'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
import { GoogleButton } from './googleLogin'
import { useInstall, useInstallable } from './install'
import { InstallSheet } from './installBanner'
import { WeatherWhySheet } from './weatherWhy'
import { MixSheet } from './myGak'
import { ownPage, useRegion } from './regionContext'
import { useSky } from './skyContext'
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
import { HeartIcon } from './svg'
import { MyTalks } from './talk'
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
export function SheetProvider({ children }: { children: ReactNode }) {
@@ -72,7 +76,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
)
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요' } as const
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
@@ -96,13 +100,15 @@ 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')
return () => {
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 : TITLES[state.type]
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type]
return (
<dialog
@@ -132,6 +138,9 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{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} />}
</div>
)}
{!state && <RegionLinks />}
@@ -519,14 +528,14 @@ function ShareSheet({ share }: { share: SharePayload }) {
const srcs = useRef<string[]>([])
const [toast, setToast] = useState('')
const image = images[size]
const text = `${share.title} · 날씨각 ${SITE_URL}`
const text = `${share.title} · 날씨각`
// 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다
useEffect(() => {
if (images[size] || failed[size]) return
let alive = true
const today = new Date().toLocaleDateString('ko-KR', { month: 'long', day: 'numeric', weekday: 'long' })
shareImage(share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then(
shareImage(size === 'square' && share.square ? share.square : share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then(
(blob) => {
if (!alive) return
const src = URL.createObjectURL(blob)
@@ -541,21 +550,28 @@ function ShareSheet({ share }: { share: SharePayload }) {
return () => {
alive = false
}
}, [size, images, failed, share.slides, kind, region.name])
}, [size, images, failed, share.slides, share.square, kind, region.name])
useEffect(() => {
const list = srcs.current
return () => list.forEach((s) => URL.revokeObjectURL(s))
}, [])
// 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 공유창이 없으면 이미지를 내려받고 링크를 복사한다
// 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 이미지만 받는 앱이 있어 링크도 복사해 둔다. 공유창이 없으면 이미지를 내려받고 링크를 복사한다
const send = () => {
if (!image) return
const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' })
if (navigator.canShare?.({ files: [file], text })) {
navigator.share({ files: [file], title: share.title, text }).then(
() => {
setToast('보냈어요')
if (navigator.canShare?.({ files: [file], text, url: SITE_URL })) {
const copied = navigator.clipboard?.writeText(SITE_URL).then(
() => true,
(e: unknown) => {
console.error('[share] copy link', e)
return false
},
)
navigator.share({ files: [file], title: share.title, text, url: SITE_URL }).then(
async () => {
setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요')
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
},
(e: unknown) => {
@@ -575,7 +591,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
setToast('이미지를 내려받았어요')
return
}
navigator.clipboard.writeText(text).then(
navigator.clipboard.writeText(`${text} ${SITE_URL}`).then(
() => setToast('이미지를 내려받고 링크를 복사했어요'),
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
)
@@ -614,8 +630,6 @@ const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
const { region } = useRegion()
const { loggedIn } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const [liked, setLiked] = useState(c.liked)
const [count, setCount] = useState(c.like_count)
@@ -626,7 +640,6 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
const [likeFailed, setLikeFailed] = useState(false)
const toggle = () => {
if (!loggedIn) return open({ type: 'login' })
if (like.isPending || unlike.isPending) return
const next = !liked
setLikeFailed(false)
@@ -708,8 +721,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
const { region } = useRegion()
const { open } = useSheet()
const { loggedIn, me } = useAuth()
const { me } = useAuth()
const queryClient = useQueryClient()
const list = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
@@ -724,12 +736,11 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
const submit = (e: FormEvent) => {
e.preventDefault()
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } })
const body = text.trim()
if (!body || add.isPending) return
setAddFailed(false)
add.mutate(
{ path: { post_id: postId }, body: { body } },
{ path: { post_id: postId }, body: { body, region: region.code } },
{
onSuccess: (res) => {
setAddFailed(!res.result?.success)
@@ -783,7 +794,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
</p>
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
<button type="submit" disabled={add.isPending || (loggedIn && !text.trim())} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
<button type="submit" disabled={add.isPending || !text.trim()} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
<Swap labels={['게시', '올리는 중…']} at={add.isPending ? 1 : 0} />
</button>
</form>
@@ -792,79 +803,49 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
}
/* ---------- 로그인 ---------- */
const AUTH_ERRORS: Record<string, string> = {
AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.',
AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.',
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.',
}
function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
const { me } = useAuth()
const [mode, setMode] = useState<'login' | 'signup'>('login')
const [loginId, setLoginId] = useState('')
const [password, setPassword] = useState('')
const [nickname, setNickname] = useState('')
const [error, setError] = useState('')
const login = useMutation(loginMutation())
const signup = useMutation(signupMutation())
const pending = login.isPending || signup.isPending
const done = (res: ResAuth) => {
if (!res.result?.success || !res.access_token) {
setError(AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.')
setError('구글로 로그인하지 못했어요. 다시 해 주세요.')
return
}
setTokens(res.access_token, res.refresh_token ?? null)
track(mode === 'login' ? 'login' : 'sign_up', { method: 'id' })
track('login', { method: 'google' })
onLoggedIn()
}
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
const submit = (e: FormEvent) => {
e.preventDefault()
setError('')
if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: done, onError: fail })
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: done, onError: fail })
}
if (me) return <MeSheet onDone={onDone} />
const field = 'w-full rounded-[14px] border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-3'
return (
<Body>
<form onSubmit={submit} className="flex flex-col gap-2.5">
<p className="text-center text-sm font-semibold text-(--ink2)">좋아요·댓글은 로그인한 뒤에 할 수 있어요.</p>
<div className="grid grid-cols-2 gap-1 rounded-full bg-[#f3f6fb] p-1" role="group" aria-label="로그인 또는 가입">
{(
[
['login', '로그인'],
['signup', '처음이에요'],
] as const
).map(([m, l]) => (
<button key={m} type="button" aria-pressed={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full py-2 text-sm font-extrabold', mode === m ? 'bg-(--ink) text-white' : 'text-(--ink2)')}>
{l}
</button>
))}
</div>
<input value={loginId} onChange={(e) => setLoginId(e.target.value)} autoComplete="username" required minLength={4} maxLength={20} placeholder="아이디" aria-label="아이디" className={field} />
<input value={password} onChange={(e) => setPassword(e.target.value)} type="password" autoComplete={mode === 'login' ? 'current-password' : 'new-password'} required minLength={mode === 'signup' ? 8 : undefined} maxLength={64} placeholder={mode === 'signup' ? '비밀번호 (8자 이상)' : '비밀번호'} aria-label="비밀번호" className={field} />
{mode === 'signup' && <input value={nickname} onChange={(e) => setNickname(e.target.value)} required minLength={2} maxLength={12} placeholder="닉네임 (2~12자)" aria-label="닉네임" className={field} />}
<p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
<div className="flex flex-col gap-2.5">
<p className="text-center text-sm font-semibold text-(--ink2)">글쓰기는 로그인한 뒤에 할 수 있어요.</p>
<GoogleButton
onResult={(res) => {
setError('')
done(res)
}}
onFail={fail}
/>
<p className="m-0 text-center text-[13px] font-bold text-(--heart) empty:hidden" aria-live="polite">
{error}
</p>
<button type="submit" disabled={pending} className="cursor-pointer rounded-[14px] bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
<Swap labels={mode === 'login' ? ['로그인', '로그인 중…'] : ['가입하고 시작하기', '가입하는 중…']} at={pending ? 1 : 0} />
</button>
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
나중에 할게요
</button>
</form>
</div>
</Body>
)
}
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
function MeSheet({ onDone }: { onDone: () => void }) {
const install = useInstall()
const installable = useInstallable()
const { me, logout } = useAuth()
const queryClient = useQueryClient()
const update = useMutation(updateMeMutation())
@@ -898,8 +879,13 @@ function MeSheet({ onDone }: { onDone: () => void }) {
<Body className="flex flex-col gap-3">
<div className="flex flex-col items-center gap-1.5">
<Avatar character={me.character} color={me.color} mood={me.mood} size={64} />
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.login_id}(으)로 로그인했어요</p>
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
</div>
{installable && (
<button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
📲 홈 화면에 추가
</button>
)}
<section aria-label="내 캐릭터">
<h4 className="m-0 mb-2 text-sm font-extrabold">내 캐릭터</h4>
<div className="grid grid-cols-3 gap-2" role="radiogroup" aria-label="캐릭터 고르기">
@@ -972,6 +958,7 @@ function MeSheet({ onDone }: { onDone: () => void }) {
<p className={cx('m-0 min-h-5 text-center text-[13px] font-bold', saving ? 'text-(--ink2)' : 'text-(--heart)')} aria-live="polite">
{saving ? (saving.nickname == null ? '저장 중…' : '') : error}
</p>
<MyTalks />
<button
type="button"
onClick={() => {
+367 -108
View File
@@ -1,15 +1,35 @@
import { Fragment, useEffect, useState, type ReactNode } from 'react'
import { Link } from 'react-router'
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
import { Link, useLocation } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
import {
RainType,
Sky,
type BandArticle,
type BandEvent,
type Hero as HeroData,
type PostReaction,
type ResWeatherToday,
type TalkData,
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'
import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner'
import { MyGakRow } from './myGak'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike } from './pinnedLike'
import { FeedComposer, TalkCard } from './talk'
import { useFeedTalks } from './talkState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { useSky } from './skyContext'
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
import { DayShareCard, DayShareGrid, GakShareCard, type DayShare } from './shareCards'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
import { deg, slotAt } from './weatherText'
type Mode = 'now' | TimeKind
@@ -24,10 +44,24 @@ const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
}
// 비·눈 줄기: 위치·주기를 엇갈려 고르게
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 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 }))
const STARS = Array.from({ length: 26 }, (_, i) => ({
left: `${(i * 37) % 100}%`,
top: `${(i * 53) % 60}%`,
opacity: 0.4 + ((i * 7) % 6) / 10,
}))
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
const SHOOTS = [
{ top: '6%', left: '80%', '--len': '90px', '--dur': '7s', '--dl': '1.5s' },
@@ -65,7 +99,12 @@ function heroVal(load: Load, v: ReactNode, skel: string) {
const failed = (load: Load) => load === 'error' || load === 'retrying'
// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간
const SLOT_KEY: Record<TimeKind, string> = { morning: 'morning', day: 'day', sunset: 'evening', night: 'night' }
const SLOT_KEY: Record<TimeKind, string> = {
morning: 'morning',
day: 'day',
sunset: 'evening',
night: 'night',
}
/** 미리보기 시간대면 서버가 해당 구간의 날씨·시간대 적합도로 계산한 점수·순위로 다시 줄 세운다. 구간 값이 없으면(예전 캐시) 그대로 */
function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
@@ -73,12 +112,27 @@ function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
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),
...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 HeroProps = {
hero?: HeroData | null
post?: PostReaction | null
today?: ResWeatherToday
ranked: TopIndex[]
all: TopIndex[]
feedLoad: Load
todayLoad: Load
}
type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet'
@@ -91,26 +145,67 @@ function weatherOf(slot?: WeatherSlot): Weather {
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 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 }
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) {
function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps) {
const { open } = useSheet()
const like = usePinnedLike('hero_post', post)
const { region } = useRegion()
const tplRef = useRef<HTMLDivElement>(null)
const gridRef = useRef<HTMLDivElement>(null)
// 내일 스위치: 내일 칸 날씨는 켤 때 받고, 시간대는 화면 전체 하늘과 따로 히어로 안에서만 고른다
// 내일 날씨 페이지(/tomorrow/...)로 들어오면 내일이 켜진 채로
const { pathname } = useLocation()
const [tmr, setTmr] = useState(() => pathname.startsWith('/tomorrow/'))
const [tmrKind, setTmrKind] = useState<TimeKind>('day')
const tomorrowQ = useQuery({
...getWeatherTodayOptions({
query: { region: region.code, day: 'tomorrow' },
}),
enabled: tmr,
})
const ahead = hero?.tomorrow
const share = () =>
tplRef.current &&
open({
type: 'share',
share: {
title: `${region.name} ${tmr ? '내일' : '오늘'} 날씨`,
slides: [tplRef.current],
square: gridRef.current ? [gridRef.current] : undefined,
},
})
const { preview, setServerKind, setPreview } = useSky()
const mode: Mode = preview ?? 'now'
const mode: Mode = tmr ? tmrKind : (preview ?? 'now')
const clock = useNow()
const t = kst(clock)
const t = kst(tmr ? new Date(clock.getTime() + 86400000) : clock)
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 slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? []
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad
// 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
// 지금은 가장 가까운 3시간 칸(17시면 18시 칸). 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
const slotOf = (k: TimeKind | 'now') => {
@@ -124,22 +219,78 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
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 slotScore = mode === 'now' ? undefined : (tmr ? ahead?.weather_slots : hero?.weather_slots)?.[SLOT_KEY[mode]]
const score = tmr ? slotScore : (slotScore ?? hero?.weather_score)
// 점수 옆 ? 버튼: 보고 있는 시간대(지금이면 지금 구간)의 날씨 점수 근거
const whyKey = mode === 'now' ? SLOT_KEY[nowKind] : SLOT_KEY[mode]
const why = (tmr ? ahead?.weather_why : hero?.weather_why)?.[whyKey]
const whyLabel = tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label
const slotTop = mode === 'now' || tmr ? undefined : ranked.find((g) => g.active)
const top1 = tmr ? ahead?.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 moon =
!tmr && (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 when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label
const bubble = slotTop ? (slotTop.score >= 70 ? `${when}은 ${slotTop.name}!` : `${when}은 쉬어 가요`) : hero ? (hero.bubble ?? '지금은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
const status = hero?.status ?? []
const bubble = tmr
? top1
? top1.score >= 70
? `내일은 ${top1.name}!`
: '내일은 쉬어 가요'
: null
: slotTop
? slotTop.score >= 70
? `${when}은 ${slotTop.name}!`
: `${when}은 쉬어 가요`
: hero
? (hero.bubble ?? '지금은 쉬어 가요')
: failed(feedLoad)
? '앗, 날씨를 못 불러왔어요'
: null
// 내일은 최저·최고 기온과 고른 시간대 습도
const temps = slots.flatMap((x) => (x.temp_c != null ? [x.temp_c] : []))
const humidity = tmr && mode !== 'now' ? slotOf(mode)?.humidity : null
const status = tmr
? [
...(temps.length
? [
{ label: '최저', value: deg(Math.min(...temps)), tone: 'info' },
{ label: '최고', value: deg(Math.max(...temps)), tone: 'info' },
]
: []),
...(humidity != null ? [{ label: '습도', value: `${humidity}%`, tone: 'info' }] : []),
]
: (hero?.status ?? [])
const rain = weather === 'rain' || weather === 'sleet'
const snow = weather === 'snow' || weather === 'sleet'
// 공유 이미지: 아침~밤 네 시간대 모두. 점수는 시간대 점수, 각은 그 시간대 1등
const days: DayShare[] = KINDS.map((k) => {
const isNow = !tmr && k === nowKind
const s = slotOf(isNow ? 'now' : k)
const top = tmr ? ahead?.top1 : atSlot(all, k).find((g) => g.active)
return {
kind: k,
label: PREVIEW[k].label,
now: isNow,
icon: k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)],
temp: s?.temp_c != null ? deg(s.temp_c) : '–',
score: (tmr ? ahead?.weather_slots : hero?.weather_slots)?.[SLOT_KEY[k]] ?? (isNow ? hero?.weather_score : null),
gak: top ? { name: top.name, icon: top.icon } : null,
}
})
// 시안 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} data-sky={weather}>
<DayShareCard days={days} ref={tplRef} />
<DayShareGrid days={days} ref={gridRef} />
<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} />
@@ -154,29 +305,109 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
{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 z-[3] flex items-center justify-between">
<span className="flex items-center gap-2">
<span className="b-strip grid grid-cols-2 rounded-full p-[3px]" role="radiogroup" aria-label="오늘 또는 내일 날씨">
{(
[
[false, '오늘'],
[true, '내일'],
] as const
).map(([v, l]) => (
<button
key={l}
type="button"
role="radio"
aria-checked={tmr === v}
onClick={() => setTmr(v)}
className={cx('cursor-pointer rounded-full px-2.5 py-0.5 font-jua text-[13px]', tmr === v ? 'b-strip-on text-(--orange-deep)' : 'opacity-75')}
>
{l}
</button>
))}
</span>
<span className="text-[13px] font-bold opacity-80">
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</span>
</span>
<span className="flex items-center gap-3 [&_svg]:size-[22px] [&_svg]:stroke-[2]">
{post && (
<>
<button
type="button"
onClick={like.toggle}
aria-pressed={like.liked}
aria-label={like.failed ? '좋아요를 반영하지 못했어요. 다시 눌러 주세요' : '오늘 날씨 좋아요'}
className={cx('relative flex cursor-pointer items-center gap-1 text-[13px] font-extrabold', TAP44, !like.liked && 'opacity-80')}
>
<HeartIcon className={like.liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-current'} />
{like.count > 0 && like.count.toLocaleString()}
</button>
<button
type="button"
onClick={() => open({ type: 'comments', postId: post.post_id })}
aria-label="오늘 날씨 댓글"
className={cx('relative flex cursor-pointer items-center gap-1 text-[13px] font-extrabold opacity-80', TAP44)}
>
<CommentIcon className="fill-none stroke-current [stroke-linejoin:round]" />
{post.comment_count > 0 && post.comment_count.toLocaleString()}
</button>
</>
)}
<button type="button" onClick={share} aria-label="오늘 날씨 보내기" className={cx('relative grid size-7 cursor-pointer place-items-center opacity-80', TAP44)}>
<SendIcon className="fill-none stroke-current [stroke-linecap:round] [stroke-linejoin:round]" />
</button>
</span>
</div>
<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">
<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>
)}
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
<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 key={c.cls} className={cx('b-fall absolute z-[1]', c.cls)} style={fall(c.d, c.f)} aria-hidden="true">
<span className="b-cloud b-bob inset-0" />
</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>
)}
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
<small className="block font-jua text-[12px]">
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : 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>
{why && score != null && (
<button
type="button"
onClick={() =>
open({
type: 'weatherWhy',
why: { label: whyLabel, score, why },
})
}
aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`}
className={cx(
'absolute right-0 bottom-1 z-[2] grid size-7 cursor-pointer place-items-center rounded-full bg-white font-jua text-[16px] text-(--orange-deep) shadow-[0_2px_6px_rgb(40_48_74/0.25)]',
TAP44,
)}
>
?
</button>
)}
</div>
</div>
</div>
<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="cursor-pointer font-jua text-[24px] leading-tight">
<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>
) : (
@@ -188,7 +419,11 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
<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>}
{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>
@@ -199,14 +434,21 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
</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 isNow = k === nowKind
const isNow = !tmr && k === nowKind
const s = slotOf(isNow ? 'now' : k)
const on = k === kind
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')}>
<button
key={k}
type="button"
role="tab"
aria-selected={on}
onClick={() => (tmr ? setTmrKind(k) : 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>
<b className="font-jua text-[15px] font-normal">{heroVal(slotsLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</b>
</button>
)
})}
@@ -227,27 +469,42 @@ function moonPath(pct: number, r: number, lit: boolean) {
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
}
function Stories({ items }: { items: TopIndex[] }) {
function GakCard({ items, post, place, at }: { items: TopIndex[]; post?: PostReaction | null; place: string; at: string }) {
const { open } = useSheet()
const tplRef = useRef<HTMLDivElement>(null)
const top = items.filter((g) => g.active).slice(0, 5)
return (
<Rail label="오늘의 각 순위">
{items.map((g, i) => (
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, 지금 시간대 아님`} className={cx('flex w-[72px] cursor-pointer flex-col items-center gap-1', !g.active && 'opacity-55')}>
<span className={cx('relative size-[68px] rounded-full p-[3px]', !g.active || g.score < 50 ? 'bg-[#d6deea]' : 'b-ring')}>
<i className="grid size-full place-items-center rounded-full border-[3px] border-(--page) bg-(--page)">
<Ic name={g.icon} className="w-[42px]" />
</i>
{i < 3 && g.active && <Ic name={MEDALS[i]} className="absolute -right-1 -bottom-1 w-[25px]" />}
</span>
<b className="font-jua text-[13px] font-normal whitespace-nowrap">{g.name}</b>
{g.active ? (
<em className="font-bagel text-[12.5px] leading-none text-(--orange) not-italic">{g.score}</em>
) : (
<small className="text-[11px] leading-none font-extrabold text-(--ink3)">지금 아님</small>
)}
</button>
))}
</Rail>
<PostFrame
title={`오늘의 각 · ${place}`}
account="오늘의 각"
avatar="rabbit"
more={<Link to="/gak">전체 보기</Link>}
caption="누르면 계산 근거를 보여 줘요"
shot={tplRef}
pinned={{ key: 'gak_post', post }}
>
<GakShareCard items={top} title={`오늘의 각 · ${place} ${at}`} ref={tplRef} />
<div className="b-band-2 px-4 pt-3.5 pb-3">
<p className="m-0 font-jua text-[19px]">
오늘의 각 · {place} {at}
</p>
<ol className="m-0 mt-2 grid list-none gap-1.5 p-0">
{top.map((g, i) => (
<li key={g.index_id}>
<button type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} className="flex w-full cursor-pointer items-center gap-2.5 rounded-[18px] bg-white px-3 py-2 text-left shadow-[inset_0_-4px_0_var(--shade)]">
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="w-[24px] shrink-0" /> : <span className="w-[24px] shrink-0 text-center font-jua text-(--ink3)">{i + 1}</span>}
<Ic name={g.icon} className="w-[34px] shrink-0" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[16px] leading-tight font-normal">{g.name}</b>
{g.summary && <small className="block truncate text-xs font-semibold text-(--ink2)">{g.summary}</small>}
</span>
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
</button>
</li>
))}
</ol>
</div>
</PostFrame>
)
}
@@ -260,27 +517,6 @@ function PostsSkel() {
)
}
const STORY_SKELS = Array.from({ length: 6 }, (_, i) => i)
/** Stories 와 같은 칸(68px 동그라미 + 이름 + 점수)을 6개 */
function StoriesSkel() {
return (
<SkelRail>
{STORY_SKELS.map((i) => (
<span key={i} className="flex w-[72px] flex-col items-center gap-1">
<Skel shape className="size-[68px] rounded-full" />
<b className="font-jua text-[13px] font-normal">
<Skel className="w-12" />
</b>
<em className="font-bagel text-[12.5px] leading-none not-italic">
<Skel className="w-6" />
</em>
</span>
))}
</SkelRail>
)
}
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
return (
<section className={cx('mt-3.5 pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
@@ -309,25 +545,6 @@ function EventsBand({ events }: { events: BandEvent[] }) {
)
}
function TopBand({ items, sub }: { items: TopIndex[]; sub: string }) {
const { open } = useSheet()
return (
<Band tone={2} title="지금 뜨는 각 TOP 5" sub={sub} to="/gak">
<Rail>
{items.slice(0, 5).map((g, i) => (
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} className="relative flex w-[138px] cursor-pointer flex-col items-start gap-1 rounded-[22px] bg-white p-3 text-left shadow-[inset_0_-5px_0_var(--shade)]">
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="absolute top-2 left-2 w-[26px]" /> : <span className="absolute top-2.5 left-3 font-jua text-(--ink3)">{i + 1}위</span>}
<Ic name={g.icon} className="w-[58px] self-center" />
<b className="font-jua text-base font-normal">{g.name}</b>
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
{g.summary && <small className="text-xs font-semibold text-(--ink2)">{g.summary}</small>}
</button>
))}
</Rail>
</Band>
)
}
function SeasonBand({ news }: { news: BandArticle[] }) {
const { open } = useSheet()
return (
@@ -347,11 +564,14 @@ function SeasonBand({ news }: { news: BandArticle[] }) {
)
}
const TALK_EVERY = 3
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 { open } = useSheet()
const f = feed.data
const posts = f?.posts ?? []
const stories = atSlot(f?.stories ?? [], preview)
@@ -359,25 +579,60 @@ export function TodayPage() {
const bands = f?.bands
const nowAt = f?.hero?.now_at
const load = loadOf(feed)
const [mine, setMine] = useState<TalkData[]>([])
// 사람들이 쓴 글은 4·7·10번째 포스트 뒤에 하나씩(3번째 뒤 행사 띠와 안 붙게), 남은 글은 피드 끝에. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고
const feedTalks = useFeedTalks()
const talks = feedTalks.talks.filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
const between = Math.max(0, Math.floor((posts.length - 1) / TALK_EVERY))
const moreRef = useRef<HTMLDivElement>(null)
const { more, loadMore } = feedTalks
useEffect(() => {
const el = moreRef.current
if (!el || !more) return
const io = new IntersectionObserver((es) => es.some((e) => e.isIntersecting) && loadMore(), { rootMargin: '600px' })
io.observe(el)
return () => io.disconnect()
}, [more, loadMore])
useEffect(() => {
window.scrollTo({ top: 0 })
}, [region.code])
// 친구가 보낸 내 각 링크(/?my=...)로 들어오면 내 동네 기준으로 보여 준다
useEffect(() => {
const url = new URL(window.location.href)
const code = url.searchParams.get('my')
if (!code) return
url.searchParams.delete('my')
window.history.replaceState(window.history.state, '', url)
const g = fromShare(code)
if (g) open({ type: 'mix', shared: g })
}, [open])
// 디자인대로 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={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} 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" />}
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} />
<FeedComposer onPosted={(t) => setMine((m) => [t, ...m])} />
{mine.map((t) => (
<TalkCard key={t.talk_id} t={t} onGone={() => setMine((m) => m.filter((x) => x.talk_id !== t.talk_id))} />
))}
<MyGakRow />
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
) : load === 'loading' ? (
<PostCardSkel />
) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
)}
<InstallBanner />
<div>
{load === 'loading' && <PostsSkel />}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
@@ -387,10 +642,14 @@ export function TodayPage() {
{posts.map((p, i) => (
<Fragment key={p.post_id}>
<PostCard post={p} />
{i === 1 && <FoliageCard />}
{i > 0 && i % TALK_EVERY === 0 && talks[i / TALK_EVERY - 1] && <TalkCard t={talks[i / TALK_EVERY - 1]} />}
{bandAt.find(([at]) => at === i + 1)?.[1]}
</Fragment>
))}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
{load !== 'loading' && talks.slice(between).map((t) => <TalkCard key={t.talk_id} t={t} />)}
<div ref={moreRef} aria-hidden />
</div>
</section>
)
+18 -8
View File
@@ -22,11 +22,12 @@
outline-offset: 2px;
}
/* 하늘에서 떨어진 뒤 둥둥 */
/* 하늘에서 떨어진 뒤(.b-fall) 둥둥(.b-bob, 그 안쪽 요소). 한 요소에 transform 애니메이션 둘이 겹치면 GPU로 못 넘겨 매 프레임 메인 스레드가 일한다 */
.b-fall {
animation:
b-drop 1.05s cubic-bezier(0.22, 0.9, 0.3, 1) var(--d, 0s) both,
b-float var(--f, 4.8s) ease-in-out calc(var(--d, 0s) + 1.05s) infinite;
animation: b-drop 1.05s cubic-bezier(0.22, 0.9, 0.3, 1) var(--d, 0s) backwards;
}
.b-bob {
animation: b-float var(--f, 4.8s) ease-in-out calc(var(--d, 0s) + 1.05s) infinite;
}
@keyframes b-drop {
0% {
@@ -53,7 +54,7 @@
transform: translateY(0);
}
50% {
transform: translateY(calc(var(--amp, 9px) * -1)) rotate(var(--tilt, 1.2deg));
transform: translateY(-9px) rotate(1.2deg);
}
}
@@ -509,6 +510,9 @@
border-radius: 50%;
background: #fff;
box-shadow: 0 0 6px rgb(255 255 255 / 0.8);
}
/* 별은 밤에만 보이니 반짝임·별똥별도 밤에만 돌린다 (낮에 안 보이는 채로 돌면 매 프레임 일을 한다) */
.b-skybg[data-t='night'] .b-skystars i {
animation: b-twinkle var(--tw, 5s) ease-in-out infinite;
animation-delay: var(--dl, 0s);
}
@@ -523,8 +527,14 @@
border-radius: 2px;
background: linear-gradient(90deg, rgb(255 255 255 / 0), #fff);
opacity: 0;
}
:is(.b-skybg, .b-hero)[data-t='night'] .b-shoot {
animation: b-shoot var(--dur, 8s) ease-in var(--dl, 0s) infinite;
}
/* 아래 창이 열려 있는 동안 뒤 화면 움직임은 멈춘다 (창이 버벅이지 않게) */
html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot, .b-stars i) {
animation-play-state: paused !important;
}
@keyframes b-shoot {
0%, 86% { opacity: 0; transform: rotate(-24deg) translateX(0); }
89% { opacity: 1; }
@@ -543,13 +553,13 @@
}
}
/* 위·아래 바는 반투명으로 하늘이 비치게 */
/* 위 바는 반투명으로 하늘이 비치게, 아래 탭 바는 홈 바 자리까지 글이 비치지 않게 불투명 */
.b-topbg {
background: rgb(255 255 255 / 0.18);
transition: background 1.4s ease;
}
.b-tabbar {
background: rgb(255 255 255 / 0.6);
background: #f7faff;
overflow: visible;
border-color: rgb(255 255 255 / 0.4);
}
@@ -557,7 +567,7 @@
background: rgb(14 20 51 / 0.35);
}
.b-app[data-t='night'] .b-tabbar {
background: rgb(18 24 60 / 0.62);
background: #121838;
border-color: rgb(255 255 255 / 0.08);
}
+109
View File
@@ -0,0 +1,109 @@
import { useState } from 'react'
import data from '../../seo/foliage_2026.json'
import { cx } from '../lib/utils'
import { kst } from './lib'
import { PostFrame } from './Post'
import { Ic } from './ui'
type Kind = 'maple' | 'ginkgo'
type Spot = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string }
type Stage = 'before' | 'first' | 'peak'
// 지도 그림(public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값
const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 }
// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 절정으로 본다
const FIRST_DAYS = 14
const PEAK_DAYS = 3
const SEASON = { from: '09-20', to: '11-25' }
const SEOUL = { lat: 37.566, lon: 126.978 }
const STAGE: Record<Stage, { label: string; icon: string }> = {
before: { label: '단풍 전', icon: 'size-3 opacity-60 grayscale' },
first: { label: '첫 단풍', icon: 'size-3.5' },
peak: { label: '절정', icon: 'size-[18px]' },
}
const KIND: Record<Kind, { label: string; icon: string }> = {
maple: { label: '단풍', icon: 'maple' },
ginkgo: { label: '은행', icon: 'ginkgo' },
}
const pos = (m: Spot) => ({
left: `${((MAP.ox + (m.lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size) * 100}%`,
top: `${((MAP.oy + (MAP.lat1 - m.lat) * MAP.s) / MAP.size) * 100}%`,
})
const DAY = 86_400_000
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
function stage(m: Spot, today: string): Stage {
const d = days(today, m.peak)
if (d <= PEAK_DAYS) return 'peak'
return d <= FIRST_DAYS ? 'first' : 'before'
}
const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
/** 단풍철에만 나오는 단풍 지도 카드. 산마다 절정 예측일로 지금 절정·곧·아직·지남을 점으로 */
export function FoliageCard() {
const [now] = useState(() => new Date())
const t = kst(now)
const today = `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}`
const [picked, setPicked] = useState<string | null>(null)
const mmdd = today.slice(5)
if (mmdd < SEASON.from || mmdd > SEASON.to) return null
const spots = (data.spots as Spot[]).map((m) => ({ ...m, stage: stage(m, today) }))
const peakNow = spots.filter((m) => m.stage === 'peak').map((m) => m.name)
// 발표 지도에 서울 안 산은 없어 서울 시청에서 가장 가까운 단풍 예측 산으로
const forecast = spots.filter((m) => m.kind === 'maple' && m.basis.startsWith('산림청'))
const seoul = forecast.reduce((a, b) => (Math.hypot(b.lat - SEOUL.lat, b.lon - SEOUL.lon) < Math.hypot(a.lat - SEOUL.lat, a.lon - SEOUL.lon) ? b : a))
const sel = spots.find((m) => m.name === picked)
return (
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peakNow.length ? `지금 절정 ${peakNow.length}곳: ${peakNow.slice(0, 5).join(' · ')}${peakNow.length > 5 ? ' 외' : ''}` : undefined}>
<div className="relative bg-[#fff6ea] px-4 pt-4 pb-3">
<p className="m-0 text-[13px] font-extrabold opacity-75">단풍 지도 · {md(today)}</p>
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">서울 근교 {seoul.name} 절정 예상 {md(seoul.peak)}</p>
<div className="relative mx-auto mt-1 aspect-square w-full">
<img src="/foliage/korea-map.webp" alt="단풍 지도" className="absolute inset-0 size-full" />
{spots.map((m) => (
<button
key={m.name}
type="button"
onClick={() => setPicked(m.name === picked ? null : m.name)}
aria-label={`${m.name} ${KIND[m.kind].label} ${STAGE[m.stage].label}, 절정 예상 ${md(m.peak)}`}
className={cx('absolute grid -translate-x-1/2 -translate-y-1/2 cursor-pointer place-items-center p-0.5', m.name === picked && 'z-[2] scale-150')}
style={pos(m)}
>
<Ic name={KIND[m.kind].icon} className={cx('drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.4)]', STAGE[m.stage].icon)} />
</button>
))}
{sel && (
<p className="absolute right-0 bottom-0 z-[3] m-0 max-w-[75%] rounded-[14px] bg-white/95 px-3 py-2 text-[13px] font-bold shadow-[0_4px_12px_rgb(40_48_74/0.15)]">
<b className="font-jua text-[16px] font-normal">{sel.name}</b> {sel.region}
<br />
{KIND[sel.kind].label} {STAGE[sel.stage].label} · 절정 예상 {md(sel.peak)}
{!sel.basis.startsWith('산림청') && <small className="block text-[11px] font-semibold text-(--ink3)">가까운 예측 지점 날짜예요</small>}
</p>
)}
</div>
<div className="mt-2 flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
{(Object.keys(KIND) as Kind[]).map((k) => (
<span key={k} className="flex items-center gap-1">
<Ic name={KIND[k].icon} className="size-4" />
{KIND[k].label}
</span>
))}
<span className="opacity-30" aria-hidden="true">|</span>
{(Object.keys(STAGE) as Stage[]).map((st) => (
<span key={st} className="flex items-center gap-1">
<Ic name="maple" className={cx('size-4', STAGE[st].icon)} />
{STAGE[st].label}
</span>
))}
</div>
<p className="m-0 mt-1.5 text-center text-[11px] font-semibold text-(--ink3)">
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요
</p>
</div>
</PostFrame>
)
}
+82
View File
@@ -0,0 +1,82 @@
import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { authConfigOptions, googleLoginMutation } from '../api/client/@tanstack/react-query.gen'
import type { ResAuth } from '../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
}
/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id
const login = useMutation(googleLoginMutation())
const box = useRef<HTMLDivElement>(null)
const [broken, setBroken] = useState(false)
const { mutate } = login
// 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다
const cb = useRef({ onResult, onFail })
useEffect(() => {
cb.current = { onResult, onFail }
}, [onResult, onFail])
useEffect(() => {
if (!clientId || !box.current) return
let alive = true
loadGoogle().then(
(g) => {
if (!alive || !box.current) return
g.initialize({
client_id: clientId,
ux_mode: 'popup',
callback: (r) => {
if (!r.credential) return cb.current.onFail()
mutate({ body: { credential: r.credential } }, { onSuccess: (res) => cb.current.onResult(res), onError: () => cb.current.onFail() })
},
})
g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth })
},
(e: unknown) => {
console.error('[google] script', e)
if (alive) setBroken(true)
},
)
return () => {
alive = false
}
}, [clientId, mutate])
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} />
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
</div>
)
}
+104
View File
@@ -0,0 +1,104 @@
import { useSyncExternalStore } from 'react'
import { track } from '../lib/analytics'
import { useSheet } from './sheetContext'
type InstallPromptEvent = Event & { prompt: () => Promise<void>; userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }> }
const DISMISS_KEY = 'nalssigak.b.installDismissed'
const DISMISS_DAYS = 14
// 안드로이드 Chrome 은 설치할 수 있을 때 이 이벤트를 한 번 준다. 앱이 뜨기 전에 올 수 있어 모듈을 불러올 때 바로 받아 둔다
let deferred: InstallPromptEvent | null = null
const listeners = new Set<() => void>()
const notify = () => listeners.forEach((cb) => cb())
if (typeof window !== 'undefined') {
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault()
deferred = e as InstallPromptEvent
notify()
})
window.addEventListener('appinstalled', () => {
deferred = null
track('install_done', {})
notify()
})
}
export type Platform = 'standalone' | 'inapp' | 'ios' | 'android' | 'other'
/** 지금 이 기기에서 홈 화면 추가를 어떻게 안내할지 */
export function platform(): Platform {
const ua = navigator.userAgent
if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) return 'standalone'
if (/KAKAOTALK|Instagram|FBAN|FBAV|NAVER\(inapp|; wv\)|Line\//i.test(ua)) return 'inapp'
if (/iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return 'ios'
if (/Android/.test(ua)) return 'android'
return 'other'
}
const onPhone = () => ['ios', 'android', 'inapp'].includes(platform())
/** 설치를 권할 곳: 휴대폰 브라우저, 그리고 설치창을 띄울 수 있는 PC 브라우저(Chrome·Edge). PC Safari·Firefox 와 이미 설치해 연 화면은 뺀다 */
export function useInstallable() {
const canPrompt = useCanPrompt()
return platform() !== 'standalone' && (onPhone() || canPrompt)
}
/** 설치창을 바로 띄울 수 있는지 (안드로이드 Chrome 등) */
export function useCanPrompt() {
return useSyncExternalStore(
(cb) => {
listeners.add(cb)
return () => listeners.delete(cb)
},
() => deferred != null,
)
}
/** 설치창을 띄운다. 띄웠으면 true */
export async function promptInstall(): Promise<boolean> {
if (!deferred) return false
const e = deferred
deferred = null
notify()
try {
await e.prompt()
} catch (err) {
// 이미 한 번 띄웠거나 브라우저가 막으면 안내 창으로 넘긴다
console.warn('[install] prompt', err)
return false
}
const { outcome } = await e.userChoice
track('install_choice', { outcome })
return true
}
export function dismissed(): boolean {
try {
const at = Number(localStorage.getItem(DISMISS_KEY))
return at > 0 && Date.now() - at < DISMISS_DAYS * 86_400_000
} catch {
// 저장소를 못 쓰는 브라우저에선 이번 방문 동안만 보인다
return false
}
}
export function dismiss() {
try {
localStorage.setItem(DISMISS_KEY, String(Date.now()))
} catch (e) {
console.warn('[install] 닫은 시각을 저장하지 못함', e)
}
}
/** 홈 화면에 추가: 설치창을 띄울 수 있으면 띄우고, 아니면 기기별 안내 창을 연다 */
export function useInstall() {
const { open } = useSheet()
const canPrompt = useCanPrompt()
return async (from: 'banner' | 'menu') => {
const shown = canPrompt && (await promptInstall())
track('install_click', { from, method: shown ? 'prompt' : 'guide' })
if (!shown) open({ type: 'install' })
}
}
+130
View File
@@ -0,0 +1,130 @@
import { useEffect, useState, type ReactNode } from 'react'
import { track } from '../lib/analytics'
import { dismiss, dismissed, platform, promptInstall, useCanPrompt, useInstall, useInstallable } from './install'
const SITE = 'https://weather.o2o.kr'
/** 오늘 탭의 작은 설치 카드. 오늘의 각까지 본 뒤 자리에 놓고, 설치할 수 있는 곳(휴대폰, PC Chrome·Edge)에서만 보인다. 닫으면 2주 숨긴다 */
export function InstallBanner() {
const install = useInstall()
const installable = useInstallable()
const [closed, setClosed] = useState(dismissed)
const hidden = !installable || closed
useEffect(() => {
if (!hidden) track('install_banner_view', {})
}, [hidden])
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]" />
<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>
</div>
</aside>
)
}
function Steps({ items }: { items: ReactNode[] }) {
return (
<ol className="m-0 flex list-none flex-col gap-2 p-0">
{items.map((t, i) => (
<li key={i} className="flex items-start gap-2.5 rounded-2xl bg-[#f3f6fb] px-3.5 py-3 text-[14.5px] font-bold">
<b className="grid size-6 shrink-0 place-items-center rounded-full bg-(--orange) font-jua text-[14px] font-normal text-white">{i + 1}</b>
<span>{t}</span>
</li>
))}
</ol>
)
}
// 사파리 아래 가운데 공유 버튼과 공유 목록의 '홈 화면에 추가' 모양 그대로
const ShareGlyph = () => (
<svg viewBox="0 0 24 24" className="mx-0.5 inline size-[22px] -translate-y-0.5 fill-none stroke-[#2f7cf6] stroke-2 [stroke-linecap:round] [stroke-linejoin:round]" aria-label="공유 버튼">
<path d="M12 3v12M8 7l4-4 4 4M6 11H5v10h14V11h-1" />
</svg>
)
const AddGlyph = () => (
<svg viewBox="0 0 24 24" className="mx-0.5 inline size-[22px] -translate-y-0.5 fill-none stroke-(--ink) stroke-2 [stroke-linecap:round]" aria-hidden="true">
<rect x="4" y="4" width="16" height="16" rx="4" />
<path d="M12 8v8M8 12h8" />
</svg>
)
/** 설치창을 띄울 수 없는 기기의 안내. 안드로이드는 열어 둔 사이 크롬이 설치를 허락하면 바로 설치 버튼으로 바뀐다 */
export function InstallSheet() {
const p = platform()
const canPrompt = useCanPrompt()
const [copied, setCopied] = useState(false)
const copy = () =>
navigator.clipboard.writeText(SITE).then(
() => setCopied(true),
(e: unknown) => console.error('[install] copy', e),
)
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
{p === 'standalone' && <p className="m-0 text-[15px] font-bold">이미 홈 화면에서 열었어요. 다음에도 아이콘을 눌러 바로 여세요.</p>}
{p === 'ios' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">아이폰은 Safari에서 이렇게 추가해요.</p>
<Steps
items={[
<>화면 아래 <ShareGlyph /> 공유 버튼을 눌러요. 안 보이면 오른쪽 아래 ··· 를 누른 뒤 공유</>,
<>목록을 올려 <AddGlyph /> 홈 화면에 추가를 눌러요</>,
"오른쪽 위 '추가'를 누르면 끝이에요",
]}
/>
</>
)}
{p === 'android' && canPrompt && (
<button type="button" onClick={() => void promptInstall()} className="w-full cursor-pointer rounded-full bg-(--orange) py-3 font-jua text-[17px] text-white">
📲 지금 설치하기
</button>
)}
{p === 'android' && !canPrompt && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">지금 브라우저에선 설치창을 바로 띄울 수 없어요. 메뉴에서 추가해 주세요.</p>
<Steps items={['오른쪽 위 ⋮ 메뉴를 눌러요', "'홈 화면에 추가' 또는 '앱 설치'를 눌러요", "'추가' 또는 '설치'를 누르면 끝이에요"]} />
</>
)}
{p === 'inapp' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">카카오톡 같은 앱 안에서는 홈 화면에 추가할 수 없어요. Safari나 Chrome에서 열어 주세요.</p>
<Steps items={["오른쪽 위 ⋮ 또는 공유 버튼에서 '다른 브라우저로 열기'를 눌러요", '안 보이면 아래 주소를 복사해 Safari·Chrome에 붙여 넣어요', "열린 화면에서 '홈 화면에 추가'를 눌러요"]} />
</>
)}
{p === 'other' && (
<>
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">휴대폰에서 열면 홈 화면에 추가할 수 있어요.</p>
<Steps items={['휴대폰 Safari(아이폰)나 Chrome(갤럭시)에서 아래 주소를 열어요', "공유 버튼이나 ⋮ 메뉴에서 '홈 화면에 추가'를 눌러요"]} />
</>
)}
{(p === 'inapp' || p === 'other') && (
<div className="mt-3 flex items-center gap-2 rounded-2xl border border-(--line) px-3.5 py-2.5">
<span className="min-w-0 flex-1 truncate text-[14.5px] font-bold select-all">{SITE}</span>
<button type="button" onClick={copy} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
{copied ? '복사함' : '주소 복사'}
</button>
</div>
)}
</div>
)
}
+2 -2
View File
@@ -1,6 +1,6 @@
import type { CSSProperties } from 'react'
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain'])
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental', 'ginkgo'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
@@ -39,7 +39,7 @@ export const MOODS = [
export const moodEmoji = (mood?: string | null) => MOODS.find(([k]) => k === mood)?.[1]
export const fall = (d: string, f = '4.8s', amp?: string) => ({ '--d': d, '--f': f, ...(amp ? { '--amp': amp } : {}) }) as CSSProperties
export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const
+235
View File
@@ -0,0 +1,235 @@
import { useState, type ReactNode } from 'react'
import type { MyGakPreset, MyGakRule, MyGakScore } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Ic, Rail, Sec } from './ui'
const SLOT_WORD = Object.fromEntries(SLOTS) as Record<Slot, string>
function Score({ s, big }: { s?: MyGakScore; big?: boolean }) {
const v = s?.score
return (
<em className={cx('ml-auto font-bagel leading-none not-italic', big ? 'text-[36px]' : 'text-[28px]', v == null || v < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>
{v ?? '–'}
</em>
)
}
function Reasons({ s }: { s?: MyGakScore }) {
if (!s?.slot) return <p className="m-0 text-[12.5px] font-semibold text-(--ink3)">예보를 불러오는 중이에요</p>
return (
<p className="m-0 text-[12.5px] leading-snug font-semibold text-(--ink2)">
<b className="mr-1 text-(--ink)">{SLOT_WORD[s.slot as Slot]}</b>
{s.reasons?.join(' · ')}
</p>
)
}
/** 오늘 탭의 내 각 줄: 내가 정한 조건으로 매긴 오늘 점수 */
export function MyGakRow() {
const { open } = useSheet()
const { items, remove } = useMyGak()
const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? []
const [copied, setCopied] = useState<number | null>(null)
const send = (g: MyGak, i: number) => {
const url = shareUrl(g)
if (navigator.share) {
navigator.share({ title: `${g.name} · 날씨각`, url }).catch((e: unknown) => {
if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[myGak] share', e)
})
return
}
navigator.clipboard.writeText(url).then(
() => setCopied(i),
(e: unknown) => console.error('[myGak] copy', e),
)
}
return (
<>
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
<Rail label="내 각">
{items.map((g, i) => (
<div key={g.id ?? 'local'} className="flex w-[220px] flex-col gap-1.5 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<div className="flex items-center gap-1">
<b className="font-jua text-[17px] leading-tight font-normal">{g.name}</b>
<Score s={scores[i]} />
</div>
<Reasons s={scores[i]} />
<div className="mt-auto flex gap-1.5 pt-0.5">
<button type="button" onClick={() => send(g, i)} className="cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
{copied === i ? '링크 복사함' : '친구에게 보내기'}
</button>
<button type="button" onClick={() => remove(g)} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[12.5px] font-extrabold text-(--ink2)">
지우기
</button>
</div>
</div>
))}
<button type="button" onClick={() => open({ type: 'mix' })} className="flex w-[120px] cursor-pointer flex-col items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-(--line) p-3 font-jua text-[15px] text-(--ink2)">
<span className="text-[26px] leading-none">+</span>
내 각 만들기
</button>
</Rail>
</>
)
}
function Row({ label, on, onToggle, children }: { label: string; on: boolean; onToggle: () => void; children: ReactNode }) {
return (
<div className={cx('flex min-h-[44px] flex-wrap items-center gap-2 border-b border-(--line) py-2', !on && 'opacity-60')}>
<label className="flex w-[84px] cursor-pointer items-center gap-1.5 text-[14px] font-extrabold">
<input type="checkbox" checked={on} onChange={onToggle} className="size-4 accent-(--orange)" />
{label}
</label>
{on ? <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5 text-[13.5px] font-bold">{children}</div> : <span className="text-[13px] font-semibold text-(--ink3)">상관없음</span>}
</div>
)
}
function Num({ value, onChange, min, max, label }: { value: number; onChange: (v: number) => void; min: number; max: number; label: string }) {
return (
<input
type="number"
inputMode="numeric"
aria-label={label}
value={value}
min={min}
max={max}
onChange={(e) => {
const v = Number(e.target.value)
if (e.target.value !== '' && Number.isFinite(v)) onChange(Math.min(max, Math.max(min, v)))
}}
className="w-[58px] rounded-xl bg-[#f3f6fb] px-2 py-1.5 text-center tabular-nums"
/>
)
}
function Choice<T extends string>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<span className="flex gap-1" role="radiogroup" aria-label={label}>
{options.map(([k, word]) => (
<button key={k} type="button" role="radio" aria-checked={value === k} onClick={() => onChange(k)} className={cx('cursor-pointer rounded-full px-3 py-1.5', value === k ? 'bg-(--orange) text-white' : 'bg-[#eef4fc]')}>
{word}
</button>
))}
</span>
)
}
type Filled<T> = { [K in keyof T]-?: NonNullable<T[K]> }
const DEFAULT_RULE: Filled<MyGakRule> = { temp: [15, 25], rain: 'dry', wind_max: 4, air: 'normal', humidity: [30, 60], slots: ['morning', 'day', 'evening', 'night'] }
type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity'
const condsOf = (r: MyGakRule): Record<Cond, boolean> => ({ temp: !!r.temp, rain: !!r.rain, wind_max: r.wind_max != null, air: !!r.air, humidity: !!r.humidity })
/** 있는 각을 골라 그 각 조건으로 채운다 */
function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) {
const items = usePresets().data ?? []
if (!items.length) return null
return (
<div className="mb-3">
<span className="font-jua text-[19px]">있는 각에서 불러오기</span>
<div className="-mx-4">
<Rail label="있는 각에서 불러오기">
{items.map((p) => (
<button
key={p.code}
type="button"
aria-pressed={picked === p.code}
onClick={() => onPick(p)}
className={cx('flex w-[68px] cursor-pointer flex-col items-center gap-1 rounded-2xl px-1 py-2 text-[12px] leading-tight font-extrabold', picked === p.code ? 'bg-(--orange) text-white' : 'bg-[#f3f6fb] text-(--ink2)')}
>
<Ic name={p.icon} className="size-9" />
<span className="w-full truncate">{p.name}</span>
</button>
))}
</Rail>
</div>
</div>
)
}
/** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */
export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) {
const { region } = useRegion()
const { create, pending, failed } = useMyGak()
const [name, setName] = useState(shared?.name ?? '')
const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE)
const [on, setOn] = useState<Record<Cond, boolean>>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false })
const [picked, setPicked] = useState<string | null>(null)
const pick = (p: MyGakPreset) => {
setPicked(p.code)
setName(p.name)
setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE)
setOn(condsOf(p.rule))
}
const set = <K extends keyof typeof vals>(k: K, v: (typeof vals)[K]) => setVals((x) => ({ ...x, [k]: v }))
const toggle = (k: Cond) => setOn((x) => ({ ...x, [k]: !x[k] }))
const rule: MyGakRule = { slots: vals.slots, ...(Object.fromEntries((Object.keys(on) as Cond[]).filter((k) => on[k]).map((k) => [k, vals[k]])) as Partial<MyGakRule>) }
const valid = Object.values(on).some(Boolean) && vals.slots.length > 0 && (!on.temp || vals.temp[0] < vals.temp[1]) && (!on.humidity || vals.humidity[0] < vals.humidity[1])
const score = useMyGakScores(valid ? [rule] : []).data?.scores?.[0]
const title = gakName(name) || '이름 없는 각'
const toggleSlot = (s: Slot) => set('slots', vals.slots.includes(s) ? vals.slots.filter((x) => x !== s) : SLOTS.map(([k]) => k).filter((k) => k === s || vals.slots.includes(k)))
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
{shared ? (
<p className="m-0 text-[13px] font-bold text-(--ink2)">친구가 보낸 각이에요. {region.name} 기준 점수예요</p>
) : (
<>
<PresetPicker picked={picked} onPick={pick} />
<label className="block">
<span className="font-jua text-[19px]">이름</span>
<input value={name} onChange={(e) => setName(e.target.value)} maxLength={11} placeholder="소맥, 야독, 새우깡" className="mt-1.5 w-full rounded-2xl bg-[#f3f6fb] px-3.5 py-2.5 text-[15px]" />
</label>
</>
)}
<fieldset disabled={!!shared} className="m-0 mt-3 border-0 p-0">
<legend className="font-jua text-[19px]">조건</legend>
<Row label="기온" on={on.temp} onToggle={() => toggle('temp')}>
<Num label="최저 기온" value={vals.temp[0]} min={-20} max={40} onChange={(v) => set('temp', [v, vals.temp[1]])} />~
<Num label="최고 기온" value={vals.temp[1]} min={-20} max={40} onChange={(v) => set('temp', [vals.temp[0], v])} />° 체감
</Row>
<Row label="비" on={on.rain} onToggle={() => toggle('rain')}>
<Choice label="비" value={vals.rain} onChange={(v) => set('rain', v)} options={[['dry', '안 와야'], ['wet', '와야']]} />
</Row>
<Row label="바람" on={on.wind_max} onToggle={() => toggle('wind_max')}>
초속 <Num label="바람 상한" value={vals.wind_max} min={1} max={20} onChange={(v) => set('wind_max', v)} />m 이하
</Row>
<Row label="미세먼지" on={on.air} onToggle={() => toggle('air')}>
<Choice label="미세먼지" value={vals.air} onChange={(v) => set('air', v)} options={[['good', '좋음만'], ['normal', '보통까지']]} />
</Row>
<Row label="습도" on={on.humidity} onToggle={() => toggle('humidity')}>
<Num label="최저 습도" value={vals.humidity[0]} min={0} max={100} onChange={(v) => set('humidity', [v, vals.humidity[1]])} />~
<Num label="최고 습도" value={vals.humidity[1]} min={0} max={100} onChange={(v) => set('humidity', [vals.humidity[0], v])} />%
</Row>
<div className="flex flex-wrap items-center gap-1.5 py-2.5 text-[13.5px] font-bold">
<span className="w-[84px] text-[14px] font-extrabold">시간대</span>
{SLOTS.map(([k, word]) => (
<button key={k} type="button" aria-pressed={vals.slots.includes(k)} onClick={() => toggleSlot(k)} className={cx('cursor-pointer rounded-full px-3 py-1.5', vals.slots.includes(k) ? 'bg-(--orange) text-white' : 'bg-[#eef4fc]')}>
{word}
</button>
))}
</div>
</fieldset>
<div className="mt-2 flex flex-col gap-1.5 rounded-[20px] bg-[#f3f6fb] p-3.5">
<div className="flex items-center">
<b className="font-jua text-[20px] font-normal">{title}</b>
<Score s={valid ? score : undefined} big />
</div>
{valid ? <Reasons s={score} /> : <p className="m-0 text-[12.5px] font-semibold text-(--ink3)">조건과 시간대를 하나 이상 골라요</p>}
</div>
{failed && <p className="mt-2 mb-0 text-xs font-bold text-(--heart)">저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요</p>}
<button
type="button"
disabled={!valid || !gakName(name) || pending}
onClick={() => create({ name, rule }, onDone)}
className="mt-3.5 w-full cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[17px] text-white disabled:cursor-default disabled:opacity-45"
>
{shared ? '내 각으로 가져오기' : '내 각으로 저장'}
</button>
</div>
)
}
+137
View File
@@ -0,0 +1,137 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useSyncExternalStore } from 'react'
import { SITE_URL } from '../api/setup'
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '../api/client/@tanstack/react-query.gen'
import { scoreMyGak } from '../api/client/sdk.gen'
import type { MyGakRule, MyGakScore } from '../api/client/types.gen'
import { useAuth } from './authContext'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
const KEY = 'nalssigak.b.myRule'
export type Slot = 'morning' | 'day' | 'evening' | 'night'
export const SLOTS: [Slot, string][] = [
['morning', '아침'],
['day', '낮'],
['evening', '저녁'],
['night', '밤'],
]
/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) */
export type MyGak = { id?: number; name: string; rule: MyGakRule }
function readLocal(): MyGak | null {
try {
const raw = localStorage.getItem(KEY)
return raw ? (JSON.parse(raw) as MyGak) : null
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
return null
}
}
// 시트와 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
let local = readLocal()
const listeners = new Set<() => void>()
const subscribe = (cb: () => void) => {
listeners.add(cb)
return () => listeners.delete(cb)
}
function setLocal(g: MyGak | null) {
local = g
listeners.forEach((cb) => cb())
try {
if (g) localStorage.setItem(KEY, JSON.stringify(g))
else localStorage.removeItem(KEY)
} catch (e) {
console.warn('[myGak] 기기에 저장하지 못함', e)
}
}
/** 이름 끝에 '각'을 붙인다 (서버와 같은 규칙) */
export const gakName = (name: string) => {
const n = name.trim().replace(/\s+/g, ' ')
return n && !n.endsWith('각') ? `${n}각` : n
}
/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 */
export function shareUrl(g: MyGak) {
const json = JSON.stringify({ n: g.name, r: g.rule })
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)))
return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`
}
export function fromShare(code: string): MyGak | null {
try {
const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/'))
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; r?: unknown }
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, rule: v.r as MyGakRule } : null
} catch (e) {
console.warn('[myGak] 받은 링크를 읽지 못함', e)
return null
}
}
/** 조건들의 우리 동네 오늘 점수. 조건이 같으면 캐시를 같이 쓴다 */
export function useMyGakScores(rules: MyGakRule[]) {
const { region } = useRegion()
return useQuery({
queryKey: ['myGakScore', region.code, rules],
enabled: rules.length > 0,
staleTime: 5 * 60_000,
queryFn: async (): Promise<{ nowSlot?: Slot | null; scores: MyGakScore[] }> => {
const { data } = await scoreMyGak({ body: { region_code: region.code, rules } })
if (!data.result?.success) throw new Error(data.result?.desc ?? 'score')
return { nowSlot: data.now_slot, scores: data.scores ?? [] }
},
})
}
/** 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기) */
export function usePresets() {
return useQuery({ ...listPresetsOptions(), staleTime: Infinity, select: (d) => d.items ?? [] })
}
export function useMyGak() {
const { loggedIn } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const q = useQuery({ ...listMyGakOptions(), enabled: loggedIn })
const saved = useSyncExternalStore(subscribe, () => local)
const refresh = () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() })
const add = useMutation({ ...addMyGakMutation(), onSuccess: refresh })
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: refresh })
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
const { mutate } = add
useEffect(() => {
if (!loggedIn || !saved) return
mutate({ body: { name: saved.name, rule: saved.rule } }, { onSuccess: () => setLocal(null) })
}, [loggedIn, saved, mutate])
const items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, rule: g.rule })) : saved ? [saved] : []
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
const create = (g: MyGak, onDone?: () => void) => {
const item = { name: gakName(g.name), rule: g.rule }
if (loggedIn) {
add.mutate({ body: item }, { onSuccess: (res) => res.result?.success && onDone?.() })
return
}
if (saved) {
open({ type: 'login' })
return
}
setLocal(item)
onDone?.()
}
const remove = (g: MyGak) => {
if (g.id != null) return del.mutate({ path: { my_gak_id: g.id } })
setLocal(null)
}
return { items, create, remove, pending: add.isPending, failed: add.data?.result?.success === false }
}
+38
View File
@@ -0,0 +1,38 @@
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen'
import type { PostReaction, ResFeed } from '../api/client/types.gen'
export type PinnedKey = 'hero_post' | 'gak_post'
/** 히어로·오늘의 각처럼 포스트 틀이 아닌 카드의 좋아요. 화면을 먼저 바꾸고 실패하면 되돌린다 */
export function usePinnedLike(key: PinnedKey, r?: PostReaction | null) {
const queryClient = useQueryClient()
const like = useMutation(likePostMutation())
const unlike = useMutation(unlikePostMutation())
const [failed, setFailed] = useState(false)
const liked = !!r?.liked
const count = r?.like_count ?? 0
const patch = (values: Partial<PostReaction>) =>
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
feed?.[key] && feed[key].post_id === r?.post_id ? { ...feed, [key]: { ...feed[key], ...values } } : feed,
)
const toggle = () => {
if (!r || like.isPending || unlike.isPending) return
const on = !liked
setFailed(false)
patch({ liked: on, like_count: count + (on ? 1 : -1) })
const revert = () => {
patch({ liked, like_count: count })
setFailed(true)
}
;(on ? like : unlike).mutate(
{ path: { post_id: r.post_id } },
{
onSuccess: (res) => (res.result?.success ? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) }) : revert()),
onError: revert,
},
)
}
return { liked, count, failed, toggle }
}
+6 -4
View File
@@ -10,9 +10,9 @@ const KEY = 'nalssigak.b.region'
type RegionPage = (typeof regionPages)[number]
/** /today/gyeonggi/seongnam, /today/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
/** /today/gyeonggi/seongnam, /tomorrow/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
function pageOf(pathname: string): RegionPage | undefined {
const path = pathname.match(/^\/today\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
const path = pathname.match(/^\/(?:today|tomorrow)\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
return path ? regionPages.find((p) => p.path === path) : undefined
}
@@ -45,9 +45,11 @@ export function RegionProvider({ children }: { children: ReactNode }) {
const navigate = useNavigate()
const page = pageOf(pathname)
const pageRef = useRef(page)
const dayRef = useRef(pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today')
useEffect(() => {
pageRef.current = page
}, [page])
dayRef.current = pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today'
}, [page, pathname])
const [stored] = useState(readStored)
const [landing] = useState(page)
const [chosen, setRegionState] = useState<RegionData>(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION)))
@@ -61,7 +63,7 @@ export function RegionProvider({ children }: { children: ReactNode }) {
setRegionState(r)
writeStored(r)
const next = ownPage(r.code)
if (pageRef.current && next && next !== pageRef.current) navigate(`/today/${next.path}`)
if (pageRef.current && next && next !== pageRef.current) navigate(`/${dayRef.current}/${next.path}`)
}, [navigate])
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음)
+116
View File
@@ -0,0 +1,116 @@
import type { Ref } from 'react'
import { createPortal } from 'react-dom'
import { cx } from '../lib/utils'
import type { TopIndex } from '../api/client/types.gen'
import { MEDALS, type TimeKind } from './lib'
import { Ic } from './ui'
/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
function Offscreen({ children }: { children: React.ReactNode }) {
return createPortal(
<div aria-hidden="true" className="pointer-events-none fixed top-0 -left-[10000px] w-[380px]">
{children}
</div>,
document.body,
)
}
export type DayShare = {
kind: TimeKind
label: string
now: boolean
icon: string
temp: string
score?: number | null
gak?: { name: string; icon: string } | null
}
function DayLabel({ d, size }: { d: DayShare; size: string }) {
return (
<span className={cx('flex items-center gap-1.5 font-jua leading-none', size)}>
{d.label}
{d.now && <small className="rounded-full bg-[#ff7a45] px-2 py-0.5 font-sans text-[13px] font-extrabold text-white">지금</small>}
</span>
)
}
/** 히어로 공유: 아침·낮·저녁·밤 네 줄. 줄마다 그 시간대 하늘에 날씨·기온, 날씨 점수, 그 시간 1등 각. 로고·지역·날짜는 공유 틀이 그린다 */
export function DayShareCard({ days, ref }: { days: DayShare[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col">
{days.map((d) => (
<div key={d.kind} className="b-hero grid flex-1 grid-cols-[96px_1fr_auto] items-center gap-3 px-4" data-t={d.kind}>
<span className="flex flex-col gap-1.5">
<DayLabel d={d} size="text-[28px]" />
<span className="flex items-center gap-1 font-jua text-[22px] leading-none">
<Ic name={d.icon} className="h-7 w-7 object-contain" />
{d.temp}
</span>
</span>
<span className="flex min-w-0 items-center gap-2">
{d.gak && <Ic name={d.gak.icon} className="w-10 shrink-0" />}
<b className="font-jua text-[24px] leading-tight font-normal break-keep">{d.gak?.name ?? '쉬어 가요'}</b>
</span>
<span className="text-right">
<b className="block font-bagel text-[62px] leading-[0.9] font-normal">{d.score ?? '–'}</b>
<small className="text-[13px] font-bold opacity-75">날씨 점수</small>
</span>
</div>
))}
</div>
</Offscreen>
)
}
/** 1:1 공유용: 같은 내용을 2×2 칸으로 */
export function DayShareGrid({ days, ref }: { days: DayShare[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="grid aspect-square grid-cols-2 grid-rows-2">
{days.map((d) => (
<div key={d.kind} className="b-hero flex flex-col justify-between p-4" data-t={d.kind}>
<span className="flex items-center justify-between">
<DayLabel d={d} size="text-[26px]" />
<span className="flex items-center gap-1 font-jua text-[20px] leading-none">
<Ic name={d.icon} className="h-7 w-7 object-contain" />
{d.temp}
</span>
</span>
<span>
<b className="block font-bagel text-[64px] leading-[0.9] font-normal">{d.score ?? '–'}</b>
<small className="text-[12px] font-bold opacity-75">날씨 점수</small>
</span>
<span className="flex min-w-0 items-center gap-1.5">
{d.gak && <Ic name={d.gak.icon} className="w-8 shrink-0" />}
<b className="truncate font-jua text-[21px] font-normal">{d.gak?.name ?? '쉬어 가요'}</b>
</span>
</div>
))}
</div>
</Offscreen>
)
}
export function GakShareCard({ items, title, ref }: { items: TopIndex[]; title: string; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="b-band-2 flex aspect-[4/5] flex-col bg-white px-5 pt-5 pb-4">
<p className="m-0 font-jua text-[22px]">{title}</p>
<ol className="m-0 mt-3 grid list-none gap-2 p-0">
{items.map((g, i) => (
<li key={g.index_id} className="flex items-center gap-2.5 rounded-[18px] bg-white px-3 py-2.5 shadow-[inset_0_-4px_0_var(--shade)]">
{i < 3 ? <Ic name={MEDALS[i]} className="w-[24px] shrink-0" /> : <span className="w-[24px] shrink-0 text-center font-jua text-(--ink3)">{i + 1}</span>}
<Ic name={g.icon} className="w-[36px] shrink-0" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[17px] leading-tight font-normal">{g.name}</b>
{g.summary && <small className="block truncate text-xs font-semibold text-(--ink2)">{g.summary}</small>}
</span>
<em className="font-bagel text-[24px] leading-none text-(--orange) not-italic">{g.score}</em>
</li>
))}
</ol>
</div>
</Offscreen>
)
}
+7 -1
View File
@@ -1,5 +1,8 @@
import type { MyGak } from './myGakState'
import type { WeatherWhyPayload } from './weatherWhy'
import { createContext, use } from 'react'
export type SharePayload = { title: string; slides: HTMLElement[] }
/** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides) */
export type SharePayload = { title: string; slides: HTMLElement[]; square?: HTMLElement[] }
type CommentsState = { type: 'comments'; postId: number; draft?: string }
@@ -12,6 +15,9 @@ export type SheetState =
| { type: 'login'; then?: CommentsState }
| { type: 'me' }
| { type: 'region' }
| { type: 'mix'; shared?: MyGak }
| { type: 'install' }
| { type: 'weatherWhy'; why: WeatherWhyPayload }
| null
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
+2 -1
View File
@@ -35,7 +35,7 @@ export function PinIcon({ className }: P) {
)
}
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' }) {
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' | 'talk' }) {
return (
<svg viewBox="0 0 24 24" {...line} className={className} aria-hidden="true">
{name === 'today' && <path d="M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />}
@@ -55,6 +55,7 @@ export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky'
<circle cx="12" cy="15" r="1.6" />
</>
)}
{name === 'talk' && <path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.5 4v-4h0A1.5 1.5 0 0 1 4 14.5zM8 8.5h8M8 12h5" />}
{name === 'season' && <path d="M12 6.5C10 5 7 4.5 3.5 5v14c3.5-.5 6.5 0 8.5 1.5 2-1.5 5-2 8.5-1.5V5C17 4.5 14 5 12 6.5zM12 6.5v14" />}
</svg>
)
+302
View File
@@ -0,0 +1,302 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from 'react'
import {
addTalkMutation,
blockTalkAuthorMutation,
deleteTalkMutation,
likeTalkMutation,
reportTalkMutation,
unlikeTalkMutation,
} from '../api/client/@tanstack/react-query.gen'
import { uploadTalkImage } from '../api/client/sdk.gen'
import { TalkReport, type TalkData } from '../api/client/types.gen'
import { API_BASE_URL } from '../api/setup'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, kst } from './lib'
import { useRegion } from './regionContext'
import { useMyTalks } from './talkState'
import { useSheet } from './sheetContext'
import { HeartIcon } from './svg'
import { Avatar, TAP44 } from './ui'
const BODY_MAX = 100
const PHOTO_MAX = 10 * 1024 * 1024
// 서버 ErrorType 이름 → 안내
const WRITE_ERRORS: Record<string, string> = {
LINK_NOT_ALLOWED: '링크나 전화번호는 쓸 수 없어요.',
DAILY_LIMIT: '오늘은 더 쓸 수 없어요. 하루 5개까지예요.',
INVALID_INPUT: '100자 안으로 써 주세요.',
}
const REASONS = [
[TalkReport.ABUSE, '욕설·비하'],
[TalkReport.SPAM, '광고·도배'],
[TalkReport.PRIVACY, '개인정보 노출'],
[TalkReport.ETC, '기타'],
] as const
/** 쓴 시각을 시간대로만: 정확한 시각은 동선이 드러나서 뭉갠다 */
function slotWord(iso: string) {
const h = kst(iso).h
return h < 6 ? '새벽' : h < 10 ? '아침' : h < 17 ? '낮' : h < 21 ? '저녁' : '밤'
}
function useRefreshTalks() {
const queryClient = useQueryClient()
return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') })
}
function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
const { region } = useRegion()
const { loggedIn, me } = useAuth()
const { open } = useSheet()
const refresh = useRefreshTalks()
const add = useMutation(addTalkMutation())
const [text, setText] = useState('')
const [error, setError] = useState<string | null>(null)
const [photo, setPhoto] = useState<{ file: File; src: string } | null>(null)
const [uploading, setUploading] = useState(false)
const fileRef = useRef<HTMLInputElement>(null)
const busy = add.isPending || uploading
useEffect(() => {
if (!photo) return
return () => URL.revokeObjectURL(photo.src)
}, [photo])
const pick = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
e.target.value = ''
if (!file) return
if (file.size > PHOTO_MAX) return setError('사진은 10MB까지 올릴 수 있어요.')
setError(null)
setPhoto({ file, src: URL.createObjectURL(file) })
}
// 사진이 있으면 먼저 올려 주소를 받고, 그 주소를 글에 붙인다
const upload = async (): Promise<string | undefined> => {
if (!photo) return undefined
setUploading(true)
try {
const { data } = await uploadTalkImage({ body: { file: photo.file } })
if (!data.result?.success || !data.image) throw new Error(data.result?.desc ?? 'upload')
return data.image
} finally {
setUploading(false)
}
}
const submit = (e: FormEvent) => {
e.preventDefault()
if (!loggedIn) return open({ type: 'login' })
const body = text.trim()
if (!body || busy) return
setError(null)
upload().then(
(image) =>
add.mutate(
{ body: { region_code: region.code, body, image } },
{
onSuccess: (res) => {
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
setText('')
setPhoto(null)
refresh()
if (res.talk) onDone?.(res.talk)
},
onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
},
),
(e: unknown) => {
console.error('[talk] photo upload', e)
setError('사진을 올리지 못했어요. 사진 파일인지 확인해 주세요.')
},
)
}
return (
<form onSubmit={submit} className="mx-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
onFocus={() => !loggedIn && open({ type: 'login' })}
readOnly={busy}
maxLength={BODY_MAX}
rows={2}
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
aria-label="동네 이야기 쓰기"
className="w-full resize-none rounded-2xl bg-[#f3f6fb] px-3 py-2.5 text-[14.5px]"
/>
{photo && (
<div className="relative mt-2 w-[96px]">
<img src={photo.src} alt="올릴 사진" className="aspect-[4/5] w-full rounded-xl object-cover" />
<button type="button" onClick={() => setPhoto(null)} aria-label="사진 빼기" className="absolute -top-1.5 -right-1.5 grid size-6 cursor-pointer place-items-center rounded-full bg-(--ink) text-[13px] font-extrabold text-white">
×
</button>
</div>
)}
<input ref={fileRef} type="file" accept="image/*" onChange={pick} hidden />
<div className="mt-1.5 flex items-center gap-2 text-xs font-bold text-(--ink3)">
<button type="button" onClick={() => (loggedIn ? fileRef.current?.click() : open({ type: 'login' }))} disabled={busy} className="shrink-0 cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2) disabled:opacity-40">
사진
</button>
<span className="min-w-0 truncate">{me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}</span>
<span className="ml-auto tabular-nums">
{text.length}/{BODY_MAX}
</span>
<button type="submit" disabled={busy || (loggedIn && !text.trim())} className="shrink-0 cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white disabled:opacity-40">
{busy ? '올리는 중…' : '올리기'}
</button>
</div>
{error && (
<p className="mt-1 mb-0 text-xs font-bold text-(--heart)" role="alert">
{error}
</p>
)}
</form>
)
}
/** onGone: 내 글을 지웠을 때. 목록을 다시 받아도 빠지지 않는 곳(방금 쓴 글)에서 직접 뺀다 */
function TalkRow({ t, onGone }: { t: TalkData; onGone?: () => void }) {
const { loggedIn } = useAuth()
const { open } = useSheet()
const refresh = useRefreshTalks()
const [liked, setLiked] = useState(t.liked)
const [count, setCount] = useState(t.like_count)
const [menu, setMenu] = useState<'closed' | 'open' | 'report' | 'done'>('closed')
const like = useMutation(likeTalkMutation())
const unlike = useMutation(unlikeTalkMutation())
const remove = useMutation(deleteTalkMutation())
const report = useMutation(reportTalkMutation())
const block = useMutation(blockTalkAuthorMutation())
const [failed, setFailed] = useState(false)
const toggle = () => {
if (like.isPending || unlike.isPending) return
const next = !liked
setLiked(next)
setCount((n) => n + (next ? 1 : -1))
;(next ? like : unlike).mutate(
{ path: { talk_id: t.talk_id } },
{
onSuccess: (res) => {
if (res.result?.success && res.like_count != null) return setCount(res.like_count)
setLiked(!next)
setCount(t.like_count)
},
onError: () => {
setLiked(!next)
setCount(t.like_count)
},
},
)
}
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
const after = {
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true)
setMenu('done')
refresh()
},
onError: () => setFailed(true),
}
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }))
return (
<div className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 border-b border-(--line) py-2.5 last:border-b-0">
<Avatar character={t.character} color={t.color} mood={t.mood} />
<div className="min-w-0">
<small className="block text-xs font-bold text-(--ink3)">
<b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b>
{[t.region_name, slotWord(t.created_at), t.weather].filter(Boolean).join(' · ')}
</small>
<p className="m-0 mt-0.5 text-[14.5px] break-words whitespace-pre-wrap">{t.body}</p>
{t.image && <img src={t.image.startsWith('/v1/') ? API_BASE_URL + t.image : t.image} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
{ago(t.created_at)} · 좋아요 {count}개 ·{' '}
<button type="button" onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
{t.mine ? '내 글' : '더보기'}
</button>
</small>
{menu !== 'closed' && (
<div className="mt-1.5 flex flex-wrap gap-1.5 text-[12.5px] font-extrabold" role="group" aria-label="글 메뉴">
{menu === 'done' ? (
<span className="text-[#1f9d62]">처리했어요</span>
) : t.mine ? (
<button type="button" onClick={() => remove.mutate({ path: { talk_id: t.talk_id } }, { ...after, onSuccess: (res) => (after.onSuccess(res), res.result?.success && onGone?.()) })} disabled={remove.isPending} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
지우기
</button>
) : menu === 'report' ? (
REASONS.map(([reason, label]) => (
<button key={reason} type="button" onClick={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after)} disabled={report.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
{label}
</button>
))
) : (
<>
<button type="button" onClick={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after))} disabled={block.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
이 사람 글 안 보기
</button>
<button type="button" onClick={() => guard(() => setMenu('report'))} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
신고하기
</button>
</>
)}
{failed && (
<span className="text-(--heart)" role="alert">
못 했어요. 다시 해 주세요
</span>
)}
</div>
)}
</div>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
</button>
</div>
)
}
/** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */
/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 방금 올린 글은 바로 아래에 보인다 (피드 사이 글은 새로 받을 때 섞인다) */
export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void }) {
return (
<div className="mt-3.5">
<Composer onDone={onPosted} />
</div>
)
}
/** 피드에 끼우는 글 한 장 */
export function TalkCard({ t, onGone }: { t: TalkData; onGone?: () => void }) {
return (
<article className="mt-3.5 border-y border-(--line) bg-white px-3" aria-label={`${t.nickname}의 글`}>
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} onGone={onGone} />
</article>
)
}
/** 내 정보 창의 내가 쓴 글 */
export function MyTalks() {
const { talks, loaded, more, loadMore } = useMyTalks()
if (!loaded) return null
return (
<section aria-label="내 글">
<h4 className="m-0 mb-1 text-sm font-extrabold">내 글</h4>
{talks.length ? (
talks.map((t) => <TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />)
) : (
<p className="m-0 text-[13px] font-semibold text-(--ink3)">아직 쓴 글이 없어요</p>
)}
{more && (
<button type="button" onClick={() => loadMore()} className="mt-1 w-full cursor-pointer rounded-[14px] bg-[#f3f6fb] py-2.5 text-[13.5px] font-extrabold text-(--ink2)">
더 보기
</button>
)}
</section>
)
}
+33
View File
@@ -0,0 +1,33 @@
import { useInfiniteQuery } from '@tanstack/react-query'
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions } from '../api/client/@tanstack/react-query.gen'
import { useRegion } from './regionContext'
/** 사람들이 쓴 글. 오늘 피드에 운영 포스트 사이사이 섞고, 남은 글은 피드 끝에 이어 붙인다 */
export function useFeedTalks() {
const { region } = useRegion()
const list = useInfiniteQuery({
...listTalksInfiniteOptions({ query: { region: region.code } }),
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
})
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
}
}
/** 내가 쓴 글 (최신순) */
export function useMyTalks() {
const list = useInfiniteQuery({
...listMyTalksInfiniteOptions(),
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
})
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
loaded: list.isSuccess,
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
}
}
+54
View File
@@ -0,0 +1,54 @@
import type { WeatherWhy } from '../api/client/types.gen'
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[] }
// 조건마다 같은 색을 막대 칸과 아래 줄 점에 같이 써서 이어 보이게
const COLOR: Record<string, string> = {
기온: '#ff7a45',
비: '#4f97e3',
햇볕: '#ffb02e',
바람: '#5fb8b0',
습도: '#8e8cf0',
미세먼지: '#b59a86',
}
const colorOf = (label: string) => COLOR[label] ?? '#9aa3b8'
/** 날씨 점수 근거: 비중만큼 나눈 막대(채운 만큼 얻은 점수)와 조건별 지금 값 */
export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) {
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-4 pb-[18px]">
<p className="m-0 flex items-baseline gap-2">
<b className="font-bagel text-[44px] leading-none font-normal">{d.score}</b>
<span className="font-jua text-[17px] text-(--ink2)">{d.label} 날씨 점수</span>
</p>
<div className="mt-3 flex h-7 gap-[3px] overflow-hidden rounded-[10px]" role="img" aria-label={d.why.map((w) => `${w.label} 비중 ${w.weight}% 중 ${w.score}점`).join(', ')}>
{d.why.map((w) => (
<span key={w.label} className="relative h-full bg-[#eef2f8]" style={{ width: `${w.weight}%` }}>
<span className="absolute inset-y-0 left-0" style={{ width: `${w.score}%`, background: colorOf(w.label) }} />
</span>
))}
</div>
<p className="m-0 mt-1.5 text-[12.5px] font-semibold text-(--ink3)">칸 넓이는 비중, 채운 만큼이 얻은 점수예요</p>
<ul className="m-0 mt-3 flex list-none flex-col gap-1.5 p-0">
{d.why.map((w) => (
<li key={w.label} className="flex items-center gap-3 rounded-2xl bg-[#f5f8fc] px-3.5 py-2.5">
<i className="size-3 shrink-0 rounded-full" style={{ background: colorOf(w.label) }} aria-hidden="true" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[16px] leading-tight font-normal">
{w.label} <small className="font-sans text-[12px] font-bold text-(--ink3)">비중 {w.weight}%</small>
</b>
<small className="block text-[13px] font-semibold text-(--ink2)">{w.note}</small>
</span>
<b className="font-jua text-[20px] font-normal tabular-nums">{w.score}</b>
</li>
))}
</ul>
<p className="m-0 mt-3 text-[13px] leading-relaxed font-semibold text-(--ink2)">
조건마다 점수를 매겨 비중대로 합쳐요. 유난히 아쉬운 조건이 있으면 조금 더 깎고, 모든 조건이 완벽할 때만 만점이 나와요.
</p>
</div>
)
}