@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 320 lines 11.8 KB
Raw
1 import {
2 navigationCustomizationAvailable,
3 overflowNavigationTabs,
4 } from "../layout/workspace/navigation-tab-order";
5 import {
6 NAVIGATION_TAB_ICONS,
7 WORKSPACE_TAB_LABELS,
8 useNavigationTabOrder,
9 useHiddenNavigationTabs,
10 } from "../layout/workspace/navigation-tabs";
11 import { currentWorkspaceSelections } from "../layout/workspace/workspace-selection-store";
12 import { rememberedSettingsPage } from "../layout/workspace/workspace-tab-navigation";
13 import { useSelectWorkspaceTab } from "../layout/workspace/useSelectWorkspaceTab";
14 import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext";
15 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
16 import { EmptyState } from "../../components/ui/EmptyState";
17 import { useAuth, useUser } from "@clerk/expo";
18 import { useNavigation, useNavigationState } from "@react-navigation/native";
19 import { use, type ComponentProps } from "react";
20 import { Platform, View } from "react-native";
21 import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
22 import { deriveProjectGroupLabel } from "@t3tools/client-runtime/state/project-grouping";
23 import { useSafeAreaInsets } from "react-native-safe-area-context";
24
25 import { hasCloudPublicConfig } from "../cloud/publicConfig";
26 import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context";
27 import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
28 import { SettingsRow } from "./components/SettingsRow";
29 import { SettingsSection, SettingsSidebarContext } from "./components/SettingsSection";
30 import { SettingsScreen } from "./components/SettingsScreen";
31 import type { SettingsPageTarget } from "./components/settings-page-targets";
32 import { useSettingsEnvironmentMenu } from "./components/SettingsEnvironmentFilterHeader";
33 import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
34 import { filterSettingsSections } from "./settings-search";
35 import { usePaneRole } from "../../components/ui/Pane";
36 import { useGT, useMessages } from "gt-react-native";
37
38 export function SettingsRouteScreen() {
39 const list = useSettingsListPlacement();
40 return <SettingsListScreen sidebar={list.sidebar} selected={list.selected} />;
41 }
42
43 /** The Settings list inside a workspace shell that draws its bar, title and search itself. */
44 export function WorkspaceSettingsList() {
45 const list = useSettingsListPlacement();
46 return (
47 <SettingsSidebarContext value={list.sidebar ? { selected: list.selected } : null}>
48 <View className="flex-1 bg-screen">
49 <SettingsListContent />
50 </View>
51 </SettingsSidebarContext>
52 );
53 }
54
55 function useSettingsListPlacement() {
56 const sidebar = usePaneRole() === "sidebar";
57 // The page open beside the list: the route right above the Settings tab's route. While
58 // another tab is open this list stays mounted, hidden, and must keep showing the page Settings
59 // reopens on; otherwise returning shows it unselected for a frame before the page arrives.
60 const selected = useNavigationState((state) => {
61 const list = state.routes.findIndex((route) => route.name === "Settings");
62 return list < 0
63 ? rememberedSettingsPage(currentWorkspaceSelections())
64 : (state.routes[list + 1]?.name ?? null);
65 });
66 return { sidebar, selected };
67 }
68
69 function SettingsListContent() {
70 return hasCloudPublicConfig() ? <ConfiguredSettingsRouteScreen /> : <LocalSettingsRouteScreen />;
71 }
72
73 export function SettingsListScreen(props: {
74 readonly sidebar: boolean;
75 readonly selected: string | null;
76 }) {
77 const gt = useGT();
78 const workspace = useWorkspaceTabs();
79 const environmentMenu = useSettingsEnvironmentMenu();
80 return (
81 <SettingsSidebarContext value={props.sidebar ? { selected: props.selected } : null}>
82 <View className="flex-1 bg-screen">
83 <SettingsScreen
84 title={gt("Settings")}
85 workspaceRoot={props.sidebar}
86 menus={[environmentMenu]}
87 search={
88 workspace
89 ? {
90 value: workspace.state.tabs.settings.query,
91 onChangeText: (query) =>
92 workspace.dispatch({ type: "query", tab: "settings", query }),
93 placeholder: gt("Search settings"),
94 }
95 : undefined
96 }
97 >
98 <SettingsListContent />
99 </SettingsScreen>
100 </View>
101 </SettingsSidebarContext>
102 );
103 }
104
105 type SettingsListRow = ComponentProps<typeof SettingsRow> & { readonly id: string };
106
107 interface SettingsListSection {
108 readonly title?: string;
109 readonly rows: readonly SettingsListRow[];
110 }
111
112 function ConfiguredSettingsRouteScreen() {
113 const gt = useGT();
114 const navigation = useNavigation();
115 const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
116 const { user } = useUser();
117 const { savedConnectionsById } = useSavedRemoteConnections();
118 const accountLabel = !isLoaded
119 ? gt("Checking")
120 : !isSignedIn
121 ? gt("Sign in")
122 : (user?.primaryEmailAddress?.emailAddress ?? gt("Signed in"));
123
124 return (
125 <SettingsList
126 connections={[
127 {
128 id: "account",
129 icon: "person.crop.circle",
130 label: gt("T3 Account"),
131 value: accountLabel,
132 disabled: !isLoaded,
133 onPress: () => navigation.navigate("SettingsAuth"),
134 },
135 environmentsRow(gt("Environments"), Object.keys(savedConnectionsById).length),
136 {
137 id: "SettingsNotifications",
138 icon: "bell.badge",
139 label: gt("Notifications"),
140 target: "SettingsNotifications",
141 },
142 ]}
143 />
144 );
145 }
146
147 function LocalSettingsRouteScreen() {
148 const gt = useGT();
149 const { savedConnectionsById } = useSavedRemoteConnections();
150 return (
151 <SettingsList
152 connections={[environmentsRow(gt("Environments"), Object.keys(savedConnectionsById).length)]}
153 />
154 );
155 }
156
157 function environmentsRow(label: string, count: number): SettingsListRow {
158 return {
159 id: "SettingsEnvironments",
160 icon: "desktopcomputer",
161 label,
162 value: `${count}`,
163 valuePosition: "trailing",
164 target: "SettingsEnvironments",
165 };
166 }
167
168 function SettingsList(props: { readonly connections: readonly SettingsListRow[] }) {
169 const gt = useGT();
170 const m = useMessages();
171 // UIKit's scroll-edge material takes the scroll view's own color; like the chat list, match
172 // the sidebar's surface so the bar doesn't darken over content at rest.
173 // Grouped cards only lift off the screen surface; the drawer is as dark as they are.
174 const listSurface = use(SettingsSidebarContext) ? "bg-drawer" : "bg-screen";
175 const insets = useSafeAreaInsets();
176 // UIKit insets the scroll view by its column's safe area, which this context can report as 0.
177 const bottomSafeArea = useNativeColumnLayoutMetrics()?.safeArea.bottom ?? insets.bottom;
178 const workspace = useWorkspaceTabs();
179 const query = workspace?.state.tabs.settings.query ?? "";
180 const overflowRows = useOverflowRows();
181 const indexSections = useSettingsIndexSections();
182 const sections = filterSettingsSections(
183 [
184 { rows: overflowRows },
185 { title: gt("Connections"), rows: props.connections },
186 ...indexSections,
187 ],
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: query.trim() })}
222 />
223 )}
224 </ScrollView>
225 </View>
226 );
227 }
228
229 function 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("SettingsFollowUp", "bubble.left.and.bubble.right", gt("Chat")),
263 ...(navigationCustomizationAvailable()
264 ? [page("SettingsNavigation", "line.3.horizontal", gt("Navigation tabs"))]
265 : []),
266 page("SettingsKeyboard", "keyboard", gt("Keyboard")),
267 page("SettingsVoice", "mic", gt("Voice")),
268 ],
269 },
270 {
271 title: gt("Agents"),
272 rows: [
273 serverPage("SettingsProviderAccounts", "person.crop.circle", gt("Providers")),
274 serverPage("SettingsThreads", "text.bubble", gt("Threads")),
275 page("SettingsScheduledTasks", "clock", gt("Scheduled tasks")),
276 ],
277 },
278 {
279 title: gt("Code"),
280 rows: [
281 page(
282 "SettingsProjectOverview",
283 "folder",
284 gt("Projects"),
285 selectedProjectKey !== null ? { value: projectLabel } : undefined,
286 ),
287 serverPage(
288 "SettingsEnvironmentSourceControl",
289 "arrow.triangle.branch",
290 gt("Source control & issues"),
291 ),
292 serverPage("SettingsWorktrees", "square.on.square", gt("Worktrees")),
293 ],
294 },
295 {
296 rows: [
297 serverPage("SettingsEnvironmentMaintenance", "arrow.clockwise", gt("Maintenance")),
298 page("SettingsLabs", "flask", gt("Labs")),
299 page("SettingsAbout", "info.circle", gt("About")),
300 page("SettingsArchive", "archivebox", gt("Archive")),
301 ],
302 },
303 ];
304 }
305
306 function useOverflowRows(): SettingsListRow[] {
307 const m = useMessages();
308 const order = useNavigationTabOrder();
309 const hidden = useHiddenNavigationTabs();
310 const { layout } = useAdaptiveWorkspaceLayout();
311 const tabs =
312 Platform.OS === "android" && layout.usesSplitView ? [] : overflowNavigationTabs(order, hidden);
313 const selectTab = useSelectWorkspaceTab();
314 return tabs.map((tab) => ({
315 id: tab,
316 icon: NAVIGATION_TAB_ICONS[tab],
317 label: m(WORKSPACE_TAB_LABELS[tab]),
318 onPress: () => selectTab(tab),
319 }));
320 }