//! Commit diff rendering, shared by the commit page, the comparison page and the pull-request
//! Files tab: the changed-file summary, the per-file index and each file's unified diff in a
//! scroll wrapper. Uses the `diff-*` classes from the stylesheet. `view!` escapes text and
//! attribute values.
//!
//! The Files tab turns on `LineComments`: each numbered line gets an id and a "+" link, the
//! review threads of a line render in a full-width row under it, and the line whose inline
//! comment form is open gets that form. Every line is its own `
`, so those rows can span
//! the table. Commit and comparison pages pass the default, which leaves all of that out.
use std::collections::HashMap;
use forge_core::{Side, Thread};
use forge_git::history::{CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind};
use topcoat::Result;
use topcoat::context::{Cx, app_context};
use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
use topcoat::router::request::uri;
use topcoat::view::{View, component, view};
use crate::auth::current_user;
use crate::i18n::Lang;
use crate::i18n::browse as b;
use crate::i18n::code::{self as g, K};
use crate::i18n::pulls_review::{self as pr_g, K as PrK};
use crate::pages::commits::url_path;
use crate::pages::user_prefs::DIFF_VIEW;
use crate::state::AppState;
use crate::views::review_thread::{ThreadCtx, review_thread_in};
/// Per-diff limits used by the commit and pull-request pages.
pub const LIMITS: DiffLimits = DiffLimits {
max_files: MAX_FILES,
max_lines_per_file: 2000,
max_total_lines: 20_000,
};
/// Files shown before the diff reports truncation. Matches `LIMITS.max_files`.
pub const MAX_FILES: usize = 300;
/// The language of a diff section. It defaults to English, so a page that does not pass one (the
/// comparison and Files tab pages, for now) keeps its English text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DiffLang(pub Lang);
impl Default for DiffLang {
fn default() -> Self {
DiffLang(Lang::En)
}
}
/// Line comments on a diff. The default leaves the diff as commit and comparison pages show it.
#[derive(Default)]
pub struct LineComments {
/// Line ids, the "+" link on each numbered line and the inline form. Set only for a viewer
/// who may comment, so anonymous viewers see no comment controls.
pub anchors: bool,
/// Threads by (file index, side, line). Each renders in the row under its line.
pub threads: HashMap<(usize, Side, u32), Vec>,
/// The line whose inline comment form is open.
pub open_form: Option<(usize, Side, u32)>,
/// URL of the Files tab, such as `/o/r/pulls/3/files`. The "+" links and the form's cancel
/// link point here.
pub files_href: String,
/// The viewer has a pending review, so the form offers "Add review comment".
pub has_pending: bool,
/// What the threads and the form need: the review POST base, CSRF, viewer and permissions.
pub ctx: ThreadCtx,
}
/// Name of the cookie that remembers the viewer's unified or split choice.
pub const DIFF_VIEW_COOKIE: &str = "forge_diff";
/// How a diff page shows its diff: unified or split, whitespace ignored or not, plus what the
/// toolbar needs to build its links. The default has no toolbar and shows a plain unified diff.
#[derive(Clone, Default)]
pub struct DiffOpts {
/// Draw the toolbar.
pub enabled: bool,
pub split: bool,
pub ignore_ws: bool,
/// Path of the page the toolbar links back to.
pub path: String,
/// The request's query pairs except the ones the toolbar owns.
pub query: Vec<(String, String)>,
/// `.patch` and `.diff` download links, when the page has them.
pub downloads: Option<(String, String)>,
}
impl DiffOpts {
/// Reads the request: `?w=1` ignores whitespace. The unified or split view comes from
/// `?view=split|unified`, which wins and is remembered: in the account's `diff_view`
/// preference when signed in, else in a cookie. Without `?view=` the remembered choice
/// decides. `downloads` are the patch and diff links.
pub async fn from_cx(cx: &Cx, downloads: Option<(String, String)>) -> Result {
let request = uri(cx);
let mut view_param = None;
let mut ignore_ws = false;
let mut query = Vec::new();
if let Some(raw) = request.query() {
for (key, value) in form_urlencoded::parse(raw.as_bytes()) {
match key.as_ref() {
"view" => view_param = Some(value.into_owned()),
"w" => ignore_ws = value == "1",
"comment" | "review_error" => {}
_ => query.push((key.into_owned(), value.into_owned())),
}
}
}
let split = match current_user(cx).await? {
Some((user, _)) => {
let state = app_context::(cx);
let stored = state
.store
.user_prefs(&user.id)
.await?
.remove(DIFF_VIEW);
match view_param.as_deref() {
Some(v @ ("split" | "unified")) => {
if stored.as_deref() != Some(v) {
state.store.set_user_pref(&user.id, DIFF_VIEW, v).await?;
}
v == "split"
}
_ => stored.as_deref() == Some("split"),
}
}
None => match view_param.as_deref() {
Some(v @ ("split" | "unified")) => {
let max_age = time::Duration::seconds(365 * 24 * 60 * 60);
cookies(cx).add(
Cookie::build((DIFF_VIEW_COOKIE, v.to_owned()))
.path("/")
.secure(true)
.same_site(SameSite::Lax)
.max_age(max_age)
.build(),
);
v == "split"
}
_ => cookies(cx)
.get(DIFF_VIEW_COOKIE)
.is_some_and(|c| c.value() == "split"),
},
};
Ok(Self {
enabled: true,
split,
ignore_ws,
path: request.path().to_owned(),
query,
downloads,
})
}
/// The page URL for the given view and whitespace setting.
pub fn href(&self, split: bool, ignore_ws: bool) -> String {
let mut ser = form_urlencoded::Serializer::new(String::new());
for (k, v) in &self.query {
ser.append_pair(k, v);
}
ser.append_pair("view", if split { "split" } else { "unified" });
if ignore_ws {
ser.append_pair("w", "1");
}
format!("{}?{}", self.path, ser.finish())
}
}
/// The toolbar above the diff, flattened for the view.
struct Toolbar {
unified_href: String,
split_href: String,
ws_href: String,
split: bool,
ignore_ws: bool,
downloads: Option<(String, String)>,
}
/// The inline comment form under an open line.
struct InlineForm {
action: String,
cancel_href: String,
csrf: String,
file_index: String,
side: &'static str,
line: String,
head_oid: String,
has_pending: bool,
can_review: bool,
/// The text of the commented line, when a suggestion can replace it (a line on the new side).
suggest_line: Option,
}
/// What renders under a line: its threads and, if open, the form.
struct RowBelow {
threads: Vec,
form: Option,
ctx: ThreadCtx,
}
/// One rendered row of a file's diff table.
struct DiffRow {
class: &'static str,
old: String,
new: String,
code: String,
anchored: bool,
/// The `L---` id, when anchors are on and the line has a number.
anchor: Option,
/// Target of the "+" link on this line.
plus_href: Option,
below: Option,
}
/// One file of the diff, flattened for the view.
struct FileView {
anchor: String,
label: String,
status: &'static str,
additions: u32,
deletions: u32,
binary: bool,
truncated: bool,
has_blob: bool,
blob_href: String,
rows: Vec,
/// Rows for the split view; filled in place of `rows` when the diff is split.
split_rows: Vec,
}
/// One side of a split row.
struct SplitSide {
/// `add`, `del`, `ctx`, `ctx dup` (the repeated side of a context line) or `empty`.
class: &'static str,
num: String,
code: String,
anchor: Option,
plus_href: Option,
}
impl SplitSide {
fn empty() -> Self {
Self {
class: "empty",
num: String::new(),
code: String::new(),
anchor: None,
plus_href: None,
}
}
fn from_row(row: DiffRow, class: &'static str, num: String) -> (Self, Option) {
(
Self {
class,
num,
code: row.code,
anchor: row.anchor,
plus_href: row.plus_href,
},
row.below,
)
}
}
/// A row of the split table: a hunk header, or a left and a right side with what sits below.
struct SplitRow {
hunk: Option,
left: SplitSide,
right: SplitSide,
below: Option,
}
fn merge_below(a: Option, b: Option) -> Option {
match (a, b) {
(Some(mut a), Some(b)) => {
a.threads.extend(b.threads);
if a.form.is_none() {
a.form = b.form;
}
Some(a)
}
(a, None) => a,
(None, b) => b,
}
}
/// Pairs each run of deleted lines with the added lines that follow it, side by side.
fn flush_pairs(out: &mut Vec, dels: &mut Vec, adds: &mut Vec) {
let mut dels = std::mem::take(dels).into_iter();
let mut adds = std::mem::take(adds).into_iter();
loop {
let (d, a) = (dels.next(), adds.next());
if d.is_none() && a.is_none() {
break;
}
let (left, left_below) = match d {
Some(row) => {
let num = row.old.clone();
SplitSide::from_row(row, "del", num)
}
None => (SplitSide::empty(), None),
};
let (right, right_below) = match a {
Some(row) => {
let num = row.new.clone();
SplitSide::from_row(row, "add", num)
}
None => (SplitSide::empty(), None),
};
out.push(SplitRow {
hunk: None,
left,
right,
below: merge_below(left_below, right_below),
});
}
}
fn split_rows(rows: Vec) -> Vec {
let mut out = Vec::new();
let mut dels: Vec = Vec::new();
let mut adds: Vec = Vec::new();
for row in rows {
match row.class {
"diff-line del" => {
if !adds.is_empty() {
flush_pairs(&mut out, &mut dels, &mut adds);
}
dels.push(row);
}
"diff-line add" => adds.push(row),
"diff-line hunk" => {
flush_pairs(&mut out, &mut dels, &mut adds);
out.push(SplitRow {
hunk: Some(row.code),
left: SplitSide::empty(),
right: SplitSide::empty(),
below: None,
});
}
_ => {
flush_pairs(&mut out, &mut dels, &mut adds);
let left = SplitSide {
class: "ctx",
num: row.old.clone(),
code: row.code.clone(),
anchor: None,
plus_href: None,
};
let new = row.new.clone();
let (right, below) = SplitSide::from_row(row, "ctx dup", new);
out.push(SplitRow {
hunk: None,
left,
right,
below,
});
}
}
}
flush_pairs(&mut out, &mut dels, &mut adds);
out
}
impl FileView {
/// `oid` is the commit being shown; `parent` is its first parent, used for the blob link of
/// deleted files (they are absent at `oid`). `comments` supplies the review data and is
/// drained of the threads it renders.
#[allow(clippy::too_many_arguments)]
fn new(
index: usize,
file: &FileDiff,
oid: &str,
parent: Option<&str>,
owner: &str,
repo: &str,
lang: Lang,
comments: &mut LineComments,
) -> Self {
let label = match (&file.old_path, &file.new_path) {
(Some(old), Some(new)) if old != new => format!("{old} → {new}"),
(_, Some(new)) => new.clone(),
(Some(old), None) => old.clone(),
(None, None) => String::new(),
};
let status = match file.status {
DiffStatus::Added => g::t(lang, K::StatusAdded),
DiffStatus::Deleted => g::t(lang, K::StatusDeleted),
DiffStatus::Modified => g::t(lang, K::StatusModified),
DiffStatus::Renamed => g::t(lang, K::StatusRenamed),
DiffStatus::Copied => g::t(lang, K::StatusCopied),
DiffStatus::TypeChanged => g::t(lang, K::StatusTypeChanged),
};
// A deleted file is absent at this commit, so its blob is read from the parent.
let blob_commit = match file.status {
DiffStatus::Deleted => parent,
_ => Some(oid),
};
let blob_path = file.new_path.as_ref().or(file.old_path.as_ref());
let blob_href = match (blob_commit, blob_path) {
(Some(commit), Some(path)) => {
format!("/{owner}/{repo}/blob/{commit}/{}", url_path(path))
}
_ => String::new(),
};
let mut rows = Vec::new();
for hunk in &file.hunks {
rows.push(DiffRow {
class: "diff-line hunk",
old: String::new(),
new: String::new(),
code: hunk.header.clone(),
anchored: comments.anchors,
anchor: None,
plus_href: None,
below: None,
});
for line in &hunk.lines {
let (class, code) = match line.kind {
LineKind::Add => ("diff-line add", format!("+{}", line.text)),
LineKind::Del => ("diff-line del", format!("-{}", line.text)),
LineKind::Context => ("diff-line ctx", format!(" {}", line.text)),
LineKind::NoNewline => ("diff-line ctx", line.text.clone()),
};
// Deleted lines sit on the old side; added and context lines on the new side.
let key = match line.kind {
LineKind::Add | LineKind::Context => line.new_no.map(|n| (Side::New, n)),
LineKind::Del => line.old_no.map(|n| (Side::Old, n)),
LineKind::NoNewline => None,
};
let (anchor, plus_href, below) =
match key {
Some((side, number)) => {
let id = format!("L-{index}-{}-{number}", side.as_str());
let anchor = comments.anchors.then(|| id.clone());
let plus_href = comments.anchors.then(|| {
format!(
"{}?comment={index}:{}:{number}#{id}",
comments.files_href,
side.as_str()
)
});
let target = (index, side, number);
let threads = comments.threads.remove(&target).unwrap_or_default();
let form = (comments.anchors && comments.open_form == Some(target))
.then(|| InlineForm {
action: format!("{}/review_comments", comments.ctx.pr_href),
cancel_href: comments.files_href.clone(),
csrf: comments.ctx.csrf.clone(),
file_index: index.to_string(),
side: side.as_str(),
line: number.to_string(),
head_oid: oid.to_owned(),
has_pending: comments.has_pending,
can_review: comments.ctx.can_review,
suggest_line: (side == Side::New).then(|| line.text.clone()),
});
let below = (!threads.is_empty() || form.is_some()).then(|| RowBelow {
threads,
form,
ctx: comments.ctx.clone(),
});
(anchor, plus_href, below)
}
None => (None, None, None),
};
rows.push(DiffRow {
class,
old: line.old_no.map(|n| n.to_string()).unwrap_or_default(),
new: line.new_no.map(|n| n.to_string()).unwrap_or_default(),
code,
anchored: comments.anchors,
anchor,
plus_href,
below,
});
}
}
Self {
anchor: format!("file-{}", index + 1),
label,
status,
additions: file.additions,
deletions: file.deletions,
binary: file.is_binary,
truncated: file.truncated,
has_blob: !blob_href.is_empty(),
blob_href,
rows,
split_rows: Vec::new(),
}
}
}
/// Entry in the file index at the top of the diff.
struct NavItem {
anchor_href: String,
label: String,
additions: u32,
deletions: u32,
}
/// The whole diff section: a summary heading with totals, the file index and every file's
/// diff. `owner` and `repo` name the repository for "view file" links, `oid` is the commit the
/// diff belongs to, and `parent` is its first parent (`None` for a root commit). `subject` names
/// what the diff shows in the truncation note, such as "this commit" or "this comparison".
/// `comments` turns on the line comments of the Files tab; the default renders a plain diff.
#[allow(clippy::too_many_arguments)]
#[component]
pub async fn diff_section(
diff: &CommitDiff,
owner: &str,
repo: &str,
oid: &str,
parent: Option<&str>,
subject: &str,
#[default] lang: DiffLang,
#[default] comments: LineComments,
#[default] opts: DiffOpts,
) -> Result {
let lang = lang.0;
let mut comments = comments;
let anchored = comments.anchors;
let split = opts.split;
let mut files: Vec = diff
.files
.iter()
.enumerate()
.map(|(i, file)| FileView::new(i, file, oid, parent, owner, repo, lang, &mut comments))
.collect();
if split {
for file in &mut files {
file.split_rows = split_rows(std::mem::take(&mut file.rows));
}
}
let toolbar = opts.enabled.then(|| Toolbar {
unified_href: opts.href(false, opts.ignore_ws),
split_href: opts.href(true, opts.ignore_ws),
ws_href: opts.href(opts.split, !opts.ignore_ws),
split: opts.split,
ignore_ws: opts.ignore_ws,
downloads: opts.downloads.clone(),
});
let nav: Vec = files
.iter()
.map(|f| NavItem {
anchor_href: format!("#{}", f.anchor),
label: f.label.clone(),
additions: f.additions,
deletions: f.deletions,
})
.collect();
let total_add: u32 = files.iter().map(|f| f.additions).sum();
let total_del: u32 = files.iter().map(|f| f.deletions).sum();
let file_count = files.len();
let no_files = files.is_empty();
let files_label = g::changed_files(lang, file_count);
let truncated_note = g::diff_truncated(lang, MAX_FILES, subject);
let truncated_files = diff.truncated_files;
let add_label = format!("+{total_add}");
let del_label = format!("-{total_del}");
Ok(view! {
(files_label.as_str()) " " (add_label.as_str()) " " (del_label.as_str())
if let Some(bar) = toolbar {
diff_toolbar(bar: bar, lang: lang)
}
if truncated_files {
(truncated_note.as_str())
}
if no_files {
(g::t(lang, K::NoFileChanges))
} else {
for item in nav.iter() {
-
(item.label.as_str())
" "
(format!("+{}", item.additions)) " " (format!("-{}", item.deletions))
}
for file in files.into_iter() {
diff_file(file: file, lang: lang, split: split, anchored: anchored)
}
}
})
}
/// Unified or split, ignore whitespace, and the patch and diff downloads.
#[component]
async fn diff_toolbar(bar: Toolbar, lang: Lang) -> Result {
let unified_on = if bar.split { "false" } else { "true" };
let split_on = if bar.split { "true" } else { "false" };
let ws_on = if bar.ignore_ws { "true" } else { "false" };
Ok(view! {
})
}
#[component]
async fn diff_file(file: FileView, lang: Lang, split: bool, anchored: bool) -> Result {
let add_label = format!("+{}", file.additions);
let del_label = format!("-{}", file.deletions);
let rows = file.rows;
let pairs = file.split_rows;
let has_rows = !rows.is_empty() || !pairs.is_empty();
let table_class = match (split, anchored) {
(true, true) => "diff-table diff-split anchored",
(true, false) => "diff-table diff-split",
_ => "diff-table",
};
Ok(view! {
if file.binary {
(g::t(lang, K::BinaryFileChanged))
} else {
if file.truncated {
if file.has_blob {
(g::t(lang, K::DiffTooLargePrefix)) (g::t(lang, K::ViewFile))
} else {
(g::t(lang, K::DiffTooLarge))
}
}
if has_rows {
for row in rows.into_iter() {
diff_line(row: row, lang: lang)
}
for row in pairs.into_iter() {
diff_split_line(row: row, lang: lang, anchored: anchored)
}
}
}
})
}
/// One split row as a ``: the two sides, then, when either has threads or an open form, a
/// full-width row holding them. A hunk header spans the table.
#[component]
async fn diff_split_line(row: SplitRow, lang: Lang, anchored: bool) -> Result {
let SplitRow {
hunk,
left,
right,
below,
} = row;
let (threads, form, ctx) = match below {
Some(below) => (below.threads, below.form, Some(below.ctx)),
None => (Vec::new(), None, None),
};
let span = if anchored { "6" } else { "4" };
let is_hunk = hunk.is_some();
let hunk_text = hunk.unwrap_or_default();
let left_plus = format!("diff-plus side-{}", left.class);
let left_ln = format!("diff-ln side-{}", left.class);
let left_code = format!("diff-code side-{}", left.class);
let right_plus = format!("diff-plus side-{}", right.class);
let right_ln = format!("diff-ln side-{}", right.class);
let right_code = format!("diff-code side-{}", right.class);
Ok(view! {
if is_hunk {
| (hunk_text.as_str()) |
} else {
if anchored {
|
if let Some(href) = left.plus_href {
"+"
}
|
}
(left.num.as_str()) |
(left.code.as_str()) |
if anchored {
if let Some(href) = right.plus_href {
"+"
}
|
}
(right.num.as_str()) |
(right.code.as_str()) |
}
if let Some(ctx) = ctx {
|
for thread in threads.into_iter() {
review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files")
}
if let Some(form) = form {
inline_comment_form(form: form, lang: lang)
}
|
}
})
}
/// One diff line as a ``: the line itself, then, when it has threads or an open form, a
/// full-width row holding them.
#[component]
async fn diff_line(row: DiffRow, lang: Lang) -> Result {
let DiffRow {
class,
old,
new,
code,
anchored,
anchor,
plus_href,
below,
} = row;
let (threads, form, ctx) = match below {
Some(below) => (below.threads, below.form, Some(below.ctx)),
None => (Vec::new(), None, None),
};
let span = if anchored { "4" } else { "3" };
Ok(view! {
if anchored {
|
if let Some(href) = plus_href {
"+"
}
|
}
(old.as_str()) |
(new.as_str()) |
(code.as_str()) |
if let Some(ctx) = ctx {
|
for thread in threads.into_iter() {
review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files")
}
if let Some(form) = form {
inline_comment_form(form: form, lang: lang)
}
|
}
})
}
/// The inline comment form under a line. "Add single comment" posts one comment; the review
/// button starts a review, or adds to the pending one.
#[component]
async fn inline_comment_form(form: InlineForm, lang: Lang) -> Result {
let InlineForm {
action,
cancel_href,
csrf,
file_index,
side,
line,
head_oid,
has_pending,
can_review,
suggest_line,
} = form;
let review_label = if has_pending {
g::t(lang, K::AddReviewComment)
} else {
g::t(lang, K::StartReview)
};
let suggest_label = pr_g::t(lang, PrK::SuggestChange);
Ok(view! {
})
}