g1t/apps/web/app/routes/repo/deployments.tsx

321 lines14,485 bytesCodeBlame
1import { ExternalLink, Globe, Rocket, RotateCw, Trash2 } from "lucide-react";
2import type { ReactNode } from "react";
3import { Form, Link, useNavigation } from "react-router";
4
5import type { Deployment, FeatureState } from "@g1t/contracts";
6
7import { host, StatusDot } from "../../components/deploy";
8
9import type { Route } from "./+types/deployments";
10import { page } from "../../lib/meta";
11import { Button, ButtonLink, ComputeNote, EmptyState, ErrorText, TimeAgo } from "../../components/ui";
12import { computeNoteFor } from "../../lib/compute.server";
13import { billing, deployments, projects } from "../../lib/services.server";
14import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server";
15import { refusal, requireRepo } from "../../lib/access.server";
16import { whyNot } from "../../lib/access";
17
18export function meta({ params, ...args }: Route.MetaArgs) {
19 return page(args, { title: `Deployments · ${params.owner}/${params.repo} · g1t` });
20}
21
22export async function loader({ params, context }: Route.LoaderArgs) {
23 const viewer = getViewer(context);
24 // Anyone who can read the repository: a public one's to anyone, a private one's to people with a role.
25 const { access } = await requireRepo(context, params, "read");
26 const ref = { workspace: params.owner, slug: params.repo };
27 const [settings, list, features, computeNote, project] = await Promise.all([
28 deployments.settings(ref, viewer),
29 deployments.list(ref, viewer),
30 billing.features(params.owner, viewer),
31 // Builds are compute: said before a deploy is refused for it.
32 computeNoteFor(params.owner, "deploy"),
33 projects.get(params.owner, params.repo, viewer).catch(() => null),
34 ]);
35 // Set not to deploy, in General settings: turning them on waits for that to change.
36 const notDeploying = project?.ok ? project.value.deploys === "no" : false;
37 // Someone outside the workspace does not see its plans; the page works without.
38 const plan = features.ok ? (features.value.find((state) => state.plan.feature === "deployments") ?? null) : null;
39 return { can: access.can, settings: unwrap(settings), ...unwrap(list), plan, computeNote, notDeploying };
40}
41
42export async function action({ request, params, context }: Route.ActionArgs) {
43 assertSameOrigin(request);
44 const user = requireUser(context, request);
45 const form = await request.formData();
46 const ref = { workspace: params.owner, slug: params.repo };
47 const intent = form.get("intent");
48 const branch = form.get("branch") ? String(form.get("branch")) : null;
49 // Deploying is compute (Write); turning deployments on or off is a deployment setting (Admin).
50 const refused = await refusal(context, params, intent === "enable" || intent === "disable" ? "manage_integrations" : "run");
51 if (refused) return { error: refused };
52 if (intent === "redeploy") {
53 const started = await deployments.redeploy(user, ref, branch);
54 return started.ok ? { notice: "Build started." } : { error: started.error.message };
55 }
56 if (intent === "take-down") {
57 const done = await deployments.takeDown(user, ref, branch);
58 return done.ok ? { notice: "Taken down." } : { error: done.error.message };
59 }
60 if (intent === "enable" || intent === "disable") {
61 const saved = await deployments.updateSettings(user, ref, { enabled: intent === "enable" });
62 return saved.ok
63 ? { notice: intent === "enable" ? "Deployments are on. Production is building." : "Deployments are off, and every app is down." }
64 : { error: saved.error.message };
65 }
66 return { error: "Unknown request." };
67}
68
69export default function RepoDeployments({ loaderData, actionData, params }: Route.ComponentProps) {
70 const { settings, deployments: builds, live, plan, can } = loaderData;
71 const busy = useNavigation().state === "submitting";
72 const base = `/${params.owner}/${params.repo}`;
73 const production = live.find((app) => app.kind === "production");
74 const previews = live.filter((app) => app.kind === "preview");
75
76 return (
77 <div className="mx-auto max-w-5xl">
78 <header className="flex flex-wrap items-start justify-between gap-4">
79 <div>
80 <h1 className="flex items-center gap-2 text-xl font-semibold tracking-tight">
81 <Rocket size={18} className="text-accent" />
82 Deployments
83 </h1>
84 <p className="mt-1 max-w-2xl text-sm text-muted">
85 Every pull request gets a live preview on g1t.page, and the default branch goes to production on each push.
86 Apps run on Cloudflare only while someone visits them.{" "}
87 <a href="https://docs.g1t.sh/guides/deployments/" className="text-fg hover:underline">
88 How it works
89 </a>
90 </p>
91 </div>
92 {settings.enabled && (
93 <a
94 href={settings.primaryDomain ? `https://${settings.primaryDomain}` : settings.productionUrl}
95 className="inline-flex items-center gap-1.5 rounded-md border border-line px-3 py-1.5 font-mono text-xs text-muted hover:border-line-strong hover:text-fg"
96 >
97 <Globe size={13} />
98 {settings.primaryDomain ?? host(settings.productionUrl)}
99 </a>
100 )}
101 </header>
102
103 <div className="mt-4 min-h-6">
104 {actionData && "notice" in actionData && <p className="text-sm text-accent">{actionData.notice}</p>}
105 <ErrorText>{actionData && "error" in actionData ? actionData.error : null}</ErrorText>
106 {!actionData && <ComputeNote note={loaderData.computeNote} />}
107 </div>
108
109 {!plan?.on ? (
110 <PlanNeeded plan={plan} owner={params.owner} />
111 ) : !settings.enabled ? (
112 <section className="mt-2 rounded-xl border border-accent/30 bg-accent/5 p-6">
113 <h2 className="font-medium">Deployments are off</h2>
114 <p className="mt-1 max-w-2xl text-sm text-muted">
115 Each project turns deployments on for itself; until then nothing builds or runs. Once on, production goes
116 up at <span className="font-mono text-fg">{host(settings.productionUrl)}</span> and every open pull request
117 gets its own preview. Workers projects (a <code className="font-mono text-fg">wrangler.jsonc</code>) and
118 static sites deploy without configuration.
119 </p>
120 {loaderData.notDeploying ? (
121 <p className="mt-4 max-w-2xl text-sm text-muted">
122 This project is set as one that doesn't deploy, a library or a tool. To deploy it, choose Deploys or Detect
123 automatically in{" "}
124 <Link to={`/${params.owner}/${params.repo}/settings#deploys`} className="text-fg underline underline-offset-4">
125 its settings
126 </Link>{" "}
127 first.
128 </p>
129 ) : (
130 <Form method="post" className="mt-4">
131 <Button variant="accent" type="submit" name="intent" value="enable" disabled={busy || !can.manage_integrations} title={whyNot(can, "manage_integrations")}>
132 <Rocket size={14} />
133 Turn on deployments
134 </Button>
135 </Form>
136 )}
137 </section>
138 ) : (
139 <>
140 <section className="mt-2 grid gap-4 md:grid-cols-2">
141 <LiveCard
142 title="Production"
143 hint="The default branch, on every push."
144 app={production}
145 off={!settings.production}
146 actions={
147 can.run ? <AppActions branch={null} up={!!production} busy={busy} /> : null
148 }
149 />
150 <div className="rounded-xl border border-line bg-surface p-5">
151 <h2 className="text-sm font-medium">Previews</h2>
152 <p className="mt-0.5 text-xs text-faint">
153 {settings.previews
154 ? `One per branch with an open pull request; down when it closes or after ${settings.idleDays} days without a visit.`
155 : "Off for this repository."}
156 </p>
157 {previews.length === 0 ? (
158 <p className="mt-4 text-sm text-muted">No previews are up.</p>
159 ) : (
160 <ul className="mt-3 divide-y divide-line">
161 {previews.map((app) => (
162 <li key={app.url} className="flex items-center gap-3 py-2 text-sm">
163 <span className="shrink-0">
164 <span className="font-medium">{app.branch}</span>
165 {app.number != null && (
166 <Link to={`${base}/pull/${app.number}`} className="ml-1.5 text-xs text-muted hover:underline">
167 #{app.number}
168 </Link>
169 )}
170 </span>
171 <a href={app.url} className="min-w-0 truncate font-mono text-xs text-muted hover:text-fg">
172 {host(app.url)}
173 </a>
174 <span className="ml-auto shrink-0">
175 {can.run && <AppActions branch={app.branch} up busy={busy} compact />}
176 </span>
177 </li>
178 ))}
179 </ul>
180 )}
181 </div>
182 </section>
183
184 <h2 className="mt-10 text-sm font-medium text-muted">Recent builds</h2>
185 <div className="mt-3">
186 {builds.length === 0 ? (
187 <EmptyState title="No builds yet">Push to the default branch or open a pull request.</EmptyState>
188 ) : (
189 <ul className="divide-y divide-line overflow-hidden rounded-xl border border-line">
190 {builds.map((build) => (
191 <BuildRow key={build.id} build={build} base={base} />
192 ))}
193 </ul>
194 )}
195 </div>
196
197 <p className="mt-10 text-sm text-muted">
198 Build command, output directory, idle days, and turning deployments off are under{" "}
199 <Link to={`${base}/settings/deployments`} className="text-fg hover:underline">
200 Settings → Deployments
201 </Link>
202 . Secrets and config for builds and running apps are under{" "}
203 <Link to={`${base}/settings/secrets`} className="text-fg hover:underline">
204 Settings → Secrets and variables
205 </Link>
206 , and production's own domains under{" "}
207 <Link to={`${base}/settings/domains`} className="text-fg hover:underline">
208 Settings → Domains
209 </Link>
210 .
211 </p>
212 </>
213 )}
214 </div>
215 );
216}
217
218function PlanNeeded({ plan, owner }: { plan: FeatureState | null; owner: string }) {
219 return (
220 <section className="mt-2 rounded-xl border border-accent/30 bg-accent/5 p-6">
221 <h2 className="font-medium">Deployments are part of a paid plan</h2>
222 <p className="mt-1 max-w-2xl text-sm text-muted">
223 Turn on Deployments for the {owner} workspace and every project in it can have a preview for each pull
224 request and production on g1t.page.
225 {plan && ` $${(plan.plan.monthlyCents / 100).toFixed(0)} a month, including:`}
226 </p>
227 {plan && (
228 <ul className="mt-3 grid gap-1.5 text-sm text-muted sm:grid-cols-2">
229 {plan.plan.includes.map((line) => (
230 <li key={line} className="flex gap-2">
231 <span className="text-accent">✓</span>
232 {line}
233 </li>
234 ))}
235 </ul>
236 )}
237 {plan && <p className="mt-3 text-xs text-faint">{plan.plan.overage}</p>}
238 <div className="mt-4">
239 <ButtonLink variant="accent" to={`/${owner}/-/billing`}>
240 See the plan under Billing
241 </ButtonLink>
242 </div>
243 </section>
244 );
245}
246
247function LiveCard({
248 title,
249 hint,
250 app,
251 off,
252 actions,
253}: {
254 title: string;
255 hint: string;
256 app: { url: string; commit: string; deployedAt: string } | undefined;
257 off: boolean;
258 actions: ReactNode;
259}) {
260 return (
261 <div className="rounded-xl border border-line bg-surface p-5">
262 <h2 className="text-sm font-medium">{title}</h2>
263 <p className="mt-0.5 text-xs text-faint">{off ? "Off for this repository." : hint}</p>
264 {app ? (
265 <>
266 <a href={app.url} className="mt-3 flex items-center gap-1.5 font-mono text-sm text-accent hover:underline">
267 {host(app.url)}
268 <ExternalLink size={12} />
269 </a>
270 <p className="mt-1 text-xs text-faint">
271 <span className="font-mono">{app.commit.slice(0, 8)}</span> · deployed <TimeAgo at={app.deployedAt} />
272 </p>
273 </>
274 ) : (
275 <p className="mt-4 text-sm text-muted">Not up.</p>
276 )}
277 {!off && <div className="mt-4">{actions}</div>}
278 </div>
279 );
280}
281
282function AppActions({ branch, up, busy, compact }: { branch: string | null; up: boolean; busy: boolean; compact?: boolean }) {
283 return (
284 <Form method="post" className="flex items-center gap-2">
285 {branch != null && <input type="hidden" name="branch" value={branch} />}
286 <Button variant="quiet" type="submit" name="intent" value="redeploy" disabled={busy} title="Build again from the current head">
287 <RotateCw size={13} />
288 {!compact && "Redeploy"}
289 </Button>
290 {up && (
291 <Button variant="quiet" type="submit" name="intent" value="take-down" disabled={busy} title="Take it down now">
292 <Trash2 size={13} />
293 {!compact && "Take down"}
294 </Button>
295 )}
296 </Form>
297 );
298}
299
300function BuildRow({ build, base }: { build: Deployment; base: string }) {
301 return (
302 <li>
303 <Link to={`${base}/deployments/${build.id}`} className="flex items-center gap-4 px-4 py-3 text-sm hover:bg-surface">
304 <span className="w-20 shrink-0">
305 <StatusDot status={build.status} />
306 </span>
307 <span className="min-w-0 grow">
308 <span className="block truncate font-medium">
309 {build.kind === "production" ? "Production" : `Preview of ${build.branch}`}
310 <span className="ml-2 font-mono text-xs font-normal text-faint">{build.commit.slice(0, 8)}</span>
311 </span>
312 {build.error && <span className="mt-0.5 block truncate text-xs text-muted">{build.error}</span>}
313 </span>
314 <span className="shrink-0 text-xs text-faint">
315 {build.buildSeconds != null && `${build.buildSeconds} s · `}
316 <TimeAgo at={build.createdAt} />
317 </span>
318 </Link>
319 </li>
320 );
321}