hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits
| 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. */ |
| 8 | const PARENT_OVERRIDES: Record<string, string> = { |
| 9 | instances: "/courses", |
| 10 | "exam-room": "/exams", |
| 11 | profile: "/", |
| 12 | }; |
| 13 | |
| 14 | const 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 | */ |
| 23 | export 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 | } |