Merge remote-tracking branch 'origin/main' into feat/apps-in-toss
# Conflicts: # TODO.md # backend/crud/user_crud.py # backend/router/v1/auth/account.py # backend/router/v1/auth/protocol.py # backend/services/auth_service.py # compose.yaml # docs/이벤트_추적.md # frontend/src/api/client/@tanstack/react-query.gen.ts # frontend/src/api/client/index.ts # frontend/src/api/client/sdk.gen.ts # frontend/src/api/client/types.gen.ts # frontend/src/b/Sheets.tsx # frontend/src/b/region.tsx # frontend/src/lib/analytics.ts
This commit is contained in:
commit
84212099e6
285 files changed
+39026
-767
No files matched your search
+79
-31
@@ -1,12 +1,27 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router'
|
||||
import regionPages from '../../seo/region.json'
|
||||
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'
|
||||
import { DEFAULT_REGION, ownPage, RegionContext, type LocateStatus } from './regionContext'
|
||||
|
||||
const KEY = 'nalssigak.b.region'
|
||||
|
||||
type RegionPage = (typeof regionPages)[number]
|
||||
|
||||
/** /today/gyeonggi/seongnam, /tomorrow/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
|
||||
function pageOf(pathname: string): RegionPage | undefined {
|
||||
const path = pathname.match(/^\/(?:today|tomorrow)\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
|
||||
return path ? regionPages.find((p) => p.path === path) : undefined
|
||||
}
|
||||
|
||||
/** 지역 페이지 안의 구: 구로 나뉜 시는 r 이 그 시 안이면 r, 아니면 시청이 있는 구 */
|
||||
function regionIn(page: RegionPage, r?: RegionData | null): RegionData {
|
||||
return page.regions.find((g) => g.code === r?.code) ?? page.regions.find((g) => g.code === page.main)!
|
||||
}
|
||||
|
||||
function readStored(): RegionData | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY)
|
||||
@@ -27,50 +42,62 @@ function writeStored(r: RegionData) {
|
||||
}
|
||||
|
||||
export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
const { pathname } = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const page = pageOf(pathname)
|
||||
const pageRef = useRef(page)
|
||||
const dayRef = useRef(pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today')
|
||||
useEffect(() => {
|
||||
pageRef.current = page
|
||||
dayRef.current = pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today'
|
||||
}, [page, pathname])
|
||||
const [stored] = useState(readStored)
|
||||
const [region, setRegionState] = useState<RegionData>(stored ?? DEFAULT_REGION)
|
||||
const [landing] = useState(page)
|
||||
const [chosen, setRegionState] = useState<RegionData>(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION)))
|
||||
// 앱 안에서 다른 지역 페이지로 옮겨 가면 그 지역으로
|
||||
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>((!stored || IS_TOSS) && canLocate ? 'locating' : 'idle')
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!landing && (!stored || IS_TOSS) && canLocate ? 'locating' : 'idle')
|
||||
|
||||
// 지역 페이지에서 고르면 주소도 그 지역 페이지로 바꿔, 공유한 링크가 보던 화면과 같게 한다
|
||||
const setRegion = useCallback((r: RegionData) => {
|
||||
setRegionState(r)
|
||||
writeStored(r)
|
||||
}, [])
|
||||
const next = ownPage(r.code)
|
||||
if (pageRef.current && next && next !== pageRef.current) navigate(`/${dayRef.current}/${next.path}`)
|
||||
}, [navigate])
|
||||
|
||||
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) => {
|
||||
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음). ask=false 면 토스에서 권한 창 없이, 이미 허용한 사람만
|
||||
const findNearest = useCallback((apply: (r: RegionData) => void, quiet = false, ask = true) => {
|
||||
const fromCoords = (lat: number, lon: number) => {
|
||||
nearestRegion({ query: { lat, lon } })
|
||||
.then(({ data: res }) => {
|
||||
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
||||
setLocateStatus('idle')
|
||||
apply(res.region)
|
||||
})
|
||||
.catch(() => !quiet && setLocateStatus('error'))
|
||||
}
|
||||
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)
|
||||
else if (loc === 'denied') setLocateStatus(quiet ? 'idle' : 'denied')
|
||||
else fromCoords(loc.lat, loc.lon)
|
||||
},
|
||||
(e: unknown) => {
|
||||
console.error('[region] toss location', e)
|
||||
setLocateStatus('error')
|
||||
setLocateStatus(quiet ? 'idle' : 'error')
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => fromCoords(pos.coords.latitude, pos.coords.longitude, onFound),
|
||||
(err) => setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||
(pos) => fromCoords(pos.coords.latitude, pos.coords.longitude),
|
||||
(err) => !quiet && setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||
{ timeout: 10000, maximumAge: 600000 },
|
||||
)
|
||||
}, [fromCoords])
|
||||
}, [])
|
||||
|
||||
const locate = useCallback((onFound?: () => void) => {
|
||||
if (!canLocate) {
|
||||
@@ -78,15 +105,36 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
return
|
||||
}
|
||||
setLocateStatus('locating')
|
||||
findNearest(onFound)
|
||||
}, [canLocate, findNearest])
|
||||
findNearest((r) => {
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'location' })
|
||||
onFound?.()
|
||||
})
|
||||
}, [canLocate, findNearest, setRegion])
|
||||
|
||||
// 처음 온 사람은 위치 권한을 물어 가장 가까운 구로 맞춘다. 토스판은 지역을 고른 적 있어도 권한이 있으면 들어올 때마다 지금 위치로
|
||||
useEffect(() => {
|
||||
if (!canLocate) return
|
||||
if (!stored) findNearest()
|
||||
else if (IS_TOSS) findNearest(undefined, false)
|
||||
}, [stored, canLocate, findNearest])
|
||||
// 처음 온 사람은 위치 권한을 물어 가장 가까운 구로 맞춘다. 토스판은 지역을 고른 적 있어도 권한이 있으면 들어올 때마다 지금 위치로
|
||||
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)
|
||||
return
|
||||
}
|
||||
// 지역 페이지로 들어오면 그 지역을 보여 준다. 구로 나뉜 시는 위치를 이미 허용했고 그 시 안에 있으면 지금 있는 구로
|
||||
if (landing.regions.length < 2) return
|
||||
navigator.permissions?.query({ name: 'geolocation' })
|
||||
.then((s) => {
|
||||
if (s.state !== 'granted') return
|
||||
findNearest((r) => {
|
||||
if (pageRef.current === landing && landing.regions.some((g) => g.code === r.code)) setRegionState(r)
|
||||
}, true)
|
||||
})
|
||||
.catch((e) => console.warn('위치 권한 상태를 읽지 못함', e))
|
||||
}, [canLocate, landing, stored, findNearest, setRegion])
|
||||
|
||||
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus])
|
||||
return <RegionContext value={api}>{children}</RegionContext>
|
||||
|
||||
Reference in new issue
Block a user