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