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