feat: 위치로 맞춘 사람은 새로고침하거나 탭으로 돌아올 때 지금 위치로 다시 맞춤 — 목록에서 고른 지역은 그대로, 토스도 같은 규칙, 위치는 1분마다 새로 읽음, 지역_변경에 method auto 추가
This commit is contained in:
1 parent
ceb700f0a8
commit
95ac3de7fe
5 files changed
+84
-19
No files matched your search
+76
-15
@@ -8,6 +8,13 @@ import { IS_TOSS, tossLocation } from '../lib/platform'
|
||||
import { DEFAULT_REGION, ownPage, pageOf, RegionContext, type LocateStatus } from './regionContext'
|
||||
|
||||
const KEY = 'nalssigak.b.region'
|
||||
/** 저장된 지역이 정해진 방법. 값이 없으면(예전에 저장한 사람) 직접 고른 것으로 본다 */
|
||||
const BY_KEY = 'nalssigak.b.region.by'
|
||||
/** 위치를 새로 읽는 간격. 이보다 최근에 읽은 위치는 그대로 쓰고, 자동으로 다시 맞추는 것도 이 간격에 한 번만 한다 */
|
||||
const LOCATION_FRESH = 60_000
|
||||
|
||||
/** location: 위치로 맞춤 (들어올 때마다 지금 위치를 따라감), list: 목록에서 고름 (그대로 둠) */
|
||||
type By = 'location' | 'list'
|
||||
|
||||
type RegionPage = (typeof regionPages)[number]
|
||||
|
||||
@@ -26,9 +33,19 @@ function readStored(): RegionData | null {
|
||||
}
|
||||
}
|
||||
|
||||
function writeStored(r: RegionData) {
|
||||
function readBy(): By {
|
||||
try {
|
||||
return localStorage.getItem(BY_KEY) === 'location' ? 'location' : 'list'
|
||||
} catch {
|
||||
// 저장소를 못 쓰면 저장된 지역도 없어, 처음 온 사람처럼 위치를 묻는다
|
||||
return 'list'
|
||||
}
|
||||
}
|
||||
|
||||
function writeStored(r: RegionData, by: By) {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(r))
|
||||
localStorage.setItem(BY_KEY, by)
|
||||
} catch {
|
||||
// 저장이 막혀도 이번 방문 동안은 메모리 값으로 계속 쓴다
|
||||
return
|
||||
@@ -51,16 +68,26 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
// 앱 안에서 다른 지역 페이지로 옮겨 가면 그 지역으로
|
||||
const region = page && !page.regions.some((g) => g.code === chosen.code) ? regionIn(page, stored) : chosen
|
||||
const canLocate = IS_TOSS || (typeof navigator !== 'undefined' && 'geolocation' in navigator)
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!landing && (!stored || IS_TOSS) && canLocate ? 'locating' : 'idle')
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!landing && !stored && canLocate ? 'locating' : 'idle')
|
||||
const [storedBy] = useState(readBy)
|
||||
const byRef = useRef(storedBy)
|
||||
const codeRef = useRef(region.code)
|
||||
useEffect(() => {
|
||||
codeRef.current = region.code
|
||||
}, [region.code])
|
||||
const followedAt = useRef(0)
|
||||
|
||||
// 지역 페이지에서 고르면 주소도 그 지역 페이지로 바꿔, 공유한 링크가 보던 화면과 같게 한다
|
||||
const setRegion = useCallback((r: RegionData) => {
|
||||
const save = useCallback((r: RegionData, by: By) => {
|
||||
setRegionState(r)
|
||||
writeStored(r)
|
||||
writeStored(r, by)
|
||||
byRef.current = by
|
||||
const next = ownPage(r.code)
|
||||
if (pageRef.current && next && next !== pageRef.current) navigate(`/${dayRef.current}/${next.path}`)
|
||||
}, [navigate])
|
||||
|
||||
const setRegion = useCallback((r: RegionData) => save(r, 'list'), [save])
|
||||
|
||||
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음). ask=false 면 토스에서 권한 창 없이, 이미 허용한 사람만
|
||||
const findNearest = useCallback((apply: (r: RegionData) => void, quiet = false, ask = true) => {
|
||||
const fromCoords = (lat: number, lon: number) => {
|
||||
@@ -89,10 +116,34 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => fromCoords(pos.coords.latitude, pos.coords.longitude),
|
||||
(err) => !quiet && setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||
{ timeout: 10000, maximumAge: 600000 },
|
||||
{ timeout: 10000, maximumAge: LOCATION_FRESH },
|
||||
)
|
||||
}, [])
|
||||
|
||||
// 위치로 맞춘 사람은 권한이 이미 있으면 조용히 지금 위치로 다시 맞춘다. 목록에서 고른 지역과 지역 페이지는 건드리지 않는다
|
||||
const follow = useCallback(() => {
|
||||
if (pageRef.current || byRef.current !== 'location') return
|
||||
const now = Date.now()
|
||||
if (now - followedAt.current < LOCATION_FRESH) return
|
||||
followedAt.current = now
|
||||
const apply = (r: RegionData) => {
|
||||
// 위치를 읽는 사이에 목록에서 골랐거나 지역 페이지로 옮겼으면 그대로 둔다
|
||||
if (pageRef.current || byRef.current !== 'location' || r.code === codeRef.current) return
|
||||
save(r, 'location')
|
||||
track('region_change', { region_name: r.name, method: 'auto' })
|
||||
}
|
||||
// 토스는 이미 허용한 경우에만(ask=false) 위치를 준다
|
||||
if (IS_TOSS) {
|
||||
findNearest(apply, true, false)
|
||||
return
|
||||
}
|
||||
navigator.permissions?.query({ name: 'geolocation' })
|
||||
.then((s) => {
|
||||
if (s.state === 'granted') findNearest(apply, true)
|
||||
})
|
||||
.catch((e) => console.warn('위치 권한 상태를 읽지 못함', e))
|
||||
}, [findNearest, save])
|
||||
|
||||
const locate = useCallback((onFound?: () => void) => {
|
||||
if (!canLocate) {
|
||||
setLocateStatus('error')
|
||||
@@ -100,22 +151,22 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
setLocateStatus('locating')
|
||||
findNearest((r) => {
|
||||
setRegion(r)
|
||||
save(r, 'location')
|
||||
track('region_change', { region_name: r.name, method: 'location' })
|
||||
onFound?.()
|
||||
})
|
||||
}, [canLocate, findNearest, setRegion])
|
||||
}, [canLocate, findNearest, save])
|
||||
|
||||
useEffect(() => {
|
||||
if (!canLocate) return
|
||||
// 처음 온 사람은 위치 권한을 물어 가장 가까운 구로 맞춘다. 토스판은 지역을 고른 적 있어도 권한이 있으면 들어올 때마다 지금 위치로
|
||||
// 처음 온 사람은 위치 권한을 물어 가장 가까운 구로 맞춘다. 다시 온 사람은 위치로 맞춘 경우에만 지금 위치로 다시 맞춘다
|
||||
if (!landing) {
|
||||
const apply = (r: RegionData) => {
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'location' })
|
||||
}
|
||||
if (!stored) findNearest(apply)
|
||||
else if (IS_TOSS) findNearest(apply, false, false)
|
||||
if (stored) follow()
|
||||
else
|
||||
findNearest((r) => {
|
||||
save(r, 'location')
|
||||
track('region_change', { region_name: r.name, method: 'location' })
|
||||
})
|
||||
return
|
||||
}
|
||||
// 지역 페이지로 들어오면 그 지역을 보여 준다. 구로 나뉜 시는 위치를 이미 허용했고 그 시 안에 있으면 지금 있는 구로
|
||||
@@ -128,7 +179,17 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
}, true)
|
||||
})
|
||||
.catch((e) => console.warn('위치 권한 상태를 읽지 못함', e))
|
||||
}, [canLocate, landing, stored, findNearest, setRegion])
|
||||
}, [canLocate, landing, stored, findNearest, save, follow])
|
||||
|
||||
// 탭으로 돌아왔을 때도 다시 맞춘다
|
||||
useEffect(() => {
|
||||
if (!canLocate) return
|
||||
const onShow = () => {
|
||||
if (document.visibilityState === 'visible') follow()
|
||||
}
|
||||
document.addEventListener('visibilitychange', onShow)
|
||||
return () => document.removeEventListener('visibilitychange', onShow)
|
||||
}, [canLocate, follow])
|
||||
|
||||
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus])
|
||||
return <RegionContext value={api}>{children}</RegionContext>
|
||||
|
||||
Reference in new issue
Block a user