forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiBc8ea10cTahinli27 days ago292 commits

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