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

This commit is contained in:
minaChoi committed 2026-10-28 17:19:57 +09:00
commit 239a22ee06
139 files changed
+7645 -59

No files matched your search

+14 -6
View File
@@ -12,13 +12,15 @@
</script>
<script>
// 이미 열었던 탭을 다시 열면 브라우저가 예전 HTML 을 다시 쓰고, 그 HTML 이 부르는 예전 빌드 파일은 배포로 지워져 첫 화면에서 멈춘다.
// 빌드 파일을 못 받았거나 12초 지나도 첫 화면이 그대로면 한 번만 새로 불러온다 (30초 안에 또 하지는 않는다)
// 돌아왔을 때 망이 아직 안 붙어 다시 불러온 것까지 실패하기도 하니, 첫 화면이 남아 있는 동안은 계속 다시 시도한다:
// 빌드 파일을 못 받았을 때, 12초마다, 탭을 다시 볼 때, 망이 다시 붙을 때 (10초 안에 또 하지는 않는다)
(function () {
var KEY = 'nalssigak.bootReload'
function reloadOnce() {
function retry() {
if (!document.getElementById('boot') || document.hidden) return
try {
var last = Number(sessionStorage.getItem(KEY) || 0)
if (Date.now() - last < 30000) return
if (Date.now() - last < 10000) return
sessionStorage.setItem(KEY, String(Date.now()))
} catch (e) {
console.error('[boot] storage', e)
@@ -27,11 +29,17 @@
}
window.addEventListener('error', function (e) {
var el = e.target
if (el && (el.tagName === 'SCRIPT' || el.tagName === 'LINK') && /\/assets\//.test(el.src || el.href || '')) reloadOnce()
if (el && (el.tagName === 'SCRIPT' || el.tagName === 'LINK') && (el.src || el.href || '').indexOf(location.origin + '/') === 0) retry()
}, true)
setTimeout(function () {
if (document.getElementById('boot')) reloadOnce()
var timer = setInterval(function () {
if (document.getElementById('boot')) retry()
else clearInterval(timer)
}, 12000)
document.addEventListener('visibilitychange', retry)
window.addEventListener('online', retry)
window.addEventListener('pageshow', function (e) {
if (e.persisted) retry()
})
})()
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4414665130371841" crossorigin="anonymous"></script>
+2
View File
@@ -17,6 +17,7 @@
"@tailwindcss/vite": "^4.3.3",
"@tanstack/react-query": "^5.104.0",
"embla-carousel-react": "^8.6.0",
"matter-js": "^0.20.0",
"modern-screenshot": "^4.7.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
@@ -25,6 +26,7 @@
},
"devDependencies": {
"@hey-api/openapi-ts": "0.99.0",
"@types/matter-js": "^0.20.2",
"@types/node": "^24.13.3",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.7",
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+4
View File
@@ -1,6 +1,8 @@
import { BrowserRouter, Route, Routes } from 'react-router'
import { BLayout } from './b/BLayout'
import { CloudMergePage } from './b/CloudMergePage'
import { FoliagePage } from './b/FoliagePage'
import { SajuPage } from './b/SajuPage'
import { GakPage } from './b/GakPage'
import { SeasonPage } from './b/SeasonPage'
import { ShortsPage } from './b/Shorts'
@@ -22,8 +24,10 @@ export default function App() {
<Route path="week" element={<WeekPage />} />
<Route path="season" element={<SeasonPage />} />
<Route path="foliage" element={<FoliagePage />} />
<Route path="saju" element={<SajuPage />} />
<Route path="talk" element={<TalkPage />} />
<Route path="shorts/:id?" element={<ShortsPage />} />
<Route path="game" element={<CloudMergePage />} />
<Route path="*" element={<TodayPage />} />
</Route>
</Routes>
+4 -1
View File
@@ -9,6 +9,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'
@@ -74,8 +75,9 @@ function TopBar() {
{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">
@@ -317,6 +319,7 @@ export function BLayout() {
<SheetProvider>
<Shell />
<TossIntro />
<LevelWatcher />
</SheetProvider>
</RegionProvider>
</AuthProvider>
+325
View File
@@ -0,0 +1,325 @@
import { useEffect, useRef, useState, type PointerEvent } from 'react'
import { createPortal } from 'react-dom'
import { useNavigate } from 'react-router'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { getWeatherTodayOptions, myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { gameRound, gameStart } from '@nalssigak/shared/api/client/sdk.gen'
import type { ResLevel } from '@nalssigak/shared/api/client/types.gen'
import { kst } from '@nalssigak/shared/lib'
import { slotAt } from '@nalssigak/shared/lib/weatherText'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { createGame, DROP_Y, H, LEVELS, LINE_Y, loadBest, randomLevel, roundTarget, saveBest, W, windDir, type Game } from './cloudMerge'
import { useLevel } from './level'
import { iconSrc } from './lib'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Ic, TAP44 } from './ui'
const gameEarned = (l: ResLevel | undefined) => l?.today?.find((a) => a.action === 'game')
/** 라운드를 깨면 서버에 알려 각을 받는다. 내 레벨은 판이 끝날 때 한 번에 바꿔, 게임 중에 레벨업 창이 뜨지 않게 한다 */
async function claimRound(play: string, round: number) {
try {
const { data } = await gameRound({ body: { play, round } })
return data.result?.success ? data : undefined
} catch (e) {
console.warn('[game] 라운드 각을 받지 못함', e)
return undefined
}
}
const images = LEVELS.map((l) => {
const img = new Image()
img.src = iconSrc(l.icon) ?? ''
return img
})
/** 부딪히는 원이 보이게 동그란 방울을 그리고 그 안에 그림 */
function bubble(ctx: CanvasRenderingContext2D, level: number, x: number, y: number, angle = 0) {
const { r, color } = LEVELS[level]
ctx.save()
ctx.translate(x, y)
ctx.beginPath()
ctx.arc(0, 0, r, 0, Math.PI * 2)
ctx.fillStyle = color
ctx.fill()
ctx.lineWidth = 2
ctx.strokeStyle = 'rgb(255 255 255 / 0.9)'
ctx.stroke()
ctx.rotate(angle)
const s = r * 1.5
ctx.drawImage(images[level], -s / 2, -s / 2, s, s)
ctx.restore()
}
function draw(ctx: CanvasRenderingContext2D, game: Game, aimX: number | null, next: number, danger: boolean) {
ctx.clearRect(0, 0, W, H)
ctx.setLineDash([6, 6])
ctx.strokeStyle = danger ? '#e5484d' : 'rgb(40 48 74 / 0.18)'
ctx.lineWidth = 2
ctx.beginPath()
ctx.moveTo(0, LINE_Y)
ctx.lineTo(W, LINE_Y)
ctx.stroke()
if (aimX != null) {
const r = LEVELS[next].r
const x = Math.min(Math.max(aimX, r), W - r)
ctx.strokeStyle = 'rgb(40 48 74 / 0.12)'
ctx.beginPath()
ctx.moveTo(x, DROP_Y)
ctx.lineTo(x, H)
ctx.stroke()
ctx.globalAlpha = 0.85
bubble(ctx, next, x, DROP_Y)
ctx.globalAlpha = 1
}
ctx.setLineDash([])
for (const p of game.pieces()) {
bubble(ctx, p.level, p.position.x, p.position.y, p.angle)
}
}
/** 구름 합치기: 같은 날씨끼리 합쳐 해까지. 지금 고른 구의 풍속만큼 떨어지는 동안 옆으로 밀린다 */
export function CloudMergePage() {
const navigate = useNavigate()
const { region } = useRegion()
const { open } = useSheet()
const { loggedIn } = useAuth()
const queryClient = useQueryClient()
const level = useLevel().data
const [earned, setEarned] = useState<number | null>(null)
const [gain, setGain] = useState(0)
const baseRef = useRef<number | undefined>(undefined)
useEffect(() => {
baseRef.current = gameEarned(level)?.earned
}, [level])
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
const [now] = useState(() => kst(new Date()))
const slots = today.data?.slots ?? []
const windMs = slots.length ? (slotAt(slots, now.h).wind_ms ?? 0) : 0
const dir = windDir(now.d)
const canvasRef = useRef<HTMLCanvasElement>(null)
const gameRef = useRef<Game | null>(null)
const aimRef = useRef<number | null>(W / 2)
const [next, setNext] = useState(randomLevel)
const nextRef = useRef(next)
const coolRef = useRef(0)
const [score, setScore] = useState(0)
const [best, setBest] = useState(loadBest)
const [over, setOver] = useState(false)
const [play, setPlay] = useState(0)
const [round, setRound] = useState(1)
const [roundGot, setRoundGot] = useState(0)
const [flash, setFlash] = useState(false)
useEffect(() => {
if (!today.isSuccess) return
const canvas = canvasRef.current
const ctx = canvas?.getContext('2d')
if (!canvas || !ctx) return
const ratio = window.devicePixelRatio || 1
canvas.width = W * ratio
canvas.height = H * ratio
ctx.scale(ratio, ratio)
let roundNo = 1
let base = 0
let flashTimer: ReturnType<typeof setTimeout> | undefined
let ticket: Promise<string | undefined> = Promise.resolve(undefined)
let lastLevel: ResLevel | undefined
let gotSoFar = baseRef.current
const settle = () => {
if (lastLevel) queryClient.setQueryData(myLevelQueryKey(), lastLevel)
lastLevel = undefined
}
if (loggedIn) {
ticket = gameStart()
.then(({ data }) => data.play ?? undefined)
.catch((e: unknown) => {
console.warn('[game] 판을 열지 못함', e)
return undefined
})
}
const claim = async (round: number) => {
const token = await ticket
if (!token) return
const res = await claimRound(token, round)
const now = gameEarned(res)?.earned
if (!res || now == null) return
lastLevel = res
if (gotSoFar != null && now > gotSoFar) setGain(now - gotSoFar)
gotSoFar = now
setEarned(now)
}
const game = createGame(windMs, dir, {
onScore: (s) => {
setScore(s)
if (s - base >= roundTarget(roundNo)) {
roundNo += 1
base = s
setRound(roundNo)
setFlash(true)
setGain(0)
clearTimeout(flashTimer)
flashTimer = setTimeout(() => setFlash(false), 1400)
void claim(roundNo - 1)
}
setRoundGot(s - base)
if (s > loadBest()) {
saveBest(s)
setBest(s)
}
},
onOver: () => {
setOver(true)
settle()
},
})
gameRef.current = game
let last = performance.now()
let raf = 0
const loop = (t: number) => {
game.step(t - last, t)
last = t
draw(ctx, game, aimRef.current, nextRef.current, game.danger())
raf = requestAnimationFrame(loop)
}
raf = requestAnimationFrame(loop)
return () => {
cancelAnimationFrame(raf)
clearTimeout(flashTimer)
game.destroy()
settle()
gameRef.current = null
}
}, [today.isSuccess, windMs, dir, play, loggedIn, queryClient])
const toX = (e: PointerEvent<HTMLCanvasElement>) => {
const rect = e.currentTarget.getBoundingClientRect()
return ((e.clientX - rect.left) / rect.width) * W
}
const onMove = (e: PointerEvent<HTMLCanvasElement>) => {
aimRef.current = toX(e)
}
const onUp = (e: PointerEvent<HTMLCanvasElement>) => {
const game = gameRef.current
if (!game || over || performance.now() < coolRef.current) return
game.drop(nextRef.current, toX(e))
coolRef.current = performance.now() + 450
nextRef.current = randomLevel()
setNext(nextRef.current)
}
const restart = () => {
setScore(0)
setOver(false)
setRound(1)
setRoundGot(0)
setPlay((n) => n + 1)
}
const cap = gameEarned(level)?.cap ?? 20
const todayGak = earned ?? gameEarned(level)?.earned ?? 0
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
const windText = windMs < 0.5 ? '바람 없음' : `${dir > 0 ? '→' : '←'} 초속 ${windMs.toFixed(1)}m`
// 스택 화면: 머리줄·탭을 덮게 body 로 띄운다(main 이 쌓임 순서를 가둬서). b-app 의 낮 색을 그대로 써 밤에도 밝은 바탕
return createPortal(
<div className="b-app fixed inset-0 z-[45] touch-none bg-[linear-gradient(#d9edff,#f5faff)]">
<div className="mx-auto flex h-full max-w-[440px] flex-col pt-[env(safe-area-inset-top,0px)] pb-[calc(10px+env(safe-area-inset-bottom,0px))] text-(--ink)">
<div className="flex items-center gap-1 px-3 pt-2">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<div className="min-w-0 flex-1 px-1">
<h2 className="m-0 font-jua text-[22px] leading-tight font-normal">구름 합치기</h2>
<p className="m-0 flex items-center gap-1 text-[12px] font-extrabold opacity-75">
<Ic name="cloud" className="size-4" />
{region.short_name} {windText}
</p>
</div>
<button type="button" onClick={() => open({ type: 'gameHelp' })} aria-label="게임 방법" className={cx('relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[18px] font-extrabold text-(--ink2) shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
?
</button>
</div>
<div className="mx-3 mt-2.5 flex items-center gap-2.5 text-[13px] font-extrabold">
<span className="shrink-0 rounded-full bg-(--ink) px-3 py-1 text-white">{round}라운드</span>
<div className="min-w-0 flex-1">
<div className="h-2.5 overflow-hidden rounded-full bg-white/80">
<i className="block h-full rounded-full bg-(--orange) transition-[width]" style={{ width: `${Math.min(100, (roundGot / roundTarget(round)) * 100)}%` }} />
</div>
<p className="m-0 mt-0.5 text-[11px] font-bold opacity-75">
다음 라운드까지 {roundGot} / {roundTarget(round)}
</p>
</div>
<span className="flex shrink-0 items-center gap-1 opacity-75">
다음 <Ic name={LEVELS[next].icon} className="size-6" />
</span>
</div>
<p className="mx-3 mt-1 mb-0 flex justify-between text-[12px] font-bold">
<span>
점수 <b className="text-[16px] text-(--orange)">{score}</b> <span className="opacity-60">· 최고 {best}</span>
</span>
{loggedIn ? (
<span className="opacity-75">
오늘 게임 각 {todayGak} / {cap}
</span>
) : (
<button type="button" onClick={() => open({ type: 'login' })} className="cursor-pointer p-0 text-[12px] font-extrabold text-(--orange-deep) underline underline-offset-2">
로그인하면 라운드마다 +2각
</button>
)}
</p>
{/* 남은 높이를 다 쓰되 2:3 비율은 지킨다 */}
<div className="mt-2 grid min-h-0 flex-1 place-items-center px-3 [container-type:size]">
<div className="relative aspect-[2/3]" style={{ width: 'min(100cqw, 100cqh * 2 / 3)' }}>
<canvas
ref={canvasRef}
onPointerMove={onMove}
onPointerDown={onMove}
onPointerUp={onUp}
className="block size-full touch-none rounded-[22px] bg-gradient-to-b from-[#cfe8ff] to-[#f3f9ff] shadow-[0_4px_14px_rgb(40_48_74/0.08)]"
/>
{!today.isSuccess && <p className="absolute inset-0 m-0 grid place-items-center text-[14px] font-bold opacity-60">{today.isError ? '날씨를 불러오지 못했어요' : '오늘 바람 불러오는 중…'}</p>}
{flash && !over && (
<p className="pointer-events-none absolute inset-x-0 top-[30%] m-0 text-center font-jua text-[34px] leading-tight text-(--orange) drop-shadow-[0_2px_0_white]">
{round}라운드!
{gain > 0 && <span className="block text-[22px] text-(--ink)">+{gain}각</span>}
</p>
)}
{over && (
<div className="absolute inset-0 grid place-items-center rounded-[22px] bg-white/75">
<div className="text-center">
<p className="m-0 font-jua text-[28px]">넘쳤어요!</p>
<p className="m-0 mt-1 text-[15px] font-bold">
{round}라운드 · 총 {score}점{score >= best && score > 0 ? ' · 최고 기록' : ''}
</p>
{loggedIn && (
<p className="m-0 mt-1 text-[13px] font-bold opacity-75">
오늘 게임 각 {todayGak} / {cap}
</p>
)}
<button type="button" onClick={restart} className="mt-4 cursor-pointer rounded-full bg-(--orange) px-6 py-2.5 text-[15px] font-extrabold text-white">
다시 하기
</button>
</div>
</div>
)}
</div>
</div>
<div className="mx-3 mt-2 flex items-center justify-center gap-x-1 text-[12px] font-bold opacity-70">
{LEVELS.map((l, i) => (
<span key={l.icon} className="flex items-center gap-0.5">
<Ic name={l.icon} className="size-5" />
{i < LEVELS.length - 1 && '›'}
</span>
))}
</div>
</div>
</div>,
document.body,
)
}
+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,
},
)
+526
View File
@@ -0,0 +1,526 @@
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useNavigate } from 'react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { matchMutation, myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { reading } from '@nalssigak/shared/api/client/sdk.gen'
import type { ResSaju, ResSajuMatch, SajuCard, SajuLock } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { progress, useLevel } from './level'
import { useRegion } from './regionContext'
import { BIRTH_PLACES, placeLon, useAccountBirth, useBirth, useSaveBirth, validBirth, type Birth } from './sajuBirth'
import { useSheet } from './sheetContext'
import { Ic, TAP44 } from './ui'
const SEEN_KEY = 'nalssigak.b.sajuSeen'
const EL_COLOR: Record<string, [string, string]> = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] }
const CARD_ICON: Record<string, string> = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' }
const POS_WORD: Record<string, string> = { hour: '시', day: '일', month: '월', year: '연' }
const HOURS = Array.from({ length: 24 }, (_, i) => i)
const MINUTES = Array.from({ length: 60 }, (_, i) => i)
const dayWord = (iso: string, weekday: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}(${weekday})`
const toBody = (b: Birth) => ({
birth_date: `${b.y}-${String(b.m).padStart(2, '0')}-${String(b.d).padStart(2, '0')}`,
birth_time: b.hour != null ? `${String(b.hour).padStart(2, '0')}:${String(b.minute ?? 0).padStart(2, '0')}` : undefined,
longitude: placeLon(b.place),
})
/** 오늘 아이콘 줄의 빨간 점: 오늘 날씨 사주를 아직 안 봤는지 */
export function sajuSeenToday() {
try {
return localStorage.getItem(SEEN_KEY) === new Date().toDateString()
} catch {
// 저장소를 못 쓰면 점을 보이지 않는다
return true
}
}
function markSeen() {
try {
localStorage.setItem(SEEN_KEY, new Date().toDateString())
} catch (e) {
console.warn('[saju] 본 날을 저장하지 못함', e)
}
}
/** 날씨 사주 페이지(/saju): 오늘 점수와 할 일, 내 기운, 레벨로 열리는 이번 주·금전·연애·궁합·이달·올해 */
export function SajuPage() {
const navigate = useNavigate()
const birth = useBirth()
const loading = useAccountBirth()
const [editing, setEditing] = useState(false)
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
return (
<div className="pb-8">
<div className="flex items-center gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<h2 className="m-0 flex items-center gap-1.5 px-1 font-jua text-[24px] font-normal">
<Ic name="yin_yang" className="size-7" />
날씨 사주
</h2>
</div>
{loading && !birth ? (
<p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">내 생년월일을 불러오는 중이에요…</p>
) : !birth || editing ? (
<BirthForm initial={birth} onDone={() => setEditing(false)} onCancel={birth ? () => setEditing(false) : undefined} />
) : (
<Reading birth={birth} onEdit={() => setEditing(true)} />
)}
</div>
)
}
function BirthForm({ initial, onDone, onCancel }: { initial: Birth | null; onDone: () => void; onCancel?: () => void }) {
const { loggedIn } = useAuth()
const save = useSaveBirth()
const [y, setY] = useState(initial ? String(initial.y) : '')
const [m, setM] = useState(initial ? String(initial.m) : '')
const [d, setD] = useState(initial ? String(initial.d) : '')
const [hour, setHour] = useState(initial?.hour != null ? String(initial.hour) : '')
const [minute, setMinute] = useState(initial?.minute != null ? String(initial.minute) : '0')
const [place, setPlace] = useState(initial?.place ?? 'seoul')
const [error, setError] = useState('')
const box = 'w-full min-w-0 rounded-2xl border-[1.5px] border-(--line) bg-white px-2 py-3 text-center text-[17px] font-bold'
const pick = cx(box, 'cursor-pointer appearance-none bg-[url("data:image/svg+xml,%3Csvg%20xmlns=%27http://www.w3.org/2000/svg%27%20width=%2712%27%20height=%278%27%3E%3Cpath%20d=%27M1%201l5%205%205-5%27%20fill=%27none%27%20stroke=%27%238a93a6%27%20stroke-width=%272%27/%3E%3C/svg%3E")] bg-[length:12px_8px] bg-[position:right_14px_center] bg-no-repeat pr-8')
const num = (set: (v: string) => void, max: number) => (e: { target: { value: string } }) => (set(e.target.value.replace(/\D/g, '').slice(0, max)), setError(''))
const submit = () => {
const [yy, mm, dd] = [Number(y), Number(m), Number(d)]
if (!y || !m || !d) return setError('생년월일을 모두 넣어 주세요')
if (!validBirth(yy, mm, dd)) return setError('없는 날짜예요. 다시 확인해 주세요')
const hh = hour === '' ? null : Number(hour)
save({ y: yy, m: mm, d: dd, hour: hh, minute: hh == null ? null : Number(minute), place, gender: initial?.gender ?? null })
track('saju_input', { with_time: hh != null })
onDone()
}
return (
<div className="mx-4 mt-4 flex flex-col gap-4 rounded-[24px] bg-white p-5 shadow-[inset_0_-5px_0_var(--shade)]">
<div className="text-center">
<Ic name="yin_yang" className="mx-auto size-14" />
<p className="m-0 mt-2 font-jua text-[20px] leading-snug">
내 사주와 오늘 날씨로
<br />
오늘 하루를 봐요
</p>
</div>
<fieldset className="m-0 flex min-w-0 flex-col gap-1.5 border-0 p-0">
<legend className="mb-1.5 p-0 text-[13px] font-extrabold text-(--ink2)">생년월일 (양력)</legend>
<div className="grid grid-cols-[1.5fr_1fr_1fr] gap-1.5">
<input inputMode="numeric" placeholder="연도" value={y} onChange={num(setY, 4)} className={box} aria-label="년" />
<input inputMode="numeric" placeholder="월" value={m} onChange={num(setM, 2)} className={box} aria-label="월" />
<input inputMode="numeric" placeholder="일" value={d} onChange={num(setD, 2)} className={box} aria-label="일" />
</div>
</fieldset>
<fieldset className="m-0 flex min-w-0 flex-col gap-1.5 border-0 p-0">
<legend className="mb-1.5 p-0 text-[13px] font-extrabold text-(--ink2)">태어난 시각 (모르면 '모름')</legend>
<div className="grid grid-cols-2 gap-1.5">
<select value={hour} onChange={(e) => setHour(e.target.value)} className={pick} aria-label="시">
<option value="">모름</option>
{HOURS.map((h) => (
<option key={h} value={h}>
{h}시
</option>
))}
</select>
<select value={minute} onChange={(e) => setMinute(e.target.value)} disabled={hour === ''} className={cx(pick, 'disabled:bg-[#f3f5f9] disabled:text-[#a0a8ba]')} aria-label="분">
{MINUTES.map((mi) => (
<option key={mi} value={mi}>
{mi}분
</option>
))}
</select>
</div>
</fieldset>
<label className="flex min-w-0 flex-col gap-1.5 text-[13px] font-extrabold text-(--ink2)">
태어난 지역
<select value={place} onChange={(e) => setPlace(e.target.value)} className={pick}>
{BIRTH_PLACES.map(([k, n]) => (
<option key={k} value={k}>
{n}
</option>
))}
</select>
<span className="text-xs font-semibold text-(--ink3)">지역마다 해가 뜨는 시각이 달라 태어난 시각을 그만큼 고쳐서 봐요.</span>
</label>
{error && <p className="m-0 text-center text-[13px] font-bold text-[#d9442f]">{error}</p>}
<button type="button" onClick={submit} className="cursor-pointer rounded-full bg-(--orange) py-3.5 text-[15px] font-extrabold text-white">
오늘 날씨 사주 보기
</button>
{onCancel && (
<button type="button" onClick={onCancel} className="-mt-2 cursor-pointer py-1 text-[13px] font-extrabold text-(--ink3)">
취소
</button>
)}
<p className="m-0 text-center text-xs font-semibold text-(--ink3)">
{loggedIn ? '내 계정에 저장돼요. 내 정보에서 언제든 지울 수 있어요.' : '이 기기에만 저장돼요. 로그인하면 계정에 저장해 어느 기기에서든 바로 볼 수 있어요.'}
</p>
</div>
)
}
function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
const { region } = useRegion()
const { loggedIn } = useAuth()
const queryClient = useQueryClient()
const level = useLevel().data?.level
const body = { ...toBody(birth), region_code: region.code, gender: birth.gender === 'M' ? ('male' as const) : birth.gender === 'F' ? ('female' as const) : undefined }
// 레벨이 오르면 키가 바뀌어 새로 열린 칸까지 다시 받는다. 사주를 보면 각이 쌓이니 레벨도 새로 받는다
const q = useQuery({
queryKey: ['saju', body, loggedIn, level],
staleTime: 10 * 60_000,
queryFn: async () => {
const { data } = await reading({ body })
if (!data.result?.success) throw new Error(data.result?.desc ?? 'saju')
if (loggedIn) queryClient.invalidateQueries({ queryKey: myLevelQueryKey() })
return data
},
})
const shot = useRef<HTMLDivElement>(null)
const { open } = useSheet()
const r = q.data
useEffect(() => {
if (!r?.today || !window.location.hash) return
document.getElementById(window.location.hash.slice(1))?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}, [r])
useEffect(() => {
if (!r?.today) return
markSeen()
track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score })
}, [r])
if (q.isPending) return <p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">사주를 풀고 있어요…</p>
if (!r?.today || !r.me)
return (
<div className="px-4 py-16 text-center">
<p className="m-0 font-semibold text-(--ink2)">결과를 불러오지 못했어요.</p>
<button type="button" onClick={() => q.refetch()} className="mt-3 cursor-pointer rounded-full bg-(--ink) px-4 py-2 text-[13px] font-extrabold text-white">
다시 시도
</button>
</div>
)
const t = r.today
const lock = (key: string) => r.locks?.find((l) => l.key === key)
return (
<div className="flex flex-col gap-3">
<div ref={shot} className="mx-4 mt-3 rounded-[26px] bg-white px-5 pt-4 pb-5 shadow-[inset_0_-5px_0_var(--shade)]">
<p className="m-0 text-center text-[12.5px] font-extrabold text-(--ink3)">
{Number(t.day.slice(5, 7))}월 {Number(t.day.slice(8, 10))}일 {t.pillar}일 · 오늘의 점수
</p>
<p className="m-0 text-center font-bagel text-[60px] leading-none">{t.score}</p>
<h3 className="m-0 mt-1.5 text-center font-jua text-[23px] leading-tight font-normal">{t.title}</h3>
<div className="mt-2.5 flex flex-wrap justify-center gap-1.5 text-[11.5px] font-extrabold">
<span className="rounded-full bg-[#f3f6fb] px-2.5 py-1">사주 {t.saju_score}점</span>
{t.weather_points != null && (
<span className={cx('rounded-full px-2.5 py-1', t.weather_points >= 0 ? 'bg-[#e3f6ea] text-[#1f7a4f]' : 'bg-[#ffe8dc] text-[#c2471b]')}>
날씨 영향 {t.weather_points >= 0 ? '+' : '−'}
{Math.abs(t.weather_points)}점
</span>
)}
</div>
{(t.why?.length ?? 0) > 0 && (
<details className="mt-2 text-center">
<summary className="cursor-pointer text-xs font-bold text-(--ink3)">왜 이 점수인가요? (↑ 올린 것 · ↓ 내린 것)</summary>
<ul className="m-0 mt-1.5 list-none p-0 text-xs font-semibold text-(--ink2)">
{t.why!.map((w) => (
<li key={w}>{w}</li>
))}
</ul>
</details>
)}
</div>
<section aria-label="오늘의 결정" className="mx-4 flex flex-col gap-2">
{t.cards.map((c) => (
<DecisionCard key={c.kind} c={c} />
))}
</section>
<MeCard r={r} onEdit={onEdit} />
{r.week && <Week r={r} />}
{r.money && (
<Panel id="saju_money" icon="money_bag" title="금전운 · 일운">
{[...r.money.map((l) => ['money_bag', l]), ...(r.work ?? []).map((l) => ['briefcase', l])].map(([icon, l]) => (
<p key={l} className="m-0 mt-1.5 flex gap-2 text-[14px] font-semibold first:mt-0">
<Ic name={icon} className="mt-px size-5 shrink-0" />
{l}
</p>
))}
</Panel>
)}
{r.love && <Love r={r} birth={birth} />}
{lock('saju_match')?.unlocked && <Match birth={birth} />}
{r.month && <Period id="saju_month" icon="spiral_calendar" p={r.month} />}
{r.year && <Period id="saju_year" icon="sunrise" p={r.year} />}
<Locked locks={(r.locks ?? []).filter((l) => !l.unlocked)} />
<div className="mx-4 flex items-center justify-between">
<span className="text-xs font-semibold text-(--ink3)">재미로 보는 날씨 사주</span>
<button
type="button"
onClick={() => shot.current && open({ type: 'share', share: { title: `오늘 내 날씨 사주 ${t.score}점 · ${t.title}`, slides: [shot.current] } })}
className="cursor-pointer rounded-full bg-(--ink) px-4 py-2 text-[13px] font-extrabold text-white"
>
공유
</button>
</div>
</div>
)
}
function DecisionCard({ c }: { c: SajuCard }) {
return (
<div className="flex gap-3 rounded-[20px] bg-white px-4 py-3 shadow-[inset_0_-4px_0_var(--shade)]">
<Ic name={CARD_ICON[c.kind] ?? 'sparkles'} className="mt-0.5 size-8 shrink-0" />
<div className="min-w-0">
<p className="m-0 text-[12px] font-extrabold text-(--orange)">{c.kind === 'when' ? '내 기운에 맞는 시간' : c.title}</p>
<p className="m-0 font-jua text-[17px] leading-snug whitespace-pre-line">{c.kind === 'when' ? `${c.title} · ${c.sub}` : c.body}</p>
<p className="m-0 mt-0.5 text-[12px] leading-snug font-semibold text-(--ink3)">{c.kind === 'when' ? c.body : c.sub}</p>
</div>
</div>
)
}
function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) {
const me = r.me!
const cols = [...me.pillars].reverse()
return (
<Panel icon={me.scene_icon} title={`내 기운 · ${me.scene.replace(/ 기운$/, '')}`} right={<button type="button" onClick={onEdit} className="cursor-pointer text-xs font-extrabold text-(--orange)">생년월일 바꾸기</button>}>
<p className="m-0 text-[14px] font-semibold text-(--ink2)">{me.scene_desc}</p>
<div className="mt-3 grid grid-cols-4 gap-1.5 text-center">
{(me.hour_known ? cols : [null, ...cols]).map((p, i) => (
<div key={p?.position ?? `none-${i}`} className="flex flex-col gap-1">
<span className="text-[11px] font-extrabold text-(--ink3)">{p ? POS_WORD[p.position] : '시'}</span>
{p ? (
<>
<Char c={p.stem} ko={p.stem_ko} el={p.stem_element} />
<Char c={p.branch} ko={p.branch_ko} el={p.branch_element} />
</>
) : (
<>
<span className="grid flex-1 place-items-center rounded-xl bg-[#f1f3f7] text-[12px] font-extrabold text-[#a0a8ba]">시각 모름</span>
</>
)}
</div>
))}
</div>
<p className="m-0 mt-2 text-[11.5px] font-semibold text-(--ink3)">태어난 연·월·일·시의 여덟 글자(사주팔자)예요. 색은 나무·불·흙·쇠·물 다섯 기운이에요.</p>
{(me.need?.length ?? 0) > 0 && <p className="m-0 mt-2 text-[13px] font-bold">내 기운에 좋은 날씨: {me.need!.join(' · ')}</p>}
{me.jeol_warning && <p className="m-0 mt-1 text-xs font-semibold text-[#c2471b]">태어난 날에 절기가 바뀌어요. 태어난 시각을 넣어야 달 기둥이 정확해요.</p>}
</Panel>
)
}
function Char({ c, ko, el }: { c: string; ko: string; el: string }) {
const [fg, bg] = EL_COLOR[el] ?? ['#28304a', '#f3f6fb']
return (
<span className="rounded-xl py-1.5" style={{ background: bg, color: fg }}>
<b className="block font-batang text-[22px] leading-tight">{c}</b>
<small className="text-[10.5px] font-extrabold">{ko}</small>
</span>
)
}
function Panel({ id, icon, title, right, children }: { id?: string; icon: string; title: string; right?: ReactNode; children: ReactNode }) {
return (
<section id={id} className="mx-4 scroll-mt-20 rounded-[22px] bg-white px-4 py-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<div className="mb-2 flex items-center gap-2">
<Ic name={icon} className="size-7" />
<h3 className="m-0 font-jua text-[17px] font-normal">{title}</h3>
{right && <span className="ml-auto">{right}</span>}
</div>
{children}
</section>
)
}
/** 아직 안 열린 것: 다음에 열릴 하나를 크게, 나머지는 한 줄로. 로그인 전이면 로그인부터 */
function Locked({ locks }: { locks: SajuLock[] }) {
const { loggedIn } = useAuth()
const { open } = useSheet()
const level = useLevel().data
if (!locks.length) return null
const [next, ...rest] = [...locks].sort((a, b) => a.level - b.level)
const close = loggedIn && level && level.next_points != null && level.level + 1 === next.level
return (
<section className="mx-4 rounded-[22px] bg-[#eef1f7] px-4 py-3.5">
<div className="flex items-center gap-3">
<Ic name="locked" className="size-8 shrink-0" />
<div className="min-w-0 flex-1">
<p className="m-0 font-jua text-[16px]">{loggedIn ? `다음은 ${next.name}` : '각을 모으면 더 볼 수 있어요'}</p>
<p className="m-0 text-xs font-bold text-(--ink2)">
{loggedIn ? (close ? `${level.next_points! - level.points}각 더 모으면 열려요` : `Lv.${next.level}이 되면 열려요`) : "로그인하고 출석·사주 보기·좋아요를 하면 활동 포인트 '각'이 쌓여요"}
</p>
</div>
<button type="button" onClick={() => open(loggedIn ? { type: 'level' } : { type: 'login', why: 'level' })} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-xs font-extrabold text-white">
{loggedIn ? '각 모으는 법' : '로그인'}
</button>
</div>
{close && (
<span className="mt-2.5 block h-1.5 overflow-hidden rounded-full bg-white">
<span className="block h-full rounded-full bg-(--orange)" style={{ width: `${Math.round(progress(level) * 100)}%` }} />
</span>
)}
<ul className="m-0 mt-2.5 flex list-none flex-wrap gap-1.5 p-0">
{(loggedIn ? rest : [next, ...rest]).map((l) => (
<li key={l.key} className="rounded-full bg-white px-2.5 py-1 text-[11.5px] font-extrabold text-(--ink2)">
Lv.{l.level} {l.name}
</li>
))}
</ul>
</section>
)
}
function Week({ r }: { r: ResSaju }) {
return (
<Panel id="saju_week" icon="spiral_calendar" title="앞으로 7일 흐름">
<ol className="m-0 flex list-none flex-col gap-1 p-0">
{r.week!.map((d) => (
<li key={d.day} className={cx('flex items-center gap-2 rounded-xl px-2 py-1.5 text-[13px] font-bold', d.best && 'bg-[#fff6ef]')}>
<span className="w-[66px] shrink-0 whitespace-nowrap">{dayWord(d.day, d.weekday)}</span>
{d.icon && <Ic name={d.icon} className="size-6 shrink-0" />}
<span className="w-[52px] shrink-0 whitespace-nowrap text-(--ink2)">{d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''}</span>
<span className="min-w-0 flex-1 truncate text-[12.5px] text-(--ink2)">{d.title}</span>
<b className={cx('font-bagel text-[15px] font-normal', d.best ? 'text-(--orange)' : '')}>{d.score}</b>
</li>
))}
</ol>
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">점수는 그날 사주와 예보로 계산해요. 주황색은 7일 중 점수가 가장 높은 날이에요.</p>
</Panel>
)
}
function Love({ r, birth }: { r: ResSaju; birth: Birth }) {
const love = r.love!
const save = useSaveBirth()
const pick = (g: 'M' | 'F' | null) => save({ ...birth, gender: g })
const chip = 'cursor-pointer rounded-full bg-[#f3f6fb] px-2.5 py-1'
return (
<Panel id="saju_love" icon="red_heart" title="앞으로 7일 연애운">
{love.good ? (
<div className="rounded-xl bg-[#fff0f3] px-3 py-2.5">
<p className="m-0 text-xs font-extrabold text-[#d6457a]">연애 기운이 좋은 날</p>
<p className="m-0 font-jua text-[17px]">
{dayWord(love.good.day, love.good.weekday)}
{love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''}
</p>
<p className="m-0 text-[13px] font-semibold">{love.good.body}</p>
<p className="m-0 text-[11.5px] font-semibold text-(--ink3)">{love.good.why}</p>
</div>
) : (
<p className="m-0 text-[13px] font-semibold text-(--ink2)">앞으로 7일 중엔 연애 기운이 두드러지는 날이 없어요.</p>
)}
{love.caution && (
<p className="m-0 mt-2 text-[13px] font-semibold">
조심할 날 {dayWord(love.caution.day, love.caution.weekday)}: {love.caution.body} <span className="text-(--ink3)">· {love.caution.why}</span>
</p>
)}
{love.gender_known ? (
<p className="m-0 mt-2.5 text-xs font-bold text-(--ink3)">
{birth.gender === 'M' ? '남성' : '여성'} 기준으로 이성 인연(재성·관성)까지 봤어요 ·{' '}
<button type="button" onClick={() => pick(null)} className="cursor-pointer font-extrabold text-(--orange)">
빼고 보기
</button>
</p>
) : (
<div className="mt-2.5 flex flex-wrap items-center gap-1.5 text-xs font-bold text-(--ink2)">
성별을 고르면 이성 인연(재성·관성)까지 봐요
<button type="button" onClick={() => pick('M')} className={chip}>
남성
</button>
<button type="button" onClick={() => pick('F')} className={chip}>
여성
</button>
</div>
)}
</Panel>
)
}
function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable<ResSaju['month']> }) {
return (
<Panel id={id} icon={icon} title={p.label}>
<p className="m-0 font-jua text-[17px]">
{p.title} <span className="text-[13px] text-(--ink3)">({p.ten_god})</span>
</p>
<p className="m-0 mt-0.5 text-[13.5px] font-semibold">{p.body}</p>
{(p.months?.length ?? 0) > 0 && <p className="m-0 mt-1.5 text-[13.5px] font-bold">{p.label.includes('미리') ? '내 사주와 잘 맞는 달' : '남은 달 중 잘 맞는 달'}: {p.months!.map((m) => `${m}월`).join(' · ')}</p>}
{p.notes?.map((n) => (
<p key={n} className="m-0 mt-1 text-xs font-semibold text-(--ink3)">
{n}
</p>
))}
</Panel>
)
}
function Match({ birth }: { birth: Birth }) {
const { region } = useRegion()
const [y, setY] = useState('')
const [m, setM] = useState('')
const [d, setD] = useState('')
const [error, setError] = useState('')
const run = useMutation({ ...matchMutation() })
const res: ResSajuMatch | undefined = run.data?.result?.success ? run.data : undefined
const input = 'w-full min-w-0 rounded-xl border-[1.5px] border-(--line) bg-white px-1 py-2 text-center text-[15px] font-bold'
const go = () => {
const [yy, mm, dd] = [Number(y), Number(m), Number(d)]
if (!y || !m || !d) return setError('상대 생년월일을 모두 넣어 주세요')
if (!validBirth(yy, mm, dd)) return setError('없는 날짜예요. 다시 확인해 주세요')
setError('')
run.mutate({ body: { region_code: region.code, me: toBody(birth), friend: { birth_date: `${yy}-${String(mm).padStart(2, '0')}-${String(dd).padStart(2, '0')}`, longitude: 126.98 } } })
}
return (
<Panel id="saju_match" icon="two_hearts" title="궁합">
{res ? (
<>
<p className="m-0 mb-1 flex items-center justify-between text-xs font-bold text-(--ink3)">
상대 {y}.{m}.{d}생
<button type="button" onClick={() => run.reset()} className="cursor-pointer font-extrabold text-(--orange)">
다른 사람 보기
</button>
</p>
<p className="m-0 font-jua text-[19px]">
{res.title} <span className="font-bagel text-[17px] text-(--orange)">{res.score}점</span>
</p>
{res.lines?.map((l) => (
<p key={l} className="m-0 mt-1 text-[13.5px] font-semibold">
{l}
</p>
))}
{res.day && (
<p className="m-0 mt-2 rounded-xl bg-[#fff6ef] px-3 py-2 text-[13.5px] font-bold">
앞으로 7일 중 같이 나가기 좋은 날: {dayWord(res.day.day, res.day.weekday)}
{res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''}
</p>
)}
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">상대 기운: {res.friend_scene}</p>
</>
) : (
<>
<p className="m-0 mb-2 text-[13px] font-semibold text-(--ink2)">상대 생년월일(양력)을 넣으면 두 사람 사주가 어떻게 맞는지와 앞으로 7일 중 같이 나가기 좋은 날을 봐요.</p>
<div className="grid grid-cols-[1.5fr_1fr_1fr_auto] gap-1.5">
<input inputMode="numeric" placeholder="연도" value={y} onChange={(e) => setY(e.target.value.replace(/\D/g, '').slice(0, 4))} className={input} aria-label="상대 년" />
<input inputMode="numeric" placeholder="월" value={m} onChange={(e) => setM(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 월" />
<input inputMode="numeric" placeholder="일" value={d} onChange={(e) => setD(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 일" />
<button type="button" onClick={go} disabled={run.isPending} className="shrink-0 cursor-pointer rounded-xl bg-(--orange) px-3 text-[14px] font-extrabold text-white">
보기
</button>
</div>
{error && <p className="m-0 mt-1.5 text-xs font-bold text-[#d9442f]">{error}</p>}
{(run.isError || (run.data && !run.data.result?.success)) && <p className="m-0 mt-1.5 text-xs font-bold text-[#d9442f]">궁합을 불러오지 못했어요. 다시 눌러 주세요.</p>}
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">상대 생년월일은 저장하지 않아요.</p>
</>
)}
</Panel>
)
}
+84 -7
View File
@@ -37,15 +37,47 @@ 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 { LevelCard, LevelSheet, LevelUpSheet, useCloseAndGo, useShareReward } from './level'
import { BIRTH_PLACES, useAccountBirth, useBirth, useSaveBirth } from './sajuBirth'
import { ownPage, useRegion } from './regionContext'
import { WeatherWhySheet } from './weatherWhy'
import { useSky } from './skyContext'
import { LEVELS } from './cloudMerge'
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'
/** 내 정보: 계정에 저장한 생년월일 (날씨 사주) */
function MyBirth() {
useAccountBirth()
const birth = useBirth()
const save = useSaveBirth()
const go = useCloseAndGo()
const place = BIRTH_PLACES.find(([k]) => k === birth?.place)?.[1]
return (
<section aria-label="내 생년월일" className="flex items-center gap-2.5 rounded-2xl bg-[#f6f8fc] px-3.5 py-3">
<Ic name="yin_yang" className="size-7 shrink-0" />
<div className="min-w-0 flex-1">
<p className="m-0 text-[13px] font-extrabold">내 생년월일</p>
<p className="m-0 truncate text-xs font-semibold text-(--ink2)">
{birth ? `${birth.y}.${birth.m}.${birth.d}${birth.hour != null ? ` ${birth.hour}시 ${birth.minute ?? 0}분` : ''}${place ? ` · ${place}` : ''}` : '넣어 두면 날씨 사주를 바로 볼 수 있어요'}
</p>
</div>
<button type="button" onClick={() => go('/saju')} className="shrink-0 cursor-pointer text-xs font-extrabold text-(--orange)">
{birth ? '사주 보기' : '넣기'}
</button>
{birth && (
<button type="button" onClick={() => save(null)} className="shrink-0 cursor-pointer text-xs font-extrabold text-(--ink3)">
지우기
</button>
)}
</section>
)
}
export function SheetProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<SheetState>(null)
// 창이 열려 있는 동안 방문 기록을 하나 쌓아 두어 뒤로 가기가 창만 닫게 한다
@@ -55,6 +87,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 +119,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
)
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기' } as const
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기', tarot: '오늘 타로', level: '내 레벨', levelUp: '레벨이 올랐어요', gameHelp: '구름 합치기 하는 법' } as const
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
@@ -166,14 +199,18 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{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 === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} why={shown.why} />}
{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 === 'tarot' && <TarotSheet />}
{shown.type === 'level' && <LevelSheet />}
{shown.type === 'levelUp' && <LevelUpSheet level={shown.level} />}
{shown.type === 'talk' && <TalkSheet talk={shown.talk} />}
{shown.type === 'gameHelp' && <GameHelpSheet />}
</div>
)}
{!shown && <RegionLinks />}
@@ -515,6 +552,37 @@ function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t:
}
/* ---------- 이번 주 특집 ---------- */
const GAME_STEPS = [
'목표 점수를 채우면 다음 라운드로 넘어가요. 라운드가 오를수록 목표가 높아져요.',
'손가락을 좌우로 움직여 떨어뜨릴 자리를 고르고, 손을 떼면 떨어져요.',
'떨어지는 동안 오늘 우리 동네 바람만큼 옆으로 밀려요. 바람 방향을 보고 조금 비켜 떨어뜨리세요.',
'같은 그림끼리 닿으면 한 단계 큰 그림으로 합쳐지고 점수가 올라요.',
'해 둘이 만나면 사라지면서 보너스 점수!',
'쌓인 그림이 위쪽 점선을 넘은 채로 잠깐 있으면 끝나요. 판은 다음 라운드로 그대로 이어져요.',
'로그인하면 라운드를 깰 때마다 2각을 받아요. 하루 20각까지예요.',
]
function GameHelpSheet() {
return (
<Body>
<ol className="m-0 flex list-decimal flex-col gap-2 pl-5 text-[15px] leading-[1.6]">
{GAME_STEPS.map((t) => (
<li key={t}>{t}</li>
))}
</ol>
<p className="mt-4 mb-2 text-[13px] font-extrabold text-(--ink2)">합쳐지는 순서</p>
<div className="grid grid-cols-4 gap-2 rounded-[16px] bg-[#f3f6fb] p-3">
{LEVELS.map((l, i) => (
<span key={l.icon} className="flex flex-col items-center gap-0.5 text-[12px] font-bold">
<Ic name={l.icon} className="size-8" />
{i + 1}. {l.name}
</span>
))}
</div>
</Body>
)
}
function SeasonWeekSheet() {
const { open } = useSheet()
const q = useQuery(getSeasonWeekOptions())
@@ -554,6 +622,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 }>>>({})
@@ -600,6 +669,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)
@@ -620,6 +690,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
@@ -693,9 +764,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 })
@@ -729,14 +801,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')}>
@@ -783,6 +855,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()
@@ -884,6 +957,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 } }) })
@@ -906,6 +980,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()
@@ -978,7 +1053,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
}
/* ---------- 로그인 ---------- */
function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
function LoginSheet({ onDone, onLoggedIn, why }: { onDone: () => void; onLoggedIn: () => void; why?: 'level' }) {
const { me } = useAuth()
const [error, setError] = useState('')
@@ -999,7 +1074,7 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
return (
<Body>
<div className="flex flex-col gap-2.5">
<p className="text-center text-sm font-semibold text-(--ink2)">글쓰기는 로그인한 뒤에 할 수 있어요.</p>
<p className="text-center text-sm font-semibold text-(--ink2)">{why === 'level' ? '로그인하면 출석·사주·좋아요로 각이 쌓여 레벨이 올라요.' : '글쓰기는 로그인한 뒤에 할 수 있어요.'}</p>
<GoogleButton
onResult={(res) => {
setError('')
@@ -1194,6 +1269,8 @@ 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 />
<MyBirth />
{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;
}
}
+120
View File
@@ -0,0 +1,120 @@
import Matter from 'matter-js'
/** 작은 것부터 큰 것 순서. 같은 단계 둘이 닿으면 다음 단계로 합쳐지고, 해 둘은 사라지며 보너스 */
export const LEVELS = [
{ icon: 'muggy', name: '물방울', r: 15, color: '#d9f0ff' },
{ icon: 'snow', name: '눈송이', r: 21, color: '#e4ecff' },
{ icon: 'cloud', name: '구름', r: 28, color: '#f1f3f8' },
{ icon: 'rain', name: '비구름', r: 36, color: '#dcdcff' },
{ icon: 'umbrella', name: '우산', r: 45, color: '#eadcff' },
{ icon: 'sun_cloud', name: '해구름', r: 55, color: '#fff1c9' },
{ icon: 'moon', name: '달', r: 66, color: '#ffe6b3' },
{ icon: 'sun', name: '해', r: 78, color: '#ffd2a1' },
] as const
export const W = 360
export const H = 540
/** 이 선 위에 쌓인 채로 LOSE_MS 넘게 있으면 끝 */
export const LINE_Y = 96
export const DROP_Y = 46
const LOSE_MS = 1600
const WALL = 40
/** 떨어지는 중에만 바람을 받는다. 초속 1m 당 가로 힘 */
const WIND_FORCE = 0.000045
const MAX_WIND = 12
/** 처음 떨어뜨리는 건 작은 4단계 중에서 */
const SPAWN_MAX = 3
const SUN_BONUS = 66
/** 라운드마다 이만큼 점수를 더 내면 다음 라운드 */
export const roundTarget = (round: number) => 200 + 80 * (round - 1)
export const pointsFor = (level: number) => ((level + 1) * (level + 2)) / 2
export type Piece = Matter.Body & { level: number; falling: boolean; merged: boolean; overSince: number | null }
export type GameEvents = { onScore: (score: number) => void; onOver: () => void }
/** 바람 방향은 날짜마다 정해 하루 동안 같게: 홀수 날은 오른쪽, 짝수 날은 왼쪽 */
export const windDir = (day: number) => (day % 2 ? 1 : -1)
export const randomLevel = () => Math.floor(Math.random() * (SPAWN_MAX + 1))
export function createGame(windMs: number, dir: number, ev: GameEvents) {
const engine = Matter.Engine.create({ gravity: { x: 0, y: 1, scale: 0.0012 } })
const wind = Math.min(Math.max(windMs, 0), MAX_WIND) * dir
const opts = { isStatic: true, friction: 0.6 }
Matter.Composite.add(engine.world, [
Matter.Bodies.rectangle(W / 2, H + WALL / 2, W + WALL * 2, WALL, opts),
Matter.Bodies.rectangle(-WALL / 2, H / 2, WALL, H * 2, opts),
Matter.Bodies.rectangle(W + WALL / 2, H / 2, WALL, H * 2, opts),
])
let score = 0
let over = false
const make = (level: number, x: number, y: number) => {
const b = Matter.Bodies.circle(x, y, LEVELS[level].r, { restitution: 0.15, friction: 0.4, frictionAir: 0.012, density: 0.0016 }) as Piece
b.level = level
b.falling = false
b.merged = false
b.overSince = null
Matter.Composite.add(engine.world, b)
return b
}
const pieces = () => engine.world.bodies.filter((b): b is Piece => 'level' in b)
Matter.Events.on(engine, 'beforeUpdate', () => {
for (const p of pieces()) if (p.falling) Matter.Body.applyForce(p, p.position, { x: p.mass * wind * WIND_FORCE, y: 0 })
})
Matter.Events.on(engine, 'collisionStart', (e) => {
for (const { bodyA, bodyB } of e.pairs) {
const a = bodyA as Piece
const b = bodyB as Piece
if ('level' in a) a.falling = false
if ('level' in b) b.falling = false
if (!('level' in a) || !('level' in b) || a.level !== b.level || a.merged || b.merged) continue
a.merged = b.merged = true
Matter.Composite.remove(engine.world, [a, b])
const last = a.level === LEVELS.length - 1
score += last ? SUN_BONUS : pointsFor(a.level + 1)
if (!last) {
const c = make(a.level + 1, (a.position.x + b.position.x) / 2, (a.position.y + b.position.y) / 2)
Matter.Body.setVelocity(c, { x: 0, y: -1 })
}
ev.onScore(score)
}
})
const step = (dt: number, now: number) => {
if (over) return
Matter.Engine.update(engine, Math.min(dt, 1000 / 60))
for (const p of pieces()) {
const above = !p.falling && p.position.y - LEVELS[p.level].r < LINE_Y
p.overSince = above ? (p.overSince ?? now) : null
if (p.overSince != null && now - p.overSince > LOSE_MS) {
over = true
ev.onOver()
return
}
}
}
const drop = (level: number, x: number) => {
if (over) return
const r = LEVELS[level].r
const p = make(level, Math.min(Math.max(x, r), W - r), DROP_Y)
p.falling = true
}
/** 위험선 근처에 있는지: 선을 빨갛게 보여 줄 때 */
const danger = () => pieces().some((p) => !p.falling && p.position.y - LEVELS[p.level].r < LINE_Y + 40)
return { step, drop, pieces, danger, wind, destroy: () => Matter.Engine.clear(engine) }
}
export type Game = ReturnType<typeof createGame>
const BEST_KEY = 'cloudMerge.best'
export const loadBest = () => Number(localStorage.getItem(BEST_KEY)) || 0
export const saveBest = (v: number) => localStorage.setItem(BEST_KEY, String(v))
+2
View File
@@ -0,0 +1,2 @@
/** 잠시 숨긴 기능 (아이콘 줄·각 모으는 법에서 뺀다). 다시 보이려면 여기서 지운다 */
export const HIDDEN = new Set<string>(['tarot'])
+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="닫기"
+231
View File
@@ -0,0 +1,231 @@
import { useEffect, useRef } from 'react'
import { useNavigate } from 'react-router'
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 { HIDDEN } from './features'
import { useSheet } from './sheetContext'
import { Ic } from './ui'
// 각을 주는 일 → 그 일을 하러 가는 곳, 숨긴 기능에 딸린 일 (서버 ACTIONS 키)
const ACTION_TO: Record<string, string> = { saju: '/saju', react: '/', talk: '/talk' }
const ACTION_FEATURE: Record<string, string> = { tarot: 'tarot', checkin: 'tarot' }
// 받침 있으면 a, 없으면 b: josa('연애운', '이', '가') → '연애운이'
const josa = (w: string, a: string, b: string) => {
const c = w.charCodeAt(w.length - 1) - 0xac00
return w + (c >= 0 && c < 11172 && c % 28 === 0 ? b : a)
}
// 창이 쌓아 둔 방문 기록을 닫으며 되돌리므로, 되돌린 뒤(popstate)에 이동해야 새 주소가 안 지워진다
export function useCloseAndGo() {
const { close } = useSheet()
const navigate = useNavigate()
return (to: string) => {
window.addEventListener('popstate', () => navigate(to), { once: true })
close()
}
}
// 레벨마다 보여 줄 하늘 아이콘 (이름은 서버 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
? '가장 높은 레벨이에요'
: unlock.length > 0
? `${level.next_points - level.points}각 더 모으면 ${josa(unlock.join(', '), '이', '가')} 열려요`
: `${level.next_points - level.points}각 더 모으면 Lv.${level.level + 1} ${level.next_name}`}
</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
const go = useCloseAndGo()
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 ?? []).filter((a) => !HIDDEN.has(ACTION_FEATURE[a.action] ?? a.action)).map((a) => {
const done = a.earned >= a.cap
const to = ACTION_TO[a.action]
return (
<li
key={a.action}
onClick={to && !done ? () => go(to) : undefined}
className={cx('flex items-center gap-2.5 border-b border-[#eef1f6] px-3.5 py-2.5 text-[13.5px] font-bold last:border-0', to && !done && 'cursor-pointer')}
>
<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)">
{done ? `오늘 ${a.earned}각 받음` : a.earned > 0 ? `${a.earned}/${a.cap}각` : `+${a.points}각`}
</span>
{to && !done && <span className="text-(--ink3)">›</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 go = useCloseAndGo()
const unlocks = (level?.unlocks ?? []).filter((u) => u.level === lv)
const opened = unlocks.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)">이제 {josa(opened.join(', '), '을', '를')} 볼 수 있어요</p>}
{unlocks.length > 0 && (
<button type="button" onClick={() => go(`/saju#${unlocks[0].key}`)} className="mt-3 w-full cursor-pointer rounded-full bg-(--orange) py-3 text-[15px] font-extrabold text-white">
{opened[0]} 보러 가기
</button>
)}
<button type="button" onClick={() => open({ type: 'level' })} className={cx('w-full cursor-pointer py-2 text-[14px] font-extrabold', unlocks.length ? 'text-(--ink2)' : 'mt-3 rounded-full bg-(--orange) py-3 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', 'yin_yang', 'tshirt', 'clapper', 'speech', 'droplet', 'leaf', 'rainbow', 'milky_way', 'shooting_star', 'alarm_clock', 'check_mark_button', 'sparkles', 'warning', 'locked', 'money_bag', 'red_heart', 'briefcase', 'spiral_calendar', 'two_hearts', 'sunrise'])
/** 아이콘 이름 → 파일 경로 (공용 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,
},
)
+112
View File
@@ -0,0 +1,112 @@
import { useEffect, useSyncExternalStore } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { getBirthQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { deleteBirth, getBirth, putBirth } from '@nalssigak/shared/api/client/sdk.gen'
import type { SajuSavedBirth } from '@nalssigak/shared/api/client/types.gen'
import { useAuth } from './authContext'
/** 날씨 사주에 쓰는 태어난 정보. 기기에 두고, 로그인했으면 계정에도 저장한다 */
export type Birth = { y: number; m: number; d: number; hour: number | null; minute: number | null; place: string; gender: 'M' | 'F' | null }
const KEY = 'nalssigak.b.birth'
/** 태어난 곳: 시각을 그곳 경도로 맞춘다 (시·도청 경도) */
export const BIRTH_PLACES: [string, string, number][] = [
['seoul', '서울', 126.98],
['busan', '부산', 129.08],
['daegu', '대구', 128.6],
['incheon', '인천', 126.71],
['gwangju', '광주', 126.85],
['daejeon', '대전', 127.38],
['ulsan', '울산', 129.31],
['sejong', '세종', 127.29],
['gyeonggi', '경기', 127.01],
['gangwon', '강원', 127.73],
['chungbuk', '충북', 127.49],
['chungnam', '충남', 126.67],
['jeonbuk', '전북', 127.11],
['jeonnam', '전남', 126.46],
['gyeongbuk', '경북', 128.51],
['gyeongnam', '경남', 128.69],
['jeju', '제주', 126.5],
]
export const placeLon = (key: string) => BIRTH_PLACES.find(([k]) => k === key)?.[2] ?? 127
function read(): Birth | null {
try {
const raw = localStorage.getItem(KEY)
return raw ? (JSON.parse(raw) as Birth) : null
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
return null
}
}
let birth = read()
const listeners = new Set<() => void>()
const subscribe = (cb: () => void) => {
listeners.add(cb)
return () => listeners.delete(cb)
}
export function setBirth(b: Birth | null) {
birth = b
listeners.forEach((cb) => cb())
try {
if (b) localStorage.setItem(KEY, JSON.stringify(b))
else localStorage.removeItem(KEY)
} catch (e) {
console.warn('[saju] 기기에 저장하지 못함', e)
}
}
export const useBirth = () => useSyncExternalStore(subscribe, () => birth)
const pad = (n: number) => String(n).padStart(2, '0')
const toSaved = (b: Birth): SajuSavedBirth => ({
birth_date: `${b.y}-${pad(b.m)}-${pad(b.d)}`,
birth_time: b.hour != null ? `${pad(b.hour)}:${pad(b.minute ?? 0)}` : undefined,
place: b.place,
gender: b.gender === 'M' ? 'male' : b.gender === 'F' ? 'female' : undefined,
})
const fromSaved = (s: SajuSavedBirth): Birth => {
const [y, m, d] = s.birth_date.split('-').map(Number)
const [hour, minute] = s.birth_time ? s.birth_time.split(':').map(Number) : [null, null]
return { y, m, d, hour, minute, place: s.place ?? 'seoul', gender: s.gender === 'male' ? 'M' : s.gender === 'female' ? 'F' : null }
}
/** 로그인했으면 계정의 생년월일을 기기로 가져온다. 계정엔 없고 기기에만 있으면 계정으로 올린다 */
export function useAccountBirth() {
const { loggedIn } = useAuth()
const q = useQuery({ queryKey: getBirthQueryKey(), enabled: loggedIn, staleTime: Infinity, queryFn: async () => (await getBirth()).data })
useEffect(() => {
if (!loggedIn || !q.data?.result?.success) return
if (q.data.birth) setBirth(fromSaved(q.data.birth))
else if (birth) putBirth({ body: toSaved(birth) }).catch((e) => console.warn('[saju] 계정에 올리지 못함', e))
}, [loggedIn, q.data])
return loggedIn && q.isPending
}
/** 생년월일 저장·지우기: 기기에 두고, 로그인했으면 계정에도 */
export function useSaveBirth() {
const { loggedIn } = useAuth()
const queryClient = useQueryClient()
return async (b: Birth | null) => {
setBirth(b)
if (!loggedIn) return
try {
const { data } = b ? await putBirth({ body: toSaved(b) }) : await deleteBirth()
if (data.result?.success) queryClient.setQueryData(getBirthQueryKey(), data)
} catch (e) {
console.warn('[saju] 계정에 저장하지 못함', e)
}
}
}
/** 있는 날짜이고 1900-01-01 ~ 오늘 사이인지 */
export function validBirth(y: number, m: number, d: number) {
const at = new Date(Date.UTC(y, m - 1, d))
const ok = at.getUTCFullYear() === y && at.getUTCMonth() === m - 1 && at.getUTCDate() === d
return ok && y >= 1900 && at.getTime() <= Date.now()
}
+5 -1
View File
@@ -13,7 +13,7 @@ export type SheetState =
| { type: 'share'; share: SharePayload }
| CommentsState
| { type: 'seasonWeek' }
| { type: 'login'; then?: CommentsState }
| { type: 'login'; then?: CommentsState; why?: 'level' }
| { type: 'me' }
| { type: 'region' }
| { type: 'mix'; shared?: MyGak }
@@ -21,6 +21,10 @@ export type SheetState =
| { type: 'install' }
| { type: 'weatherWhy'; why: WeatherWhyPayload }
| { type: 'talk'; talk: TalkData }
| { type: 'tarot' }
| { type: 'level' }
| { type: 'levelUp'; level: number }
| { type: 'gameHelp' }
| null
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
+12 -6
View File
@@ -20,6 +20,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
@@ -105,6 +106,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)
@@ -215,7 +217,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)
},
@@ -228,14 +233,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)
@@ -271,7 +277,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">
@@ -284,13 +290,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)">
+79
View File
@@ -0,0 +1,79 @@
import { type ReactNode } from 'react'
import { Link } from 'react-router'
import { track } from '../lib/analytics'
import { HIDDEN } from './features'
import { useFoliage } from './foliage'
import { useTarotBadge } from './fortune'
import { sajuSeenToday } from './SajuPage'
import { useSheet } from './sheetContext'
import { Ic, Rail } from './ui'
/** 오늘 탭 '내 각' 줄 자리 (아이콘에서 거기로 내려간다) */
export const MY_GAK_ID = 'my-gak'
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 { inSeason } = useFoliage()
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: 'saju', label: '날씨 사주', icon: 'yin_yang', badge: sajuSeenToday() ? null : <Dot />, to: '/saju' },
{ key: 'game', label: '날씨 게임', icon: 'game', to: '/game' },
...(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' },
].filter((it) => !HIDDEN.has(it.key))
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>
)
}
+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)
}
+26
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,31 @@ 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 }
saju_input: { with_time: boolean }
saju_view: { scene: string; score: number }
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() }) }),
})
// 홈 화면 설치 조건(서비스 워커)과, 홈 화면 아이콘으로 연 횟수