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 { 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;
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-[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 );
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-[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 );
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 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 };
269}
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 );
288}
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 );
335}
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 );
440}
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 createdAt: new Date().toISOString(),
475 });
476 const result = await createProject({
477 environmentId: environment.environmentId,
478 input: command,
479 });
480 if (AsyncResult.isFailure(result)) {
481 return result;
482 }
483 router.replace({
484 pathname: "/new/draft",
485 params: {
486 environmentId: environment.environmentId,
487 projectId,
488 title: inferProjectTitleFromPath(workspaceRoot),
489 },
490 });
491 return result;
492 },
493 [createProject, environment, projects, router],
494 );
495}
496
497function useEnvironmentFromParam(): EnvironmentOption | null {
498 const params = useLocalSearchParams<{ environmentId?: string }>();
499 const environmentOptions = useEnvironmentOptions();
500 const environmentId = stringParam(params.environmentId) as EnvironmentId | null;
501 return (
502 environmentOptions.find((environment) => environment.environmentId === environmentId) ??
503 environmentOptions[0] ??
504 null
505 );
506}
507
508export function AddProjectRepositoryScreen() {
509 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
510 reportFailure: false,
511 });
512 const router = useRouter();
513 const params = useLocalSearchParams<{ environmentId?: string; source?: string }>();
514 const environment = useEnvironmentFromParam();
515 const source = sourceFromParam(params.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 router.push({
528 pathname: "/new/add-project/destination",
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 router.push({
552 pathname: "/new/add-project/destination",
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, router, 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-[20px]"
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 );
589}
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 );
682}
683
684export function AddProjectLocalFolderScreen() {
685 const environment = useEnvironmentFromParam();
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 );
746}
747
748export function AddProjectDestinationScreen() {
749 const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
750 reportFailure: false,
751 });
752 const params = useLocalSearchParams<{
753 environmentId?: string;
754 remoteUrl?: string;
755 repositoryTitle?: string;
756 }>();
757 const environment = useEnvironmentFromParam();
758 const createProject = useCreateProject(environment);
759 const remoteUrl = stringParam(params.remoteUrl);
760 const repositoryTitle = stringParam(params.repositoryTitle);
761 const [pathInput, setPathInput] = useState(() =>
762 getAddProjectInitialQuery(environment?.baseDirectory),
763 );
764 const [isSubmitting, setIsSubmitting] = useState(false);
765 const [error, setError] = useState<string | null>(null);
766
767 useEffect(() => {
768 if (!environment) return;
769 setPathInput(getAddProjectInitialQuery(environment.baseDirectory));
770 }, [environment]);
771
772 const submitPath = useCallback(async () => {
773 if (!environment || !remoteUrl || isSubmitting) return;
774 setError(null);
775 const resolved = resolveAddProjectPath({
776 rawPath: pathInput,
777 currentProjectCwd: null,
778 platform: environment.platform,
779 });
780 if (!resolved.ok) {
781 setError(resolved.error);
782 return;
783 }
784
785 setIsSubmitting(true);
786 const cloneResult = await cloneRepository({
787 environmentId: environment.environmentId,
788 input: {
789 remoteUrl,
790 destinationPath: resolved.path,
791 },
792 });
793 if (AsyncResult.isFailure(cloneResult)) {
794 setError(errorMessage(Cause.squash(cloneResult.cause)));
795 } else {
796 const createResult = await createProject(cloneResult.value.cwd);
797 if (createResult && AsyncResult.isFailure(createResult)) {
798 setError(errorMessage(Cause.squash(createResult.cause)));
799 }
800 }
801 setIsSubmitting(false);
802 }, [cloneRepository, createProject, environment, isSubmitting, pathInput, remoteUrl]);
803
804 return (
805 <AddProjectShell>
806 {error ? <ErrorBanner message={error} /> : null}
807 {repositoryTitle ? (
808 <View className="rounded-[24px] bg-card px-4 py-3">
809 <Text className="text-base font-t3-bold">{repositoryTitle}</Text>
810 <Text className="mt-0.5 text-xs text-foreground-muted" numberOfLines={2}>
811 {remoteUrl}
812 </Text>
813 </View>
814 ) : null}
815 {environment ? (
816 <>
817 <ProjectPathInput
818 value={pathInput}
819 onChangeText={setPathInput}
820 onSubmit={() => void submitPath()}
821 />
822 <PrimaryActionButton
823 label="Clone project"
824 disabled={isSubmitting || !remoteUrl}
825 onPress={() => void submitPath()}
826 loading={isSubmitting}
827 />
828 <FolderBrowser
829 environment={environment}
830 pathInput={pathInput}
831 setPathInput={setPathInput}
832 />
833 </>
834 ) : (
835 <EmptyEnvironmentState />
836 )}
837 </AddProjectShell>
838 );
839}