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