|
| 1 | +import * as R from "remeda"; |
1 | 2 |
|
2 | | -import BackendAPISchemas from '../schemas'; |
| 3 | +import BackendAPISchemas from "../schemas"; |
3 | 4 |
|
4 | | -export const buildNestedSiteMap: (flattened: BackendAPISchemas.FlattenedSiteMapSchema[]) => BackendAPISchemas.NestedSiteMapSchema[] = (flattened) => { |
| 5 | +export const buildNestedSiteMap: ( |
| 6 | + flattened: BackendAPISchemas.FlattenedSiteMapSchema[] |
| 7 | +) => { [key: string]: BackendAPISchemas.NestedSiteMapSchema } = (flattened) => { |
5 | 8 | const map: Record<string, BackendAPISchemas.NestedSiteMapSchema> = {}; |
6 | 9 | const roots: BackendAPISchemas.NestedSiteMapSchema[] = []; |
7 | 10 |
|
| 11 | + const siteMapIdRouteCodeMap = flattened.reduce((acc, item) => { |
| 12 | + acc[item.id] = item.route_code; |
| 13 | + return acc; |
| 14 | + }, {} as Record<string, string>); |
| 15 | + |
8 | 16 | flattened.forEach((item) => { |
9 | 17 | map[item.id] = { |
10 | 18 | ...item, |
11 | | - children: [], |
| 19 | + children: {}, |
12 | 20 | }; |
13 | 21 | }); |
14 | 22 |
|
15 | 23 | flattened.forEach((item) => { |
16 | 24 | if (item.parent_sitemap) { |
17 | | - map[item.parent_sitemap].children.push(map[item.id]); |
| 25 | + map[item.parent_sitemap].children[siteMapIdRouteCodeMap[item.id]] = map[item.id]; |
18 | 26 | } else { |
19 | 27 | roots.push(map[item.id]); |
20 | 28 | } |
21 | 29 | }); |
22 | 30 |
|
23 | | - return roots; |
24 | | -} |
| 31 | + return roots.reduce((acc, item) => { |
| 32 | + acc[item.route_code] = item; |
| 33 | + return acc; |
| 34 | + }, {} as Record<string, BackendAPISchemas.NestedSiteMapSchema>); |
| 35 | +}; |
| 36 | + |
| 37 | +export const findSiteMapUsingRoute = (route: string, siteMapData: BackendAPISchemas.NestedSiteMapSchema): BackendAPISchemas.NestedSiteMapSchema | null => { |
| 38 | + const currentRouteCodes = ['', ...route.split('/').filter((code) => !R.isEmpty(code))]; |
| 39 | + |
| 40 | + let currentSitemap: BackendAPISchemas.NestedSiteMapSchema | null | undefined = siteMapData.children[currentRouteCodes[0]]; |
| 41 | + if (currentSitemap === undefined) return null; |
| 42 | + |
| 43 | + for (const routeCode of currentRouteCodes.slice(1)) { |
| 44 | + if ((currentSitemap = currentSitemap.children[routeCode] || null) === null) { |
| 45 | + break; |
| 46 | + } |
| 47 | + } |
| 48 | + return currentSitemap; |
| 49 | +}; |
| 50 | + |
| 51 | +export const parseCss = (t: unknown): React.CSSProperties => (R.isString(t) && !R.isEmpty(t) && JSON.parse(t)) || {}; |
0 commit comments