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