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-text"
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(
409 options.filter((environment) => canCreateProjectInEnvironment(environment.connectionState)),
410 environmentOptionOrder,
411 );
412 }, [connectedEnvironments, savedConnectionsById, serverConfigByEnvironmentId]);
413}
414
415function useSelectedEnvironment(): {
416 readonly environmentOptions: ReadonlyArray<EnvironmentOption>;
417 readonly selectedEnvironment: EnvironmentOption | null;
418 readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void;
419} {
420 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
421 const environmentOptions = useEnvironmentOptions();
422 const selectedEnvironment =
423 environmentOptions.find(
424 (environment) =>
425 environment.environmentId === selectedEnvironmentId &&
426 canCreateProjectInEnvironment(environment.connectionState),
427 ) ??
428 environmentOptions.find((environment) =>
429 canCreateProjectInEnvironment(environment.connectionState),
430 ) ??
431 null;
432
433 return {
434 environmentOptions,
435 selectedEnvironment,
436 setSelectedEnvironmentId,
437 };
438}
439
440function EmptyEnvironmentState() {
441 const navigation = useNavigation();
442
443 return (
444 <View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
445 <Text className="text-center text-lg font-t3-bold">Environment unavailable</Text>
446 <Text className="text-center text-sm leading-normal text-foreground-muted">
447 Start or reconnect an environment before adding a project.
448 </Text>
449 <Pressable
450 onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))}
451 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
452 >
453 <Text className="text-sm font-t3-bold text-primary-foreground">Add environment</Text>
454 </Pressable>
455 </View>
456 );
457}
458
459function SourceControlRow(props: {
460 readonly source: AddProjectRemoteSource;
461 readonly selectedEnvironmentId: EnvironmentId;
462 readonly ready: boolean;
463 readonly hint: string;
464 readonly isFirst: boolean;
465}) {
466 const navigation = useNavigation();
467 const title =
468 props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`;
469 const subtitle =
470 props.source === "url"
471 ? "Clone from a remote URL"
472 : `Clone ${addProjectRemoteSourceLabel(props.source)} ${props.hint}`;
473 const icon =
474 props.source === "url" ? (
475 <SymbolView
476 name="link"
477 size={Platform.OS === "android" ? 24 : 17}
478 tintColorClassName="accent-icon"
479 type="monochrome"
480 />
481 ) : (
482 <SourceControlIcon
483 kind={props.source}
484 size={Platform.OS === "android" ? 24 : 18}
485 colorClassName="accent-icon"
486 />
487 );
488
489 if (!props.ready) {
490 return (
491 <ListRow title={title} subtitle={props.hint} icon={icon} disabled isFirst={props.isFirst} />
492 );
493 }
494
495 return (
496 <ListRow
497 title={title}
498 subtitle={subtitle}
499 icon={icon}
500 isFirst={props.isFirst}
501 onPress={() =>
502 navigation.dispatch(
503 StackActions.push("AddProjectRepository", {
504 environmentId: props.selectedEnvironmentId,
505 source: props.source,
506 }),
507 )
508 }
509 />
510 );
511}
512
513export function AddProjectSourceScreen() {
514 const navigation = useNavigation();
515 const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
516 useSelectedEnvironment();
517 const discoveryState = useEnvironmentQuery(
518 selectedEnvironment === null
519 ? null
520 : sourceControlEnvironment.discovery({
521 environmentId: selectedEnvironment.environmentId,
522 input: {},
523 }),
524 );
525 const readiness = useMemo(
526 () => buildAddProjectRemoteSourceReadiness(discoveryState.data),
527 [discoveryState.data],
528 );
529
530 return (
531 <AddProjectShell title="Add project">
532 {selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
533
534 {environmentOptions.length > 1 ? (
535 <>
536 <SectionTitle>Environments</SectionTitle>
537 <ListSection>
538 {environmentOptions.map((environment, index) => (
539 <ListRow
540 key={environment.environmentId}
541 title={environment.label}
542 subtitle={
543 canCreateProjectInEnvironment(environment.connectionState)
544 ? undefined
545 : connectionStatusText({
546 phase: environment.connectionState,
547 error: environment.connectionError,
548 traceId: environment.connectionErrorTraceId,
549 })
550 }
551 icon={
552 <EnvironmentMachineSymbol
553 kind={environment.machine}
554 size={Platform.OS === "android" ? 24 : 17}
555 tintColorClassName="accent-icon"
556 />
557 }
558 selected={environment.environmentId === selectedEnvironment?.environmentId}
559 disabled={!canCreateProjectInEnvironment(environment.connectionState)}
560 isFirst={index === 0}
561 right={
562 environment.environmentId === selectedEnvironment?.environmentId ? (
563 <SymbolView
564 name="checkmark"
565 size={Platform.OS === "android" ? 20 : 14}
566 tintColorClassName="accent-icon"
567 type="monochrome"
568 />
569 ) : null
570 }
571 onPress={() => setSelectedEnvironmentId(environment.environmentId)}
572 />
573 ))}
574 </ListSection>
575 </>
576 ) : null}
577
578 {selectedEnvironment ? (
579 <>
580 <ListSection>
581 <ListRow
582 title="Local folder"
583 subtitle="Browse a folder on disk"
584 icon={
585 <SymbolView
586 name="folder.badge.plus"
587 size={Platform.OS === "android" ? 24 : 17}
588 tintColorClassName="accent-icon"
589 type="monochrome"
590 />
591 }
592 isFirst
593 onPress={() =>
594 navigation.dispatch(
595 StackActions.push("AddProjectLocal", {
596 environmentId: selectedEnvironment.environmentId,
597 }),
598 )
599 }
600 />
601 {(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
602 (candidate) => (
603 <SourceControlRow
604 key={candidate}
605 source={candidate}
606 selectedEnvironmentId={selectedEnvironment.environmentId}
607 ready={readiness[candidate].ready}
608 hint={
609 readiness[candidate].ready
610 ? addProjectRemoteSourcePathHint(candidate)
611 : (readiness[candidate].hint ?? "")
612 }
613 isFirst={false}
614 />
615 ),
616 )}
617 </ListSection>
618 {discoveryState.isPending ? (
619 <ActivityIndicator colorClassName="accent-icon-muted" />
620 ) : null}
621 </>
622 ) : null}
623 </AddProjectShell>
624 );
625}
626
627function openNewTaskDraft(
628 navigation: { dispatch: (action: ReturnType<typeof CommonActions.reset>) => void },
629 params: { environmentId: EnvironmentId; projectId: ProjectId; title: string; cloning?: "1" },
630) {
631 navigation.dispatch(
632 CommonActions.reset({ index: 0, routes: [{ name: "NewTaskDraft", params }] }),
633 );
634}
635
636function useCreateProject(environment: EnvironmentOption | null) {
637 const navigation = useNavigation();
638 const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
639 const projects = useProjects();
640
641 return useCallback(
642 async (workspaceRoot: string) => {
643 if (!environment || !canCreateProjectInEnvironment(environment.connectionState)) return;
644
645 const existing = findExistingAddProject({
646 projects,
647 environmentId: environment.environmentId,
648 path: workspaceRoot,
649 });
650 if (existing) {
651 Alert.alert("Project already exists", existing.title);
652 navigation.dispatch(
653 CommonActions.reset({
654 index: 0,
655 routes: [
656 {
657 name: "NewTaskDraft",
658 params: {
659 environmentId: existing.environmentId,
660 projectId: existing.id,
661 title: existing.title,
662 },
663 },
664 ],
665 }),
666 );
667 return;
668 }
669
670 const projectId = ProjectId.make(uuidv4());
671 const command = buildProjectCreateCommand({
672 commandId: CommandId.make(uuidv4()),
673 projectId,
674 workspaceRoot,
675 });
676 const result = await createProject({
677 environmentId: environment.environmentId,
678 input: command,
679 });
680 if (AsyncResult.isFailure(result)) {
681 return result;
682 }
683 navigation.dispatch(
684 CommonActions.reset({
685 index: 0,
686 routes: [
687 {
688 name: "NewTaskDraft",
689 params: {
690 environmentId: environment.environmentId,
691 projectId,
692 title: inferProjectTitleFromPath(workspaceRoot),
693 },
694 },
695 ],
696 }),
697 );
698 return result;
699 },
700 [createProject, environment, projects, navigation],
701 );
702}
703
704function useEnvironmentFromParam(
705 environmentIdParam: string | string[] | undefined,
706): EnvironmentOption | null {
707 const environmentOptions = useEnvironmentOptions();
708 const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
709 return resolveAddProjectEnvironment(environmentOptions, environmentId);
710}
711
712export function AddProjectRepositoryScreen(props: {
713 readonly environmentId?: string | string[];
714 readonly source?: string | string[];
715}) {
716 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
717 reportFailure: false,
718 });
719 const navigation = useNavigation();
720 const environment = useEnvironmentFromParam(props.environmentId);
721 const source = sourceFromParam(props.source);
722 const [repositoryInput, setRepositoryInput] = useState("");
723 const [isSubmitting, setIsSubmitting] = useState(false);
724 const [error, setError] = useState<string | null>(null);
725
726 const lookupRepository = useCallback(async () => {
727 if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
728 setError(null);
729 setIsSubmitting(true);
730 const provider = addProjectRemoteSourceProvider(source);
731 if (!provider) {
732 const remoteUrl = normalizePastedCloneUrl(repositoryInput);
733 navigation.dispatch(
734 StackActions.push("AddProjectDestination", {
735 environmentId: environment.environmentId,
736 source,
737 remoteUrl,
738 repositoryTitle: remoteUrl,
739 repositoryName: getCloneDirectoryName(remoteUrl),
740 }),
741 );
742 setIsSubmitting(false);
743 return;
744 }
745
746 const result = await lookupRepositoryQuery({
747 environmentId: environment.environmentId,
748 input: {
749 provider,
750 repository: repositoryInput.trim(),
751 },
752 });
753 if (AsyncResult.isFailure(result)) {
754 setError(errorMessage(Cause.squash(result.cause)));
755 } else {
756 const repository = result.value;
757 navigation.dispatch(
758 StackActions.push("AddProjectDestination", {
759 environmentId: environment.environmentId,
760 source,
761 remoteUrl: getDefaultCloneUrl(repository),
762 repositoryTitle: repository.nameWithOwner,
763 repositoryName: getCloneDirectoryName(repository.nameWithOwner),
764 }),
765 );
766 }
767 setIsSubmitting(false);
768 }, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
769
770 return (
771 <AddProjectShell title={source === "url" ? "Git URL" : addProjectRemoteSourceLabel(source)}>
772 {error ? <ErrorBanner message={error} /> : null}
773 {environment ? (
774 <>
775 <TextInput
776 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
777 value={repositoryInput}
778 onChangeText={setRepositoryInput}
779 autoCapitalize="none"
780 autoCorrect={false}
781 placeholder={
782 source === "url"
783 ? "https://github.com/org/repo.git"
784 : addProjectRemoteSourcePathHint(source)
785 }
786 returnKeyType="next"
787 onSubmitEditing={() => void lookupRepository()}
788 />
789 <PrimaryActionButton
790 label={source === "url" ? "Continue" : "Lookup repository"}
791 disabled={isSubmitting || repositoryInput.trim().length === 0}
792 onPress={() => void lookupRepository()}
793 loading={isSubmitting}
794 />
795 </>
796 ) : (
797 <EmptyEnvironmentState />
798 )}
799 </AddProjectShell>
800 );
801}
802
803function FolderBrowser(props: {
804 readonly environment: EnvironmentOption;
805 readonly pathInput: string;
806 readonly setPathInput: (path: string) => void;
807 readonly navigateToBrowsePath: (input: {
808 readonly browseDirectoryPath: string;
809 readonly selectedDirectoryName?: string;
810 }) => Promise<boolean>;
811 readonly pinnedDirectoryName?: string;
812}) {
813 const browsePath = useMemo(
814 () => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
815 [props.environment.platform, props.pathInput],
816 );
817 const browseInput = useMemo(
818 () => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
819 [browsePath.directoryPath],
820 );
821 const browseState = useEnvironmentQuery(
822 browseInput === null
823 ? null
824 : filesystemEnvironment.browse({
825 environmentId: props.environment.environmentId,
826 input: browseInput,
827 }),
828 );
829 // A pinned repository folder does not exist yet, so filtering the listing by
830 // it would empty the folder picker. Anything the user typed still filters.
831 const pinnedDirectoryName = props.pinnedDirectoryName ?? "";
832 const pinnedDirectoryMatches = isWindowsPlatform(props.environment.platform)
833 ? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
834 : browsePath.filterQuery === pinnedDirectoryName;
835 const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
836 const { visibleEntries: visibleBrowseEntries } = useMemo(
837 () => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browseFilterQuery),
838 [browseFilterQuery, browseState.data?.entries],
839 );
840
841 return (
842 <>
843 <SectionTitle>Browse folders</SectionTitle>
844 {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
845 <ListSection>
846 {browseState.isPending && browseState.data === null ? (
847 <View className="items-center py-5">
848 <ActivityIndicator colorClassName="accent-icon-muted" />
849 </View>
850 ) : null}
851 {browsePath.canBrowseUp ? (
852 <ListRow
853 title=".."
854 icon={
855 <SymbolView
856 name="arrow.turn.left.up"
857 size={Platform.OS === "android" ? 24 : 17}
858 tintColorClassName="accent-icon-muted"
859 type="monochrome"
860 />
861 }
862 isFirst
863 right={null}
864 onPress={() => {
865 if (browsePath.parentPath) {
866 void props.navigateToBrowsePath({
867 browseDirectoryPath: browsePath.parentPath,
868 });
869 }
870 }}
871 />
872 ) : null}
873 {visibleBrowseEntries.map((entry, index) => (
874 <ListRow
875 key={entry.fullPath}
876 title={entry.name}
877 icon={
878 <SymbolView
879 name="folder"
880 size={Platform.OS === "android" ? 24 : 17}
881 tintColorClassName="accent-icon-muted"
882 type="monochrome"
883 />
884 }
885 isFirst={index === 0 && !browsePath.canBrowseUp}
886 right={null}
887 onPress={() => {
888 void props.navigateToBrowsePath({
889 browseDirectoryPath: browsePath.directoryPath,
890 selectedDirectoryName: entry.name,
891 });
892 }}
893 />
894 ))}
895 </ListSection>
896 </>
897 );
898}
899
900export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
901 const environment = useEnvironmentFromParam(props.environmentId);
902 const createProject = useCreateProject(environment);
903 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
904 useBrowsePathInput(environment);
905 const [isSubmitting, setIsSubmitting] = useState(false);
906 const [error, setError] = useState<string | null>(null);
907
908 const submitPath = useCallback(async () => {
909 if (!environment || isBrowseNavigating || isSubmitting) return;
910 setError(null);
911 const resolved = resolveAddProjectPath({
912 rawPath: pathInput,
913 currentProjectCwd: null,
914 platform: environment.platform,
915 });
916 if (!resolved.ok) {
917 setError(resolved.error);
918 return;
919 }
920
921 setIsSubmitting(true);
922 const result = await createProject(resolved.path);
923 if (result && AsyncResult.isFailure(result)) {
924 setError(errorMessage(Cause.squash(result.cause)));
925 }
926 setIsSubmitting(false);
927 }, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
928
929 return (
930 <AddProjectShell title="Local folder">
931 {error ? <ErrorBanner message={error} /> : null}
932 {environment ? (
933 <>
934 <ProjectPathInput
935 value={pathInput}
936 onChangeText={setPathInput}
937 onSubmit={() => void submitPath()}
938 />
939 <PrimaryActionButton
940 label="Add project"
941 disabled={isBrowseNavigating || isSubmitting}
942 onPress={() => void submitPath()}
943 loading={isSubmitting}
944 />
945 <FolderBrowser
946 environment={environment}
947 navigateToBrowsePath={navigateToBrowsePath}
948 pathInput={pathInput}
949 setPathInput={setPathInput}
950 />
951 </>
952 ) : (
953 <EmptyEnvironmentState />
954 )}
955 </AddProjectShell>
956 );
957}
958
959export function AddProjectDestinationScreen(props: {
960 readonly environmentId?: string | string[];
961 readonly remoteUrl?: string | string[];
962 readonly repositoryTitle?: string | string[];
963 readonly repositoryName?: string | string[];
964}) {
965 const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
966 reportFailure: false,
967 });
968 const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, {
969 reportFailure: false,
970 });
971 const navigation = useNavigation();
972 const environment = useEnvironmentFromParam(props.environmentId);
973 const createProject = useCreateProject(environment);
974 const remoteUrl = stringParam(props.remoteUrl);
975 const repositoryTitle = stringParam(props.repositoryTitle);
976 // A lookup derives this from "owner/repo", a pasted clone URL from its own
977 // last segment. Older links without the param keep the browsed folder.
978 // Trim once here: the path input and the folder-list filter must compare the
979 // same value, or a deep link with a padded param empties the folder picker.
980 const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
981 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
982 environment,
983 repositoryName,
984 );
985 const [isSubmitting, setIsSubmitting] = useState(false);
986 const [error, setError] = useState<string | null>(null);
987
988 const submitPath = useCallback(async () => {
989 if (!environment || !remoteUrl || isBrowseNavigating || isSubmitting) return;
990 setError(null);
991 const resolved = resolveAddProjectPath({
992 rawPath: pathInput,
993 currentProjectCwd: null,
994 platform: environment.platform,
995 });
996 if (!resolved.ok) {
997 setError(resolved.error);
998 return;
999 }
1000
1001 setIsSubmitting(true);
1002 if (environment.supportsCloneTracking) {
1003 // The server creates the project and clones in the background; the
1004 // draft screen shows progress and holds Start until the files land.
1005 const projectId = ProjectId.make(uuidv4());
1006 const title = inferProjectTitleFromPath(resolved.path);
1007 const startResult = await startProjectClone({
1008 environmentId: environment.environmentId,
1009 input: {
1010 projectId,
1011 title,
1012 createdAt: new Date().toISOString(),
1013 remoteUrl,
1014 destinationPath: resolved.path,
1015 },
1016 });
1017 if (AsyncResult.isFailure(startResult)) {
1018 setError(errorMessage(Cause.squash(startResult.cause)));
1019 } else {
1020 // The draft screen resolves its project from the client store, so it
1021 // must not open before the create event has arrived (it would fall
1022 // back to the project picker and lose the clone controls). Stay in
1023 // the submitting state until then; the clone keeps running either way.
1024 const project = await waitForProject(
1025 { environmentId: environment.environmentId, projectId },
1026 15_000,
1027 );
1028 if (project === null) {
1029 setError(
1030 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
1031 );
1032 } else {
1033 openNewTaskDraft(navigation, {
1034 environmentId: environment.environmentId,
1035 projectId,
1036 title,
1037 cloning: "1",
1038 });
1039 }
1040 }
1041 setIsSubmitting(false);
1042 return;
1043 }
1044 const cloneResult = await cloneRepository({
1045 environmentId: environment.environmentId,
1046 input: {
1047 remoteUrl,
1048 destinationPath: resolved.path,
1049 },
1050 });
1051 if (AsyncResult.isFailure(cloneResult)) {
1052 setError(errorMessage(Cause.squash(cloneResult.cause)));
1053 } else {
1054 const createResult = await createProject(cloneResult.value.cwd);
1055 if (createResult && AsyncResult.isFailure(createResult)) {
1056 setError(errorMessage(Cause.squash(createResult.cause)));
1057 }
1058 }
1059 setIsSubmitting(false);
1060 }, [
1061 cloneRepository,
1062 createProject,
1063 environment,
1064 isBrowseNavigating,
1065 isSubmitting,
1066 navigation,
1067 pathInput,
1068 remoteUrl,
1069 startProjectClone,
1070 ]);
1071
1072 return (
1073 <AddProjectShell title="Clone destination">
1074 {error ? <ErrorBanner message={error} /> : null}
1075 {repositoryTitle ? (
1076 <View className="rounded-[24px] bg-card px-4 py-3">
1077 <Text className="text-base font-t3-bold">{repositoryTitle}</Text>
1078 <Text className="mt-0.5 text-xs text-foreground-muted" numberOfLines={2}>
1079 {remoteUrl}
1080 </Text>
1081 </View>
1082 ) : null}
1083 {environment ? (
1084 <>
1085 <ProjectPathInput
1086 value={pathInput}
1087 onChangeText={setPathInput}
1088 onSubmit={() => void submitPath()}
1089 />
1090 <PrimaryActionButton
1091 label="Clone project"
1092 disabled={isBrowseNavigating || isSubmitting || !remoteUrl}
1093 onPress={() => void submitPath()}
1094 loading={isSubmitting}
1095 />
1096 <FolderBrowser
1097 environment={environment}
1098 navigateToBrowsePath={navigateToBrowsePath}
1099 pathInput={pathInput}
1100 setPathInput={setPathInput}
1101 pinnedDirectoryName={repositoryName}
1102 />
1103 </>
1104 ) : (
1105 <EmptyEnvironmentState />
1106 )}
1107 </AddProjectShell>
1108 );
1109}