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

AddProjectScreen.tsx

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