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

AddProjectScreen.tsx

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