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

AddProjectScreen.tsx

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