steid

@jamesgill /

1//! The branches and tags pages — `/{handle}/repos/{name}/branches` and `/tags`.
2//!
3//! The destinations `plans/ui.md` reserved for the counts beside the revision switcher,
4//! which were plain text until these existed because a dead link is worse than a
5//! number.
6//!
7//! **One `git` process each**, and one more only when the list comes back empty, to
8//! tell "nothing pushed yet" from "no tags yet". Everything a row shows — the tip
9//! commit's subject, its sha, its date, which branch is the default — arrives in that
10//! one `for-each-ref`; see [`list_branches`](crate::application::list_branches).
11//!
12//! Both pages sit under the Code tab. They are ways of getting *into* the code rather
13//! than a place of their own, and a tab each for two lists would make the strip advertise
14//! plumbing.
15
16use topcoat::{
17 Result,
18 context::Cx,
19 icon::{icon, iconify::iconify_icon},
20 router::{error::RouterErrorExt, page, query_params},
21 view::{View, attributes, component, view},
22};
23
24use crate::{
25 application::{RefPage, RepoView, Stores, list_branches, list_tags, port::ArchiveFormat},
26 components::badge::{BadgeVariant, badge},
27 domain::{BranchRow, RefName, TagRow},
28};
29
30use super::{
31 archive::archive_url,
32 browse::empty_repo,
33 context::{current_actor, memberships, orgs, queries, repos, server_error, timed_out},
34 format::{ago, timestamp},
35 layout::wide,
36 paging::{Pages, list_pages, requested_page, showing},
37 pulls::new_pull_url,
38 repo::{Tab, clone_url_for, repo_for, repo_header},
39 urls::{encode, log_url, tree_url},
40};
41
42/// `?page=N` on either refs page.
43#[query_params(error = bad_request)]
44struct PageQuery {
45 page: Option<String>,
46}
47
48/// Where the branches page lives. Linked from the toolbar count and the About sidebar.
49pub(super) fn branches_url(handle: &str, name: &str) -> String {
50 format!("/{handle}/repos/{name}/branches")
51}
52
53/// Where the tags page lives.
54pub(super) fn tags_url(handle: &str, name: &str) -> String {
55 format!("/{handle}/repos/{name}/tags")
56}
57
58/// The comparison between the default branch and another one.
59///
60/// **This page does not exist on this branch.** The URL is the contract the compare
61/// feature is being built to, and rendering the link now is what makes the two land as
62/// one working feature rather than as a page nobody can reach.
63///
64/// The refs are encoded whole, slashes included, so `feature/login` stays one segment —
65/// the `...` between them is then the only literal separator, exactly as `/-/` is on a
66/// tree URL.
67fn compare_url(handle: &str, name: &str, base: &RefName, head: &RefName) -> String {
68 format!(
69 "/{handle}/repos/{name}/compare/{}...{}",
70 encode(base.as_str(), false),
71 encode(head.as_str(), false)
72 )
73}
74
75#[page("/{handle}/repos/{name}/branches")]
76async fn branches_page(cx: &Cx) -> Result {
77 let repo = repo_for(cx).await?;
78 let clone = clone_url_for(cx, &repo);
79 let other = tags_url(repo.handle.as_str(), repo.name.as_str());
80
81 let listed = list_branches(
82 &repo.handle,
83 &repo.name,
84 Some(requested_page(
85 query_params::<PageQuery>(cx)?.page.as_deref(),
86 )),
87 &current_actor(cx).await?,
88 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
89 &queries(cx),
90 )
91 .await;
92
93 let listed: RefPage<BranchRow> = match listed {
94 Ok(page) => page.ok_or_not_found()?,
95 Err(error) if timed_out(&error) => {
96 return view! {
97 wide(
98 repo_header(repo: &repo, rev: "", active: Tab::Code)
99 heading(
100 title: "Branches",
101 count: None,
102 other: "Tags",
103 href: other.as_str(),
104 )
105 took_too_long(what: "branches")
106 )
107 };
108 }
109 Err(error) => return Err(server_error(error)),
110 };
111
112 // The default branch is first, because the use case pinned it there. Its name is
113 // also what a comparison is made *against*, so the whole page reads it from the row
114 // rather than spending a process on `symbolic-ref`.
115 let default = listed
116 .rows
117 .items
118 .iter()
119 .find(|row| row.is_default)
120 .map(|row| row.name.clone());
121
122 let at = default.as_ref().map(RefName::as_str).unwrap_or_default();
123 let sentence = showing(
124 listed.rows.offset(),
125 listed.rows.items.len(),
126 listed.rows.total,
127 "branches",
128 );
129 let pages = Pages::numbered(listed.rows.page, listed.rows.pages, |page| {
130 format!(
131 "{}?page={page}",
132 branches_url(repo.handle.as_str(), repo.name.as_str())
133 )
134 });
135
136 view! {
137 wide(
138 repo_header(repo: &repo, rev: at, active: Tab::Code)
139 heading(
140 title: "Branches",
141 count: Some(listed.rows.total),
142 other: "Tags",
143 href: other.as_str(),
144 )
145
146 if listed.repo_is_empty {
147 empty_repo(url: clone.as_str())
148 } else if listed.rows.items.is_empty() {
149 nothing_here("No branches. Every commit in this repository is reachable only by tag or by sha.")
150 } else {
151 <ul class="divide-y divide-border overflow-hidden rounded-lg border border-border">
152 for row in &listed.rows.items {
153 <li>
154 branch_row(repo: &repo, row: row, default: default.as_ref())
155 </li>
156 }
157 </ul>
158 list_pages(summary: sentence.as_str(), pages: &pages)
159 }
160 )
161 }
162}
163
164/// One branch, on one line.
165///
166/// The name is the thing being scanned for, so it leads and is the only thing at full
167/// contrast. Everything after it — subject, sha, date — is the answer to "and what is on
168/// it", and is muted so a column of thirty branches reads as a list of names.
169///
170/// **No ahead/behind count.** It is a `rev-list` per branch, so a repository with twenty
171/// branches would fork twenty extra processes to decorate one page — the fork-per-fact
172/// cost [0006](../../../plans/decisions/0006-git-binary-behind-narrow-ports.md) exists to
173/// bound. It stays out until something keeps git alive between questions.
174#[component]
175async fn branch_row(repo: &RepoView, row: &BranchRow, default: Option<&RefName>) -> Result {
176 let handle = repo.handle.as_str();
177 let name = repo.name.as_str();
178 let tree = tree_url(handle, name, &row.name, &crate::domain::RepoPath::root());
179 let log = log_url(handle, name, row.name.as_str());
180
181 view! {
182 <div class="flex items-center gap-3 px-4 py-2 text-sm">
183 <a href=(tree.as_str()) class="max-w-[45%] shrink-0 truncate font-mono hover:underline">
184 (row.name.as_str())
185 </a>
186 if row.is_default {
187 badge(variant: BadgeVariant::Outline, "default")
188 }
189
190 // Hidden on a phone rather than wrapped: the row is a scanning surface, and
191 // a two-line row breaks the column of names that makes it scannable.
192 <a
193 href=(log.as_str())
194 class="hidden min-w-0 flex-1 truncate text-muted-foreground hover:text-foreground sm:block"
195 >(&row.summary)</a>
196
197 <span class="ml-auto flex shrink-0 items-center gap-3 text-xs text-muted-foreground sm:ml-0">
198 <code class="font-mono">(row.commit.short())</code>
199 // A fixed, right-aligned column: relative dates vary in width, and
200 // without one the sha beside them zig-zags down a list of thirty rows.
201 // Only from `sm` up — on a phone the reserved width is what pushes the
202 // row off the side of the screen.
203 <span class="sm:w-24 sm:text-right" title=(timestamp(row.committed_at))>
204 (ago(row.committed_at))
205 </span>
206 // A fixed slot, kept even on the default branch's row: comparing a
207 // branch with itself is an empty diff so that one row has no link, and
208 // without the slot its sha and date would sit out of line with the rest.
209 // Gone on a phone, with the commit subject: the row keeps what identifies
210 // a branch and drops the secondary action rather than overflowing.
211 //
212 // Two links now, in one slot widened to hold them. **Compare first**: it
213 // is the answer to "what is on this branch", which is what somebody
214 // scanning a branch list is asking, and opening a pull request is what
215 // you do once you have read it. The second is offered only to the owner,
216 // whose submission is the only one that would be accepted.
217 <span class="hidden w-36 text-right sm:block">
218 match default {
219 Some(base) if base != &row.name => {
220 <a
221 href=(compare_url(handle, name, base, &row.name))
222 class="hover:text-foreground"
223 >"Compare"</a>
224 if repo.viewer_is_owner {
225 <span class="px-1.5">"·"</span>
226 <a
227 href=(new_pull_url(
228 handle,
229 name,
230 row.name.as_str(),
231 base.as_str(),
232 ))
233 class="hover:text-foreground"
234 >"Pull request"</a>
235 }
236 }
237 _ => "",
238 }
239 </span>
240 </span>
241 </div>
242 }
243}
244
245#[page("/{handle}/repos/{name}/tags")]
246async fn tags_page(cx: &Cx) -> Result {
247 let repo = repo_for(cx).await?;
248 let clone = clone_url_for(cx, &repo);
249 let other = branches_url(repo.handle.as_str(), repo.name.as_str());
250
251 let listed = list_tags(
252 &repo.handle,
253 &repo.name,
254 Some(requested_page(
255 query_params::<PageQuery>(cx)?.page.as_deref(),
256 )),
257 &current_actor(cx).await?,
258 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
259 &queries(cx),
260 )
261 .await;
262
263 let listed: RefPage<TagRow> = match listed {
264 Ok(page) => page.ok_or_not_found()?,
265 Err(error) if timed_out(&error) => {
266 return view! {
267 wide(
268 repo_header(repo: &repo, rev: "", active: Tab::Code)
269 heading(
270 title: "Tags",
271 count: None,
272 other: "Branches",
273 href: other.as_str(),
274 )
275 took_too_long(what: "tags")
276 )
277 };
278 }
279 Err(error) => return Err(server_error(error)),
280 };
281
282 let sentence = showing(
283 listed.rows.offset(),
284 listed.rows.items.len(),
285 listed.rows.total,
286 "tags",
287 );
288 let pages = Pages::numbered(listed.rows.page, listed.rows.pages, |page| {
289 format!(
290 "{}?page={page}",
291 tags_url(repo.handle.as_str(), repo.name.as_str())
292 )
293 });
294
295 view! {
296 wide(
297 // The tags page names no revision: it is a list of them.
298 repo_header(repo: &repo, rev: "", active: Tab::Code)
299 heading(
300 title: "Tags",
301 count: Some(listed.rows.total),
302 other: "Branches",
303 href: other.as_str(),
304 )
305
306 if listed.repo_is_empty {
307 empty_repo(url: clone.as_str())
308 } else if listed.rows.items.is_empty() {
309 nothing_here(
310 "No tags yet. Push one with "
311 <code class="font-mono text-foreground">"git push --tags"</code>
312 " to see it here."
313 )
314 } else {
315 <ul class="divide-y divide-border overflow-hidden rounded-lg border border-border">
316 for row in &listed.rows.items {
317 <li>tag_row(repo: &repo, row: row)</li>
318 }
319 </ul>
320 list_pages(summary: sentence.as_str(), pages: &pages)
321 }
322 )
323 }
324}
325
326/// One tag, on one line.
327///
328/// The right of the row holds the two archive links the slot was reserved for. They are
329/// the reason a visitor comes to this page rather than to the branches page: a tag is a
330/// release, and downloading one is what you do with a release.
331///
332/// This is also the only entry point a tag's archive has. The sidebar's Download block
333/// renders on the landing page, which has no revision, so it can only ever offer the
334/// default branch — the gap the wave-1 integration pass found.
335#[component]
336async fn tag_row(repo: &RepoView, row: &TagRow) -> Result {
337 let handle = repo.handle.as_str();
338 let name = repo.name.as_str();
339 let tree = tree_url(handle, name, &row.name, &crate::domain::RepoPath::root());
340 let log = log_url(handle, name, row.name.as_str());
341
342 view! {
343 <div class="flex items-center gap-3 px-4 py-2 text-sm">
344 <span class="shrink-0 text-muted-foreground">
345 icon(data: iconify_icon!("feather:tag"), attrs: attributes! { class="size-3.5" })
346 </span>
347 <a href=(tree.as_str()) class="max-w-[45%] shrink-0 truncate font-mono hover:underline">
348 (row.name.as_str())
349 </a>
350 // Only an annotated tag carries one. A lightweight tag has no message of its
351 // own, and showing the commit's subject here would put words in its mouth.
352 if row.annotated {
353 badge(variant: BadgeVariant::Outline, "annotated")
354 }
355
356 match &row.message {
357 Some(message) => <span
358 class="hidden min-w-0 flex-1 truncate text-muted-foreground sm:block"
359 >(message)</span>,
360 None => <span class="hidden flex-1 sm:block"></span>,
361 }
362
363 <span class="ml-auto flex shrink-0 items-center gap-3 text-xs text-muted-foreground sm:ml-0">
364 // The commit the tag names, peeled through the tag object — the log at
365 // the tag is where it can be seen in context.
366 <a href=(log.as_str()) class="font-mono hover:text-foreground">
367 (row.commit.short())
368 </a>
369 <span class="sm:w-24 sm:text-right" title=(timestamp(row.created_at))>
370 (ago(row.created_at))
371 </span>
372 // A fixed slot on the right, like Compare on the branches row, so a
373 // column of tags keeps its dates in line. Hidden below `sm` with the
374 // message: the row keeps what identifies a tag rather than overflowing,
375 // and the archive is still one tap away through the tag's own tree.
376 <span class="hidden shrink-0 items-center gap-1.5 sm:inline-flex">
377 <a
378 href=(archive_url(handle, name, row.name.as_str(), ArchiveFormat::Zip))
379 class="font-mono hover:text-foreground hover:underline"
380 >"zip"</a>
381 "·"
382 <a
383 href=(archive_url(handle, name, row.name.as_str(), ArchiveFormat::TarGz))
384 class="font-mono hover:text-foreground hover:underline"
385 >"tar.gz"</a>
386 </span>
387 </span>
388 </div>
389 }
390}
391
392/// The line above the list: what this page is, how many, and the other one.
393///
394/// The cross-link is the whole navigation between the two pages. Both live under the
395/// Code tab, so the strip cannot say which of them you are on, and having arrived from
396/// one count the visitor usually wants the other.
397#[component]
398async fn heading(title: &str, count: Option<usize>, other: &str, href: &str) -> Result {
399 view! {
400 <div class="mb-2 flex items-baseline gap-2.5">
401 <h2 class="text-sm font-medium">(title)</h2>
402 match count {
403 Some(count) => <span class="font-mono text-xs text-muted-foreground">
404 (count.to_string())
405 </span>,
406 None => "",
407 }
408 <a href=(href) class="ml-auto inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground">
409 (other)
410 icon(data: iconify_icon!("feather:arrow-right"), attrs: attributes! {
411 class="size-3.5"
412 })
413 </a>
414 </div>
415 }
416}
417
418/// A repository that has history but nothing of this kind in it.
419///
420/// Distinct from an empty repository, which gets the push snippet: this one is not
421/// missing a setup step, so telling it how to push would be answering a question it did
422/// not ask.
423#[component]
424async fn nothing_here(#[default] child: View) -> Result {
425 view! {
426 <p class="rounded-lg border border-border px-4 py-10 text-center text-sm text-muted-foreground">
427 (child)
428 </p>
429 }
430}
431
432/// What a read that ran out of time looks like.
433///
434/// A page state rather than a 500: the repository is fine, and the honest thing to say
435/// is that this one question took too long — with reloading offered, because on a
436/// repository this large it may well not the second time.
437#[component]
438async fn took_too_long(what: &str) -> Result {
439 view! {
440 <div class="rounded-lg border border-border px-4 py-10 text-center">
441 <p class="text-sm text-muted-foreground">
442 "Listing this repository's " (what) " took too long."
443 </p>
444 <p class="mt-1 text-xs text-muted-foreground">
445 "Nothing is wrong with the repository — reading it simply ran out of time. Try again."
446 </p>
447 </div>
448 }
449}
450
451#[cfg(test)]
452mod tests {
453 use super::*;
454
455 fn rev(value: &str) -> RefName {
456 RefName::new(value).expect("valid revision")
457 }
458
459 #[test]
460 fn the_pages_live_under_the_repository() {
461 assert_eq!(branches_url("ada", "steid"), "/ada/repos/steid/branches");
462 assert_eq!(tags_url("ada", "steid"), "/ada/repos/steid/tags");
463 }
464
465 #[test]
466 fn a_comparison_names_the_default_branch_first() {
467 assert_eq!(
468 compare_url("ada", "steid", &rev("main"), &rev("spike")),
469 "/ada/repos/steid/compare/main...spike"
470 );
471 }
472
473 #[test]
474 fn a_tag_row_offers_both_archive_formats_at_that_tag() {
475 assert_eq!(
476 archive_url("ada", "steid", "v0.2.0", ArchiveFormat::Zip),
477 "/ada/repos/steid/archive/v0.2.0.zip"
478 );
479 assert_eq!(
480 archive_url("ada", "steid", "release/2.0", ArchiveFormat::TarGz),
481 "/ada/repos/steid/archive/release%2F2.0.tar.gz"
482 );
483 }
484
485 #[test]
486 fn a_refs_slashes_are_encoded_so_the_separator_stays_the_only_one() {
487 // Otherwise `feature/login` would look like extra path segments, which is the
488 // same ambiguity `/-/` removes on a tree URL.
489 assert_eq!(
490 compare_url("ada", "steid", &rev("main"), &rev("feature/login")),
491 "/ada/repos/steid/compare/main...feature%2Flogin"
492 );
493 }
494}