- 예전 화면(/, /a)과 목업 데이터를 지우고 시안 B 를 / 로 - @hey-api/openapi-ts 로 타입·TanStack Query 함수 생성, 토큰·401 갱신 처리 - 공유는 기본 공유창, 없으면 링크 복사 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
71 lines
2.4 KiB
TypeScript
71 lines
2.4 KiB
TypeScript
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
|
import { nearestRegion } from '../api/client/sdk.gen'
|
|
import type { RegionData } from '../api/client/types.gen'
|
|
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
|
|
|
const KEY = 'nalssigak.b.region'
|
|
|
|
function readStored(): RegionData | null {
|
|
try {
|
|
const raw = localStorage.getItem(KEY)
|
|
return raw ? (JSON.parse(raw) as RegionData) : null
|
|
} catch {
|
|
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 기본 구로 시작
|
|
return null
|
|
}
|
|
}
|
|
|
|
function writeStored(r: RegionData) {
|
|
try {
|
|
localStorage.setItem(KEY, JSON.stringify(r))
|
|
} catch {
|
|
// 저장이 막혀도 이번 방문 동안은 메모리 값으로 계속 쓴다
|
|
return
|
|
}
|
|
}
|
|
|
|
export function RegionProvider({ children }: { children: ReactNode }) {
|
|
const [stored] = useState(readStored)
|
|
const [region, setRegionState] = useState<RegionData>(stored ?? DEFAULT_REGION)
|
|
const canLocate = typeof navigator !== 'undefined' && 'geolocation' in navigator
|
|
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!stored && canLocate ? 'locating' : 'idle')
|
|
|
|
const setRegion = useCallback((r: RegionData) => {
|
|
setRegionState(r)
|
|
writeStored(r)
|
|
}, [])
|
|
|
|
const findNearest = useCallback(() => {
|
|
navigator.geolocation.getCurrentPosition(
|
|
(pos) => {
|
|
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
|
.then(({ data: res }) => {
|
|
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
|
setRegion(res.region)
|
|
setLocateStatus('idle')
|
|
})
|
|
.catch(() => setLocateStatus('error'))
|
|
},
|
|
(err) => setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
|
{ timeout: 10000, maximumAge: 600000 },
|
|
)
|
|
}, [setRegion])
|
|
|
|
const locate = useCallback(() => {
|
|
if (!canLocate) {
|
|
setLocateStatus('error')
|
|
return
|
|
}
|
|
setLocateStatus('locating')
|
|
findNearest()
|
|
}, [canLocate, findNearest])
|
|
|
|
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
|
useEffect(() => {
|
|
if (!stored && canLocate) findNearest()
|
|
}, [stored, canLocate, findNearest])
|
|
|
|
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus])
|
|
return <RegionContext value={api}>{children}</RegionContext>
|
|
}
|