Merge remote-tracking branch 'origin/main' into feat/apps-in-toss

# Conflicts:
#	frontend/src/b/BLayout.tsx
#	frontend/src/b/Shorts.tsx
#	frontend/src/b/talk.tsx
This commit is contained in:
minaChoi committed 2026-10-27 19:08:51 +09:00
commit 4875ea4333
101 files changed
+3533 -502

No files matched your search

+20
View File
@@ -527,6 +527,26 @@
"basis": "가장 가까운 산림청 예측 지점(수리산, 은행나무) 날짜",
"coord_point": "서울숲"
},
{
"name": "어린이대공원",
"kind": "maple",
"region": "서울 광진",
"lat": 37.5493,
"lon": 127.07626,
"peak": "2026-11-02",
"basis": "가장 가까운 산림청 예측 지점(수리산, 단풍나무류) 날짜",
"coord_point": "서울어린이대공원"
},
{
"name": "경복궁",
"kind": "maple",
"region": "서울 종로",
"lat": 37.57603,
"lon": 126.97672,
"peak": "2026-11-02",
"basis": "가장 가까운 산림청 예측 지점(수리산, 단풍나무류) 날짜",
"coord_point": "경복궁"
},
{
"name": "덕수궁 돌담길",
"kind": "ginkgo",
+13 -3
View File
@@ -1,13 +1,14 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
import { useIsFetching, useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { useIsFetching, useQuery, useQueryClient } from '@tanstack/react-query'
import { authConfigOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { cx } from '../lib/utils'
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
import './b.css'
import { AuthProvider } from './auth'
import { RegionProvider } from './region'
import { useAuth } from './authContext'
import { preloadGoogle } from './googleScript'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { SheetProvider } from './Sheets'
@@ -46,7 +47,16 @@ function TopBar() {
const { region, locateStatus } = useRegion()
const { open } = useSheet()
const { me, mePending } = useAuth()
const queryClient = useQueryClient()
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
const loggedOut = !mePending && !me
// 로그인 창을 처음 열 때 버벅이지 않게 구글 로그인 준비물을 미리 받아 둔다
useEffect(() => {
if (!loggedOut) return
void queryClient.prefetchQuery({ ...authConfigOptions(), staleTime: Infinity })
return preloadGoogle()
}, [loggedOut, queryClient])
return (
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
@@ -253,7 +263,7 @@ function Shell() {
{/* 위·아래 바: 띠는 화면 끝까지, 내용은 가운데 440px 안 */}
<div className="b-topbg fixed inset-x-0 top-0 z-[19] h-[calc(54px+env(safe-area-inset-top,0px))] backdrop-blur-md" aria-hidden="true" />
<div className="fixed inset-x-0 top-0 z-[19] h-[env(safe-area-inset-top,0px)] transition-colors duration-1400" style={{ backgroundColor: NOTCH_BG[kind] }} aria-hidden="true" />
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(70px+env(safe-area-inset-bottom,0px))]">
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip pb-[calc(104px+env(safe-area-inset-bottom,0px))]">
<TopBar />
<main className="relative z-[1]">
<Outlet />
+8 -4
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, STAGE, headline, md, placeLabels, spread, useFoliage, useLabelSize, type Box, type Kind, type Pt, type Spot, type Stage } from './foliage'
import { ICON_R, LABEL, LABEL_INK, LAND_CX, LEAF_SHADOW, MAP_IMG, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, STAGE, headline, md, placeLabels, spread, useFoliage, useLabelSize, type Box, type Kind, type Pt, type Spot, type Stage } from './foliage'
import { useSheet } from './sheetContext'
import { FoliageMapShare, FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
@@ -52,7 +52,7 @@ function Marker({ p, sel }: { p: Pt; sel: boolean }) {
)
}
/** 단풍 지도 페이지: 명소 65곳을 지도에서 확대해 보고 목록으로 고른다. 한 손가락은 확대 전엔 페이지 스크롤, 확대 뒤엔 지도 이동 */
/** 단풍 지도 페이지: 명소 67곳을 지도에서 확대해 보고 목록으로 고른다. 한 손가락은 확대 전엔 페이지 스크롤, 확대 뒤엔 지도 이동 */
export function FoliagePage() {
const navigate = useNavigate()
const [params] = useSearchParams()
@@ -85,8 +85,10 @@ export function FoliagePage() {
const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)]
// 위쪽은 맨 북쪽 이름표가 잘리지 않게 FIT_TOP 만큼 띄우고, 아래는 제주까지만
const h = H - FIT_TOP - FIT_BOTTOM
const s = Math.min(W / ((x1 - x0 + 0.14) * W), h / ((y1 - y0) * W))
return { s, tx: W / 2 - ((x0 + x1) / 2) * W * s, ty: FIT_TOP + h / 2 - ((y0 + y1) / 2) * W * s }
// 가로는 땅 가운데(LAND_CX)에 맞추되 동·서 끝 명소가 다 들어오게
const half = Math.max(LAND_CX - x0, x1 - LAND_CX) + 0.07
const s = Math.min(W / (2 * half * W), h / ((y1 - y0) * W))
return { s, tx: W / 2 - LAND_CX * W * s, ty: FIT_TOP + h / 2 - ((y0 + y1) / 2) * W * s }
}, [box, spots])
const clamp = useCallback(
@@ -289,6 +291,8 @@ export function FoliagePage() {
drag = null
}
const onDbl = (e: MouseEvent) => {
// +/− 를 빨리 두 번 누른 건 확대로 치지 않는다
if ((e.target as HTMLElement).closest('button')) return
const p = local(e)
zoomAt(2, p.x, p.y, true)
}
+50 -18
View File
@@ -13,6 +13,7 @@ import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { useSheet } from './sheetContext'
import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { useCarousel } from './carousel'
import { MoonArt } from './moon'
import { Arrows, Credit, Ic, Rows, Skel, TAP44, Thumb } from './ui'
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
@@ -52,7 +53,8 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter'
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length]
if (slide.kind === 'image') return 'sky'
if (post.post_type === PostType.EVENT) return 'night'
if (post.post_type === PostType.MOON) return 'night'
if (post.post_type === PostType.EVENT) return slide.image ? 'night' : 'peach'
if (post.post_type === PostType.TIP) return 'sky'
if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac'
if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint'
@@ -62,18 +64,16 @@ 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
const BG_IMAGES: Record<string, number> = { bike: 4, picnic: 1, hiking: 1, hangang: 1 }
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
}
@@ -104,6 +104,27 @@ function Pic({ name, className }: { name: string; className?: string }) {
const slideBase = 'relative flex h-full w-full shrink-0 flex-col px-5 py-[22px]'
// 달 포스트 밤하늘 별: [left %, top %, 크기 px]
const STARS: [number, number, number][] = [
[8, 34, 2], [18, 52, 1.5], [30, 40, 2.5], [44, 30, 1.5], [52, 58, 2], [62, 22, 1.5], [90, 18, 2], [94, 44, 1.5], [12, 70, 1.5], [38, 66, 2], [76, 74, 1.5], [86, 64, 2], [24, 12, 1.5], [70, 10, 2.5],
]
/** 달 포스트 그림: 아이콘 대신 오늘 밤 실제 모양의 달과 별 */
function MoonPic({ pct, waxing }: { pct: number; waxing: boolean }) {
return (
<>
<span className="pointer-events-none absolute inset-0 -z-10" aria-hidden="true">
{STARS.map(([x, y, s]) => (
<i key={`${x},${y}`} className="absolute rounded-full bg-white opacity-80 shadow-[0_0_6px_rgb(255_255_255/0.8)]" style={{ left: `${x}%`, top: `${y}%`, width: s, height: s }} />
))}
</span>
<span className="b-fall pointer-events-none absolute top-[22%] right-0 w-[60%]" style={fall('.1s', '5s')}>
<MoonArt pct={pct} waxing={waxing} className="b-bob w-full" />
</span>
</>
)
}
function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
const { open } = useSheet()
if (slide.kind === 'hours') {
@@ -142,17 +163,28 @@ function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSPro
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
<Big>{slide.line}</Big>
<Pic name={slide.code} />
<Pic name={slide.code} className="[@media(max-height:700px)]:top-[26%] [@media(max-height:700px)]:w-[34%]" />
{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 className="relative z-[1] mt-auto flex items-end justify-between gap-3">
<div>
<b className="block font-bagel text-[82px] leading-[0.9] font-normal text-(--orange) [@media(max-height:700px)]:text-[64px]">{slide.score}</b>
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
</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>
{!!slide.trend?.length && (
<div className="grid w-[46%] grid-cols-2 gap-1.5">
{slide.trend.map((t) => (
<div key={t.day} className="rounded-xl bg-white/80 px-1 py-1.5 text-center">
<small className="block text-[11px] font-extrabold whitespace-nowrap text-(--ink2)">
{t.label}
{t.estimated && ' 예상'}
</small>
<b className="block font-bagel text-lg leading-tight font-normal text-(--orange)">{t.score}</b>
</div>
))}
</div>
)}
</div>
<button type="button" onClick={() => open({ type: 'gak', indexId: slide.index_id })} className="mt-3 cursor-pointer self-start rounded-full bg-(--orange) px-4 py-[9px] font-jua text-[15px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)]">
계산 근거 보기
</button>
@@ -258,12 +290,12 @@ function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSPro
</div>
)
return (
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
<div className={cx(slideBase, `b-bg-${bg}`, slide.moon_pct != null && 'isolate')} style={img}>
<Eyebrow className={DARK.has(bg) ? 'opacity-85' : undefined}>{slide.eyebrow}</Eyebrow>
<Big className="relative z-[1]">
<Lines text={slide.line} />
</Big>
<Pic name={slide.icon} className="w-[36%]" />
{slide.moon_pct != null ? <MoonPic pct={slide.moon_pct} waxing={!!slide.moon_waxing} /> : <Pic name={slide.icon} className="w-[36%]" />}
<Rows rows={slide.rows ?? []} dark={DARK.has(bg)} />
</div>
)
@@ -416,7 +448,7 @@ function FullCard({ post }: PostProps) {
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span>
</div>
<div className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
<div className="b-day relative aspect-[4/5] overflow-hidden" onClick={onTap}>
{n > 1 && (
<span data-noshot className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white" aria-hidden="true">
{index + 1}/{n}
@@ -526,7 +558,7 @@ export function PostFrame({ title, account, avatar, caption, more, shot, pinned,
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
</span>
</div>
<div ref={bodyRef}>{children}</div>
<div ref={bodyRef} className="b-day">{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 && (
<>
+52 -27
View File
@@ -35,8 +35,8 @@ import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf,
import { GoogleButton } from './googleLogin'
import { useInstall, useInstallable } from './install'
import { InstallSheet } from './installBanner'
import { ARTICLE_CAT } from './lib'
import { MixSheet } from './myGak'
import { ARTICLE_CAT, SHEET_CLOSE_MS, SHEET_OPEN_MS } from './lib'
import { MixSheet, MyGakSheet } from './myGak'
import { ownPage, useRegion } from './regionContext'
import { WeatherWhySheet } from './weatherWhy'
import { useSky } from './skyContext'
@@ -96,11 +96,25 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const [gakTitle, setGakTitle] = useState('')
const [articleTitle, setArticleTitle] = useState('')
// 닫히는 동안에도 내려가는 창에 내용이 남아 있게, 마지막으로 연 창을 들고 있는다
const [shown, setShown] = useState<SheetState>(state)
if (state && state !== shown) setShown(state)
const closing = !state && shown != null
useEffect(() => {
const el = ref.current
if (!el) return
if (state && !el.open) el.showModal()
if (!state && el.open) el.close()
if (state) {
if (!el.open) el.showModal()
return
}
if (!el.open) return
// 내려가는 애니메이션이 끝난 뒤에 실제로 닫는다
const t = setTimeout(() => {
el.close()
setShown(null)
}, SHEET_CLOSE_MS)
return () => clearTimeout(t)
}, [state])
// 창이 열려 있는 동안 뒤 페이지는 스크롤되지 않게 잠근다
@@ -110,15 +124,17 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const root = document.documentElement
const before = root.style.overflow
root.style.overflow = 'hidden'
root.classList.add('b-sheet-open')
// 뒤 화면 움직임 멈추기는 페이지 전체 스타일을 다시 계산하게 해서, 창이 다 올라온 뒤에 한다
const pause = setTimeout(() => root.classList.add('b-sheet-open'), SHEET_OPEN_MS)
return () => {
clearTimeout(pause)
root.style.overflow = before
root.classList.remove('b-sheet-open')
}
}, [isOpen])
const then = state?.type === 'login' ? state.then : undefined
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type]
const then = shown?.type === 'login' ? shown.then : undefined
const title = !shown ? '' : shown.type === 'gak' ? gakTitle : shown.type === 'article' ? articleTitle || TITLES.article : shown.type === 'mix' ? (shown.shared ? '받은 각' : '내 각 만들기') : shown.type === 'myGak' ? '내 각' : TITLES[shown.type]
return (
<dialog
@@ -126,12 +142,17 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
aria-label={title}
data-t={kind}
onClose={onClose}
// ESC 도 바로 닫지 않고 내려가며 닫히게
onCancel={(e) => {
e.preventDefault()
onClose()
}}
onClick={(e) => {
if (e.target === e.currentTarget) onClose()
}}
className="b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)"
className={cx('b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)', closing && 'b-sheet-closing')}
>
{state && (
{shown && (
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white pb-[env(safe-area-inset-bottom,0px)]">
<div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center">
<div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-(--line)" aria-hidden="true" />
@@ -140,21 +161,22 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
×
</button>
</div>
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
{state.type === 'share' && <ShareSheet share={state.share} />}
{state.type === 'comments' && <CommentsSheet postId={state.postId} draft={state.draft} />}
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />}
{state.type === 'install' && <InstallSheet />}
{state.type === 'weatherWhy' && <WeatherWhySheet d={state.why} />}
{state.type === 'talk' && <TalkSheet talk={state.talk} />}
{shown.type === 'gak' && <GakSheet indexId={shown.indexId} onTitle={setGakTitle} />}
{shown.type === 'article' && <ArticleSheet articleId={shown.articleId} onTitle={setArticleTitle} />}
{shown.type === 'seasonWeek' && <SeasonWeekSheet />}
{shown.type === 'share' && <ShareSheet share={shown.share} />}
{shown.type === 'comments' && <CommentsSheet postId={shown.postId} draft={shown.draft} />}
{shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{shown.type === 'me' && <MeSheet onDone={onClose} />}
{shown.type === 'region' && <RegionSheet onDone={onClose} />}
{shown.type === 'mix' && <MixSheet shared={shown.shared} onDone={onClose} />}
{shown.type === 'myGak' && <MyGakSheet gak={shown.gak} shot={shown.shot} onDone={onClose} />}
{shown.type === 'install' && <InstallSheet />}
{shown.type === 'weatherWhy' && <WeatherWhySheet d={shown.why} />}
{shown.type === 'talk' && <TalkSheet talk={shown.talk} />}
</div>
)}
{!state && <RegionLinks />}
{!shown && <RegionLinks />}
</dialog>
)
}
@@ -540,6 +562,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
const [toast, setToast] = useState('')
const image = images[size]
const text = `${share.title} · 날씨각`
const url = share.url ?? SITE_URL
// 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다
useEffect(() => {
@@ -585,15 +608,15 @@ function ShareSheet({ share }: { share: SharePayload }) {
)
return
}
if (navigator.canShare?.({ files: [file], text, url: SITE_URL })) {
const copied = navigator.clipboard?.writeText(SITE_URL).then(
if (navigator.canShare?.({ files: [file], text, url })) {
const copied = navigator.clipboard?.writeText(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(
navigator.share({ files: [file], title: share.title, text, url }).then(
async () => {
setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요')
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
@@ -615,7 +638,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
setToast('이미지를 내려받았어요')
return
}
navigator.clipboard.writeText(`${text} ${SITE_URL}`).then(
navigator.clipboard.writeText(`${text} ${url}`).then(
() => setToast('이미지를 내려받고 링크를 복사했어요'),
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
)
@@ -802,6 +825,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
<div>
<p className="m-0 text-sm">
<b className="mr-1.5 font-extrabold">{c.nickname}</b>
{c.official && <span className="mr-1.5 inline-block -translate-y-px rounded-md bg-(--orange) px-1.5 py-px align-middle text-[10.5px] font-extrabold text-white">날씨각</span>}
{c.body}
</p>
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
@@ -814,7 +838,8 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
</button>
</>
)}
{!c.mine && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
{/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
{!c.mine && !c.official && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
</small>
</div>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className={cx('relative cursor-pointer pt-1', TAP44)}>
+13 -5
View File
@@ -5,6 +5,7 @@ import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-
import type { ShortItem } from '@nalssigak/shared/api/client'
import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils'
import { CloseIcon } from './svg'
import { Rail, Skel, SkelRail, TAP44 } from './ui'
// 유튜브는 플레이어가 200×200 이상이어야 해서, 카드 안 미리보기는 200px 너비로 띄우고 줄여 보인다.
@@ -16,13 +17,18 @@ const SCALE = (CARD_W / PLAYER_W) * 1.4
// 쇼츠 페이지의 영상 칸: 위 헤더(54px)·버튼 줄(48px)과 아래 탭 바(--shorts-tab) 사이 높이와 화면 너비 안에 9:16으로 맞춘다
const FIT = { width: 'min(100vw, calc((100dvh - env(safe-area-inset-top, 0px) - 54px - 48px - var(--shorts-tab, 0px)) * 9 / 16))', aspectRatio: '9 / 16' }
/** 아래 탭 바 높이 (기기마다 안전 영역이 달라 실제로 잰다) */
/** 아래 탭 바가 가리는 높이: 탭 바 위로 솟은 가운데 홈 동그라미까지 (기기마다 안전 영역이 달라 실제로 잰다) */
function useTabBarHeight() {
const [h, setH] = useState(0)
useLayoutEffect(() => {
const nav = document.querySelector<HTMLElement>('nav.b-tabbar')
if (!nav) return
const ro = new ResizeObserver(() => setH(nav.offsetHeight))
const measure = () => {
const bar = nav.getBoundingClientRect()
const bump = nav.querySelector('.b-tab-main > *')?.getBoundingClientRect().top ?? bar.top
setH(Math.round(bar.bottom - Math.min(bar.top, bump)))
}
const ro = new ResizeObserver(measure)
ro.observe(nav)
return () => ro.disconnect()
}, [])
@@ -92,7 +98,8 @@ export function ShortsRail() {
<section ref={ref} aria-label="날씨각 쇼츠">
<Rail label="쇼츠 목록">
{items.map((s, i) => (
<ShortCard key={s.id} s={s} playing={i === 0 && visible} />
// 토스 앱 웹뷰는 유튜브 플레이어가 무거워, 줄에선 표지만 보이고 누르면 재생
<ShortCard key={s.id} s={s} playing={!IS_TOSS && i === 0 && visible} />
))}
</Rail>
</section>
@@ -299,8 +306,9 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
/>
<div className="absolute inset-0 bg-black/35" aria-hidden="true" />
<div className="relative mx-auto flex h-12 w-full max-w-[440px] shrink-0 items-center justify-between px-3">
<button type="button" onClick={onClose} aria-label="닫기" className={cx('relative grid size-9 cursor-pointer place-items-center rounded-full bg-white/15 text-xl text-white', TAP44)}>
×
{/* 글자 '×'는 글꼴마다 아래로 처져 그림으로 */}
<button type="button" onClick={onClose} aria-label="닫기" className={cx('relative grid size-9 cursor-pointer place-items-center rounded-full bg-white/15 text-white', TAP44)}>
<CloseIcon className="size-[18px]" />
</button>
{PLAIN ? (
<div className="flex gap-2">
+58 -26
View File
@@ -1,44 +1,76 @@
import { useEffect, useEffectEvent, useRef } from 'react'
import { useSearchParams } from 'react-router'
import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { TalkCard } from './talk'
import { TOPICS, useTopicTalks } from './talkState'
import { Sec } from './ui'
import { useAuth } from './authContext'
import { useSheet } from './sheetContext'
import { FeedComposer, TalkCard } from './talk'
import { TOPICS, useMyTalks, useTopicTalks } from './talkState'
import { Rail, Sec } from './ui'
/** 주제별 사람 글: 위 주제 탭, 아래 글 목록. 피드 묶음의 '전체 보기'가 ?topic= 으로 연다 */
type Tab = TalkTopic | 'all' | 'mine'
/** 목록 끝이 화면 아래 600px 안에 들어오면 다음 쪽을 받는다 (글이 많아도 버튼 없이 이어서) */
function MoreOnScroll({ onMore }: { onMore: () => void }) {
const ref = useRef<HTMLDivElement>(null)
const more = useEffectEvent(onMore)
useEffect(() => {
const el = ref.current
if (!el) return
const io = new IntersectionObserver(([e]) => e.isIntersecting && more(), { rootMargin: '0px 0px 600px 0px' })
io.observe(el)
return () => io.disconnect()
}, [])
return <div ref={ref} className="h-px" aria-hidden="true" />
}
/** 주제별 사람 글: 위 주제 탭(한 줄 가로로 밀기, 끝에 '내 글'), 아래 글 목록. 피드 묶음의 '전체 보기'가 ?topic= · ?mine=1 로 연다 */
export function TalkPage() {
const [params, setParams] = useSearchParams()
const { loggedIn } = useAuth()
const { open } = useSheet()
const raw = Number(params.get('topic'))
const topic = TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : undefined
const { talks, loaded, more, loadMore } = useTopicTalks(topic)
const tabs: (readonly [TalkTopic | undefined, string])[] = [[undefined, '전체'], ...TOPICS]
const tab: Tab = params.get('mine') ? 'mine' : TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : 'all'
const topicList = useTopicTalks(tab === 'all' || tab === 'mine' ? undefined : tab)
const mineList = useMyTalks(tab === 'mine' && loggedIn)
const { talks, loaded, more, loadMore } = tab === 'mine' ? mineList : topicList
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...TOPICS, ['mine', '내 글']]
const go = (k: Tab) => setParams(k === 'mine' ? { mine: '1' } : k === 'all' ? {} : { topic: String(k) }, { replace: true })
return (
<section aria-label="동네 사람들 글">
<Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" />
<div className="flex flex-wrap gap-1.5 px-4 pb-1" role="tablist" aria-label="글 주제">
{tabs.map(([k, label]) => (
<button
key={label}
type="button"
role="tab"
aria-selected={topic === k}
onClick={() => setParams(k ? { topic: String(k) } : {}, { replace: true })}
className={cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold', topic === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2)')}
>
{label}
</button>
))}
<div role="tablist" aria-label="글 주제">
<Rail className="gap-1.5 pt-0">
{tabs.map(([k, label]) => (
<button
key={label}
type="button"
role="tab"
aria-selected={tab === k}
onClick={() => go(k)}
className={cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold whitespace-nowrap', tab === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2)')}
>
{label}
</button>
))}
</Rail>
</div>
{loaded && !talks.length && <p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">아직 이 주제 글이 없어요. 오늘 탭에서 첫 글을 써 주세요.</p>}
<FeedComposer />
{tab === 'mine' && !loggedIn ? (
<p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">
로그인하면 내가 쓴 글을 모아 볼 수 있어요.{' '}
<button type="button" onClick={() => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--orange)">
로그인
</button>
</p>
) : (
loaded && !talks.length && <p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">{tab === 'mine' ? '아직 쓴 글이 없어요. 위 칸에서 첫 글을 써 주세요.' : '아직 이 주제 글이 없어요. 위 칸에서 첫 글을 써 주세요.'}</p>
)}
{talks.map((t) => (
<TalkCard key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
))}
{more && (
<button type="button" onClick={() => loadMore()} className="mx-3 mt-3 w-[calc(100%-1.5rem)] cursor-pointer rounded-[14px] bg-white py-2.5 text-[13.5px] font-extrabold text-(--ink2)">
더 보기
</button>
)}
{more && <MoreOnScroll onMore={() => loadMore()} />}
</section>
)
}
+50 -52
View File
@@ -12,22 +12,23 @@ import {
type Hero as HeroData,
type PostReaction,
type ResWeatherToday,
type TalkData,
type TopIndex,
type WeatherSlot,
} from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
import { fall } from './lib'
import { useAuth } from './authContext'
import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner'
import { MoonArt } from './moon'
import { MyGakRow } from './myGak'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike, type PinnedKey } from './pinnedLike'
import { usePinnedLike } from './pinnedLike'
import { ShortsRail } from './Shorts'
import { FeedComposer, NearTalks, TalkCard, TalkGroup } from './talk'
import { topicName, useTalkGroups } from './talkState'
import { FeedComposer, NearTalks, TalkGroup } from './talk'
import { topicName, useTalkGroups, useTodayMyTalks } from './talkState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { useSky } from './skyContext'
@@ -158,8 +159,8 @@ const WEATHER_ICON: Record<Weather, string> = {
sleet: 'snow',
}
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋
// 히어로 오른쪽 위 좋아요·댓글·보내기: 셋 다 같은 32px 칸에 아이콘 가운데, 수는 아이콘 옆
const HERO_ACT = 'relative flex h-8 min-w-8 cursor-pointer items-center justify-center gap-1 text-[13px] font-extrabold'
// 히어로 오른쪽 위 좋아요·댓글·보내기: 아이콘마다 좌우 여백을 같게, 숫자가 붙어도 아이콘 사이 간격이 그대로
const HERO_ACT = 'relative flex h-8 cursor-pointer items-center justify-center gap-1 px-[5px] text-[13px] leading-none font-extrabold tabular-nums'
const CLOUDS = [
{ cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' },
{ cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' },
@@ -210,6 +211,10 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
const kind = mode === 'now' ? nowKind : mode
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind])
// 내일을 볼 땐 배경·글자색도 내일 고른 칸을 따른다 (오늘 밤을 고른 채 내일 낮을 보면 낮 하늘에 흰 글자가 되던 것)
useEffect(() => {
if (tmr) setPreview(tmrKind)
}, [tmr, tmrKind, setPreview])
const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? []
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad
// 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
@@ -242,13 +247,14 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
waning: WANING.includes(hero.moon_name),
}
: null
// 말풍선 머리말은 칸 이름 그대로: 지금은 / 아침은 / 낮은 / 저녁은 / 밤은
const when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label
// 말풍선 머리말: 지금은 / 오늘 낮은 / 내일은 / 내일 낮은 (어느 날 어느 칸인지 같이)
const when = mode === 'now' || mode === nowKind ? '지금' : `오늘 ${PREVIEW[mode].label}`
const tmrWhen = mode === 'now' ? '내일' : `내일 ${PREVIEW[mode].label}`
const bubble = tmr
? top1
? top1.score >= 70
? `내일은 ${top1.name}!`
: '내일은 쉬어 가요'
? `${tmrWhen}은 ${top1.name}!`
: `${tmrWhen}은 쉬어 가요`
: null
: slotTop
? slotTop.score >= 70
@@ -325,7 +331,11 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
type="button"
role="radio"
aria-checked={tmr === v}
onClick={() => setTmr(v)}
onClick={() => {
// 내일로 넘어갈 땐 지금 보던 시간대 그대로 시작해 배경이 튀지 않게
if (v && !tmr) setTmrKind(kind)
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}
@@ -372,13 +382,9 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
</span>
))}
<div className={'b-fall absolute top-2 left-1/2 -ml-16 aspect-square w-32'} style={fall('0s', '5.6s')}>
<div className="b-sun b-bob relative grid size-full place-items-center rounded-full text-center">
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
{moon && (
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
<path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} />
</svg>
)}
<div className={cx('b-sun b-bob relative grid size-full place-items-center rounded-full text-center', moon && 'b-moon')}>
{/* 오늘 밤 실제 모양의 달 (빛 번짐까지 그려서 공보다 크게) */}
{moon && <MoonArt pct={moon.pct} waxing={!moon.waning} tone={kind === 'sunset' ? 'dusk' : 'night'} className="pointer-events-none absolute -top-1/4 -left-1/4 size-[150%] max-w-none" />}
{/* 점수 근거가 있으면 해를 눌러도 근거 창: 구석 버튼은 구름에 가려져서 상태 줄 끝으로 옮김 */}
{(() => {
const body = (
@@ -389,7 +395,8 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
</>
)
const cls = cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')
// 가운데가 밝은 달이면 진한 글씨에 흰 번짐, 가운데가 어두운 달(초승·그믐)이면 흰 글씨
const cls = cx('relative', moon && (moon.pct >= 50 ? '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]' : 'text-white [text-shadow:0_1px_8px_rgb(10_14_40/0.6)]'))
if (!why || score == null) return <span className={cls}>{body}</span>
return (
<button
@@ -470,16 +477,6 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
const WANING = ['기우는 달', '하현달', '그믐달']
/**
* 반지름 r 인 달에서 밝은 쪽(lit) 또는 어두운 쪽 경로. 차오르는 달 기준(오른쪽이 밝음), 기우는 달은 좌우를 뒤집어 쓴다.
* 바깥 반원과 명암 경계(가로 반지름 r·|1-2k| 인 타원 호)로 이루어진다.
*/
function moonPath(pct: number, r: number, lit: boolean) {
const k = pct / 100
const edge = `A${r * Math.abs(1 - 2 * k)},${r} 0 0 ${k < 0.5 ? 0 : 1} 0,${-r}`
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
}
function GakCard({ items, post, place, at }: { items: TopIndex[]; post?: PostReaction | null; place: string; at: string }) {
const { open } = useSheet()
const tplRef = useRef<HTMLDivElement>(null)
@@ -528,21 +525,18 @@ function PostsSkel() {
)
}
/** 띠도 포스트 틀에 담아 좋아요·댓글·보내기를 단다 (post 는 서버의 띠 자리) */
function Band({ tone, title, sub, to, avatar, post, pinKey, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; avatar: string; post?: PostReaction | null; pinKey: PinnedKey; children: ReactNode }) {
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
return (
<PostFrame title={title} account={title} avatar={avatar} pinned={{ key: pinKey, post }}>
<section className={cx('pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
<Sec title={title} sub={sub} more={{ to }} className="pt-0" />
{children}
</section>
</PostFrame>
<section className={cx('mt-3.5 pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
<Sec title={title} sub={sub} more={{ to }} className="pt-0" />
{children}
</section>
)
}
function EventsBand({ events, post }: { events: BandEvent[]; post?: PostReaction | null }) {
function EventsBand({ events }: { events: BandEvent[] }) {
return (
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week" avatar="fireworks" post={post} pinKey="events_post">
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week">
<Rail>
{events.map((e, i) => (
<Link key={e.event_id} to="/week" className="w-[200px] overflow-hidden rounded-[22px] bg-white shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
@@ -559,10 +553,10 @@ function EventsBand({ events, post }: { events: BandEvent[]; post?: PostReaction
)
}
function SeasonBand({ news, post }: { news: BandArticle[]; post?: PostReaction | null }) {
function SeasonBand({ news }: { news: BandArticle[] }) {
const { open } = useSheet()
return (
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season" avatar="fallen_leaf" post={post} pinKey="season_post">
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season">
<Rail>
{news.map((a) => (
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="w-[200px] cursor-pointer overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
@@ -591,8 +585,9 @@ export function TodayPage() {
const bands = f?.bands
const nowAt = f?.hero?.now_at
const load = loadOf(feed)
const [mine, setMine] = useState<TalkData[]>([])
// 사람 글은 묶음으로: '동네 사람들'은 오늘의 각 아래, 주제 묶음은 같은 주제 포스트 아래. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고
// 사람 글은 묶음으로: '동네 사람들'은 오늘의 각 아래, 주제 묶음은 같은 주제 포스트 아래. 오늘 쓴 내 글은 글쓰기 칸 아래 '오늘 내 글'에 따로 있으니 빼고
const { loggedIn } = useAuth()
const mine = useTodayMyTalks(loggedIn)
const talkGroups = useTalkGroups()
const groupOf = (topic: number) => (talkGroups.groups.get(topic) ?? []).filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
const group = (topic: number) => {
@@ -622,12 +617,12 @@ export function TodayPage() {
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} post={f?.events_post} /> : null],
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} post={f?.season_post} /> : null],
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
]
// 사람 글 묶음은 포스트 사이사이에 하나씩: 묶음·띠·단풍 카드가 이미 붙는 자리와 바로 앞 자리는 건너뛰어 가로 목록이 연달아 나오지 않게
const spreadTopics = [TalkTopic.OUTFIT, ...(raining ? [] : [TalkTopic.RAIN]), ...(sunsetAt < 0 ? [TalkTopic.SKY] : []), ...(posts.length < 2 ? [TalkTopic.FOLIAGE] : [])].filter((tp) => groupOf(tp).length)
const spreadTopics = [TalkTopic.OUTFIT, ...(raining ? [] : [TalkTopic.RAIN]), ...(sunsetAt < 0 ? [TalkTopic.SKY] : [])].filter((tp) => groupOf(tp).length)
const taken = new Set([1, sunsetAt, ...bandAt.map(([at]) => at - 1)])
const spreadAt = new Map<number, ReactNode>()
let spreadN = 0
@@ -642,10 +637,8 @@ export function TodayPage() {
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} />
<ShortsRail />
<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))} />
))}
<FeedComposer />
{mine.length > 0 && <TalkGroup title="오늘 내 글" talks={mine} href="/talk?mine=1" />}
{raining && group(TalkTopic.RAIN)}
<MyGakRow />
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
@@ -664,12 +657,17 @@ export function TodayPage() {
{load !== 'loading' && !posts.length && (
<StateBox load="ready" empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'} hold={<PostsSkel />} className="inset-x-3 top-3.5 bottom-auto" />
)}
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에, 단풍 이야기 묶음은 바로 아래 */}
{load !== 'loading' && posts.length > 0 && (
<>
<FoliageCard />
{group(TalkTopic.FOLIAGE)}
</>
)}
{posts.map((p, i) => (
<Fragment key={p.post_id}>
<PostCard post={p} />
{i === sunsetAt && group(TalkTopic.SKY)}
{i === 1 && <FoliageCard post={f?.foliage_post} />}
{i === 1 && group(TalkTopic.FOLIAGE)}
{bandAt.find(([at]) => at === i + 1)?.[1]}
{spreadAt.get(i)}
</Fragment>
+72 -27
View File
@@ -2,7 +2,7 @@
.b-app {
--ink: #28304a;
--ink2: #5a6380;
--ink3: #8a92aa;
--ink3: #6b738c;
--line: #e6ecf4;
--page: #f7fbff;
--outer: #dfeaf6;
@@ -120,13 +120,37 @@
}
}
/* 아래 창은 불투명한 채로 화면 아래에서 끝까지 올라오고, 닫힐 땐 다시 내려간다 (반투명으로 올라오면 뒤 탭 바가 비쳐 깜빡여 보였다) */
.b-sheet {
animation: b-up 0.26s cubic-bezier(0.2, 0.9, 0.3, 1);
animation: b-up 0.28s cubic-bezier(0.2, 0.9, 0.3, 1);
}
.b-sheet-dialog[open]::backdrop {
animation: b-fade-in 0.2s ease-out;
}
.b-sheet-closing .b-sheet {
animation: b-down 0.2s ease-in forwards;
}
.b-sheet-closing::backdrop {
animation: b-fade-out 0.2s ease-in forwards;
}
@keyframes b-up {
from {
transform: translateY(40px);
opacity: 0.4;
transform: translateY(100%);
}
}
@keyframes b-down {
to {
transform: translateY(100%);
}
}
@keyframes b-fade-in {
from {
opacity: 0;
}
}
@keyframes b-fade-out {
to {
opacity: 0;
}
}
@@ -150,11 +174,13 @@
.b-fall,
.b-heart-pop,
.b-like-bit,
.b-sheet {
.b-sheet,
.b-sheet-dialog[open]::backdrop {
animation: none !important;
}
.b-heart-pop,
.b-like-bit {
.b-like-bit,
.b-sheet-closing .b-sheet {
opacity: 0;
}
}
@@ -287,6 +313,11 @@
inset 16px 18px 28px rgb(255 255 255 / 0.6),
0 0 60px rgb(190 180 255 / 0.45);
}
/* 달 그림(MoonArt)이 빛까지 그리므로 공 바탕·그림자는 뺀다 */
.b-hero .b-sun.b-moon {
background: none;
box-shadow: none;
}
.b-cloud {
position: absolute;
@@ -589,72 +620,86 @@ html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot,
.b-app[data-t='night'] .b-tabbar {
--ink: #fff;
}
.b-app[data-t='night'] .bg-white {
.b-app[data-t='night'] .bg-white:not(.b-day, .b-day *) {
background-color: var(--card);
}
.b-app[data-t='night'] [class*='bg-white/'] {
.b-app[data-t='night'] [class*='bg-white/']:not(.b-day, .b-day *) {
background-color: rgb(34 42 92 / 0.85);
}
.b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']):not(.b-keep-bg) {
.b-app[data-t='night'] :is([class*='bg-[#f'], [class*='bg-[#e'], [class*='bg-[#d'], [class*='bg-[#c'], [class*='bg-[linear-gradient']):not(.b-keep-bg, .b-day, .b-day *) {
background: var(--chip);
}
.b-app[data-t='night'] [class*='border-[#dfe5ee]'] {
.b-app[data-t='night'] [class*='border-[#dfe5ee]']:not(.b-day, .b-day *) {
border-color: rgb(255 255 255 / 0.12);
}
.b-app[data-t='night'] [class*='rgb(217_229_244'] {
.b-app[data-t='night'] [class*='rgb(217_229_244']:not(.b-day, .b-day *) {
box-shadow: inset 0 -5px 0 var(--shade);
}
.b-app[data-t='night'] .bg-\(--ink\) {
.b-app[data-t='night'] .bg-\(--ink\):not(.b-day, .b-day *) {
background-color: #4b56b5;
color: #fff;
}
.b-app[data-t='night'] .bg-\(--ink\) .text-\[\#ffb3c4\] {
.b-app[data-t='night'] .bg-\(--ink\) .text-\[\#ffb3c4\]:not(.b-day, .b-day *) {
color: #ffd0dc;
}
/* b-keep-bg(밤에도 밝은 바탕 그대로) 안은 글자도 그대로 */
.b-app[data-t='night'] .text-\[\#28304a\]:not(.b-keep-bg, .b-keep-bg *) {
.b-app[data-t='night'] .text-\[\#28304a\]:not(.b-keep-bg, .b-keep-bg *, .b-day, .b-day *) {
color: var(--ink);
}
.b-app[data-t='night'] :is(.text-\[\#1f9d62\], .text-\[\#1f7a4f\]) {
.b-app[data-t='night'] :is(.text-\[\#1f9d62\], .text-\[\#1f7a4f\]):not(.b-day, .b-day *) {
color: #4fd39a;
}
.b-app[data-t='night'] .text-\[\#d6457a\] {
.b-app[data-t='night'] .text-\[\#d6457a\]:not(.b-day, .b-day *) {
color: #ff8db5;
}
.b-app[data-t='night'] .text-\[\#c2471b\] {
.b-app[data-t='night'] .text-\[\#c2471b\]:not(.b-day, .b-day *) {
color: #ffab85;
}
.b-app[data-t='night'] .bg-\[\#dff5ea\] {
.b-app[data-t='night'] .bg-\[\#dff5ea\]:not(.b-day, .b-day *) {
background: rgb(79 211 154 / 0.16);
}
.b-app[data-t='night'] .bg-\[\#ffe8dc\] {
.b-app[data-t='night'] .bg-\[\#ffe8dc\]:not(.b-day, .b-day *) {
background: rgb(255 138 87 / 0.16);
}
.b-app[data-t='night'] .b-bg-sky {
.b-app[data-t='night'] .b-bg-sky:not(.b-day, .b-day *) {
background: linear-gradient(180deg, #2a4384, #1f2c62);
}
.b-app[data-t='night'] .b-bg-butter {
.b-app[data-t='night'] .b-bg-butter:not(.b-day, .b-day *) {
background: linear-gradient(180deg, #4d4128, #2c2a3e);
}
.b-app[data-t='night'] .b-bg-peach {
.b-app[data-t='night'] .b-bg-peach:not(.b-day, .b-day *) {
background: linear-gradient(180deg, #553632, #2e2840);
}
.b-app[data-t='night'] .b-bg-mint {
.b-app[data-t='night'] .b-bg-mint:not(.b-day, .b-day *) {
background: linear-gradient(180deg, #1f4a45, #1d2d4a);
}
.b-app[data-t='night'] .b-bg-lilac {
.b-app[data-t='night'] .b-bg-lilac:not(.b-day, .b-day *) {
background: linear-gradient(180deg, #3d3480, #262a5e);
}
.b-app[data-t='night'] .b-band-1 {
.b-app[data-t='night'] .b-band-1:not(.b-day, .b-day *) {
background: linear-gradient(180deg, rgb(255 160 110 / 0.12), rgb(255 255 255 / 0));
}
.b-app[data-t='night'] .b-band-2 {
.b-app[data-t='night'] .b-band-2:not(.b-day, .b-day *) {
background: linear-gradient(180deg, rgb(255 214 110 / 0.12), rgb(255 255 255 / 0));
}
.b-app[data-t='night'] .b-band-3 {
.b-app[data-t='night'] .b-band-3:not(.b-day, .b-day *) {
background: linear-gradient(180deg, rgb(110 230 180 / 0.12), rgb(255 255 255 / 0));
}
/* 밤에도 포스트 카드 본문은 낮 색 그대로 (어두운 카드가 줄줄이 이어지지 않게). 위 밤 덮어쓰기는 이 안을 뺀다 */
.b-app[data-t='night'] .b-day {
--ink: #28304a;
--ink2: #5a6380;
--ink3: #6b738c;
--line: #e6ecf4;
--shade: #d9e5f4;
--orange: #ff7a45;
--heart: #ff3b5c;
--skel: color-mix(in oklab, currentColor 13%, transparent);
color: var(--ink);
color-scheme: light;
}
.b-app[data-t='night'] img[data-dark] {
filter: drop-shadow(0 0 1px rgb(255 255 255 / 0.9)) drop-shadow(0 0 6px rgb(255 255 255 / 0.3));
}
+3 -1
View File
@@ -30,6 +30,8 @@ function stage(peak: string, today: string): Stage {
}
const toXY = (lat: number, lon: number) => ({ x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size })
// 처음 화면 가로 가운데: 명소 가운데(127.9°)로 잡으면 서해 섬까지 든 땅이 왼쪽으로 쏠려 보여 서쪽으로 당김
export const LAND_CX = toXY(36, 127.65).x
// 지도 위 시·도 이름 자리(위경도). 서울·경기는 겹치지 않게 경기를 북쪽으로 조금 올림
export const PROVINCES = (
@@ -50,7 +52,7 @@ export const PROVINCES = (
export const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
const province = (m: Spot) => m.region.split(' ')[0].split('·')
/** 오늘(한국 시각) 기준 명소 65곳과 단계. 단풍철이 아니면 inSeason 이 false */
/** 오늘(한국 시각) 기준 명소 67곳과 단계. 단풍철이 아니면 inSeason 이 false */
export function useFoliage() {
const [today] = useState(() => {
const t = kst(new Date())
+6 -5
View File
@@ -1,7 +1,6 @@
import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useNavigate } from 'react-router'
import { cx } from '../lib/utils'
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen'
import { useCarousel } from './carousel'
import { headline, ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, spread, useFoliage, useLabelSize } from './foliage'
import { PostFrame } from './Post'
@@ -14,7 +13,7 @@ const TAP_R = 24
const RANK_N = 7
/** 피드의 단풍 지도 카드: 1장은 지금 절정인 곳만 잎 아이콘으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위. '지도 크게 보기'로 단풍 지도 페이지 */
export function FoliageCard({ post }: { post?: PostReaction | null }) {
export function FoliageCard() {
const navigate = useNavigate()
const { today, spots, inSeason } = useFoliage()
const peak = useMemo(() => spots.filter((m) => m.stage === 'peak').sort((a, b) => Number(a.kind === 'ginkgo') - Number(b.kind === 'ginkgo') || a.y - b.y), [spots])
@@ -56,7 +55,7 @@ export function FoliageCard({ post }: { post?: PostReaction | null }) {
// 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로
const ranked = rankNow(spots).slice(0, RANK_N)
return (
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" pinned={{ key: 'foliage_post', post }} caption={peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined}>
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined}>
<div className="b-keep-bg relative bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<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">{headline(spots)}</p>
@@ -66,8 +65,10 @@ export function FoliageCard({ post }: { post?: PostReaction | null }) {
</span>
<div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
<div className="flex">
<div className="min-w-0 shrink-0 grow-0 basis-full">
<div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full bg-[#fff6ea]">
{/* 밀어 낸 지도가 옆 장(가기 좋은 곳)을 덮지 않게 이 장 밖은 자른다 */}
<div className="min-w-0 shrink-0 grow-0 basis-full overflow-hidden">
{/* 지도 그림은 땅이 왼쪽에 치우쳐 있어 오른쪽(빈 바다)으로 밀어 가운데에 맞춘다 */}
<div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full translate-x-[7%] bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={MAP_IMG} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
+20 -34
View File
@@ -2,43 +2,20 @@ import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'
type GoogleId = {
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 로그인 창을 처음 열 때 한 번만 받는다 */
function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
import { cx } from '../lib/utils'
import { loadGoogle } from './googleScript'
import { SHEET_OPEN_MS } from './lib'
import { Skel } from './ui'
/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id
const config = useQuery({ ...authConfigOptions(), staleTime: Infinity })
const clientId = config.data?.google_client_id
const login = useMutation(googleLoginMutation())
const box = useRef<HTMLDivElement>(null)
const [broken, setBroken] = useState(false)
// 구글 버튼(iframe)이 다 그려지기 전엔 같은 크기의 스켈레톤을 보여 준다. 빈칸에 버튼이 툭 튀어나오면 버벅이는 것처럼 보여서
const [ready, setReady] = useState(false)
const { mutate } = login
// 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다
const cb = useRef({ onResult, onFail })
@@ -49,8 +26,10 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
useEffect(() => {
if (!clientId || !box.current) return
let alive = true
loadGoogle().then(
(g) => {
// 버튼(iframe)을 만드는 일이 무거워, 로그인 창이 다 올라온 뒤에 만든다. 자리는 min-h 로 잡아 둬서 밀리지 않는다
const wait = new Promise((r) => setTimeout(r, SHEET_OPEN_MS))
Promise.all([loadGoogle(), wait]).then(
([g]) => {
if (!alive || !box.current) return
g.initialize({
client_id: clientId,
@@ -61,6 +40,9 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
},
})
g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth })
const frame = box.current.querySelector('iframe')
if (frame) frame.addEventListener('load', () => alive && setReady(true), { once: true })
else setReady(true)
},
(e: unknown) => {
console.error('[google] script', e)
@@ -72,10 +54,14 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
}
}, [clientId, mutate])
if (config.isPending) return <Skel shape className="mx-auto h-[44px] w-full max-w-[400px] rounded-full" />
if (!clientId) return null
return (
<div className="flex flex-col gap-2">
<div ref={box} className="flex min-h-[44px] justify-center" aria-busy={login.isPending} />
<div className="relative">
{!ready && !broken && <Skel shape className="absolute inset-x-0 top-0 mx-auto h-[44px] w-full max-w-[400px] rounded-full" />}
<div ref={box} className={cx('flex min-h-[44px] justify-center transition-opacity duration-200', ready ? 'opacity-100' : 'opacity-0')} aria-busy={login.isPending || !ready} />
</div>
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
</div>
)
+40
View File
@@ -0,0 +1,40 @@
export type GoogleId = {
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 한 번만 받는다. 실패하면 다음에 다시 받는다 */
export function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
/** 로그인 안 한 사람은 화면이 한가할 때 스크립트를 미리 받아 둔다. 로그인 창이 올라오는 도중에 스크립트를 실행하느라 화면이 멈추지 않게. 돌려준 함수로 취소 */
export function preloadGoogle(): () => void {
const run = () => void loadGoogle().catch((e: unknown) => console.error('[google] preload', e))
if ('requestIdleCallback' in window) {
const id = requestIdleCallback(run, { timeout: 4000 })
return () => cancelIdleCallback(id)
}
const id = setTimeout(run, 2500)
return () => clearTimeout(id)
}
+20 -19
View File
@@ -1,6 +1,8 @@
import { useEffect, useState, type ReactNode } from 'react'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { dismiss, dismissed, platform, promptInstall, useCanPrompt, useInstall, useInstallable } from './install'
import { TAP44 } from './ui'
const SITE = 'https://weather.o2o.kr'
@@ -17,27 +19,26 @@ export function InstallBanner() {
if (hidden) return null
return (
<aside aria-label="홈 화면에 추가" className="mx-3 mt-3.5 flex items-center gap-3 rounded-[22px] bg-white p-3.5 shadow-[inset_0_-5px_0_var(--shade)]">
<img src="/app/icon-192.png" alt="" className="size-12 shrink-0 rounded-[14px]" />
<aside aria-label="홈 화면에 추가" className="mt-3.5 flex items-center gap-2.5 border-y border-(--line) bg-white py-2.5 pr-1.5 pl-3">
<img src="/app/icon-192.png" alt="" className="size-10 shrink-0 rounded-[11px]" />
<div className="min-w-0 flex-1">
<p className="m-0 font-jua text-[16.5px] leading-snug">내일도 우산각·빨래각, 바로 확인하세요</p>
<p className="m-0 mt-0.5 text-[12.5px] font-semibold text-(--ink2)">날씨각을 홈 화면에 추가하고 한 번에 열어보세요.</p>
<div className="mt-2 flex gap-1.5">
<button type="button" onClick={() => install('banner')} className="cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">
📲 홈 화면에 추가
</button>
<button
type="button"
onClick={() => {
dismiss()
setClosed(true)
}}
className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2)"
>
닫기
</button>
</div>
<p className="m-0 font-jua text-[15px] leading-snug">내일도 우산각·빨래각, 바로 확인하세요</p>
<p className="m-0 text-xs leading-snug font-semibold text-(--ink2)">홈 화면에서 바로 열어 보세요.</p>
</div>
<button type="button" onClick={() => install('banner')} className="shrink-0 cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">
추가
</button>
<button
type="button"
onClick={() => {
dismiss()
setClosed(true)
}}
aria-label="닫기"
className={cx('relative grid size-[30px] shrink-0 cursor-pointer place-items-center text-xl text-(--ink3)', TAP44)}
>
×
</button>
</aside>
)
}
+5
View File
@@ -14,3 +14,8 @@ export function iconSrc(name: string) {
export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: [ARTICLE_LABEL[1], 'text-[#1f9d62]'], 2: [ARTICLE_LABEL[2], 'text-[#7a5cd6]'], 3: [ARTICLE_LABEL[3], 'text-(--orange)'] }
/** 아래 창이 다 올라오는 시간(.b-sheet 0.26s). 무거운 일은 이 뒤로 미뤄 올라오는 동안 버벅이지 않게 */
export const SHEET_OPEN_MS = 280
/** 아래 창이 내려가며 닫히는 시간(.b-sheet-closing 0.2s). 이 뒤에 실제로 닫는다 */
export const SHEET_CLOSE_MS = 200
+79
View File
@@ -0,0 +1,79 @@
import { useId } from 'react'
import { moonPath } from '@nalssigak/shared/lib/today'
// 앞면 바다(어두운 무늬) 자리: [x, y, 가로 반지름, 세로 반지름]. 실제 달 앞면 배치를 대강 따른다
const MARIA: [number, number, number, number][] = [
[-0.32, -0.36, 0.3, 0.26],
[0.12, -0.36, 0.17, 0.15],
[0.3, -0.06, 0.2, 0.17],
[-0.56, 0.06, 0.26, 0.42],
[0.66, -0.26, 0.1, 0.12],
[0.52, 0.22, 0.13, 0.15],
[-0.14, 0.44, 0.18, 0.13],
[-0.46, 0.5, 0.1, 0.09],
]
// 작은 크레이터: [x, y, 반지름]
const CRATERS: [number, number, number][] = [
[0.1, 0.72, 0.07],
[0.42, 0.52, 0.05],
[-0.66, -0.5, 0.05],
[0.62, 0.52, 0.04],
[-0.2, 0.08, 0.04],
]
// 저녁(노을)엔 노을빛이 도는 달, 밤엔 하얀 달
const TONES = {
night: { body: ['#fffcf2', '#f6ebcb', '#e0cc98'], shade: '#1a2050' },
dusk: { body: ['#fff8ee', '#ffe2cc', '#f2b9a2'], shade: '#4a2a63' },
}
/** 오늘 밤 실제 모양대로 그린 달. pct 는 빛나는 면의 비율 0~100, 기우는 달은 왼쪽이 밝다 */
export function MoonArt({ pct, waxing, tone = 'night', className }: { pct: number; waxing: boolean; tone?: keyof typeof TONES; className?: string }) {
const id = useId()
const t = TONES[tone]
const k = pct / 100
const full = pct >= 99
const hidden = pct <= 1
return (
<svg viewBox="-1.5 -1.5 3 3" className={className} aria-hidden="true">
<defs>
<radialGradient id={`${id}glow`}>
<stop offset="0.6" stopColor="#fff4cf" stopOpacity="0.55" />
<stop offset="0.8" stopColor="#ffe9a8" stopOpacity="0.16" />
<stop offset="1" stopColor="#ffe9a8" stopOpacity="0" />
</radialGradient>
<radialGradient id={`${id}body`} cx="0.4" cy="0.36" r="0.72">
<stop offset="0" stopColor={t.body[0]} />
<stop offset="0.6" stopColor={t.body[1]} />
<stop offset="1" stopColor={t.body[2]} />
</radialGradient>
<radialGradient id={`${id}limb`}>
<stop offset="0.72" stopColor="#8a6f3c" stopOpacity="0" />
<stop offset="1" stopColor="#8a6f3c" stopOpacity="0.28" />
</radialGradient>
<clipPath id={`${id}disc`}>
<circle r="1" />
</clipPath>
<filter id={`${id}soft`} x="-0.2" y="-0.2" width="1.4" height="1.4">
<feGaussianBlur stdDeviation="0.035" />
</filter>
</defs>
{!hidden && <circle r="1.5" fill={`url(#${id}glow)`} opacity={full ? 1 : 0.12 + 0.8 * k} />}
<g clipPath={`url(#${id}disc)`}>
<circle r="1" fill={`url(#${id}body)`} />
<g filter={`url(#${id}soft)`} fill="#c4b287" opacity="0.55">
{MARIA.map(([x, y, rx, ry]) => (
<ellipse key={`${x},${y}`} cx={x} cy={y} rx={rx} ry={ry} />
))}
</g>
{CRATERS.map(([x, y, r]) => (
<circle key={`${x},${y}`} cx={x} cy={y} r={r} fill="#efe2bd" stroke="#cdbb8c" strokeWidth="0.018" opacity="0.8" />
))}
<circle r="1" fill={`url(#${id}limb)`} />
{/* 안 보이는 쪽: 흐릿한 경계로 덮고, 땅빛(지구조) 정도만 비치게 */}
{!full && <path d={moonPath(pct, 1.04, false)} fill={t.shade} opacity="0.94" filter={`url(#${id}soft)`} transform={waxing ? undefined : 'scale(-1,1)'} />}
</g>
{hidden && <circle r="1" fill="none" stroke="#fff" strokeOpacity="0.18" strokeWidth="0.025" />}
</svg>
)
}
+173 -37
View File
@@ -1,7 +1,8 @@
import { useState, type ReactNode } from 'react'
import { useRef, useState, type ReactNode } from 'react'
import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
import { gakName, MY_GAK_ICON, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
import { MyGakShareCard } from './shareCards'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Ic, Rail, Sec } from './ui'
@@ -27,55 +28,160 @@ function Reasons({ s }: { s?: MyGakScore }) {
)
}
/** 오늘 탭의 내 각 줄: 내가 정한 조건으로 매긴 오늘 점수 */
// 조건 이름. 점수 응답의 factors 와 reasons 는 같은 순서다
const AXIS_NAME: Record<string, string> = { temp: '기온', rain: '비', wind: '바람', air: '미세먼지', humidity: '습도' }
// 조건 점수가 이보다 낮으면 '아쉬운 조건'으로 카드에 칩을 단다
const SHORT = 70
/** 조건마다 이름·점수·실제 값 (실제 값은 근거 문구의 첫 마디: 체감 15°) */
function conditions(s?: MyGakScore) {
const notes = s?.reasons ?? []
return Object.entries(s?.factors ?? {}).map(([axis, value], i) => ({ axis, label: AXIS_NAME[axis] ?? axis, value, note: notes[i] ?? '', short: (notes[i] ?? '').split(', ')[0] }))
}
/** 오늘 탭의 내 각 줄: 카드엔 아이콘·이름·점수·아쉬운 조건만, 누르면 상세 창 */
export function MyGakRow() {
const { open } = useSheet()
const { items, remove } = useMyGak()
const { items } = 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),
)
}
const shots = useRef<(HTMLDivElement | null)[]>([])
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>
))}
{items.map((g, i) => {
const s = scores[i]
const miss = conditions(s).filter((c) => c.value < SHORT).slice(0, 2)
return (
<button
key={g.id ?? 'local'}
type="button"
onClick={() => open({ type: 'myGak', gak: g, shot: shots.current[i] })}
aria-label={`${g.name} ${s?.score ?? ''}점 자세히`}
className="flex w-[200px] cursor-pointer flex-col gap-2 rounded-[22px] bg-white p-3 text-left shadow-[inset_0_-5px_0_var(--shade)]"
>
<span className="flex w-full items-start justify-between">
<Ic name={g.icon ?? MY_GAK_ICON} className="size-10" />
<Score s={s} big />
</span>
<span>
<b className="block font-jua text-[17px] leading-tight font-normal">{g.name}</b>
<small className="text-xs font-bold text-(--ink3)">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준` : '예보를 불러오는 중이에요'}</small>
</span>
{s?.slot && (
<span className="flex flex-wrap gap-1 text-[11.5px] font-extrabold">
{miss.length ? (
miss.map((c) => (
<span key={c.axis} className="rounded-full bg-[#ffe8dc] px-2 py-0.5 text-[#c2471b]">
{c.short}
</span>
))
) : (
<span className="rounded-full bg-[#dff5ea] px-2 py-0.5 text-[#1f7a4f]">조건 다 맞아요</span>
)}
</span>
)}
</button>
)
})}
<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>
{items.map((g, i) => (
<MyGakShareCard
key={g.id ?? 'local'}
name={g.name}
icon={g.icon ?? MY_GAK_ICON}
score={scores[i]?.score}
slot={scores[i]?.slot ? SLOT_WORD[scores[i].slot as Slot] : undefined}
rows={conditions(scores[i])}
ref={(el) => {
shots.current[i] = el
}}
/>
))}
</>
)
}
/** 내 각 상세: 시간대별 점수, 조건별 점수와 실제 값, 공유하기(다른 포스트와 같은 공유 창)·지우기 */
export function MyGakSheet({ gak, shot, onDone }: { gak: MyGak; shot?: HTMLElement | null; onDone: () => void }) {
const { open } = useSheet()
const { remove } = useMyGak()
const s = useMyGakScores([gak.rule]).data?.scores?.[0]
const [confirm, setConfirm] = useState(false)
const rows = conditions(s)
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
<div className="flex items-center gap-3">
<Ic name={gak.icon ?? MY_GAK_ICON} className="size-14" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[22px] leading-tight font-normal">{gak.name}</b>
<small className="text-[12.5px] font-bold text-(--ink3)">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준 점수` : '예보를 불러오는 중이에요'}</small>
</span>
<Score s={s} big />
</div>
<div className="mt-3 grid grid-cols-4 gap-1.5" aria-label="시간대별 점수">
{SLOTS.map(([k, word]) => {
const v = s?.slots?.[k]
return (
<div key={k} className={cx('rounded-2xl px-1 py-2 text-center', s?.slot === k ? 'bg-[#fff4ec]' : 'bg-[#f3f6fb]')}>
<small className="block text-xs font-extrabold text-(--ink2)">{word}</small>
<b className={cx('block font-bagel text-xl font-normal', v != null ? 'text-(--orange)' : 'text-(--ink3)')}>{v ?? '–'}</b>
</div>
)
})}
</div>
<div className="mt-3.5 flex flex-col gap-2.5">
{rows.map((c) => (
<div key={c.axis} className="grid grid-cols-[64px_1fr_32px] items-center gap-x-2.5 text-[13.5px] font-bold">
<span>{c.label}</span>
<i className="block h-[9px] overflow-hidden rounded-full bg-[#e3eaf4]">
<s className="b-keep-bg block h-full bg-[linear-gradient(90deg,#ffc86e,var(--orange))]" style={{ width: `${c.value}%` }} />
</i>
<em className="text-right text-xs text-(--ink2) not-italic tabular-nums">{c.value}</em>
<p className="col-start-2 col-end-4 m-0 -mt-0.5 text-[12.5px] font-semibold text-(--ink2)">{c.note}</p>
</div>
))}
</div>
<div className="mt-4 flex gap-2">
<button
type="button"
onClick={() => open({ type: 'share', share: { title: gak.name, slides: shot ? [shot] : [], url: shareUrl(gak) } })}
disabled={!shot}
className="flex-1 cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[16px] text-white disabled:opacity-45"
>
공유하기
</button>
{confirm ? (
<>
<button
type="button"
onClick={() => {
remove(gak)
onDone()
}}
className="cursor-pointer rounded-2xl bg-[#fdecec] px-4 py-3 font-jua text-[16px] text-(--heart)"
>
지우기
</button>
<button type="button" onClick={() => setConfirm(false)} className="cursor-pointer rounded-2xl bg-[#eef4fc] px-4 py-3 font-jua text-[16px] text-(--ink2)">
취소
</button>
</>
) : (
<button type="button" onClick={() => setConfirm(true)} className="cursor-pointer rounded-2xl bg-[#eef4fc] px-4 py-3 font-jua text-[16px] text-(--ink2)">
지우기
</button>
)}
</div>
{confirm && <p className="mt-1.5 mb-0 text-right text-[12.5px] font-bold text-(--ink2)">지울까요?</p>}
</div>
)
}
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')}>
@@ -124,6 +230,32 @@ type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity'
const condsOf = (r: MyGakRule): Record<Cond, boolean> => ({ temp: !!r.temp, rain: !!r.rain, wind_max: r.wind_max != null, air: !!r.air, humidity: !!r.humidity })
/** 내 각 아이콘 고르기: 있는 각 아이콘 그대로 */
function IconPicker({ value, onPick }: { value: string; onPick: (icon: string) => void }) {
const icons = [...new Set([MY_GAK_ICON, ...(usePresets().data ?? []).map((p) => p.icon)])]
return (
<div className="mt-3">
<span className="font-jua text-[19px]">아이콘</span>
<div className="-mx-4">
<Rail label="아이콘" className="gap-1.5">
{icons.map((icon) => (
<button
key={icon}
type="button"
aria-pressed={value === icon}
aria-label={`아이콘 ${icon}`}
onClick={() => onPick(icon)}
className={cx('grid size-12 cursor-pointer place-items-center rounded-2xl', value === icon ? 'bg-(--orange) ring-2 ring-(--orange)' : 'bg-[#f3f6fb]')}
>
<Ic name={icon} className="size-8" />
</button>
))}
</Rail>
</div>
</div>
)
}
/** 있는 각을 골라 그 각 조건으로 채운다 */
function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) {
const items = usePresets().data ?? []
@@ -159,9 +291,11 @@ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => voi
const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE)
const [on, setOn] = useState<Record<Cond, boolean>>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false })
const [picked, setPicked] = useState<string | null>(null)
const [icon, setIcon] = useState(shared?.icon ?? MY_GAK_ICON)
const pick = (p: MyGakPreset) => {
setPicked(p.code)
setName(p.name)
setIcon(p.icon)
setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE)
setOn(condsOf(p.rule))
}
@@ -184,6 +318,7 @@ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => voi
<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>
<IconPicker value={icon} onPick={setIcon} />
</>
)}
<fieldset disabled={!!shared} className="m-0 mt-3 border-0 p-0">
@@ -215,7 +350,8 @@ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => voi
</div>
</fieldset>
<div className="mt-2 flex flex-col gap-1.5 rounded-[20px] bg-[#f3f6fb] p-3.5">
<div className="flex items-center">
<div className="flex items-center gap-2">
<Ic name={icon} className="size-8" />
<b className="font-jua text-[20px] font-normal">{title}</b>
<Score s={valid ? score : undefined} big />
</div>
@@ -225,7 +361,7 @@ export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => voi
<button
type="button"
disabled={!valid || !gakName(name) || pending}
onClick={() => create({ name, rule }, onDone)}
onClick={() => create({ name, icon, 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 ? '내 각으로 가져오기' : '내 각으로 저장'}
+11 -7
View File
@@ -19,7 +19,10 @@ export const SLOTS: [Slot, string][] = [
]
/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) */
export type MyGak = { id?: number; name: string; rule: MyGakRule }
export type MyGak = { id?: number; name: string; icon?: string | null; rule: MyGakRule }
/** 아이콘을 안 골랐을 때 */
export const MY_GAK_ICON = 'rabbit'
function readLocal(): MyGak | null {
try {
@@ -58,7 +61,7 @@ export const gakName = (name: string) => {
/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 */
export function shareUrl(g: MyGak) {
const json = JSON.stringify({ n: g.name, r: g.rule })
const json = JSON.stringify({ n: g.name, i: g.icon ?? undefined, r: g.rule })
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)))
return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`
}
@@ -66,8 +69,9 @@ export function shareUrl(g: MyGak) {
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
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; i?: unknown; r?: unknown }
const icon = typeof v.i === 'string' && /^[a-z_]{1,32}$/.test(v.i) ? v.i : null
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, icon, rule: v.r as MyGakRule } : null
} catch (e) {
console.warn('[myGak] 받은 링크를 읽지 못함', e)
return null
@@ -108,14 +112,14 @@ export function useMyGak() {
const { mutate } = add
useEffect(() => {
if (!loggedIn || !saved) return
mutate({ body: { name: saved.name, rule: saved.rule } }, { onSuccess: () => setLocal(null) })
mutate({ body: { name: saved.name, icon: saved.icon, 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 items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, icon: g.icon, rule: g.rule })) : saved ? [saved] : []
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
const create = (g: MyGak, onDone?: () => void) => {
const item = { name: gakName(g.name), rule: g.rule }
const item = { name: gakName(g.name), icon: g.icon, rule: g.rule }
if (loggedIn) {
add.mutate({ body: item }, { onSuccess: (res) => res.result?.success && onDone?.() })
return
+29
View File
@@ -185,3 +185,32 @@ export function FoliageMapShare({ title, peak, ranked, ref }: { title: string; p
</Offscreen>
)
}
/** 내 각 공유: 아이콘·이름·점수, 조건마다 막대와 실제 값. 로고·지역·날짜는 공유 틀이 그린다 */
export function MyGakShareCard({ name, icon, score, slot, rows, ref }: { name: string; icon: string; score?: number | null; slot?: string; rows: { axis: string; label: string; value: number; note: string }[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="b-band-1 flex aspect-[4/5] flex-col bg-white px-5 pt-5 pb-4 text-[#28304a]">
<p className="m-0 text-[13px] font-extrabold opacity-75">내 각{slot ? ` · ${slot} 기준` : ''}</p>
<div className="mt-2 flex items-center gap-3">
<Ic name={icon} className="w-[64px] shrink-0" />
<b className="min-w-0 flex-1 font-jua text-[28px] leading-tight font-normal">{name}</b>
<em className="font-bagel text-[52px] leading-none text-[#ff7a45] not-italic">{score ?? '–'}</em>
</div>
<ul className="m-0 mt-4 grid list-none gap-2.5 p-0">
{rows.map((r) => (
<li key={r.axis} className="rounded-[18px] bg-white px-3 py-2.5 shadow-[inset_0_-4px_0_#d9e5f4]">
<span className="flex items-center gap-2 text-[14px] font-extrabold">
{r.label}
<i className="block h-[8px] flex-1 overflow-hidden rounded-full bg-[#e3eaf4]">
<s className="block h-full bg-[linear-gradient(90deg,#ffc86e,#ff7a45)]" style={{ width: `${r.value}%` }} />
</i>
</span>
<small className="mt-0.5 block text-[12.5px] font-semibold text-[#5a6380]">{r.note}</small>
</li>
))}
</ul>
</div>
</Offscreen>
)
}
+3 -2
View File
@@ -2,8 +2,8 @@ import type { MyGak } from './myGakState'
import type { TalkData } from '@nalssigak/shared/api/client/types.gen'
import type { WeatherWhyPayload } from './weatherWhy'
import { createContext, use } from 'react'
/** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides) */
export type SharePayload = { title: string; slides: HTMLElement[]; square?: HTMLElement[] }
/** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides). url: 같이 보낼 링크 (없으면 사이트 주소) */
export type SharePayload = { title: string; slides: HTMLElement[]; square?: HTMLElement[]; url?: string }
type CommentsState = { type: 'comments'; postId: number; draft?: string }
@@ -17,6 +17,7 @@ export type SheetState =
| { type: 'me' }
| { type: 'region' }
| { type: 'mix'; shared?: MyGak }
| { type: 'myGak'; gak: MyGak; shot?: HTMLElement | null }
| { type: 'install' }
| { type: 'weatherWhy'; why: WeatherWhyPayload }
| { type: 'talk'; talk: TalkData }
+44 -15
View File
@@ -2,7 +2,9 @@ import { domToCanvas } from 'modern-screenshot'
import { API_BASE_URL } from '../api/setup'
const W = 1080
const SIDE = 60
const SIDE = 24
// 1:1·4:5 아래 띠 높이: 날씨각 · 동네·날짜 · 주소 한 줄
const FOOT = 84
// 시간대별 배경 (화면 하늘 배경과 같은 색)
const SKY: Record<string, [string, string, string]> = {
@@ -12,11 +14,14 @@ const SKY: Record<string, [string, string, string]> = {
night: ['#0e1433', '#1b2356', '#2a2e6e'],
}
/** 공유 이미지 크기. 위: 로고·지역 날짜, 가운데: 카드, 아래: 주소 */
/**
* 공유 이미지 크기. 9:16 은 위 로고·지역 날짜, 가운데 카드, 아래 주소 알약.
* 1:1·4:5(strip)는 카드를 크게 두고 아래 얇은 띠 한 줄(날씨각 · 지역 날짜 · 주소)만
*/
export const SHARE_SIZES = {
story: { ratio: '9:16', w: 9, hr: 16, h: 1920, logoY: 250, logoPx: 96, subY: 325, subPx: 40, pillY: 1760, pillH: 100, labelPx: 34, hostPx: 46 },
feed: { ratio: '4:5', w: 4, hr: 5, h: 1350, logoY: 140, logoPx: 76, subY: 200, subPx: 34, pillY: 1250, pillH: 84, labelPx: 30, hostPx: 40 },
square: { ratio: '1:1', w: 1, hr: 1, h: 1080, logoY: 115, logoPx: 64, subY: 168, subPx: 30, pillY: 990, pillH: 80, labelPx: 28, hostPx: 38 },
story: { ratio: '9:16', w: 9, hr: 16, h: 1920, strip: false, logoY: 250, logoPx: 96, subY: 325, subPx: 40, pillY: 1760, pillH: 100, labelPx: 34, hostPx: 46 },
feed: { ratio: '4:5', w: 4, hr: 5, h: 1350, strip: true, logoY: 0, logoPx: 40, subY: 0, subPx: 26, pillY: 0, pillH: 0, labelPx: 0, hostPx: 32 },
square: { ratio: '1:1', w: 1, hr: 1, h: 1080, strip: true, logoY: 0, logoPx: 40, subY: 0, subPx: 26, pillY: 0, pillH: 0, labelPx: 0, hostPx: 32 },
} as const
export type ShareSize = keyof typeof SHARE_SIZES
@@ -113,7 +118,7 @@ type Box = { x: number; y: number; w: number; h: number }
function place(n: number, aspect: number, top: number, bottom: number): Box[] {
const room = bottom - top
if (n === 1) {
const w = Math.min(W - SIDE * 3, room / aspect)
const w = Math.min(W - SIDE * 2, room / aspect)
const h = w * aspect
return [{ x: (W - w) / 2, y: top + (room - h) / 2, w, h }]
}
@@ -152,11 +157,11 @@ export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize;
document.fonts.load(LOGO(z.hostPx), opts.host),
document.fonts.load(LOGO(36), '12'),
document.fonts.load(SANS(z.subPx), opts.sub),
document.fonts.load(SANS(z.labelPx), PILL_LABEL),
...(z.strip ? [] : [document.fonts.load(SANS(z.labelPx), PILL_LABEL)]),
])
const css = await fontCss(cards.map((c) => c.textContent ?? '').join(''))
const aspect = cards[0].offsetHeight / cards[0].offsetWidth
const boxes = place(cards.length, aspect, z.subY + 60, z.pillY - z.pillH / 2 - 50)
const boxes = z.strip ? place(cards.length, aspect, SIDE, z.h - FOOT) : place(cards.length, aspect, z.subY + 60, z.pillY - z.pillH / 2 - 50)
const shots = await Promise.all(cards.map((c, i) => domToCanvas(c, { scale: boxes[i].w / c.offsetWidth, filter: keep, font: css ? { cssText: css } : false, fetchFn: viaProxy })))
const canvas = document.createElement('canvas')
@@ -173,13 +178,15 @@ export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize;
ctx.fillStyle = bg
ctx.fillRect(0, 0, W, z.h)
ctx.textAlign = 'center'
ctx.fillStyle = '#ff7a45'
ctx.font = LOGO(z.logoPx)
ctx.fillText('날씨각', W / 2, z.logoY)
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
ctx.font = SANS(z.subPx)
ctx.fillText(opts.sub, W / 2, z.subY, W - SIDE * 2)
if (!z.strip) {
ctx.textAlign = 'center'
ctx.fillStyle = '#ff7a45'
ctx.font = LOGO(z.logoPx)
ctx.fillText('날씨각', W / 2, z.logoY)
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
ctx.font = SANS(z.subPx)
ctx.fillText(opts.sub, W / 2, z.subY, W - SIDE * 2)
}
const r = 40 * (boxes[0].w / 900)
shots.forEach((shot, i) => {
@@ -200,6 +207,28 @@ export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize;
})
if (shots.length > 1) boxes.forEach((b, i) => badge(ctx, b.x + 6, b.y + 6, i + 1))
if (z.strip) {
// 아래 띠: 왼쪽 [날씨각 지역 · 날짜], 오른쪽 주소. 카드 양 끝에 맞춘다
const left = Math.min(...boxes.map((b) => b.x))
const right = Math.max(...boxes.map((b) => b.x + b.w))
const y = z.h - FOOT / 2 + 2
ctx.textBaseline = 'middle'
ctx.textAlign = 'left'
ctx.fillStyle = '#ff7a45'
ctx.font = LOGO(z.logoPx)
ctx.fillText('날씨각', left, y)
const logoW = ctx.measureText('날씨각').width
ctx.font = LOGO(z.hostPx)
const hostW = ctx.measureText(opts.host).width
ctx.textAlign = 'right'
ctx.fillText(opts.host, right, y)
ctx.textAlign = 'left'
ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380'
ctx.font = SANS(z.subPx)
ctx.fillText(opts.sub, left + logoW + 16, y, Math.max(0, right - hostW - 24 - (left + logoW + 16)))
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png'))
}
// 주소 알약: [오늘 내 동네 각 보기 host]
ctx.font = SANS(z.labelPx)
const lw = ctx.measureText(PILL_LABEL).width
+18 -1
View File
@@ -5,7 +5,7 @@ const line = { fill: 'none', stroke: 'currentColor', strokeLinecap: 'round', str
// 좋아요·댓글·보내기 세 아이콘이 나란히 놓일 때 크기가 같아 보이게: 하트는 원래 그림이 작아 10% 키우고(보이는 칸을 좁힘), 보내기는 커서 5% 줄인다
export function HeartIcon({ className }: P) {
return (
<svg viewBox="1.1 2.75 21.8 21.8" className={className} aria-hidden="true">
<svg viewBox="1.1 1.95 21.8 21.8" className={className} aria-hidden="true">
<path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" />
</svg>
)
@@ -27,6 +27,23 @@ export function SendIcon({ className }: P) {
)
}
export function CloseIcon({ className }: P) {
return (
<svg viewBox="0 0 24 24" {...line} strokeWidth="2.4" className={className} aria-hidden="true">
<path d="M6 6l12 12M18 6 6 18" />
</svg>
)
}
export function CameraIcon({ className }: P) {
return (
<svg viewBox="0 0 24 24" {...line} strokeWidth="2" className={className} aria-hidden="true">
<path d="M4 8.5A1.5 1.5 0 0 1 5.5 7h2.2l1.5-2h5.6l1.5 2h2.2A1.5 1.5 0 0 1 20 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 17.5z" />
<circle cx="12" cy="13" r="3.5" />
</svg>
)
}
export function PinIcon({ className }: P) {
return (
<svg viewBox="0 0 24 24" {...line} strokeWidth="2.2" className={className} aria-hidden="true">
+62 -27
View File
@@ -14,11 +14,11 @@ import { TalkReport, TalkTopic, type TalkData } from '@nalssigak/shared/api/clie
import { API_BASE_URL } from '../api/setup'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, kst } from '@nalssigak/shared/lib'
import { kst } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext'
import { topicName, TOPICS, useMyTalks } from './talkState'
import { useSheet } from './sheetContext'
import { HeartIcon } from './svg'
import { CameraIcon, HeartIcon } from './svg'
import { Avatar, Rail, TAP44 } from './ui'
const BODY_MAX = 100
@@ -31,8 +31,6 @@ const WRITE_ERRORS: Record<string, string> = {
INVALID_INPUT: '100자 안으로 써 주세요.',
}
// 글이 이보다 적으면 '동네 사람들' 묶음 대신 첫 글 쓰기 카드
const GROUP_MIN = 3
const COMPOSE_ID = 'talk-compose'
const REASONS = [
@@ -129,8 +127,19 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
id={COMPOSE_ID}
value={text}
onChange={(e) => setText(e.target.value)}
onFocus={() => !loggedIn && open({ type: 'login' })}
readOnly={busy}
// 로그인 전엔 읽기 전용이라 눌러도 키보드가 안 올라온다 (키보드가 떴다 내려가며 로그인 창이 버벅이던 것). 누르거나 Enter 면 로그인 창
onClick={(e) => {
if (loggedIn) return
// 창이 닫힐 때 포커스가 이 칸으로 돌아와 테두리가 번쩍이지 않게
e.currentTarget.blur()
open({ type: 'login' })
}}
onKeyDown={(e) => {
if (loggedIn || (e.key !== 'Enter' && e.key !== ' ')) return
e.preventDefault()
open({ type: 'login' })
}}
readOnly={busy || !loggedIn}
maxLength={BODY_MAX}
rows={2}
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
@@ -161,8 +170,9 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
</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 type="button" onClick={() => (loggedIn ? fileRef.current?.click() : open({ type: 'login' }))} disabled={busy} aria-label="사진 붙이기" className={cx('relative grid size-8 shrink-0 cursor-pointer place-items-center rounded-full bg-[#eef4fc] text-(--ink2) disabled:opacity-40', TAP44)}>
<CameraIcon className="size-[18px]" />
</button>
<span className="min-w-0 truncate">{me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}</span>
<span className="ml-auto tabular-nums">
@@ -188,7 +198,7 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
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 [menu, setMenu] = useState<'closed' | 'open' | 'confirm' | 'report' | 'done'>('closed')
const like = useMutation(likeTalkMutation())
const unlike = useMutation(unlikeTalkMutation())
const remove = useMutation(deleteTalkMutation())
@@ -230,7 +240,7 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
const src = t.image?.startsWith('/v1/') ? API_BASE_URL + t.image : (t.image ?? undefined)
return (
<div className={cx('grid grid-cols-[34px_1fr_24px] gap-2.5 border-b border-(--line) py-2.5 last:border-b-0', compact ? 'h-full w-full items-stretch' : 'items-start')}>
<div className={cx('grid grid-cols-[34px_1fr_auto] gap-2.5 border-b border-(--line) py-2.5 last:border-b-0', compact ? 'h-full w-full items-stretch' : 'items-start')}>
<span className="self-start">
<Avatar character={t.character} color={t.color} mood={t.mood} />
</span>
@@ -238,6 +248,7 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
<div className={cx('min-w-0', compact && 'flex flex-col')}>
<small className={cx('block text-xs font-bold text-(--ink3)', compact && 'truncate')}>
<b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b>
{t.mine && <span className="mr-1 rounded-full bg-[#ffe8dc] px-1.5 py-px text-[11px] font-extrabold text-[#c2471b]">내 글</span>}
{[t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ')}
</small>
{/* 묶음 안 작은 카드는 글이 잘리니, 누르면 창에서 글 전체·큰 사진을 본다 */}
@@ -251,17 +262,24 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
)}
{t.image && !compact && <img src={src} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
<small className={cx('block text-xs font-bold text-(--ink3)', compact ? 'mt-auto pt-1.5' : 'mt-0.5')}>
{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>
{t.ago} · 좋아요 {count}개
</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 && menu === 'confirm' ? (
<>
<span className="self-center text-(--ink2)">지울까요?</span>
<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>
<button type="button" onClick={() => setMenu('closed')} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
취소
</button>
</>
) : 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 type="button" onClick={() => setMenu('confirm')} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
지우기
</button>
) : menu === 'report' ? (
@@ -288,24 +306,36 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
</div>
)}
</div>
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="좋아요" className={cx('relative cursor-pointer self-start pt-1', TAP44)}>
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
</button>
{/* 글 메뉴(⋯)는 하트 옆 오른쪽 위에: 아래 줄 끝에 두면 말줄임표처럼 읽힌다 */}
<span className="flex items-start gap-4 self-start">
<button
type="button"
onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')}
aria-expanded={menu !== 'closed'}
aria-label="글 메뉴"
className={cx('relative cursor-pointer pt-0.5 text-[15px] leading-none font-extrabold tracking-[1px] text-(--ink3)', TAP44)}
>
⋯
</button>
<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>
</span>
</div>
)
}
/** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */
/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 방금 올린 글은 바로 아래에 보인다 (피드 사이 글은 새로 받을 때 섞인다) */
export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void }) {
/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 오늘 쓴 내 글은 바로 아래 '오늘 내 글' 묶음에 보인다 */
export function FeedComposer() {
return (
<div className="mt-3.5">
<Composer onDone={onPosted} />
<Composer />
</div>
)
}
/** 묶음에서 누른 글 하나를 창으로: 글 전체·큰 사진·좋아요·더보기 */
/** 묶음에서 누른 글 하나를 창으로: 글 전체·큰 사진·좋아요·글 메뉴 */
export function TalkSheet({ talk }: { talk: TalkData }) {
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pb-[18px]">
@@ -317,19 +347,20 @@ export function TalkSheet({ talk }: { talk: TalkData }) {
/** 피드에 끼우는 글 한 장 */
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}의 글`}>
<article className="mx-3 mt-3 rounded-[20px] bg-white px-3 shadow-[inset_0_-4px_0_var(--shade)]" aria-label={`${t.nickname}의 글`}>
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} onGone={onGone} />
</article>
)
}
/** 오늘 피드의 사람 글 묶음: 옆으로 넘기는 카드, 끝에 그 주제 전체 보기 */
export function TalkGroup({ title, topic, talks }: { title: string; topic?: number; talks: TalkData[] }) {
/** href: 오른쪽 위 '전체 보기'가 여는 곳 (없으면 이야기 탭의 그 주제) */
export function TalkGroup({ title, topic, talks, href }: { title: string; topic?: number; talks: TalkData[]; href?: string }) {
return (
<section aria-label={title} className="mt-3.5">
<div className="flex items-end justify-between px-4">
<h2 className="m-0 font-jua text-[19px] font-normal">{title}</h2>
<Link to={topic ? `/talk?topic=${topic}` : '/talk'} className="text-[13px] font-bold text-(--ink2)">
<Link to={href ?? (topic ? `/talk?topic=${topic}` : '/talk')} className="text-[13px] font-bold text-(--ink2)">
전체 보기
</Link>
</div>
@@ -348,7 +379,10 @@ export function TalkGroup({ title, topic, talks }: { title: string; topic?: numb
export function FirstTalkCard() {
const { region } = useRegion()
const place = region.name.split(' ').at(-1)
const { loggedIn } = useAuth()
const { open } = useSheet()
const go = () => {
if (!loggedIn) return open({ type: 'login' })
const el = document.getElementById(COMPOSE_ID)
el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
el?.focus({ preventScroll: true })
@@ -364,10 +398,11 @@ export function FirstTalkCard() {
)
}
/** '동네 사람들' 자리: 글이 GROUP_MIN 개 이상이면 묶음, 아니면 첫 글 쓰기 */
/** '동네 사람들' 자리: 글이 하나라도 있으면 묶음, 없으면 첫 글 쓰기 */
export function NearTalks({ talks, loaded }: { talks: TalkData[]; loaded: boolean }) {
if (!loaded) return null
return talks.length >= GROUP_MIN ? <TalkGroup title="동네 사람들" talks={talks} /> : <FirstTalkCard />
if (talks.length) return <TalkGroup title="동네 사람들" talks={talks} />
return <FirstTalkCard />
}
/** 내 정보 창의 내가 쓴 글 */
+16 -2
View File
@@ -1,6 +1,8 @@
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions, talkGroupsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { useState } from 'react'
import { listMyTalksInfiniteOptions, listMyTalksOptions, listTalksInfiniteOptions, talkGroupsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen'
import { kst } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext'
// 글 주제와 피드 묶음 이름
@@ -37,10 +39,22 @@ export function useTopicTalks(topic?: TalkTopic) {
}
}
/** 오늘(한국 날짜) 쓴 내 글, 최신순. 로그인했을 때만 받는다 */
export function useTodayMyTalks(loggedIn: boolean) {
const q = useQuery({ ...listMyTalksOptions(), enabled: loggedIn })
// 오늘 날짜는 화면을 연 때 기준으로 한 번만
const [now] = useState(() => kst(new Date()))
return (q.data?.talks ?? []).filter((t) => {
const d = kst(t.created_at)
return d.y === now.y && d.mo === now.mo && d.d === now.d
})
}
/** 내가 쓴 글 (최신순) */
export function useMyTalks() {
export function useMyTalks(enabled = true) {
const list = useInfiniteQuery({
...listMyTalksInfiniteOptions(),
enabled,
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
})