Open History to see the last commit
1import {
2 addProjectRemoteSourceLabel,
3 addProjectRemoteSourcePathHint,
4 addProjectRemoteSourceProvider,
5 buildAddProjectRemoteSourceReadiness,
6 buildProjectCreateCommand,
7 canCreateProjectInEnvironment,
8 findExistingAddProject,
9 getAddProjectInitialQuery,
10 resolveAddProjectPath,
11 sortAddProjectProviderSources,
12 type AddProjectRemoteSource,
13} from "@t3tools/client-runtime/operations/projects";
14import {
15 connectionStatusText,
16 type EnvironmentConnectionPhase,
17} from "@t3tools/client-runtime/connection";
18import {
19 canPreloadBrowsePath,
20 createBrowseNavigationCoordinator,
21 filterFilesystemBrowseEntries,
22 getFilesystemBrowsePath,
23} from "@t3tools/client-runtime/state/filesystem";
24import {
25 appendBrowsePathSegment,
26 ensureBrowseDirectoryPath,
27 inferProjectTitleFromPath,
28} from "@t3tools/client-runtime/state/projects";
29import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
30import { StackActions, useNavigation } from "@react-navigation/native";
31import { SymbolView } from "../../components/AppSymbol";
32import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
33import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
34import { useSafeAreaInsets } from "react-native-safe-area-context";
35import * as Arr from "effect/Array";
36import * as Cause from "effect/Cause";
37import * as Order from "effect/Order";
38import { AsyncResult } from "effect/unstable/reactivity";
39import { cn } from "../../lib/cn";
40
41import { useProjects, useServerConfigs } from "../../state/entities";
42import { filesystemEnvironment } from "../../state/filesystem";
43import { projectEnvironment } from "../../state/projects";
44import { useEnvironmentQuery } from "../../state/query";
45import { sourceControlEnvironment } from "../../state/sourceControl";
46import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
47import { ErrorBanner } from "../../components/ErrorBanner";
48import { SourceControlIcon } from "../../components/SourceControlIcon";
49import { useThemeColor } from "../../lib/useThemeColor";
50import { uuidv4 } from "../../lib/uuid";
51import { useAtomCommand } from "../../state/use-atom-command";
52import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
53import {
54 useRemoteConnectionStatus,
55 useRemoteEnvironmentRuntime,
56 useSavedRemoteConnections,
57} from "../../state/use-remote-environment-registry";
58import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
59
60interface EnvironmentOption {
61 readonly environmentId: EnvironmentId;
62 readonly label: string;
63 readonly platform: string;
64 readonly baseDirectory: string | null;
65 readonly connectionState: EnvironmentConnectionPhase;
66 readonly connectionError: string | null;
67 readonly connectionErrorTraceId: string | null;
68}
69
70const environmentOptionOrder = Order.mapInput(
71 Order.Struct({
72 label: Order.String,
73 }),
74 (environment: EnvironmentOption) => ({ label: environment.label }),
75);
76
77function platformFromOs(os: string | null | undefined): string {
78 if (os === "windows") return "Win32";
79 if (os === "darwin") return "MacIntel";
80 if (os === "linux") return "Linux";
81 return "";
82}
83
84function errorMessage(error: unknown): string {
85 return error instanceof Error && error.message.trim().length > 0
86 ? error.message
87 : "An error occurred.";
88}
89
90function stringParam(value: string | string[] | undefined): string | null {
91 if (Array.isArray(value)) return value[0] ?? null;
92 return value ?? null;
93}
94
95function sourceFromParam(value: string | string[] | undefined): AddProjectRemoteSource {
96 const source = stringParam(value);
97 if (
98 source === "url" ||
99 source === "github" ||
100 source === "gitlab" ||
101 source === "bitbucket" ||
102 source === "azure-devops"
103 ) {
104 return source;
105 }
106 return "url";
107}
108
109function SectionTitle(props: { readonly children: string }) {
110 return (
111 <Text className="px-1 text-2xs font-t3-bold tracking-[0.7px] uppercase text-foreground-muted">
112 {props.children}
113 </Text>
114 );
115}
116
117function AddProjectShell(props: { readonly children: ReactNode }) {
118 const insets = useSafeAreaInsets();
119
120 return (
121 // collapsable={false} is load-bearing: if this wrapper is flattened, the
122 // ScrollView lands directly under RNSSafeAreaView and RNS's formSheet
123 // scroll-view frame correction mistakes this full-height wrapper for a
124 // "header" sibling, coercing the ScrollView to zero height (blank sheet
125 // as soon as the sheet re-lays-out, e.g. when the keyboard opens).
126 <View collapsable={false} className="flex-1 bg-sheet">
127 <ScrollView
128 keyboardShouldPersistTaps="handled"
129 contentInsetAdjustmentBehavior="automatic"
130 contentContainerStyle={{
131 paddingHorizontal: 20,
132 paddingTop: 16,
133 paddingBottom: Math.max(insets.bottom, 18) + 18,
134 gap: 10,
135 }}
136 >
137 {props.children}
138 </ScrollView>
139 </View>
140 );
141}
142
143function ListSection(props: { readonly children: ReactNode }) {
144 return <View className="overflow-hidden rounded-[24px] bg-card">{props.children}</View>;
145}
146
147function ListRow(props: {
148 readonly title: string;
149 readonly subtitle?: string | null;
150 readonly icon: ReactNode;
151 readonly disabled?: boolean;
152 readonly selected?: boolean;
153 readonly isFirst?: boolean;
154 readonly right?: ReactNode;
155 readonly onPress?: () => void;
156}) {
157 const chevronColor = useThemeColor("--color-chevron");
158
159 return (
160 <Pressable
161 disabled={props.disabled}
162 onPress={props.onPress}
163 className={cn(
164 "bg-card px-3.5 py-2.5 active:opacity-70",
165 !props.isFirst && "border-t border-border-subtle",
166 props.disabled && "opacity-[0.45]",
167 )}
168 >
169 <View className="flex-row items-center gap-3">
170 <View
171 className={
172 props.selected
173 ? "h-7 w-7 items-center justify-center rounded-full bg-primary"
174 : "h-7 w-7 items-center justify-center"
175 }
176 >
177 {props.icon}
178 </View>
179 <View className="flex-1 gap-0.5">
180 <Text className="text-base leading-snug font-t3-bold">{props.title}</Text>
181 {props.subtitle ? (
182 <Text className="text-sm leading-snug text-foreground-muted" numberOfLines={2}>
183 {props.subtitle}
184 </Text>
185 ) : null}
186 </View>
187 {"right" in props ? (
188 props.right
189 ) : !props.disabled ? (
190 <SymbolView name="chevron.right" size={13} tintColor={chevronColor} type="monochrome" />
191 ) : null}
192 </View>
193 </Pressable>
194 );
195}
196
197function PrimaryActionButton(props: {
198 readonly label: string;
199 readonly disabled?: boolean;
200 readonly loading?: boolean;
201 readonly onPress: () => void;
202}) {
203 const primaryForeground = useThemeColor("--color-primary-foreground");
204
205 return (
206 <Pressable
207 disabled={props.disabled}
208 onPress={props.onPress}
209 className="h-12 items-center justify-center rounded-full bg-primary active:opacity-70 disabled:opacity-45"
210 >
211 {props.loading ? (
212 <ActivityIndicator color={String(primaryForeground)} />
213 ) : (
214 <Text className="text-base font-t3-bold text-primary-foreground">{props.label}</Text>
215 )}
216 </Pressable>
217 );
218}
219
220function ProjectPathInput(props: {
221 readonly value: string;
222 readonly onChangeText: (value: string) => void;
223 readonly onSubmit: () => void;
224}) {
225 return (
226 <TextInput
227 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
228 value={props.value}
229 onChangeText={props.onChangeText}
230 autoCapitalize="none"
231 autoCorrect={false}
232 placeholder="~/projects/my-app"
233 returnKeyType="done"
234 onSubmitEditing={props.onSubmit}
235 />
236 );
237}
238
239function useBrowsePathInput(environment: EnvironmentOption | null) {
240 const environmentId = environment?.environmentId ?? null;
241 const environmentBaseDirectory = environment?.baseDirectory ?? null;
242 const [pathInput, commitPathInput] = useState(() =>
243 getAddProjectInitialQuery(environmentBaseDirectory),
244 );
245 const previousEnvironmentIdRef = useRef(environmentId);
246 const environmentRuntime = useRemoteEnvironmentRuntime(environmentId);
247 const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
248 reportFailure: false,
249 reportDefect: false,
250 });
251 const [browseNavigation] = useState(createBrowseNavigationCoordinator);
252 const [isBrowseNavigating, setIsBrowseNavigating] = useState(false);
253 const setPathInput = useCallback(
254 (path: string) => {
255 browseNavigation.invalidate();
256 setIsBrowseNavigating(false);
257 commitPathInput(path);
258 },
259 [browseNavigation],
260 );
261 const navigateToBrowsePath = useCallback(
262 async (path: string) => {
263 setIsBrowseNavigating(true);
264 const committed = await browseNavigation.run(
265 async () => {
266 if (environment && canPreloadBrowsePath(environmentRuntime?.connectionState)) {
267 await loadBrowsePath({
268 environmentId: environment.environmentId,
269 input: { partialPath: path },
270 });
271 }
272 },
273 () => commitPathInput(path),
274 );
275 if (committed) {
276 setIsBrowseNavigating(false);
277 }
278 return committed;
279 },
280 [browseNavigation, environment, environmentRuntime?.connectionState, loadBrowsePath],
281 );
282
283 useEffect(() => {
284 if (environmentId !== null && environmentId !== previousEnvironmentIdRef.current) {
285 previousEnvironmentIdRef.current = environmentId;
286 setPathInput(getAddProjectInitialQuery(environmentBaseDirectory));
287 }
288 }, [environmentBaseDirectory, environmentId, setPathInput]);
289
290 useEffect(
291 () => () => {
292 browseNavigation.invalidate();
293 },
294 [browseNavigation],
295 );
296
297 return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath };
298}
299
300function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
301 const serverConfigByEnvironmentId = useServerConfigs();
302 const { savedConnectionsById } = useSavedRemoteConnections();
303 const { connectedEnvironments } = useRemoteConnectionStatus();
304
305 return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
306 const runtimeByEnvironmentId = new Map(
307 connectedEnvironments.map((environment) => [environment.environmentId, environment] as const),
308 );
309 const options = Object.values(savedConnectionsById).map((connection) => {
310 const config = serverConfigByEnvironmentId.get(connection.environmentId);
311 const runtime = runtimeByEnvironmentId.get(connection.environmentId);
312 return {
313 environmentId: connection.environmentId,
314 label: connection.environmentLabel,
315 platform: platformFromOs(config?.environment.platform.os ?? null),
316 baseDirectory: config?.settings.addProjectBaseDirectory ?? null,
317 connectionState: runtime?.connectionState ?? "available",
318 connectionError: runtime?.connectionError ?? null,
319 connectionErrorTraceId: runtime?.connectionErrorTraceId ?? null,
320 };
321 });
322 return Arr.sort(options, environmentOptionOrder);
323 }, [connectedEnvironments, savedConnectionsById, serverConfigByEnvironmentId]);
324}
325
326function useSelectedEnvironment(): {
327 readonly environmentOptions: ReadonlyArray<EnvironmentOption>;
328 readonly selectedEnvironment: EnvironmentOption | null;
329 readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void;
330} {
331 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
332 const environmentOptions = useEnvironmentOptions();
333 const selectedEnvironment =
334 environmentOptions.find(
335 (environment) =>
336 environment.environmentId === selectedEnvironmentId &&
337 canCreateProjectInEnvironment(environment.connectionState),
338 ) ??
339 environmentOptions.find((environment) =>
340 canCreateProjectInEnvironment(environment.connectionState),
341 ) ??
342 null;
343
344 return {
345 environmentOptions,
346 selectedEnvironment,
347 setSelectedEnvironmentId,
348 };
349}
350
351function EmptyEnvironmentState() {
352 const navigation = useNavigation();
353
354 return (
355 <View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
356 <Text className="text-center text-lg font-t3-bold">Environment unavailable</Text>
357 <Text className="text-center text-sm leading-normal text-foreground-muted">
358 Start or reconnect an environment before adding a project.
359 </Text>
360 <Pressable
361 onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))}
362 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
363 >
364 <Text className="text-sm font-t3-bold text-primary-foreground">Add environment</Text>
365 </Pressable>
366 </View>
367 );
368}
369
370function SourceControlRow(props: {
371 readonly source: AddProjectRemoteSource;
372 readonly selectedEnvironmentId: EnvironmentId;
373 readonly ready: boolean;
374 readonly hint: string;
375 readonly isFirst: boolean;
376}) {
377 const navigation = useNavigation();
378 const iconColor = useThemeColor("--color-icon");
379 const title =
380 props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`;
381 const subtitle =
382 props.source === "url"
383 ? "Clone from a remote URL"
384 : `Clone ${addProjectRemoteSourceLabel(props.source)} ${props.hint}`;
385 const icon =
386 props.source === "url" ? (
387 <SymbolView name="link" size={17} tintColor={iconColor} type="monochrome" />
388 ) : (
389 <SourceControlIcon kind={props.source} size={18} color={String(iconColor)} />
390 );
391
392 if (!props.ready) {
393 return (
394 <ListRow title={title} subtitle={props.hint} icon={icon} disabled isFirst={props.isFirst} />
395 );
396 }
397
398 return (
399 <ListRow
400 title={title}
401 subtitle={subtitle}
402 icon={icon}
403 isFirst={props.isFirst}
404 onPress={() =>
405 navigation.navigate("NewTaskSheet", {
406 screen: "AddProjectRepository",
407 params: {
408 environmentId: props.selectedEnvironmentId,
409 source: props.source,
410 },
411 })
412 }
413 />
414 );
415}
416
417export function AddProjectSourceScreen() {
418 const navigation = useNavigation();
419 const accentColor = useThemeColor("--color-icon-muted");
420 const iconColor = useThemeColor("--color-icon");
421 const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
422 useSelectedEnvironment();
423 const discoveryState = useEnvironmentQuery(
424 selectedEnvironment === null
425 ? null
426 : sourceControlEnvironment.discovery({
427 environmentId: selectedEnvironment.environmentId,
428 input: {},
429 }),
430 );
431 const readiness = useMemo(
432 () => buildAddProjectRemoteSourceReadiness(discoveryState.data),
433 [discoveryState.data],
434 );
435
436 return (
437 <AddProjectShell>
438 {selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
439
440 {environmentOptions.length > 1 ? (
441 <>
442 <SectionTitle>Environments</SectionTitle>
443 <ListSection>
444 {environmentOptions.map((environment, index) => (
445 <ListRow
446 key={environment.environmentId}
447 title={environment.label}
448 subtitle={
449 canCreateProjectInEnvironment(environment.connectionState)
450 ? environment.environmentId
451 : connectionStatusText({
452 phase: environment.connectionState,
453 error: environment.connectionError,
454 traceId: environment.connectionErrorTraceId,
455 })
456 }
457 icon={
458 <SymbolView
459 name="server.rack"
460 size={17}
461 tintColor={iconColor}
462 type="monochrome"
463 />
464 }
465 selected={environment.environmentId === selectedEnvironment?.environmentId}
466 disabled={!canCreateProjectInEnvironment(environment.connectionState)}
467 isFirst={index === 0}
468 right={
469 environment.environmentId === selectedEnvironment?.environmentId ? (
470 <SymbolView
471 name="checkmark"
472 size={14}
473 tintColor={iconColor}
474 type="monochrome"
475 />
476 ) : null
477 }
478 onPress={() => setSelectedEnvironmentId(environment.environmentId)}
479 />
480 ))}
481 </ListSection>
482 </>
483 ) : null}
484
485 {selectedEnvironment ? (
486 <>
487 <ListSection>
488 <ListRow
489 title="Local folder"
490 subtitle="Browse a folder on disk"
491 icon={
492 <SymbolView
493 name="folder.badge.plus"
494 size={17}
495 tintColor={iconColor}
496 type="monochrome"
497 />
498 }
499 isFirst
500 onPress={() =>
501 navigation.navigate("NewTaskSheet", {
502 screen: "AddProjectLocal",
503 params: {
504 environmentId: selectedEnvironment.environmentId,
505 },
506 })
507 }
508 />
509 {(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
510 (candidate) => (
511 <SourceControlRow
512 key={candidate}
513 source={candidate}
514 selectedEnvironmentId={selectedEnvironment.environmentId}
515 ready={readiness[candidate].ready}
516 hint={
517 readiness[candidate].ready
518 ? addProjectRemoteSourcePathHint(candidate)
519 : (readiness[candidate].hint ?? "")
520 }
521 isFirst={false}
522 />
523 ),
524 )}
525 </ListSection>
526 {discoveryState.isPending ? <ActivityIndicator color={accentColor} /> : null}
527 </>
528 ) : null}
529 </AddProjectShell>
530 );
531}
532
533function useCreateProject(environment: EnvironmentOption | null) {
534 const navigation = useNavigation();
535 const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
536 const projects = useProjects();
537
538 return useCallback(
539 async (workspaceRoot: string) => {
540 if (!environment || !canCreateProjectInEnvironment(environment.connectionState)) return;
541
542 const existing = findExistingAddProject({
543 projects,
544 environmentId: environment.environmentId,
545 path: workspaceRoot,
546 });
547 if (existing) {
548 Alert.alert("Project already exists", existing.title);
549 navigation.dispatch(
550 StackActions.replace("NewTaskDraft", {
551 environmentId: existing.environmentId,
552 projectId: existing.id,
553 title: existing.title,
554 }),
555 );
556 return;
557 }
558
559 const projectId = ProjectId.make(uuidv4());
560 const command = buildProjectCreateCommand({
561 commandId: CommandId.make(uuidv4()),
562 projectId,
563 workspaceRoot,
564 createdAt: new Date().toISOString(),
565 });
566 const result = await createProject({
567 environmentId: environment.environmentId,
568 input: command,
569 });
570 if (AsyncResult.isFailure(result)) {
571 return result;
572 }
573 navigation.dispatch(
574 StackActions.replace("NewTaskDraft", {
575 environmentId: environment.environmentId,
576 projectId,
577 title: inferProjectTitleFromPath(workspaceRoot),
578 }),
579 );
580 return result;
581 },
582 [createProject, environment, projects, navigation],
583 );
584}
585
586function useEnvironmentFromParam(
587 environmentIdParam: string | string[] | undefined,
588): EnvironmentOption | null {
589 const environmentOptions = useEnvironmentOptions();
590 const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
591 return resolveAddProjectEnvironment(environmentOptions, environmentId);
592}
593
594export function AddProjectRepositoryScreen(props: {
595 readonly environmentId?: string | string[];
596 readonly source?: string | string[];
597}) {
598 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
599 reportFailure: false,
600 });
601 const navigation = useNavigation();
602 const environment = useEnvironmentFromParam(props.environmentId);
603 const source = sourceFromParam(props.source);
604 const [repositoryInput, setRepositoryInput] = useState("");
605 const [isSubmitting, setIsSubmitting] = useState(false);
606 const [error, setError] = useState<string | null>(null);
607
608 const lookupRepository = useCallback(async () => {
609 if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
610 setError(null);
611 setIsSubmitting(true);
612 const provider = addProjectRemoteSourceProvider(source);
613 if (!provider) {
614 const remoteUrl = repositoryInput.trim();
615 navigation.navigate("NewTaskSheet", {
616 screen: "AddProjectDestination",
617 params: {
618 environmentId: environment.environmentId,
619 source,
620 remoteUrl,
621 repositoryTitle: remoteUrl,
622 },
623 });
624 setIsSubmitting(false);
625 return;
626 }
627
628 const result = await lookupRepositoryQuery({
629 environmentId: environment.environmentId,
630 input: {
631 provider,
632 repository: repositoryInput.trim(),
633 },
634 });
635 if (AsyncResult.isFailure(result)) {
636 setError(errorMessage(Cause.squash(result.cause)));
637 } else {
638 const repository = result.value;
639 navigation.navigate("NewTaskSheet", {
640 screen: "AddProjectDestination",
641 params: {
642 environmentId: environment.environmentId,
643 source,
644 remoteUrl: repository.sshUrl,
645 repositoryTitle: repository.nameWithOwner,
646 },
647 });
648 }
649 setIsSubmitting(false);
650 }, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
651
652 return (
653 <AddProjectShell>
654 {error ? <ErrorBanner message={error} /> : null}
655 {environment ? (
656 <>
657 <TextInput
658 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
659 value={repositoryInput}
660 onChangeText={setRepositoryInput}
661 autoCapitalize="none"
662 autoCorrect={false}
663 placeholder={
664 source === "url"
665 ? "https://github.com/org/repo.git"
666 : addProjectRemoteSourcePathHint(source)
667 }
668 returnKeyType="next"
669 onSubmitEditing={() => void lookupRepository()}
670 />
671 <PrimaryActionButton
672 label={source === "url" ? "Continue" : "Lookup repository"}
673 disabled={isSubmitting || repositoryInput.trim().length === 0}
674 onPress={() => void lookupRepository()}
675 loading={isSubmitting}
676 />
677 </>
678 ) : (
679 <EmptyEnvironmentState />
680 )}
681 </AddProjectShell>
682 );
683}
684
685function FolderBrowser(props: {
686 readonly environment: EnvironmentOption;
687 readonly pathInput: string;
688 readonly setPathInput: (path: string) => void;
689 readonly navigateToBrowsePath: (path: string) => Promise<boolean>;
690}) {
691 const accentColor = useThemeColor("--color-icon-muted");
692 const browsePath = useMemo(
693 () => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
694 [props.environment.platform, props.pathInput],
695 );
696 const browseInput = useMemo(
697 () => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
698 [browsePath.directoryPath],
699 );
700 const browseState = useEnvironmentQuery(
701 browseInput === null
702 ? null
703 : filesystemEnvironment.browse({
704 environmentId: props.environment.environmentId,
705 input: browseInput,
706 }),
707 );
708 const { visibleEntries: visibleBrowseEntries } = useMemo(
709 () => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browsePath.filterQuery),
710 [browsePath.filterQuery, browseState.data?.entries],
711 );
712
713 return (
714 <>
715 <SectionTitle>Browse folders</SectionTitle>
716 {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
717 <ListSection>
718 {browseState.isPending && browseState.data === null ? (
719 <View className="items-center py-5">
720 <ActivityIndicator color={accentColor} />
721 </View>
722 ) : null}
723 {browsePath.canBrowseUp ? (
724 <ListRow
725 title=".."
726 icon={
727 <SymbolView
728 name="arrow.turn.left.up"
729 size={17}
730 tintColor={accentColor}
731 type="monochrome"
732 />
733 }
734 isFirst
735 right={null}
736 onPress={() => {
737 if (browsePath.parentPath) {
738 void props.navigateToBrowsePath(browsePath.parentPath);
739 }
740 }}
741 />
742 ) : null}
743 {visibleBrowseEntries.map((entry, index) => (
744 <ListRow
745 key={entry.fullPath}
746 title={entry.name}
747 icon={<SymbolView name="folder" size={17} tintColor={accentColor} type="monochrome" />}
748 isFirst={index === 0 && !browsePath.canBrowseUp}
749 right={null}
750 onPress={() => {
751 const nextPath =
752 browsePath.directoryPath.length > 0
753 ? appendBrowsePathSegment(browsePath.directoryPath, entry.name)
754 : ensureBrowseDirectoryPath(entry.fullPath);
755 void props.navigateToBrowsePath(nextPath);
756 }}
757 />
758 ))}
759 </ListSection>
760 </>
761 );
762}
763
764export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
765 const environment = useEnvironmentFromParam(props.environmentId);
766 const createProject = useCreateProject(environment);
767 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
768 useBrowsePathInput(environment);
769 const [isSubmitting, setIsSubmitting] = useState(false);
770 const [error, setError] = useState<string | null>(null);
771
772 const submitPath = useCallback(async () => {
773 if (!environment || isBrowseNavigating || isSubmitting) return;
774 setError(null);
775 const resolved = resolveAddProjectPath({
776 rawPath: pathInput,
777 currentProjectCwd: null,
778 platform: environment.platform,
779 });
780 if (!resolved.ok) {
781 setError(resolved.error);
782 return;
783 }
784
785 setIsSubmitting(true);
786 const result = await createProject(resolved.path);
787 if (result && AsyncResult.isFailure(result)) {
788 setError(errorMessage(Cause.squash(result.cause)));
789 }
790 setIsSubmitting(false);
791 }, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
792
793 return (
794 <AddProjectShell>
795 {error ? <ErrorBanner message={error} /> : null}
796 {environment ? (
797 <>
798 <ProjectPathInput
799 value={pathInput}
800 onChangeText={setPathInput}
801 onSubmit={() => void submitPath()}
802 />
803 <PrimaryActionButton
804 label="Add project"
805 disabled={isBrowseNavigating || isSubmitting}
806 onPress={() => void submitPath()}
807 loading={isSubmitting}
808 />
809 <FolderBrowser
810 environment={environment}
811 navigateToBrowsePath={navigateToBrowsePath}
812 pathInput={pathInput}
813 setPathInput={setPathInput}
814 />
815 </>
816 ) : (
817 <EmptyEnvironmentState />
818 )}
819 </AddProjectShell>
820 );
821}
822
823export function AddProjectDestinationScreen(props: {
824 readonly environmentId?: string | string[];
825 readonly remoteUrl?: string | string[];
826 readonly repositoryTitle?: string | string[];
827}) {
828 const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
829 reportFailure: false,
830 });
831 const environment = useEnvironmentFromParam(props.environmentId);
832 const createProject = useCreateProject(environment);
833 const remoteUrl = stringParam(props.remoteUrl);
834 const repositoryTitle = stringParam(props.repositoryTitle);
835 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
836 useBrowsePathInput(environment);
837 const [isSubmitting, setIsSubmitting] = useState(false);
838 const [error, setError] = useState<string | null>(null);
839
840 const submitPath = useCallback(async () => {
841 if (!environment || !remoteUrl || isBrowseNavigating || isSubmitting) return;
842 setError(null);
843 const resolved = resolveAddProjectPath({
844 rawPath: pathInput,
845 currentProjectCwd: null,
846 platform: environment.platform,
847 });
848 if (!resolved.ok) {
849 setError(resolved.error);
850 return;
851 }
852
853 setIsSubmitting(true);
854 const cloneResult = await cloneRepository({
855 environmentId: environment.environmentId,
856 input: {
857 remoteUrl,
858 destinationPath: resolved.path,
859 },
860 });
861 if (AsyncResult.isFailure(cloneResult)) {
862 setError(errorMessage(Cause.squash(cloneResult.cause)));
863 } else {
864 const createResult = await createProject(cloneResult.value.cwd);
865 if (createResult && AsyncResult.isFailure(createResult)) {
866 setError(errorMessage(Cause.squash(createResult.cause)));
867 }
868 }
869 setIsSubmitting(false);
870 }, [
871 cloneRepository,
872 createProject,
873 environment,
874 isBrowseNavigating,
875 isSubmitting,
876 pathInput,
877 remoteUrl,
878 ]);
879
880 return (
881 <AddProjectShell>
882 {error ? <ErrorBanner message={error} /> : null}
883 {repositoryTitle ? (
884 <View className="rounded-[24px] bg-card px-4 py-3">
885 <Text className="text-base font-t3-bold">{repositoryTitle}</Text>
886 <Text className="mt-0.5 text-xs text-foreground-muted" numberOfLines={2}>
887 {remoteUrl}
888 </Text>
889 </View>
890 ) : null}
891 {environment ? (
892 <>
893 <ProjectPathInput
894 value={pathInput}
895 onChangeText={setPathInput}
896 onSubmit={() => void submitPath()}
897 />
898 <PrimaryActionButton
899 label="Clone project"
900 disabled={isBrowseNavigating || isSubmitting || !remoteUrl}
901 onPress={() => void submitPath()}
902 loading={isSubmitting}
903 />
904 <FolderBrowser
905 environment={environment}
906 navigateToBrowsePath={navigateToBrowsePath}
907 pathInput={pathInput}
908 setPathInput={setPathInput}
909 />
910 </>
911 ) : (
912 <EmptyEnvironmentState />
913 )}
914 </AddProjectShell>
915 );
916}