feat: 나만의 각 1단계 — 공식 각 두 개를 섞어 내 각 만들기(점수는 낮은 쪽), 로그인 없이 1개·로그인하면 계정 저장, 친구에게 보낸 링크로 내 동네 점수 보기
This commit is contained in:
1 parent
96cbd19c61
commit
a8a126f6a5
18 files changed
+842
-6
No files matched your search
@@ -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 }
|
||||
}
|
||||
Reference in new issue
Block a user