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