Open History to see the last commit
1import {
2 navigationCustomizationAvailable,
3 overflowNavigationTabs,
4} from "../layout/workspace/navigation-tab-order";
5import {
6 NAVIGATION_TAB_ICONS,
7 WORKSPACE_TAB_LABELS,
8 useNavigationTabOrder,
9 useHiddenNavigationTabs,
10} from "../layout/workspace/navigation-tabs";
11import { currentWorkspaceSelections } from "../layout/workspace/workspace-selection-store";
12import { rememberedSettingsPage } from "../layout/workspace/workspace-tab-navigation";
13import { useSelectWorkspaceTab } from "../layout/workspace/useSelectWorkspaceTab";
14import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext";
15import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
16import { EmptyState } from "../../components/ui/EmptyState";
17import { useAuth, useUser } from "@clerk/expo";
18import { useNavigation, useNavigationState } from "@react-navigation/native";
19import { use, type ComponentProps } from "react";
20import { Platform, View } from "react-native";
21import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
22import { deriveProjectGroupLabel } from "@t3tools/client-runtime/state/project-grouping";
23import { useSafeAreaInsets } from "react-native-safe-area-context";
24
25import { hasCloudPublicConfig } from "../cloud/publicConfig";
26import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context";
27import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
28import { SettingsRow } from "./components/SettingsRow";
29import { SettingsSection, SettingsSidebarContext } from "./components/SettingsSection";
30import { SettingsScreen } from "./components/SettingsScreen";
31import type { SettingsPageTarget } from "./components/settings-page-targets";
32import { useSettingsEnvironmentMenu } from "./components/SettingsEnvironmentFilterHeader";
33import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
34import { filterSettingsSections } from "./settings-search";
35import { usePaneRole } from "../../components/ui/Pane";
36import { I18nProvider, useGT } from "../../i18n/I18nProvider";
37
38export function SettingsRouteScreen() {
39 const list = useSettingsListPlacement();
40 return <SettingsListScreen sidebar={list.sidebar} selected={list.selected} />;
41}
42
43/** The Settings list inside a workspace shell that draws its bar, title and search itself. */
44export function WorkspaceSettingsList() {
45 const list = useSettingsListPlacement();
46 return (
47 <SettingsSidebarContext value={list.sidebar ? { selected: list.selected } : null}>
48 <View className="flex-1 bg-screen">
49 <I18nProvider>
50 <SettingsListContent />
51 </I18nProvider>
52 </View>
53 </SettingsSidebarContext>
54 );
55}
56
57function useSettingsListPlacement() {
58 const sidebar = usePaneRole() === "sidebar";
59 // The page open beside the list: the route right above the Settings tab's route. While
60 // another tab is open this list stays mounted, hidden, and must keep showing the page Settings
61 // reopens on; otherwise returning shows it unselected for a frame before the page arrives.
62 const selected = useNavigationState((state) => {
63 const list = state.routes.findIndex((route) => route.name === "Settings");
64 return list < 0
65 ? rememberedSettingsPage(currentWorkspaceSelections())
66 : (state.routes[list + 1]?.name ?? null);
67 });
68 return { sidebar, selected };
69}
70
71function SettingsListContent() {
72 return hasCloudPublicConfig() ? <ConfiguredSettingsRouteScreen /> : <LocalSettingsRouteScreen />;
73}
74
75export function SettingsListScreen(props: {
76 readonly sidebar: boolean;
77 readonly selected: string | null;
78}) {
79 return (
80 <I18nProvider>
81 <TranslatedSettingsListScreen {...props} />
82 </I18nProvider>
83 );
84}
85
86function TranslatedSettingsListScreen(props: {
87 readonly sidebar: boolean;
88 readonly selected: string | null;
89}) {
90 const gt = useGT();
91 const workspace = useWorkspaceTabs();
92 const environmentMenu = useSettingsEnvironmentMenu();
93 return (
94 <SettingsSidebarContext value={props.sidebar ? { selected: props.selected } : null}>
95 <View className="flex-1 bg-screen">
96 <SettingsScreen
97 title={gt("Settings")}
98 workspaceRoot={props.sidebar}
99 menus={[environmentMenu]}
100 search={
101 workspace
102 ? {
103 value: workspace.state.tabs.settings.query,
104 onChangeText: (query) =>
105 workspace.dispatch({ type: "query", tab: "settings", query }),
106 placeholder: gt("Search settings"),
107 }
108 : undefined
109 }
110 >
111 <SettingsListContent />
112 </SettingsScreen>
113 </View>
114 </SettingsSidebarContext>
115 );
116}
117
118type SettingsListRow = ComponentProps<typeof SettingsRow> & { readonly id: string };
119
120interface SettingsListSection {
121 readonly title?: string;
122 readonly rows: readonly SettingsListRow[];
123}
124
125function ConfiguredSettingsRouteScreen() {
126 const gt = useGT();
127 const navigation = useNavigation();
128 const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
129 const { user } = useUser();
130 const { savedConnectionsById } = useSavedRemoteConnections();
131 const accountLabel = !isLoaded
132 ? gt("Checking")
133 : !isSignedIn
134 ? gt("Sign in")
135 : (user?.primaryEmailAddress?.emailAddress ?? gt("Signed in"));
136
137 return (
138 <SettingsList
139 connections={[
140 {
141 id: "account",
142 icon: "person.crop.circle",
143 label: gt("T3 Account"),
144 value: accountLabel,
145 disabled: !isLoaded,
146 onPress: () => navigation.navigate("SettingsAuth"),
147 },
148 environmentsRow(gt("Environments"), Object.keys(savedConnectionsById).length),
149 {
150 id: "SettingsNotifications",
151 icon: "bell.badge",
152 label: gt("Notifications"),
153 target: "SettingsNotifications",
154 },
155 ]}
156 />
157 );
158}
159
160function LocalSettingsRouteScreen() {
161 const gt = useGT();
162 const { savedConnectionsById } = useSavedRemoteConnections();
163 return (
164 <SettingsList
165 connections={[environmentsRow(gt("Environments"), Object.keys(savedConnectionsById).length)]}
166 />
167 );
168}
169
170function environmentsRow(label: string, count: number): SettingsListRow {
171 return {
172 id: "SettingsEnvironments",
173 icon: "desktopcomputer",
174 label,
175 value: `${count}`,
176 valuePosition: "trailing",
177 target: "SettingsEnvironments",
178 };
179}
180
181function SettingsList(props: { readonly connections: readonly SettingsListRow[] }) {
182 const gt = useGT();
183 // UIKit's scroll-edge material takes the scroll view's own color; like the chat list, match
184 // the sidebar's surface so the bar doesn't darken over content at rest.
185 // Grouped cards only lift off the screen surface; the drawer is as dark as they are.
186 const listSurface = use(SettingsSidebarContext) ? "bg-drawer" : "bg-screen";
187 const insets = useSafeAreaInsets();
188 // UIKit insets the scroll view by its column's safe area, which this context can report as 0.
189 const bottomSafeArea = useNativeColumnLayoutMetrics()?.safeArea.bottom ?? insets.bottom;
190 const workspace = useWorkspaceTabs();
191 const query = workspace?.state.tabs.settings.query ?? "";
192 const overflowRows = useOverflowRows();
193 const indexSections = useSettingsIndexSections();
194 const sections = filterSettingsSections(
195 [
196 { rows: overflowRows },
197 { title: gt("Connections"), rows: props.connections },
198 ...indexSections,
199 ],
200 query,
201 );
202
203 return (
204 <View collapsable={false} className="flex-1">
205 <ScrollView
206 contentInsetAdjustmentBehavior="automatic"
207 keyboardShouldPersistTaps="handled"
208 showsVerticalScrollIndicator={false}
209 className={`flex-1 ${listSurface}`}
210 contentContainerClassName="gap-4 px-5 pt-4"
211 contentContainerStyle={{
212 // The workspace's clearance keeps the last row above its search field and keyboard.
213 paddingBottom:
214 Platform.OS === "ios"
215 ? Math.max(Math.max(bottomSafeArea, 18) + 18, workspace?.bottomClearance ?? 0) -
216 bottomSafeArea
217 : Math.max(Math.max(insets.bottom, 18) + 18, workspace?.bottomClearance ?? 0),
218 }}
219 >
220 {sections.length ? (
221 sections.map((section, index) => (
222 <SettingsSection key={section.title ?? `untitled-${index}`} title={section.title}>
223 {section.rows.map(({ id, ...row }) => (
224 <SettingsRow key={id} {...row} />
225 ))}
226 </SettingsSection>
227 ))
228 ) : (
229 <EmptyState
230 variant="plain"
231 title={gt("No results")}
232 detail={gt("No settings match “{query}”.", { query: query.trim() })}
233 />
234 )}
235 </ScrollView>
236 </View>
237 );
238}
239
240function useSettingsIndexSections(): SettingsListSection[] {
241 const gt = useGT();
242 const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter();
243 const noServerTargets = selectedTargets.length === 0;
244 const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey);
245 const scopedProjectMembers =
246 selectedProject?.members
247 .map((member) => member.project)
248 .filter((project) =>
249 selectedTargets.some((target) => target.environmentId === project.environmentId),
250 ) ?? [];
251 const projectLabel =
252 selectedProject && scopedProjectMembers.length > 0
253 ? deriveProjectGroupLabel({
254 groupKey: selectedProject.key,
255 representative: scopedProjectMembers[0]!,
256 members: scopedProjectMembers,
257 })
258 : (selectedProject?.label ?? gt("Unavailable project"));
259 const page = (
260 target: SettingsPageTarget,
261 icon: SettingsListRow["icon"],
262 label: string,
263 extra?: Pick<SettingsListRow, "disabled" | "value">,
264 ): SettingsListRow => ({ id: target, icon, label, target, ...extra });
265 const serverPage = (target: SettingsPageTarget, icon: SettingsListRow["icon"], label: string) =>
266 page(target, icon, label, { disabled: noServerTargets });
267 // The same pages and groups as Settings on web, minus what mobile has no setting for.
268 return [
269 {
270 rows: [
271 page("SettingsOrganization", "gearshape", gt("General")),
272 page("SettingsAppearance", "paintbrush", gt("Appearance")),
273 page("SettingsFollowUp", "bubble.left.and.bubble.right", gt("Chat")),
274 ...(navigationCustomizationAvailable()
275 ? [page("SettingsNavigation", "line.3.horizontal", gt("Navigation tabs"))]
276 : []),
277 page("SettingsKeyboard", "keyboard", gt("Keyboard")),
278 page("SettingsVoice", "mic", gt("Voice")),
279 ],
280 },
281 {
282 title: gt("Agents"),
283 rows: [
284 serverPage("SettingsProviderAccounts", "person.crop.circle", gt("Providers")),
285 serverPage("SettingsThreads", "text.bubble", gt("Threads")),
286 page("SettingsScheduledTasks", "clock", gt("Scheduled tasks")),
287 ],
288 },
289 {
290 title: gt("Code"),
291 rows: [
292 page(
293 "SettingsProjectOverview",
294 "folder",
295 gt("Projects"),
296 selectedProjectKey !== null ? { value: projectLabel } : undefined,
297 ),
298 serverPage(
299 "SettingsEnvironmentSourceControl",
300 "arrow.triangle.branch",
301 gt("Source control"),
302 ),
303 serverPage("SettingsWorktrees", "square.on.square", gt("Worktrees")),
304 ],
305 },
306 {
307 rows: [
308 serverPage("SettingsEnvironmentMaintenance", "arrow.clockwise", gt("Maintenance")),
309 page("SettingsLabs", "flask", gt("Labs")),
310 page("SettingsAbout", "info.circle", gt("About")),
311 page("SettingsArchive", "archivebox", gt("Archive")),
312 ],
313 },
314 ];
315}
316
317function useOverflowRows(): SettingsListRow[] {
318 const order = useNavigationTabOrder();
319 const hidden = useHiddenNavigationTabs();
320 const { layout } = useAdaptiveWorkspaceLayout();
321 const tabs =
322 Platform.OS === "android" && layout.usesSplitView ? [] : overflowNavigationTabs(order, hidden);
323 const selectTab = useSelectWorkspaceTab();
324 return tabs.map((tab) => ({
325 id: tab,
326 icon: NAVIGATION_TAB_ICONS[tab],
327 label: WORKSPACE_TAB_LABELS[tab],
328 onPress: () => selectTab(tab),
329 }));
330}