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

AddProjectScreen.tsx

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