steid

@jamesgill /

Rust31.7 KBCode·Blame·History·Raw
1//! Labels — `/{handle}/repos/{name}/labels`.
2//!
3//! One page, two doors: the issues toolbar and the repository settings section list.
4//! It sits inside the repository frame under the Issues tab rather than under Settings,
5//! because a label is a thing you reach for while looking at issues — the settings entry
6//! is the second way in, not the page's home.
7//!
8//! **Readable by anyone who can read the repository, writable only by its owner.** The
9//! pills are already on the issues list, so a legend nobody may read would be a legend
10//! that does not work; the use cases decide both, and the guards here only keep a form
11//! from rendering for someone whose submission would be refused anyway.
12//!
13//! The colour control is a row of eight radio inputs drawn as swatches — see
14//! `styles.css`. There is no hex field and there will not be one: ui.md's rule is theme
15//! tokens, never raw colours.
16
17use std::time::SystemTime;
18
19use serde::Deserialize;
20use topcoat::{
21 Result,
22 context::Cx,
23 icon::{icon, iconify::iconify_icon},
24 router::{
25 StatusCode,
26 content::Form,
27 error::{bad_request, not_found},
28 page, path_param, query_params,
29 },
30 view::{attributes, component, view},
31};
32
33use crate::{
34 application::{
35 Error, LabelEdit, LabelPage, LabelRow, LabelView, NewLabel, RepoView, create_label,
36 delete_label, list_labels, set_issue_labels, set_pull_labels, update_label,
37 },
38 components::{
39 button::{ButtonSize, ButtonVariant, button},
40 flash::{FlashKind, flash},
41 input::input,
42 label::label,
43 },
44 domain::{DomainError, IssueNumber, Label, LabelColour, LabelId},
45};
46
47use super::{
48 context::{
49 current_actor, issues, labels, location, memberships, orgs, pulls, repos, server_error,
50 },
51 layout::wide,
52 repo::{Tab, repo_for, repo_header},
53};
54
55/// `{id}` from the path — a label's id.
56///
57/// Named for the parameter, not for what it identifies: a `#[path_param]` struct's name
58/// snake-cased **is** the URL parameter, so a struct called `Label` would have to be
59/// `{label}` in the route and would then shadow the domain's `Label` in this module.
60#[path_param]
61struct Id(str);
62
63/// `{number}` from the path, on the assignment route. Its own struct rather than
64/// `issues`' because a `#[path_param]` type is module-scoped.
65#[path_param]
66struct Number(str);
67
68/// Set after a delete so the confirmation survives the redirect.
69#[query_params(error = bad_request)]
70struct Removed {
71 removed: Option<String>,
72}
73
74#[derive(Debug, Deserialize)]
75struct LabelForm {
76 name: String,
77 colour: String,
78 description: String,
79}
80
81// --- URLs ---------------------------------------------------------------------------
82
83pub(super) fn labels_url(handle: &str, name: &str) -> String {
84 format!("/{handle}/repos/{name}/labels")
85}
86
87/// The issues list narrowed to one label.
88///
89/// The name goes in the query string rather than the path: it is a filter on a list, not
90/// a place of its own, and a label may be renamed without breaking a URL that anybody
91/// bookmarked as "this repository's issues".
92pub(super) fn filtered_issues_url(handle: &str, name: &str, pill: &str) -> String {
93 format!("/{handle}/repos/{name}/issues?label={}", encode(pill))
94}
95
96/// The same, for the pull request list.
97pub(super) fn filtered_pulls_url(handle: &str, name: &str, pill: &str) -> String {
98 format!("/{handle}/repos/{name}/pulls?label={}", encode(pill))
99}
100
101/// Which list a pill leads to.
102///
103/// A label is on issues and on pull requests alike, so a pill has two possible
104/// destinations and only its surroundings know which: the one you clicked on a pull
105/// request row means "the other requests like this". Issues is the default because that
106/// is where most pills are drawn, and it keeps the existing call sites unchanged.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
108pub(super) enum Filtering {
109 #[default]
110 Issues,
111 Pulls,
112}
113
114impl Filtering {
115 fn url(self, handle: &str, name: &str, pill: &str) -> String {
116 match self {
117 Self::Issues => filtered_issues_url(handle, name, pill),
118 Self::Pulls => filtered_pulls_url(handle, name, pill),
119 }
120 }
121}
122
123/// Percent-encodes a label name for a query string.
124///
125/// Hand-rolled because the one thing that needs escaping here is small and known: a name
126/// is a single line of at most fifty characters, and everything outside the unreserved
127/// set is encoded rather than guessed at.
128pub(super) fn encode(value: &str) -> String {
129 let mut encoded = String::with_capacity(value.len());
130
131 for byte in value.as_bytes() {
132 match byte {
133 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
134 encoded.push(*byte as char)
135 }
136 other => encoded.push_str(&format!("%{other:02X}")),
137 }
138 }
139
140 encoded
141}
142
143// --- Resolution -----------------------------------------------------------------------
144
145/// The repository, refused for anyone who does not own it.
146///
147/// A 404 rather than a 403, the rule the settings page sets: a 403 on a repository they
148/// cannot see would confirm it exists.
149async fn owned(cx: &Cx) -> Result<RepoView> {
150 let repo = repo_for(cx).await?;
151
152 if !repo.viewer_is_owner {
153 return Err(not_found().into());
154 }
155
156 Ok(repo)
157}
158
159async fn listing(cx: &Cx, repo: &RepoView) -> Result<LabelPage> {
160 list_labels(
161 &current_actor(cx).await?,
162 &repo.handle,
163 &repo.name,
164 &orgs(cx),
165 &memberships(cx),
166 &repos(cx),
167 &labels(cx),
168 )
169 .await
170 .map_err(server_error)?
171 // `repo_for` already resolved the repository as visible, so `None` here means it
172 // vanished between the two reads.
173 .ok_or_else(|| not_found().into())
174}
175
176/// Turns a use case failure into either a message to re-render with, or a response.
177fn write_failure(error: Error) -> std::result::Result<String, topcoat::Error> {
178 match error {
179 Error::Domain(DomainError::Validation { field, reason }) => {
180 Ok(format!("That {field} is no good: {reason}."))
181 }
182 // Both are "no such label of yours" by the time they reach a page whose guard
183 // already checked ownership.
184 Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. }) => {
185 Err(not_found().into())
186 }
187 other => Err(server_error(std::io::Error::other(other.to_string()))),
188 }
189}
190
191/// The colour a form posted, or a bad request.
192///
193/// A value the palette cannot name is a tampered form, not something to default:
194/// defaulting would silently save a label in a colour nobody chose.
195fn colour_of(value: &str) -> Result<LabelColour> {
196 value
197 .parse::<LabelColour>()
198 .map_err(|_| bad_request("unknown label colour").into())
199}
200
201/// A description field, absent rather than empty when nothing was typed.
202fn described(value: &str) -> Option<String> {
203 let trimmed = value.trim();
204
205 (!trimmed.is_empty()).then(|| trimmed.to_owned())
206}
207
208// --- The page -------------------------------------------------------------------------
209
210#[page("/{handle}/repos/{name}/labels")]
211async fn labels_page(cx: &Cx) -> Result {
212 let repo = repo_for(cx).await?;
213 let listed = listing(cx, &repo).await?;
214 let removed = query_params::<Removed>(cx)?.removed.is_some();
215
216 view! {
217 wide(
218 repo_header(repo: &repo, rev: "", active: Tab::Issues)
219 labels_view(
220 handle: repo.handle.as_str(),
221 name: repo.name.as_str(),
222 listed: &listed,
223 notice: Notice { removed, ..Notice::default() },
224 )
225 )
226 }
227}
228
229/// Adds a label, then redirects so a reload cannot repeat it.
230#[page(POST "/{handle}/repos/{name}/labels")]
231async fn add(cx: &Cx, Form(submitted): Form<LabelForm>) -> Result {
232 let repo = owned(cx).await?;
233 let colour = colour_of(&submitted.colour)?;
234
235 let outcome = create_label(
236 &current_actor(cx).await?,
237 &repo.handle,
238 &repo.name,
239 &NewLabel {
240 name: submitted.name.clone(),
241 colour,
242 description: described(&submitted.description),
243 },
244 SystemTime::now(),
245 &orgs(cx),
246 &memberships(cx),
247 &repos(cx),
248 &labels(cx),
249 )
250 .await;
251
252 let message = match outcome {
253 Ok(()) => {
254 return view! {
255 (StatusCode::SEE_OTHER)
256 (location(&labels_url(repo.handle.as_str(), repo.name.as_str()))?)
257 };
258 }
259 Err(error) => write_failure(error)?,
260 };
261
262 // Re-rendered with what was typed. Bouncing back to an empty form would throw away
263 // the name and the colour to say the name was taken.
264 let listed = listing(cx, &repo).await?;
265
266 view! {
267 wide(
268 repo_header(repo: &repo, rev: "", active: Tab::Issues)
269 labels_view(
270 handle: repo.handle.as_str(),
271 name: repo.name.as_str(),
272 listed: &listed,
273 notice: Notice {
274 error: message.as_str(),
275 typed: submitted.name.as_str(),
276 described: submitted.description.as_str(),
277 colour,
278 ..Notice::default()
279 },
280 )
281 )
282 }
283}
284
285/// Renames, recolours or redescribes one label.
286#[page(POST "/{handle}/repos/{name}/labels/{id}/edit")]
287async fn edit(cx: &Cx, Form(submitted): Form<LabelForm>) -> Result {
288 let repo = owned(cx).await?;
289 let id = LabelId::from_trusted(path_param::<Id>(cx));
290 let colour = colour_of(&submitted.colour)?;
291
292 let outcome = update_label(
293 &current_actor(cx).await?,
294 &repo.handle,
295 &repo.name,
296 &id,
297 &LabelEdit {
298 name: submitted.name.clone(),
299 colour,
300 description: described(&submitted.description),
301 },
302 &orgs(cx),
303 &memberships(cx),
304 &repos(cx),
305 &labels(cx),
306 )
307 .await;
308
309 let message = match outcome {
310 Ok(()) => {
311 return view! {
312 (StatusCode::SEE_OTHER)
313 (location(&labels_url(repo.handle.as_str(), repo.name.as_str()))?)
314 };
315 }
316 Err(error) => write_failure(error)?,
317 };
318
319 // The row's panel is opened on the label that was refused, so the reason is visible
320 // and so is what caused it.
321 let listed = listing(cx, &repo).await?;
322
323 view! {
324 wide(
325 repo_header(repo: &repo, rev: "", active: Tab::Issues)
326 labels_view(
327 handle: repo.handle.as_str(),
328 name: repo.name.as_str(),
329 listed: &listed,
330 notice: Notice {
331 error: message.as_str(),
332 editing: Some(&id),
333 ..Notice::default()
334 },
335 )
336 )
337 }
338}
339
340/// Removes a label, then redirects so a reload cannot repeat it.
341#[page(POST "/{handle}/repos/{name}/labels/{id}/delete")]
342async fn remove(cx: &Cx) -> Result {
343 let repo = owned(cx).await?;
344 let id = LabelId::from_trusted(path_param::<Id>(cx));
345
346 match delete_label(
347 &current_actor(cx).await?,
348 &repo.handle,
349 &repo.name,
350 &id,
351 &orgs(cx),
352 &memberships(cx),
353 &repos(cx),
354 &labels(cx),
355 )
356 .await
357 {
358 Ok(()) => {}
359 // Already gone, or never this repository's. Both leave the list looking the way
360 // the visitor wanted it.
361 Err(Error::Domain(DomainError::NotFound { .. })) => {}
362 Err(other) => {
363 write_failure(other)?;
364 }
365 }
366
367 view! {
368 (StatusCode::SEE_OTHER)
369 (location(&format!(
370 "{}?removed",
371 labels_url(repo.handle.as_str(), repo.name.as_str())
372 ))?)
373 }
374}
375
376/// Replaces an issue's labels with what the checkboxes say.
377///
378/// `Form<Vec<(String, String)>>` rather than a struct: a checkbox list posts the same key
379/// once per tick, which no struct field can hold. Reading the raw pairs is also what
380/// makes "none ticked" arrive as an empty set rather than as a missing field.
381#[page(POST "/{handle}/repos/{name}/issues/{number}/labels")]
382async fn set_labels(cx: &Cx, Form(submitted): Form<Vec<(String, String)>>) -> Result {
383 let repo = owned(cx).await?;
384
385 let number = path_param::<Number>(cx)
386 .parse::<IssueNumber>()
387 .map_err(|_| not_found())?;
388
389 let chosen: Vec<LabelId> = submitted
390 .into_iter()
391 .filter(|(field, _)| field == "label")
392 .map(|(_, id)| LabelId::from_trusted(id))
393 .collect();
394
395 match set_issue_labels(
396 &current_actor(cx).await?,
397 &repo.handle,
398 &repo.name,
399 number,
400 &chosen,
401 &orgs(cx),
402 &memberships(cx),
403 &repos(cx),
404 &issues(cx),
405 &labels(cx),
406 )
407 .await
408 {
409 Ok(()) => {}
410 // Nothing typed to preserve and nothing to explain — an id that is not this
411 // repository's is a tampered form, not a mistake somebody made.
412 Err(error) => {
413 write_failure(error)?;
414 }
415 }
416
417 view! {
418 (StatusCode::SEE_OTHER)
419 (location(&format!(
420 "/{}/repos/{}/issues/{number}",
421 repo.handle, repo.name
422 ))?)
423 }
424}
425
426/// Replaces a pull request's labels with what the checkboxes say.
427///
428/// The issue route's twin, and it lives here beside it rather than in
429/// [`pulls`](super::pulls): the form, the `Vec<(String, String)>` reading and the
430/// tampered-id rule are the same three things, and two copies would be two places for
431/// them to drift.
432#[page(POST "/{handle}/repos/{name}/pulls/{number}/labels")]
433async fn set_pull_request_labels(cx: &Cx, Form(submitted): Form<Vec<(String, String)>>) -> Result {
434 let repo = owned(cx).await?;
435
436 let number = path_param::<Number>(cx)
437 .parse::<IssueNumber>()
438 .map_err(|_| not_found())?;
439
440 let chosen: Vec<LabelId> = submitted
441 .into_iter()
442 .filter(|(field, _)| field == "label")
443 .map(|(_, id)| LabelId::from_trusted(id))
444 .collect();
445
446 match set_pull_labels(
447 &current_actor(cx).await?,
448 &repo.handle,
449 &repo.name,
450 number,
451 &chosen,
452 &orgs(cx),
453 &memberships(cx),
454 &repos(cx),
455 &pulls(cx),
456 &labels(cx),
457 )
458 .await
459 {
460 Ok(()) => {}
461 Err(error) => {
462 write_failure(error)?;
463 }
464 }
465
466 view! {
467 (StatusCode::SEE_OTHER)
468 (location(&format!(
469 "/{}/repos/{}/pulls/{number}",
470 repo.handle, repo.name
471 ))?)
472 }
473}
474
475// --- Shared components ------------------------------------------------------------------
476
477/// One label, drawn as a pill, linking to the issues it is on.
478///
479/// A link everywhere it appears — on a list row, on an issue, on this page — because
480/// "what else is like this" is the only question a label prompts. The colour class is
481/// built here rather than being a Tailwind utility: see the note above `.label-pill` in
482/// `styles.css`.
483#[component]
484pub(super) async fn label_pill(
485 handle: &str,
486 name: &str,
487 pill: &LabelView,
488 /// Which list to lead to. Issues unless the pill is drawn on a pull request.
489 #[default]
490 to: Filtering,
491) -> Result {
492 view! {
493 <a
494 href=(to.url(handle, name, &pill.name))
495 class=(format!("label-pill label-{}", pill.colour))
496 title=(pill.description.as_deref().unwrap_or(""))
497 >(pill.name.as_str())</a>
498 }
499}
500
501/// The eight swatches, as radio inputs.
502#[component]
503async fn swatches(field: &str, chosen: LabelColour) -> Result {
504 view! {
505 <div class="flex flex-wrap items-center gap-2">
506 for colour in LabelColour::ALL {
507 <label class=(format!("label-swatch label-{colour}")) title=(colour.as_str())>
508 <input
509 type="radio"
510 name=(field)
511 value=(colour.as_str())
512 checked=(colour == chosen)
513 />
514 <span></span>
515 </label>
516 }
517 </div>
518 }
519}
520
521// --- The view ---------------------------------------------------------------------------
522
523/// What the page has to say about the last thing that happened, grouped so the view takes
524/// one argument for it rather than five that must stay in the same order at three call
525/// sites — the shape `webhook.rs`'s `Notice` already uses.
526#[derive(Debug, Clone, Copy, Default)]
527struct Notice<'a> {
528 removed: bool,
529 error: &'a str,
530 /// A name that was rejected, put back in the add form.
531 typed: &'a str,
532 /// A description that was rejected, put back with it.
533 described: &'a str,
534 /// The colour that was chosen when it was rejected.
535 colour: LabelColour,
536 /// The row whose panel starts open — the one whose edit was refused.
537 editing: Option<&'a LabelId>,
538}
539
540#[component]
541async fn labels_view(handle: &str, name: &str, listed: &LabelPage, notice: Notice<'_>) -> Result {
542 let Notice {
543 removed,
544 error,
545 typed,
546 described,
547 colour,
548 editing,
549 } = notice;
550
551 view! {
552 <div class="max-w-3xl">
553 <div class="flex flex-wrap items-baseline gap-x-3 gap-y-1">
554 <h1 class="text-lg font-semibold tracking-tight">"Labels"</h1>
555 <span class="font-mono text-xs text-muted-foreground">(listed.labels.len())</span>
556 <a
557 href=(format!("/{handle}/repos/{name}/issues"))
558 class="ml-auto text-sm text-muted-foreground hover:text-foreground"
559 >"Back to issues"</a>
560 </div>
561 <p class="mt-1 text-sm text-muted-foreground">
562 "A label is this repository's own — the same word on another repository is "
563 "a different label. Issues and pull requests share the set; click a pill "
564 "for the issues, or the count for the pull requests."
565 </p>
566
567 if removed {
568 <div class="mt-4">
569 flash(kind: FlashKind::Success, "Label deleted. The issues that had it kept everything else.")
570 </div>
571 }
572
573 if !error.is_empty() {
574 <div class="mt-4">
575 flash(kind: FlashKind::Error, (error))
576 </div>
577 }
578
579 if listed.viewer_is_owner {
580 add_form(
581 handle: handle,
582 name: name,
583 typed: typed,
584 described: described,
585 colour: colour,
586 )
587 }
588
589 if listed.labels.is_empty() {
590 <div class="mt-4 rounded-lg border border-border px-4 py-10 text-center">
591 <p class="text-sm text-muted-foreground">"No labels yet."</p>
592 if !listed.viewer_is_owner {
593 <p class="mt-1 text-xs text-muted-foreground">
594 "Only the owner can make one."
595 </p>
596 }
597 </div>
598 } else {
599 <ul class="mt-4 divide-y divide-border rounded-lg border border-border">
600 for row in &listed.labels {
601 label_row(
602 handle: handle,
603 name: name,
604 row: row,
605 editable: listed.viewer_is_owner,
606 open: editing == Some(&row.label.id),
607 )
608 }
609 </ul>
610 }
611 </div>
612 }
613}
614
615/// The add form, in a panel above the list.
616#[component]
617async fn add_form(
618 handle: &str,
619 name: &str,
620 typed: &str,
621 described: &str,
622 colour: LabelColour,
623) -> Result {
624 view! {
625 <form
626 method="post"
627 action=(labels_url(handle, name))
628 class="mt-4 space-y-3 rounded-lg border border-border p-4"
629 >
630 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
631 "New label"
632 </h2>
633
634 // Name and colour on one row: they are the two halves of one decision, and a
635 // row each spent a row on each.
636 <div class="flex flex-wrap items-end gap-x-4 gap-y-3">
637 <div class="min-w-48 flex-1 space-y-2">
638 label(attrs: attributes! { for="label-name" }, "Name")
639 input(attrs: attributes! {
640 id="label-name"
641 name="name"
642 type="text"
643 value=(typed)
644 placeholder="bug"
645 required=(true)
646 autocomplete="off"
647 maxlength=(Label::MAX_NAME_LEN.to_string())
648 })
649 </div>
650 <div class="space-y-2">
651 label(attrs: attributes! { for="" }, "Colour")
652 swatches(field: "colour", chosen: colour)
653 </div>
654 </div>
655
656 <div class="space-y-2">
657 label(attrs: attributes! { for="label-description" }, "Description")
658 input(attrs: attributes! {
659 id="label-description"
660 name="description"
661 type="text"
662 value=(described)
663 placeholder="Something is broken (optional)"
664 autocomplete="off"
665 maxlength=(Label::MAX_DESCRIPTION_LEN.to_string())
666 })
667 </div>
668
669 button(size: ButtonSize::Sm, attrs: attributes! { type="submit" }, "Add label")
670 </form>
671 }
672}
673
674/// One label: the pill, what it means, how much use it gets, and the panel that changes
675/// it.
676///
677/// For the owner the whole row is a `<summary>`, so the panel opens from anywhere on it
678/// rather than from a four-pixel word at the end. The pill and the count are still links
679/// inside it, which a browser resolves in the link's favour: clicking one navigates
680/// rather than toggling. The row **must not** be a `display: contents` disclosure —
681/// tried, and the panel becomes a flex sibling of the row's own items and lands beside
682/// them instead of under them.
683#[component]
684async fn label_row(handle: &str, name: &str, row: &LabelRow, editable: bool, open: bool) -> Result {
685 let id = row.label.id.as_str();
686 let action = |what: &str| format!("{}/{id}/{what}", labels_url(handle, name));
687
688 view! {
689 <li class="px-4 py-2.5 text-sm">
690 if editable {
691 <details open=(open)>
692 <summary class="flex cursor-pointer list-none flex-wrap items-center gap-x-3 gap-y-1.5">
693 label_summary(handle: handle, name: name, row: row)
694 <span class="shrink-0 text-xs text-muted-foreground">"Edit"</span>
695 </summary>
696
697 <div class="mt-3 space-y-4">
698 <form method="post" action=(action("edit")) class="space-y-3">
699 <div class="flex flex-wrap items-end gap-x-4 gap-y-3">
700 <div class="min-w-48 flex-1 space-y-2">
701 label(attrs: attributes! { for=(format!("name-{id}")) }, "Name")
702 input(attrs: attributes! {
703 id=(format!("name-{id}"))
704 name="name"
705 type="text"
706 value=(row.label.name.as_str())
707 required=(true)
708 autocomplete="off"
709 maxlength=(Label::MAX_NAME_LEN.to_string())
710 })
711 </div>
712 <div class="space-y-2">
713 label(attrs: attributes! { for="" }, "Colour")
714 swatches(field: "colour", chosen: row.label.colour)
715 </div>
716 </div>
717
718 <div class="space-y-2">
719 label(
720 attrs: attributes! { for=(format!("description-{id}")) },
721 "Description"
722 )
723 input(attrs: attributes! {
724 id=(format!("description-{id}"))
725 name="description"
726 type="text"
727 value=(row.label.description.as_deref().unwrap_or(""))
728 autocomplete="off"
729 maxlength=(Label::MAX_DESCRIPTION_LEN.to_string())
730 })
731 </div>
732
733 button(
734 size: ButtonSize::Sm,
735 attrs: attributes! { type="submit" },
736 "Save label"
737 )
738 </form>
739
740 // The confirm, without JavaScript: the checkbox is `required`, so
741 // the button cannot delete anything until it is ticked.
742 // Deliberately behind the same disclosure as the edit form, which
743 // is what keeps a stray click on a list row harmless.
744 <form
745 method="post"
746 action=(action("delete"))
747 class="flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-border pt-3"
748 >
749 <label class="flex items-center gap-2 text-xs text-muted-foreground">
750 <input type="checkbox" name="confirm" value="yes" required=(true) />
751 // What it comes off, counted honestly: a label on nothing
752 // but pull requests must not say "0 issues" and read as
753 // free to delete.
754 if row.issues > 0 || row.pulls > 0 {
755 "Delete this label — it comes off "
756 if row.issues > 0 {
757 (row.issues)
758 if row.issues == 1 { " issue" } else { " issues" }
759 }
760 if row.issues > 0 && row.pulls > 0 { " and " }
761 if row.pulls > 0 {
762 (row.pulls)
763 if row.pulls == 1 {
764 " pull request"
765 } else {
766 " pull requests"
767 }
768 }
769 "."
770 } else {
771 "Delete this label."
772 }
773 </label>
774 button(
775 variant: ButtonVariant::Ghost,
776 size: ButtonSize::Sm,
777 attrs: attributes! {
778 type="submit"
779 class="text-destructive hover:bg-destructive/10"
780 },
781 icon(
782 data: iconify_icon!("feather:trash-2"),
783 attrs: attributes! { class="size-3.5" }
784 )
785 "Delete"
786 )
787 </form>
788 </div>
789 </details>
790 } else {
791 <div class="flex flex-wrap items-center gap-x-3 gap-y-1.5">
792 label_summary(handle: handle, name: name, row: row)
793 </div>
794 }
795 </li>
796 }
797}
798
799/// What a row says whoever is looking at it: the pill, the description, the count.
800#[component]
801async fn label_summary(handle: &str, name: &str, row: &LabelRow) -> Result {
802 view! {
803 label_pill(handle: handle, name: name, pill: &row.label)
804
805 if let Some(description) = row.label.description.as_deref() {
806 <span class="min-w-0 flex-1 truncate text-xs text-muted-foreground">(description)</span>
807 } else {
808 <span class="min-w-0 flex-1"></span>
809 }
810
811 // Both counts, because a label is on two kinds of thing and each links to its
812 // own list. The pull request count is drawn only when there is one: a repository
813 // that labels issues alone should not grow a column of zeroes.
814 <a
815 href=(filtered_issues_url(handle, name, &row.label.name))
816 class="shrink-0 text-xs text-muted-foreground hover:text-foreground"
817 >
818 <span class="font-mono">(row.issues)</span>
819 if row.issues == 1 { " issue" } else { " issues" }
820 </a>
821
822 if row.pulls > 0 {
823 <a
824 href=(filtered_pulls_url(handle, name, &row.label.name))
825 class="shrink-0 text-xs text-muted-foreground hover:text-foreground"
826 >
827 <span class="font-mono">(row.pulls)</span>
828 if row.pulls == 1 { " pull request" } else { " pull requests" }
829 </a>
830 }
831 }
832}
833
834#[cfg(test)]
835mod tests {
836 use crate::domain::LabelColour;
837
838 /// The stylesheet, read at compile time. The palette lives in two places that must
839 /// change together — [`LabelColour::ALL`] and the `--label-*` tokens — and nothing
840 /// but this test connects them: a ninth variant with no tokens renders a pill with
841 /// no tint at all, silently, exactly like every other class Tailwind never sees.
842 const STYLES: &str = include_str!("../../../styles.css");
843
844 /// Tokens under the `--label-` prefix that are not colours: the mix ratios and the
845 /// per-pill tint each rule sets. Listed so the orphan check below can tell "a colour
846 /// nothing declares" from "a knob".
847 const NOT_COLOURS: [&str; 4] = ["fill", "edge", "ink", "tint"];
848
849 #[test]
850 fn every_label_colour_has_its_tokens_in_both_schemes() {
851 for colour in LabelColour::ALL {
852 let name = colour.as_str();
853
854 // Both schemes, because a colour defined in one and missing from the other
855 // reads correctly to whoever wrote it and is invisible to everyone else.
856 assert_eq!(
857 STYLES.matches(&format!("--label-{name}: ")).count(),
858 2,
859 "--label-{name} should be defined for the light and dark schemes"
860 );
861 assert!(
862 STYLES.contains(&format!(".label-{name} {{")),
863 "no .label-{name} rule to give a pill its tint"
864 );
865 }
866 }
867
868 #[test]
869 fn no_token_names_a_colour_that_no_longer_exists() {
870 // The other direction: a variant removed from the enum leaves dead tokens, and
871 // a typo in a token name looks exactly the same as a missing one.
872 for line in STYLES.lines() {
873 let Some(rest) = line.trim().strip_prefix("--label-") else {
874 continue;
875 };
876 let Some(name) = rest.split(':').next() else {
877 continue;
878 };
879
880 if NOT_COLOURS.contains(&name) {
881 continue;
882 }
883
884 assert!(
885 LabelColour::ALL
886 .into_iter()
887 .any(|colour| colour.as_str() == name),
888 "--label-{name} names no LabelColour variant"
889 );
890 }
891 }
892}