feat: 나만의 각 1단계 — 공식 각 두 개를 섞어 내 각 만들기(점수는 낮은 쪽), 로그인 없이 1개·로그인하면 계정 저장, 친구에게 보낸 링크로 내 동네 점수 보기

This commit is contained in:
minaChoi committed 2026-10-20 11:37:40 +09:00
1 parent 96cbd19c61
commit a8a126f6a5
18 files changed
+842 -6

No files matched your search

+11 -1
View File
@@ -25,6 +25,8 @@ import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
import { MixSheet } from './myGak'
import { useMyGak } from './myGakState'
import { ownPage, useRegion } from './regionContext'
import { useSky } from './skyContext'
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
@@ -102,7 +104,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
}, [isOpen])
const then = state?.type === 'login' ? state.then : undefined
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type]
return (
<dialog
@@ -132,6 +134,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'mix' && <MixSheet ids={state.ids} shared={state.shared} onDone={onClose} />}
</div>
)}
{!state && <RegionLinks />}
@@ -323,6 +326,8 @@ function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[];
function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) => void }) {
const { region } = useRegion()
const { open } = useSheet()
const { mixable } = useMyGak()
const q = useQuery(getIndexOptions({ path: { index_id: indexId }, query: { region: region.code } }))
const d: ResIndexDetail | undefined = q.data
const g = d?.index
@@ -355,6 +360,11 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
<b className={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b>
</div>
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{mixable.has(g.index_id) && (
<button type="button" onClick={() => open({ type: 'mix', ids: [g.index_id] })} className="mt-2.5 w-full cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
다른 각과 섞어 내 각 만들기
</button>
)}
{now && (
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
+13
View File
@@ -5,6 +5,7 @@ import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/
import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
import { MyGakRow } from './myGak'
import { PostCard, PostCardSkel } from './Post'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
@@ -352,6 +353,7 @@ export function TodayPage() {
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
const { preview } = useSky()
const { open } = useSheet()
const f = feed.data
const posts = f?.posts ?? []
const stories = atSlot(f?.stories ?? [], preview)
@@ -364,6 +366,16 @@ export function TodayPage() {
window.scrollTo({ top: 0 })
}, [region.code])
// 친구가 보낸 섞은 각 링크(/?mix=3,8)로 들어오면 내 동네 기준으로 보여 준다
useEffect(() => {
const url = new URL(window.location.href)
const ids = url.searchParams.get('mix')?.split(',').map(Number).filter(Number.isInteger)
if (!ids || ids.length !== 2) return
url.searchParams.delete('mix')
window.history.replaceState(window.history.state, '', url)
open({ type: 'mix', ids, shared: true })
}, [open])
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
@@ -375,6 +387,7 @@ 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} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<MyGakRow stories={f?.stories ?? []} />
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} className="inset-x-3 top-3 bottom-1" />}
+135
View File
@@ -0,0 +1,135 @@
import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { getFeedOptions } from '../api/client/@tanstack/react-query.gen'
import type { TopIndex } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { mix, shareUrl, useMyGak } from './myGakState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Ic, Sec } from './ui'
function Bar({ g, low }: { g: TopIndex; low: boolean }) {
return (
<span className="grid grid-cols-[1fr_auto] items-center gap-x-2 text-[12.5px] font-bold">
<span>{g.name}</span>
<em className={cx('font-jua not-italic', low ? 'text-(--ink2)' : 'text-(--orange)')}>{g.score}</em>
<i className="col-span-2 block h-[7px] overflow-hidden rounded-full bg-[#e3eaf4]">
<s className={cx('b-keep-bg block h-full', low ? 'bg-[#f3b38f]' : 'bg-(--orange)')} style={{ width: `${g.score}%` }} />
</i>
</span>
)
}
/** 오늘 탭의 내 각 줄: 섞은 각 카드들과 새로 섞기 */
export function MyGakRow({ stories }: { stories: TopIndex[] }) {
const { open } = useSheet()
const { pairs, remove } = useMyGak()
const [copied, setCopied] = useState<string | null>(null)
const send = (ids: number[], name: string) => {
const url = shareUrl(ids)
if (navigator.share) {
navigator.share({ title: `${name} · 날씨각`, url }).catch((e: unknown) => {
if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[myGak] share', e)
})
return
}
navigator.clipboard.writeText(url).then(
() => setCopied(ids.join()),
(e: unknown) => console.error('[myGak] copy', e),
)
}
if (!stories.length) return null
return (
<>
<Sec title="내 각" sub="공식 각 두 개를 섞어 만들어요. 둘 다 좋아야 높아요" />
<div className="flex snap-x gap-2 overflow-x-auto px-3 pb-1 [scrollbar-width:none]">
{pairs.map((p) => {
const m = mix(stories, p.ids)
if (!m) return null
return (
<div key={p.ids.join()} className="flex w-[220px] shrink-0 snap-start flex-col gap-1.5 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<div className="flex items-center gap-1">
<Ic name={m.a.icon} className="w-8" />
<Ic name={m.b.icon} className="-ml-3 w-8" />
<b className="ml-1 font-jua text-[17px] leading-tight font-normal">{m.name}</b>
<em className={cx('ml-auto font-bagel text-[28px] leading-none not-italic', m.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{m.score}</em>
</div>
<Bar g={m.a} low={m.low === m.a && m.a.score !== m.b.score} />
<Bar g={m.b} low={m.low === m.b && m.a.score !== m.b.score} />
<div className="mt-0.5 flex gap-1.5">
<button type="button" onClick={() => send(p.ids, m.name)} className="cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
{copied === p.ids.join() ? '링크 복사함' : '친구에게 보내기'}
</button>
<button type="button" onClick={() => remove(p)} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[12.5px] font-extrabold text-(--ink2)">
지우기
</button>
</div>
</div>
)
})}
<button type="button" onClick={() => open({ type: 'mix' })} className="flex w-[120px] shrink-0 cursor-pointer snap-start flex-col items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-(--line) p-3 font-jua text-[15px] text-(--ink2)">
<span className="text-[26px] leading-none">+</span>
각 섞기
</button>
</div>
</>
)
}
/** 섞을 각 고르기와 미리보기. ids 가 둘이면(받은 링크) 바로 미리보기 */
export function MixSheet({ ids: start = [], shared = false, onDone }: { ids?: number[]; shared?: boolean; onDone: () => void }) {
const { region } = useRegion()
const stories = useQuery(getFeedOptions({ query: { region: region.code } })).data?.stories ?? []
const { mixable, has, create, pending } = useMyGak()
const [ids, setIds] = useState<number[]>(start.slice(0, 2))
const choices = stories.filter((g) => mixable.has(g.index_id))
const m = ids.length === 2 ? mix(stories, ids) : null
const owned = ids.length === 2 && has(ids)
const toggle = (id: number) => setIds((now) => (now.includes(id) ? now.filter((x) => x !== id) : now.length < 2 ? [...now, id] : [now[0], id]))
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
{!shared && (
<>
<p className="m-0 font-jua text-[19px]">{ids.length === 2 ? '이 둘을 섞어요' : ids.length ? '하나 더 골라요' : '섞을 각 두 개를 골라요'}</p>
<p className="mt-0.5 mb-2.5 text-[13px] font-semibold text-(--ink2)">함께 할 일끼리 골라요. 점수는 둘 중 낮은 쪽이에요</p>
<div className="flex flex-wrap gap-1.5" role="group" aria-label="섞을 각">
{choices.map((g) => {
const on = ids.includes(g.index_id)
return (
<button key={g.index_id} type="button" aria-pressed={on} onClick={() => toggle(g.index_id)} className={cx('flex cursor-pointer items-center gap-1 rounded-full py-1 pr-3 pl-1.5 text-[13.5px] font-extrabold', on ? 'bg-(--orange) text-white' : 'bg-[#eef4fc] text-(--ink)')}>
<Ic name={g.icon} className="w-6" />
{g.name.replace(/각$/, '')}
</button>
)
})}
</div>
</>
)}
{m && (
<div className="mt-3.5 flex flex-col gap-2 rounded-[20px] bg-[#f3f6fb] p-3.5">
{shared && <p className="m-0 text-[13px] font-bold text-(--ink2)">친구가 보낸 각이에요. {region.name} 기준 점수예요</p>}
<div className="flex items-center gap-1">
<Ic name={m.a.icon} className="w-9" />
<Ic name={m.b.icon} className="-ml-3 w-9" />
<b className="ml-1 font-jua text-[20px] font-normal">{m.name}</b>
<em className={cx('ml-auto font-bagel text-[36px] leading-none not-italic', m.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{m.score}</em>
</div>
<Bar g={m.a} low={m.low === m.a && m.a.score !== m.b.score} />
<Bar g={m.b} low={m.low === m.b && m.a.score !== m.b.score} />
<p className="m-0 text-[13px] font-semibold text-(--ink2)">
{m.a.score === m.b.score ? '두 각 점수가 같아요' : `오늘은 ${m.low.name} 점수를 따라가요`}
</p>
</div>
)}
<button
type="button"
disabled={!m || owned || pending}
onClick={() => m && create(ids, onDone)}
className="mt-3.5 w-full cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[17px] text-white disabled:cursor-default disabled:opacity-45"
>
{owned ? '이미 내 각에 있어요' : shared ? '내 각으로 가져오기' : '내 각으로 만들기'}
</button>
</div>
)
}
+99
View File
@@ -0,0 +1,99 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useSyncExternalStore } from 'react'
import { SITE_URL } from '../api/setup'
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey } from '../api/client/@tanstack/react-query.gen'
import type { TopIndex } from '../api/client/types.gen'
import { useAuth } from './authContext'
import { useSheet } from './sheetContext'
const KEY = 'nalssigak.b.myGak'
/** 로그인하지 않으면 이 기기에 하나만 */
export type Pair = { id?: number; ids: [number, number] }
const sameIds = (a: number[], b: number[]) => a.length === 2 && b.length === 2 && a[0] === b[0] && a[1] === b[1]
const sorted = (ids: number[]) => [...ids].sort((x, y) => x - y) as [number, number]
function readLocal(): [number, number] | null {
try {
const raw = localStorage.getItem(KEY)
return raw ? sorted(JSON.parse(raw) as number[]) : null
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
return null
}
}
// 시트와 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
let local = readLocal()
const listeners = new Set<() => void>()
const subscribe = (cb: () => void) => {
listeners.add(cb)
return () => listeners.delete(cb)
}
function setLocal(ids: [number, number] | null) {
local = ids
listeners.forEach((cb) => cb())
try {
if (ids) localStorage.setItem(KEY, JSON.stringify(ids))
else localStorage.removeItem(KEY)
} catch (e) {
console.warn('[myGak] 기기에 저장하지 못함', e)
}
}
/** 두 각 이름을 이어 붙인 이름: 러닝각 + 치맥각 → 러닝·치맥각 */
const pairName = (a: TopIndex, b: TopIndex) => `${a.name.replace(/각$/, '')}·${b.name}`
/** 섞은 각 점수: 둘 다 좋아야 좋은 날이라 낮은 쪽 */
export function mix(stories: TopIndex[], ids: number[]) {
const a = stories.find((g) => g.index_id === ids[0])
const b = stories.find((g) => g.index_id === ids[1])
if (!a || !b) return null
return { a, b, name: pairName(a, b), score: Math.min(a.score, b.score), low: a.score <= b.score ? a : b }
}
export const shareUrl = (ids: number[]) => `${SITE_URL}/?mix=${ids.join(',')}`
export function useMyGak() {
const { loggedIn } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const q = useQuery(listMyGakOptions())
const saved = useSyncExternalStore(subscribe, () => local)
const add = useMutation({ ...addMyGakMutation(), onSuccess: () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() }) })
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() }) })
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
const { mutate } = add
useEffect(() => {
if (!loggedIn || !saved) return
mutate({ body: { index_ids: saved } }, { onSuccess: () => setLocal(null) })
}, [loggedIn, saved, mutate])
const pairs: Pair[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, ids: sorted(g.index_ids) })) : saved ? [{ ids: saved }] : []
const has = (ids: number[]) => pairs.some((p) => sameIds(p.ids, sorted(ids)))
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
const create = (ids: number[], onDone?: () => void) => {
const two = sorted(ids)
if (loggedIn) {
add.mutate({ body: { index_ids: two } }, { onSuccess: onDone })
return
}
if (saved && !sameIds(saved, two)) {
open({ type: 'login' })
return
}
setLocal(two)
onDone?.()
}
const remove = (p: Pair) => {
if (p.id != null) return del.mutate({ path: { my_gak_id: p.id } })
setLocal(null)
}
return { mixable: new Set(q.data?.mixable ?? []), pairs, has, create, remove, pending: add.isPending }
}
+1
View File
@@ -12,6 +12,7 @@ export type SheetState =
| { type: 'login'; then?: CommentsState }
| { type: 'me' }
| { type: 'region' }
| { type: 'mix'; ids?: number[]; shared?: boolean }
| null
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }