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

AddProjectScreen.tsx

1,078 lines36.2 KB

1import {
2 addProjectRemoteSourcePathHint,
3 addProjectRemoteSourceProvider,
4 addProjectRemoteTargetLabel,
5 addProjectRemoteTargetReadiness,
6 buildAddProjectRemoteSourceReadiness,
7 buildAddProjectRemoteTargets,
8 buildProjectCreateCommand,
9 canCreateProjectInEnvironment,
10 findExistingAddProject,
11 getAddProjectInitialQuery,
12 getCloneDestinationBrowsePath,
13 getCloneDestinationPath,
14 getCloneDirectoryName,
15 getDefaultCloneUrl,
16 normalizePastedCloneUrl,
17 resolveAddProjectPath,
18 sortAddProjectProviderSources,
19 type AddProjectRemoteSource,
20 type AddProjectRemoteTarget,
21} from "@t3tools/client-runtime/operations/projects";
22import {
23 connectionStatusText,
24 type EnvironmentConnectionPhase,
25} from "@t3tools/client-runtime/connection";
26import {
27 canPreloadBrowsePath,
28 createBrowseNavigationCoordinator,
29 filterFilesystemBrowseEntries,
30 getFilesystemBrowsePath,
31} from "@t3tools/client-runtime/state/filesystem";
32import {
33 appendBrowsePathSegment,
34 inferProjectTitleFromPath,
35 isWindowsPlatform,
36} from "@t3tools/client-runtime/state/projects";
37import {
38 CommandId,
39 type EnvironmentId,
40 type EnvironmentMachineKind,
41 ProjectId,
42 resolveEnvironmentMachineKind,
43} from "@t3tools/contracts";
44import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
45import { SymbolView } from "../../components/AppSymbol";
46import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
47import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
48import { useSafeAreaInsets } from "react-native-safe-area-context";
49import * as Arr from "effect/Array";
50import * as Cause from "effect/Cause";
51import * as Order from "effect/Order";
52import { AsyncResult } from "effect/unstable/reactivity";
53import { cn } from "../../lib/cn";
54​
55import { useProjects, useServerConfigs, waitForProject } from "../../state/entities";
56import { filesystemEnvironment } from "../../state/filesystem";
57import { projectEnvironment } from "../../state/projects";
58import { useEnvironmentQuery } from "../../state/query";
59import { sourceControlEnvironment } from "../../state/sourceControl";
60import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
61import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
62import { ErrorBanner } from "../../components/ErrorBanner";
63import { SourceControlIcon } from "../../components/SourceControlIcon";
64import { uuidv4 } from "../../lib/uuid";
65import { useAtomCommand } from "../../state/use-atom-command";
66import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
67import {
68 useRemoteConnectionStatus,
69 useRemoteEnvironmentRuntime,
70 useSavedRemoteConnections,
71} from "../../state/use-remote-environment-registry";
72import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
73​
74interface EnvironmentOption {
75 readonly environmentId: EnvironmentId;
76 readonly label: string;
77 readonly platform: string;
78 readonly machine: EnvironmentMachineKind;
79 readonly baseDirectory: string | null;
80 readonly connectionState: EnvironmentConnectionPhase;
81 readonly connectionError: string | null;
82 readonly connectionErrorTraceId: string | null;
83 /** Server runs clones in the background and streams progress; older servers block. */
84 readonly supportsCloneTracking: boolean;
86​
87const environmentOptionOrder = Order.mapInput(
88 Order.Struct({
89 label: Order.String,
90 }),
91 (environment: EnvironmentOption) => ({ label: environment.label }),
92);
93​
94function platformFromOs(os: string | null | undefined): string {
95 if (os === "windows") return "Win32";
96 if (os === "darwin") return "MacIntel";
97 if (os === "linux") return "Linux";
98 return "";
100​
101function errorMessage(error: unknown): string {
102 return error instanceof Error && error.message.trim().length > 0
103 ? error.message
104 : "An error occurred.";
106​
107function stringParam(value: string | string[] | undefined): string | null {
108 if (Array.isArray(value)) return value[0] ?? null;
109 return value ?? null;
111​
112function sourceFromParam(value: string | string[] | undefined): AddProjectRemoteSource {
113 const source = stringParam(value);
114 if (
115 source === "url" ||
116 source === "github" ||
117 source === "github-enterprise" ||
118 source === "gitlab" ||
119 source === "forgejo" ||
120 source === "bitbucket" ||
121 source === "azure-devops"
122 ) {
123 return source;
124 }
125 return "url";
127​
128function SectionTitle(props: { readonly children: string }) {
129 return (
130 <Text className="px-1 text-2xs font-t3-bold tracking-[0.7px] uppercase text-foreground-muted">
131 {props.children}
132 </Text>
133 );
135​
136function AddProjectShell(props: { readonly children: ReactNode }) {
137 const insets = useSafeAreaInsets();
138​
139 return (
140 // collapsable={false} is load-bearing: if this wrapper is flattened, the
141 // ScrollView lands directly under RNSSafeAreaView and RNS's formSheet
142 // scroll-view frame correction mistakes this full-height wrapper for a
143 // "header" sibling, coercing the ScrollView to zero height (blank sheet
144 // as soon as the sheet re-lays-out, e.g. when the keyboard opens).
145 <View collapsable={false} className="flex-1 bg-sheet">
146 <ScrollView
147 keyboardShouldPersistTaps="handled"
148 contentInsetAdjustmentBehavior="automatic"
149 contentContainerStyle={{
150 paddingHorizontal: 20,
151 paddingTop: 16,
152 paddingBottom: Math.max(insets.bottom, 18) + 18,
153 gap: 10,
154 }}
155 >
156 {props.children}
157 </ScrollView>
158 </View>
159 );
161​
162function ListSection(props: { readonly children: ReactNode }) {
163 return <View className="overflow-hidden rounded-[24px] bg-card">{props.children}</View>;
165​
166function ListRow(props: {
167 readonly title: string;
168 readonly subtitle?: string | null;
169 readonly icon: ReactNode;
170 readonly disabled?: boolean;
171 readonly selected?: boolean;
172 readonly isFirst?: boolean;
173 readonly right?: ReactNode;
174 readonly onPress?: () => void;
175}) {
176 return (
177 <Pressable
178 disabled={props.disabled}
179 onPress={props.onPress}
180 className={cn(
181 "bg-card px-3.5 py-2.5 active:opacity-70",
182 !props.isFirst && "border-t border-border-subtle",
183 props.disabled && "opacity-[0.45]",
184 )}
185 >
186 <View className="flex-row items-center gap-3">
187 <View
188 className={
189 props.selected
190 ? "h-7 w-7 items-center justify-center rounded-full bg-primary"
191 : "h-7 w-7 items-center justify-center"
192 }
193 >
194 {props.icon}
195 </View>
196 <View className="flex-1 gap-0.5">
197 <Text className="text-base leading-snug font-t3-bold">{props.title}</Text>
198 {props.subtitle ? (
199 <Text className="text-sm leading-snug text-foreground-muted" numberOfLines={2}>
200 {props.subtitle}
201 </Text>
202 ) : null}
203 </View>
204 {"right" in props ? (
205 props.right
206 ) : !props.disabled ? (
207 <SymbolView
208 name="chevron.right"
209 size={13}
210 tintColorClassName={"accent-chevron"}
211 type="monochrome"
212 />
213 ) : null}
214 </View>
215 </Pressable>
216 );
218​
219function PrimaryActionButton(props: {
220 readonly label: string;
221 readonly disabled?: boolean;
222 readonly loading?: boolean;
223 readonly onPress: () => void;
224}) {
225 return (
226 <Pressable
227 disabled={props.disabled}
228 onPress={props.onPress}
229 className="h-12 items-center justify-center rounded-full bg-primary active:opacity-70 disabled:opacity-45"
230 >
231 {props.loading ? (
232 <ActivityIndicator colorClassName={String("accent-primary-foreground")} />
233 ) : (
234 <Text className="text-base font-t3-bold text-primary-foreground">{props.label}</Text>
235 )}
236 </Pressable>
237 );
239​
240function ProjectPathInput(props: {
241 readonly value: string;
242 readonly onChangeText: (value: string) => void;
243 readonly onSubmit: () => void;
244}) {
245 return (
246 <TextInput
247 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
248 value={props.value}
249 onChangeText={props.onChangeText}
250 autoCapitalize="none"
251 autoCorrect={false}
252 placeholder="~/projects/my-app"
253 returnKeyType="done"
254 onSubmitEditing={props.onSubmit}
255 />
256 );
258​
259// `pinnedDirectoryName` is the repository folder the clone destination keeps
260// appended to whatever folder the user browses to. The plain add-project flow
261// passes nothing, so it keeps proposing the browsed folder itself.
262function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirectoryName = "") {
263 const environmentId = environment?.environmentId ?? null;
264 const environmentBaseDirectory = environment?.baseDirectory ?? null;
265 const clonePathCaseSensitive = !isWindowsPlatform(environment?.platform ?? "");
266 const [pathInput, commitPathInput] = useState(() =>
267 getCloneDestinationPath(
268 getAddProjectInitialQuery(environmentBaseDirectory),
269 pinnedDirectoryName,
270 ),
271 );
272 const previousEnvironmentIdRef = useRef(environmentId);
273 const environmentRuntime = useRemoteEnvironmentRuntime(environmentId);
274 const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
275 reportFailure: false,
276 reportDefect: false,
277 });
278 const [browseNavigation] = useState(createBrowseNavigationCoordinator);
279 const [isBrowseNavigating, setIsBrowseNavigating] = useState(false);
280 const setPathInput = useCallback(
281 (path: string) => {
282 browseNavigation.invalidate();
283 setIsBrowseNavigating(false);
284 commitPathInput(path);
285 },
286 [browseNavigation],
287 );
288 const navigateToBrowsePath = useCallback(
289 async (input: {
290 readonly browseDirectoryPath: string;
291 readonly selectedDirectoryName?: string;
292 }) => {
293 const selectedDirectoryPath = input.selectedDirectoryName
294 ? appendBrowsePathSegment(input.browseDirectoryPath, input.selectedDirectoryName)
295 : input.browseDirectoryPath;
296 const nextPathInput =
297 pinnedDirectoryName && input.selectedDirectoryName
298 ? getCloneDestinationBrowsePath({
299 browseDirectoryPath: input.browseDirectoryPath,
300 selectedDirectoryName: input.selectedDirectoryName,
301 cloneDirectoryName: pinnedDirectoryName,
302 caseSensitive: clonePathCaseSensitive,
303 })
304 : getCloneDestinationPath(selectedDirectoryPath, pinnedDirectoryName);
305 setIsBrowseNavigating(true);
306 const committed = await browseNavigation.run(
307 async () => {
308 if (environment && canPreloadBrowsePath(environmentRuntime?.connectionState)) {
309 await loadBrowsePath({
310 environmentId: environment.environmentId,
311 input: { partialPath: selectedDirectoryPath },
312 });
313 }
314 },
315 () => commitPathInput(nextPathInput),
316 );
317 if (committed) {
318 setIsBrowseNavigating(false);
319 }
320 return committed;
321 },
322 [
323 browseNavigation,
324 clonePathCaseSensitive,
325 environment,
326 environmentRuntime?.connectionState,
327 loadBrowsePath,
328 pinnedDirectoryName,
329 ],
330 );
331​
332 useEffect(() => {
333 if (environmentId !== null && environmentId !== previousEnvironmentIdRef.current) {
334 previousEnvironmentIdRef.current = environmentId;
335 setPathInput(
336 getCloneDestinationPath(
337 getAddProjectInitialQuery(environmentBaseDirectory),
338 pinnedDirectoryName,
339 ),
340 );
341 }
342 }, [environmentBaseDirectory, environmentId, pinnedDirectoryName, setPathInput]);
343​
344 useEffect(
345 () => () => {
346 browseNavigation.invalidate();
347 },
348 [browseNavigation],
349 );
350​
351 return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath };
353​
354function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
355 const serverConfigByEnvironmentId = useServerConfigs();
356 const { savedConnectionsById } = useSavedRemoteConnections();
357 const { connectedEnvironments } = useRemoteConnectionStatus();
358​
359 return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
360 const runtimeByEnvironmentId = new Map(
361 connectedEnvironments.map((environment) => [environment.environmentId, environment] as const),
362 );
363 const options = Object.values(savedConnectionsById).map((connection) => {
364 const config = serverConfigByEnvironmentId.get(connection.environmentId);
365 const runtime = runtimeByEnvironmentId.get(connection.environmentId);
366 return {
367 environmentId: connection.environmentId,
368 label: connection.environmentLabel,
369 platform: platformFromOs(config?.environment.platform.os ?? null),
370 machine: resolveEnvironmentMachineKind(config ?? null),
371 baseDirectory: config?.settings.addProjectBaseDirectory ?? null,
372 connectionState: runtime?.connectionState ?? "available",
373 connectionError: runtime?.connectionError ?? null,
374 connectionErrorTraceId: runtime?.connectionErrorTraceId ?? null,
375 supportsCloneTracking: config?.environment.capabilities.projectCloneTracking === true,
376 };
377 });
378 return Arr.sort(options, environmentOptionOrder);
379 }, [connectedEnvironments, savedConnectionsById, serverConfigByEnvironmentId]);
381​
382function useSelectedEnvironment(): {
383 readonly environmentOptions: ReadonlyArray<EnvironmentOption>;
384 readonly selectedEnvironment: EnvironmentOption | null;
385 readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void;
386} {
387 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
388 const environmentOptions = useEnvironmentOptions();
389 const selectedEnvironment =
390 environmentOptions.find(
391 (environment) =>
392 environment.environmentId === selectedEnvironmentId &&
393 canCreateProjectInEnvironment(environment.connectionState),
394 ) ??
395 environmentOptions.find((environment) =>
396 canCreateProjectInEnvironment(environment.connectionState),
397 ) ??
398 null;
399​
400 return {
401 environmentOptions,
402 selectedEnvironment,
403 setSelectedEnvironmentId,
404 };
406​
407function EmptyEnvironmentState() {
408 const navigation = useNavigation();
409​
410 return (
411 <View className="items-center gap-3 rounded-2xl bg-card px-5 py-8">
412 <Text className="text-center text-lg font-t3-bold">Environment unavailable</Text>
413 <Text className="text-center text-sm leading-normal text-foreground-muted">
414 Start or reconnect an environment before adding a project.
415 </Text>
416 <Pressable
417 onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))}
418 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
419 >
420 <Text className="text-sm font-t3-bold text-primary-foreground">Add environment</Text>
421 </Pressable>
422 </View>
423 );
425​
426function SourceControlRow(props: {
427 readonly target: AddProjectRemoteTarget;
428 readonly selectedEnvironmentId: EnvironmentId;
429 readonly ready: boolean;
430 readonly hint: string;
431 readonly isFirst: boolean;
432}) {
433 const navigation = useNavigation();
434 const label = addProjectRemoteTargetLabel(props.target);
435 const title = props.target.source === "url" ? "Git URL" : `${label} repository`;
436 const subtitle =
437 props.target.source === "url" ? "Clone from a remote URL" : `Clone ${label} ${props.hint}`;
438 const icon =
439 props.target.source === "url" ? (
440 <SymbolView name="link" size={17} tintColorClassName={"accent-icon"} type="monochrome" />
441 ) : (
442 <SourceControlIcon kind={props.target.source} size={18} colorClassName="accent-icon" />
443 );
444​
445 if (!props.ready) {
446 return (
447 <ListRow title={title} subtitle={props.hint} icon={icon} disabled isFirst={props.isFirst} />
448 );
449 }
450​
451 return (
452 <ListRow
453 title={title}
454 subtitle={subtitle}
455 icon={icon}
456 isFirst={props.isFirst}
457 onPress={() =>
458 navigation.dispatch(
459 StackActions.push("AddProjectRepository", {
460 environmentId: props.selectedEnvironmentId,
461 source: props.target.source,
462 ...(props.target.host ? { host: props.target.host } : {}),
463 }),
464 )
465 }
466 />
467 );
469​
470export function AddProjectSourceScreen() {
471 const navigation = useNavigation();
472 const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
473 useSelectedEnvironment();
474 const discoveryState = useEnvironmentQuery(
475 selectedEnvironment === null
476 ? null
477 : sourceControlEnvironment.discovery({
478 environmentId: selectedEnvironment.environmentId,
479 input: {},
480 }),
481 );
482 const readiness = useMemo(
483 () => buildAddProjectRemoteSourceReadiness(discoveryState.data),
484 [discoveryState.data],
485 );
486 const targets = useMemo(
487 () => buildAddProjectRemoteTargets(discoveryState.data),
488 [discoveryState.data],
489 );
490​
491 return (
492 <AddProjectShell>
493 {selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
494​
495 {environmentOptions.length > 1 ? (
496 <>
497 <SectionTitle>Environments</SectionTitle>
498 <ListSection>
499 {environmentOptions.map((environment, index) => (
500 <ListRow
501 key={environment.environmentId}
502 title={environment.label}
503 subtitle={
504 canCreateProjectInEnvironment(environment.connectionState)
505 ? environment.environmentId
506 : connectionStatusText({
507 phase: environment.connectionState,
508 error: environment.connectionError,
509 traceId: environment.connectionErrorTraceId,
510 })
511 }
512 icon={
513 <EnvironmentMachineSymbol
514 kind={environment.machine}
515 size={17}
516 tintColorClassName="accent-icon"
517 />
518 }
519 selected={environment.environmentId === selectedEnvironment?.environmentId}
520 disabled={!canCreateProjectInEnvironment(environment.connectionState)}
521 isFirst={index === 0}
522 right={
523 environment.environmentId === selectedEnvironment?.environmentId ? (
524 <SymbolView
525 name="checkmark"
526 size={14}
527 tintColorClassName={"accent-icon"}
528 type="monochrome"
529 />
530 ) : null
531 }
532 onPress={() => setSelectedEnvironmentId(environment.environmentId)}
533 />
534 ))}
535 </ListSection>
536 </>
537 ) : null}
538​
539 {selectedEnvironment ? (
540 <>
541 <ListSection>
542 <ListRow
543 title="Local folder"
544 subtitle="Browse a folder on disk"
545 icon={
546 <SymbolView
547 name="folder.badge.plus"
548 size={17}
549 tintColorClassName={"accent-icon"}
550 type="monochrome"
551 />
552 }
553 isFirst
554 onPress={() =>
555 navigation.dispatch(
556 StackActions.push("AddProjectLocal", {
557 environmentId: selectedEnvironment.environmentId,
558 }),
559 )
560 }
561 />
562 {[
563 { id: "url", source: "url", host: null } as AddProjectRemoteTarget,
564 ...sortAddProjectProviderSources(readiness, targets),
565 ].map((target) => {
566 const targetReadiness = addProjectRemoteTargetReadiness(readiness, target.id);
567 return (
568 <SourceControlRow
569 key={target.id}
570 target={target}
571 selectedEnvironmentId={selectedEnvironment.environmentId}
572 ready={targetReadiness.ready}
573 hint={
574 targetReadiness.ready
575 ? addProjectRemoteSourcePathHint(target.source)
576 : (targetReadiness.hint ?? "")
577 }
578 isFirst={false}
579 />
580 );
581 })}
582 </ListSection>
583 {discoveryState.isPending ? (
584 <ActivityIndicator colorClassName={"accent-icon-muted"} />
585 ) : null}
586 </>
587 ) : null}
588 </AddProjectShell>
589 );
591​
592function openNewTaskDraft(
593 navigation: { dispatch: (action: ReturnType<typeof CommonActions.reset>) => void },
594 params: { environmentId: EnvironmentId; projectId: ProjectId; title: string; cloning?: "1" },
595) {
596 navigation.dispatch(
597 CommonActions.reset({ index: 0, routes: [{ name: "NewTaskDraft", params }] }),
598 );
600​
601function useCreateProject(environment: EnvironmentOption | null) {
602 const navigation = useNavigation();
603 const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
604 const projects = useProjects();
605​
606 return useCallback(
607 async (workspaceRoot: string) => {
608 if (!environment || !canCreateProjectInEnvironment(environment.connectionState)) return;
609​
610 const existing = findExistingAddProject({
611 projects,
612 environmentId: environment.environmentId,
613 path: workspaceRoot,
614 });
615 if (existing) {
616 Alert.alert("Project already exists", existing.title);
617 navigation.dispatch(
618 CommonActions.reset({
619 index: 0,
620 routes: [
621 {
622 name: "NewTaskDraft",
623 params: {
624 environmentId: existing.environmentId,
625 projectId: existing.id,
626 title: existing.title,
627 },
628 },
629 ],
630 }),
631 );
632 return;
633 }
634​
635 const projectId = ProjectId.make(uuidv4());
636 const command = buildProjectCreateCommand({
637 commandId: CommandId.make(uuidv4()),
638 projectId,
639 workspaceRoot,
640 createdAt: new Date().toISOString(),
641 });
642 const result = await createProject({
643 environmentId: environment.environmentId,
644 input: command,
645 });
646 if (AsyncResult.isFailure(result)) {
647 return result;
648 }
649 navigation.dispatch(
650 CommonActions.reset({
651 index: 0,
652 routes: [
653 {
654 name: "NewTaskDraft",
655 params: {
656 environmentId: environment.environmentId,
657 projectId,
658 title: inferProjectTitleFromPath(workspaceRoot),
659 },
660 },
661 ],
662 }),
663 );
664 return result;
665 },
666 [createProject, environment, projects, navigation],
667 );
669​
670function useEnvironmentFromParam(
671 environmentIdParam: string | string[] | undefined,
672): EnvironmentOption | null {
673 const environmentOptions = useEnvironmentOptions();
674 const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
675 return resolveAddProjectEnvironment(environmentOptions, environmentId);
677​
678export function AddProjectRepositoryScreen(props: {
679 readonly environmentId?: string | string[];
680 readonly source?: string | string[];
681 readonly host?: string | string[];
682}) {
683 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
684 reportFailure: false,
685 });
686 const navigation = useNavigation();
687 const environment = useEnvironmentFromParam(props.environmentId);
688 const source = sourceFromParam(props.source);
689 const host = stringParam(props.host);
690 const [repositoryInput, setRepositoryInput] = useState("");
691 const [isSubmitting, setIsSubmitting] = useState(false);
692 const [error, setError] = useState<string | null>(null);
693​
694 const lookupRepository = useCallback(async () => {
695 if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
696 setError(null);
697 setIsSubmitting(true);
698 const provider = addProjectRemoteSourceProvider(source);
699 if (!provider) {
700 const remoteUrl = normalizePastedCloneUrl(repositoryInput);
701 navigation.dispatch(
702 StackActions.push("AddProjectDestination", {
703 environmentId: environment.environmentId,
704 source,
705 remoteUrl,
706 repositoryTitle: remoteUrl,
707 repositoryName: getCloneDirectoryName(remoteUrl),
708 }),
709 );
710 setIsSubmitting(false);
711 return;
712 }
713​
714 const result = await lookupRepositoryQuery({
715 environmentId: environment.environmentId,
716 input: {
717 provider,
718 repository: repositoryInput.trim(),
719 ...(host ? { host } : {}),
720 },
721 });
722 if (AsyncResult.isFailure(result)) {
723 setError(errorMessage(Cause.squash(result.cause)));
724 } else {
725 const repository = result.value;
726 navigation.dispatch(
727 StackActions.push("AddProjectDestination", {
728 environmentId: environment.environmentId,
729 source,
730 remoteUrl: getDefaultCloneUrl(repository),
731 repositoryTitle: repository.nameWithOwner,
732 repositoryName: getCloneDirectoryName(repository.nameWithOwner),
733 }),
734 );
735 }
736 setIsSubmitting(false);
737 }, [environment, host, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
738​
739 return (
740 <AddProjectShell>
741 {error ? <ErrorBanner message={error} /> : null}
742 {environment ? (
743 <>
744 <TextInput
745 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
746 value={repositoryInput}
747 onChangeText={setRepositoryInput}
748 autoCapitalize="none"
749 autoCorrect={false}
750 placeholder={
751 source === "url"
752 ? "https://github.com/org/repo.git"
753 : addProjectRemoteSourcePathHint(source)
754 }
755 returnKeyType="next"
756 onSubmitEditing={() => void lookupRepository()}
757 />
758 <PrimaryActionButton
759 label={source === "url" ? "Continue" : "Lookup repository"}
760 disabled={isSubmitting || repositoryInput.trim().length === 0}
761 onPress={() => void lookupRepository()}
762 loading={isSubmitting}
763 />
764 </>
765 ) : (
766 <EmptyEnvironmentState />
767 )}
768 </AddProjectShell>
769 );
771​
772function FolderBrowser(props: {
773 readonly environment: EnvironmentOption;
774 readonly pathInput: string;
775 readonly setPathInput: (path: string) => void;
776 readonly navigateToBrowsePath: (input: {
777 readonly browseDirectoryPath: string;
778 readonly selectedDirectoryName?: string;
779 }) => Promise<boolean>;
780 readonly pinnedDirectoryName?: string;
781}) {
782 const browsePath = useMemo(
783 () => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
784 [props.environment.platform, props.pathInput],
785 );
786 const browseInput = useMemo(
787 () => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
788 [browsePath.directoryPath],
789 );
790 const browseState = useEnvironmentQuery(
791 browseInput === null
792 ? null
793 : filesystemEnvironment.browse({
794 environmentId: props.environment.environmentId,
795 input: browseInput,
796 }),
797 );
798 // A pinned repository folder does not exist yet, so filtering the listing by
799 // it would empty the folder picker. Anything the user typed still filters.
800 const pinnedDirectoryName = props.pinnedDirectoryName ?? "";
801 const pinnedDirectoryMatches = isWindowsPlatform(props.environment.platform)
802 ? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
803 : browsePath.filterQuery === pinnedDirectoryName;
804 const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
805 const { visibleEntries: visibleBrowseEntries } = useMemo(
806 () => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browseFilterQuery),
807 [browseFilterQuery, browseState.data?.entries],
808 );
809​
810 return (
811 <>
812 <SectionTitle>Browse folders</SectionTitle>
813 {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
814 <ListSection>
815 {browseState.isPending && browseState.data === null ? (
816 <View className="items-center py-5">
817 <ActivityIndicator colorClassName={"accent-icon-muted"} />
818 </View>
819 ) : null}
820 {browsePath.canBrowseUp ? (
821 <ListRow
822 title=".."
823 icon={
824 <SymbolView
825 name="arrow.turn.left.up"
826 size={17}
827 tintColorClassName={"accent-icon-muted"}
828 type="monochrome"
829 />
830 }
831 isFirst
832 right={null}
833 onPress={() => {
834 if (browsePath.parentPath) {
835 void props.navigateToBrowsePath({
836 browseDirectoryPath: browsePath.parentPath,
837 });
838 }
839 }}
840 />
841 ) : null}
842 {visibleBrowseEntries.map((entry, index) => (
843 <ListRow
844 key={entry.fullPath}
845 title={entry.name}
846 icon={
847 <SymbolView
848 name="folder"
849 size={17}
850 tintColorClassName={"accent-icon-muted"}
851 type="monochrome"
852 />
853 }
854 isFirst={index === 0 && !browsePath.canBrowseUp}
855 right={null}
856 onPress={() => {
857 void props.navigateToBrowsePath({
858 browseDirectoryPath: browsePath.directoryPath,
859 selectedDirectoryName: entry.name,
860 });
861 }}
862 />
863 ))}
864 </ListSection>
865 </>
866 );
868​
869export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
870 const environment = useEnvironmentFromParam(props.environmentId);
871 const createProject = useCreateProject(environment);
872 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
873 useBrowsePathInput(environment);
874 const [isSubmitting, setIsSubmitting] = useState(false);
875 const [error, setError] = useState<string | null>(null);
876​
877 const submitPath = useCallback(async () => {
878 if (!environment || isBrowseNavigating || isSubmitting) return;
879 setError(null);
880 const resolved = resolveAddProjectPath({
881 rawPath: pathInput,
882 currentProjectCwd: null,
883 platform: environment.platform,
884 });
885 if (!resolved.ok) {
886 setError(resolved.error);
887 return;
888 }
889​
890 setIsSubmitting(true);
891 const result = await createProject(resolved.path);
892 if (result && AsyncResult.isFailure(result)) {
893 setError(errorMessage(Cause.squash(result.cause)));
894 }
895 setIsSubmitting(false);
896 }, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
897​
898 return (
899 <AddProjectShell>
900 {error ? <ErrorBanner message={error} /> : null}
901 {environment ? (
902 <>
903 <ProjectPathInput
904 value={pathInput}
905 onChangeText={setPathInput}
906 onSubmit={() => void submitPath()}
907 />
908 <PrimaryActionButton
909 label="Add project"
910 disabled={isBrowseNavigating || isSubmitting}
911 onPress={() => void submitPath()}
912 loading={isSubmitting}
913 />
914 <FolderBrowser
915 environment={environment}
916 navigateToBrowsePath={navigateToBrowsePath}
917 pathInput={pathInput}
918 setPathInput={setPathInput}
919 />
920 </>
921 ) : (
922 <EmptyEnvironmentState />
923 )}
924 </AddProjectShell>
925 );
927​
928export function AddProjectDestinationScreen(props: {
929 readonly environmentId?: string | string[];
930 readonly remoteUrl?: string | string[];
931 readonly repositoryTitle?: string | string[];
932 readonly repositoryName?: string | string[];
933}) {
934 const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
935 reportFailure: false,
936 });
937 const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, {
938 reportFailure: false,
939 });
940 const navigation = useNavigation();
941 const environment = useEnvironmentFromParam(props.environmentId);
942 const createProject = useCreateProject(environment);
943 const remoteUrl = stringParam(props.remoteUrl);
944 const repositoryTitle = stringParam(props.repositoryTitle);
945 // A lookup derives this from "owner/repo", a pasted clone URL from its own
946 // last segment. Older links without the param keep the browsed folder.
947 // Trim once here: the path input and the folder-list filter must compare the
948 // same value, or a deep link with a padded param empties the folder picker.
949 const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
950 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
951 environment,
952 repositoryName,
953 );
954 const [isSubmitting, setIsSubmitting] = useState(false);
955 const [error, setError] = useState<string | null>(null);
956​
957 const submitPath = useCallback(async () => {
958 if (!environment || !remoteUrl || isBrowseNavigating || isSubmitting) return;
959 setError(null);
960 const resolved = resolveAddProjectPath({
961 rawPath: pathInput,
962 currentProjectCwd: null,
963 platform: environment.platform,
964 });
965 if (!resolved.ok) {
966 setError(resolved.error);
967 return;
968 }
969​
970 setIsSubmitting(true);
971 if (environment.supportsCloneTracking) {
972 // The server creates the project and clones in the background; the
973 // draft screen shows progress and holds Start until the files land.
974 const projectId = ProjectId.make(uuidv4());
975 const title = inferProjectTitleFromPath(resolved.path);
976 const startResult = await startProjectClone({
977 environmentId: environment.environmentId,
978 input: {
979 projectId,
980 title,
981 createdAt: new Date().toISOString(),
982 remoteUrl,
983 destinationPath: resolved.path,
984 },
985 });
986 if (AsyncResult.isFailure(startResult)) {
987 setError(errorMessage(Cause.squash(startResult.cause)));
988 } else {
989 // The draft screen resolves its project from the client store, so it
990 // must not open before the create event has arrived (it would fall
991 // back to the project picker and lose the clone controls). Stay in
992 // the submitting state until then; the clone keeps running either way.
993 const project = await waitForProject(
994 { environmentId: environment.environmentId, projectId },
995 15_000,
996 );
997 if (project === null) {
998 setError(
999 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
1000 );
1001 } else {
1002 openNewTaskDraft(navigation, {
1003 environmentId: environment.environmentId,
1004 projectId,
1005 title,
1006 cloning: "1",
1007 });
1010 setIsSubmitting(false);
1011 return;
1013 const cloneResult = await cloneRepository({
1014 environmentId: environment.environmentId,
1015 input: {
1016 remoteUrl,
1017 destinationPath: resolved.path,
1018 },
1019 });
1020 if (AsyncResult.isFailure(cloneResult)) {
1021 setError(errorMessage(Cause.squash(cloneResult.cause)));
1022 } else {
1023 const createResult = await createProject(cloneResult.value.cwd);
1024 if (createResult && AsyncResult.isFailure(createResult)) {
1025 setError(errorMessage(Cause.squash(createResult.cause)));
1028 setIsSubmitting(false);
1029 }, [
1030 cloneRepository,
1031 createProject,
1032 environment,
1033 isBrowseNavigating,
1034 isSubmitting,
1035 navigation,
1036 pathInput,
1037 remoteUrl,
1038 startProjectClone,
1039 ]);
1040​
1041 return (
1042 <AddProjectShell>
1043 {error ? <ErrorBanner message={error} /> : null}
1044 {repositoryTitle ? (
1045 <View className="rounded-[24px] bg-card px-4 py-3">
1046 <Text className="text-base font-t3-bold">{repositoryTitle}</Text>
1047 <Text className="mt-0.5 text-xs text-foreground-muted" numberOfLines={2}>
1048 {remoteUrl}
1049 </Text>
1050 </View>
1051 ) : null}
1052 {environment ? (
1053 <>
1054 <ProjectPathInput
1055 value={pathInput}
1056 onChangeText={setPathInput}
1057 onSubmit={() => void submitPath()}
1058 />
1059 <PrimaryActionButton
1060 label="Clone project"
1061 disabled={isBrowseNavigating || isSubmitting || !remoteUrl}
1062 onPress={() => void submitPath()}
1063 loading={isSubmitting}
1064 />
1065 <FolderBrowser
1066 environment={environment}
1067 navigateToBrowsePath={navigateToBrowsePath}
1068 pathInput={pathInput}
1069 setPathInput={setPathInput}
1070 pinnedDirectoryName={repositoryName}
1071 />
1072 </>
1073 ) : (
1074 <EmptyEnvironmentState />
1075 )}
1076 </AddProjectShell>
1077 );