| 1 |
import React, { useEffect, useMemo } from "react"; |
| 2 |
import Router from "./Router"; |
| 3 |
import routes from "../inc/routes"; |
| 4 |
import { generateRouteArray } from "../inc/Route"; |
| 5 |
import NoRouterComponentFoundError from "../inc/err/NoRouterComponentFoundError"; |
| 6 |
|
| 7 |
/** |
| 8 |
* RouterProvider component. |
| 9 |
* |
| 10 |
* @param {Object} props component properties |
| 11 |
* @param {Router} props.children router component |
| 12 |
* @class |
| 13 |
*/ |
| 14 |
function RouterProvider({ children, currentRoutePath, setCurrentRoutePath }) { |
| 15 |
const RouterChild = useMemo(() => { |
| 16 |
const Component = children?.type === Router ? children.type : null; |
| 17 |
|
| 18 |
if (Component === null) { |
| 19 |
throw new NoRouterComponentFoundError(); |
| 20 |
} |
| 21 |
|
| 22 |
return Component; |
| 23 |
}, [currentRoutePath]); |
| 24 |
|
| 25 |
const generatedRoutes = useMemo(() => { |
| 26 |
return generateRouteArray(routes); |
| 27 |
}, []); |
| 28 |
|
| 29 |
/** |
| 30 |
* Parse url and set route path. |
| 31 |
*/ |
| 32 |
const parseRouteFromUrl = () => { |
| 33 |
const url = new URL(window.location.href); |
| 34 |
const urlRoute = url.searchParams.get("route"); |
| 35 |
|
| 36 |
if (urlRoute) { |
| 37 |
setCurrentRoutePath(urlRoute); |
| 38 |
} |
| 39 |
}; |
| 40 |
|
| 41 |
/** |
| 42 |
* Hook to add event listener for popstate. |
| 43 |
*/ |
| 44 |
useEffect(() => { |
| 45 |
window.addEventListener("popstate", parseRouteFromUrl); |
| 46 |
}, []); |
| 47 |
|
| 48 |
/** |
| 49 |
* Parse url and set route path at startup. |
| 50 |
*/ |
| 51 |
useEffect(() => { |
| 52 |
parseRouteFromUrl(); |
| 53 |
}, []); |
| 54 |
|
| 55 |
/** |
| 56 |
* Add route path to url. |
| 57 |
*/ |
| 58 |
useEffect(() => { |
| 59 |
const url = new URL(window.location.href); |
| 60 |
url.searchParams.set("route", currentRoutePath); |
| 61 |
window.history.pushState(null, null, url.href); |
| 62 |
}, [currentRoutePath]); |
| 63 |
|
| 64 |
return ( |
| 65 |
<RouterChild |
| 66 |
routes={generatedRoutes} |
| 67 |
currentRoutePath={currentRoutePath} |
| 68 |
/> |
| 69 |
); |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* @module RouterProvider |
| 74 |
*/ |
| 75 |
export default RouterProvider; |
| 76 |
|