steid

@jamesgill /

Rust40.9 KBCode·Blame·History·Raw
1//! Issues — `/{handle}/repos/{name}/issues`.
2//!
3//! Three pages: the list, the new-issue form, and one issue with its conversation.
4//! `new` is a static segment and `{number}` a parameterised one, so the router prefers
5//! `new` — and a number can never be the word `new` anyway, so unlike repository names
6//! there is nothing to reserve.
7//!
8//! **Bodies are markdown, rendered through [`markdown`](super::markdown), which never
9//! passes raw HTML from the source through.** That module writes every tag itself, so a
10//! `<script>` someone types into an issue arrives as visible, inert text. This is user
11//! content on the same origin as the session cookie, so that property is the reason it
12//! can be rendered at all — see that module's header before changing anything here.
13//!
14//! A visitor who may read the repository may read its issues; every write is the
15//! owner's. The use cases decide both — the guards on this page only keep a form from
16//! rendering for someone whose submission would be refused anyway.
17
18use std::time::SystemTime;
19
20use serde::Deserialize;
21use topcoat::{
22 Result,
23 context::Cx,
24 icon::{icon, iconify::iconify_icon},
25 router::{
26 StatusCode,
27 content::Form,
28 error::{bad_request, forbidden, not_found},
29 page, path_param, query_params,
30 },
31 view::{attributes, component, view},
32};
33
34use crate::{
35 application::{
36 CommentView, Error, IssueDetail, IssueEdit, IssueList, IssueSummary, NewIssue, Numbered,
37 RepoView, comment_on_issue, create_issue, edit_issue, list_issues, set_issue_state,
38 view_issue,
39 },
40 components::{
41 badge::{BadgeVariant, badge},
42 button::{ButtonSize, ButtonVariant, button, button_variants},
43 flash::{FlashKind, flash},
44 input::input,
45 label::label,
46 textarea::textarea,
47 },
48 domain::{DomainError, IssueNumber, IssueState, OrgName},
49};
50
51use super::{
52 atom::{feed_link, issues_feed_path},
53 browse::{ago, timestamp},
54 context::{
55 current_actor, issues, labels, location, memberships, orgs, repos, server_error, users,
56 },
57 labels::{encode, label_pill, labels_url},
58 layout::wide,
59 markdown,
60 paging::{Pages, list_pages, requested_page, showing},
61 pulls::{Found, elsewhere_or_missing},
62 repo::{Tab, repo_for, repo_header},
63};
64
65/// `{number}` from the path, raw — validation is [`IssueNumber`]'s job.
66#[path_param]
67struct Number(str);
68
69/// `?state=closed`, and `?label=bug`. Anything else in `state`, including nothing,
70/// means open.
71#[query_params(error = bad_request)]
72struct StateQuery {
73 state: Option<String>,
74 label: Option<String>,
75 /// `?page=N`, 1-based. It travels beside the filters rather than instead of them —
76 /// see [`filtered_url`].
77 page: Option<String>,
78}
79
80#[derive(Debug, Deserialize)]
81struct IssueForm {
82 title: String,
83 body: String,
84}
85
86#[derive(Debug, Deserialize)]
87struct CommentForm {
88 body: String,
89}
90
91#[derive(Debug, Deserialize)]
92struct StateForm {
93 state: String,
94}
95
96// --- URLs ---------------------------------------------------------------------------
97
98fn issues_url(handle: &str, name: &str) -> String {
99 format!("/{handle}/repos/{name}/issues")
100}
101
102/// The list's URL with whichever of state, label and page it needs.
103///
104/// One builder for all three, because the parts have to survive each other: paging out
105/// of a filter would silently widen the list, and switching state must not lose the
106/// label or strand the reader on page 4 of a list that now has one page.
107fn filtered_url(handle: &str, name: &str, state: IssueState, filter: &str, page: usize) -> String {
108 let mut url = issues_url(handle, name);
109 let mut parts = Vec::new();
110
111 if !state.is_open() {
112 parts.push("state=closed".to_owned());
113 }
114
115 if !filter.is_empty() {
116 parts.push(format!("label={}", encode(filter)));
117 }
118
119 // Page 1 is the bare URL: a `?page=1` in a shared link says nothing and makes two
120 // URLs for one page.
121 if page > 1 {
122 parts.push(format!("page={page}"));
123 }
124
125 if !parts.is_empty() {
126 url.push('?');
127 url.push_str(&parts.join("&"));
128 }
129
130 url
131}
132
133pub(super) fn issue_url(handle: &str, name: &str, number: IssueNumber) -> String {
134 format!("/{handle}/repos/{name}/issues/{number}")
135}
136
137// --- Resolution ---------------------------------------------------------------------
138
139/// The number in the path, or 404.
140///
141/// A number that does not parse is not a bad request: `/issues/banana` is a URL that
142/// names nothing, exactly like `/issues/9999`, and answering differently would tell a
143/// prober which of the two they had found.
144fn number_for(cx: &Cx) -> Result<IssueNumber> {
145 path_param::<Number>(cx)
146 .parse::<IssueNumber>()
147 .map_err(|_| not_found().into())
148}
149
150/// The repository's issues in the state the query string asks for, narrowed to the label
151/// it names.
152async fn listing(
153 cx: &Cx,
154 repo: &RepoView,
155 state: IssueState,
156 filter: Option<&str>,
157 page: usize,
158) -> Result<IssueList> {
159 let listed = list_issues(
160 &current_actor(cx).await?,
161 &repo.handle,
162 &repo.name,
163 state,
164 filter,
165 page,
166 &orgs(cx),
167 &memberships(cx),
168 &repos(cx),
169 &issues(cx),
170 &users(cx),
171 &labels(cx),
172 )
173 .await
174 .map_err(server_error)?;
175
176 // `repo_for` already resolved the repository as visible, so `None` here would mean
177 // it vanished between the two reads. A 404 is the honest answer to that.
178 listed.ok_or_else(|| not_found().into())
179}
180
181/// One issue, or 404 — for a number that is not there and for a repository that is not
182/// visible alike.
183///
184/// The one exception is a number that is a **pull request**: the two share a sequence
185/// precisely so that `#7` names one thing, so the caller sends the visitor there rather
186/// than 404ing at a cross-reference that was written correctly. See
187/// [`elsewhere_or_missing`](super::pulls::elsewhere_or_missing), which both directions
188/// share so they cannot disagree about when a number is worth redirecting.
189async fn detail(cx: &Cx, repo: &RepoView, number: IssueNumber) -> Result<Found<IssueDetail>> {
190 let found = view_issue(
191 &current_actor(cx).await?,
192 &repo.handle,
193 &repo.name,
194 number,
195 &orgs(cx),
196 &memberships(cx),
197 &repos(cx),
198 &issues(cx),
199 &users(cx),
200 &labels(cx),
201 )
202 .await
203 .map_err(server_error)?;
204
205 match found {
206 Some(issue) => Ok(Found::Here(Box::new(issue))),
207 None => elsewhere_or_missing(cx, repo, number, Numbered::PullRequest).await,
208 }
209}
210
211/// The issue a failed write re-renders from.
212///
213/// A write only reaches here having already resolved the issue, so a number that has
214/// become a pull request in the meantime is a state nothing can produce and a 404 is the
215/// honest answer.
216async fn reread(cx: &Cx, repo: &RepoView, number: IssueNumber) -> Result<Box<IssueDetail>> {
217 match detail(cx, repo, number).await? {
218 Found::Here(issue) => Ok(issue),
219 Found::Elsewhere(_) => Err(not_found().into()),
220 }
221}
222
223/// The repository, refused for anyone who does not own it.
224///
225/// A non-owner gets a 404 rather than a 403, the rule the settings page already sets:
226/// a 403 on a repository they cannot see would confirm it exists.
227async fn owned_repo(cx: &Cx) -> Result<RepoView> {
228 let repo = repo_for(cx).await?;
229
230 if !repo.viewer_is_owner {
231 return Err(not_found().into());
232 }
233
234 Ok(repo)
235}
236
237/// Turns a use case failure into either a message to re-render with, or a response.
238///
239/// `Forbidden` reaching here means the actor lost ownership between the guard and the
240/// write, and `NotFound` that the issue went away — both are pages, not messages.
241fn write_failure(error: Error) -> std::result::Result<String, topcoat::Error> {
242 match error {
243 Error::Domain(DomainError::Validation { field, reason }) => {
244 Ok(format!("That {field} is no good: {reason}."))
245 }
246 Error::Domain(DomainError::Forbidden) => Err(forbidden().into()),
247 Error::Domain(DomainError::NotFound { .. }) => Err(not_found().into()),
248 other => Err(server_error(std::io::Error::other(other.to_string()))),
249 }
250}
251
252// --- The list -------------------------------------------------------------------------
253
254#[page("/{handle}/repos/{name}/issues")]
255async fn issues_page(cx: &Cx) -> Result {
256 let repo = repo_for(cx).await?;
257
258 // An unrecognised `?state=` shows the open list rather than erroring: this is a
259 // link someone may have mangled, not a form, and the only thing it can reveal is
260 // which issues are open anyway.
261 let query = query_params::<StateQuery>(cx)?;
262
263 let state = match query.state.as_deref() {
264 Some("closed") => IssueState::Closed,
265 _ => IssueState::Open,
266 };
267
268 // Kept as the raw string as well as resolved, so a filter naming a label that has
269 // been deleted still says what it was filtering on rather than silently widening.
270 let filter = query.label.as_deref().filter(|name| !name.is_empty());
271 let page = requested_page(query.page.as_deref());
272 let listed = listing(cx, &repo, state, filter, page).await?;
273
274 view! {
275 wide(
276 repo_header(
277 repo: &repo,
278 rev: "",
279 active: Tab::Issues,
280 )
281 issue_list(
282 handle: repo.handle.as_str(),
283 name: repo.name.as_str(),
284 listed: &listed,
285 filter: filter.unwrap_or(""),
286 )
287 )
288 }
289}
290
291/// The state filter, the label filter, and the way in, on one row.
292#[component]
293async fn issues_toolbar(handle: &str, name: &str, listed: &IssueList, filter: &str) -> Result {
294 // The primary colour marks which list you are looking at, the same way the tab
295 // strip marks which page you are on. Nothing else on the row is coloured.
296 let current = |active: bool| {
297 if active {
298 "text-foreground"
299 } else {
300 "text-muted-foreground hover:text-foreground"
301 }
302 };
303 let url = issues_url(handle, name);
304 let feed = issues_feed_path(handle, name);
305
306 // The state links keep the label filter, so switching between Open and Closed does
307 // not silently widen the list you are looking at — and drop the page, because page
308 // 4 of the open issues is not page 4 of the closed ones.
309 let carrying = |state: IssueState| filtered_url(handle, name, state, filter, 1);
310
311 view! {
312 <div class="mb-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
313 <a href=(carrying(IssueState::Open)) class=(format!("flex items-center gap-1.5 {}", current(listed.state.is_open())))>
314 state_icon(state: IssueState::Open, muted: !listed.state.is_open())
315 "Open"
316 <span class="font-mono text-xs text-muted-foreground">(listed.open)</span>
317 </a>
318 <a href=(carrying(IssueState::Closed)) class=(format!("flex items-center gap-1.5 {}", current(!listed.state.is_open())))>
319 state_icon(state: IssueState::Closed, muted: listed.state.is_open())
320 "Closed"
321 <span class="font-mono text-xs text-muted-foreground">(listed.closed)</span>
322 </a>
323
324 // The active filter, with the way out of it. Shown from the raw query value
325 // rather than only when it resolved, so filtering on a label that has since
326 // been deleted still says what it is filtering on.
327 if !filter.is_empty() {
328 <span class="flex items-center gap-1.5">
329 if let Some(pill) = listed.filter.as_ref() {
330 label_pill(handle: handle, name: name, pill: pill)
331 } else {
332 <span class="label-pill label-gray">(filter)</span>
333 }
334 <a
335 href=(if listed.state.is_open() { url.clone() } else { format!("{url}?state=closed") })
336 class="text-muted-foreground hover:text-foreground"
337 title=("Clear this filter")
338 >"×"</a>
339 </span>
340 }
341
342 <span class="ml-auto flex items-center gap-4">
343 <a
344 href=(labels_url(handle, name))
345 class="text-muted-foreground hover:text-foreground"
346 >"Labels"</a>
347 feed_link(href: feed.as_str())
348 if listed.viewer_is_owner {
349 <a
350 href=(format!("{url}/new"))
351 class=(button_variants(ButtonVariant::Primary, ButtonSize::Sm))
352 >"New issue"</a>
353 }
354 </span>
355 </div>
356 }
357}
358
359/// The state marker: open in the success colour, closed muted.
360///
361/// The one live thing about an issue is whether it is still open, so that is what
362/// carries the colour. A closed issue is history and reads as history.
363#[component]
364async fn state_icon(state: IssueState, #[default] muted: bool) -> Result {
365 let tone = if muted {
366 "text-muted-foreground"
367 } else if state.is_open() {
368 "text-success"
369 } else {
370 "text-muted-foreground"
371 };
372
373 view! {
374 icon(
375 data: if state.is_open() {
376 iconify_icon!("feather:alert-circle")
377 } else {
378 iconify_icon!("feather:check-circle")
379 },
380 attrs: attributes! { class=(format!("size-3.5 shrink-0 {tone}")) }
381 )
382 }
383}
384
385#[component]
386async fn issue_list(handle: &str, name: &str, listed: &IssueList, filter: &str) -> Result {
387 let issues = &listed.issues;
388 // The noun says which list is being counted, so a filtered page cannot read as
389 // though it were showing 3 of every issue in the repository.
390 let noun = match (listed.state.is_open(), filter.is_empty()) {
391 (true, true) => "open issues".to_owned(),
392 (false, true) => "closed issues".to_owned(),
393 (true, false) => format!("open issues labelled {filter}"),
394 (false, false) => format!("closed issues labelled {filter}"),
395 };
396 let sentence = showing(issues.offset(), issues.items.len(), issues.total, &noun);
397 let pages = Pages::numbered(issues.page, issues.pages, |page| {
398 filtered_url(handle, name, listed.state, filter, page)
399 });
400
401 view! {
402 issues_toolbar(handle: handle, name: name, listed: listed, filter: filter)
403
404 if listed.issues.items.is_empty() {
405 <div class="rounded-lg border border-border px-4 py-10 text-center">
406 <p class="text-sm text-muted-foreground">
407 if !filter.is_empty() {
408 "No " if listed.state.is_open() { "open" } else { "closed" }
409 " issues labelled " (filter) "."
410 } else if listed.state.is_open() { "No open issues." } else { "No closed issues." }
411 </p>
412 // No "New issue" button here: the toolbar already carries one for the
413 // owner, forty pixels above, and offering it twice reads as two things.
414 if !filter.is_empty() {
415 <p class="mt-1 text-xs">
416 <a
417 href=(issues_url(handle, name))
418 class="text-muted-foreground underline hover:text-foreground"
419 >"Show every issue"</a>
420 </p>
421 } else if !listed.viewer_is_owner && listed.state.is_open() {
422 <p class="mt-1 text-xs text-muted-foreground">
423 "Only the owner can open one here."
424 </p>
425 }
426 </div>
427 } else {
428 <ul class="divide-y divide-border rounded-lg border border-border">
429 for issue in &listed.issues.items {
430 issue_row(handle: handle, name: name, issue: issue)
431 }
432 </ul>
433 list_pages(summary: sentence.as_str(), pages: &pages)
434 }
435 }
436}
437
438/// One issue on one line: what it is, then who and when, then how much talk.
439#[component]
440async fn issue_row(handle: &str, name: &str, issue: &IssueSummary) -> Result {
441 let author = issue
442 .author
443 .as_ref()
444 .map(OrgName::as_str)
445 .unwrap_or("someone");
446
447 view! {
448 <li class="flex items-center gap-3 px-4 py-2.5 text-sm">
449 state_icon(state: issue.state)
450
451 <div class="min-w-0 flex-1">
452 <div class="flex flex-wrap items-center gap-x-2 gap-y-1">
453 <a
454 href=(issue_url(handle, name, issue.number))
455 class="truncate font-medium hover:text-primary"
456 >(issue.title.as_str())</a>
457 // After the title and before the meta line: a pill is part of what
458 // the issue is, not part of when it happened.
459 for pill in &issue.labels {
460 label_pill(handle: handle, name: name, pill: pill)
461 }
462 </div>
463 <p class="mt-0.5 truncate text-xs text-muted-foreground">
464 <span class="font-mono">"#" (issue.number.get())</span>
465 " opened "
466 <span title=(timestamp(issue.created_at))>(ago(issue.created_at))</span>
467 " by "
468 <span class="font-mono">"@" (author)</span>
469 </p>
470 </div>
471
472 if issue.comments > 0 {
473 <span
474 class="flex shrink-0 items-center gap-1 text-xs text-muted-foreground"
475 title=(format!("{} comments", issue.comments))
476 >
477 icon(
478 data: iconify_icon!("feather:message-square"),
479 attrs: attributes! { class="size-3.5" }
480 )
481 <span class="font-mono">(issue.comments)</span>
482 </span>
483 }
484 </li>
485 }
486}
487
488// --- Opening one ----------------------------------------------------------------------
489
490#[page("/{handle}/repos/{name}/issues/new")]
491async fn new_issue_page(cx: &Cx) -> Result {
492 let repo = owned_repo(cx).await?;
493
494 view! {
495 wide(
496 repo_header(
497 repo: &repo,
498 rev: "",
499 active: Tab::Issues,
500 )
501 new_issue_form(
502 handle: repo.handle.as_str(),
503 name: repo.name.as_str(),
504 title: "",
505 body: "",
506 error: "",
507 )
508 )
509 }
510}
511
512/// Opens the issue, then redirects to it.
513///
514/// The redirect is a 303 rather than `redirect()`'s 307, which would re-POST the form
515/// to the new issue's own URL — see [`location`].
516#[page(POST "/{handle}/repos/{name}/issues")]
517async fn create(cx: &Cx, Form(submitted): Form<IssueForm>) -> Result {
518 let repo = owned_repo(cx).await?;
519
520 let outcome = create_issue(
521 &current_actor(cx).await?,
522 &repo.handle,
523 &repo.name,
524 &NewIssue {
525 title: submitted.title.clone(),
526 body: submitted.body.clone(),
527 },
528 SystemTime::now(),
529 &orgs(cx),
530 &memberships(cx),
531 &repos(cx),
532 &issues(cx),
533 )
534 .await;
535
536 let message = match outcome {
537 Ok(issue) => {
538 return view! {
539 (StatusCode::SEE_OTHER)
540 (location(&issue_url(repo.handle.as_str(), repo.name.as_str(), issue.number))?)
541 };
542 }
543 Err(error) => write_failure(error)?,
544 };
545
546 // Re-rendered with what was typed. Bouncing back to an empty form would throw away
547 // a body someone spent ten minutes on to tell them the title was too long.
548 view! {
549 wide(
550 repo_header(
551 repo: &repo,
552 rev: "",
553 active: Tab::Issues,
554 )
555 new_issue_form(
556 handle: repo.handle.as_str(),
557 name: repo.name.as_str(),
558 title: submitted.title.as_str(),
559 body: submitted.body.as_str(),
560 error: message.as_str(),
561 )
562 )
563 }
564}
565
566#[component]
567async fn new_issue_form(handle: &str, name: &str, title: &str, body: &str, error: &str) -> Result {
568 // `max-w-3xl` without `mx-auto`: a centred column inside the full-width repository
569 // header leaves the two edges out of line, and the header is what the eye anchors on.
570 view! {
571 <div class="max-w-3xl">
572 <h1 class="text-lg font-semibold tracking-tight">"New issue"</h1>
573
574 if !error.is_empty() {
575 <div class="mt-4">
576 flash(kind: FlashKind::Error, (error))
577 </div>
578 }
579
580 <form method="post" action=(issues_url(handle, name)) class="mt-5 space-y-4">
581 <div class="space-y-2">
582 label(attrs: attributes! { for="title" }, "Title")
583 input(attrs: attributes! {
584 id="title"
585 name="title"
586 type="text"
587 value=(title)
588 placeholder="Blame is slow on large files"
589 required=(true)
590 autofocus=(true)
591 })
592 </div>
593
594 <div class="space-y-2">
595 label(attrs: attributes! { for="body" }, "Description")
596 textarea(
597 attrs: attributes! {
598 id="body"
599 name="body"
600 rows="12"
601 placeholder="Markdown is supported."
602 },
603 (body)
604 )
605 <p class="text-xs text-muted-foreground">
606 "Markdown. HTML in the source is shown as text, never rendered."
607 </p>
608 </div>
609
610 <div class="flex items-center gap-3">
611 button(attrs: attributes! { type="submit" }, "Open issue")
612 <a
613 href=(issues_url(handle, name))
614 class="text-sm text-muted-foreground hover:text-foreground"
615 >"Cancel"</a>
616 </div>
617 </form>
618 </div>
619 }
620}
621
622// --- One issue ------------------------------------------------------------------------
623
624#[page("/{handle}/repos/{name}/issues/{number}")]
625async fn issue_page(cx: &Cx) -> Result {
626 let repo = repo_for(cx).await?;
627
628 let issue = match detail(cx, &repo, number_for(cx)?).await? {
629 Found::Here(issue) => issue,
630 Found::Elsewhere(url) => {
631 return view! { (StatusCode::SEE_OTHER) (location(&url)?) };
632 }
633 };
634
635 view! {
636 wide(
637 repo_header(
638 repo: &repo,
639 rev: "",
640 active: Tab::Issues,
641 )
642 issue_view(
643 handle: repo.handle.as_str(),
644 name: repo.name.as_str(),
645 issue: &issue,
646 error: "",
647 comment: "",
648 editing: false,
649 )
650 )
651 }
652}
653
654/// Adds a comment, then redirects so a reload cannot repeat it.
655///
656/// Named `add_comment` rather than `comment` because `#[page]` turns a handler's name
657/// into a unit struct in module scope, which would shadow every `comment` binding in
658/// this file — including the loop variable that renders one.
659#[page(POST "/{handle}/repos/{name}/issues/{number}/comments")]
660async fn add_comment(cx: &Cx, Form(submitted): Form<CommentForm>) -> Result {
661 let repo = owned_repo(cx).await?;
662 let number = number_for(cx)?;
663
664 let outcome = comment_on_issue(
665 &current_actor(cx).await?,
666 &repo.handle,
667 &repo.name,
668 number,
669 &submitted.body,
670 SystemTime::now(),
671 &orgs(cx),
672 &memberships(cx),
673 &repos(cx),
674 &issues(cx),
675 )
676 .await;
677
678 let message = match outcome {
679 Ok(()) => {
680 return view! {
681 (StatusCode::SEE_OTHER)
682 (location(&issue_url(repo.handle.as_str(), repo.name.as_str(), number))?)
683 };
684 }
685 Err(error) => write_failure(error)?,
686 };
687
688 let issue = reread(cx, &repo, number).await?;
689
690 view! {
691 wide(
692 repo_header(
693 repo: &repo,
694 rev: "",
695 active: Tab::Issues,
696 )
697 issue_view(
698 handle: repo.handle.as_str(),
699 name: repo.name.as_str(),
700 issue: &issue,
701 error: message.as_str(),
702 // Kept, so a rejected comment is not silently thrown away.
703 comment: submitted.body.as_str(),
704 editing: false,
705 )
706 )
707 }
708}
709
710/// Closes or reopens, then redirects.
711///
712/// One route for both, because the two differ only in the value posted — and because
713/// two routes would mean two copies of the same guard.
714#[page(POST "/{handle}/repos/{name}/issues/{number}/state")]
715async fn set_state(cx: &Cx, Form(submitted): Form<StateForm>) -> Result {
716 let repo = owned_repo(cx).await?;
717 let number = number_for(cx)?;
718
719 // A value neither state can name is a tampered form, not something to default:
720 // defaulting would close an issue somebody asked to reopen.
721 let state = submitted
722 .state
723 .parse::<IssueState>()
724 .map_err(|_| bad_request("unknown issue state"))?;
725
726 match set_issue_state(
727 &current_actor(cx).await?,
728 &repo.handle,
729 &repo.name,
730 number,
731 state,
732 SystemTime::now(),
733 &orgs(cx),
734 &memberships(cx),
735 &repos(cx),
736 &issues(cx),
737 )
738 .await
739 {
740 Ok(()) => {}
741 // Nothing typed to preserve and nothing to explain, so a failure here is a
742 // response rather than a re-render.
743 Err(error) => {
744 write_failure(error)?;
745 }
746 }
747
748 view! {
749 (StatusCode::SEE_OTHER)
750 (location(&issue_url(repo.handle.as_str(), repo.name.as_str(), number))?)
751 }
752}
753
754/// Changes the title and body, then redirects.
755#[page(POST "/{handle}/repos/{name}/issues/{number}/edit")]
756async fn edit(cx: &Cx, Form(submitted): Form<IssueForm>) -> Result {
757 let repo = owned_repo(cx).await?;
758 let number = number_for(cx)?;
759
760 let outcome = edit_issue(
761 &current_actor(cx).await?,
762 &repo.handle,
763 &repo.name,
764 number,
765 &IssueEdit {
766 title: submitted.title.clone(),
767 body: submitted.body.clone(),
768 },
769 SystemTime::now(),
770 &orgs(cx),
771 &memberships(cx),
772 &repos(cx),
773 &issues(cx),
774 )
775 .await;
776
777 let message = match outcome {
778 Ok(()) => {
779 return view! {
780 (StatusCode::SEE_OTHER)
781 (location(&issue_url(repo.handle.as_str(), repo.name.as_str(), number))?)
782 };
783 }
784 Err(error) => write_failure(error)?,
785 };
786
787 // The stored issue, with the rejected edit put back into the form and the panel
788 // opened on it — otherwise the reason is visible but what caused it is hidden
789 // behind a closed disclosure.
790 let stored = reread(cx, &repo, number).await?;
791 let attempted = IssueDetail {
792 title: submitted.title.clone(),
793 body: submitted.body.clone(),
794 ..*stored
795 };
796
797 view! {
798 wide(
799 repo_header(
800 repo: &repo,
801 rev: "",
802 active: Tab::Issues,
803 )
804 issue_view(
805 handle: repo.handle.as_str(),
806 name: repo.name.as_str(),
807 issue: &attempted,
808 error: message.as_str(),
809 comment: "",
810 editing: true,
811 )
812 )
813 }
814}
815
816#[component]
817async fn issue_view(
818 handle: &str,
819 name: &str,
820 issue: &IssueDetail,
821 error: &str,
822 /// A comment that was rejected, put back in the box.
823 comment: &str,
824 /// Whether the edit panel starts open — true only when an edit was refused.
825 editing: bool,
826) -> Result {
827 let author = issue
828 .author
829 .as_ref()
830 .map(OrgName::as_str)
831 .unwrap_or("someone");
832 let url = issue_url(handle, name, issue.number);
833
834 view! {
835 <div class="max-w-3xl">
836 <div class="flex items-start gap-3">
837 <h1 class="min-w-0 flex-1 text-xl font-semibold tracking-tight">
838 (issue.title.as_str())
839 <span class="ml-2 font-mono text-lg font-normal text-muted-foreground">
840 "#" (issue.number.get())
841 </span>
842 </h1>
843 </div>
844
845 // Straight after the title, on their own line: the labels say what kind of
846 // thing this is, which is read with the title rather than with the metadata.
847 if !issue.labels.is_empty() {
848 <div class="mt-2 flex flex-wrap items-center gap-1.5">
849 for pill in &issue.labels {
850 label_pill(handle: handle, name: name, pill: pill)
851 }
852 </div>
853 }
854
855 <div class="mt-2 flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-muted-foreground">
856 // The badge is the only coloured thing here, because whether the issue is
857 // still open is the only live fact on the page.
858 badge(
859 variant: if issue.state.is_open() {
860 BadgeVariant::Primary
861 } else {
862 BadgeVariant::Secondary
863 },
864 if issue.state.is_open() { "Open" } else { "Closed" }
865 )
866 <span>
867 <span class="font-mono">"@" (author)</span>
868 " opened this "
869 <span title=(timestamp(issue.created_at))>(ago(issue.created_at))</span>
870 </span>
871 if let Some(closed_at) = issue.closed_at {
872 <span>
873 "closed " <span title=(timestamp(closed_at))>(ago(closed_at))</span>
874 </span>
875 }
876 <span>
877 (issue.comments.len())
878 if issue.comments.len() == 1 { " comment" } else { " comments" }
879 </span>
880 </div>
881
882 if !error.is_empty() {
883 <div class="mt-4">
884 flash(kind: FlashKind::Error, (error))
885 </div>
886 }
887
888 <div class="mt-4 space-y-3">
889 <article class="rounded-lg border border-border">
890 <header class="flex items-center gap-2 border-b border-border px-4 py-2 text-xs text-muted-foreground">
891 <span class="font-mono">"@" (author)</span>
892 <span title=(timestamp(issue.created_at))>(ago(issue.created_at))</span>
893 </header>
894 body_panel(
895 handle: handle,
896 name: name,
897 source: issue.body.as_str(),
898 empty: "No description given.",
899 )
900 </article>
901
902 for comment in &issue.comments {
903 issue_comment(handle: handle, name: name, comment: comment)
904 }
905 </div>
906
907 if issue.viewer_is_owner {
908 // The two actions sit on one row under the textarea, per ui.md's
909 // density rule: they are the two things to do here and stacking them
910 // spent a whole row on each.
911 //
912 // They are still **two forms** — a form cannot nest, and posting a draft
913 // comment along with a close would be a surprise either way. The Comment
914 // button reaches its own form by id rather than by containment, which is
915 // what lets the row hold both without the textarea joining it.
916 <form
917 id="comment-form"
918 method="post"
919 action=(format!("{url}/comments"))
920 class="mt-5 space-y-2"
921 >
922 label(attrs: attributes! { for="comment-body" }, "Comment")
923 textarea(
924 attrs: attributes! {
925 id="comment-body"
926 name="body"
927 rows="5"
928 placeholder="Markdown is supported."
929 },
930 (comment)
931 )
932 </form>
933
934 <div class="mt-3 flex flex-wrap items-center gap-2">
935 button(
936 size: ButtonSize::Sm,
937 attrs: attributes! { type="submit" form="comment-form" },
938 "Comment"
939 )
940
941 // The state posted is the one being moved *to*.
942 <form method="post" action=(format!("{url}/state"))>
943 <input
944 type="hidden"
945 name="state"
946 value=(if issue.state.is_open() { "closed" } else { "open" })
947 />
948 button(
949 variant: ButtonVariant::Outline,
950 size: ButtonSize::Sm,
951 attrs: attributes! { type="submit" },
952 if issue.state.is_open() { "Close issue" } else { "Reopen issue" }
953 )
954 </form>
955 </div>
956
957 // On its own row for the same reason the edit panel is: the form it
958 // reveals is full width, and nesting it in a flex row indents it all.
959 <details class="mt-3">
960 <summary class="cursor-pointer text-sm text-muted-foreground hover:text-foreground">
961 "Labels"
962 </summary>
963
964 if issue.repo_labels.is_empty() {
965 <p class="mt-2 text-xs text-muted-foreground">
966 "This repository has no labels yet. "
967 <a href=(labels_url(handle, name)) class="underline hover:text-foreground">
968 "Make one"
969 </a>
970 "."
971 </p>
972 } else {
973 // Every box, ticked or not, submitted as the whole set — which is
974 // what makes pressing Save twice mean the same thing as once.
975 <form method="post" action=(format!("{url}/labels")) class="mt-2 space-y-2">
976 <div class="flex flex-wrap gap-x-4 gap-y-2">
977 for choice in &issue.repo_labels {
978 <label class="flex items-center gap-2 text-xs">
979 <input
980 type="checkbox"
981 name="label"
982 value=(choice.id.as_str())
983 checked=(issue.labels.iter().any(|on| on.id == choice.id))
984 />
985 <span class=(format!("label-pill label-{}", choice.colour))>
986 (choice.name.as_str())
987 </span>
988 </label>
989 }
990 </div>
991 <div class="flex items-center gap-3 pt-1">
992 button(
993 size: ButtonSize::Sm,
994 variant: ButtonVariant::Outline,
995 attrs: attributes! { type="submit" },
996 "Save labels"
997 )
998 <a
999 href=(labels_url(handle, name))
1000 class="text-xs text-muted-foreground hover:text-foreground"
1001 >"Manage labels"</a>
1002 </div>
1003 </form>
1004 }
1005 </details>
1006
1007 // On its own row rather than beside the button: the form it reveals is
1008 // full width, and nesting it in a flex row indents the whole thing.
1009 <details class="mt-3" open=(editing)>
1010 <summary class="cursor-pointer text-sm text-muted-foreground hover:text-foreground">
1011 "Edit title and description"
1012 </summary>
1013
1014 <form method="post" action=(format!("{url}/edit")) class="mt-3 space-y-4">
1015 <div class="space-y-2">
1016 label(attrs: attributes! { for="edit-title" }, "Title")
1017 input(attrs: attributes! {
1018 id="edit-title"
1019 name="title"
1020 type="text"
1021 value=(issue.title.as_str())
1022 required=(true)
1023 })
1024 </div>
1025 <div class="space-y-2">
1026 label(attrs: attributes! { for="edit-body" }, "Description")
1027 textarea(
1028 attrs: attributes! { id="edit-body" name="body" rows="10" },
1029 (issue.body.as_str())
1030 )
1031 </div>
1032 button(
1033 size: ButtonSize::Sm,
1034 attrs: attributes! { type="submit" },
1035 "Save changes"
1036 )
1037 </form>
1038 </details>
1039 } else {
1040 <p class="mt-5 rounded-lg border border-border px-4 py-3 text-xs text-muted-foreground">
1041 "Only the owner can comment on or change this issue."
1042 </p>
1043 }
1044
1045 <p class="mt-8">
1046 <a
1047 href=(issues_url(handle, name))
1048 class="text-sm text-muted-foreground hover:text-foreground"
1049 >"Back to issues"</a>
1050 </p>
1051 </div>
1052 }
1053}
1054
1055#[component]
1056async fn issue_comment(handle: &str, name: &str, comment: &CommentView) -> Result {
1057 let author = comment
1058 .author
1059 .as_ref()
1060 .map(OrgName::as_str)
1061 .unwrap_or("someone");
1062
1063 view! {
1064 <article class="rounded-lg border border-border">
1065 <header class="flex items-center gap-2 border-b border-border px-4 py-2 text-xs text-muted-foreground">
1066 <span class="font-mono">"@" (author)</span>
1067 <span title=(timestamp(comment.created_at))>(ago(comment.created_at))</span>
1068 </header>
1069 body_panel(handle: handle, name: name, source: comment.body.as_str(), empty: "")
1070 </article>
1071 }
1072}
1073
1074/// A markdown body inside a panel.
1075///
1076/// Split out so the one `view!` holding rendered markdown is a single line. Safe
1077/// because [`markdown`](super::markdown) writes every tag itself and never passes
1078/// source HTML through — the same reason the README can be rendered.
1079#[component]
1080async fn body_panel(handle: &str, name: &str, source: &str, empty: &str) -> Result {
1081 view! {
1082 if source.is_empty() {
1083 <p class="px-4 py-3 text-sm text-muted-foreground italic">(empty)</p>
1084 } else {
1085 <div class="overflow-x-auto px-4 py-2 text-sm [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
1086 (markdown::render(
1087 source,
1088 Some(markdown::Crossref {
1089 handle,
1090 name,
1091 origin: None,
1092 }),
1093 ))
1094 </div>
1095 }
1096 }
1097}
1098
1099#[cfg(test)]
1100mod tests {
1101 use super::*;
1102
1103 #[test]
1104 fn the_first_page_of_the_open_list_is_the_bare_url() {
1105 assert_eq!(
1106 filtered_url("ada", "steid", IssueState::Open, "", 1),
1107 "/ada/repos/steid/issues"
1108 );
1109 }
1110
1111 #[test]
1112 fn a_page_link_carries_the_state_and_the_label_with_it() {
1113 // The property the list depends on: paging out of a filter would silently widen
1114 // the list somebody is reading.
1115 assert_eq!(
1116 filtered_url("ada", "steid", IssueState::Closed, "needs review", 3),
1117 "/ada/repos/steid/issues?state=closed&label=needs%20review&page=3"
1118 );
1119 }
1120
1121 #[test]
1122 fn a_state_link_keeps_the_label_and_drops_the_page() {
1123 // Page 4 of the open issues is not page 4 of the closed ones, so switching
1124 // state starts again at the first page — with the filter intact.
1125 assert_eq!(
1126 filtered_url("ada", "steid", IssueState::Closed, "bug", 1),
1127 "/ada/repos/steid/issues?state=closed&label=bug"
1128 );
1129 }
1130}