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