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

AddProjectScreen.tsx

1,003 lines33.2 KB

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;
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 "";
95​
96function errorMessage(error: unknown): string {
97 return error instanceof Error && error.message.trim().length > 0
98 ? error.message
99 : "An error occurred.";
101​
102function stringParam(value: string | string[] | undefined): string | null {
103 if (Array.isArray(value)) return value[0] ?? null;
104 return value ?? null;
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";
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 );
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 );
154​
155function ListSection(props: { readonly children: ReactNode }) {
156 return <View className="overflow-hidden rounded-[24px] bg-card">{props.children}</View>;
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 );
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 );
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 );
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 };
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]);
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 };
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 );
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 );
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 );
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 createdAt: new Date().toISOString(),
617 });
618 const result = await createProject({
619 environmentId: environment.environmentId,
620 input: command,
621 });
622 if (AsyncResult.isFailure(result)) {
623 return result;
624 }
625 navigation.dispatch(
626 CommonActions.reset({
627 index: 0,
628 routes: [
629 {
630 name: "NewTaskDraft",
631 params: {
632 environmentId: environment.environmentId,
633 projectId,
634 title: inferProjectTitleFromPath(workspaceRoot),
635 },
636 },
637 ],
638 }),
639 );
640 return result;
641 },
642 [createProject, environment, projects, navigation],
643 );
645​
646function useEnvironmentFromParam(
647 environmentIdParam: string | string[] | undefined,
648): EnvironmentOption | null {
649 const environmentOptions = useEnvironmentOptions();
650 const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
651 return resolveAddProjectEnvironment(environmentOptions, environmentId);
653​
654export function AddProjectRepositoryScreen(props: {
655 readonly environmentId?: string | string[];
656 readonly source?: string | string[];
657}) {
658 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
659 reportFailure: false,
660 });
661 const navigation = useNavigation();
662 const environment = useEnvironmentFromParam(props.environmentId);
663 const source = sourceFromParam(props.source);
664 const [repositoryInput, setRepositoryInput] = useState("");
665 const [isSubmitting, setIsSubmitting] = useState(false);
666 const [error, setError] = useState<string | null>(null);
667​
668 const lookupRepository = useCallback(async () => {
669 if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
670 setError(null);
671 setIsSubmitting(true);
672 const provider = addProjectRemoteSourceProvider(source);
673 if (!provider) {
674 const remoteUrl = normalizePastedCloneUrl(repositoryInput);
675 navigation.dispatch(
676 StackActions.push("AddProjectDestination", {
677 environmentId: environment.environmentId,
678 source,
679 remoteUrl,
680 repositoryTitle: remoteUrl,
681 repositoryName: getCloneDirectoryName(remoteUrl),
682 }),
683 );
684 setIsSubmitting(false);
685 return;
686 }
687​
688 const result = await lookupRepositoryQuery({
689 environmentId: environment.environmentId,
690 input: {
691 provider,
692 repository: repositoryInput.trim(),
693 },
694 });
695 if (AsyncResult.isFailure(result)) {
696 setError(errorMessage(Cause.squash(result.cause)));
697 } else {
698 const repository = result.value;
699 navigation.dispatch(
700 StackActions.push("AddProjectDestination", {
701 environmentId: environment.environmentId,
702 source,
703 remoteUrl: getDefaultCloneUrl(repository),
704 repositoryTitle: repository.nameWithOwner,
705 repositoryName: getCloneDirectoryName(repository.nameWithOwner),
706 }),
707 );
708 }
709 setIsSubmitting(false);
710 }, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
711​
712 return (
713 <AddProjectShell>
714 {error ? <ErrorBanner message={error} /> : null}
715 {environment ? (
716 <>
717 <TextInput
718 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
719 value={repositoryInput}
720 onChangeText={setRepositoryInput}
721 autoCapitalize="none"
722 autoCorrect={false}
723 placeholder={
724 source === "url"
725 ? "https://github.com/org/repo.git"
726 : addProjectRemoteSourcePathHint(source)
727 }
728 returnKeyType="next"
729 onSubmitEditing={() => void lookupRepository()}
730 />
731 <PrimaryActionButton
732 label={source === "url" ? "Continue" : "Lookup repository"}
733 disabled={isSubmitting || repositoryInput.trim().length === 0}
734 onPress={() => void lookupRepository()}
735 loading={isSubmitting}
736 />
737 </>
738 ) : (
739 <EmptyEnvironmentState />
740 )}
741 </AddProjectShell>
742 );
744​
745function FolderBrowser(props: {
746 readonly environment: EnvironmentOption;
747 readonly pathInput: string;
748 readonly setPathInput: (path: string) => void;
749 readonly navigateToBrowsePath: (input: {
750 readonly browseDirectoryPath: string;
751 readonly selectedDirectoryName?: string;
752 }) => Promise<boolean>;
753 readonly pinnedDirectoryName?: string;
754}) {
755 const browsePath = useMemo(
756 () => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
757 [props.environment.platform, props.pathInput],
758 );
759 const browseInput = useMemo(
760 () => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
761 [browsePath.directoryPath],
762 );
763 const browseState = useEnvironmentQuery(
764 browseInput === null
765 ? null
766 : filesystemEnvironment.browse({
767 environmentId: props.environment.environmentId,
768 input: browseInput,
769 }),
770 );
771 // A pinned repository folder does not exist yet, so filtering the listing by
772 // it would empty the folder picker. Anything the user typed still filters.
773 const pinnedDirectoryName = props.pinnedDirectoryName ?? "";
774 const pinnedDirectoryMatches = isWindowsPlatform(props.environment.platform)
775 ? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
776 : browsePath.filterQuery === pinnedDirectoryName;
777 const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
778 const { visibleEntries: visibleBrowseEntries } = useMemo(
779 () => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browseFilterQuery),
780 [browseFilterQuery, browseState.data?.entries],
781 );
782​
783 return (
784 <>
785 <SectionTitle>Browse folders</SectionTitle>
786 {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
787 <ListSection>
788 {browseState.isPending && browseState.data === null ? (
789 <View className="items-center py-5">
790 <ActivityIndicator colorClassName={"accent-icon-muted"} />
791 </View>
792 ) : null}
793 {browsePath.canBrowseUp ? (
794 <ListRow
795 title=".."
796 icon={
797 <SymbolView
798 name="arrow.turn.left.up"
799 size={17}
800 tintColorClassName={"accent-icon-muted"}
801 type="monochrome"
802 />
803 }
804 isFirst
805 right={null}
806 onPress={() => {
807 if (browsePath.parentPath) {
808 void props.navigateToBrowsePath({
809 browseDirectoryPath: browsePath.parentPath,
810 });
811 }
812 }}
813 />
814 ) : null}
815 {visibleBrowseEntries.map((entry, index) => (
816 <ListRow
817 key={entry.fullPath}
818 title={entry.name}
819 icon={
820 <SymbolView
821 name="folder"
822 size={17}
823 tintColorClassName={"accent-icon-muted"}
824 type="monochrome"
825 />
826 }
827 isFirst={index === 0 && !browsePath.canBrowseUp}
828 right={null}
829 onPress={() => {
830 void props.navigateToBrowsePath({
831 browseDirectoryPath: browsePath.directoryPath,
832 selectedDirectoryName: entry.name,
833 });
834 }}
835 />
836 ))}
837 </ListSection>
838 </>
839 );
841​
842export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
843 const environment = useEnvironmentFromParam(props.environmentId);
844 const createProject = useCreateProject(environment);
845 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
846 useBrowsePathInput(environment);
847 const [isSubmitting, setIsSubmitting] = useState(false);
848 const [error, setError] = useState<string | null>(null);
849​
850 const submitPath = useCallback(async () => {
851 if (!environment || isBrowseNavigating || isSubmitting) return;
852 setError(null);
853 const resolved = resolveAddProjectPath({
854 rawPath: pathInput,
855 currentProjectCwd: null,
856 platform: environment.platform,
857 });
858 if (!resolved.ok) {
859 setError(resolved.error);
860 return;
861 }
862​
863 setIsSubmitting(true);
864 const result = await createProject(resolved.path);
865 if (result && AsyncResult.isFailure(result)) {
866 setError(errorMessage(Cause.squash(result.cause)));
867 }
868 setIsSubmitting(false);
869 }, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
870​
871 return (
872 <AddProjectShell>
873 {error ? <ErrorBanner message={error} /> : null}
874 {environment ? (
875 <>
876 <ProjectPathInput
877 value={pathInput}
878 onChangeText={setPathInput}
879 onSubmit={() => void submitPath()}
880 />
881 <PrimaryActionButton
882 label="Add project"
883 disabled={isBrowseNavigating || isSubmitting}
884 onPress={() => void submitPath()}
885 loading={isSubmitting}
886 />
887 <FolderBrowser
888 environment={environment}
889 navigateToBrowsePath={navigateToBrowsePath}
890 pathInput={pathInput}
891 setPathInput={setPathInput}
892 />
893 </>
894 ) : (
895 <EmptyEnvironmentState />
896 )}
897 </AddProjectShell>
898 );
900​
901export function AddProjectDestinationScreen(props: {
902 readonly environmentId?: string | string[];
903 readonly remoteUrl?: string | string[];
904 readonly repositoryTitle?: string | string[];
905 readonly repositoryName?: string | string[];
906}) {
907 const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
908 reportFailure: false,
909 });
910 const environment = useEnvironmentFromParam(props.environmentId);
911 const createProject = useCreateProject(environment);
912 const remoteUrl = stringParam(props.remoteUrl);
913 const repositoryTitle = stringParam(props.repositoryTitle);
914 // A lookup derives this from "owner/repo", a pasted clone URL from its own
915 // last segment. Older links without the param keep the browsed folder.
916 // Trim once here: the path input and the folder-list filter must compare the
917 // same value, or a deep link with a padded param empties the folder picker.
918 const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
919 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
920 environment,
921 repositoryName,
922 );
923 const [isSubmitting, setIsSubmitting] = useState(false);
924 const [error, setError] = useState<string | null>(null);
925​
926 const submitPath = useCallback(async () => {
927 if (!environment || !remoteUrl || isBrowseNavigating || isSubmitting) return;
928 setError(null);
929 const resolved = resolveAddProjectPath({
930 rawPath: pathInput,
931 currentProjectCwd: null,
932 platform: environment.platform,
933 });
934 if (!resolved.ok) {
935 setError(resolved.error);
936 return;
937 }
938​
939 setIsSubmitting(true);
940 const cloneResult = await cloneRepository({
941 environmentId: environment.environmentId,
942 input: {
943 remoteUrl,
944 destinationPath: resolved.path,
945 },
946 });
947 if (AsyncResult.isFailure(cloneResult)) {
948 setError(errorMessage(Cause.squash(cloneResult.cause)));
949 } else {
950 const createResult = await createProject(cloneResult.value.cwd);
951 if (createResult && AsyncResult.isFailure(createResult)) {
952 setError(errorMessage(Cause.squash(createResult.cause)));
953 }
954 }
955 setIsSubmitting(false);
956 }, [
957 cloneRepository,
958 createProject,
959 environment,
960 isBrowseNavigating,
961 isSubmitting,
962 pathInput,
963 remoteUrl,
964 ]);
965​
966 return (
967 <AddProjectShell>
968 {error ? <ErrorBanner message={error} /> : null}
969 {repositoryTitle ? (
970 <View className="rounded-[24px] bg-card px-4 py-3">
971 <Text className="text-base font-t3-bold">{repositoryTitle}</Text>
972 <Text className="mt-0.5 text-xs text-foreground-muted" numberOfLines={2}>
973 {remoteUrl}
974 </Text>
975 </View>
976 ) : null}
977 {environment ? (
978 <>
979 <ProjectPathInput
980 value={pathInput}
981 onChangeText={setPathInput}
982 onSubmit={() => void submitPath()}
983 />
984 <PrimaryActionButton
985 label="Clone project"
986 disabled={isBrowseNavigating || isSubmitting || !remoteUrl}
987 onPress={() => void submitPath()}
988 loading={isSubmitting}
989 />
990 <FolderBrowser
991 environment={environment}
992 navigateToBrowsePath={navigateToBrowsePath}
993 pathInput={pathInput}
994 setPathInput={setPathInput}
995 pinnedDirectoryName={repositoryName}
996 />
997 </>
998 ) : (
999 <EmptyEnvironmentState />
1000 )}
1001 </AddProjectShell>
1002 );