forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

back-target.ts33 lines, 1.3 KiBHistoryRawDownload
1/**
2 * Where the shell's back button goes when there is no in-app history entry to
3 * return to (a deep link, a new tab, a reload). Going `history.back()` there
4 * leaves the app, so we walk up the path to the nearest route that exists.
5 */
6
7/** Detail routes whose natural parent is not their path prefix. */
8const PARENT_OVERRIDES: Record<string, string> = {
9 instances: "/courses",
10 "exam-room": "/exams",
11 profile: "/",
12};
13
14const matches = (pattern: string, segments: string[]) => {
15 const parts = pattern.split("/").filter(Boolean);
16 return parts.length === segments.length && parts.every((part, i) => part.startsWith("$") || part === segments[i]);
17};
18
19/**
20 * @param pathname current location pathname
21 * @param routePaths every registered route path, e.g. `/exams/$id`
22 */
23export function backTarget(pathname: string, routePaths: readonly string[]): string {
24 const segments = pathname.split("/").filter(Boolean);
25 const override = segments.length > 1 ? PARENT_OVERRIDES[segments[0]] : undefined;
26 if (override && segments.length === 2) return override;
27
28 for (let depth = segments.length - 1; depth > 0; depth -= 1) {
29 const candidate = segments.slice(0, depth);
30 if (routePaths.some((pattern) => matches(pattern, candidate))) return `/${candidate.join("/")}`;
31 }
32 return "/";
33}