Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mainAppLocation.ts

127 lines5.2 KB

1import { useNavigate, useRouter, type AnyRouter } from "@tanstack/react-router";
2​
3import { GUEST_PAGE_PATH } from "../../guestPage";
4import { withoutAssistantCitationHash } from "../../lib/assistantCitationNavigation";
5import { resolveThreadRouteTarget, type ThreadRouteTarget } from "../../threadRoutes";
6​
7/** Settings and Usage open as modals over the last main-app view. */
8export function isAppModalPage(pathname: string) {
9 return pathname === "/settings" || pathname.startsWith("/settings/") || pathname === "/usage";
11​
12export function isSidebarUtilityPage(pathname: string) {
13 return (
14 pathname.startsWith("/projects/") ||
15 pathname === "/pull-requests" ||
16 pathname === "/issues" ||
17 pathname === "/workflows"
18 );
20​
21// Pages the root route always renders without the app shell, so they are never
22// a page to return to. Other paths seen before auth or on a prompt-link landing
23// are still recorded; they are real app URLs, so returning to one is harmless.
24const SHELL_LESS_PATHS = new Set(["/pair", "/connect", "/connect-agent", GUEST_PAGE_PATH]);
25​
26let mainAppHref: string | null = null;
27let appModalReturnHref: string | null = null;
28let appModalReturnHistoryIndex: number | null = null;
29let appModalReturnThreadTarget: ThreadRouteTarget | null = null;
30let initialHistoryIndex = 0;
31let appModalEntryKeys: string[] = [];
32// Modal entries left as forward history when a modal closed on the document's first entry. Kept
33// in session storage because going Back past that entry and Forward again reloads the document.
34const DISMISSED_APP_MODAL_ENTRIES_KEY = "t3code:dismissed-app-modal-entries";
35​
36function readDismissedAppModalEntryKeys(): string[] {
37 try {
38 const keys: unknown = JSON.parse(
39 sessionStorage.getItem(DISMISSED_APP_MODAL_ENTRIES_KEY) ?? "[]",
40 );
41 return Array.isArray(keys) ? keys.filter((key) => typeof key === "string") : [];
42 } catch {
43 return [];
44 }
46​
47function dismissAppModalEntries(keys: readonly string[]) {
48 const dismissed = [...readDismissedAppModalEntryKeys(), ...keys].slice(-50);
49 try {
50 sessionStorage.setItem(DISMISSED_APP_MODAL_ENTRIES_KEY, JSON.stringify(dismissed));
51 } catch {}
53​
54/** Remembers where Settings, Usage, and the utility pages lead back to. */
55export function startMainAppLocationTracking(router: AnyRouter): () => void {
56 initialHistoryIndex = router.state.location.state.__TSR_index;
57 const record = () => {
58 const { pathname } = router.state.location;
59 if (isAppModalPage(pathname)) {
60 const key = router.state.location.state.__TSR_key;
61 if (key) appModalEntryKeys.push(key);
62 return;
63 }
64 if (SHELL_LESS_PATHS.has(pathname)) return;
65 appModalEntryKeys = [];
66 const href = withoutAssistantCitationHash(router.state.location.href);
67 appModalReturnHref = href;
68 // Only an entry that is exactly the return location can be stepped back to.
69 appModalReturnHistoryIndex =
70 href === router.state.location.href ? router.state.location.state.__TSR_index : null;
71 appModalReturnThreadTarget = resolveThreadRouteTarget(
72 router.state.matches.at(-1)?.params ?? {},
73 );
74 if (!isSidebarUtilityPage(pathname)) mainAppHref = href;
75 };
76 record();
77 // Forward onto a dismissed modal returns to the page it closed to instead of reopening it.
78 const unsubscribeLoad = router.subscribe("onBeforeLoad", ({ fromLocation, toLocation }) => {
79 const key = toLocation.state.__TSR_key;
80 if (fromLocation && key && readDismissedAppModalEntryKeys().includes(key)) {
81 router.history.go(fromLocation.state.__TSR_index - toLocation.state.__TSR_index);
82 }
83 });
84 const unsubscribeResolved = router.subscribe("onResolved", record);
85 return () => {
86 unsubscribeLoad();
87 unsubscribeResolved();
88 };
90​
91/** The thread Settings or Usage opened over, for views mounted while the modal is open. */
92export function getAppModalReturnThreadTarget() {
93 return appModalReturnThreadTarget;
95​
96export function useNavigateToMainApp() {
97 const navigate = useNavigate();
98 return () => navigate({ href: mainAppHref ?? "/" });
100​
101/** Leaves Settings or Usage for the page that opened it. */
102export function useCloseAppModal() {
103 const navigate = useNavigate();
104 const router = useRouter();
105 return () => {
106 const href = appModalReturnHref ?? mainAppHref ?? "/";
107 const returnIndex = appModalReturnHistoryIndex ?? Number.NaN;
108 const steps = router.state.location.state.__TSR_index - returnIndex;
109 // Written as a negated comparison so a missing (NaN) history index also falls back to
110 // client navigation.
111 if (!(returnIndex >= initialHistoryIndex && steps > 0))
112 return navigate({ href, replace: true });
113 // Stepping back past this document's first entry reloads the page, so return to that entry
114 // itself: the modal stays a forward stop rather than becoming a duplicate back stop.
115 if (returnIndex === initialHistoryIndex) {
116 dismissAppModalEntries(appModalEntryKeys);
117 return router.history.go(-steps);
118 }
119 // Go back to the entry before the return page and push it again: only a push drops the
120 // modal's entries from forward history, and reusing the old entry avoids a duplicate stop.
121 const unsubscribe = router.history.subscribe(() => {
122 unsubscribe();
123 void navigate({ href });
124 });
125 router.history.go(-(steps + 1));
126 };