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

SettingsRouteScreen.tsx

337 lines12.3 KB

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