80 lines
2.7 KiB
TypeScript
80 lines
2.7 KiB
TypeScript
import {
|
|
CustomRouteObject,
|
|
RouteObjectAdditionalProps,
|
|
flatRoutes,
|
|
} from "../configure";
|
|
import {
|
|
clearMultiplePathSlashes,
|
|
trimPathOfParameters,
|
|
} from "./StringTransformationUtils";
|
|
|
|
interface FlatternRoutingTableElement extends RouteObjectAdditionalProps {
|
|
path: string;
|
|
name: string;
|
|
}
|
|
//! WARNING: This function will generate error if paths aren't unique, disableInNavbar or disableRedirect to prevent this. It's a useful feature to prevent duplicate path in navbar
|
|
/**
|
|
* @description Convert a existing routing table as a flat array
|
|
*/
|
|
export const flatternRoutingTable = (
|
|
routes: CustomRouteObject[],
|
|
previousPath = "undefined",
|
|
): FlatternRoutingTableElement[] => {
|
|
const result: FlatternRoutingTableElement[] = [];
|
|
routes.forEach((route: CustomRouteObject) => {
|
|
if (route.additionalProps.disableRedirect) return; // Skip if disable redirect, children are skipped too
|
|
if (
|
|
typeof route.path !== "undefined" &&
|
|
typeof previousPath === "undefined" &&
|
|
!route.additionalProps.disableInNavbar
|
|
) {
|
|
result.push({
|
|
path: trimPathOfParameters(route.path),
|
|
name: route.additionalProps.name,
|
|
disableBreadcrumbBar: route.additionalProps.disableBreadcrumbBar,
|
|
disableInNavbar: route.additionalProps.disableInNavbar,
|
|
disableRedirect: route.additionalProps.disableRedirect,
|
|
});
|
|
}
|
|
if (
|
|
typeof route.path !== "undefined" &&
|
|
typeof previousPath !== "undefined" &&
|
|
!route.additionalProps.disableInNavbar
|
|
) {
|
|
result.push({
|
|
path: trimPathOfParameters(
|
|
clearMultiplePathSlashes(`/${previousPath}/${route.path}`),
|
|
),
|
|
name: route.additionalProps.name,
|
|
disableBreadcrumbBar: route.additionalProps.disableBreadcrumbBar,
|
|
disableInNavbar: route.additionalProps.disableInNavbar,
|
|
disableRedirect: route.additionalProps.disableRedirect,
|
|
});
|
|
}
|
|
if (route.children && typeof previousPath === "undefined") {
|
|
result.push(...flatternRoutingTable(route.children));
|
|
}
|
|
if (route.children && typeof previousPath !== "undefined") {
|
|
result.push(...flatternRoutingTable(route.children, route.path));
|
|
}
|
|
// Errors handling
|
|
if (typeof route.path === "undefined")
|
|
console.error(`Route ${route.additionalProps.name} is missing path`);
|
|
});
|
|
return result;
|
|
};
|
|
/**
|
|
* @description Function to find element in flattern routes array by LAST path ex: /admin/MAINTENANCE
|
|
*/
|
|
export const findElementInFlatRoutes = (
|
|
path: string,
|
|
): FlatternRoutingTableElement | undefined => {
|
|
// Split path string into array, split by '/', then get the last element
|
|
const _route = flatRoutes.find((route) => {
|
|
const pathArray = route.path.split("/");
|
|
if (pathArray[pathArray.length - 1] === path) return true;
|
|
else return false;
|
|
});
|
|
return _route;
|
|
};
|