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

AddProjectScreen.tsx

838 lines26.2 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 "@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 { useLocalSearchParams, useRouter } from "expo-router";
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;
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 "";
74​
75function errorMessage(error: unknown): string {
76 return error instanceof Error && error.message.trim().length > 0
77 ? error.message
78 : "An error occurred.";
80​
81function stringParam(value: string | string[] | undefined): string | null {
82 if (Array.isArray(value)) return value[0] ?? null;
83 return value ?? null;
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";
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 );
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 );
131​
132function ListSection(props: { readonly children: ReactNode }) {
133 return <View className="overflow-hidden rounded-[24px] bg-card">{props.children}</View>;
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-[21px] font-t3-bold">{props.title}</Text>
172 {props.subtitle ? (
173 <Text className="text-sm leading-[17px] 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 );
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 );
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-[20px]"
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 );
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]);
247​
248function useSelectedEnvironment(): {
249 readonly environmentOptions: ReadonlyArray<EnvironmentOption>;
250 readonly selectedEnvironment: EnvironmentOption | null;
251 readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void;
252} {
253 const router = useRouter();
254 const params = useLocalSearchParams<{ environmentId?: string }>();
255 const environmentOptions = useEnvironmentOptions();
256 const requestedEnvironmentId = stringParam(params.environmentId) as EnvironmentId | null;
257 const selectedEnvironment =
258 environmentOptions.find(
259 (environment) => environment.environmentId === requestedEnvironmentId,
260 ) ??
261 environmentOptions[0] ??
262 null;
263​
264 return {
265 environmentOptions,
266 selectedEnvironment,
267 setSelectedEnvironmentId: (environmentId) => router.setParams({ environmentId }),
268 };
270​
271function EmptyEnvironmentState() {
272 const router = useRouter();
273​
274 return (
275 <View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
276 <Text className="text-center text-lg font-t3-bold">No environments connected</Text>
277 <Text className="text-center text-sm leading-[20px] text-foreground-muted">
278 Add an environment before adding a project.
279 </Text>
280 <Pressable
281 onPress={() => router.replace("/connections/new")}
282 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
283 >
284 <Text className="text-sm font-t3-bold text-primary-foreground">Add environment</Text>
285 </Pressable>
286 </View>
287 );
289​
290function SourceControlRow(props: {
291 readonly source: AddProjectRemoteSource;
292 readonly selectedEnvironmentId: EnvironmentId;
293 readonly ready: boolean;
294 readonly hint: string;
295 readonly isFirst: boolean;
296}) {
297 const router = useRouter();
298 const iconColor = useThemeColor("--color-icon");
299 const title =
300 props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`;
301 const subtitle =
302 props.source === "url"
303 ? "Clone from a remote URL"
304 : `Clone ${addProjectRemoteSourceLabel(props.source)} ${props.hint}`;
305 const icon =
306 props.source === "url" ? (
307 <SymbolView name="link" size={17} tintColor={iconColor} type="monochrome" />
308 ) : (
309 <SourceControlIcon kind={props.source} size={18} color={String(iconColor)} />
310 );
311​
312 if (!props.ready) {
313 return (
314 <ListRow title={title} subtitle={props.hint} icon={icon} disabled isFirst={props.isFirst} />
315 );
316 }
317​
318 return (
319 <ListRow
320 title={title}
321 subtitle={subtitle}
322 icon={icon}
323 isFirst={props.isFirst}
324 onPress={() =>
325 router.push({
326 pathname: "/new/add-project/repository",
327 params: {
328 environmentId: props.selectedEnvironmentId,
329 source: props.source,
330 },
331 })
332 }
333 />
334 );
336​
337export function AddProjectSourceScreen() {
338 const router = useRouter();
339 const accentColor = useThemeColor("--color-icon-muted");
340 const iconColor = useThemeColor("--color-icon");
341 const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
342 useSelectedEnvironment();
343 const discoveryState = useEnvironmentQuery(
344 selectedEnvironment === null
345 ? null
346 : sourceControlEnvironment.discovery({
347 environmentId: selectedEnvironment.environmentId,
348 input: {},
349 }),
350 );
351 const readiness = useMemo(
352 () => buildAddProjectRemoteSourceReadiness(discoveryState.data),
353 [discoveryState.data],
354 );
355​
356 return (
357 <AddProjectShell>
358 {environmentOptions.length === 0 ? <EmptyEnvironmentState /> : null}
359​
360 {environmentOptions.length > 1 ? (
361 <>
362 <SectionTitle>Connected environments</SectionTitle>
363 <ListSection>
364 {environmentOptions.map((environment, index) => (
365 <ListRow
366 key={environment.environmentId}
367 title={environment.label}
368 subtitle={environment.environmentId}
369 icon={
370 <SymbolView
371 name="server.rack"
372 size={17}
373 tintColor={iconColor}
374 type="monochrome"
375 />
376 }
377 selected={environment.environmentId === selectedEnvironment?.environmentId}
378 isFirst={index === 0}
379 right={
380 environment.environmentId === selectedEnvironment?.environmentId ? (
381 <SymbolView
382 name="checkmark"
383 size={14}
384 tintColor={iconColor}
385 type="monochrome"
386 />
387 ) : null
388 }
389 onPress={() => setSelectedEnvironmentId(environment.environmentId)}
390 />
391 ))}
392 </ListSection>
393 </>
394 ) : null}
395​
396 {selectedEnvironment ? (
397 <>
398 <ListSection>
399 <ListRow
400 title="Local folder"
401 subtitle="Browse a folder on disk"
402 icon={
403 <SymbolView
404 name="folder.badge.plus"
405 size={17}
406 tintColor={iconColor}
407 type="monochrome"
408 />
409 }
410 isFirst
411 onPress={() =>
412 router.push({
413 pathname: "/new/add-project/local",
414 params: { environmentId: selectedEnvironment.environmentId },
415 })
416 }
417 />
418 {(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
419 (candidate) => (
420 <SourceControlRow
421 key={candidate}
422 source={candidate}
423 selectedEnvironmentId={selectedEnvironment.environmentId}
424 ready={readiness[candidate].ready}
425 hint={
426 readiness[candidate].ready
427 ? addProjectRemoteSourcePathHint(candidate)
428 : (readiness[candidate].hint ?? "")
429 }
430 isFirst={false}
431 />
432 ),
433 )}
434 </ListSection>
435 {discoveryState.isPending ? <ActivityIndicator color={accentColor} /> : null}
436 </>
437 ) : null}
438 </AddProjectShell>
439 );
441​
442function useCreateProject(environment: EnvironmentOption | null) {
443 const router = useRouter();
444 const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
445 const projects = useProjects();
446​
447 return useCallback(
448 async (workspaceRoot: string) => {
449 if (!environment) return;
450​
451 const existing = findExistingAddProject({
452 projects,
453 environmentId: environment.environmentId,
454 path: workspaceRoot,
455 });
456 if (existing) {
457 Alert.alert("Project already exists", existing.title);
458 router.replace({
459 pathname: "/new/draft",
460 params: {
461 environmentId: existing.environmentId,
462 projectId: existing.id,
463 title: existing.title,
464 },
465 });
466 return;
467 }
468​
469 const projectId = ProjectId.make(uuidv4());
470 const command = buildProjectCreateCommand({
471 commandId: CommandId.make(uuidv4()),
472 projectId,
473 workspaceRoot,
474 });
475 const result = await createProject({
476 environmentId: environment.environmentId,
477 input: command,
478 });
479 if (AsyncResult.isFailure(result)) {
480 return result;
481 }
482 router.replace({
483 pathname: "/new/draft",
484 params: {
485 environmentId: environment.environmentId,
486 projectId,
487 title: inferProjectTitleFromPath(workspaceRoot),
488 },
489 });
490 return result;
491 },
492 [createProject, environment, projects, router],
493 );
495​
496function useEnvironmentFromParam(): EnvironmentOption | null {
497 const params = useLocalSearchParams<{ environmentId?: string }>();
498 const environmentOptions = useEnvironmentOptions();
499 const environmentId = stringParam(params.environmentId) as EnvironmentId | null;
500 return (
501 environmentOptions.find((environment) => environment.environmentId === environmentId) ??
502 environmentOptions[0] ??
503 null
504 );
506​
507export function AddProjectRepositoryScreen() {
508 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
509 reportFailure: false,
510 });
511 const router = useRouter();
512 const params = useLocalSearchParams<{ environmentId?: string; source?: string }>();
513 const environment = useEnvironmentFromParam();
514 const source = sourceFromParam(params.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 router.push({
527 pathname: "/new/add-project/destination",
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 router.push({
551 pathname: "/new/add-project/destination",
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, router, 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-[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 = 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 );
682​
683export function AddProjectLocalFolderScreen() {
684 const environment = useEnvironmentFromParam();
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 );
746​
747export function AddProjectDestinationScreen() {
748 const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
749 reportFailure: false,
750 });
751 const params = useLocalSearchParams<{
752 environmentId?: string;
753 remoteUrl?: string;
754 repositoryTitle?: string;
755 }>();
756 const environment = useEnvironmentFromParam();
757 const createProject = useCreateProject(environment);
758 const remoteUrl = stringParam(params.remoteUrl);
759 const repositoryTitle = stringParam(params.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-t3-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 );