feat: 10/20 회의 반영 — 이야기 탭을 오늘 피드로 합침(글쓰기 칸·사진 올리기·위치 정보 삭제), 오늘의 각 카드와 히어로·각 공유 템플릿, 나만의 각을 이름+날씨 조건 저장으로, 로그인 없이 좋아요(IP 해시), 피드 순서·불쾌지수 상시·포스트 그림 배경, 새 각 아이콘
This commit is contained in:
1 parent
017022a0b0
commit
d0213f41a6
81 files changed
+3503
-593
No files matched your search
@@ -2,22 +2,29 @@ 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 { scoreMyGak } from '../api/client/sdk.gen'
|
||||
import type { MyGakRule, MyGakScore } from '../api/client/types.gen'
|
||||
import { useAuth } from './authContext'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
|
||||
const KEY = 'nalssigak.b.myGak'
|
||||
const KEY = 'nalssigak.b.myRule'
|
||||
|
||||
/** 로그인하지 않으면 이 기기에 하나만 */
|
||||
export type Pair = { id?: number; ids: [number, number] }
|
||||
export type Slot = 'morning' | 'day' | 'evening' | 'night'
|
||||
export const SLOTS: [Slot, string][] = [
|
||||
['morning', '아침'],
|
||||
['day', '낮'],
|
||||
['evening', '저녁'],
|
||||
['night', '밤'],
|
||||
]
|
||||
|
||||
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]
|
||||
/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) */
|
||||
export type MyGak = { id?: number; name: string; rule: MyGakRule }
|
||||
|
||||
function readLocal(): [number, number] | null {
|
||||
function readLocal(): MyGak | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY)
|
||||
return raw ? sorted(JSON.parse(raw) as number[]) : null
|
||||
return raw ? (JSON.parse(raw) as MyGak) : null
|
||||
} catch {
|
||||
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
|
||||
return null
|
||||
@@ -32,68 +39,94 @@ const subscribe = (cb: () => void) => {
|
||||
return () => listeners.delete(cb)
|
||||
}
|
||||
|
||||
function setLocal(ids: [number, number] | null) {
|
||||
local = ids
|
||||
function setLocal(g: MyGak | null) {
|
||||
local = g
|
||||
listeners.forEach((cb) => cb())
|
||||
try {
|
||||
if (ids) localStorage.setItem(KEY, JSON.stringify(ids))
|
||||
if (g) localStorage.setItem(KEY, JSON.stringify(g))
|
||||
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 gakName = (name: string) => {
|
||||
const n = name.trim().replace(/\s+/g, ' ')
|
||||
return n && !n.endsWith('각') ? `${n}각` : n
|
||||
}
|
||||
|
||||
export const shareUrl = (ids: number[]) => `${SITE_URL}/?mix=${ids.join(',')}`
|
||||
/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 */
|
||||
export function shareUrl(g: MyGak) {
|
||||
const json = JSON.stringify({ n: g.name, r: g.rule })
|
||||
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)))
|
||||
return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`
|
||||
}
|
||||
|
||||
export function fromShare(code: string): MyGak | null {
|
||||
try {
|
||||
const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/'))
|
||||
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; r?: unknown }
|
||||
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, rule: v.r as MyGakRule } : null
|
||||
} catch (e) {
|
||||
console.warn('[myGak] 받은 링크를 읽지 못함', e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 조건들의 우리 동네 오늘 점수. 조건이 같으면 캐시를 같이 쓴다 */
|
||||
export function useMyGakScores(rules: MyGakRule[]) {
|
||||
const { region } = useRegion()
|
||||
return useQuery({
|
||||
queryKey: ['myGakScore', region.code, rules],
|
||||
enabled: rules.length > 0,
|
||||
staleTime: 5 * 60_000,
|
||||
queryFn: async (): Promise<{ nowSlot?: Slot | null; scores: MyGakScore[] }> => {
|
||||
const { data } = await scoreMyGak({ body: { region_code: region.code, rules } })
|
||||
if (!data.result?.success) throw new Error(data.result?.desc ?? 'score')
|
||||
return { nowSlot: data.now_slot, scores: data.scores ?? [] }
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useMyGak() {
|
||||
const { loggedIn } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const queryClient = useQueryClient()
|
||||
const q = useQuery(listMyGakOptions())
|
||||
const q = useQuery({ ...listMyGakOptions(), enabled: loggedIn })
|
||||
const saved = useSyncExternalStore(subscribe, () => local)
|
||||
const add = useMutation({ ...addMyGakMutation(), onSuccess: () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() }) })
|
||||
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() }) })
|
||||
const refresh = () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() })
|
||||
const add = useMutation({ ...addMyGakMutation(), onSuccess: refresh })
|
||||
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: refresh })
|
||||
|
||||
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
|
||||
const { mutate } = add
|
||||
useEffect(() => {
|
||||
if (!loggedIn || !saved) return
|
||||
mutate({ body: { index_ids: saved } }, { onSuccess: () => setLocal(null) })
|
||||
mutate({ body: { name: saved.name, rule: saved.rule } }, { 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 items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, rule: g.rule })) : saved ? [saved] : []
|
||||
|
||||
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
|
||||
const create = (ids: number[], onDone?: () => void) => {
|
||||
const two = sorted(ids)
|
||||
const create = (g: MyGak, onDone?: () => void) => {
|
||||
const item = { name: gakName(g.name), rule: g.rule }
|
||||
if (loggedIn) {
|
||||
add.mutate({ body: { index_ids: two } }, { onSuccess: onDone })
|
||||
add.mutate({ body: item }, { onSuccess: (res) => res.result?.success && onDone?.() })
|
||||
return
|
||||
}
|
||||
if (saved && !sameIds(saved, two)) {
|
||||
if (saved) {
|
||||
open({ type: 'login' })
|
||||
return
|
||||
}
|
||||
setLocal(two)
|
||||
setLocal(item)
|
||||
onDone?.()
|
||||
}
|
||||
|
||||
const remove = (p: Pair) => {
|
||||
if (p.id != null) return del.mutate({ path: { my_gak_id: p.id } })
|
||||
const remove = (g: MyGak) => {
|
||||
if (g.id != null) return del.mutate({ path: { my_gak_id: g.id } })
|
||||
setLocal(null)
|
||||
}
|
||||
|
||||
return { mixable: new Set(q.data?.mixable ?? []), pairs, has, create, remove, pending: add.isPending }
|
||||
return { items, create, remove, pending: add.isPending, failed: add.data?.result?.success === false }
|
||||
}
|
||||
Reference in new issue
Block a user