steid

@jamesgill /

Rust15.8 KBCode·Blame·History·Raw
1//! The owner's home page — `/{handle}`. The handle is a person or an organisation.
2//!
3//! Public. This is the first page that renders for anonymous visitors, so everything it
4//! shows comes from [`PublicProfile`](crate::application::PublicProfile), which has no
5//! private fields to leak.
6
7use topcoat::{
8 Result,
9 context::Cx,
10 router::{
11 error::{RouterErrorExt, not_found},
12 page, path_param, query_params,
13 },
14 view::{component, view},
15};
16
17use crate::{
18 application::{Paged, PublicProfile, RepoSummary, Stores, list_repos, view_profile},
19 components::{
20 badge::{BadgeVariant, badge},
21 button::{ButtonSize, ButtonVariant, button_variants},
22 },
23 domain::{ImportState, OrgName},
24};
25
26use super::{
27 atom::{feed_link, profile_feed_path},
28 context::{current_actor, memberships, orgs, repos, server_error},
29 format::ago,
30 layout::narrow,
31 paging::{Pages, list_pages, requested_page, showing},
32};
33
34/// `{handle}` from the path. The struct name snake-cased is the parameter name.
35///
36/// Declared as `str` so the raw segment arrives unparsed — validation is `OrgName`'s
37/// job, and a handle that fails it is a page that does not exist rather than a bad
38/// request.
39#[path_param]
40struct Handle(str);
41
42/// `?page=N` on the Repositories tab.
43#[query_params(error = bad_request)]
44struct PageQuery {
45 page: Option<String>,
46}
47
48/// Resolves `{handle}` from the path, or 404.
49///
50/// A malformed handle 404s rather than erroring: `/Not A Handle` is a page that does
51/// not exist, not a bad request.
52///
53/// Shared with `/api`, which resolves the same segment without wanting a profile —
54/// listing repositories under a handle needs the handle and nothing else.
55pub(super) fn handle_param(cx: &Cx) -> Result<OrgName> {
56 Ok(OrgName::new(path_param::<Handle>(cx)).map_err(|_| not_found())?)
57}
58
59/// Resolves `{handle}` from the path into a profile, or 404.
60pub(super) async fn profile_for(cx: &Cx) -> Result<PublicProfile> {
61 let handle = handle_param(cx)?;
62 let actor = current_actor(cx).await?;
63
64 Ok(view_profile(&handle, &actor, &orgs(cx), &memberships(cx))
65 .await
66 .map_err(server_error)?
67 .ok_or_not_found()?)
68}
69
70/// How many repositories the overview previews before deferring to the index.
71///
72/// Small on purpose. The overview is a shopfront, not an inventory — the tab is where
73/// completeness lives.
74const PREVIEW: usize = 5;
75
76/// Which tab is lit.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub(super) enum Tab {
79 Overview,
80 Repositories,
81}
82
83/// The identity block and the tab bar, shared by every page that is *about a handle*
84/// rather than about a thing inside one.
85///
86/// Flat navigation rather than stacked sections: an empty section stops being a visible
87/// failure on the front page and becomes a destination that happens to be empty. See
88/// `plans/ui.md`.
89/// The parameter is `identity`, not `profile`: the `#[page] async fn profile` below puts
90/// a unit struct of that name in module scope, which shadows a parameter sharing it.
91#[component]
92pub(super) async fn profile_chrome(
93 identity: &PublicProfile,
94 active: Tab,
95 repo_count: usize,
96) -> Result {
97 let handle = identity.handle.as_str();
98 let overview = format!("/{handle}");
99 let repositories = format!("/{handle}/repos");
100 let settings = format!("/{handle}/settings");
101 let count = repo_count.to_string();
102
103 view! {
104 <header>
105 <h1 class="text-xl font-semibold tracking-tight">(&identity.label)</h1>
106 <p class="mt-0.5 font-mono text-[13px] text-muted-foreground">"@" (handle)</p>
107 ({
108 match &identity.bio {
109 Some(bio) => view! {
110 <p class="mt-3.5 max-w-lg text-sm leading-relaxed text-muted-foreground">(bio)</p>
111 },
112 None => view! {},
113 }
114 }?)
115 </header>
116
117 <nav class="mt-8 flex items-center gap-6 border-b border-border text-[13px]">
118 tab_link(
119 href: overview.as_str(),
120 label: "Overview",
121 count: "",
122 active: active == Tab::Overview,
123 )
124 tab_link(
125 href: repositories.as_str(),
126 label: "Repositories",
127 count: count.as_str(),
128 active: active == Tab::Repositories,
129 )
130
131 if identity.viewer_is_owner {
132 <a
133 href=(settings.as_str())
134 class="ml-auto -mb-px border-b-2 border-transparent pb-2.5 text-muted-foreground hover:text-foreground"
135 >"Settings"</a>
136 }
137 </nav>
138 }
139}
140
141/// One tab. A plain link, so every tab is a real URL and none of this needs JavaScript.
142#[component]
143async fn tab_link(href: &str, label: &str, count: &str, active: bool) -> Result {
144 view! {
145 <a
146 href=(href)
147 class=(if active {
148 "-mb-px border-b-2 border-foreground pb-2.5 font-medium text-foreground"
149 } else {
150 "-mb-px border-b-2 border-transparent pb-2.5 text-muted-foreground hover:text-foreground"
151 })
152 >
153 (label)
154 if !count.is_empty() {
155 <span class="ml-1.5 text-xs text-muted-foreground/60">(count)</span>
156 }
157 </a>
158 }
159}
160
161/// The pinned repository, given weight by everything except size.
162///
163/// Eyebrow, a heavier weight, a roomier description and a rule beneath it —
164/// `plans/ui.md` records why scale is deliberately not one of the devices.
165#[component]
166async fn lead(handle: &str, repo: &RepoSummary) -> Result {
167 view! {
168 <section class="mt-8 border-b border-border/60 pb-8">
169 <p class="text-[11px] font-medium uppercase tracking-[0.1em] text-muted-foreground/70">
170 "Recently active"
171 </p>
172 <div class="mt-2 flex items-baseline gap-2">
173 <a
174 href=(format!("/{handle}/repos/{}", repo.name))
175 class="text-sm font-semibold hover:underline"
176 >(repo.name.as_str())</a>
177 if !repo.visibility.is_public() {
178 badge(variant: BadgeVariant::Outline, "Private")
179 }
180 if repo.archived {
181 badge(variant: BadgeVariant::Outline, "Archived")
182 }
183 match repo.import_state {
184 Some(state) => badge(
185 variant: BadgeVariant::Outline,
186 (import_label(state))
187 ),
188 None => "",
189 }
190 </div>
191 ({
192 match &repo.description {
193 Some(description) => view! {
194 <p class="mt-2 max-w-lg text-sm leading-relaxed text-muted-foreground">
195 (description)
196 </p>
197 },
198 None => view! {},
199 }
200 }?)
201 <p class="mt-2.5 font-mono text-[11px] text-muted-foreground/80">
202 "updated " (ago(repo.updated_at))
203 </p>
204 </section>
205 }
206}
207
208/// What a listing row says about an import.
209///
210/// "Importing" on a row that failed an hour ago would be a lie, and the two are equally
211/// worth a badge: one says wait, the other says do something.
212fn import_label(state: ImportState) -> &'static str {
213 match state {
214 ImportState::Importing => "Importing",
215 ImportState::Failed => "Import failed",
216 }
217}
218
219/// A flat list of repositories. Rows and hairlines, never boxes.
220#[component]
221pub(super) async fn repo_rows(handle: &str, repos: &[RepoSummary]) -> Result {
222 view! {
223 <div class="mt-1">
224 for repo in repos {
225 <a
226 href=(format!("/{handle}/repos/{}", repo.name))
227 class="group -mx-2.5 flex items-baseline justify-between gap-4 rounded px-2.5 py-2.5 hover:bg-surface"
228 >
229 <div>
230 <div class="flex items-baseline gap-2">
231 <span class="text-sm font-medium group-hover:underline">
232 (repo.name.as_str())
233 </span>
234 if !repo.visibility.is_public() {
235 badge(variant: BadgeVariant::Outline, "Private")
236 }
237 if repo.archived {
238 badge(variant: BadgeVariant::Outline, "Archived")
239 }
240 // A row that leads nowhere useful yet says so here rather
241 // than only on the page behind it: a listing is where an
242 // owner notices an import that has not landed.
243 match repo.import_state {
244 Some(state) => badge(
245 variant: BadgeVariant::Outline,
246 (import_label(state))
247 ),
248 None => "",
249 }
250 </div>
251 ({
252 match &repo.description {
253 Some(description) => view! {
254 <p class="mt-0.5 text-[13px] leading-snug text-muted-foreground">
255 (description)
256 </p>
257 },
258 None => view! {},
259 }
260 }?)
261 </div>
262 <span class="shrink-0 font-mono text-[11px] text-muted-foreground">
263 (ago(repo.updated_at))
264 </span>
265 </a>
266 }
267 </div>
268 }
269}
270
271#[page("/{handle}")]
272async fn profile(cx: &Cx) -> Result {
273 let profile = profile_for(cx).await?;
274
275 // The handle resolved above, so `None` here is impossible; an empty list is the
276 // right answer either way rather than a 500.
277 // Every repository, not a page: the overview picks the pinned one out of the whole
278 // list and counts the rest, then previews five.
279 let listed = list_repos(
280 &profile.handle,
281 &current_actor(cx).await?,
282 None,
283 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
284 )
285 .await
286 .map_err(server_error)?
287 .map(|paged| paged.items)
288 .unwrap_or_default();
289
290 // The lead comes out of the listing rather than a second query, so the two can
291 // never disagree about which repository is pinned.
292 let lead_repo = listed.iter().find(|repo| repo.pinned).cloned();
293 let rest: Vec<RepoSummary> = listed
294 .iter()
295 .filter(|repo| !repo.pinned)
296 .take(PREVIEW)
297 .cloned()
298 .collect();
299 let more = listed
300 .len()
301 .saturating_sub(rest.len() + usize::from(lead_repo.is_some()));
302 let handle = profile.handle.to_string();
303 let feed = profile_feed_path(&handle);
304
305 view! {
306 narrow(
307 profile_chrome(identity: &profile, active: Tab::Overview, repo_count: listed.len())
308
309 ({
310 match &lead_repo {
311 Some(repo) => view! { lead(handle: handle.as_str(), repo: repo) },
312 None => view! {},
313 }
314 }?)
315
316 if !rest.is_empty() {
317 <section class="mt-8">
318 <div class="flex items-baseline justify-between">
319 <div class="flex items-baseline gap-3">
320 <h2 class="text-[11px] font-medium uppercase tracking-[0.1em] text-muted-foreground/70">
321 "Repositories"
322 </h2>
323 // Beside the heading rather than in the tab bar: the feed is
324 // of what happens *to* these, and this is where they are.
325 // Outside the `h2` so it does not inherit its casing and
326 // tracking and read as part of the label.
327 feed_link(href: feed.as_str())
328 </div>
329 if more > 0 {
330 <a
331 href=(format!("/{handle}/repos"))
332 class="text-xs text-muted-foreground hover:text-foreground"
333 >"All " (listed.len().to_string()) " \u{2192}"</a>
334 }
335 </div>
336 repo_rows(handle: handle.as_str(), repos: &rest)
337 </section>
338 }
339
340 // Nothing to show. A visitor gets silence rather than an empty box advertising
341 // incompleteness; the owner gets the way to fix it.
342 if listed.is_empty() {
343 if profile.viewer_is_owner {
344 <div class="mt-8">
345 <p class="text-sm text-muted-foreground">"No repositories yet."</p>
346 <p class="mt-3">
347 <a
348 href=(format!("/{handle}/repos/new"))
349 class=(button_variants(ButtonVariant::Outline, ButtonSize::Sm))
350 >"New repository"</a>
351 </p>
352 </div>
353 }
354 }
355 )
356 }
357}
358
359/// Every repository under a handle that the viewer may see.
360///
361/// The tab's destination, and where completeness lives — the overview deliberately
362/// previews only [`PREVIEW`] of them.
363#[page("/{handle}/repos")]
364async fn repos_index(cx: &Cx) -> Result {
365 // Not `profile`: the `#[page] async fn profile` above is a unit struct in this
366 // module, so `let profile = …` parses as a unit-struct pattern rather than a new
367 // binding. The error names neither the page nor the shadowing.
368 let identity = profile_for(cx).await?;
369
370 let listed = list_repos(
371 &identity.handle,
372 &current_actor(cx).await?,
373 Some(requested_page(
374 query_params::<PageQuery>(cx)?.page.as_deref(),
375 )),
376 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
377 )
378 .await
379 .map_err(server_error)?
380 .unwrap_or_else(|| Paged::of(Vec::new(), 0, 1, 1));
381
382 let handle = identity.handle.to_string();
383 let new_repo = format!("/{handle}/repos/new");
384 let sentence = showing(
385 listed.offset(),
386 listed.items.len(),
387 listed.total,
388 "repositories",
389 );
390 let pages = Pages::numbered(listed.page, listed.pages, |page| {
391 format!("/{handle}/repos?page={page}")
392 });
393
394 view! {
395 narrow(
396 profile_chrome(identity: &identity, active: Tab::Repositories, repo_count: listed.total)
397
398 if listed.items.is_empty() {
399 <p class="mt-8 text-sm text-muted-foreground">"No repositories yet."</p>
400 if identity.viewer_is_owner {
401 <p class="mt-3">
402 <a
403 href=(new_repo.as_str())
404 class=(button_variants(ButtonVariant::Outline, ButtonSize::Sm))
405 >"New repository"</a>
406 </p>
407 }
408 } else {
409 <div class="mt-6">
410 if identity.viewer_is_owner {
411 <p class="mb-2 flex justify-end">
412 <a
413 href=(new_repo.as_str())
414 class=(button_variants(ButtonVariant::Outline, ButtonSize::Sm))
415 >"New repository"</a>
416 </p>
417 }
418 repo_rows(handle: handle.as_str(), repos: &listed.items)
419 list_pages(summary: sentence.as_str(), pages: &pages)
420 </div>
421 }
422 )
423 }
424}