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

AddProjectScreen.tsx

827 lines26.0 KB

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