94 lines
3.4 KiB
TypeScript
94 lines
3.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 { track } from '../lib/analytics'
|
|
import { IS_TOSS, tossLocation } from '../lib/platform'
|
|
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 = IS_TOSS || (typeof navigator !== 'undefined' && 'geolocation' in navigator)
|
|
const [locateStatus, setLocateStatus] = useState<LocateStatus>((!stored || IS_TOSS) && canLocate ? 'locating' : 'idle')
|
|
|
|
const setRegion = useCallback((r: RegionData) => {
|
|
setRegionState(r)
|
|
writeStored(r)
|
|
}, [])
|
|
|
|
const fromCoords = useCallback((lat: number, lon: number, onFound?: () => void) => {
|
|
nearestRegion({ query: { lat, lon } })
|
|
.then(({ data: res }) => {
|
|
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
|
setRegion(res.region)
|
|
setLocateStatus('idle')
|
|
track('region_change', { region_name: res.region.name, method: 'location' })
|
|
onFound?.()
|
|
})
|
|
.catch(() => setLocateStatus('error'))
|
|
}, [setRegion])
|
|
|
|
// ask=false 면 토스에서 권한 창 없이, 이미 허용한 사람만 위치로 맞춘다
|
|
const findNearest = useCallback((onFound?: () => void, ask = true) => {
|
|
if (IS_TOSS) {
|
|
tossLocation(ask).then(
|
|
(loc) => {
|
|
if (loc === null) setLocateStatus('idle')
|
|
else if (loc === 'denied') setLocateStatus('denied')
|
|
else fromCoords(loc.lat, loc.lon, onFound)
|
|
},
|
|
(e: unknown) => {
|
|
console.error('[region] toss location', e)
|
|
setLocateStatus('error')
|
|
},
|
|
)
|
|
return
|
|
}
|
|
navigator.geolocation.getCurrentPosition(
|
|
(pos) => fromCoords(pos.coords.latitude, pos.coords.longitude, onFound),
|
|
(err) => setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
|
{ timeout: 10000, maximumAge: 600000 },
|
|
)
|
|
}, [fromCoords])
|
|
|
|
const locate = useCallback((onFound?: () => void) => {
|
|
if (!canLocate) {
|
|
setLocateStatus('error')
|
|
return
|
|
}
|
|
setLocateStatus('locating')
|
|
findNearest(onFound)
|
|
}, [canLocate, findNearest])
|
|
|
|
// 처음 온 사람은 위치 권한을 물어 가장 가까운 구로 맞춘다. 토스판은 지역을 고른 적 있어도 권한이 있으면 들어올 때마다 지금 위치로
|
|
useEffect(() => {
|
|
if (!canLocate) return
|
|
if (!stored) findNearest()
|
|
else if (IS_TOSS) findNearest(undefined, false)
|
|
}, [stored, canLocate, findNearest])
|
|
|
|
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus])
|
|
return <RegionContext value={api}>{children}</RegionContext>
|
|
}
|