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

SettingsRouteScreen.tsx

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