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