-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathuseDynamicBackPath.ts
More file actions
46 lines (38 loc) · 1.92 KB
/
Copy pathuseDynamicBackPath.ts
File metadata and controls
46 lines (38 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import findAllMatchingDynamicSuffixes from '@libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes';
import getPathWithoutDynamicSuffix from '@libs/Navigation/helpers/dynamicRoutesUtils/getPathWithoutDynamicSuffix';
import getPathFromState from '@libs/Navigation/helpers/getPathFromState';
import type {State} from '@libs/Navigation/types';
import type {DynamicRouteSuffix, Route} from '@src/ROUTES';
import ROUTES from '@src/ROUTES';
import useRootNavigationState from './useRootNavigationState';
/**
* Removes the given dynamic suffix from the end of the current URL to produce a "back" path.
*
* Supported suffix types: static (`/edit`), parametric (`/:reportID`),
* and parametric with optional params (`/:reportID/:reportActionID?`).
*
* If the suffix doesn't match the tail of the current path, returns the path as-is.
*
* @param dynamicRouteSuffix - The dynamic route pattern to remove from the current URL.
* @param isEnabled - Pass false from a caller that discards the result, to skip the work behind it. Serializing the
* navigation tree and matching every suffix against it runs on each navigation event, for each mounted caller.
* @returns The back path for the dynamic route.
*/
function useDynamicBackPath(dynamicRouteSuffix: DynamicRouteSuffix, isEnabled = true): Route {
const path = useRootNavigationState((state) => {
if (!isEnabled || !state) {
return undefined;
}
return getPathFromState(state as State);
});
if (!path) {
return ROUTES.HOME;
}
const pathWithoutLeadingSlash = path.replaceAll(/^\/+/g, '');
const match = findAllMatchingDynamicSuffixes(pathWithoutLeadingSlash).find((m) => m.pattern === dynamicRouteSuffix);
if (match) {
return getPathWithoutDynamicSuffix(match.pathUsedForMatching, match.actualSuffix, match.pattern);
}
return pathWithoutLeadingSlash as Route;
}
export default useDynamicBackPath;