Merge remote-tracking branch 'origin/main' into feat/weather-game

# Conflicts:
#	frontend/src/b/Sheets.tsx
#	frontend/src/b/sheetContext.ts
This commit is contained in:
minaChoi committed 2026-10-28 15:37:45 +09:00
commit 7d097a05de
99 files changed
+3230 -41

No files matched your search

+4 -1
View File
@@ -10,6 +10,7 @@ import { AuthProvider } from './auth'
import { RegionProvider } from './region'
import { useAuth } from './authContext'
import { preloadGoogle } from './googleScript'
import { LevelBadge, LevelWatcher } from './level'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { SheetProvider } from './Sheets'
@@ -75,8 +76,9 @@ function TopBar() {
{IS_TOSS ? null : mePending ? (
<Skel shape className="size-9 shrink-0 rounded-full" />
) : me ? (
<button type="button" onClick={() => open({ type: 'me' })} aria-label={`내 정보, ${me.nickname}`} className="shrink-0 cursor-pointer rounded-full shadow-[0_6px_12px_rgb(40_48_74/0.12)]">
<button type="button" onClick={() => open({ type: 'me' })} aria-label={`내 정보, ${me.nickname}`} className="relative shrink-0 cursor-pointer rounded-full shadow-[0_6px_12px_rgb(40_48_74/0.12)]">
<Avatar character={me.character} color={me.color} mood={me.mood} size={36} />
<LevelBadge />
</button>
) : (
<button type="button" onClick={() => open({ type: 'login' })} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[13px] font-extrabold text-white">
@@ -318,6 +320,7 @@ export function BLayout() {
<SheetProvider>
<Shell />
<TossIntro />
<LevelWatcher />
</SheetProvider>
</RegionProvider>
</AuthProvider>
+5
View File
@@ -6,6 +6,7 @@ import { useSheet } from './sheetContext'
import { FoliageMapShare, FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Chips, Ic, TAP44 } from './ui'
import { track } from '../lib/analytics'
type View = { s: number; tx: number; ty: number }
type Filter = 'all' | Kind
@@ -66,6 +67,10 @@ export function FoliagePage() {
const spotShotRef = useRef<HTMLDivElement>(null)
const mapShotRef = useRef<HTMLDivElement>(null)
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.kind === filter), [spots, filter])
useEffect(() => track('foliage_open', {}), [])
useEffect(() => {
if (sel) track('foliage_spot', { spot_name: sel, from: 'page' })
}, [sel])
const vpRef = useRef<HTMLDivElement>(null)
const [box, setBox] = useState({ W: 0, H: 0 })
+6 -4
View File
@@ -15,6 +15,7 @@ import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { useCarousel } from './carousel'
import { MoonArt } from './moon'
import { Arrows, Credit, Ic, Rows, Skel, TAP44, Thumb } from './ui'
import { track } from '../lib/analytics'
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
@@ -416,10 +417,11 @@ function FullCard({ post }: PostProps) {
;(on ? like : unlike).mutate(
{ path: { post_id: post.post_id } },
{
onSuccess: (res) =>
res.result?.success
? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) })
: revert(),
onSuccess: (res) => {
if (!res.result?.success) return revert()
patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) })
if (on) track('like', { content_type: 'post', item_id: post.post_id })
},
onError: revert,
},
)
+20 -4
View File
@@ -36,6 +36,9 @@ import { useInstall, useInstallable } from './install'
import { InstallSheet } from './installBanner'
import { ARTICLE_CAT, SHEET_CLOSE_MS, SHEET_OPEN_MS } from './lib'
import { MixSheet, MyGakSheet } from './myGak'
import { TarotSheet } from './fortune'
import { OotdSheet } from './todayIcons'
import { LevelCard, LevelSheet, LevelUpSheet, useShareReward } from './level'
import { ownPage, useRegion } from './regionContext'
import { WeatherWhySheet } from './weatherWhy'
import { useSky } from './skyContext'
@@ -55,6 +58,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
window.history.pushState({ ...window.history.state, sheet: true }, '')
pushed.current = true
}
track('sheet_open', { sheet: s.type })
setState(s)
}, [])
const close = useCallback(() => {
@@ -86,7 +90,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
)
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기', gameHelp: '구름 합치기 하는 법' } as const
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기', tarot: '오늘 타로', ootd: '오늘 코디', level: '내 레벨', levelUp: '레벨이 올랐어요', gameHelp: '구름 합치기 하는 법' } as const
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
@@ -173,6 +177,10 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{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 === 'tarot' && <TarotSheet />}
{shown.type === 'ootd' && <OotdSheet />}
{shown.type === 'level' && <LevelSheet />}
{shown.type === 'levelUp' && <LevelUpSheet level={shown.level} />}
{shown.type === 'talk' && <TalkSheet talk={shown.talk} />}
{shown.type === 'gameHelp' && <GameHelpSheet />}
</div>
@@ -585,6 +593,7 @@ const SIZE_KEYS = Object.keys(SHARE_SIZES) as ShareSize[]
function ShareSheet({ share }: { share: SharePayload }) {
const { region } = useRegion()
const reward = useShareReward()
const { kind } = useSky()
const [size, setSize] = useState<ShareSize>('story')
const [images, setImages] = useState<Partial<Record<ShareSize, { blob: Blob; src: string }>>>({})
@@ -631,6 +640,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
(r) => {
setToast(r === 'saved' ? '이미지를 저장하고 링크를 보냈어요' : '링크를 보냈어요')
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
reward()
},
(e: unknown) => {
console.error('[share] toss', e)
@@ -651,6 +661,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
async () => {
setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요')
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
reward()
},
(e: unknown) => {
if (e instanceof DOMException && e.name === 'AbortError') return
@@ -724,9 +735,10 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
const block = useMutation(blockAuthorMutation())
const pending = report.isPending || block.isPending
const finish = (notice: string) => ({
const finish = (notice: string, done: () => void) => ({
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true)
done()
setStep('closed')
onNotice(notice)
queryClient.invalidateQueries({ predicate: isCommentList })
@@ -760,14 +772,14 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
)}
{step === 'report' &&
REPORT_REASONS.map(([reason, label]) => (
<button key={reason} type="button" disabled={pending} className={btn} onClick={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.'))}>
<button key={reason} type="button" disabled={pending} className={btn} onClick={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.', () => track('report', { content_type: 'comment', reason })))}>
{label}
</button>
))}
{step === 'block' && (
<>
<span className="w-full text-[13px] font-bold text-(--ink)">{c.nickname}님 댓글을 더는 안 볼까요?</span>
<button type="button" disabled={pending} className={cx(btn, 'bg-(--heart) text-white')} onClick={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.'))}>
<button type="button" disabled={pending} className={cx(btn, 'bg-(--heart) text-white')} onClick={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.', () => track('block', { content_type: 'comment' })))}>
차단하기
</button>
<button type="button" disabled={pending} className={btn} onClick={() => go('closed')}>
@@ -814,6 +826,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
if (res.result?.success) {
setLiked(!!res.liked)
if (res.like_count != null) setCount(res.like_count)
if (next) track('like', { content_type: 'comment', item_id: c.comment_id })
return
}
revert()
@@ -915,6 +928,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true)
setAddFailed(!res.result?.success)
if (!res.result?.success) return
track('comment', { post_id: postId })
setText('')
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) })
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
@@ -937,6 +951,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
{
onSuccess: (res) => {
if (!res.result?.success) return setAddFailed(true)
track('terms_agree', {})
queryClient.setQueryData(meQueryKey(), res)
setAskTerms(false)
send()
@@ -1186,6 +1201,7 @@ function MeSheet({ onDone }: { onDone: () => void }) {
<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.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
</div>
<LevelCard />
{installable && (
<button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
📲 홈 화면에 추가
+10 -1
View File
@@ -7,6 +7,7 @@ import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils'
import { CloseIcon } from './svg'
import { Rail, Skel, SkelRail, TAP44 } from './ui'
import { track } from '../lib/analytics'
// 유튜브는 플레이어가 200×200 이상이어야 해서, 카드 안 미리보기는 200px 너비로 띄우고 줄여 보인다.
// 위 로고·아래 제목 줄이 작은 카드에서 겹쳐 보이지 않게 가운데를 1.4배로 키워 위아래를 잘라 낸다
@@ -156,9 +157,16 @@ export function ShortsPage() {
const start = Math.max(0, items.findIndex((s) => s.id === firstId))
// 앱 안에서 들어왔으면 뒤로, 링크로 바로 들어왔으면 오늘 화면으로
const close = () => ((window.history.state as { idx?: number } | null)?.idx ? navigate(-1) : navigate('/', { replace: true }))
useEffect(() => {
if (firstId) track('shorts_open', { video_id: firstId })
}, [firstId])
const at = (s: ShortItem) => {
track('shorts_view', { video_id: s.id, index: items.indexOf(s) })
navigate(`/shorts/${s.id}`, { replace: true })
}
if (!items.length) return <div className="fixed inset-0 z-[70] bg-[#1d2233]" aria-busy={q.isPending} />
return <ShortsViewer items={items} start={start} onClose={close} onAt={(s) => navigate(`/shorts/${s.id}`, { replace: true })} />
return <ShortsViewer items={items} start={start} onClose={close} onAt={at} />
}
/**
@@ -300,6 +308,7 @@ function ShortsViewer({ items, start, onClose, onAt }: { items: ShortItem[]; sta
const on = !sound
soundRef.current = on
setSound(on)
track('shorts_sound', { on })
command(frames.current.get(at), on ? 'unMute' : 'mute')
}
+7 -1
View File
@@ -23,6 +23,7 @@ import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner'
import { MoonArt } from './moon'
import { MyGakRow } from './myGak'
import { MY_GAK_ID, TodayIcons } from './todayIcons'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike } from './pinnedLike'
@@ -36,6 +37,7 @@ import { DayShareCard, DayShareGrid, GakShareCard, type DayShare } from './share
import { CommentIcon, HeartIcon, SendIcon } from './svg'
import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText'
import { track } from '../lib/analytics'
type Mode = 'now' | TimeKind
@@ -334,6 +336,7 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
onClick={() => {
// 내일로 넘어갈 땐 지금 보던 시간대 그대로 시작해 배경이 튀지 않게
if (v && !tmr) setTmrKind(kind)
if (v !== tmr) track('hero_day_switch', { day: v ? 'tomorrow' : 'today' })
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')}
@@ -636,11 +639,14 @@ 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)} />
<TodayIcons />
<ShortsRail />
<FeedComposer />
{mine.length > 0 && <TalkGroup title="오늘 내 글" talks={mine} href="/talk?mine=1" />}
{raining && group(TalkTopic.RAIN)}
<MyGakRow />
<div id={MY_GAK_ID} className="scroll-mt-16">
<MyGakRow />
</div>
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
+20
View File
@@ -708,3 +708,23 @@ html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot,
.b-app[data-t='night'] .b-tab-main > span {
--tw-ring-color: rgb(18 24 60 / 0.9);
}
/* 오늘 한 장: 뽑은 카드가 뒤집히며 나온다 */
.b-card-flip {
animation: b-card-flip 0.55s cubic-bezier(0.2, 0.8, 0.3, 1);
}
@keyframes b-card-flip {
0% {
opacity: 0.4;
transform: perspective(600px) rotateY(90deg);
}
100% {
opacity: 1;
transform: perspective(600px) rotateY(0);
}
}
@media (prefers-reduced-motion: reduce) {
.b-card-flip {
animation: none;
}
}
+6 -1
View File
@@ -1,4 +1,4 @@
import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useNavigate } from 'react-router'
import { cx } from '../lib/utils'
import { useCarousel } from './carousel'
@@ -8,6 +8,7 @@ import { useSheet } from './sheetContext'
import { FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Ic } from './ui'
import { track } from '../lib/analytics'
const TAP_R = 24
const RANK_N = 7
@@ -37,6 +38,10 @@ export function FoliageCard() {
const labelAt = useMemo(() => placeLabels(pts, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true), [pts, size, W])
const provs = useMemo(() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: v.x * W, y: v.y * W })), pts, labelBoxes(labelAt, size)), [pts, W, labelAt, size])
useEffect(() => {
if (picked) track('foliage_spot', { spot_name: picked, from: 'card' })
}, [picked])
if (!inSeason) return null
const go = (name?: string) => navigate(name ? `/foliage?spot=${encodeURIComponent(name)}` : '/foliage')
const toggle = (name: string) => setPicked(name === picked ? null : name)
+360
View File
@@ -0,0 +1,360 @@
import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { getFortuneTodayOptions, getFortuneTodayQueryKey, importFortuneMutation, searchFortunePlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { drawFortune, saveDayLog } from '@nalssigak/shared/api/client/sdk.gen'
import type { DayLogData, LocalDraw, LocalLog, ResFortuneToday } from '@nalssigak/shared/api/client/types.gen'
import { kst } from '@nalssigak/shared/lib'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Ic } from './ui'
const KEY = 'nalssigak.b.fortune'
// 기기에 남기는 날 수 (서버도 이 안쪽만 받는다)
const KEEP_DAYS = 60
const MOODS = ['😆', '🙂', '😐', '😕', '😢']
const STAMPS = 7
/** 로그인하지 않았을 때 이 기기에 남기는 뽑은 카드·체크인 */
type Local = { draws: LocalDraw[]; logs: LocalLog[] }
const EMPTY: Local = { draws: [], logs: [] }
function readLocal(): Local {
try {
const raw = localStorage.getItem(KEY)
return raw ? { ...EMPTY, ...(JSON.parse(raw) as Local) } : EMPTY
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
return EMPTY
}
}
let local = readLocal()
const listeners = new Set<() => void>()
const subscribe = (cb: () => void) => {
listeners.add(cb)
return () => listeners.delete(cb)
}
function setLocal(next: Local) {
const recent = <T extends { day: string }>(rows: T[]) => [...rows].sort((a, b) => b.day.localeCompare(a.day)).slice(0, KEEP_DAYS)
local = { draws: recent(next.draws), logs: recent(next.logs) }
listeners.forEach((cb) => cb())
try {
if (local.draws.length || local.logs.length) localStorage.setItem(KEY, JSON.stringify(local))
else localStorage.removeItem(KEY)
} catch (e) {
console.warn('[fortune] 기기에 저장하지 못함', e)
}
}
const pad = (n: number) => String(n).padStart(2, '0')
function todayKst() {
const t = kst(new Date())
return `${t.y}-${pad(t.mo)}-${pad(t.d)}`
}
async function draw(regionCode: string, cardCode?: string, days: string[] = []): Promise<ResFortuneToday> {
const { data } = await drawFortune({ body: { region_code: regionCode, card_code: cardCode, days } })
if (!data.result?.success || !data.card) throw new Error(data.result?.desc ?? 'draw')
return data
}
/** 오늘 카드·행운·체크인. 로그인했으면 서버, 아니면 이 기기에 있는 오늘 카드로 행운만 서버에서 받는다 */
export function useTodayCard() {
const { loggedIn } = useAuth()
const { region } = useRegion()
const queryClient = useQueryClient()
const saved = useSyncExternalStore(subscribe, () => local)
const day = todayKst()
const mine = saved.draws.find((d) => d.day === day)
const pastDays = saved.draws.filter((d) => d.day < day).map((d) => d.day)
const serverKey = getFortuneTodayQueryKey({ query: { region: region.code } })
const deviceKey = ['fortuneDevice', region.code, mine?.card_code, day]
const server = useQuery({ ...getFortuneTodayOptions({ query: { region: region.code } }), enabled: loggedIn, staleTime: 5 * 60_000 })
const device = useQuery({
queryKey: deviceKey,
enabled: !loggedIn && !!mine,
staleTime: 5 * 60_000,
queryFn: () => draw(region.code, mine?.card_code, pastDays),
})
const pick = useMutation({
mutationFn: () => draw(region.code, undefined, loggedIn ? [] : pastDays),
onSuccess: (data) => {
track('fortune_draw', { card: data.card!.code })
if (loggedIn) {
queryClient.setQueryData(serverKey, data)
return
}
setLocal({ ...local, draws: [...local.draws.filter((d) => d.day !== data.day), { day: data.day!, card_code: data.card!.code }] })
queryClient.setQueryData(['fortuneDevice', region.code, data.card!.code, data.day], data)
},
})
// 로그인하면 이 기기에 있던 기록을 계정으로 옮긴다
const { mutate: moveUp } = useMutation({ ...importFortuneMutation() })
useEffect(() => {
if (!loggedIn || (!saved.draws.length && !saved.logs.length)) return
moveUp(
{ body: { draws: saved.draws, logs: saved.logs } },
{
onSuccess: (res) => {
if (!res.result?.success) return
setLocal(EMPTY)
queryClient.invalidateQueries({ queryKey: serverKey })
},
},
)
}, [loggedIn, saved, moveUp, queryClient, serverKey])
const today = loggedIn ? server.data : device.data
const log: DayLogData | LocalLog | undefined = (loggedIn ? today?.log : saved.logs.find((g) => g.day === day)) ?? undefined
const saveLog = useMutation({
mutationFn: async (v: Omit<LocalLog, 'day' | 'region_code'>) => {
const body = { ...v, region_code: region.code }
if (!loggedIn) {
setLocal({ ...local, logs: [...local.logs.filter((g) => g.day !== day), { ...body, day }] })
return
}
const { data } = await saveDayLog({ body })
if (!data.result?.success || !data.log) throw new Error(data.result?.desc ?? 'log')
queryClient.setQueryData(serverKey, (old: ResFortuneToday | undefined) => (old ? { ...old, log: data.log } : old))
},
onSuccess: (_, v) => track('day_log', { mood: v.mood, went_out: v.went_out, card_hit: v.card_hit ?? null }),
})
const loading = loggedIn ? server.isPending : !!mine && device.isPending
return { today, log, loading, pick, saveLog, loggedIn }
}
const shift = (day: string, n: number) => new Date(Date.parse(`${day}T00:00:00Z`) + n * 86_400_000).toISOString().slice(0, 10)
/** 서버 streak 과 같은 규칙: 오늘(안 뽑았으면 어제)부터 거꾸로 이어 뽑은 날 수, 하루 빠진 날은 7일에 한 번 봐준다 */
function localStreak(days: Set<string>, today: string) {
let d = days.has(today) ? today : shift(today, -1)
let count = 0
const rests: string[] = []
for (;;) {
if (days.has(d)) count++
else if (days.has(shift(d, -1)) && rests.every((r) => (Date.parse(r) - Date.parse(d)) / 86_400_000 >= 7)) rests.push(d)
else return count
d = shift(d, -1)
}
}
/** 아이콘 줄의 오늘 타로 표시: 오늘 뽑았는지, 이어 뽑은 날 수 (로그인 안 했으면 이 기기 기록으로, 서버를 부르지 않는다) */
export function useTarotBadge() {
const { loggedIn } = useAuth()
const { region } = useRegion()
const saved = useSyncExternalStore(subscribe, () => local)
const server = useQuery({ ...getFortuneTodayOptions({ query: { region: region.code } }), enabled: loggedIn, staleTime: 5 * 60_000 })
if (loggedIn) return { drawn: !!server.data?.card, streak: server.data?.streak ?? 0 }
const day = todayKst()
const days = new Set(saved.draws.map((d) => d.day))
return { drawn: days.has(day), streak: days.has(day) ? localStreak(days, day) : 0 }
}
/** 오늘 타로 창: 하루 한 장 뽑는 날씨 카드, 실제 날씨로 정한 행운, 연속 도장, 저녁엔 체크인 */
export function TarotSheet() {
const { today, log, loading, pick, saveLog, loggedIn } = useTodayCard()
const { open } = useSheet()
const shot = useRef<HTMLDivElement>(null)
const card = today?.card
const luck = today?.luck
const streak = today?.streak ?? 0
const filled = streak > 0 ? ((streak - 1) % STAMPS) + 1 : 0
const share = () => {
if (card && shot.current) open({ type: 'share', share: { title: `오늘 내 날씨 카드는 ${card.name}`, slides: [shot.current] } })
}
return (
<div className="px-4 pb-2">
{!card ? (
<button
type="button"
onClick={() => pick.mutate()}
disabled={loading || pick.isPending}
className="mx-auto flex w-full cursor-pointer flex-col items-center gap-2"
>
<img src="/fortune/back.webp" alt="" className={cx('aspect-[2/3] w-[150px] rounded-2xl object-cover', (loading || pick.isPending) && 'animate-pulse')} />
<span className="font-jua text-[16px] text-(--orange)">눌러서 오늘 카드 뽑기</span>
</button>
) : (
<div ref={shot} className="b-card-flip rounded-2xl bg-white">
<div className="flex gap-3">
<img src={`/fortune/${card.code}.webp`} alt={card.name} className="aspect-[2/3] w-[112px] shrink-0 rounded-xl object-cover" />
<div className="flex min-w-0 flex-col justify-center gap-1.5">
<b className="font-jua text-[22px] leading-tight font-normal">{card.name}</b>
<p className="m-0 text-[14px] leading-snug font-semibold text-(--ink2)">{card.reading}</p>
</div>
</div>
{luck && (
<dl className="m-0 mt-3 grid grid-cols-2 gap-1.5">
<Luck label="행운 시간" value={luck.time} sub="날씨가 가장 좋은 때" />
<Luck label="행운 장소" value={luck.place} />
<Luck label="행운 색" value={card.color} swatch={card.hex} />
<Luck label="오늘 1위" value={luck.top_gak} icon={luck.top_icon} />
</dl>
)}
<p className="m-0 mt-2 text-center text-[11px] font-semibold text-(--ink3)">재미로 보는 날씨 운세</p>
</div>
)}
{(streak > 0 || card) && (
<div className="mt-2.5 flex items-center gap-1.5">
{streak > 0 && (
<>
<span className="flex gap-1" aria-hidden>
{Array.from({ length: STAMPS }, (_, i) => (
<i key={i} className={cx('grid size-[18px] place-items-center rounded-full text-[10px] not-italic', i < filled ? 'bg-(--orange) text-white' : 'bg-[#ffe2cf]')}>
{i < filled ? '✓' : ''}
</i>
))}
</span>
<span className="text-xs font-bold text-(--ink2)">{streak}일째</span>
</>
)}
{card && (
<button type="button" onClick={share} className="ml-auto cursor-pointer rounded-full bg-(--ink) px-4 py-1.5 text-[13px] font-extrabold text-white">
공유
</button>
)}
</div>
)}
{card && today?.checkin_open && <CheckIn log={log} saving={saveLog.isPending} onSave={(v) => saveLog.mutate(v)} anon={!loggedIn} />}
</div>
)
}
function Luck({ label, value, sub, swatch, icon }: { label: string; value?: string | null; sub?: string; swatch?: string; icon?: string | null }) {
if (!value) return null
return (
<div className="rounded-xl bg-[#fff6ef] px-2.5 py-2">
<dt className="text-[11px] font-bold text-(--ink3)">{label}</dt>
<dd className="m-0 flex items-center gap-1 text-[14px] leading-tight font-extrabold">
{swatch && <span aria-hidden className="size-3 shrink-0 rounded-[4px] border border-black/10" style={{ background: swatch }} />}
{icon && <Ic name={icon} className="size-5 shrink-0" />}
<span className="truncate">{value}</span>
</dd>
{sub && <p className="m-0 text-[10.5px] font-semibold text-(--ink3)">{sub}</p>}
</div>
)
}
type LogInput = { mood: number; went_out: boolean; place_name?: string | null; place_ref?: string | null; card_hit?: boolean | null }
/** 저녁 체크인: 기분 하나, 다녀온 곳(목록에서 찾거나 직접), 오늘 카드 맞았나 */
function CheckIn({ log, saving, onSave, anon }: { log?: LogInput; saving: boolean; onSave: (v: LogInput) => void; anon: boolean }) {
const { region } = useRegion()
const [editing, setEditing] = useState(!log)
const [mood, setMood] = useState(log?.mood ?? 0)
const [place, setPlace] = useState(log?.place_name ?? '')
const [ref, setRef] = useState<string | null>(log?.place_ref ?? null)
const [stayed, setStayed] = useState(log ? !log.went_out : false)
const [hit, setHit] = useState<boolean | null>(log?.card_hit ?? null)
const [q, setQ] = useState('')
// 글자를 멈춘 뒤에 찾는다
useEffect(() => {
const t = setTimeout(() => setQ(ref ? '' : place.trim()), 250)
return () => clearTimeout(t)
}, [place, ref])
const found = useQuery({ ...searchFortunePlacesOptions({ query: { region: region.code, q } }), enabled: q.length > 0, select: (d) => d.items ?? [] })
if (log && !editing) {
return (
<button type="button" onClick={() => setEditing(true)} className="mt-3 flex w-full cursor-pointer items-center gap-2 rounded-xl bg-[#f3f6fb] px-3 py-2.5 text-left">
<span className="text-[22px] leading-none">{MOODS[log.mood - 1]}</span>
<span className="min-w-0 flex-1">
<b className="block text-[13.5px] font-extrabold">오늘 하루를 적어 뒀어요</b>
{log.place_name && <span className="block truncate text-xs font-semibold text-(--ink2)">{log.place_name}</span>}
</span>
</button>
)
}
const ready = mood > 0 && (stayed || place.trim().length > 0)
const save = () => {
onSave({ mood, went_out: !stayed, place_name: stayed ? null : place.trim(), place_ref: stayed ? null : ref, card_hit: hit })
setEditing(false)
}
const chip = (on: boolean) => cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold', on ? 'bg-(--ink) text-white' : 'bg-[#f3f6fb] text-(--ink2)')
return (
<div className="mt-3 border-t border-(--line) pt-3">
<p className="m-0 font-jua text-[17px]">오늘 하루 어땠어요?</p>
<div className="mt-2 flex justify-between">
{MOODS.map((m, i) => (
<button key={m} type="button" onClick={() => setMood(i + 1)} aria-pressed={mood === i + 1} className={cx('grid size-11 cursor-pointer place-items-center rounded-full text-[24px]', mood === i + 1 ? 'bg-[#ffe2cf] ring-2 ring-(--orange)' : 'bg-[#f3f6fb]')}>
{m}
</button>
))}
</div>
<p className="m-0 mt-3.5 text-[14px] font-extrabold">어디 다녀왔어요?</p>
<div className="relative mt-1.5 flex gap-1.5">
<input
value={place}
onChange={(e) => {
setPlace(e.target.value.slice(0, 40))
setRef(null)
setStayed(false)
}}
placeholder="장소 이름"
disabled={stayed}
className="min-w-0 flex-1 rounded-xl border border-(--line) bg-white px-3 py-2 text-[14px] font-semibold disabled:opacity-50"
/>
<button
type="button"
onClick={() => {
setStayed(!stayed)
setPlace('')
setRef(null)
}}
aria-pressed={stayed}
className={chip(stayed)}
>
안 나갔어요
</button>
{!stayed && !ref && (found.data?.length ?? 0) > 0 && (
<ul className="absolute top-full right-0 left-0 z-10 m-0 mt-1 max-h-48 list-none overflow-auto rounded-xl border border-(--line) bg-white p-1 shadow-lg">
{found.data!.map((p) => (
<li key={p.ref}>
<button
type="button"
onClick={() => {
setPlace(p.name)
setRef(p.ref)
}}
className="w-full cursor-pointer rounded-lg px-2.5 py-2 text-left text-[14px] font-semibold hover:bg-[#f3f6fb]"
>
{p.name}
</button>
</li>
))}
</ul>
)}
</div>
<p className="m-0 mt-3.5 text-[14px] font-extrabold">오늘 카드, 맞았어요?</p>
<div className="mt-1.5 flex gap-1.5">
<button type="button" onClick={() => setHit(hit === true ? null : true)} aria-pressed={hit === true} className={chip(hit === true)}>
맞았어요
</button>
<button type="button" onClick={() => setHit(hit === false ? null : false)} aria-pressed={hit === false} className={chip(hit === false)}>
글쎄요
</button>
</div>
<button type="button" onClick={save} disabled={!ready || saving} className="mt-3.5 w-full cursor-pointer rounded-full bg-(--orange) py-2.5 text-[14px] font-extrabold text-white disabled:opacity-40">
적어 두기
</button>
{anon && <p className="m-0 mt-2 text-center text-[11.5px] font-semibold text-(--ink3)">이 기기에만 남아요. 로그인하면 폰을 바꿔도 남아요.</p>}
</div>
)
}
+1
View File
@@ -32,6 +32,7 @@ export function InstallBanner() {
type="button"
onClick={() => {
dismiss()
track('install_banner_close', {})
setClosed(true)
}}
aria-label="닫기"
+192
View File
@@ -0,0 +1,192 @@
import { useEffect, useRef } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { attendMutation, myLevelOptions, myLevelQueryKey, sharedMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ResLevel } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { useSheet } from './sheetContext'
import { Ic } from './ui'
// 레벨마다 보여 줄 하늘 아이콘 (이름은 서버 LEVELS)
const LEVEL_ICON = ['droplet', 'sun', 'leaf', 'rainbow', 'sunset', 'milky_way', 'shooting_star']
export const levelIcon = (level: number) => LEVEL_ICON[Math.min(Math.max(level, 1), LEVEL_ICON.length) - 1]
const SEEN_KEY = 'nalssigak.b.levelSeen'
/** 서버 응답에서 기본값이 있는 칸은 생략될 수 있어 채워 둔다 */
export type Level = ResLevel & { points: number; level: number; floor: number; streak: number }
const toLevel = (d: ResLevel): Level | undefined => (d.result?.success ? { ...d, points: d.points ?? 0, level: d.level ?? 1, floor: d.floor ?? 0, streak: d.streak ?? 0 } : undefined)
/** 내 레벨 (로그인했을 때만). 각을 주는 일은 모두 mutation 이라 끝날 때마다 다시 받는다(main.tsx) */
export function useLevel() {
const { loggedIn } = useAuth()
return useQuery({ ...myLevelOptions(), enabled: loggedIn, staleTime: 60_000, select: toLevel })
}
/** 다음 레벨까지 진행률 0~1 */
export function progress(l: Level) {
if (l.next_points == null) return 1
return Math.min(1, (l.points - l.floor) / (l.next_points - l.floor))
}
/** 다음 레벨에서 열리는 것 이름 */
export const nextUnlock = (l: Level) => (l.unlocks ?? []).filter((u) => u.level === l.level + 1).map((u) => u.name)
/** 로그인한 사람이 앱을 열면 하루 한 번 출석 각. 레벨이 오르면 축하 창을 띄운다 (레이아웃에 한 번 둔다) */
export function LevelWatcher() {
const { loggedIn, me } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const level = useLevel().data
const { mutate } = useMutation({ ...attendMutation() })
const attended = useRef<string | null>(null)
useEffect(() => {
if (!loggedIn || !me || attended.current === me.login_id) return
attended.current = me.login_id
mutate({}, { onSuccess: (res) => res.result?.success && queryClient.setQueryData(myLevelQueryKey(), res) })
}, [loggedIn, me, mutate, queryClient])
useEffect(() => {
if (!level || !me) return
const key = `${SEEN_KEY}.${me.login_id}`
let seen: number | null = null
try {
seen = Number(localStorage.getItem(key)) || null
localStorage.setItem(key, String(level.level))
} catch (e) {
console.warn('[level] 본 레벨을 저장하지 못함', e)
}
// 처음 보는 기기에선 축하하지 않는다 (예전 레벨을 모름)
if (seen != null && level.level > seen) open({ type: 'levelUp', level: level.level })
}, [level, me, open])
return null
}
/** 공유를 마치면 하루 한 번 각 (로그인했을 때만) */
export function useShareReward() {
const { loggedIn } = useAuth()
const { mutate } = useMutation({ ...sharedMutation() })
return () => {
if (loggedIn) mutate({})
}
}
/** 헤더 아바타 옆 작은 레벨 표시 */
export function LevelBadge() {
const level = useLevel().data
if (!level) return null
return <span className="pointer-events-none absolute -right-1.5 -bottom-1.5 rounded-full bg-(--ink) px-1.5 text-[9.5px] leading-4 font-extrabold text-white ring-2 ring-white">Lv.{level.level}</span>
}
function Bar({ value }: { value: number }) {
return (
<span className="block h-2 overflow-hidden rounded-full bg-[#eef1f6]">
<span className="block h-full rounded-full bg-[linear-gradient(90deg,#ffb27a,var(--orange))]" style={{ width: `${Math.round(value * 100)}%` }} />
</span>
)
}
/** 내 정보 위쪽: 레벨·모은 각·다음 레벨에서 열리는 것. link 가 있으면 '각 모으는 법'으로 내 레벨 창을 연다 */
export function LevelCard({ link = true }: { link?: boolean }) {
const level = useLevel().data
const { open } = useSheet()
if (!level) return null
const unlock = nextUnlock(level)
return (
<section aria-label="내 레벨" className="rounded-2xl bg-[#fff6ef] px-3.5 py-3">
<div className="flex items-center gap-2">
<Ic name={levelIcon(level.level)} className="size-7" />
<b className="font-jua text-[16px] font-normal">
Lv.{level.level} {level.name}
</b>
<b className="ml-auto font-bagel text-[15px] font-normal">{level.points}각</b>
</div>
<div className="mt-2">
<Bar value={progress(level)} />
</div>
<div className="mt-1.5 flex items-center justify-between gap-2 text-xs font-bold text-(--ink2)">
<span>
{level.next_points != null ? `${level.next_points - level.points}각 더 모으면 Lv.${level.level + 1} ${level.next_name}` : '가장 높은 레벨이에요'}
{unlock.length > 0 && <b className="text-(--orange)"> · {unlock.join(', ')}</b>}
</span>
{link && (
<button type="button" onClick={() => open({ type: 'level' })} className="shrink-0 cursor-pointer text-(--orange)">
각 모으는 법 ›
</button>
)}
</div>
</section>
)
}
/** 내 레벨 창: 오늘 받을 수 있는 각, 레벨마다 열리는 것 */
export function LevelSheet() {
const level = useLevel().data
if (!level) return null
const steps = (level.unlocks ?? []).reduce<Record<number, string[]>>((m, u) => ({ ...m, [u.level]: [...(m[u.level] ?? []), u.name] }), {})
return (
<div className="flex flex-col gap-4 px-4 pb-4">
<LevelCard link={false} />
<section>
<h4 className="m-0 mb-2 text-sm font-extrabold">오늘 받을 수 있는 각</h4>
<ul className="m-0 list-none rounded-2xl bg-white p-0 shadow-[inset_0_-4px_0_var(--shade)]">
{(level.today ?? []).map((a) => {
const done = a.earned >= a.cap
return (
<li key={a.action} className="flex items-center gap-2.5 border-b border-[#eef1f6] px-3.5 py-2.5 text-[13.5px] font-bold last:border-0">
<span className={cx('grid size-5 place-items-center rounded-full text-[11px] text-white', done ? 'bg-[#1f9d62]' : 'bg-[#dfe5ef]')}>{done ? '✓' : ''}</span>
<span className={cx(done && 'text-(--ink3) line-through')}>{a.name}</span>
<span className="ml-auto font-bagel text-[13px] font-normal text-(--orange)">
{a.earned > 0 && a.cap > a.points ? `${a.earned}/${a.cap}` : `+${a.points}`}각
</span>
</li>
)
})}
</ul>
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">{level.streak > 0 ? `${level.streak}일 이어 출석 · 7일마다 +50각` : '7일 이어 출석하면 +50각'}</p>
</section>
<section>
<h4 className="m-0 mb-2 text-sm font-extrabold">레벨이 오르면 열려요</h4>
<ol className="m-0 flex list-none flex-col gap-1.5 p-0">
{(level.levels ?? []).map(({ level: lv, name, points }) => {
const reached = level.level >= lv
return (
<li key={lv} className={cx('flex items-center gap-2.5 rounded-xl px-2.5 py-2', lv === level.level ? 'bg-[#fff6ef]' : '')}>
<Ic name={levelIcon(lv)} className={cx('size-7', !reached && 'opacity-40 grayscale')} />
<span className="min-w-0 flex-1">
<b className="block text-[13.5px] font-extrabold">
Lv.{lv} {name} <span className="font-semibold text-(--ink3)">· {points}각</span>
</b>
<span className="block text-xs font-semibold text-(--ink2)">{lv === 1 ? '지금 있는 기능 전부' : (steps[lv] ?? []).join(', ')}</span>
</span>
</li>
)
})}
</ol>
</section>
</div>
)
}
/** 레벨이 오른 순간 */
export function LevelUpSheet({ level: lv }: { level: number }) {
const level = useLevel().data
const { open } = useSheet()
const opened = (level?.unlocks ?? []).filter((u) => u.level === lv).map((u) => u.name)
const name = level?.levels?.find((l) => l.level === lv)?.name
return (
<div className="flex flex-col items-center gap-2 px-6 pt-2 pb-6 text-center">
<Ic name={levelIcon(lv)} className="size-24" />
<b className="font-jua text-[28px] font-normal">
Lv.{lv} {name}
</b>
{opened.length > 0 && <p className="m-0 text-[15px] font-bold text-(--ink2)">새로 열렸어요: {opened.join(', ')}</p>}
<button type="button" onClick={() => open({ type: 'level' })} className="mt-3 w-full cursor-pointer rounded-full bg-(--orange) py-3 text-[15px] font-extrabold text-white">
내 레벨 보기
</button>
</div>
)
}
+1 -1
View File
@@ -2,7 +2,7 @@ import type { CSSProperties } from 'react'
import { ARTICLE_LABEL } from '@nalssigak/shared/lib'
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental', 'ginkgo'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert', 'crystal_ball', 'tshirt', 'clapper', 'speech', 'droplet', 'leaf', 'rainbow', 'milky_way', 'shooting_star'])
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
export function iconSrc(name: string) {
+12 -1
View File
@@ -7,6 +7,7 @@ import type { MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.g
import { useAuth } from './authContext'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { track } from '../lib/analytics'
const KEY = 'nalssigak.b.myRule'
@@ -121,7 +122,16 @@ export function useMyGak() {
const create = (g: MyGak, onDone?: () => void) => {
const item = { name: gakName(g.name), icon: g.icon, rule: g.rule }
if (loggedIn) {
add.mutate({ body: item }, { onSuccess: (res) => res.result?.success && onDone?.() })
add.mutate(
{ body: item },
{
onSuccess: (res) => {
if (!res.result?.success) return
track('my_gak_save', { gak_name: item.name })
onDone?.()
},
},
)
return
}
if (saved) {
@@ -129,6 +139,7 @@ export function useMyGak() {
return
}
setLocal(item)
track('my_gak_save', { gak_name: item.name })
onDone?.()
}
+6 -1
View File
@@ -2,6 +2,7 @@ import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { PostReaction, ResFeed } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics'
export type PinnedKey = 'hero_post' | 'gak_post' | 'foliage_post' | 'events_post' | 'season_post'
@@ -29,7 +30,11 @@ export function usePinnedLike(key: PinnedKey, r?: PostReaction | null) {
;(on ? like : unlike).mutate(
{ path: { post_id: r.post_id } },
{
onSuccess: (res) => (res.result?.success ? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) }) : revert()),
onSuccess: (res) => {
if (!res.result?.success) return revert()
patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) })
if (on) track('like', { content_type: key, item_id: r.post_id })
},
onError: revert,
},
)
+4
View File
@@ -21,6 +21,10 @@ export type SheetState =
| { type: 'install' }
| { type: 'weatherWhy'; why: WeatherWhyPayload }
| { type: 'talk'; talk: TalkData }
| { type: 'tarot' }
| { type: 'ootd' }
| { type: 'level' }
| { type: 'levelUp'; level: number }
| { type: 'gameHelp' }
| null
+12 -6
View File
@@ -21,6 +21,7 @@ import { topicName, TOPICS, useMyTalks } from './talkState'
import { useSheet } from './sheetContext'
import { CameraIcon, HeartIcon } from './svg'
import { Avatar, Rail, TAP44 } from './ui'
import { track } from '../lib/analytics'
const BODY_MAX = 100
const PHOTO_MAX = 10 * 1024 * 1024
@@ -106,6 +107,7 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
{
onSuccess: (res) => {
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
track('talk_post', { topic, with_image: !!image })
setText('')
setPhoto(null)
setTopic(TalkTopic.LOCAL)
@@ -216,7 +218,10 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
{ path: { talk_id: t.talk_id } },
{
onSuccess: (res) => {
if (res.result?.success && res.like_count != null) return setCount(res.like_count)
if (res.result?.success && res.like_count != null) {
if (next) track('like', { content_type: 'talk', item_id: t.talk_id })
return setCount(res.like_count)
}
setLiked(!next)
setCount(t.like_count)
},
@@ -229,14 +234,15 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
}
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
const after = {
const after = (done?: () => void) => ({
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true)
done?.()
setMenu('done')
refresh()
},
onError: () => setFailed(true),
}
})
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }))
const src = t.image?.startsWith('/v1/') ? API_BASE_URL + t.image : (t.image ?? undefined)
@@ -272,7 +278,7 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
) : 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 type="button" onClick={() => remove.mutate({ path: { talk_id: t.talk_id } }, after(() => 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">
@@ -285,13 +291,13 @@ function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; com
</button>
) : menu === 'report' ? (
REASONS.map(([reason, label]) => (
<button key={reason} type="button" onClick={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after)} disabled={report.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
<button key={reason} type="button" onClick={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after(() => track('report', { content_type: 'talk', reason })))} disabled={report.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
{label}
</button>
))
) : (
<>
<button type="button" onClick={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after))} disabled={block.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
<button type="button" onClick={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after(() => track('block', { content_type: 'talk' }))))} disabled={block.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
이 사람 글 안 보기
</button>
<button type="button" onClick={() => guard(() => setMenu('report'))} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
+136
View File
@@ -0,0 +1,136 @@
import { useState, type ReactNode } from 'react'
import { Link } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { getPostOptions, latestCardOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { kst } from '@nalssigak/shared/lib'
import { track } from '../lib/analytics'
import { useFoliage } from './foliage'
import { useTarotBadge } from './fortune'
import { PostCard, PostCardSkel } from './Post'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Ic, Rail } from './ui'
/** 오늘 탭 '내 각' 줄 자리 (아이콘에서 거기로 내려간다) */
export const MY_GAK_ID = 'my-gak'
const OOTD_SEEN = 'nalssigak.b.ootdSeen'
function readSeen() {
try {
return Number(localStorage.getItem(OOTD_SEEN)) || null
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 매번 새로 보는 것으로
return null
}
}
function markSeen(postId: number) {
try {
localStorage.setItem(OOTD_SEEN, String(postId))
} catch (e) {
console.warn('[ootd] 본 코디를 저장하지 못함', e)
}
}
function isToday(iso?: string | null) {
if (!iso) return false
const a = kst(iso)
const b = kst(new Date())
return a.y === b.y && a.mo === b.mo && a.d === b.d
}
const useLatestOotd = () => useQuery({ ...latestCardOptions({ query: { template: 'ootd' } }), staleTime: 10 * 60_000 })
type Item = { key: string; label: string; icon: string; badge?: ReactNode; to?: string; onClick?: () => void }
const Dot = () => <span className="absolute -top-0.5 -right-0.5 size-[11px] rounded-full border-2 border-white bg-[#ff4d4f]" />
/** 오늘 탭 히어로 아래 아이콘 줄: 누르면 창이 뜨거나 그 페이지로 간다. 오늘 아직 안 본 것엔 빨간 점 */
export function TodayIcons() {
const { open } = useSheet()
const tarot = useTarotBadge()
const ootd = useLatestOotd().data
const [seen, setSeen] = useState(readSeen)
const { inSeason } = useFoliage()
const newOotd = !!ootd?.post_id && isToday(ootd.published_at) && seen !== ootd.post_id
const items: Item[] = [
{
key: 'tarot',
label: '오늘 타로',
icon: 'crystal_ball',
badge: tarot.drawn ? (
<span className="absolute -bottom-1.5 left-1/2 -translate-x-1/2 rounded-full bg-(--orange) px-1.5 text-[9.5px] leading-4 font-extrabold whitespace-nowrap text-white">{tarot.streak}일째</span>
) : (
<Dot />
),
onClick: () => open({ type: 'tarot' }),
},
{
key: 'ootd',
label: '오늘 코디',
icon: 'tshirt',
badge: newOotd ? <Dot /> : null,
onClick: () => {
if (ootd?.post_id) {
markSeen(ootd.post_id)
setSeen(ootd.post_id)
}
open({ type: 'ootd' })
},
},
...(inSeason ? [{ key: 'foliage', label: '단풍 지도', icon: 'maple', to: '/foliage' }] : []),
{ key: 'shorts', label: '쇼츠', icon: 'clapper', to: '/shorts' },
{ key: 'myGak', label: '내 각', icon: 'rabbit', onClick: () => document.getElementById(MY_GAK_ID)?.scrollIntoView({ behavior: 'smooth', block: 'start' }) },
{ key: 'talk', label: '동네 이야기', icon: 'speech', to: '/talk' },
]
const tile = (it: Item) => (
<>
<span className="relative grid size-[52px] place-items-center rounded-[17px] bg-white shadow-[inset_0_-4px_0_var(--shade)]">
<Ic name={it.icon} className="size-8" />
{it.badge}
</span>
<span className="mt-1.5 text-[11.5px] font-extrabold whitespace-nowrap text-(--ink2)">{it.label}</span>
</>
)
const cls = 'flex w-[60px] cursor-pointer flex-col items-center'
return (
<Rail label="바로 가기" className="pb-2">
{items.map((it) =>
it.to ? (
<Link key={it.key} to={it.to} onClick={() => track('today_icon', { icon: it.key })} className={cls}>
{tile(it)}
</Link>
) : (
<button
key={it.key}
type="button"
onClick={() => {
track('today_icon', { icon: it.key })
it.onClick?.()
}}
className={cls}
>
{tile(it)}
</button>
),
)}
</Rail>
)
}
/** 오늘 코디 창: 오늘 피드에 올린 코디 카드 (오늘 것이 없으면 안내) */
export function OotdSheet() {
const { region } = useRegion()
const latest = useLatestOotd()
const postId = latest.data?.post_id
const today = isToday(latest.data?.published_at)
const post = useQuery({ ...getPostOptions({ path: { post_id: postId ?? 0 }, query: { region: region.code } }), enabled: !!postId && today })
if (latest.isPending || (postId && today && post.isPending)) return <PostCardSkel />
if (!postId || !today || !post.data?.post) return <p className="m-0 px-4 py-10 text-center text-[14px] font-semibold text-(--ink2)">아직 오늘 코디가 없어요</p>
return <PostCard post={post.data.post} />
}
+2
View File
@@ -1,6 +1,7 @@
import { useState } from 'react'
import { IS_TOSS } from '../lib/platform'
import { Ic } from './ui'
import { track } from '../lib/analytics'
const KEY = 'nalssigak.b.tossIntroSeen'
@@ -29,6 +30,7 @@ export function TossIntro() {
} catch (e) {
console.warn('[intro] 본 기록을 저장하지 못함', e)
}
track('toss_intro_start', {})
setOpen(false)
}
+24
View File
@@ -1,3 +1,6 @@
import type { PinnedKey } from '../b/pinnedLike'
import type { SheetState } from '../b/sheetContext'
/** GA4로 보내는 이벤트와 값. 목록은 docs/이벤트_추적.md */
type Events = {
view_gak: { index_id: number; gak_name: string; score: number; rank: number }
@@ -11,8 +14,29 @@ type Events = {
install_choice: { outcome: 'accepted' | 'dismissed' }
install_done: Record<string, never>
app_launch: { mode: 'standalone' }
sheet_open: { sheet: SheetType }
like: { content_type: 'post' | 'comment' | 'talk' | PinnedKey; item_id: number }
comment: { post_id: number }
report: { content_type: 'comment' | 'talk'; reason: number }
block: { content_type: 'comment' | 'talk' }
terms_agree: Record<string, never>
talk_post: { topic: number; with_image: boolean }
hero_day_switch: { day: 'today' | 'tomorrow' }
shorts_open: { video_id: string }
shorts_view: { video_id: string; index: number }
shorts_sound: { on: boolean }
foliage_open: Record<string, never>
foliage_spot: { spot_name: string; from: 'page' | 'card' }
my_gak_save: { gak_name: string }
fortune_draw: { card: string }
day_log: { mood: number; went_out: boolean; card_hit: boolean | null }
today_icon: { icon: string }
toss_intro_start: Record<string, never>
install_banner_close: Record<string, never>
}
type SheetType = Exclude<SheetState, null>['type']
declare global {
interface Window {
gtag?: (command: 'event', name: string, params: Record<string, unknown>) => void
+5 -2
View File
@@ -1,4 +1,5 @@
import { keepPreviousData, QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { keepPreviousData, MutationCache, QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
@@ -11,8 +12,10 @@ import { track } from './lib/analytics'
for (const type of ['gesturestart', 'gesturechange']) document.addEventListener(type, (e) => e.preventDefault(), { passive: false })
// 칩·지역·검색어를 바꿔 다시 받는 동안 이전 결과를 그대로 두어 화면이 비거나 접히지 않게 한다
const queryClient = new QueryClient({
const queryClient: QueryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, refetchOnWindowFocus: false, placeholderData: keepPreviousData } },
// 각을 주는 일(타로·좋아요·댓글·글·체크인·공유)은 모두 mutation 이라, 끝나면 내 레벨을 다시 받는다
mutationCache: new MutationCache({ onSuccess: () => queryClient.invalidateQueries({ queryKey: myLevelQueryKey() }) }),
})
// 홈 화면 설치 조건(서비스 워커)과, 홈 화면 아이콘으로 연 횟수