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

# Conflicts:
#	TODO.md
#	backend/crud/user_crud.py
#	backend/router/v1/auth/account.py
#	backend/router/v1/auth/protocol.py
#	backend/services/auth_service.py
#	compose.yaml
#	docs/이벤트_추적.md
#	frontend/src/api/client/@tanstack/react-query.gen.ts
#	frontend/src/api/client/index.ts
#	frontend/src/api/client/sdk.gen.ts
#	frontend/src/api/client/types.gen.ts
#	frontend/src/b/Sheets.tsx
#	frontend/src/b/region.tsx
#	frontend/src/lib/analytics.ts
This commit is contained in:
minaChoi committed 2026-10-23 16:22:18 +09:00
commit 84212099e6
285 files changed
+39026 -767

No files matched your search

+85 -73
View File
@@ -1,5 +1,6 @@
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
import regionPages from '../../seo/region.json'
import { setTokens, subscribeAuth } from '../api/auth'
import { SITE_URL } from '../api/setup'
import {
@@ -13,9 +14,7 @@ import {
listCommentsInfiniteOptions,
listCommentsInfiniteQueryKey,
listRegionsOptions,
loginMutation,
meQueryKey,
signupMutation,
tossMutation,
unlikeCommentMutation,
updateMeMutation,
@@ -26,11 +25,17 @@ import { IS_TOSS, tossLogin, tossShare } from '../lib/platform'
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 { useRegion } from './regionContext'
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, TalkSheet } from './talk'
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
export function SheetProvider({ children }: { children: ReactNode }) {
@@ -73,7 +78,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: '날씨 점수는 이렇게 나와요', talk: '이야기' } as const
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
@@ -97,13 +102,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
@@ -133,8 +140,13 @@ 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} />}
{state.type === 'talk' && <TalkSheet talk={state.talk} />}
</div>
)}
{!state && <RegionLinks />}
</dialog>
)
}
@@ -354,7 +366,7 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
</div>
<b className={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b>
</div>
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금은 제철이 아니에요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{now && (
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
@@ -519,14 +531,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,14 +553,14 @@ 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' })
@@ -565,10 +577,17 @@ function ShareSheet({ share }: { share: SharePayload }) {
)
return
}
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) => {
@@ -588,7 +607,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
setToast('이미지를 내려받았어요')
return
}
navigator.clipboard.writeText(text).then(
navigator.clipboard.writeText(`${text} ${SITE_URL}`).then(
() => setToast('이미지를 내려받고 링크를 복사했어요'),
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
)
@@ -627,8 +646,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)
@@ -639,7 +656,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)
@@ -721,8 +737,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 } }),
@@ -737,12 +752,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)
@@ -796,7 +810,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>
@@ -805,74 +819,42 @@ 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} />
if (IS_TOSS) return <TossLoginSheet onDone={onDone} onLoggedIn={onLoggedIn} />
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>
)
}
@@ -929,6 +911,8 @@ function TossLoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn
/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */
function MeSheet({ onDone }: { onDone: () => void }) {
const install = useInstall()
const installable = useInstallable()
const { me, logout } = useAuth()
const queryClient = useQueryClient()
const update = useMutation(updateMeMutation())
@@ -962,8 +946,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.provider === AuthProvider.TOSS ? '토스로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.provider === AuthProvider.TOSS ? '토스로 로그인했어요' : 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="캐릭터 고르기">
@@ -1036,6 +1025,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={() => {
@@ -1053,6 +1043,27 @@ function MeSheet({ onDone }: { onDone: () => void }) {
/* ---------- 지역 ---------- */
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const
/** 구 코드 → 그 구의 지역 페이지 주소 */
const pageHref = (code: string) => {
const p = ownPage(code)
return p ? `/today/${p.path}` : '/'
}
/** 지역 바꾸기가 닫혀 있을 때도 지역 페이지 링크를 HTML에 둔다 (검색 로봇이 링크를 따라가게) */
function RegionLinks() {
return (
<nav aria-label="지역별 오늘 날씨">
<ul>
{regionPages.map((p) => (
<li key={p.path}>
<a href={`/today/${p.path}`}>{p.name} 오늘 날씨</a>
</li>
))}
</ul>
</nav>
)
}
function RegionSheet({ onDone }: { onDone: () => void }) {
const { region, setRegion, locate, locateStatus } = useRegion()
const { me, logout } = useAuth()
@@ -1084,10 +1095,11 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
<ul className={cx('mt-2 flex flex-col transition-opacity', list.isPlaceholderData && 'opacity-60')}>
{regions.map((r) => (
<li key={r.code}>
<button
type="button"
<a
href={pageHref(r.code)}
aria-current={r.code === region.code ? 'true' : undefined}
onClick={() => {
onClick={(e) => {
e.preventDefault()
setRegion(r)
track('region_change', { region_name: r.name, method: 'list' })
onDone()
@@ -1096,7 +1108,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
>
{r.name}
{r.code === region.code && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
</button>
</a>
</li>
))}
</ul>