Files
o2o-weather/frontend/src/b/regionContext.ts
T

37 lines
1.8 KiB
TypeScript

import { createContext, use } from 'react'
import { useLocation } from 'react-router'
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
import regionPages from '../../seo/region.json'
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus }
export { DEFAULT_REGION } from '@nalssigak/shared/lib'
/** 구 하나만 보여 주는 지역 페이지: 일반 시군구, 또는 구로 나뉜 시의 구 페이지 */
export const ownPage = (code: string) => regionPages.find((p) => p.regions.length === 1 && p.regions[0].code === code)
/** /today/gyeonggi/seongnam, /tomorrow/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
export function pageOf(pathname: string) {
const path = pathname.match(/^\/(?:today|tomorrow)\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
return path ? regionPages.find((p) => p.path === path) : undefined
}
/** 지역 페이지로 들어오면 서버가 채운 소개 글(#root 안)을 앱이 덮기 전에 잡아 둔다. 구글은 JS 실행 뒤 화면으로 색인한다 */
const landingAbout = pageOf(location.pathname) ? { path: location.pathname, html: document.querySelector('#root > main')?.innerHTML ?? '' } : null
/** 들어온 지역 페이지에 그대로 있을 때만 그 소개 글 */
export function useLandingAbout(): string | null {
const { pathname } = useLocation()
return landingAbout?.html && landingAbout.path === pathname ? landingAbout.html : null
}
export const RegionContext = createContext<RegionApi | null>(null)
export function useRegion() {
const ctx = use(RegionContext)
if (!ctx) throw new Error('useRegion must be used inside RegionProvider')
return ctx
}