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 createdAt: new Date().toISOString(),
676 });
677 const result = await createProject({
678 environmentId: environment.environmentId,
679 input: command,
680 });
681 if (AsyncResult.isFailure(result)) {
682 return result;
683 }
684 navigation.dispatch(
685 CommonActions.reset({
686 index: 0,
687 routes: [
688 {
689 name: "NewTaskDraft",
690 params: {
691 environmentId: environment.environmentId,
692 projectId,
693 title: inferProjectTitleFromPath(workspaceRoot),
694 },
695 },
696 ],
697 }),
698 );
699 return result;
700 },
701 [createProject, environment, projects, navigation],
702 );
703}
704
705function useEnvironmentFromParam(
706 environmentIdParam: string | string[] | undefined,
707): EnvironmentOption | null {
708 const environmentOptions = useEnvironmentOptions();
709 const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
710 return resolveAddProjectEnvironment(environmentOptions, environmentId);
711}
712
713export function AddProjectRepositoryScreen(props: {
714 readonly environmentId?: string | string[];
715 readonly source?: string | string[];
716}) {
717 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
718 reportFailure: false,
719 });
720 const navigation = useNavigation();
721 const environment = useEnvironmentFromParam(props.environmentId);
722 const source = sourceFromParam(props.source);
723 const [repositoryInput, setRepositoryInput] = useState("");
724 const [isSubmitting, setIsSubmitting] = useState(false);
725 const [error, setError] = useState<string | null>(null);
726
727 const lookupRepository = useCallback(async () => {
728 if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
729 setError(null);
730 setIsSubmitting(true);
731 const provider = addProjectRemoteSourceProvider(source);
732 if (!provider) {
733 const remoteUrl = normalizePastedCloneUrl(repositoryInput);
734 navigation.dispatch(
735 StackActions.push("AddProjectDestination", {
736 environmentId: environment.environmentId,
737 source,
738 remoteUrl,
739 repositoryTitle: remoteUrl,
740 repositoryName: getCloneDirectoryName(remoteUrl),
741 }),
742 );
743 setIsSubmitting(false);
744 return;
745 }
746
747 const result = await lookupRepositoryQuery({
748 environmentId: environment.environmentId,
749 input: {
750 provider,
751 repository: repositoryInput.trim(),
752 },
753 });
754 if (AsyncResult.isFailure(result)) {
755 setError(errorMessage(Cause.squash(result.cause)));
756 } else {
757 const repository = result.value;
758 navigation.dispatch(
759 StackActions.push("AddProjectDestination", {
760 environmentId: environment.environmentId,
761 source,
762 remoteUrl: getDefaultCloneUrl(repository),
763 repositoryTitle: repository.nameWithOwner,
764 repositoryName: getCloneDirectoryName(repository.nameWithOwner),
765 }),
766 );
767 }
768 setIsSubmitting(false);
769 }, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
770
771 return (
772 <AddProjectShell title={source === "url" ? "Git URL" : addProjectRemoteSourceLabel(source)}>
773 {error ? <ErrorBanner message={error} /> : null}
774 {environment ? (
775 <>
776 <TextInput
777 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
778 value={repositoryInput}
779 onChangeText={setRepositoryInput}
780 autoCapitalize="none"
781 autoCorrect={false}
782 placeholder={
783 source === "url"
784 ? "https://github.com/org/repo.git"
785 : addProjectRemoteSourcePathHint(source)
786 }
787 returnKeyType="next"
788 onSubmitEditing={() => void lookupRepository()}
789 />
790 <PrimaryActionButton
791 label={source === "url" ? "Continue" : "Lookup repository"}
792 disabled={isSubmitting || repositoryInput.trim().length === 0}
793 onPress={() => void lookupRepository()}
794 loading={isSubmitting}
795 />
796 </>
797 ) : (
798 <EmptyEnvironmentState />
799 )}
800 </AddProjectShell>
801 );
802}
803
804function FolderBrowser(props: {
805 readonly environment: EnvironmentOption;
806 readonly pathInput: string;
807 readonly setPathInput: (path: string) => void;
808 readonly navigateToBrowsePath: (input: {
809 readonly browseDirectoryPath: string;
810 readonly selectedDirectoryName?: string;
811 }) => Promise<boolean>;
812 readonly pinnedDirectoryName?: string;
813}) {
814 const browsePath = useMemo(
815 () => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
816 [props.environment.platform, props.pathInput],
817 );
818 const browseInput = useMemo(
819 () => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
820 [browsePath.directoryPath],
821 );
822 const browseState = useEnvironmentQuery(
823 browseInput === null
824 ? null
825 : filesystemEnvironment.browse({
826 environmentId: props.environment.environmentId,
827 input: browseInput,
828 }),
829 );
830 // A pinned repository folder does not exist yet, so filtering the listing by
831 // it would empty the folder picker. Anything the user typed still filters.
832 const pinnedDirectoryName = props.pinnedDirectoryName ?? "";
833 const pinnedDirectoryMatches = isWindowsPlatform(props.environment.platform)
834 ? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
835 : browsePath.filterQuery === pinnedDirectoryName;
836 const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
837 const { visibleEntries: visibleBrowseEntries } = useMemo(
838 () => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browseFilterQuery),
839 [browseFilterQuery, browseState.data?.entries],
840 );
841
842 return (
843 <>
844 <SectionTitle>Browse folders</SectionTitle>
845 {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
846 <ListSection>
847 {browseState.isPending && browseState.data === null ? (
848 <View className="items-center py-5">
849 <ActivityIndicator colorClassName="accent-icon-muted" />
850 </View>
851 ) : null}
852 {browsePath.canBrowseUp ? (
853 <ListRow
854 title=".."
855 icon={
856 <SymbolView
857 name="arrow.turn.left.up"
858 size={Platform.OS === "android" ? 24 : 17}
859 tintColorClassName="accent-icon-muted"
860 type="monochrome"
861 />
862 }
863 isFirst
864 right={null}
865 onPress={() => {
866 if (browsePath.parentPath) {
867 void props.navigateToBrowsePath({
868 browseDirectoryPath: browsePath.parentPath,
869 });
870 }
871 }}
872 />
873 ) : null}
874 {visibleBrowseEntries.map((entry, index) => (
875 <ListRow
876 key={entry.fullPath}
877 title={entry.name}
878 icon={
879 <SymbolView
880 name="folder"
881 size={Platform.OS === "android" ? 24 : 17}
882 tintColorClassName="accent-icon-muted"
883 type="monochrome"
884 />
885 }
886 isFirst={index === 0 && !browsePath.canBrowseUp}
887 right={null}
888 onPress={() => {
889 void props.navigateToBrowsePath({
890 browseDirectoryPath: browsePath.directoryPath,
891 selectedDirectoryName: entry.name,
892 });
893 }}
894 />
895 ))}
896 </ListSection>
897 </>
898 );
899}
900
901export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
902 const environment = useEnvironmentFromParam(props.environmentId);
903 const createProject = useCreateProject(environment);
904 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
905 useBrowsePathInput(environment);
906 const [isSubmitting, setIsSubmitting] = useState(false);
907 const [error, setError] = useState<string | null>(null);
908
909 const submitPath = useCallback(async () => {
910 if (!environment || isBrowseNavigating || isSubmitting) return;
911 setError(null);
912 const resolved = resolveAddProjectPath({
913 rawPath: pathInput,
914 currentProjectCwd: null,
915 platform: environment.platform,
916 });
917 if (!resolved.ok) {
918 setError(resolved.error);
919 return;
920 }
921
922 setIsSubmitting(true);
923 const result = await createProject(resolved.path);
924 if (result && AsyncResult.isFailure(result)) {
925 setError(errorMessage(Cause.squash(result.cause)));
926 }
927 setIsSubmitting(false);
928 }, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
929
930 return (
931 <AddProjectShell title="Local folder">
932 {error ? <ErrorBanner message={error} /> : null}
933 {environment ? (
934 <>
935 <ProjectPathInput
936 value={pathInput}
937 onChangeText={setPathInput}
938 onSubmit={() => void submitPath()}
939 />
940 <PrimaryActionButton
941 label="Add project"
942 disabled={isBrowseNavigating || isSubmitting}
943 onPress={() => void submitPath()}
944 loading={isSubmitting}
945 />
946 <FolderBrowser
947 environment={environment}
948 navigateToBrowsePath={navigateToBrowsePath}
949 pathInput={pathInput}
950 setPathInput={setPathInput}
951 />
952 </>
953 ) : (
954 <EmptyEnvironmentState />
955 )}
956 </AddProjectShell>
957 );
958}
959
960export function AddProjectDestinationScreen(props: {
961 readonly environmentId?: string | string[];
962 readonly remoteUrl?: string | string[];
963 readonly repositoryTitle?: string | string[];
964 readonly repositoryName?: string | string[];
965}) {
966 const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
967 reportFailure: false,
968 });
969 const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, {
970 reportFailure: false,
971 });
972 const navigation = useNavigation();
973 const environment = useEnvironmentFromParam(props.environmentId);
974 const createProject = useCreateProject(environment);
975 const remoteUrl = stringParam(props.remoteUrl);
976 const repositoryTitle = stringParam(props.repositoryTitle);
977 // A lookup derives this from "owner/repo", a pasted clone URL from its own
978 // last segment. Older links without the param keep the browsed folder.
979 // Trim once here: the path input and the folder-list filter must compare the
980 // same value, or a deep link with a padded param empties the folder picker.
981 const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
982 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
983 environment,
984 repositoryName,
985 );
986 const [isSubmitting, setIsSubmitting] = useState(false);
987 const [error, setError] = useState<string | null>(null);
988
989 const submitPath = useCallback(async () => {
990 if (!environment || !remoteUrl || isBrowseNavigating || isSubmitting) return;
991 setError(null);
992 const resolved = resolveAddProjectPath({
993 rawPath: pathInput,
994 currentProjectCwd: null,
995 platform: environment.platform,
996 });
997 if (!resolved.ok) {
998 setError(resolved.error);
999 return;
1000 }
1001
1002 setIsSubmitting(true);
1003 if (environment.supportsCloneTracking) {
1004 // The server creates the project and clones in the background; the
1005 // draft screen shows progress and holds Start until the files land.
1006 const projectId = ProjectId.make(uuidv4());
1007 const title = inferProjectTitleFromPath(resolved.path);
1008 const startResult = await startProjectClone({
1009 environmentId: environment.environmentId,
1010 input: {
1011 projectId,
1012 title,
1013 createdAt: new Date().toISOString(),
1014 remoteUrl,
1015 destinationPath: resolved.path,
1016 },
1017 });
1018 if (AsyncResult.isFailure(startResult)) {
1019 setError(errorMessage(Cause.squash(startResult.cause)));
1020 } else {
1021 // The draft screen resolves its project from the client store, so it
1022 // must not open before the create event has arrived (it would fall
1023 // back to the project picker and lose the clone controls). Stay in
1024 // the submitting state until then; the clone keeps running either way.
1025 const project = await waitForProject(
1026 { environmentId: environment.environmentId, projectId },
1027 15_000,
1028 );
1029 if (project === null) {
1030 setError(
1031 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
1032 );
1033 } else {
1034 openNewTaskDraft(navigation, {
1035 environmentId: environment.environmentId,
1036 projectId,
1037 title,
1038 cloning: "1",
1039 });
1040 }
1041 }
1042 setIsSubmitting(false);
1043 return;
1044 }
1045 const cloneResult = await cloneRepository({
1046 environmentId: environment.environmentId,
1047 input: {
1048 remoteUrl,
1049 destinationPath: resolved.path,
1050 },
1051 });
1052 if (AsyncResult.isFailure(cloneResult)) {
1053 setError(errorMessage(Cause.squash(cloneResult.cause)));
1054 } else {
1055 const createResult = await createProject(cloneResult.value.cwd);
1056 if (createResult && AsyncResult.isFailure(createResult)) {
1057 setError(errorMessage(Cause.squash(createResult.cause)));
1058 }
1059 }
1060 setIsSubmitting(false);
1061 }, [
1062 cloneRepository,
1063 createProject,
1064 environment,
1065 isBrowseNavigating,
1066 isSubmitting,
1067 navigation,
1068 pathInput,
1069 remoteUrl,
1070 startProjectClone,
1071 ]);
1072
1073 return (
1074 <AddProjectShell title="Clone destination">
1075 {error ? <ErrorBanner message={error} /> : null}
1076 {repositoryTitle ? (
1077 <View className="rounded-[24px] bg-card px-4 py-3">
1078 <Text className="text-base font-t3-bold">{repositoryTitle}</Text>
1079 <Text className="mt-0.5 text-xs text-foreground-muted" numberOfLines={2}>
1080 {remoteUrl}
1081 </Text>
1082 </View>
1083 ) : null}
1084 {environment ? (
1085 <>
1086 <ProjectPathInput
1087 value={pathInput}
1088 onChangeText={setPathInput}
1089 onSubmit={() => void submitPath()}
1090 />
1091 <PrimaryActionButton
1092 label="Clone project"
1093 disabled={isBrowseNavigating || isSubmitting || !remoteUrl}
1094 onPress={() => void submitPath()}
1095 loading={isSubmitting}
1096 />
1097 <FolderBrowser
1098 environment={environment}
1099 navigateToBrowsePath={navigateToBrowsePath}
1100 pathInput={pathInput}
1101 setPathInput={setPathInput}
1102 pinnedDirectoryName={repositoryName}
1103 />
1104 </>
1105 ) : (
1106 <EmptyEnvironmentState />
1107 )}
1108 </AddProjectShell>
1109 );
1110}