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

SettingsRouteScreen.tsx

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