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