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

AddProjectScreen.tsx

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