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

SettingsRouteScreen.tsx

295 lines11.1 KB

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