Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AddProjectScreen.tsx

1,369 lines46.7 KB

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/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;
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 "";
106​
107function errorMessage(error: unknown): string {
108 return error instanceof Error && error.message.trim().length > 0
109 ? error.message
110 : "An error occurred.";
112​
113function stringParam(value: string | string[] | undefined): string | null {
114 if (Array.isArray(value)) return value[0] ?? null;
115 return value ?? null;
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";
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 );
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 );
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 );
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 );
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 );
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 );
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 };
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]);
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 };
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 );
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 );
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 );
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 );
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 });
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 );
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);
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 );
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 );
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;
1023 const { projectId, workspaceRoot, commitError } = result.value;
1024 if (commitError !== undefined) {
1025 Alert.alert("Created without a first commit", commitError);
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 );
1043 });
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;
1059 openNewTaskDraft(navigation, {
1060 environmentId: environment.environmentId,
1061 projectId,
1062 title: trimmedName,
1063 });
1064 } finally {
1065 submittingRef.current = false;
1066 setIsSubmitting(false);
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
1103 icon={
1104 <SourceControlIcon
1105 kind="github"
1106 size={Platform.OS === "android" ? 24 : 18}
1107 colorClassName="accent-icon"
1108 />
1110 isFirst
1111 right={
1112 <ThemedSwitch
1113 accessibilityLabel="Create private repository on GitHub"
1114 value={publishesToGitHub}
1115 onValueChange={setPublishesToGitHub}
1116 />
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 />
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"))
1148 />
1149 </ListSection>
1150 </>
1151 ) : environmentOptions.length > 0 ? (
1152 machineRows
1153 ) : (
1154 <EmptyEnvironmentState />
1155 )}
1156 </AddProjectShell>
1157 );
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;
1180​
1181 setIsSubmitting(true);
1182 const result = await createProject(resolved.path);
1183 if (result && AsyncResult.isFailure(result)) {
1184 setError(errorMessage(Cause.squash(result.cause)));
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 );
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;
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 });
1301 setIsSubmitting(false);
1302 return;
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)));
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-grouped-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 );