| 1 | import { Check, Copy, GitCommitHorizontal, GitPullRequest, MessageSquareOff, MessagesSquare, Sparkles } from "lucide-react"; |
| 2 | import { Suspense, useState } from "react"; |
| 3 | import { Await, Link, data, redirect } from "react-router"; |
| 4 | |
| 5 | import type { Comparison, Pull } from "@g1t/contracts"; |
| 6 | |
| 7 | import { asComments } from "../../lib/commit-comments"; |
| 8 | |
| 9 | import { parseCommitMessage } from "../../lib/commit-message"; |
| 10 | import { firstScreens } from "../../lib/diff"; |
| 11 | import type { Route } from "./+types/commit"; |
| 12 | import { page } from "../../lib/meta"; |
| 13 | import { CommitChecksBadge } from "../../components/commit-checks"; |
| 14 | import { DiffView } from "../../components/diff-view"; |
| 15 | import { CommitAvatars, CommitNames } from "../../components/commit-person"; |
| 16 | import { ErrorText, TimeAgo } from "../../components/ui"; |
| 17 | import { CommentForm, CommentList } from "../../components/work"; |
| 18 | import { Badge } from "../../components/ui/badge"; |
| 19 | import { Button } from "../../components/ui/button"; |
| 20 | import { Card } from "../../components/ui/card"; |
| 21 | import { Skeleton } from "../../components/ui/skeleton"; |
| 22 | import { commitChecksFor } from "../../lib/commit-checks.server"; |
| 23 | import { immutable } from "../../lib/immutable.server"; |
| 24 | import { pullForCommit } from "../../lib/provenance.server"; |
| 25 | import { showOneCommit } from "../../lib/commit-people.server"; |
| 26 | import { repos, work } from "../../lib/services.server"; |
| 27 | import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server"; |
| 28 | import { accessTo } from "../../lib/access.server"; |
| 29 | |
| 30 | export function headers({ loaderHeaders }: Route.HeadersArgs) { |
| 31 | return { "Server-Timing": loaderHeaders.get("Server-Timing") ?? "" }; |
| 32 | } |
| 33 | |
| 34 | export function meta({ loaderData, params, ...args }: Route.MetaArgs) { |
| 35 | const subject = loaderData?.commit.message.split("\n")[0]; |
| 36 | return page(args, { |
| 37 | title: `${subject ? `${subject} · ` : ""}${params.hash.slice(0, 7)} · ${params.owner}/${params.repo} · g1t`, |
| 38 | }); |
| 39 | } |
| 40 | |
| 41 | /** How far back a short hash is looked for. */ |
| 42 | const SHORT_HASH_SEARCH = 300; |
| 43 | |
| 44 | export async function loader({ params, context }: Route.LoaderArgs) { |
| 45 | const viewer = getViewer(context); |
| 46 | const path = { namespace: params.owner, name: params.repo }; |
| 47 | const hash = params.hash.toLowerCase(); |
| 48 | if (!/^[0-9a-f]{4,40}$/.test(hash)) throw data(null, { status: 404 }); |
| 49 | if (hash.length < 40) { |
| 50 | // A short hash: find the commit it names and go to its full address. |
| 51 | const log = await repos.log(path, viewer, null, SHORT_HASH_SEARCH); |
| 52 | const matches = log.ok ? log.value.filter((commit) => commit.hash.startsWith(hash)) : []; |
| 53 | if (matches.length === 1) throw redirect(`/${params.owner}/${params.repo}/commit/${matches[0]!.hash}`); |
| 54 | throw new Response("Commit not found.", { status: 404 }); |
| 55 | } |
| 56 | const started = Date.now(); |
| 57 | // Its comments and whether more may be added: never cached, read beside the commit. |
| 58 | const said = Promise.all([ |
| 59 | work.commitComments(viewer, path, hash).catch(() => null), |
| 60 | work.getSettings(path, viewer).catch(() => null), |
| 61 | accessTo(context, params).catch(() => null), |
| 62 | ]); |
| 63 | const found = unwrap(await repos.get(path, viewer)); |
| 64 | // The viewer may read the repository, and a commit never changes: after |
| 65 | // the first visit it and its diff come from the cache. |
| 66 | let cached = true; |
| 67 | const loaded = await immutable(`commit:${found.id}:${hash}`, async () => { |
| 68 | cached = false; |
| 69 | // At once: a commit is compared with its first parent, so the diff |
| 70 | // does not wait for the commit. |
| 71 | const [log, compared] = await Promise.all([ |
| 72 | repos.log(path, viewer, hash, 1), |
| 73 | repos.compare(found.id, viewer, null, hash), |
| 74 | ]); |
| 75 | const commit = log.ok ? log.value[0] : undefined; |
| 76 | if (!commit) return null; |
| 77 | const comparison: Comparison = compared.ok |
| 78 | ? compared.value |
| 79 | : { base: null, head: commit.hash, files: [], truncated: false }; |
| 80 | return { commit, comparison }; |
| 81 | }); |
| 82 | if (!loaded) throw new Response("Commit not found.", { status: 404 }); |
| 83 | // Its people, as their accounts where there are any; not kept with the |
| 84 | // commit, since an address can be confirmed or removed later. |
| 85 | const commit = (await showOneCommit(loaded.commit))!; |
| 86 | const [comments, settings, access] = await said; |
| 87 | return data( |
| 88 | { |
| 89 | ...loaded, |
| 90 | // Its first screens with their lines; the rest load as they are reached. |
| 91 | comparison: firstScreens(loaded.comparison), |
| 92 | commit, |
| 93 | // Streamed: the page shows the commit while this is worked out. |
| 94 | pull: pullForCommit(path, viewer, loaded.commit.hash), |
| 95 | // Never cached: checks report on a commit long after it was made. |
| 96 | checks: commitChecksFor(path, viewer, [loaded.commit.hash]), |
| 97 | comments: comments?.ok ? comments.value : [], |
| 98 | // Off, the comments made stay readable and no more can be added. |
| 99 | commentsOn: settings?.ok ? settings.value.allowCommitComments : true, |
| 100 | viewer: viewer ? { username: viewer.username } : null, |
| 101 | // Maintain and up edit and delete anyone's comments; everyone, their own. |
| 102 | canModerate: access?.can.manage_settings ?? false, |
| 103 | }, |
| 104 | { headers: { "Server-Timing": `load;dur=${Date.now() - started};desc="${cached ? "cached" : "read"}"` } }, |
| 105 | ); |
| 106 | } |
| 107 | |
| 108 | export async function action({ request, params, context }: Route.ActionArgs) { |
| 109 | assertSameOrigin(request); |
| 110 | const user = requireUser(context, request); |
| 111 | const form = await request.formData(); |
| 112 | const path = { namespace: params.owner, name: params.repo }; |
| 113 | const action = String(form.get("action") ?? ""); |
| 114 | const body = String(form.get("body") ?? ""); |
| 115 | if (action === "edit-comment" || action === "delete-comment") { |
| 116 | const id = String(form.get("comment") ?? ""); |
| 117 | const changed = |
| 118 | action === "edit-comment" ? await work.editCommitComment(user, path, id, body) : await work.deleteCommitComment(user, path, id); |
| 119 | return changed.ok ? null : { action, comment: id, error: changed.error.message }; |
| 120 | } |
| 121 | if (action !== "comment") return { action, error: "Unknown action." }; |
| 122 | if (!body.trim()) return { action, error: "Write something first." }; |
| 123 | // On one line of a file it changed, from the diff, or on the whole commit. |
| 124 | const file = String(form.get("path") ?? ""); |
| 125 | const line = Number(form.get("line")); |
| 126 | const added = await work.addCommitComment( |
| 127 | user, |
| 128 | path, |
| 129 | params.hash.toLowerCase(), |
| 130 | body, |
| 131 | file && line > 0 ? { path: file, line } : undefined, |
| 132 | ); |
| 133 | return added.ok ? null : { action, error: added.error.message }; |
| 134 | } |
| 135 | |
| 136 | function CopyHash({ hash }: { hash: string }) { |
| 137 | const [copied, setCopied] = useState(false); |
| 138 | return ( |
| 139 | <Button |
| 140 | type="button" |
| 141 | onClick={() => { |
| 142 | void navigator.clipboard?.writeText(hash).then(() => { |
| 143 | setCopied(true); |
| 144 | setTimeout(() => setCopied(false), 1500); |
| 145 | }); |
| 146 | }} variant="outline" size="inline" className="bg-bg px-2 py-1 font-mono text-xs text-muted" aria-label="Copy the full hash"> |
| 147 | {hash.slice(0, 12)} |
| 148 | {copied ? <Check size={12} className="text-success" /> : <Copy size={12} />} |
| 149 | </Button> |
| 150 | ); |
| 151 | } |
| 152 | |
| 153 | /** The pull request a commit arrived in, once it has been worked out. */ |
| 154 | function MergedIn({ base, pull }: { base: string; pull: Pull }) { |
| 155 | const byAgent = pull.runtime === "hosted"; |
| 156 | return ( |
| 157 | <div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-line px-5 py-3 text-sm"> |
| 158 | <span className="flex items-center gap-2"> |
| 159 | <GitPullRequest size={15} className="text-merged" /> |
| 160 | <span className="text-muted">Merged in</span> |
| 161 | <Link to={`${base}/pull/${pull.number}`} className="font-medium hover:underline"> |
| 162 | {pull.title} <span className="font-normal text-faint">#{pull.number}</span> |
| 163 | </Link> |
| 164 | </span> |
| 165 | {byAgent && ( |
| 166 | <Badge tone="accent" size="md" className="gap-1.5"> |
| 167 | <Sparkles size={12} /> |
| 168 | written by {pull.agent} |
| 169 | </Badge> |
| 170 | )} |
| 171 | <Link |
| 172 | to={`${base}/pull/${pull.number}?tab=session`} |
| 173 | className="ml-auto flex items-center gap-1.5 rounded-md border border-line px-2.5 py-1 text-xs text-muted transition-colors hover:border-line-strong hover:text-fg" |
| 174 | > |
| 175 | <MessagesSquare size={13} /> |
| 176 | Why it was written |
| 177 | </Link> |
| 178 | </div> |
| 179 | ); |
| 180 | } |
| 181 | |
| 182 | export default function CommitPage({ loaderData, actionData, params }: Route.ComponentProps) { |
| 183 | const { commit, pull, comparison, checks, comments, commentsOn, viewer, canModerate } = loaderData; |
| 184 | const said = asComments(comments); |
| 185 | const general = said.filter((comment) => !comment.path); |
| 186 | const base = `/${params.owner}/${params.repo}`; |
| 187 | const { subject, body, trailers } = parseCommitMessage(commit.message); |
| 188 | return ( |
| 189 | <div> |
| 190 | <Card asChild className="overflow-hidden"> |
| 191 | <section> |
| 192 | <div className="p-5"> |
| 193 | <p className="flex items-center gap-2 text-xs text-faint"> |
| 194 | <GitCommitHorizontal size={14} /> |
| 195 | <Link to={`${base}/commits`} className="hover:text-fg"> |
| 196 | Commit |
| 197 | </Link> |
| 198 | </p> |
| 199 | <h2 className="mt-2 text-xl font-semibold tracking-tight text-balance">{subject}</h2> |
| 200 | {body && <p className="mt-3 max-w-3xl text-sm whitespace-pre-wrap text-muted">{body}</p>} |
| 201 | {trailers.length > 0 && ( |
| 202 | <dl className="mt-3 space-y-0.5 font-mono text-xs text-faint"> |
| 203 | {trailers.map((trailer) => ( |
| 204 | <div key={`${trailer.key}:${trailer.value}`}> |
| 205 | <dt className="inline">{trailer.key}:</dt> <dd className="inline text-muted">{trailer.value}</dd> |
| 206 | </div> |
| 207 | ))} |
| 208 | </dl> |
| 209 | )} |
| 210 | </div> |
| 211 | <div className="flex flex-wrap items-center gap-x-5 gap-y-3 border-t border-line bg-bg/40 px-5 py-3 text-sm"> |
| 212 | <span className="flex items-center gap-2"> |
| 213 | <CommitAvatars commit={commit} size={20} /> |
| 214 | <span className="font-medium"> |
| 215 | <CommitNames commit={commit} all /> |
| 216 | </span> |
| 217 | <span className="text-muted"> |
| 218 | committed <TimeAgo at={commit.authoredAt} /> |
| 219 | </span> |
| 220 | </span> |
| 221 | <span className="flex items-center gap-2 text-xs text-muted"> |
| 222 | {commit.parents.length === 0 ? ( |
| 223 | "The first commit" |
| 224 | ) : ( |
| 225 | <> |
| 226 | {commit.parents.length === 1 ? "Parent" : "Parents"} |
| 227 | {commit.parents.map((parent) => ( |
| 228 | <Link |
| 229 | key={parent} |
| 230 | to={`${base}/commit/${parent}`} |
| 231 | prefetch="intent" |
| 232 | className="font-mono text-fg/80 hover:text-accent hover:underline" |
| 233 | > |
| 234 | {parent.slice(0, 7)} |
| 235 | </Link> |
| 236 | ))} |
| 237 | </> |
| 238 | )} |
| 239 | </span> |
| 240 | <span className="ml-auto flex items-center gap-2"> |
| 241 | <CommitChecksBadge checks={checks} sha={commit.hash} /> |
| 242 | <Link |
| 243 | to={`${base}/tree/${commit.hash}/`} |
| 244 | className="rounded-md px-2 py-1 text-xs text-muted hover:bg-raised hover:text-fg" |
| 245 | > |
| 246 | Browse files |
| 247 | </Link> |
| 248 | <CopyHash hash={commit.hash} /> |
| 249 | </span> |
| 250 | </div> |
| 251 | <Suspense |
| 252 | fallback={ |
| 253 | <div aria-busy="true" className="flex h-12 items-center gap-3 border-t border-line px-4"> |
| 254 | <Skeleton className="size-4 rounded-full" /> |
| 255 | <Skeleton className="h-3 w-64 max-w-[60%]" /> |
| 256 | </div> |
| 257 | } |
| 258 | > |
| 259 | <Await resolve={pull}>{(pull) => (pull ? <MergedIn base={base} pull={pull} /> : null)}</Await> |
| 260 | </Suspense> |
| 261 | </section> |
| 262 | </Card> |
| 263 | <div className="mt-6"> |
| 264 | <DiffView |
| 265 | comparison={comparison} |
| 266 | repo={base} |
| 267 | empty="This commit changes no files." |
| 268 | fileBase={`${base}/blob/${commit.hash}`} |
| 269 | review={{ comments: said.filter((comment) => comment.path), canComment: viewer != null && commentsOn }} |
| 270 | /> |
| 271 | </div> |
| 272 | <section aria-labelledby="commit-comments" className="mt-10 space-y-4"> |
| 273 | <h3 id="commit-comments" className="flex items-center gap-2 text-sm font-medium"> |
| 274 | <MessagesSquare size={15} className="text-faint" /> |
| 275 | {general.length === 0 ? "Comments" : `${general.length} ${general.length === 1 ? "comment" : "comments"}`} |
| 276 | {said.length > general.length && ( |
| 277 | <span className="font-normal text-faint"> |
| 278 | · {said.length - general.length} on lines above |
| 279 | </span> |
| 280 | )} |
| 281 | </h3> |
| 282 | <CommentList |
| 283 | comments={general} |
| 284 | base={base} |
| 285 | // Commit comments name their author by username. |
| 286 | viewerId={viewer?.username ?? null} |
| 287 | canModerate={canModerate} |
| 288 | failed={actionData && "comment" in actionData ? { comment: String(actionData.comment), error: actionData.error } : null} |
| 289 | /> |
| 290 | {commentsOn ? ( |
| 291 | <CommentForm author={viewer?.username ?? null} resetKey={said.length} /> |
| 292 | ) : ( |
| 293 | <Card className="flex items-center gap-2.5 px-4 py-3 text-sm text-muted"> |
| 294 | <MessageSquareOff size={15} className="shrink-0 text-faint" /> |
| 295 | Comments on commits are turned off in this repository. |
| 296 | </Card> |
| 297 | )} |
| 298 | {actionData?.action === "comment" && <ErrorText>{actionData.error}</ErrorText>} |
| 299 | </section> |
| 300 | </div> |
| 301 | ); |
| 302 | } |