forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiB3d53dfdTahinli1 month ago208 commits

diff.rs808 lines, 30.6 KiBHistoryRawDownload
1//! Commit diff rendering, shared by the commit page, the comparison page and the pull-request
2//! Files tab: the changed-file summary, the per-file index and each file's unified diff in a
3//! scroll wrapper. Uses the `diff-*` classes from the stylesheet. `view!` escapes text and
4//! attribute values.
5//!
6//! The Files tab turns on `LineComments`: each numbered line gets an id and a "+" link, the
7//! review threads of a line render in a full-width row under it, and the line whose inline
8//! comment form is open gets that form. Every line is its own `<tbody>`, so those rows can span
9//! the table. Commit and comparison pages pass the default, which leaves all of that out.
10
11use std::collections::HashMap;
12
13use forge_core::{Side, Thread};
14use forge_git::history::{CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind};
15use topcoat::Result;
16use topcoat::context::Cx;
17use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
18use topcoat::router::request::uri;
19use topcoat::view::{View, component, view};
20
21use crate::i18n::Lang;
22use crate::i18n::browse as b;
23use crate::i18n::code::{self as g, K};
24use crate::i18n::pulls_review::{self as pr_g, K as PrK};
25use crate::pages::commits::url_path;
26use crate::views::review_thread::{ThreadCtx, review_thread_in};
27
28/// Per-diff limits used by the commit and pull-request pages.
29pub const LIMITS: DiffLimits = DiffLimits {
30 max_files: MAX_FILES,
31 max_lines_per_file: 2000,
32 max_total_lines: 20_000,
33};
34
35/// Files shown before the diff reports truncation. Matches `LIMITS.max_files`.
36pub const MAX_FILES: usize = 300;
37
38/// The language of a diff section. It defaults to English, so a page that does not pass one (the
39/// comparison and Files tab pages, for now) keeps its English text.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub struct DiffLang(pub Lang);
42
43impl Default for DiffLang {
44 fn default() -> Self {
45 DiffLang(Lang::En)
46 }
47}
48
49/// Line comments on a diff. The default leaves the diff as commit and comparison pages show it.
50#[derive(Default)]
51pub struct LineComments {
52 /// Line ids, the "+" link on each numbered line and the inline form. Set only for a viewer
53 /// who may comment, so anonymous viewers see no comment controls.
54 pub anchors: bool,
55 /// Threads by (file index, side, line). Each renders in the row under its line.
56 pub threads: HashMap<(usize, Side, u32), Vec<Thread>>,
57 /// The line whose inline comment form is open.
58 pub open_form: Option<(usize, Side, u32)>,
59 /// URL of the Files tab, such as `/o/r/pulls/3/files`. The "+" links and the form's cancel
60 /// link point here.
61 pub files_href: String,
62 /// The viewer has a pending review, so the form offers "Add review comment".
63 pub has_pending: bool,
64 /// What the threads and the form need: the review POST base, CSRF, viewer and permissions.
65 pub ctx: ThreadCtx,
66}
67
68/// Name of the cookie that remembers the viewer's unified or split choice.
69pub const DIFF_VIEW_COOKIE: &str = "forge_diff";
70
71/// How a diff page shows its diff: unified or split, whitespace ignored or not, plus what the
72/// toolbar needs to build its links. The default has no toolbar and shows a plain unified diff.
73#[derive(Clone, Default)]
74pub struct DiffOpts {
75 /// Draw the toolbar.
76 pub enabled: bool,
77 pub split: bool,
78 pub ignore_ws: bool,
79 /// Path of the page the toolbar links back to.
80 pub path: String,
81 /// The request's query pairs except the ones the toolbar owns.
82 pub query: Vec<(String, String)>,
83 /// `.patch` and `.diff` download links, when the page has them.
84 pub downloads: Option<(String, String)>,
85}
86
87impl DiffOpts {
88 /// Reads the request: `?view=split|unified` wins and is remembered in a cookie, else the
89 /// cookie decides; `?w=1` ignores whitespace. `downloads` are the patch and diff links.
90 pub fn from_cx(cx: &Cx, downloads: Option<(String, String)>) -> Self {
91 let request = uri(cx);
92 let mut view_param = None;
93 let mut ignore_ws = false;
94 let mut query = Vec::new();
95 if let Some(raw) = request.query() {
96 for (key, value) in form_urlencoded::parse(raw.as_bytes()) {
97 match key.as_ref() {
98 "view" => view_param = Some(value.into_owned()),
99 "w" => ignore_ws = value == "1",
100 "comment" | "review_error" => {}
101 _ => query.push((key.into_owned(), value.into_owned())),
102 }
103 }
104 }
105 let split = match view_param.as_deref() {
106 Some(v @ ("split" | "unified")) => {
107 let max_age = time::Duration::seconds(365 * 24 * 60 * 60);
108 cookies(cx).add(
109 Cookie::build((DIFF_VIEW_COOKIE, v.to_owned()))
110 .path("/")
111 .secure(true)
112 .same_site(SameSite::Lax)
113 .max_age(max_age)
114 .build(),
115 );
116 v == "split"
117 }
118 _ => cookies(cx)
119 .get(DIFF_VIEW_COOKIE)
120 .is_some_and(|c| c.value() == "split"),
121 };
122 Self {
123 enabled: true,
124 split,
125 ignore_ws,
126 path: request.path().to_owned(),
127 query,
128 downloads,
129 }
130 }
131
132 /// The page URL for the given view and whitespace setting.
133 pub fn href(&self, split: bool, ignore_ws: bool) -> String {
134 let mut ser = form_urlencoded::Serializer::new(String::new());
135 for (k, v) in &self.query {
136 ser.append_pair(k, v);
137 }
138 ser.append_pair("view", if split { "split" } else { "unified" });
139 if ignore_ws {
140 ser.append_pair("w", "1");
141 }
142 format!("{}?{}", self.path, ser.finish())
143 }
144}
145
146/// The toolbar above the diff, flattened for the view.
147struct Toolbar {
148 unified_href: String,
149 split_href: String,
150 ws_href: String,
151 split: bool,
152 ignore_ws: bool,
153 downloads: Option<(String, String)>,
154}
155
156/// The inline comment form under an open line.
157struct InlineForm {
158 action: String,
159 cancel_href: String,
160 csrf: String,
161 file_index: String,
162 side: &'static str,
163 line: String,
164 head_oid: String,
165 has_pending: bool,
166 can_review: bool,
167 /// The text of the commented line, when a suggestion can replace it (a line on the new side).
168 suggest_line: Option<String>,
169}
170
171/// What renders under a line: its threads and, if open, the form.
172struct RowBelow {
173 threads: Vec<Thread>,
174 form: Option<InlineForm>,
175 ctx: ThreadCtx,
176}
177
178/// One rendered row of a file's diff table.
179struct DiffRow {
180 class: &'static str,
181 old: String,
182 new: String,
183 code: String,
184 anchored: bool,
185 /// The `L-<file>-<side>-<line>` id, when anchors are on and the line has a number.
186 anchor: Option<String>,
187 /// Target of the "+" link on this line.
188 plus_href: Option<String>,
189 below: Option<RowBelow>,
190}
191
192/// One file of the diff, flattened for the view.
193struct FileView {
194 anchor: String,
195 label: String,
196 status: &'static str,
197 additions: u32,
198 deletions: u32,
199 binary: bool,
200 truncated: bool,
201 has_blob: bool,
202 blob_href: String,
203 rows: Vec<DiffRow>,
204 /// Rows for the split view; filled in place of `rows` when the diff is split.
205 split_rows: Vec<SplitRow>,
206}
207
208/// One side of a split row.
209struct SplitSide {
210 /// `add`, `del`, `ctx`, `ctx dup` (the repeated side of a context line) or `empty`.
211 class: &'static str,
212 num: String,
213 code: String,
214 anchor: Option<String>,
215 plus_href: Option<String>,
216}
217
218impl SplitSide {
219 fn empty() -> Self {
220 Self {
221 class: "empty",
222 num: String::new(),
223 code: String::new(),
224 anchor: None,
225 plus_href: None,
226 }
227 }
228
229 fn from_row(row: DiffRow, class: &'static str, num: String) -> (Self, Option<RowBelow>) {
230 (
231 Self {
232 class,
233 num,
234 code: row.code,
235 anchor: row.anchor,
236 plus_href: row.plus_href,
237 },
238 row.below,
239 )
240 }
241}
242
243/// A row of the split table: a hunk header, or a left and a right side with what sits below.
244struct SplitRow {
245 hunk: Option<String>,
246 left: SplitSide,
247 right: SplitSide,
248 below: Option<RowBelow>,
249}
250
251fn merge_below(a: Option<RowBelow>, b: Option<RowBelow>) -> Option<RowBelow> {
252 match (a, b) {
253 (Some(mut a), Some(b)) => {
254 a.threads.extend(b.threads);
255 if a.form.is_none() {
256 a.form = b.form;
257 }
258 Some(a)
259 }
260 (a, None) => a,
261 (None, b) => b,
262 }
263}
264
265/// Pairs each run of deleted lines with the added lines that follow it, side by side.
266fn flush_pairs(out: &mut Vec<SplitRow>, dels: &mut Vec<DiffRow>, adds: &mut Vec<DiffRow>) {
267 let mut dels = std::mem::take(dels).into_iter();
268 let mut adds = std::mem::take(adds).into_iter();
269 loop {
270 let (d, a) = (dels.next(), adds.next());
271 if d.is_none() && a.is_none() {
272 break;
273 }
274 let (left, left_below) = match d {
275 Some(row) => {
276 let num = row.old.clone();
277 SplitSide::from_row(row, "del", num)
278 }
279 None => (SplitSide::empty(), None),
280 };
281 let (right, right_below) = match a {
282 Some(row) => {
283 let num = row.new.clone();
284 SplitSide::from_row(row, "add", num)
285 }
286 None => (SplitSide::empty(), None),
287 };
288 out.push(SplitRow {
289 hunk: None,
290 left,
291 right,
292 below: merge_below(left_below, right_below),
293 });
294 }
295}
296
297fn split_rows(rows: Vec<DiffRow>) -> Vec<SplitRow> {
298 let mut out = Vec::new();
299 let mut dels: Vec<DiffRow> = Vec::new();
300 let mut adds: Vec<DiffRow> = Vec::new();
301 for row in rows {
302 match row.class {
303 "diff-line del" => {
304 if !adds.is_empty() {
305 flush_pairs(&mut out, &mut dels, &mut adds);
306 }
307 dels.push(row);
308 }
309 "diff-line add" => adds.push(row),
310 "diff-line hunk" => {
311 flush_pairs(&mut out, &mut dels, &mut adds);
312 out.push(SplitRow {
313 hunk: Some(row.code),
314 left: SplitSide::empty(),
315 right: SplitSide::empty(),
316 below: None,
317 });
318 }
319 _ => {
320 flush_pairs(&mut out, &mut dels, &mut adds);
321 let left = SplitSide {
322 class: "ctx",
323 num: row.old.clone(),
324 code: row.code.clone(),
325 anchor: None,
326 plus_href: None,
327 };
328 let new = row.new.clone();
329 let (right, below) = SplitSide::from_row(row, "ctx dup", new);
330 out.push(SplitRow {
331 hunk: None,
332 left,
333 right,
334 below,
335 });
336 }
337 }
338 }
339 flush_pairs(&mut out, &mut dels, &mut adds);
340 out
341}
342
343impl FileView {
344 /// `oid` is the commit being shown; `parent` is its first parent, used for the blob link of
345 /// deleted files (they are absent at `oid`). `comments` supplies the review data and is
346 /// drained of the threads it renders.
347 #[allow(clippy::too_many_arguments)]
348 fn new(
349 index: usize,
350 file: &FileDiff,
351 oid: &str,
352 parent: Option<&str>,
353 owner: &str,
354 repo: &str,
355 lang: Lang,
356 comments: &mut LineComments,
357 ) -> Self {
358 let label = match (&file.old_path, &file.new_path) {
359 (Some(old), Some(new)) if old != new => format!("{old} → {new}"),
360 (_, Some(new)) => new.clone(),
361 (Some(old), None) => old.clone(),
362 (None, None) => String::new(),
363 };
364 let status = match file.status {
365 DiffStatus::Added => g::t(lang, K::StatusAdded),
366 DiffStatus::Deleted => g::t(lang, K::StatusDeleted),
367 DiffStatus::Modified => g::t(lang, K::StatusModified),
368 DiffStatus::Renamed => g::t(lang, K::StatusRenamed),
369 DiffStatus::Copied => g::t(lang, K::StatusCopied),
370 DiffStatus::TypeChanged => g::t(lang, K::StatusTypeChanged),
371 };
372 // A deleted file is absent at this commit, so its blob is read from the parent.
373 let blob_commit = match file.status {
374 DiffStatus::Deleted => parent,
375 _ => Some(oid),
376 };
377 let blob_path = file.new_path.as_ref().or(file.old_path.as_ref());
378 let blob_href = match (blob_commit, blob_path) {
379 (Some(commit), Some(path)) => {
380 format!("/{owner}/{repo}/blob/{commit}/{}", url_path(path))
381 }
382 _ => String::new(),
383 };
384
385 let mut rows = Vec::new();
386 for hunk in &file.hunks {
387 rows.push(DiffRow {
388 class: "diff-line hunk",
389 old: String::new(),
390 new: String::new(),
391 code: hunk.header.clone(),
392 anchored: comments.anchors,
393 anchor: None,
394 plus_href: None,
395 below: None,
396 });
397 for line in &hunk.lines {
398 let (class, code) = match line.kind {
399 LineKind::Add => ("diff-line add", format!("+{}", line.text)),
400 LineKind::Del => ("diff-line del", format!("-{}", line.text)),
401 LineKind::Context => ("diff-line ctx", format!(" {}", line.text)),
402 LineKind::NoNewline => ("diff-line ctx", line.text.clone()),
403 };
404 // Deleted lines sit on the old side; added and context lines on the new side.
405 let key = match line.kind {
406 LineKind::Add | LineKind::Context => line.new_no.map(|n| (Side::New, n)),
407 LineKind::Del => line.old_no.map(|n| (Side::Old, n)),
408 LineKind::NoNewline => None,
409 };
410 let (anchor, plus_href, below) =
411 match key {
412 Some((side, number)) => {
413 let id = format!("L-{index}-{}-{number}", side.as_str());
414 let anchor = comments.anchors.then(|| id.clone());
415 let plus_href = comments.anchors.then(|| {
416 format!(
417 "{}?comment={index}:{}:{number}#{id}",
418 comments.files_href,
419 side.as_str()
420 )
421 });
422 let target = (index, side, number);
423 let threads = comments.threads.remove(&target).unwrap_or_default();
424 let form = (comments.anchors && comments.open_form == Some(target))
425 .then(|| InlineForm {
426 action: format!("{}/review_comments", comments.ctx.pr_href),
427 cancel_href: comments.files_href.clone(),
428 csrf: comments.ctx.csrf.clone(),
429 file_index: index.to_string(),
430 side: side.as_str(),
431 line: number.to_string(),
432 head_oid: oid.to_owned(),
433 has_pending: comments.has_pending,
434 can_review: comments.ctx.can_review,
435 suggest_line: (side == Side::New).then(|| line.text.clone()),
436 });
437 let below = (!threads.is_empty() || form.is_some()).then(|| RowBelow {
438 threads,
439 form,
440 ctx: comments.ctx.clone(),
441 });
442 (anchor, plus_href, below)
443 }
444 None => (None, None, None),
445 };
446 rows.push(DiffRow {
447 class,
448 old: line.old_no.map(|n| n.to_string()).unwrap_or_default(),
449 new: line.new_no.map(|n| n.to_string()).unwrap_or_default(),
450 code,
451 anchored: comments.anchors,
452 anchor,
453 plus_href,
454 below,
455 });
456 }
457 }
458
459 Self {
460 anchor: format!("file-{}", index + 1),
461 label,
462 status,
463 additions: file.additions,
464 deletions: file.deletions,
465 binary: file.is_binary,
466 truncated: file.truncated,
467 has_blob: !blob_href.is_empty(),
468 blob_href,
469 rows,
470 split_rows: Vec::new(),
471 }
472 }
473}
474
475/// Entry in the file index at the top of the diff.
476struct NavItem {
477 anchor_href: String,
478 label: String,
479 additions: u32,
480 deletions: u32,
481}
482
483/// The whole diff section: a summary heading with totals, the file index and every file's
484/// diff. `owner` and `repo` name the repository for "view file" links, `oid` is the commit the
485/// diff belongs to, and `parent` is its first parent (`None` for a root commit). `subject` names
486/// what the diff shows in the truncation note, such as "this commit" or "this comparison".
487/// `comments` turns on the line comments of the Files tab; the default renders a plain diff.
488#[allow(clippy::too_many_arguments)]
489#[component]
490pub async fn diff_section(
491 diff: &CommitDiff,
492 owner: &str,
493 repo: &str,
494 oid: &str,
495 parent: Option<&str>,
496 subject: &str,
497 #[default] lang: DiffLang,
498 #[default] comments: LineComments,
499 #[default] opts: DiffOpts,
500) -> Result<impl View> {
501 let lang = lang.0;
502 let mut comments = comments;
503 let anchored = comments.anchors;
504 let split = opts.split;
505 let mut files: Vec<FileView> = diff
506 .files
507 .iter()
508 .enumerate()
509 .map(|(i, file)| FileView::new(i, file, oid, parent, owner, repo, lang, &mut comments))
510 .collect();
511 if split {
512 for file in &mut files {
513 file.split_rows = split_rows(std::mem::take(&mut file.rows));
514 }
515 }
516 let toolbar = opts.enabled.then(|| Toolbar {
517 unified_href: opts.href(false, opts.ignore_ws),
518 split_href: opts.href(true, opts.ignore_ws),
519 ws_href: opts.href(opts.split, !opts.ignore_ws),
520 split: opts.split,
521 ignore_ws: opts.ignore_ws,
522 downloads: opts.downloads.clone(),
523 });
524 let nav: Vec<NavItem> = files
525 .iter()
526 .map(|f| NavItem {
527 anchor_href: format!("#{}", f.anchor),
528 label: f.label.clone(),
529 additions: f.additions,
530 deletions: f.deletions,
531 })
532 .collect();
533 let total_add: u32 = files.iter().map(|f| f.additions).sum();
534 let total_del: u32 = files.iter().map(|f| f.deletions).sum();
535 let file_count = files.len();
536 let no_files = files.is_empty();
537 let files_label = g::changed_files(lang, file_count);
538 let truncated_note = g::diff_truncated(lang, MAX_FILES, subject);
539 let truncated_files = diff.truncated_files;
540 let add_label = format!("+{total_add}");
541 let del_label = format!("-{total_del}");
542
543 Ok(view! {
544 <section class="diff-section">
545 <h2>(files_label.as_str()) " " <span class="diff-stats"><span class="add">(add_label.as_str())</span> " " <span class="del">(del_label.as_str())</span></span></h2>
546 if let Some(bar) = toolbar {
547 diff_toolbar(bar: bar, lang: lang)
548 }
549 if truncated_files {
550 <p class="muted">(truncated_note.as_str())</p>
551 }
552 if no_files {
553 <p class="muted">(g::t(lang, K::NoFileChanges))</p>
554 } else {
555 <ul class="diff-index">
556 for item in nav.iter() {
557 <li>
558 <a href=(item.anchor_href.as_str())>(item.label.as_str())</a>
559 " "
560 <span class="diff-stats"><span class="add">(format!("+{}", item.additions))</span> " " <span class="del">(format!("-{}", item.deletions))</span></span>
561 </li>
562 }
563 </ul>
564 for file in files.into_iter() {
565 diff_file(file: file, lang: lang, split: split, anchored: anchored)
566 }
567 }
568 </section>
569 })
570}
571
572/// Unified or split, ignore whitespace, and the patch and diff downloads.
573#[component]
574async fn diff_toolbar(bar: Toolbar, lang: Lang) -> Result<impl View> {
575 let unified_on = if bar.split { "false" } else { "true" };
576 let split_on = if bar.split { "true" } else { "false" };
577 let ws_on = if bar.ignore_ws { "true" } else { "false" };
578 Ok(view! {
579 <div class="diff-toolbar">
580 <div class="seg" role="group" aria-label=(b::t(lang, b::K::DiffView))>
581 <a class="seg-item" href=(bar.unified_href.as_str()) aria-pressed=(unified_on)>(b::t(lang, b::K::Unified))</a>
582 <a class="seg-item" href=(bar.split_href.as_str()) aria-pressed=(split_on)>(b::t(lang, b::K::Split))</a>
583 </div>
584 <a class="seg-item toggle" href=(bar.ws_href.as_str()) aria-pressed=(ws_on)>(b::t(lang, b::K::IgnoreWhitespace))</a>
585 if let Some((patch, diff)) = bar.downloads {
586 <span class="diff-downloads">
587 <a href=(patch.as_str()) title=(b::t(lang, b::K::PatchTitle))>(b::t(lang, b::K::PatchLink))</a>
588 <a href=(diff.as_str()) title=(b::t(lang, b::K::DiffTitle))>(b::t(lang, b::K::DiffLink))</a>
589 </span>
590 }
591 </div>
592 })
593}
594
595#[component]
596async fn diff_file(file: FileView, lang: Lang, split: bool, anchored: bool) -> Result<impl View> {
597 let add_label = format!("+{}", file.additions);
598 let del_label = format!("-{}", file.deletions);
599 let rows = file.rows;
600 let pairs = file.split_rows;
601 let has_rows = !rows.is_empty() || !pairs.is_empty();
602 let table_class = match (split, anchored) {
603 (true, true) => "diff-table diff-split anchored",
604 (true, false) => "diff-table diff-split",
605 _ => "diff-table",
606 };
607 Ok(view! {
608 <section class="diff-file" id=(file.anchor.as_str()) data-keep-anchor=(file.label.as_str())>
609 <header class="diff-file-header">
610 <code class="diff-path">(file.label.as_str())</code>
611 <span class="diff-file-meta">
612 <span class="muted small">(file.status)</span>
613 <span class="diff-stats"><span class="add">(add_label.as_str())</span> " " <span class="del">(del_label.as_str())</span></span>
614 </span>
615 </header>
616 if file.binary {
617 <p class="muted diff-collapsed">(g::t(lang, K::BinaryFileChanged))</p>
618 } else {
619 if file.truncated {
620 if file.has_blob {
621 <p class="muted diff-collapsed">(g::t(lang, K::DiffTooLargePrefix)) <a href=(file.blob_href.as_str())>(g::t(lang, K::ViewFile))</a></p>
622 } else {
623 <p class="muted diff-collapsed">(g::t(lang, K::DiffTooLarge))</p>
624 }
625 }
626 if has_rows {
627 <div class="diff-file-body">
628 <table class=(table_class)>
629 for row in rows.into_iter() {
630 diff_line(row: row, lang: lang)
631 }
632 for row in pairs.into_iter() {
633 diff_split_line(row: row, lang: lang, anchored: anchored)
634 }
635 </table>
636 </div>
637 }
638 }
639 </section>
640 })
641}
642
643/// One split row as a `<tbody>`: the two sides, then, when either has threads or an open form, a
644/// full-width row holding them. A hunk header spans the table.
645#[component]
646async fn diff_split_line(row: SplitRow, lang: Lang, anchored: bool) -> Result<impl View> {
647 let SplitRow {
648 hunk,
649 left,
650 right,
651 below,
652 } = row;
653 let (threads, form, ctx) = match below {
654 Some(below) => (below.threads, below.form, Some(below.ctx)),
655 None => (Vec::new(), None, None),
656 };
657 let span = if anchored { "6" } else { "4" };
658 let is_hunk = hunk.is_some();
659 let hunk_text = hunk.unwrap_or_default();
660 let left_plus = format!("diff-plus side-{}", left.class);
661 let left_ln = format!("diff-ln side-{}", left.class);
662 let left_code = format!("diff-code side-{}", left.class);
663 let right_plus = format!("diff-plus side-{}", right.class);
664 let right_ln = format!("diff-ln side-{}", right.class);
665 let right_code = format!("diff-code side-{}", right.class);
666 Ok(view! {
667 <tbody>
668 if is_hunk {
669 <tr class="diff-line hunk">
670 <td colspan=(span) class="diff-code">(hunk_text.as_str())</td>
671 </tr>
672 } else {
673 <tr class="diff-split-row">
674 if anchored {
675 <td class=(left_plus.as_str())>
676 if let Some(href) = left.plus_href {
677 <a href=(href.as_str()) title=(g::t(lang, K::CommentOnLine)) aria-label=(g::t(lang, K::CommentOnLine))>"+"</a>
678 }
679 </td>
680 }
681 <td class=(left_ln.as_str())>(left.num.as_str())</td>
682 <td class=(left_code.as_str()) id=(left.anchor.as_deref())>(left.code.as_str())</td>
683 if anchored {
684 <td class=(right_plus.as_str())>
685 if let Some(href) = right.plus_href {
686 <a href=(href.as_str()) title=(g::t(lang, K::CommentOnLine)) aria-label=(g::t(lang, K::CommentOnLine))>"+"</a>
687 }
688 </td>
689 }
690 <td class=(right_ln.as_str())>(right.num.as_str())</td>
691 <td class=(right_code.as_str()) id=(right.anchor.as_deref())>(right.code.as_str())</td>
692 </tr>
693 }
694 if let Some(ctx) = ctx {
695 <tr class="review-row">
696 <td colspan=(span)>
697 <div class="review-threads">
698 for thread in threads.into_iter() {
699 review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files")
700 }
701 if let Some(form) = form {
702 inline_comment_form(form: form, lang: lang)
703 }
704 </div>
705 </td>
706 </tr>
707 }
708 </tbody>
709 })
710}
711
712/// One diff line as a `<tbody>`: the line itself, then, when it has threads or an open form, a
713/// full-width row holding them.
714#[component]
715async fn diff_line(row: DiffRow, lang: Lang) -> Result<impl View> {
716 let DiffRow {
717 class,
718 old,
719 new,
720 code,
721 anchored,
722 anchor,
723 plus_href,
724 below,
725 } = row;
726 let (threads, form, ctx) = match below {
727 Some(below) => (below.threads, below.form, Some(below.ctx)),
728 None => (Vec::new(), None, None),
729 };
730 let span = if anchored { "4" } else { "3" };
731 Ok(view! {
732 <tbody>
733 <tr class=(class) id=(anchor.as_deref())>
734 if anchored {
735 <td class="diff-plus">
736 if let Some(href) = plus_href {
737 <a href=(href.as_str()) title=(g::t(lang, K::CommentOnLine)) aria-label=(g::t(lang, K::CommentOnLine))>"+"</a>
738 }
739 </td>
740 }
741 <td class="diff-ln">(old.as_str())</td>
742 <td class="diff-ln">(new.as_str())</td>
743 <td class="diff-code">(code.as_str())</td>
744 </tr>
745 if let Some(ctx) = ctx {
746 <tr class="review-row">
747 <td colspan=(span)>
748 <div class="review-threads">
749 for thread in threads.into_iter() {
750 review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files")
751 }
752 if let Some(form) = form {
753 inline_comment_form(form: form, lang: lang)
754 }
755 </div>
756 </td>
757 </tr>
758 }
759 </tbody>
760 })
761}
762
763/// The inline comment form under a line. "Add single comment" posts one comment; the review
764/// button starts a review, or adds to the pending one.
765#[component]
766async fn inline_comment_form(form: InlineForm, lang: Lang) -> Result<impl View> {
767 let InlineForm {
768 action,
769 cancel_href,
770 csrf,
771 file_index,
772 side,
773 line,
774 head_oid,
775 has_pending,
776 can_review,
777 suggest_line,
778 } = form;
779 let review_label = if has_pending {
780 g::t(lang, K::AddReviewComment)
781 } else {
782 g::t(lang, K::StartReview)
783 };
784 let suggest_label = pr_g::t(lang, PrK::SuggestChange);
785 Ok(view! {
786 <form method="post" action=(action.as_str()) class="review-inline-form stack">
787 <input type="hidden" name="csrf" value=(csrf.as_str())>
788 <input type="hidden" name="file_index" value=(file_index.as_str())>
789 <input type="hidden" name="side" value=(side)>
790 <input type="hidden" name="line" value=(line.as_str())>
791 <input type="hidden" name="head_oid" value=(head_oid.as_str())>
792 <label>
793 <span>(g::t(lang, K::CommentLabel))</span>
794 <textarea name="body" rows="4"></textarea>
795 </label>
796 <div class="issue-actions">
797 <button type="submit" name="action" value="single">(g::t(lang, K::AddSingleComment))</button>
798 if can_review {
799 <button type="submit" name="action" value="review">(review_label)</button>
800 }
801 if let Some(text) = suggest_line {
802 <button type="button" class="link-button" data-suggest=(text.as_str())>(suggest_label)</button>
803 }
804 <a href=(cancel_href.as_str())>(g::t(lang, K::CancelLink))</a>
805 </div>
806 </form>
807 })
808}