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