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

AddProjectScreen.tsx

838 lines26.7 KB

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