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

AddProjectScreen.tsx

990 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 { useThemeColor } from "../../lib/useThemeColor";
55import { uuidv4 } from "../../lib/uuid";
56import { useAtomCommand } from "../../state/use-atom-command";
57import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
58import {
59 useRemoteConnectionStatus,
60 useRemoteEnvironmentRuntime,
61 useSavedRemoteConnections,
62} from "../../state/use-remote-environment-registry";
63import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
64​
65interface EnvironmentOption {
66 readonly environmentId: EnvironmentId;
67 readonly label: string;
68 readonly platform: string;
69 readonly baseDirectory: string | null;
70 readonly connectionState: EnvironmentConnectionPhase;
71 readonly connectionError: string | null;
72 readonly connectionErrorTraceId: string | null;
74​
75const environmentOptionOrder = Order.mapInput(
76 Order.Struct({
77 label: Order.String,
78 }),
79 (environment: EnvironmentOption) => ({ label: environment.label }),
80);
81​
82function platformFromOs(os: string | null | undefined): string {
83 if (os === "windows") return "Win32";
84 if (os === "darwin") return "MacIntel";
85 if (os === "linux") return "Linux";
86 return "";
88​
89function errorMessage(error: unknown): string {
90 return error instanceof Error && error.message.trim().length > 0
91 ? error.message
92 : "An error occurred.";
94​
95function stringParam(value: string | string[] | undefined): string | null {
96 if (Array.isArray(value)) return value[0] ?? null;
97 return value ?? null;
99​
100function sourceFromParam(value: string | string[] | undefined): AddProjectRemoteSource {
101 const source = stringParam(value);
102 if (
103 source === "url" ||
104 source === "github" ||
105 source === "gitlab" ||
106 source === "bitbucket" ||
107 source === "azure-devops"
108 ) {
109 return source;
110 }
111 return "url";
113​
114function SectionTitle(props: { readonly children: string }) {
115 return (
116 <Text className="px-1 text-2xs font-t3-bold tracking-[0.7px] uppercase text-foreground-muted">
117 {props.children}
118 </Text>
119 );
121​
122function AddProjectShell(props: { readonly children: ReactNode }) {
123 const insets = useSafeAreaInsets();
124​
125 return (
126 // collapsable={false} is load-bearing: if this wrapper is flattened, the
127 // ScrollView lands directly under RNSSafeAreaView and RNS's formSheet
128 // scroll-view frame correction mistakes this full-height wrapper for a
129 // "header" sibling, coercing the ScrollView to zero height (blank sheet
130 // as soon as the sheet re-lays-out, e.g. when the keyboard opens).
131 <View collapsable={false} className="flex-1 bg-sheet">
132 <ScrollView
133 keyboardShouldPersistTaps="handled"
134 contentInsetAdjustmentBehavior="automatic"
135 contentContainerStyle={{
136 paddingHorizontal: 20,
137 paddingTop: 16,
138 paddingBottom: Math.max(insets.bottom, 18) + 18,
139 gap: 10,
140 }}
141 >
142 {props.children}
143 </ScrollView>
144 </View>
145 );
147​
148function ListSection(props: { readonly children: ReactNode }) {
149 return <View className="overflow-hidden rounded-[24px] bg-card">{props.children}</View>;
151​
152function ListRow(props: {
153 readonly title: string;
154 readonly subtitle?: string | null;
155 readonly icon: ReactNode;
156 readonly disabled?: boolean;
157 readonly selected?: boolean;
158 readonly isFirst?: boolean;
159 readonly right?: ReactNode;
160 readonly onPress?: () => void;
161}) {
162 const chevronColor = useThemeColor("--color-chevron");
163​
164 return (
165 <Pressable
166 disabled={props.disabled}
167 onPress={props.onPress}
168 className={cn(
169 "bg-card px-3.5 py-2.5 active:opacity-70",
170 !props.isFirst && "border-t border-border-subtle",
171 props.disabled && "opacity-[0.45]",
172 )}
173 >
174 <View className="flex-row items-center gap-3">
175 <View
176 className={
177 props.selected
178 ? "h-7 w-7 items-center justify-center rounded-full bg-primary"
179 : "h-7 w-7 items-center justify-center"
180 }
181 >
182 {props.icon}
183 </View>
184 <View className="flex-1 gap-0.5">
185 <Text className="text-base leading-snug font-t3-bold">{props.title}</Text>
186 {props.subtitle ? (
187 <Text className="text-sm leading-snug text-foreground-muted" numberOfLines={2}>
188 {props.subtitle}
189 </Text>
190 ) : null}
191 </View>
192 {"right" in props ? (
193 props.right
194 ) : !props.disabled ? (
195 <SymbolView name="chevron.right" size={13} tintColor={chevronColor} type="monochrome" />
196 ) : null}
197 </View>
198 </Pressable>
199 );
201​
202function PrimaryActionButton(props: {
203 readonly label: string;
204 readonly disabled?: boolean;
205 readonly loading?: boolean;
206 readonly onPress: () => void;
207}) {
208 const primaryForeground = useThemeColor("--color-primary-foreground");
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 color={String(primaryForeground)} />
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 iconColor = useThemeColor("--color-icon");
418 const title =
419 props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`;
420 const subtitle =
421 props.source === "url"
422 ? "Clone from a remote URL"
423 : `Clone ${addProjectRemoteSourceLabel(props.source)} ${props.hint}`;
424 const icon =
425 props.source === "url" ? (
426 <SymbolView name="link" size={17} tintColor={iconColor} type="monochrome" />
427 ) : (
428 <SourceControlIcon kind={props.source} size={18} color={String(iconColor)} />
429 );
430​
431 if (!props.ready) {
432 return (
433 <ListRow title={title} subtitle={props.hint} icon={icon} disabled isFirst={props.isFirst} />
434 );
435 }
436​
437 return (
438 <ListRow
439 title={title}
440 subtitle={subtitle}
441 icon={icon}
442 isFirst={props.isFirst}
443 onPress={() =>
444 navigation.dispatch(
445 StackActions.push("AddProjectRepository", {
446 environmentId: props.selectedEnvironmentId,
447 source: props.source,
448 }),
449 )
450 }
451 />
452 );
454​
455export function AddProjectSourceScreen() {
456 const navigation = useNavigation();
457 const accentColor = useThemeColor("--color-icon-muted");
458 const iconColor = useThemeColor("--color-icon");
459 const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
460 useSelectedEnvironment();
461 const discoveryState = useEnvironmentQuery(
462 selectedEnvironment === null
463 ? null
464 : sourceControlEnvironment.discovery({
465 environmentId: selectedEnvironment.environmentId,
466 input: {},
467 }),
468 );
469 const readiness = useMemo(
470 () => buildAddProjectRemoteSourceReadiness(discoveryState.data),
471 [discoveryState.data],
472 );
473​
474 return (
475 <AddProjectShell>
476 {selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
477​
478 {environmentOptions.length > 1 ? (
479 <>
480 <SectionTitle>Environments</SectionTitle>
481 <ListSection>
482 {environmentOptions.map((environment, index) => (
483 <ListRow
484 key={environment.environmentId}
485 title={environment.label}
486 subtitle={
487 canCreateProjectInEnvironment(environment.connectionState)
488 ? environment.environmentId
489 : connectionStatusText({
490 phase: environment.connectionState,
491 error: environment.connectionError,
492 traceId: environment.connectionErrorTraceId,
493 })
494 }
495 icon={
496 <SymbolView
497 name="server.rack"
498 size={17}
499 tintColor={iconColor}
500 type="monochrome"
501 />
502 }
503 selected={environment.environmentId === selectedEnvironment?.environmentId}
504 disabled={!canCreateProjectInEnvironment(environment.connectionState)}
505 isFirst={index === 0}
506 right={
507 environment.environmentId === selectedEnvironment?.environmentId ? (
508 <SymbolView
509 name="checkmark"
510 size={14}
511 tintColor={iconColor}
512 type="monochrome"
513 />
514 ) : null
515 }
516 onPress={() => setSelectedEnvironmentId(environment.environmentId)}
517 />
518 ))}
519 </ListSection>
520 </>
521 ) : null}
522​
523 {selectedEnvironment ? (
524 <>
525 <ListSection>
526 <ListRow
527 title="Local folder"
528 subtitle="Browse a folder on disk"
529 icon={
530 <SymbolView
531 name="folder.badge.plus"
532 size={17}
533 tintColor={iconColor}
534 type="monochrome"
535 />
536 }
537 isFirst
538 onPress={() =>
539 navigation.dispatch(
540 StackActions.push("AddProjectLocal", {
541 environmentId: selectedEnvironment.environmentId,
542 }),
543 )
544 }
545 />
546 {(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
547 (candidate) => (
548 <SourceControlRow
549 key={candidate}
550 source={candidate}
551 selectedEnvironmentId={selectedEnvironment.environmentId}
552 ready={readiness[candidate].ready}
553 hint={
554 readiness[candidate].ready
555 ? addProjectRemoteSourcePathHint(candidate)
556 : (readiness[candidate].hint ?? "")
557 }
558 isFirst={false}
559 />
560 ),
561 )}
562 </ListSection>
563 {discoveryState.isPending ? <ActivityIndicator color={accentColor} /> : null}
564 </>
565 ) : null}
566 </AddProjectShell>
567 );
569​
570function useCreateProject(environment: EnvironmentOption | null) {
571 const navigation = useNavigation();
572 const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
573 const projects = useProjects();
574​
575 return useCallback(
576 async (workspaceRoot: string) => {
577 if (!environment || !canCreateProjectInEnvironment(environment.connectionState)) return;
578​
579 const existing = findExistingAddProject({
580 projects,
581 environmentId: environment.environmentId,
582 path: workspaceRoot,
583 });
584 if (existing) {
585 Alert.alert("Project already exists", existing.title);
586 navigation.dispatch(
587 CommonActions.reset({
588 index: 0,
589 routes: [
590 {
591 name: "NewTaskDraft",
592 params: {
593 environmentId: existing.environmentId,
594 projectId: existing.id,
595 title: existing.title,
596 },
597 },
598 ],
599 }),
600 );
601 return;
602 }
603​
604 const projectId = ProjectId.make(uuidv4());
605 const command = buildProjectCreateCommand({
606 commandId: CommandId.make(uuidv4()),
607 projectId,
608 workspaceRoot,
609 createdAt: new Date().toISOString(),
610 });
611 const result = await createProject({
612 environmentId: environment.environmentId,
613 input: command,
614 });
615 if (AsyncResult.isFailure(result)) {
616 return result;
617 }
618 navigation.dispatch(
619 CommonActions.reset({
620 index: 0,
621 routes: [
622 {
623 name: "NewTaskDraft",
624 params: {
625 environmentId: environment.environmentId,
626 projectId,
627 title: inferProjectTitleFromPath(workspaceRoot),
628 },
629 },
630 ],
631 }),
632 );
633 return result;
634 },
635 [createProject, environment, projects, navigation],
636 );
638​
639function useEnvironmentFromParam(
640 environmentIdParam: string | string[] | undefined,
641): EnvironmentOption | null {
642 const environmentOptions = useEnvironmentOptions();
643 const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
644 return resolveAddProjectEnvironment(environmentOptions, environmentId);
646​
647export function AddProjectRepositoryScreen(props: {
648 readonly environmentId?: string | string[];
649 readonly source?: string | string[];
650}) {
651 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
652 reportFailure: false,
653 });
654 const navigation = useNavigation();
655 const environment = useEnvironmentFromParam(props.environmentId);
656 const source = sourceFromParam(props.source);
657 const [repositoryInput, setRepositoryInput] = useState("");
658 const [isSubmitting, setIsSubmitting] = useState(false);
659 const [error, setError] = useState<string | null>(null);
660​
661 const lookupRepository = useCallback(async () => {
662 if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
663 setError(null);
664 setIsSubmitting(true);
665 const provider = addProjectRemoteSourceProvider(source);
666 if (!provider) {
667 const remoteUrl = normalizePastedCloneUrl(repositoryInput);
668 navigation.dispatch(
669 StackActions.push("AddProjectDestination", {
670 environmentId: environment.environmentId,
671 source,
672 remoteUrl,
673 repositoryTitle: remoteUrl,
674 repositoryName: getCloneDirectoryName(remoteUrl),
675 }),
676 );
677 setIsSubmitting(false);
678 return;
679 }
680​
681 const result = await lookupRepositoryQuery({
682 environmentId: environment.environmentId,
683 input: {
684 provider,
685 repository: repositoryInput.trim(),
686 },
687 });
688 if (AsyncResult.isFailure(result)) {
689 setError(errorMessage(Cause.squash(result.cause)));
690 } else {
691 const repository = result.value;
692 navigation.dispatch(
693 StackActions.push("AddProjectDestination", {
694 environmentId: environment.environmentId,
695 source,
696 remoteUrl: getDefaultCloneUrl(repository),
697 repositoryTitle: repository.nameWithOwner,
698 repositoryName: getCloneDirectoryName(repository.nameWithOwner),
699 }),
700 );
701 }
702 setIsSubmitting(false);
703 }, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
704​
705 return (
706 <AddProjectShell>
707 {error ? <ErrorBanner message={error} /> : null}
708 {environment ? (
709 <>
710 <TextInput
711 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
712 value={repositoryInput}
713 onChangeText={setRepositoryInput}
714 autoCapitalize="none"
715 autoCorrect={false}
716 placeholder={
717 source === "url"
718 ? "https://github.com/org/repo.git"
719 : addProjectRemoteSourcePathHint(source)
720 }
721 returnKeyType="next"
722 onSubmitEditing={() => void lookupRepository()}
723 />
724 <PrimaryActionButton
725 label={source === "url" ? "Continue" : "Lookup repository"}
726 disabled={isSubmitting || repositoryInput.trim().length === 0}
727 onPress={() => void lookupRepository()}
728 loading={isSubmitting}
729 />
730 </>
731 ) : (
732 <EmptyEnvironmentState />
733 )}
734 </AddProjectShell>
735 );
737​
738function FolderBrowser(props: {
739 readonly environment: EnvironmentOption;
740 readonly pathInput: string;
741 readonly setPathInput: (path: string) => void;
742 readonly navigateToBrowsePath: (input: {
743 readonly browseDirectoryPath: string;
744 readonly selectedDirectoryName?: string;
745 }) => Promise<boolean>;
746 readonly pinnedDirectoryName?: string;
747}) {
748 const accentColor = useThemeColor("--color-icon-muted");
749 const browsePath = useMemo(
750 () => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
751 [props.environment.platform, props.pathInput],
752 );
753 const browseInput = useMemo(
754 () => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
755 [browsePath.directoryPath],
756 );
757 const browseState = useEnvironmentQuery(
758 browseInput === null
759 ? null
760 : filesystemEnvironment.browse({
761 environmentId: props.environment.environmentId,
762 input: browseInput,
763 }),
764 );
765 // A pinned repository folder does not exist yet, so filtering the listing by
766 // it would empty the folder picker. Anything the user typed still filters.
767 const pinnedDirectoryName = props.pinnedDirectoryName ?? "";
768 const pinnedDirectoryMatches = isWindowsPlatform(props.environment.platform)
769 ? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
770 : browsePath.filterQuery === pinnedDirectoryName;
771 const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
772 const { visibleEntries: visibleBrowseEntries } = useMemo(
773 () => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browseFilterQuery),
774 [browseFilterQuery, browseState.data?.entries],
775 );
776​
777 return (
778 <>
779 <SectionTitle>Browse folders</SectionTitle>
780 {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
781 <ListSection>
782 {browseState.isPending && browseState.data === null ? (
783 <View className="items-center py-5">
784 <ActivityIndicator color={accentColor} />
785 </View>
786 ) : null}
787 {browsePath.canBrowseUp ? (
788 <ListRow
789 title=".."
790 icon={
791 <SymbolView
792 name="arrow.turn.left.up"
793 size={17}
794 tintColor={accentColor}
795 type="monochrome"
796 />
797 }
798 isFirst
799 right={null}
800 onPress={() => {
801 if (browsePath.parentPath) {
802 void props.navigateToBrowsePath({
803 browseDirectoryPath: browsePath.parentPath,
804 });
805 }
806 }}
807 />
808 ) : null}
809 {visibleBrowseEntries.map((entry, index) => (
810 <ListRow
811 key={entry.fullPath}
812 title={entry.name}
813 icon={<SymbolView name="folder" size={17} tintColor={accentColor} type="monochrome" />}
814 isFirst={index === 0 && !browsePath.canBrowseUp}
815 right={null}
816 onPress={() => {
817 void props.navigateToBrowsePath({
818 browseDirectoryPath: browsePath.directoryPath,
819 selectedDirectoryName: entry.name,
820 });
821 }}
822 />
823 ))}
824 </ListSection>
825 </>
826 );
828​
829export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
830 const environment = useEnvironmentFromParam(props.environmentId);
831 const createProject = useCreateProject(environment);
832 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
833 useBrowsePathInput(environment);
834 const [isSubmitting, setIsSubmitting] = useState(false);
835 const [error, setError] = useState<string | null>(null);
836​
837 const submitPath = useCallback(async () => {
838 if (!environment || isBrowseNavigating || isSubmitting) return;
839 setError(null);
840 const resolved = resolveAddProjectPath({
841 rawPath: pathInput,
842 currentProjectCwd: null,
843 platform: environment.platform,
844 });
845 if (!resolved.ok) {
846 setError(resolved.error);
847 return;
848 }
849​
850 setIsSubmitting(true);
851 const result = await createProject(resolved.path);
852 if (result && AsyncResult.isFailure(result)) {
853 setError(errorMessage(Cause.squash(result.cause)));
854 }
855 setIsSubmitting(false);
856 }, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
857​
858 return (
859 <AddProjectShell>
860 {error ? <ErrorBanner message={error} /> : null}
861 {environment ? (
862 <>
863 <ProjectPathInput
864 value={pathInput}
865 onChangeText={setPathInput}
866 onSubmit={() => void submitPath()}
867 />
868 <PrimaryActionButton
869 label="Add project"
870 disabled={isBrowseNavigating || isSubmitting}
871 onPress={() => void submitPath()}
872 loading={isSubmitting}
873 />
874 <FolderBrowser
875 environment={environment}
876 navigateToBrowsePath={navigateToBrowsePath}
877 pathInput={pathInput}
878 setPathInput={setPathInput}
879 />
880 </>
881 ) : (
882 <EmptyEnvironmentState />
883 )}
884 </AddProjectShell>
885 );
887​
888export function AddProjectDestinationScreen(props: {
889 readonly environmentId?: string | string[];
890 readonly remoteUrl?: string | string[];
891 readonly repositoryTitle?: string | string[];
892 readonly repositoryName?: string | string[];
893}) {
894 const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
895 reportFailure: false,
896 });
897 const environment = useEnvironmentFromParam(props.environmentId);
898 const createProject = useCreateProject(environment);
899 const remoteUrl = stringParam(props.remoteUrl);
900 const repositoryTitle = stringParam(props.repositoryTitle);
901 // A lookup derives this from "owner/repo", a pasted clone URL from its own
902 // last segment. Older links without the param keep the browsed folder.
903 // Trim once here: the path input and the folder-list filter must compare the
904 // same value, or a deep link with a padded param empties the folder picker.
905 const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
906 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
907 environment,
908 repositoryName,
909 );
910 const [isSubmitting, setIsSubmitting] = useState(false);
911 const [error, setError] = useState<string | null>(null);
912​
913 const submitPath = useCallback(async () => {
914 if (!environment || !remoteUrl || isBrowseNavigating || isSubmitting) return;
915 setError(null);
916 const resolved = resolveAddProjectPath({
917 rawPath: pathInput,
918 currentProjectCwd: null,
919 platform: environment.platform,
920 });
921 if (!resolved.ok) {
922 setError(resolved.error);
923 return;
924 }
925​
926 setIsSubmitting(true);
927 const cloneResult = await cloneRepository({
928 environmentId: environment.environmentId,
929 input: {
930 remoteUrl,
931 destinationPath: resolved.path,
932 },
933 });
934 if (AsyncResult.isFailure(cloneResult)) {
935 setError(errorMessage(Cause.squash(cloneResult.cause)));
936 } else {
937 const createResult = await createProject(cloneResult.value.cwd);
938 if (createResult && AsyncResult.isFailure(createResult)) {
939 setError(errorMessage(Cause.squash(createResult.cause)));
940 }
941 }
942 setIsSubmitting(false);
943 }, [
944 cloneRepository,
945 createProject,
946 environment,
947 isBrowseNavigating,
948 isSubmitting,
949 pathInput,
950 remoteUrl,
951 ]);
952​
953 return (
954 <AddProjectShell>
955 {error ? <ErrorBanner message={error} /> : null}
956 {repositoryTitle ? (
957 <View className="rounded-[24px] bg-card px-4 py-3">
958 <Text className="text-base font-t3-bold">{repositoryTitle}</Text>
959 <Text className="mt-0.5 text-xs text-foreground-muted" numberOfLines={2}>
960 {remoteUrl}
961 </Text>
962 </View>
963 ) : null}
964 {environment ? (
965 <>
966 <ProjectPathInput
967 value={pathInput}
968 onChangeText={setPathInput}
969 onSubmit={() => void submitPath()}
970 />
971 <PrimaryActionButton
972 label="Clone project"
973 disabled={isBrowseNavigating || isSubmitting || !remoteUrl}
974 onPress={() => void submitPath()}
975 loading={isSubmitting}
976 />
977 <FolderBrowser
978 environment={environment}
979 navigateToBrowsePath={navigateToBrowsePath}
980 pathInput={pathInput}
981 setPathInput={setPathInput}
982 pinnedDirectoryName={repositoryName}
983 />
984 </>
985 ) : (
986 <EmptyEnvironmentState />
987 )}
988 </AddProjectShell>
989 );