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

AddProjectScreen.tsx

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