import React, { useContext, useReducer, useEffect, ComponentType, Dispatch, Reducer, AnchorHTMLAttributes, useCallback, MouseEvent, MouseEventHandler, ReactNode } from 'react' import {UnionToIntersection} from '@karma.run/utility' import pathToRegexp, {Key} from 'path-to-regexp' import {useEventListener} from './hooks' export enum HistoryType { Push = 'push', Replace = 'replace' } export interface ScrollData { x: number y: number } export interface HistoryState { type: HistoryType path: string data?: any scroll?: ScrollData | null } export interface RouteContextState { readonly current: R | null readonly next: R | null readonly previous: R | null readonly history: HistoryState | null } export const RouteContext = React.createContext(null) export type RouteDispatchContextState = Dispatch< RouteAction > export const RouteDispatchContext = React.createContext(null) export enum RouteActionType { PushRoute = 'pushRoute', ReplaceRoute = 'replaceRoute', SetCurrentRoute = 'setCurrentRoute', SyncFromBrowser = 'syncFromBrowser' } export interface PushRouteAction { readonly type: RouteActionType.PushRoute readonly route: R } export function pushRoute(route: R): PushRouteAction { return {type: RouteActionType.PushRoute, route} } export interface ReplaceRouteAction { readonly type: RouteActionType.ReplaceRoute readonly route: R } export function replaceRoute( route: R ): ReplaceRouteAction { return {type: RouteActionType.ReplaceRoute, route} } export interface SetCurrentRouteAction { readonly type: RouteActionType.SetCurrentRoute readonly route: R } export function setCurrentRoute( route: R ): SetCurrentRouteAction { return {type: RouteActionType.SetCurrentRoute, route} } export interface SyncFromBrowser { readonly type: RouteActionType.SyncFromBrowser readonly route: R } export function syncFromBrowser( route: R ): SyncFromBrowser { return {type: RouteActionType.SyncFromBrowser, route} } export type RouteAction = | PushRouteAction | ReplaceRouteAction | SetCurrentRouteAction | SyncFromBrowser /** @deprecated Use route.path instead */ export function fullPathForRoute(route: RouteInstance) { return route.path } export function routeReducer( state: RouteContextState, action: RouteAction ): RouteContextState { switch (action.type) { case RouteActionType.PushRoute: return { current: state.current, next: action.route, previous: state.previous, history: { type: HistoryType.Push, path: action.route.path, data: action.route.data, scroll: action.route.scroll } } case RouteActionType.ReplaceRoute: return { current: state.current, next: action.route, previous: state.previous, history: { type: HistoryType.Replace, path: action.route.path, data: action.route.data, scroll: action.route.scroll } } case RouteActionType.SetCurrentRoute: return { current: action.route, next: null, previous: state.current, history: { type: HistoryType.Replace, path: action.route.path, data: action.route.data, scroll: action.route.scroll } } case RouteActionType.SyncFromBrowser: { return { current: state.current, next: action.route, previous: state.previous, history: null } } } } export interface RouteProviderProps { readonly initialRoute?: R | null readonly handleNextRoute?: HandleNextRouteFn readonly children?: ReactNode } export interface LinkProps { readonly route?: R } export interface LinkPropsWithAnchorAttributes extends LinkProps, AnchorHTMLAttributes {} export type LinkHOCCompatibleProps = {href?: string; onClick?: MouseEventHandler} export interface CreateRouteContextResult { readonly RouteProvider: ComponentType> readonly Link: ComponentType> useRoute(): RouteContextState useRouteDispatch(): RouteDispatchContextState matchRoute(url: string): R | null routeLink

( Component: ComponentType

): ComponentType

> } export type RouteResolveFn = (url: string) => R export type HandleNextRouteFn = ( route: R, dispatch: Dispatch> ) => () => void export function createRouteContext< T extends readonly Route[], R extends RouteInstancesForRoutes = RouteInstancesForRoutes >(routes: T): CreateRouteContextResult { function matchRoute(url: string): R | null { return matchRoutes(url, routes) } function useRouteDispatch(): RouteDispatchContextState { const routeDispatchContext = useContext(RouteDispatchContext) if (!routeDispatchContext) { throw new Error( "Couldn't find a RouteDispatchContext provider, did you forget to include RouteProvider in the component tree." ) } return routeDispatchContext as RouteDispatchContextState } function useRoute(): RouteContextState { const routeContext = useContext(RouteContext) if (!routeContext) { throw new Error( "Couldn't find a RouteContext provider, did you forget to include RouteProvider in the component tree." ) } return routeContext as RouteContextState } function Link({route, onClick, ...rest}: LinkPropsWithAnchorAttributes) { const dispatch = useRouteDispatch() const clickHandler = useCallback( (e: MouseEvent) => { if (onClick) onClick(e) if (e.isDefaultPrevented()) return e.preventDefault() dispatch(pushRoute(route!)) }, [route] ) if (route) { return } else { return } } function routeLink

( Component: ComponentType

): ComponentType

> { return ({route, onClick, ...rest}: P & LinkProps) => { const dispatch = useRouteDispatch() const clickHandler = useCallback( (e: MouseEvent) => { if (onClick) onClick(e) if (e.isDefaultPrevented()) return e.preventDefault() dispatch(pushRoute(route!)) }, [route] ) if (route) { return } else { return } } } function RouteProvider({initialRoute, handleNextRoute, children}: RouteProviderProps) { const [state, dispatch] = useReducer, RouteAction>>( routeReducer as Reducer, RouteAction>, { current: initialRoute || null, next: null, previous: null, history: null } ) // `dispatch` function identity will not change, but for consistency's sake we still add it to // the dependencies array. useEffect(() => { if (!state.next || !handleNextRoute) return return handleNextRoute(state.next, dispatch) }, [state.next, dispatch]) // Initialize if we don't have any route setup useEffect(() => { if (!state.next && !state.current) { const route = matchRoute(window.location.href) if (!route) return dispatch(syncFromBrowser(route)) } }, [state.next, state.current]) // Sync state with browser. useEffect(() => { if (state.history) { switch (state.history.type) { case HistoryType.Push: if (state.current) { // Save current scroll position into state window.history.replaceState( { scroll: {x: window.scrollX, y: window.scrollY}, data: state.current ? state.current.data : null }, '', window.location.href ) } window.history.pushState( {data: state.history.data, scroll: state.history.scroll}, '', state.history.path ) break case HistoryType.Replace: window.history.replaceState( {data: state.history.data, scroll: state.history.scroll}, '', state.history.path ) break } } }, [state.history]) useEventListener(() => [ window, 'popstate', (e: PopStateEvent) => { const route = matchRoute(window.location.href) if (!route) return route.data = e.state?.data ?? route.data route.scroll = e.state?.scroll ?? null dispatch(syncFromBrowser(route)) } ]) return ( {children} ) } return { Link, RouteProvider, matchRoute, useRouteDispatch, useRoute, routeLink } } export enum RouteParameterType { Required = 'required', Optional = 'optional', ZeroOrMore = 'zeroOrMore', OneOrMore = 'oneOrMore', Regexp = 'regexp' } export interface RequiredRouteParameter { readonly type: RouteParameterType.Required readonly key: K } export interface OptionalRouteParameter { readonly type: RouteParameterType.Optional readonly key: K } export interface ZeroOrMoreRouteParameter { readonly type: RouteParameterType.ZeroOrMore readonly key: K } export interface OneOrMoreRouteParameter { readonly type: RouteParameterType.OneOrMore readonly key: K } export interface RegexpRouteParameter { readonly type: RouteParameterType.Regexp readonly key: K readonly regexp: RegExp } export type RouteParameter = | RequiredRouteParameter | OptionalRouteParameter | ZeroOrMoreRouteParameter | OneOrMoreRouteParameter | RegexpRouteParameter function routeParamToPathParam(param: RouteParameter): string { switch (param.type) { case RouteParameterType.Required: return `:${param.key}` case RouteParameterType.Optional: return `:${param.key}?` case RouteParameterType.Regexp: return `:${param.key}(${param.regexp.source})` case RouteParameterType.ZeroOrMore: return `:${param.key}*` case RouteParameterType.OneOrMore: return `:${param.key}+` } } export function required(key: K): RequiredRouteParameter { return {type: RouteParameterType.Required, key} } export function optional(key: K): OptionalRouteParameter { return {type: RouteParameterType.Optional, key} } export function zeroOrMore(key: K): ZeroOrMoreRouteParameter { return {type: RouteParameterType.ZeroOrMore, key} } export function oneOrMore(key: K): OneOrMoreRouteParameter { return {type: RouteParameterType.OneOrMore, key} } export function regexp(key: K, regexp: RegExp): RegexpRouteParameter { return {type: RouteParameterType.Regexp, key, regexp} } export interface RouteInstance< T extends string = string, P extends RouteParameter[] = any, D = unknown > { type: T params: ObjectForParams

data: D pathname: string path: string query?: Record hash?: string scroll?: ScrollData | null } export interface Route { readonly type: T readonly path: RoutePath

readonly defaultData: D create(params: ObjectForParams

, opts?: CreateOptions): RouteInstance reverse(params: ObjectForParams

, query?: {[key: string]: string}, hash?: string): string match(path: string): ObjectForParams

| null } export interface CreateOptions { data?: D query?: {[key: string]: string} hash?: string scroll?: ScrollData | null } export function route( type: T, path: RoutePath

): Route export function route( type: T, path: RoutePath

, defaultData: D ): Route export function route( type: T, path: RoutePath

, defaultData: unknown = null ): Route { return { type, path, defaultData: defaultData || null, reverse: path.reverse, match: path.match, create( params, {data, query, hash, scroll}: CreateOptions = {} ): RouteInstance { return { type, params, pathname: path.reverse(params), path: path.reverse(params, query, hash), query, hash, data: data === undefined ? defaultData : data, scroll: scroll === undefined ? {x: 0, y: 0} : scroll } } } } export interface RoutePath

{ readonly path: string readonly regexp: RegExp readonly keys: Key[] readonly params: P reverse(params: ObjectForParams

, query?: Record, hash?: string): string match(path: string): ObjectForParams

| null } export function routePath

( template: TemplateStringsArray, ...params: P ): RoutePath

{ const path = template.reduce( (acc, path, index) => `${acc}${path}${params[index] ? routeParamToPathParam(params[index]) : ''}`, '' ) const keys: Key[] = [] const regexp = pathToRegexp(path, keys) const toPath = pathToRegexp.compile(path) return { path, regexp, keys, params, reverse(params: ObjectForParams

, query?: Record, hash?: string) { const queryString = new URLSearchParams(query).toString() const path = toPath(params as object) || '/' return `${path}${queryString ? `?${queryString}` : ''}${hash ? `#${hash}` : ''}` }, match(path: string) { const result = regexp.exec(path) if (!result) return null return keys.reduce( (acc, key, i) => ({[key.name]: result[i + 1], ...acc}), {} ) as ObjectForParams

} } } export type ObjectForParams

= UnionToIntersection< { [K in keyof P]: P[K] extends | RequiredRouteParameter | RegexpRouteParameter | OneOrMoreRouteParameter ? {[PK in P[K]['key']]: string} : P[K] extends OptionalRouteParameter | ZeroOrMoreRouteParameter ? {[PK in P[K]['key']]?: string} : {} }[number] > export function matchRoutes>( url: string | URL, routes: R ): I | null { url = url instanceof URL ? url : new URL(url) for (const route of routes) { const match = route.match(url.pathname) if (match) { const queryObj = Object.fromEntries(url.searchParams.entries()) return { type: route.type, data: route.defaultData, params: match, query: Object.keys(queryObj).length ? queryObj : undefined, hash: url.hash.slice(1) || undefined, path: url.pathname + url.search + url.hash, pathname: url.pathname } as I } } return null } export type RouteInstancesForRoutes = { [K in keyof R]: R[K] extends Route ? RouteInstance : never }[number]