Open History to see the last commit
1import {
2 Outlet,
3 createFileRoute,
4 redirect,
5 useCanGoBack,
6 useLocation,
7 useNavigate,
8} from "@tanstack/react-router";
9import { useCallback, useEffect, useState, type ReactNode } from "react";
10import { RotateCcwIcon } from "lucide-react";
11import { Button } from "../components/ui/button";
12import { useSettingsRestore } from "../components/settings/SettingsPanels";
13
14import { SettingsBreadcrumb } from "../components/settings/SettingsBreadcrumb";
15import { SidebarInset } from "../components/ui/sidebar";
16import { WorkspacePageHeader } from "../components/WorkspacePageHeader";
17import { isElectron } from "../env";
18import {
19 SettingsScopeProvider,
20 useSettingsScope,
21} from "../components/settings/SettingsScopeContext";
22import { useEnvironments } from "../state/environments";
23import { SettingsScopeNotice } from "../components/settings/SettingsScopeNotice";
24import { SETTINGS_DEVICE_ONLY_PATHS } from "../components/settings/SettingsScopeSentence";
25import { SettingsPageContainer } from "../components/settings/settingsLayout";
26import {
27 retainSettingsScope,
28 validateSettingsRouteSearch,
29} from "../components/settings/settingsScopeNavigation";
30import {
31 getSettingsSearchTargetScope,
32 getThreadAutoSettlementSearchAvailability,
33 isSettingsSearchScopeAvailable,
34} from "../components/settings/settingsSearch";
35
36function RestoreDeviceDefaultsButton({ onRestored }: { onRestored: () => void }) {
37 const { changedSettingLabels, restoreDefaults } = useSettingsRestore(onRestored);
38 return (
39 <Button
40 size="xs"
41 variant="ghost"
42 disabled={changedSettingLabels.length === 0}
43 onClick={() => void restoreDefaults()}
44 >
45 <RotateCcwIcon className="mx-1 size-3.5" />
46 Restore device defaults
47 </Button>
48 );
49}
50
51function SettingsScopeBoundary({ pathname, children }: { pathname: string; children: ReactNode }) {
52 const { scope, connectedEnvironments } = useSettingsScope();
53 const { environments } = useEnvironments();
54 const hash = useLocation({ select: (location) => location.hash });
55 const searchTarget = getSettingsSearchTargetScope(hash);
56 const autoSettlementAvailability = searchTarget?.requiresThreadAutoSettlement
57 ? getThreadAutoSettlementSearchAvailability(environments, scope)
58 : null;
59 if (
60 scope.kind !== "unavailable" &&
61 searchTarget &&
62 autoSettlementAvailability &&
63 !autoSettlementAvailability.isTargetAvailable
64 ) {
65 return (
66 <SettingsScopeNotice
67 target="environment"
68 targetId={hash}
69 eligibleEnvironmentIds={autoSettlementAvailability.eligibleEnvironmentIds}
70 >
71 {autoSettlementAvailability.eligibleEnvironmentIds.length > 0
72 ? `${searchTarget.title} requires a supporting environment. Choose one to continue.`
73 : `${searchTarget.title} requires a supporting environment. Connect or update an environment to continue.`}
74 </SettingsScopeNotice>
75 );
76 }
77 if (
78 scope.kind !== "unavailable" &&
79 searchTarget &&
80 !isSettingsSearchScopeAvailable(searchTarget.scope, scope.kind)
81 ) {
82 const target =
83 searchTarget.scope === "environment" ||
84 searchTarget.scope === "project" ||
85 searchTarget.scope === "checkout"
86 ? searchTarget.scope
87 : "all";
88 return (
89 <SettingsScopeNotice target={target} targetId={hash}>
90 {`${searchTarget.title} is not available for the selected target. Choose its owning scope to continue.`}
91 </SettingsScopeNotice>
92 );
93 }
94 // Device-local pages ignore the scope entirely; the project page follows
95 // remembered members while a grouping change replaces its URL key.
96 if (SETTINGS_DEVICE_ONLY_PATHS.has(pathname) || pathname === "/settings/projects") {
97 return children;
98 }
99 // Keep the scope sentence on screen so the selection can be changed back.
100 if (scope.kind === "unavailable")
101 return (
102 <SettingsPageContainer>
103 <p className="text-sm text-muted-foreground">{scope.message}</p>
104 </SettingsPageContainer>
105 );
106 if (scope.kind === "environment" && connectedEnvironments.length === 0) {
107 return (
108 <SettingsPageContainer>
109 <p className="text-sm text-muted-foreground">
110 Reconnect {scope.label} to change its settings.
111 </p>
112 </SettingsPageContainer>
113 );
114 }
115 return children;
116}
117
118function SettingsContentLayout() {
119 const location = useLocation();
120 const navigate = useNavigate();
121 const canGoBack = useCanGoBack();
122 const { search } = useSettingsScope();
123 const [restoreSignal, setRestoreSignal] = useState(0);
124 const navigateBackWithinApp = useCallback(() => {
125 if (canGoBack) {
126 window.history.back();
127 return;
128 }
129 void navigate({ to: "/" });
130 }, [canGoBack, navigate]);
131
132 useEffect(() => {
133 const onKeyDown = (event: KeyboardEvent) => {
134 if (event.defaultPrevented) return;
135 if (event.key === "Escape") {
136 event.preventDefault();
137
138 const activeElement = document.activeElement;
139 if (activeElement instanceof HTMLElement) {
140 activeElement.blur();
141 }
142
143 navigateBackWithinApp();
144 }
145 };
146
147 window.addEventListener("keydown", onKeyDown);
148 return () => {
149 window.removeEventListener("keydown", onKeyDown);
150 };
151 }, [navigateBackWithinApp]);
152
153 return (
154 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none isolate">
155 <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
156 <WorkspacePageHeader electron={isElectron}>
157 <div className="flex w-full items-center gap-3">
158 <SettingsBreadcrumb pathname={location.pathname} />
159 {location.pathname === "/settings/general" ? (
160 <div className="ms-auto flex shrink-0 items-center">
161 <RestoreDeviceDefaultsButton
162 onRestored={() => setRestoreSignal((value) => value + 1)}
163 />
164 </div>
165 ) : null}
166 </div>
167 </WorkspacePageHeader>
168
169 <div
170 key={`${JSON.stringify(search)}:${restoreSignal}`}
171 className="min-h-0 flex flex-1 flex-col"
172 >
173 <SettingsScopeBoundary pathname={location.pathname}>
174 <Outlet />
175 </SettingsScopeBoundary>
176 </div>
177 </div>
178 </SidebarInset>
179 );
180}
181
182function SettingsRouteLayout() {
183 const rawSearch = Route.useSearch();
184 const navigate = Route.useNavigate();
185 const pathname = useLocation({ select: (location) => location.pathname });
186 return (
187 <SettingsScopeProvider
188 search={rawSearch}
189 onChange={(next) => {
190 // Send every axis so the retain middleware sees an explicit target
191 // even when the choice is "all", which is the absence of a key.
192 void navigate({
193 to: pathname,
194 search: () => ({
195 project: next.project,
196 machine: next.machine,
197 checkout: next.checkout,
198 }),
199 hash: "",
200 resetScroll: false,
201 });
202 }}
203 >
204 <SettingsContentLayout />
205 </SettingsScopeProvider>
206 );
207}
208
209export const Route = createFileRoute("/settings")({
210 validateSearch: validateSettingsRouteSearch,
211 search: { middlewares: [retainSettingsScope] },
212 beforeLoad: async ({ context, location }) => {
213 if (
214 context.authGateState.status !== "authenticated" &&
215 context.authGateState.status !== "hosted-static"
216 ) {
217 throw redirect({ to: "/pair", replace: true });
218 }
219
220 if (location.pathname === "/settings") {
221 throw redirect({ to: "/settings/general", replace: true });
222 }
223 },
224 component: SettingsRouteLayout,
225});