pr_01m47d15m3e54sn21z27rpy5n9/apps/web/app/routes/new.tsx

221 lines9,296 bytesCodeBlame
1import { Box, Download, GitBranch, Globe, Lock, Sparkles } from "lucide-react";
2import { useState } from "react";
3import { Form, redirect, useNavigate, useNavigation } from "react-router";
4
5import type { Route } from "./+types/new";
6import { page } from "../lib/meta";
7import { Avatar, Button, ErrorText } from "../components/ui";
8import { Field, FieldDescription, FieldLabel, FieldLegend, FieldSet } from "../components/ui/field";
9import { Input, InputAddon, InputGroup } from "../components/ui/input";
10import { RadioCard, RadioGroup } from "../components/ui/radio-group";
11import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "../components/ui/select";
12import { repos } from "../lib/services.server";
13import { GithubMark } from "../components/github";
14import { githubApp } from "../lib/github.server";
15import { assertSameOrigin, requireUser } from "../lib/session.server";
16
17export function meta(args: Route.MetaArgs) {
18 return page(args, { title: "New project · g1t" });
19}
20
21export async function loader({ request, context }: Route.LoaderArgs) {
22 const user = requireUser(context, request);
23 const workspaces = (user.workspaces ?? []).map((membership) => ({
24 slug: membership.slug,
25 role: membership.role,
26 name: membership.name ?? membership.slug,
27 avatar: membership.avatar ?? null,
28 }));
29 // Projects live in a workspace, so there has to be one first.
30 if (workspaces.length === 0) throw redirect("/workspaces/new");
31 const asked = new URL(request.url).searchParams.get("workspace");
32 const selected = asked && workspaces.some((workspace) => workspace.slug === asked) ? asked : workspaces[0].slug;
33 // With g1t's GitHub App configured, repositories can come from GitHub.
34 const github = await githubApp.status(user, selected).catch(() => null);
35 return { workspaces, selected, github: Boolean(github?.ok && github.value.configured) };
36}
37
38export async function action({ request, context }: Route.ActionArgs) {
39 assertSameOrigin(request);
40 const user = requireUser(context, request);
41 const form = await request.formData();
42 // A project hosted on g1t: its repository is made with it, and the
43 // project takes the repository's name.
44 const result = await repos.create(user, {
45 namespace: String(form.get("workspace") ?? ""),
46 name: String(form.get("name") ?? ""),
47 description: String(form.get("description") ?? ""),
48 isPrivate: form.get("visibility") === "private",
49 importUrl: form.get("source") === "import" ? String(form.get("importUrl") ?? "").trim() || undefined : undefined,
50 });
51 if (!result.ok) return { error: result.error.message };
52 throw redirect(`/${result.value.namespace}/${result.value.name}`);
53}
54
55type Source = "empty" | "import";
56
57const SOURCES: { id: Source | "mirror"; title: string; text: string; icon: React.ReactNode; soon?: boolean }[] = [
58 {
59 id: "empty",
60 title: "Start empty",
61 text: "A new repository on g1t. Push to it, or hand an agent the first issue.",
62 icon: <Sparkles />,
63 },
64 {
65 id: "import",
66 title: "Import code",
67 text: "Copy a public repository from GitHub or any git host into a new one on g1t.",
68 icon: <Download />,
69 },
70 {
71 id: "mirror",
72 title: "Mirror GitHub, GitLab or Bitbucket",
73 text: "Keep the code where it is and work on it with g1t's agents. Deployments are yours to turn on.",
74 icon: <GitBranch />,
75 soon: true,
76 },
77];
78
79const ROLE_LABELS: Record<string, string> = { owner: "Owner", admin: "Admin", member: "Member" };
80
81/** Replaces the mirror card when g1t's GitHub App is configured. */
82const GITHUB_SOURCE = {
83 id: "github" as const,
84 title: "Import from GitHub",
85 text: "Import, mirror or move repositories you can reach on GitHub, private ones too.",
86 icon: <GithubMark />,
87 soon: false,
88};
89
90export default function NewProject({ loaderData, actionData }: Route.ComponentProps) {
91 const [source, setSource] = useState<Source>("empty");
92 const navigate = useNavigate();
93 const sources = loaderData.github ? SOURCES.map((option) => (option.id === "mirror" ? GITHUB_SOURCE : option)) : SOURCES;
94 const [workspace, setWorkspace] = useState(loaderData.selected);
95 const [name, setName] = useState("");
96 const busy = useNavigation().state === "submitting";
97 return (
98 <main className="mx-auto max-w-2xl px-4 py-12">
99 <span className="flex size-10 items-center justify-center rounded-xl bg-accent/10 text-accent ring-1 ring-accent/30">
100 <Box size={18} />
101 </span>
102 <h1 className="mt-4 text-2xl font-semibold tracking-tight">New project</h1>
103 <p className="mt-1.5 text-sm text-muted">
104 A project is what you build and run. Its code lives in its source; its deployments, environments, secrets and
105 variables belong to the project.
106 </p>
107
108 <Form method="post" className="mt-8 space-y-8">
109 <FieldSet>
110 <FieldLegend>Where its code comes from</FieldLegend>
111 <RadioGroup
112 name="source"
113 value={source}
114 onValueChange={(value) =>
115 value === "github" ? navigate(`/new/github?workspace=${workspace}`) : setSource(value as Source)
116 }
117 aria-label="Where its code comes from"
118 className="gap-3 sm:grid-cols-3"
119 >
120 {sources.map((option) => (
121 <RadioCard
122 key={option.id}
123 value={option.id}
124 title={option.title}
125 description={option.text}
126 icon={option.icon}
127 disabled={option.soon}
128 badge={option.soon ? "Soon" : undefined}
129 />
130 ))}
131 </RadioGroup>
132 </FieldSet>
133
134 {source === "import" && (
135 <Field className="animate-fade-in">
136 <FieldLabel htmlFor="importUrl">Repository to import</FieldLabel>
137 <Input id="importUrl" name="importUrl" type="url" required placeholder="https://github.com/owner/repo" />
138 <FieldDescription>The address of a public repository. Its default branch is copied, up to 40 MB.</FieldDescription>
139 </Field>
140 )}
141
142 <Field>
143 <FieldLabel htmlFor="name">Name</FieldLabel>
144 <InputGroup className="h-10">
145 <Select name="workspace" value={workspace} onValueChange={setWorkspace}>
146 <SelectTrigger
147 aria-label="Workspace"
148 className="h-full w-auto max-w-[55%] shrink-0 rounded-none border-0 bg-surface px-2.5 font-medium hover:bg-raised focus-visible:ring-0 data-[state=open]:bg-raised data-[state=open]:ring-0 sm:max-w-[45%]"
149 >
150 <SelectValue />
151 </SelectTrigger>
152 <SelectContent align="start" className="min-w-64">
153 <SelectGroup>
154 <SelectLabel>Workspaces</SelectLabel>
155 {loaderData.workspaces.map((option) => (
156 <SelectItem
157 key={option.slug}
158 value={option.slug}
159 icon={<Avatar name={option.name} image={option.avatar} size={18} square />}
160 description={`g1t.sh/${option.slug} · ${ROLE_LABELS[option.role] ?? option.role}`}
161 >
162 {option.name}
163 </SelectItem>
164 ))}
165 </SelectGroup>
166 </SelectContent>
167 </Select>
168 <InputAddon className="border-l border-line px-2 font-mono text-base text-faint">/</InputAddon>
169 <Input
170 id="name"
171 name="name"
172 required
173 autoFocus
174 maxLength={100}
175 placeholder="my-app"
176 value={name}
177 onChange={(event) => setName(event.target.value)}
178 className="pl-1 font-mono"
179 />
180 </InputGroup>
181 <FieldDescription>
182 The project and its repository share it:{" "}
183 <span className="font-mono text-muted">
184 g1t.sh/{workspace}/<span className={name ? "text-fg" : undefined}>{name || "name"}</span>
185 </span>
186 </FieldDescription>
187 </Field>
188
189 <Field>
190 <FieldLabel htmlFor="description">
191 Description <span className="font-normal text-faint">(optional)</span>
192 </FieldLabel>
193 <Input id="description" name="description" maxLength={200} placeholder="What it is, in a line" />
194 </Field>
195
196 <FieldSet>
197 <FieldLegend>Who can see it</FieldLegend>
198 <RadioGroup name="visibility" defaultValue="public" aria-label="Who can see it" className="gap-3 sm:grid-cols-2">
199 <RadioCard
200 value="public"
201 icon={<Globe />}
202 title="Public"
203 description="Anyone can see its code and open issues."
204 />
205 <RadioCard
206 value="private"
207 icon={<Lock />}
208 title="Private"
209 description="Only members of the workspace."
210 />
211 </RadioGroup>
212 </FieldSet>
213
214 <ErrorText>{actionData?.error}</ErrorText>
215 <Button type="submit" variant="accent" disabled={busy}>
216 Create project
217 </Button>
218 </Form>
219 </main>
220 );
221}