forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiB8e56ffcTahinli1 month ago262 commits

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