Skip to content

Commit

Permalink
Rename ROUTERS to Routers
Browse files Browse the repository at this point in the history
  • Loading branch information
willybrauner committed Nov 9, 2023
1 parent 6ebbb1d commit 9aee243
Show file tree
Hide file tree
Showing 11 changed files with 84 additions and 85 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ Services:
Global:

- [`Helpers`](#Helpers) Global Routers helpers
- [`Routers object`](#Routers) Global Routers object contains all routers properties (history, instances...)
- [`Routers object`](#Routers) Global Routers object contains all Routers properties (history, instances...)

## Installation

Expand Down Expand Up @@ -202,8 +202,8 @@ const routesList = [

## Sub-router

cher-ami router supports nested routes from sub routers instance 🙏🏽.
It is possible to nest as many routers as you want.
cher-ami router supports nested routes from sub Routers instance 🙏🏽.
It is possible to nest as many Routers as you want.

1. Define children routes in initial routes list with `children` property;

Expand Down Expand Up @@ -883,7 +883,7 @@ Push new route in current history. Stack(s) component(s) will return the appriop
## Routers
Routers is a global object who contains all routers informations. Because @cher-ami/router is possibly multi-stack, we need a global object to store shared informations between router instances.
Routers is a global object who contains all Routers informations. Because @cher-ami/router is possibly multi-stack, we need a global object to store shared informations between router instances.
#### Routers.routes
Expand Down
66 changes: 33 additions & 33 deletions src/components/Router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import React, {
} from "react"
import { formatRoutes, TParams, TQueryParams } from "../core/core"
import { getNotFoundRoute, getRouteFromUrl } from "../core/core"
import { ROUTERS } from "../core/ROUTERS"
import { Routers } from "../core/Routers"
import LangService, { TLanguage } from "../core/LangService"
import { staticPropsCache } from "../core/staticPropsCache"
import { isSSR, removeLastCharFromString } from "../core/helpers"
Expand Down Expand Up @@ -115,7 +115,7 @@ function Router(props: {
}): JSX.Element {
/**
* Check if is the first router or a sub-router
* If is the first router, reset ROUTERS store
* If is the first router, reset Routers store
*/
const IS_CLIENT_OR_SERVER_ROOT_ROUTER = useMemo(() => {
// base on supposition that:
Expand All @@ -124,37 +124,37 @@ function Router(props: {
const isRootRouter = !!props.staticLocation || !!props.history
log(props.id, "IS_CLIENT_OR_SERVER_ROOT_ROUTER", isRootRouter)

// reset ROUTERS store
// reset Routers store
if (IS_SERVER && isRootRouter) {
ROUTERS.base = undefined
ROUTERS.routes = undefined
ROUTERS.history = undefined
ROUTERS.staticLocation = undefined
ROUTERS.routeCounter = 1
ROUTERS.isFirstRoute = true
ROUTERS.currentRoute = undefined
ROUTERS.langService = undefined
ROUTERS.staticPropsCache = {}
Routers.base = undefined
Routers.routes = undefined
Routers.history = undefined
Routers.staticLocation = undefined
Routers.routeCounter = 1
Routers.isFirstRoute = true
Routers.currentRoute = undefined
Routers.langService = undefined
Routers.staticPropsCache = {}
}
return isRootRouter
}, [props.id, props.staticLocation, props.history])

/**
* 0. LangService
* Check if langService props exist.
* If props exist, store langService instance in ROUTERS store.
* If props exist, store langService instance in Routers store.
*/
const langService = useMemo(() => {
if (IS_CLIENT_OR_SERVER_ROOT_ROUTER) {
ROUTERS.langService = props.langService
Routers.langService = props.langService
}
return ROUTERS.langService
return Routers.langService
}, [props.langService])

/**
* 1. routes
* Format and return routes list
* If is the first Router instance, register routes in 'ROUTERS' store.
* If is the first Router instance, register routes in 'Routers' store.
* In other case, return current props.routes
*
* const { routes } = useRouter();
Expand All @@ -169,8 +169,8 @@ function Router(props: {
)

// register is Store if...
if (!ROUTERS.routes && props.routes) {
ROUTERS.routes = routesList
if (!Routers.routes && props.routes) {
Routers.routes = routesList
}

// return current instance routes list
Expand All @@ -180,38 +180,38 @@ function Router(props: {
/**
* 2. base
* Format and return base URL
* Register base in 'ROUTERS' obj if is the first Router instance
* Register base in 'Routers' obj if is the first Router instance
* In all case, return current props.base
*/
if (!ROUTERS.base) {
ROUTERS.base = props.base
if (!Routers.base) {
Routers.base = props.base
}
const base = ROUTERS.base
const base = Routers.base

/**
* 3. history
* If is the first Router instance, register history in 'ROUTERS' store
* If is the first Router instance, register history in 'Routers' store
* 'history' object need to be the same between each Router instance
*/
if (!ROUTERS.history && props.history) {
ROUTERS.history = props.history
if (!Routers.history && props.history) {
Routers.history = props.history
}
const history = ROUTERS.history
const history = Routers.history

/**
* 4 static location
* Is useful in SSR context
*/
if (props.staticLocation) {
ROUTERS.staticLocation = props.staticLocation
Routers.staticLocation = props.staticLocation
}
const staticLocation: string | undefined = ROUTERS.staticLocation
const staticLocation: string | undefined = Routers.staticLocation

/**
* 5. reset is fist route visited
*/
if (IS_SERVER) {
ROUTERS.isFirstRoute = true
Routers.isFirstRoute = true
}

// -------------------------------------------------------------------------------- ROUTE CHANGE
Expand Down Expand Up @@ -334,7 +334,7 @@ function Router(props: {
// CLIENT
else {
// CLIENT > FIRST ROUTE
if (ROUTERS.isFirstRoute) {
if (Routers.isFirstRoute) {
if (props.initialStaticProps) {
log(props.id, "firstRoute > isClient > assign initialStaticProps to newRoute props & set cache");
Object.assign(newRoute.props, props.initialStaticProps?.props ?? {});
Expand Down Expand Up @@ -363,10 +363,10 @@ function Router(props: {
// Final process: update context currentRoute from dispatch method \o/ !
dispatch({ type: "update-current-route", value: newRoute })

// & register this new route as currentRoute in local and in ROUTERS store
// & register this new route as currentRoute in local and in Routers store
currentRouteRef.current = newRoute
ROUTERS.currentRoute = newRoute
ROUTERS.isFirstRoute = false
Routers.currentRoute = newRoute
Routers.isFirstRoute = false
}

/**
Expand Down
7 changes: 3 additions & 4 deletions src/core/LangService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ROUTERS } from "./ROUTERS"
import { Routers } from "./Routers"
import { compileUrl, createUrl } from "./core"
import { isSSR, joinPaths, removeLastCharFromString } from "./helpers"
import { TRoute } from "../components/Router"
Expand Down Expand Up @@ -97,7 +97,7 @@ class LangService<TLang = any> {
public setLang(
toLang: TLanguage<TLang>,
forcePageReload = true,
currentRoute: TRoute = ROUTERS.currentRoute,
currentRoute: TRoute = Routers.currentRoute,
): void {
if (toLang.key === this.currentLang.key) {
log("setLang: This is the same language, exit.")
Expand Down Expand Up @@ -142,7 +142,6 @@ class LangService<TLang = any> {
}

// 3. if current lang is default lang, add /currentLang.key after base
// else if (this.needToContainLangInUrl(toLang.key)) {
else if (!this.showDefaultLangInUrl && this.isDefaultLangKey(this.currentLang.key)) {
const newUrlWithoutBase = preparedNewUrl.substring(
this.base.length,
Expand Down Expand Up @@ -415,7 +414,7 @@ class LangService<TLang = any> {
*/
protected reloadOrRefresh(newUrl: string, forcePageReload = true): void {
if (isSSR()) return
forcePageReload ? window?.open(newUrl, "_self") : ROUTERS.history.push(newUrl)
forcePageReload ? window?.open(newUrl, "_self") : Routers.history.push(newUrl)
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/core/routers.ts → src/core/Routers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ export type TRouters = {
}

/**
* ROUTERS object allows to keep safe globales values between ROUTERS instances
* ROUTERS object allows to keep safe globales values between Routers instances
* This object values do not depend of one single router
*/
export const ROUTERS: TRouters = {
export const Routers: TRouters = {
base: undefined,
routes: undefined,
history: undefined,
Expand Down
42 changes: 21 additions & 21 deletions src/core/core.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ROUTERS } from "./ROUTERS"
import { Routers } from "./Routers"
import debug from "@cher-ami/debug"
import { compile, match } from "path-to-regexp"
import { TRoute } from "../components/Router"
Expand Down Expand Up @@ -31,21 +31,21 @@ export type TOpenRouteParams = {
*/
export function createUrl(
args: string | TOpenRouteParams,
base: string = ROUTERS.base,
allRoutes: TRoute[] = ROUTERS.routes,
langService = ROUTERS.langService,
base: string = Routers.base,
allRoutes: TRoute[] = Routers.routes,
langService = Routers.langService,
): string {
if (!allRoutes) return
let finalURL: string
let urlToPush: string

// STRING param
if (typeof args === "string") {
finalURL = args as string
urlToPush = args as string
if (!!langService) {
finalURL = addLangToUrl(finalURL)
urlToPush = addLangToUrl(urlToPush)
}
finalURL = joinPaths([base === "/" ? "" : base, finalURL])
return finalURL
urlToPush = joinPaths([base === "/" ? "" : base, urlToPush])
return urlToPush
}

// OBJECT param, add lang to params if no exist
Expand Down Expand Up @@ -73,7 +73,7 @@ export function createUrl(

return getUrlByRouteName(allRoutes, args, base) + queryParams + hash

// in other case return
// in other case return.
} else {
console.warn("createUrl param isn't valid. to use createUrl return.", args)
return
Expand All @@ -96,7 +96,7 @@ export function getSubRouterBase(
): string {
// case langService is init, and we don't want to show default lang in URL, and we are on default lang.
// /:lang is return as path, but we want to get no lang in returned base string
const addLang = ROUTERS.langService?.showLangInUrl() && addLangToUrl ? "/:lang" : ""
const addLang = Routers.langService?.showLangInUrl() && addLangToUrl ? "/:lang" : ""
const pathAfterLang = path === "/:lang" ? getLangPath("/") : getLangPath(path)
return joinPaths([base, addLang, pathAfterLang])
}
Expand All @@ -114,7 +114,7 @@ export function getSubRouterRoutes(
// case langService is init, and we don't want to show default lang in URL, and we are on default lang.
// /:lang is return as path, but we want to search path with "/" instead
const formattedPath =
!ROUTERS.langService?.showLangInUrl() && path === "/:lang" ? "/" : path
!Routers.langService?.showLangInUrl() && path === "/:lang" ? "/" : path

return routes.find((route) => {
return getLangPath(route.path) === getLangPath(formattedPath)
Expand All @@ -137,7 +137,7 @@ export function getPathByRouteName(
if (route.name === name || route?.component?.displayName === name) {
// specific case, we want to retrieve path of route with "/" route and langService is used,
// we need to patch it with lang param
if (route.path === "/" && ROUTERS.langService) {
if (route.path === "/" && Routers.langService) {
return "/:lang"
} else {
return route.path
Expand All @@ -159,7 +159,7 @@ export function getPathByRouteName(
* @param args can be string or TOpenRouteParams object
* @param history
*/
export function openRoute(args: string | TOpenRouteParams, history = ROUTERS?.history) {
export function openRoute(args: string | TOpenRouteParams, history = Routers?.history) {
const url = typeof args === "string" ? args : createUrl(args)
history?.push(url)
}
Expand Down Expand Up @@ -404,7 +404,7 @@ export const extractQueryParamsAndHash = (
* ]
* @param routes
*/
export function patchMissingRootRoute(routes: TRoute[] = ROUTERS.routes): TRoute[] {
export function patchMissingRootRoute(routes: TRoute[] = Routers.routes): TRoute[] {
if (!routes) {
log("routes doesnt exist, return", routes)
return
Expand Down Expand Up @@ -448,7 +448,7 @@ export function applyMiddlewaresToRoutes(

/**
* Format and return routes list
* If is the first Router instance, register routes in 'ROUTERS' store.
* If is the first Router instance, register routes in 'Routers' store.
* In other case, return current props.routes
*/
export function formatRoutes(
Expand Down Expand Up @@ -498,7 +498,7 @@ export function getFullPathByPath(
routes: TRoute[],
path: string | { [x: string]: string },
routeName: string,
lang: string = ROUTERS.langService?.currentLang.key || undefined,
lang: string = Routers.langService?.currentLang.key || undefined,
basePath: string = null,
): string {
let localPath: string[] = [basePath]
Expand Down Expand Up @@ -550,7 +550,7 @@ export function getFullPathByPath(
export function getUrlByRouteName(
pRoutes: TRoute[],
pParams: TOpenRouteParams,
base: string,
base?: string,
): string {
// need to wrap the function to be able to access the preserved "pRoutes" param
// in local scope after recursion
Expand Down Expand Up @@ -603,7 +603,7 @@ export function getUrlByRouteName(
*/
export function getLangPath(
langPath: string | { [p: string]: string },
lang: string = ROUTERS.langService?.currentLang.key,
lang: string = Routers.langService?.currentLang.key,
) {
let path
if (typeof langPath === "string") {
Expand Down Expand Up @@ -639,8 +639,8 @@ export function getLangPath(
*/
export function addLangToUrl(
url: string,
lang: string = ROUTERS.langService?.currentLang.key,
enable = ROUTERS.langService?.showLangInUrl(),
lang: string = Routers.langService?.currentLang.key,
enable = Routers.langService?.showLangInUrl(),
): string {
if (!enable) return url
url = joinPaths([`/${lang}`, url === "/" ? "" : url])
Expand Down
4 changes: 2 additions & 2 deletions src/core/staticPropsCache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ROUTERS } from "./ROUTERS"
import { Routers } from "./Routers"
import debug from "@cher-ami/debug"
const componentName: string = "cache"
const log = debug(`router:${componentName}`)
Expand All @@ -7,7 +7,7 @@ const log = debug(`router:${componentName}`)
* Cache used to store getStaticProps result
* @param cache
*/
export function staticPropsCache(cache = ROUTERS.staticPropsCache) {
export function staticPropsCache(cache = Routers.staticPropsCache) {
/**
* Get data in static props cache
*/
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useLang.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import LangService, { TLanguage } from "../core/LangService"
import debug from "@cher-ami/debug"
import React from "react"
import { ROUTERS } from "../core/ROUTERS"
import { Routers } from "../core/Routers"
import { useHistory } from "../hooks/useHistory"
const log = debug("router:useLang")

/**
* useLang
*/
export const useLang = (
langService: LangService = ROUTERS.langService,
langService: LangService = Routers.langService,
): [lang: TLanguage, setLang: (lang: TLanguage | string, force: boolean) => void] => {
const [lang, setLang] = React.useState<TLanguage>(langService?.currentLang)

Expand Down
Loading

0 comments on commit 9aee243

Please sign in to comment.