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

AddProjectScreen.tsx

928 lines30.3 KB

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 { CommonActions, 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;
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 "";
83​
84function errorMessage(error: unknown): string {
85 return error instanceof Error && error.message.trim().length > 0
86 ? error.message
87 : "An error occurred.";
89​
90function stringParam(value: string | string[] | undefined): string | null {
91 if (Array.isArray(value)) return value[0] ?? null;
92 return value ?? null;
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";
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 );
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 );
142​
143function ListSection(props: { readonly children: ReactNode }) {
144 return <View className="overflow-hidden rounded-[24px] bg-card">{props.children}</View>;
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 );
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 );
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 );
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 };
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]);
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 };
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 );
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.dispatch(
406 StackActions.push("AddProjectRepository", {
407 environmentId: props.selectedEnvironmentId,
408 source: props.source,
409 }),
410 )
411 }
412 />
413 );
415​
416export function AddProjectSourceScreen() {
417 const navigation = useNavigation();
418 const accentColor = useThemeColor("--color-icon-muted");
419 const iconColor = useThemeColor("--color-icon");
420 const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
421 useSelectedEnvironment();
422 const discoveryState = useEnvironmentQuery(
423 selectedEnvironment === null
424 ? null
425 : sourceControlEnvironment.discovery({
426 environmentId: selectedEnvironment.environmentId,
427 input: {},
428 }),
429 );
430 const readiness = useMemo(
431 () => buildAddProjectRemoteSourceReadiness(discoveryState.data),
432 [discoveryState.data],
433 );
434​
435 return (
436 <AddProjectShell>
437 {selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
438​
439 {environmentOptions.length > 1 ? (
440 <>
441 <SectionTitle>Environments</SectionTitle>
442 <ListSection>
443 {environmentOptions.map((environment, index) => (
444 <ListRow
445 key={environment.environmentId}
446 title={environment.label}
447 subtitle={
448 canCreateProjectInEnvironment(environment.connectionState)
449 ? environment.environmentId
450 : connectionStatusText({
451 phase: environment.connectionState,
452 error: environment.connectionError,
453 traceId: environment.connectionErrorTraceId,
454 })
455 }
456 icon={
457 <SymbolView
458 name="server.rack"
459 size={17}
460 tintColor={iconColor}
461 type="monochrome"
462 />
463 }
464 selected={environment.environmentId === selectedEnvironment?.environmentId}
465 disabled={!canCreateProjectInEnvironment(environment.connectionState)}
466 isFirst={index === 0}
467 right={
468 environment.environmentId === selectedEnvironment?.environmentId ? (
469 <SymbolView
470 name="checkmark"
471 size={14}
472 tintColor={iconColor}
473 type="monochrome"
474 />
475 ) : null
476 }
477 onPress={() => setSelectedEnvironmentId(environment.environmentId)}
478 />
479 ))}
480 </ListSection>
481 </>
482 ) : null}
483​
484 {selectedEnvironment ? (
485 <>
486 <ListSection>
487 <ListRow
488 title="Local folder"
489 subtitle="Browse a folder on disk"
490 icon={
491 <SymbolView
492 name="folder.badge.plus"
493 size={17}
494 tintColor={iconColor}
495 type="monochrome"
496 />
497 }
498 isFirst
499 onPress={() =>
500 navigation.dispatch(
501 StackActions.push("AddProjectLocal", {
502 environmentId: selectedEnvironment.environmentId,
503 }),
504 )
505 }
506 />
507 {(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
508 (candidate) => (
509 <SourceControlRow
510 key={candidate}
511 source={candidate}
512 selectedEnvironmentId={selectedEnvironment.environmentId}
513 ready={readiness[candidate].ready}
514 hint={
515 readiness[candidate].ready
516 ? addProjectRemoteSourcePathHint(candidate)
517 : (readiness[candidate].hint ?? "")
518 }
519 isFirst={false}
520 />
521 ),
522 )}
523 </ListSection>
524 {discoveryState.isPending ? <ActivityIndicator color={accentColor} /> : null}
525 </>
526 ) : null}
527 </AddProjectShell>
528 );
530​
531function useCreateProject(environment: EnvironmentOption | null) {
532 const navigation = useNavigation();
533 const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
534 const projects = useProjects();
535​
536 return useCallback(
537 async (workspaceRoot: string) => {
538 if (!environment || !canCreateProjectInEnvironment(environment.connectionState)) return;
539​
540 const existing = findExistingAddProject({
541 projects,
542 environmentId: environment.environmentId,
543 path: workspaceRoot,
544 });
545 if (existing) {
546 Alert.alert("Project already exists", existing.title);
547 navigation.dispatch(
548 CommonActions.reset({
549 index: 0,
550 routes: [
551 {
552 name: "NewTaskDraft",
553 params: {
554 environmentId: existing.environmentId,
555 projectId: existing.id,
556 title: existing.title,
557 },
558 },
559 ],
560 }),
561 );
562 return;
563 }
564​
565 const projectId = ProjectId.make(uuidv4());
566 const command = buildProjectCreateCommand({
567 commandId: CommandId.make(uuidv4()),
568 projectId,
569 workspaceRoot,
570 createdAt: new Date().toISOString(),
571 });
572 const result = await createProject({
573 environmentId: environment.environmentId,
574 input: command,
575 });
576 if (AsyncResult.isFailure(result)) {
577 return result;
578 }
579 navigation.dispatch(
580 CommonActions.reset({
581 index: 0,
582 routes: [
583 {
584 name: "NewTaskDraft",
585 params: {
586 environmentId: environment.environmentId,
587 projectId,
588 title: inferProjectTitleFromPath(workspaceRoot),
589 },
590 },
591 ],
592 }),
593 );
594 return result;
595 },
596 [createProject, environment, projects, navigation],
597 );
599​
600function useEnvironmentFromParam(
601 environmentIdParam: string | string[] | undefined,
602): EnvironmentOption | null {
603 const environmentOptions = useEnvironmentOptions();
604 const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
605 return resolveAddProjectEnvironment(environmentOptions, environmentId);
607​
608export function AddProjectRepositoryScreen(props: {
609 readonly environmentId?: string | string[];
610 readonly source?: string | string[];
611}) {
612 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
613 reportFailure: false,
614 });
615 const navigation = useNavigation();
616 const environment = useEnvironmentFromParam(props.environmentId);
617 const source = sourceFromParam(props.source);
618 const [repositoryInput, setRepositoryInput] = useState("");
619 const [isSubmitting, setIsSubmitting] = useState(false);
620 const [error, setError] = useState<string | null>(null);
621​
622 const lookupRepository = useCallback(async () => {
623 if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
624 setError(null);
625 setIsSubmitting(true);
626 const provider = addProjectRemoteSourceProvider(source);
627 if (!provider) {
628 const remoteUrl = repositoryInput.trim();
629 navigation.dispatch(
630 StackActions.push("AddProjectDestination", {
631 environmentId: environment.environmentId,
632 source,
633 remoteUrl,
634 repositoryTitle: remoteUrl,
635 }),
636 );
637 setIsSubmitting(false);
638 return;
639 }
640​
641 const result = await lookupRepositoryQuery({
642 environmentId: environment.environmentId,
643 input: {
644 provider,
645 repository: repositoryInput.trim(),
646 },
647 });
648 if (AsyncResult.isFailure(result)) {
649 setError(errorMessage(Cause.squash(result.cause)));
650 } else {
651 const repository = result.value;
652 navigation.dispatch(
653 StackActions.push("AddProjectDestination", {
654 environmentId: environment.environmentId,
655 source,
656 remoteUrl: repository.sshUrl,
657 repositoryTitle: repository.nameWithOwner,
658 }),
659 );
660 }
661 setIsSubmitting(false);
662 }, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
663​
664 return (
665 <AddProjectShell>
666 {error ? <ErrorBanner message={error} /> : null}
667 {environment ? (
668 <>
669 <TextInput
670 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
671 value={repositoryInput}
672 onChangeText={setRepositoryInput}
673 autoCapitalize="none"
674 autoCorrect={false}
675 placeholder={
676 source === "url"
677 ? "https://github.com/org/repo.git"
678 : addProjectRemoteSourcePathHint(source)
679 }
680 returnKeyType="next"
681 onSubmitEditing={() => void lookupRepository()}
682 />
683 <PrimaryActionButton
684 label={source === "url" ? "Continue" : "Lookup repository"}
685 disabled={isSubmitting || repositoryInput.trim().length === 0}
686 onPress={() => void lookupRepository()}
687 loading={isSubmitting}
688 />
689 </>
690 ) : (
691 <EmptyEnvironmentState />
692 )}
693 </AddProjectShell>
694 );
696​
697function FolderBrowser(props: {
698 readonly environment: EnvironmentOption;
699 readonly pathInput: string;
700 readonly setPathInput: (path: string) => void;
701 readonly navigateToBrowsePath: (path: string) => Promise<boolean>;
702}) {
703 const accentColor = useThemeColor("--color-icon-muted");
704 const browsePath = useMemo(
705 () => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
706 [props.environment.platform, props.pathInput],
707 );
708 const browseInput = useMemo(
709 () => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
710 [browsePath.directoryPath],
711 );
712 const browseState = useEnvironmentQuery(
713 browseInput === null
714 ? null
715 : filesystemEnvironment.browse({
716 environmentId: props.environment.environmentId,
717 input: browseInput,
718 }),
719 );
720 const { visibleEntries: visibleBrowseEntries } = useMemo(
721 () => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browsePath.filterQuery),
722 [browsePath.filterQuery, browseState.data?.entries],
723 );
724​
725 return (
726 <>
727 <SectionTitle>Browse folders</SectionTitle>
728 {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
729 <ListSection>
730 {browseState.isPending && browseState.data === null ? (
731 <View className="items-center py-5">
732 <ActivityIndicator color={accentColor} />
733 </View>
734 ) : null}
735 {browsePath.canBrowseUp ? (
736 <ListRow
737 title=".."
738 icon={
739 <SymbolView
740 name="arrow.turn.left.up"
741 size={17}
742 tintColor={accentColor}
743 type="monochrome"
744 />
745 }
746 isFirst
747 right={null}
748 onPress={() => {
749 if (browsePath.parentPath) {
750 void props.navigateToBrowsePath(browsePath.parentPath);
751 }
752 }}
753 />
754 ) : null}
755 {visibleBrowseEntries.map((entry, index) => (
756 <ListRow
757 key={entry.fullPath}
758 title={entry.name}
759 icon={<SymbolView name="folder" size={17} tintColor={accentColor} type="monochrome" />}
760 isFirst={index === 0 && !browsePath.canBrowseUp}
761 right={null}
762 onPress={() => {
763 const nextPath =
764 browsePath.directoryPath.length > 0
765 ? appendBrowsePathSegment(browsePath.directoryPath, entry.name)
766 : ensureBrowseDirectoryPath(entry.fullPath);
767 void props.navigateToBrowsePath(nextPath);
768 }}
769 />
770 ))}
771 </ListSection>
772 </>
773 );
775​
776export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
777 const environment = useEnvironmentFromParam(props.environmentId);
778 const createProject = useCreateProject(environment);
779 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
780 useBrowsePathInput(environment);
781 const [isSubmitting, setIsSubmitting] = useState(false);
782 const [error, setError] = useState<string | null>(null);
783​
784 const submitPath = useCallback(async () => {
785 if (!environment || isBrowseNavigating || isSubmitting) return;
786 setError(null);
787 const resolved = resolveAddProjectPath({
788 rawPath: pathInput,
789 currentProjectCwd: null,
790 platform: environment.platform,
791 });
792 if (!resolved.ok) {
793 setError(resolved.error);
794 return;
795 }
796​
797 setIsSubmitting(true);
798 const result = await createProject(resolved.path);
799 if (result && AsyncResult.isFailure(result)) {
800 setError(errorMessage(Cause.squash(result.cause)));
801 }
802 setIsSubmitting(false);
803 }, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
804​
805 return (
806 <AddProjectShell>
807 {error ? <ErrorBanner message={error} /> : null}
808 {environment ? (
809 <>
810 <ProjectPathInput
811 value={pathInput}
812 onChangeText={setPathInput}
813 onSubmit={() => void submitPath()}
814 />
815 <PrimaryActionButton
816 label="Add project"
817 disabled={isBrowseNavigating || isSubmitting}
818 onPress={() => void submitPath()}
819 loading={isSubmitting}
820 />
821 <FolderBrowser
822 environment={environment}
823 navigateToBrowsePath={navigateToBrowsePath}
824 pathInput={pathInput}
825 setPathInput={setPathInput}
826 />
827 </>
828 ) : (
829 <EmptyEnvironmentState />
830 )}
831 </AddProjectShell>
832 );
834​
835export function AddProjectDestinationScreen(props: {
836 readonly environmentId?: string | string[];
837 readonly remoteUrl?: string | string[];
838 readonly repositoryTitle?: string | string[];
839}) {
840 const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
841 reportFailure: false,
842 });
843 const environment = useEnvironmentFromParam(props.environmentId);
844 const createProject = useCreateProject(environment);
845 const remoteUrl = stringParam(props.remoteUrl);
846 const repositoryTitle = stringParam(props.repositoryTitle);
847 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
848 useBrowsePathInput(environment);
849 const [isSubmitting, setIsSubmitting] = useState(false);
850 const [error, setError] = useState<string | null>(null);
851​
852 const submitPath = useCallback(async () => {
853 if (!environment || !remoteUrl || isBrowseNavigating || isSubmitting) return;
854 setError(null);
855 const resolved = resolveAddProjectPath({
856 rawPath: pathInput,
857 currentProjectCwd: null,
858 platform: environment.platform,
859 });
860 if (!resolved.ok) {
861 setError(resolved.error);
862 return;
863 }
864​
865 setIsSubmitting(true);
866 const cloneResult = await cloneRepository({
867 environmentId: environment.environmentId,
868 input: {
869 remoteUrl,
870 destinationPath: resolved.path,
871 },
872 });
873 if (AsyncResult.isFailure(cloneResult)) {
874 setError(errorMessage(Cause.squash(cloneResult.cause)));
875 } else {
876 const createResult = await createProject(cloneResult.value.cwd);
877 if (createResult && AsyncResult.isFailure(createResult)) {
878 setError(errorMessage(Cause.squash(createResult.cause)));
879 }
880 }
881 setIsSubmitting(false);
882 }, [
883 cloneRepository,
884 createProject,
885 environment,
886 isBrowseNavigating,
887 isSubmitting,
888 pathInput,
889 remoteUrl,
890 ]);
891​
892 return (
893 <AddProjectShell>
894 {error ? <ErrorBanner message={error} /> : null}
895 {repositoryTitle ? (
896 <View className="rounded-[24px] bg-card px-4 py-3">
897 <Text className="text-base font-t3-bold">{repositoryTitle}</Text>
898 <Text className="mt-0.5 text-xs text-foreground-muted" numberOfLines={2}>
899 {remoteUrl}
900 </Text>
901 </View>
902 ) : null}
903 {environment ? (
904 <>
905 <ProjectPathInput
906 value={pathInput}
907 onChangeText={setPathInput}
908 onSubmit={() => void submitPath()}
909 />
910 <PrimaryActionButton
911 label="Clone project"
912 disabled={isBrowseNavigating || isSubmitting || !remoteUrl}
913 onPress={() => void submitPath()}
914 loading={isSubmitting}
915 />
916 <FolderBrowser
917 environment={environment}
918 navigateToBrowsePath={navigateToBrowsePath}
919 pathInput={pathInput}
920 setPathInput={setPathInput}
921 />
922 </>
923 ) : (
924 <EmptyEnvironmentState />
925 )}
926 </AddProjectShell>
927 );