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