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

SettingsRouteScreen.tsx

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