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

AddProjectScreen.tsx

1,416 lines48.2 KB

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