Unified/split diff toggle, ignore whitespace and .patch/.diff downloads
Browse files at this commit4be055313b57318c08fa624a5a79f7d0c8f53fcaParent: 620ce2c- feat
- unified/split diff toggle, ignore whitespace and .patch/.diff downloads
7 changed files +698 -40
- crates/forge-web/src/i18n/browse.rs +137 -0
- crates/forge-web/src/i18n/mod.rs +1 -0
- crates/forge-web/src/pages/commit.rs +63 -6
- crates/forge-web/src/pages/compare.rs +50 -5
- crates/forge-web/src/pages/pull_files.rs +25 -6
- crates/forge-web/src/pages/repo_ctx.rs +66 -18
- crates/forge-web/src/views/diff.rs +356 -5
crates/forge-web/src/i18n/browse.rsadded+137 -0
| @@ -0,0 +1,137 @@ | |||
| 1 | +//! Strings for the code-browsing upgrades: the diff toolbar, blob line selection, blame, the file | ||
| 2 | +//! finder and the branches page. The `strings!` macro keeps the key list, the lookup and the test | ||
| 3 | +//! list in one place. | ||
| 4 | + | ||
| 5 | +use super::Lang; | ||
| 6 | + | ||
| 7 | +macro_rules! strings { | ||
| 8 | + ($($key:ident => $en:expr, $tr:expr;)*) => { | ||
| 9 | + #[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 10 | + pub enum K { | ||
| 11 | + $($key,)* | ||
| 12 | + } | ||
| 13 | + | ||
| 14 | + pub fn t(lang: Lang, key: K) -> &'static str { | ||
| 15 | + match (key, lang) { | ||
| 16 | + $((K::$key, Lang::En) => $en, (K::$key, Lang::Tr) => $tr,)* | ||
| 17 | + } | ||
| 18 | + } | ||
| 19 | + | ||
| 20 | + #[cfg(test)] | ||
| 21 | + const ALL: &[K] = &[$(K::$key,)*]; | ||
| 22 | + }; | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +strings! { | ||
| 26 | + DiffView => "Diff view", "Fark görünümü"; | ||
| 27 | + Unified => "Unified", "Birleşik"; | ||
| 28 | + Split => "Split", "Bölünmüş"; | ||
| 29 | + IgnoreWhitespace => "Ignore whitespace", "Boşlukları yoksay"; | ||
| 30 | + PatchLink => ".patch", ".patch"; | ||
| 31 | + DiffLink => ".diff", ".diff"; | ||
| 32 | + PatchTitle => "Download as an email-style patch", "E-posta biçiminde yama olarak indir"; | ||
| 33 | + DiffTitle => "Download as a plain diff", "Düz fark olarak indir"; | ||
| 34 | + | ||
| 35 | + BlameLink => "Blame", "Satır geçmişi"; | ||
| 36 | + BlameTitle => "Blame", "Satır geçmişi"; | ||
| 37 | + BlameBackToFile => "Back to file", "Dosyaya dön"; | ||
| 38 | + BlamePrior => "Blame prior to this commit", "Bu işlemeden önceki satır geçmişi"; | ||
| 39 | + BlameTimeout => "Blame took too long and was stopped. Try a smaller file or git on your machine.", "Satır geçmişi çok uzun sürdü ve durduruldu. Daha küçük bir dosya deneyin ya da kendi makinenizde git çalıştırın."; | ||
| 40 | + BlameFailed => "Blame could not be computed for this file.", "Bu dosya için satır geçmişi hesaplanamadı."; | ||
| 41 | + BlameNotText => "Blame is only available for text files.", "Satır geçmişi yalnızca metin dosyaları için kullanılabilir."; | ||
| 42 | + | ||
| 43 | + CopyPermalink => "Copy permalink", "Kalıcı bağlantıyı kopyala"; | ||
| 44 | + PermalinkCopied => "Permalink copied", "Kalıcı bağlantı kopyalandı"; | ||
| 45 | + PermalinkHint => "Link to this exact commit. Press y to switch the address bar.", "Tam bu işlemeye bağlantı. Adres çubuğunu değiştirmek için y'ye basın."; | ||
| 46 | + | ||
| 47 | + GoToFile => "Go to file", "Dosyaya git"; | ||
| 48 | + FinderTitle => "Go to file", "Dosyaya git"; | ||
| 49 | + FinderPlaceholder => "Type to find a file", "Dosya bulmak için yazın"; | ||
| 50 | + FinderHint => "Up and down to move, Enter to open, Esc to close", "Gezinmek için yukarı ve aşağı, açmak için Enter, kapatmak için Esc"; | ||
| 51 | + FinderEmpty => "No matching files", "Eşleşen dosya yok"; | ||
| 52 | + FinderLoading => "Loading files", "Dosyalar yükleniyor"; | ||
| 53 | + FinderFailed => "The file list could not be loaded.", "Dosya listesi yüklenemedi."; | ||
| 54 | + FinderTruncated => "Very large tree: only the first files are searchable.", "Çok büyük ağaç: yalnızca ilk dosyalar aranabilir."; | ||
| 55 | + | ||
| 56 | + BranchAuthorHeader => "Author", "Yazar"; | ||
| 57 | + BranchAheadBehindHeader => "Ahead / behind", "Önde / geride"; | ||
| 58 | + BranchActionsHeader => "Actions", "İşlemler"; | ||
| 59 | + UpToDate => "Even with the default branch", "Varsayılan dalla aynı"; | ||
| 60 | + NewPr => "New PR", "Yeni PR"; | ||
| 61 | + DeleteBranch => "Delete", "Sil"; | ||
| 62 | + DeleteConfirm => "Delete this branch? Its commits stay in the repository until they are cleaned up.", "Bu dal silinsin mi? İşlemeleri temizlenene kadar depoda kalır."; | ||
| 63 | + DeleteConfirmYes => "Yes, delete branch", "Evet, dalı sil"; | ||
| 64 | + DeleteCancel => "Cancel", "Vazgeç"; | ||
| 65 | + NewBranchTitle => "New branch", "Yeni dal"; | ||
| 66 | + BranchNameLabel => "Branch name", "Dal adı"; | ||
| 67 | + BranchFromLabel => "From", "Kaynak"; | ||
| 68 | + BranchFromPlaceholder => "branch, tag or commit", "dal, etiket veya işleme"; | ||
| 69 | + CreateBranch => "Create branch", "Dal oluştur"; | ||
| 70 | + BranchCreated => "Branch created.", "Dal oluşturuldu."; | ||
| 71 | + BranchDeleted => "Branch deleted.", "Dal silindi."; | ||
| 72 | + BranchExists => "A branch with that name already exists.", "Bu adda bir dal zaten var."; | ||
| 73 | + BranchInvalidName => "That is not a valid branch name.", "Bu geçerli bir dal adı değil."; | ||
| 74 | + BranchSourceMissing => "The source branch, tag or commit was not found.", "Kaynak dal, etiket veya işleme bulunamadı."; | ||
| 75 | + BranchIsDefault => "The default branch cannot be deleted. Change the default branch in settings first.", "Varsayılan dal silinemez. Önce ayarlardan varsayılan dalı değiştirin."; | ||
| 76 | + BranchProtectedDelete => "This branch is protected and cannot be deleted.", "Bu dal korumalı ve silinemez."; | ||
| 77 | + BranchPullOnly => "A protection rule on this branch only allows changes through pull requests.", "Bu daldaki bir koruma kuralı yalnızca birleştirme istekleriyle değişikliğe izin verir."; | ||
| 78 | + BranchGone => "That branch no longer exists or has moved.", "Bu dal artık yok ya da taşındı."; | ||
| 79 | + BranchFailed => "The branch change could not be made.", "Dal değişikliği yapılamadı."; | ||
| 80 | + BranchForbidden => "You need write access to change branches.", "Dalları değiştirmek için yazma erişimi gerekir."; | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// "3 ahead, 1 behind", or the up-to-date text when both are zero. | ||
| 84 | +pub fn ahead_behind(lang: Lang, ahead: u32, behind: u32) -> String { | ||
| 85 | + match lang { | ||
| 86 | + Lang::En => format!("{ahead} ahead, {behind} behind"), | ||
| 87 | + Lang::Tr => format!("{ahead} önde, {behind} geride"), | ||
| 88 | + } | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// "Delete branch `name`?" for the accessible name of the delete button. | ||
| 92 | +pub fn delete_aria(lang: Lang, name: &str) -> String { | ||
| 93 | + match lang { | ||
| 94 | + Lang::En => format!("Delete branch {name}"), | ||
| 95 | + Lang::Tr => format!("{name} dalını sil"), | ||
| 96 | + } | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// Shown when blame has a file of `size` bytes over the limit. | ||
| 100 | +pub fn blame_limit(lang: Lang, limit: &str) -> String { | ||
| 101 | + match lang { | ||
| 102 | + Lang::En => format!("Blame is limited to files of {limit} or less."), | ||
| 103 | + Lang::Tr => format!("Satır geçmişi en çok {limit} boyutundaki dosyalarla sınırlıdır."), | ||
| 104 | + } | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +#[cfg(test)] | ||
| 108 | +mod tests { | ||
| 109 | + use super::*; | ||
| 110 | + | ||
| 111 | + #[test] | ||
| 112 | + fn every_key_has_text_in_both_languages() { | ||
| 113 | + for key in ALL { | ||
| 114 | + assert!(!t(Lang::En, *key).is_empty(), "{key:?} has no English text"); | ||
| 115 | + assert!(!t(Lang::Tr, *key).is_empty(), "{key:?} has no Turkish text"); | ||
| 116 | + } | ||
| 117 | + } | ||
| 118 | + | ||
| 119 | + #[test] | ||
| 120 | + fn no_em_dashes() { | ||
| 121 | + for key in ALL { | ||
| 122 | + for lang in [Lang::En, Lang::Tr] { | ||
| 123 | + assert!( | ||
| 124 | + !t(lang, *key).contains('\u{2014}'), | ||
| 125 | + "{key:?} has an em dash" | ||
| 126 | + ); | ||
| 127 | + } | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + #[test] | ||
| 132 | + fn helpers_carry_their_arguments() { | ||
| 133 | + assert_eq!(ahead_behind(Lang::En, 3, 1), "3 ahead, 1 behind"); | ||
| 134 | + assert!(delete_aria(Lang::Tr, "x").contains('x')); | ||
| 135 | + assert!(blame_limit(Lang::En, "1 MiB").contains("1 MiB")); | ||
| 136 | + } | ||
| 137 | +} | ||
crates/forge-web/src/i18n/mod.rsmodified+1 -0
| @@ -19,6 +19,7 @@ use forge_core::User; | |||
| 19 | 19 | ||
| 20 | pub mod accents; | 20 | pub mod accents; |
| 21 | pub mod admin; | 21 | pub mod admin; |
| 22 | +pub mod browse; | ||
| 22 | pub mod code; | 23 | pub mod code; |
| 23 | pub mod community; | 24 | pub mod community; |
| 24 | pub mod integrations; | 25 | pub mod integrations; |
crates/forge-web/src/pages/commit.rsmodified+63 -6
| @@ -5,7 +5,7 @@ use forge_git::browse; | |||
| 5 | use forge_git::history; | 5 | use forge_git::history; |
| 6 | use topcoat::Result; | 6 | use topcoat::Result; |
| 7 | use topcoat::context::{Cx, app_context}; | 7 | use topcoat::context::{Cx, app_context}; |
| 8 | -use topcoat::router::error::not_found; | 8 | +use topcoat::router::error::{content_too_large, not_found}; |
| 9 | use topcoat::router::{page, path_param, route}; | 9 | use topcoat::router::{page, path_param, route}; |
| 10 | use topcoat::view::{View, view}; | 10 | use topcoat::view::{View, view}; |
| 11 | 11 | ||
| @@ -13,12 +13,12 @@ use crate::i18n::code::{self as g, K}; | |||
| 13 | use crate::i18n::{self}; | 13 | use crate::i18n::{self}; |
| 14 | use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid}; | 14 | use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid}; |
| 15 | use crate::pages::repo::repo_head; | 15 | use crate::pages::repo::repo_head; |
| 16 | -use crate::pages::repo_ctx::load_repo; | 16 | +use crate::pages::repo_ctx::{RawDownload, load_repo}; |
| 17 | use crate::render::emoji::emojify; | 17 | use crate::render::emoji::emojify; |
| 18 | use crate::signatures; | 18 | use crate::signatures; |
| 19 | use crate::state::AppState; | 19 | use crate::state::AppState; |
| 20 | use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary}; | 20 | use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary}; |
| 21 | -use crate::views::diff::{DiffLang, LIMITS, diff_section}; | 21 | +use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section}; |
| 22 | use crate::views::relative_time; | 22 | use crate::views::relative_time; |
| 23 | use crate::views::shell; | 23 | use crate::views::shell; |
| 24 | 24 | ||
| @@ -43,11 +43,47 @@ fn is_hex_prefix(s: &str) -> bool { | |||
| 43 | (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit()) | 43 | (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit()) |
| 44 | } | 44 | } |
| 45 | 45 | ||
| 46 | +/// Which plain download a `.patch` or `.diff` suffix asks for. | ||
| 47 | +#[derive(Clone, Copy, PartialEq, Eq)] | ||
| 48 | +pub enum Download { | ||
| 49 | + Patch, | ||
| 50 | + Diff, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +impl Download { | ||
| 54 | + /// Splits a `.patch` or `.diff` suffix off `spec`. | ||
| 55 | + pub fn split(spec: &str) -> (&str, Option<Download>) { | ||
| 56 | + if let Some(rest) = spec.strip_suffix(".patch") { | ||
| 57 | + (rest, Some(Download::Patch)) | ||
| 58 | + } else if let Some(rest) = spec.strip_suffix(".diff") { | ||
| 59 | + (rest, Some(Download::Diff)) | ||
| 60 | + } else { | ||
| 61 | + (spec, None) | ||
| 62 | + } | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + /// The bytes as a download. Output cut at the cap is refused rather than served broken. | ||
| 66 | + pub fn serve(self, out: history::PatchOut, stem: &str) -> Result<RawDownload> { | ||
| 67 | + if !out.complete { | ||
| 68 | + return Err(content_too_large().into()); | ||
| 69 | + } | ||
| 70 | + let ext = match self { | ||
| 71 | + Download::Patch => "patch", | ||
| 72 | + Download::Diff => "diff", | ||
| 73 | + }; | ||
| 74 | + Ok(RawDownload { | ||
| 75 | + content_type: "text/plain; charset=utf-8", | ||
| 76 | + filename: format!("{stem}.{ext}"), | ||
| 77 | + data: out.data, | ||
| 78 | + }) | ||
| 79 | + } | ||
| 80 | +} | ||
| 81 | + | ||
| 46 | #[page("/{owner}/{repo}/commit/{oid}")] | 82 | #[page("/{owner}/{repo}/commit/{oid}")] |
| 47 | async fn commit_page(cx: &Cx) -> Result<impl View> { | 83 | async fn commit_page(cx: &Cx) -> Result<impl View> { |
| 48 | let owner = path_param::<Owner>(cx); | 84 | let owner = path_param::<Owner>(cx); |
| 49 | let name = path_param::<Repo>(cx); | 85 | let name = path_param::<Repo>(cx); |
| 50 | - let rev = path_param::<Oid>(cx); | 86 | + let (rev, download) = Download::split(path_param::<Oid>(cx)); |
| 51 | if !is_hex_prefix(rev) { | 87 | if !is_hex_prefix(rev) { |
| 52 | return Err(not_found().into()); | 88 | return Err(not_found().into()); |
| 53 | } | 89 | } |
| @@ -66,7 +102,28 @@ async fn commit_page(cx: &Cx) -> Result<impl View> { | |||
| 66 | let Some(info) = blocking(move || browse::read_commit(&repo_dir, &lookup)).await? else { | 102 | let Some(info) = blocking(move || browse::read_commit(&repo_dir, &lookup)).await? else { |
| 67 | return Err(not_found().into()); | 103 | return Err(not_found().into()); |
| 68 | }; | 104 | }; |
| 69 | - let diff = history::commit_diff(&state.git, &ctx.path, &info.oid, LIMITS).await?; | 105 | + if let Some(kind) = download { |
| 106 | + let out = match kind { | ||
| 107 | + Download::Patch => history::commit_patch(&state.git, &ctx.path, &info.oid).await?, | ||
| 108 | + Download::Diff => history::commit_raw_diff(&state.git, &ctx.path, &info.oid).await?, | ||
| 109 | + }; | ||
| 110 | + return Err(kind.serve(out, &info.oid)?.into()); | ||
| 111 | + } | ||
| 112 | + let opts = DiffOpts::from_cx( | ||
| 113 | + cx, | ||
| 114 | + Some(( | ||
| 115 | + format!( | ||
| 116 | + "/{}/{}/commit/{}.patch", | ||
| 117 | + ctx.repo.owner_name, ctx.repo.name, info.oid | ||
| 118 | + ), | ||
| 119 | + format!( | ||
| 120 | + "/{}/{}/commit/{}.diff", | ||
| 121 | + ctx.repo.owner_name, ctx.repo.name, info.oid | ||
| 122 | + ), | ||
| 123 | + )), | ||
| 124 | + ); | ||
| 125 | + let diff = | ||
| 126 | + history::commit_diff_ws(&state.git, &ctx.path, &info.oid, LIMITS, opts.ignore_ws).await?; | ||
| 70 | 127 | ||
| 71 | let owner_name = ctx.repo.owner_name.clone(); | 128 | let owner_name = ctx.repo.owner_name.clone(); |
| 72 | let repo_name = ctx.repo.name.clone(); | 129 | let repo_name = ctx.repo.name.clone(); |
| @@ -145,7 +202,7 @@ async fn commit_page(cx: &Cx) -> Result<impl View> { | |||
| 145 | if has_body { | 202 | if has_body { |
| 146 | <pre class="code commit-message"><code>(message.as_str())</code></pre> | 203 | <pre class="code commit-message"><code>(message.as_str())</code></pre> |
| 147 | } | 204 | } |
| 148 | - diff_section(diff: &diff, owner: owner_name.as_str(), repo: repo_name.as_str(), oid: info.oid.as_str(), parent: parent.as_deref(), subject: g::t(lang, K::ThisCommit), lang: DiffLang(lang)) | 205 | + diff_section(diff: &diff, owner: owner_name.as_str(), repo: repo_name.as_str(), oid: info.oid.as_str(), parent: parent.as_deref(), subject: g::t(lang, K::ThisCommit), lang: DiffLang(lang), opts: opts) |
| 149 | ) | 206 | ) |
| 150 | }) | 207 | }) |
| 151 | } | 208 | } |
crates/forge-web/src/pages/compare.rsmodified+50 -5
| @@ -14,6 +14,7 @@ use std::path::PathBuf; | |||
| 14 | use forge_core::{Action, Repo as RepoRecord, Session, authorize, validate_body, validate_title}; | 14 | use forge_core::{Action, Repo as RepoRecord, Session, authorize, validate_body, validate_title}; |
| 15 | use forge_git::browse::{self, CommitInfo, RefKind}; | 15 | use forge_git::browse::{self, CommitInfo, RefKind}; |
| 16 | use forge_git::command::ObjectSource; | 16 | use forge_git::command::ObjectSource; |
| 17 | +use forge_git::history; | ||
| 17 | use forge_git::pulls; | 18 | use forge_git::pulls; |
| 18 | use forge_git::repo::repo_path; | 19 | use forge_git::repo::repo_path; |
| 19 | use serde::Deserialize; | 20 | use serde::Deserialize; |
| @@ -28,12 +29,13 @@ use crate::auth::{check_csrf, require_user}; | |||
| 28 | use crate::i18n; | 29 | use crate::i18n; |
| 29 | use crate::i18n::pulls::{self as g, K}; | 30 | use crate::i18n::pulls::{self as g, K}; |
| 30 | use crate::notify::{self, Activity}; | 31 | use crate::notify::{self, Activity}; |
| 31 | -use crate::pages::commits::{CommitRow, blocking, now_secs, url_path}; | 32 | +use crate::pages::commit::Download; |
| 33 | +use crate::pages::commits::{CommitRow, blocking, now_secs, short_oid, url_path}; | ||
| 32 | use crate::pages::repo::repo_head; | 34 | use crate::pages::repo::repo_head; |
| 33 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; | 35 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| 34 | use crate::state::AppState; | 36 | use crate::state::AppState; |
| 35 | use crate::templates; | 37 | use crate::templates; |
| 36 | -use crate::views::diff::{DiffLang, LIMITS, diff_section}; | 38 | +use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section}; |
| 37 | use crate::views::{alert, repo_href, shell, user_facing_message}; | 39 | use crate::views::{alert, repo_href, shell, user_facing_message}; |
| 38 | use crate::webhooks::emit::{Sender, emit_pull}; | 40 | use crate::webhooks::emit::{Sender, emit_pull}; |
| 39 | 41 | ||
| @@ -256,15 +258,29 @@ async fn compare_view( | |||
| 256 | let show_diff = related && has_commits; | 258 | let show_diff = related && has_commits; |
| 257 | let parent = cmp.merge_base.clone(); | 259 | let parent = cmp.merge_base.clone(); |
| 258 | 260 | ||
| 261 | + let compare_path = format!( | ||
| 262 | + "/{owner}/{name}/compare/{}", | ||
| 263 | + url_path(&format!("{base}...{head}")) | ||
| 264 | + ); | ||
| 265 | + let mut opts = DiffOpts::from_cx( | ||
| 266 | + cx, | ||
| 267 | + Some(( | ||
| 268 | + format!("{compare_path}.patch"), | ||
| 269 | + format!("{compare_path}.diff"), | ||
| 270 | + )), | ||
| 271 | + ); | ||
| 272 | + // The page may be a failed POST re-shown; the toolbar still links to the comparison itself. | ||
| 273 | + opts.path = compare_path; | ||
| 259 | let diff = if show_diff { | 274 | let diff = if show_diff { |
| 260 | Some( | 275 | Some( |
| 261 | - pulls::range_diff_files_with( | 276 | + pulls::range_diff_files_ws( |
| 262 | &state.git, | 277 | &state.git, |
| 263 | &ctx.path, | 278 | &ctx.path, |
| 264 | cmp.objects(), | 279 | cmp.objects(), |
| 265 | &cmp.base_oid, | 280 | &cmp.base_oid, |
| 266 | &cmp.head_oid, | 281 | &cmp.head_oid, |
| 267 | LIMITS, | 282 | LIMITS, |
| 283 | + opts.ignore_ws, | ||
| 268 | ) | 284 | ) |
| 269 | .await?, | 285 | .await?, |
| 270 | ) | 286 | ) |
| @@ -374,7 +390,7 @@ async fn compare_view( | |||
| 374 | } | 390 | } |
| 375 | if show_diff { | 391 | if show_diff { |
| 376 | for d in diff.iter() { | 392 | for d in diff.iter() { |
| 377 | - diff_section(diff: d, owner: owner.as_str(), repo: name.as_str(), oid: cmp.head_oid.as_str(), parent: parent.as_deref(), subject: g::t(lang, K::ThisComparison), lang: DiffLang(lang)) | 393 | + diff_section(diff: d, owner: owner.as_str(), repo: name.as_str(), oid: cmp.head_oid.as_str(), parent: parent.as_deref(), subject: g::t(lang, K::ThisComparison), lang: DiffLang(lang), opts: opts.clone()) |
| 378 | } | 394 | } |
| 379 | } | 395 | } |
| 380 | ) | 396 | ) |
| @@ -450,7 +466,8 @@ async fn compare_picker(cx: &Cx) -> Result<impl View> { | |||
| 450 | async fn compare_page(cx: &Cx) -> Result<impl View> { | 466 | async fn compare_page(cx: &Cx) -> Result<impl View> { |
| 451 | let owner = path_param::<Owner>(cx); | 467 | let owner = path_param::<Owner>(cx); |
| 452 | let name = path_param::<Repo>(cx); | 468 | let name = path_param::<Repo>(cx); |
| 453 | - let spec = path_param::<Spec>(cx).collect::<Vec<_>>().join("/"); | 469 | + let full_spec = path_param::<Spec>(cx).collect::<Vec<_>>().join("/"); |
| 470 | + let (spec, download) = Download::split(&full_spec); | ||
| 454 | let ctx = load_repo(cx, owner, name).await?; | 471 | let ctx = load_repo(cx, owner, name).await?; |
| 455 | let state = app_context::<AppState>(cx); | 472 | let state = app_context::<AppState>(cx); |
| 456 | let Some((base, head)) = spec.split_once("...") else { | 473 | let Some((base, head)) = spec.split_once("...") else { |
| @@ -462,6 +479,34 @@ async fn compare_page(cx: &Cx) -> Result<impl View> { | |||
| 462 | let Some(cmp) = resolve_comparison(state, &ctx, base, head).await? else { | 479 | let Some(cmp) = resolve_comparison(state, &ctx, base, head).await? else { |
| 463 | return Err(not_found().into()); | 480 | return Err(not_found().into()); |
| 464 | }; | 481 | }; |
| 482 | + if let Some(kind) = download { | ||
| 483 | + let out = match kind { | ||
| 484 | + Download::Patch => { | ||
| 485 | + history::range_patch( | ||
| 486 | + &state.git, | ||
| 487 | + &ctx.path, | ||
| 488 | + cmp.objects(), | ||
| 489 | + &cmp.base_oid, | ||
| 490 | + &cmp.head_oid, | ||
| 491 | + ) | ||
| 492 | + .await? | ||
| 493 | + } | ||
| 494 | + Download::Diff => { | ||
| 495 | + let from = match &cmp.merge_base { | ||
| 496 | + Some(mb) => mb.clone(), | ||
| 497 | + None => history::empty_tree_for(&cmp.head_oid).to_owned(), | ||
| 498 | + }; | ||
| 499 | + history::raw_diff(&state.git, &ctx.path, cmp.objects(), &from, &cmp.head_oid) | ||
| 500 | + .await? | ||
| 501 | + } | ||
| 502 | + }; | ||
| 503 | + let stem = format!( | ||
| 504 | + "{}...{}", | ||
| 505 | + short_oid(&cmp.base_oid), | ||
| 506 | + short_oid(&cmp.head_oid) | ||
| 507 | + ); | ||
| 508 | + return Err(kind.serve(out, &stem)?.into()); | ||
| 509 | + } | ||
| 465 | compare_view(cx, ctx, cmp, None, None).await | 510 | compare_view(cx, ctx, cmp, None, None).await |
| 466 | } | 511 | } |
| 467 | 512 | ||
crates/forge-web/src/pages/pull_files.rsmodified+25 -6
| @@ -7,7 +7,9 @@ | |||
| 7 | use std::collections::HashMap; | 7 | use std::collections::HashMap; |
| 8 | 8 | ||
| 9 | use forge_core::{Action, IssueState, Side, Thread, authorize}; | 9 | use forge_core::{Action, IssueState, Side, Thread, authorize}; |
| 10 | +use forge_git::command::ObjectSource; | ||
| 10 | use forge_git::history::CommitDiff; | 11 | use forge_git::history::CommitDiff; |
| 12 | +use forge_git::pulls::range_diff_files_ws; | ||
| 11 | use topcoat::Result; | 13 | use topcoat::Result; |
| 12 | use topcoat::context::{Cx, app_context}; | 14 | use topcoat::context::{Cx, app_context}; |
| 13 | use topcoat::router::error::not_found; | 15 | use topcoat::router::error::not_found; |
| @@ -25,7 +27,7 @@ use crate::pages::repo::repo_head; | |||
| 25 | use crate::pages::repo_ctx::load_repo; | 27 | use crate::pages::repo_ctx::load_repo; |
| 26 | use crate::pages::tree::link_context; | 28 | use crate::pages::tree::link_context; |
| 27 | use crate::state::AppState; | 29 | use crate::state::AppState; |
| 28 | -use crate::views::diff::{DiffLang, LineComments, diff_section}; | 30 | +use crate::views::diff::{DiffLang, DiffOpts, LIMITS, LineComments, diff_section}; |
| 29 | use crate::views::review_thread::ThreadCtx; | 31 | use crate::views::review_thread::ThreadCtx; |
| 30 | use crate::views::{alert, shell}; | 32 | use crate::views::{alert, shell}; |
| 31 | 33 | ||
| @@ -125,8 +127,25 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | |||
| 125 | 127 | ||
| 126 | let lang = i18n::lang(cx, viewer(&ctx)); | 128 | let lang = i18n::lang(cx, viewer(&ctx)); |
| 127 | let commit_count = commits_of(state, &ctx, &pr).await?.len(); | 129 | let commit_count = commits_of(state, &ctx, &pr).await?.len(); |
| 128 | - let diff = pull_diff(state, &ctx, &pr).await?; | 130 | + let full_diff = pull_diff(state, &ctx, &pr).await?; |
| 129 | - let frame = frame_in(lang, state, &ctx, &pr, commit_count, diff.files.len()).await?; | 131 | + let frame = frame_in(lang, state, &ctx, &pr, commit_count, full_diff.files.len()).await?; |
| 132 | + let opts = DiffOpts::from_cx(cx, None); | ||
| 133 | + // With whitespace ignored the file list can shrink, so file indexes differ from the comment | ||
| 134 | + // routes' view. Existing threads still show; new inline comments wait for the full diff. | ||
| 135 | + let diff = if opts.ignore_ws { | ||
| 136 | + range_diff_files_ws( | ||
| 137 | + &state.git, | ||
| 138 | + &ctx.path, | ||
| 139 | + ObjectSource::default(), | ||
| 140 | + &pr.base_oid, | ||
| 141 | + &pr.head_oid, | ||
| 142 | + LIMITS, | ||
| 143 | + true, | ||
| 144 | + ) | ||
| 145 | + .await? | ||
| 146 | + } else { | ||
| 147 | + full_diff | ||
| 148 | + }; | ||
| 130 | 149 | ||
| 131 | let viewer_id = viewer(&ctx).map(|user| user.id.clone()); | 150 | let viewer_id = viewer(&ctx).map(|user| user.id.clone()); |
| 132 | let signed_in = viewer_id.is_some(); | 151 | let signed_in = viewer_id.is_some(); |
| @@ -180,9 +199,9 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | |||
| 180 | edits, | 199 | edits, |
| 181 | }; | 200 | }; |
| 182 | let comments = LineComments { | 201 | let comments = LineComments { |
| 183 | - anchors: can_comment, | 202 | + anchors: can_comment && !opts.ignore_ws, |
| 184 | threads: by_line, | 203 | threads: by_line, |
| 185 | - open_form: comment_target(cx).filter(|_| can_comment), | 204 | + open_form: comment_target(cx).filter(|_| can_comment && !opts.ignore_ws), |
| 186 | files_href: format!("{href}/files"), | 205 | files_href: format!("{href}/files"), |
| 187 | has_pending: pending > 0, | 206 | has_pending: pending > 0, |
| 188 | ctx: thread_ctx, | 207 | ctx: thread_ctx, |
| @@ -208,7 +227,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | |||
| 208 | } | 227 | } |
| 209 | diff_section(diff: &diff, owner: owner.as_str(), repo: name.as_str(), | 228 | diff_section(diff: &diff, owner: owner.as_str(), repo: name.as_str(), |
| 210 | oid: pr.head_oid.as_str(), parent: parent.as_deref(), | 229 | oid: pr.head_oid.as_str(), parent: parent.as_deref(), |
| 211 | - subject: g::t(lang, K::ThisPullRequest), lang: DiffLang(lang), comments: comments) | 230 | + subject: g::t(lang, K::ThisPullRequest), lang: DiffLang(lang), comments: comments, opts: opts) |
| 212 | ) | 231 | ) |
| 213 | }) | 232 | }) |
| 214 | } | 233 | } |
crates/forge-web/src/pages/repo_ctx.rsmodified+66 -18
| @@ -119,6 +119,24 @@ impl std::fmt::Display for RepoMoved { | |||
| 119 | 119 | ||
| 120 | impl std::error::Error for RepoMoved {} | 120 | impl std::error::Error for RepoMoved {} |
| 121 | 121 | ||
| 122 | +/// A plain-text download (a `.patch` or `.diff`) raised by a page handler that cannot return a | ||
| 123 | +/// response of its own. The `repo_moved` layer turns it into a 200 with these bytes. | ||
| 124 | +#[derive(Debug, Clone)] | ||
| 125 | +pub struct RawDownload { | ||
| 126 | + pub content_type: &'static str, | ||
| 127 | + /// File name offered to the browser. | ||
| 128 | + pub filename: String, | ||
| 129 | + pub data: Vec<u8>, | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +impl std::fmt::Display for RawDownload { | ||
| 133 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 134 | + f.write_str("raw download") | ||
| 135 | + } | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +impl std::error::Error for RawDownload {} | ||
| 139 | + | ||
| 122 | impl RepoCtx { | 140 | impl RepoCtx { |
| 123 | /// Whether the viewer may delete this repo: its owner or an instance admin only. | 141 | /// Whether the viewer may delete this repo: its owner or an instance admin only. |
| 124 | pub fn can_delete(&self) -> bool { | 142 | pub fn can_delete(&self) -> bool { |
| @@ -343,24 +361,54 @@ impl Layer for RepoMovedLayer { | |||
| 343 | } | 361 | } |
| 344 | } | 362 | } |
| 345 | 363 | ||
| 346 | -/// Turns a `RepoMoved` error from a handler into a 301 with the new location. Other errors pass | 364 | +/// Turns a `RepoMoved` error from a handler into a 301 with the new location, and a `RawDownload` |
| 347 | -/// through unchanged. | 365 | +/// into its plain-text response. Other errors pass through unchanged. |
| 348 | async fn repo_moved(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> { | 366 | async fn repo_moved(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> { |
| 349 | - match next.run(cx, body).await { | 367 | + let error = match next.run(cx, body).await { |
| 350 | - Ok(response) => Ok(response), | 368 | + Ok(response) => return Ok(response), |
| 351 | - Err(error) => match error.downcast_ref::<RepoMoved>() { | 369 | + Err(error) => error, |
| 352 | - Some(moved) => { | 370 | + }; |
| 353 | - let mut response = Response::new(Body::empty()); | 371 | + let error = match error.downcast_cloned::<RawDownload>() { |
| 354 | - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; | 372 | + Ok(download) => { |
| 355 | - // Owner and repo names are plain ASCII and the query came from a valid URI, so this | 373 | + return raw_download_response(download).ok_or_else(|| not_found().into()); |
| 356 | - // only fails on a corrupt location; a 404 is the safe answer then. | 374 | + } |
| 357 | - let Ok(location) = HeaderValue::from_str(&moved.location) else { | 375 | + Err(error) => error, |
| 358 | - return Err(not_found().into()); | 376 | + }; |
| 359 | - }; | 377 | + match error.downcast_ref::<RepoMoved>() { |
| 360 | - response.headers_mut().insert(LOCATION, location); | 378 | + Some(moved) => { |
| 361 | - Ok(response) | 379 | + let mut response = Response::new(Body::empty()); |
| 362 | - } | 380 | + *response.status_mut() = StatusCode::MOVED_PERMANENTLY; |
| 363 | - None => Err(error), | 381 | + // Owner and repo names are plain ASCII and the query came from a valid URI, so this |
| 364 | - }, | 382 | + // only fails on a corrupt location; a 404 is the safe answer then. |
| 383 | + let Ok(location) = HeaderValue::from_str(&moved.location) else { | ||
| 384 | + return Err(not_found().into()); | ||
| 385 | + }; | ||
| 386 | + response.headers_mut().insert(LOCATION, location); | ||
| 387 | + Ok(response) | ||
| 388 | + } | ||
| 389 | + None => Err(error), | ||
| 365 | } | 390 | } |
| 366 | } | 391 | } |
| 392 | + | ||
| 393 | +/// The 200 response for a [`RawDownload`]. `None` when the file name is not a valid header value. | ||
| 394 | +fn raw_download_response(download: RawDownload) -> Option<Response> { | ||
| 395 | + let mut response = Response::new(Body::from(download.data)); | ||
| 396 | + let headers = response.headers_mut(); | ||
| 397 | + headers.insert( | ||
| 398 | + http::header::CONTENT_TYPE, | ||
| 399 | + HeaderValue::from_static(download.content_type), | ||
| 400 | + ); | ||
| 401 | + headers.insert( | ||
| 402 | + http::header::CONTENT_DISPOSITION, | ||
| 403 | + HeaderValue::from_str(&format!("inline; filename=\"{}\"", download.filename)).ok()?, | ||
| 404 | + ); | ||
| 405 | + headers.insert( | ||
| 406 | + http::header::X_CONTENT_TYPE_OPTIONS, | ||
| 407 | + HeaderValue::from_static("nosniff"), | ||
| 408 | + ); | ||
| 409 | + headers.insert( | ||
| 410 | + http::header::CACHE_CONTROL, | ||
| 411 | + HeaderValue::from_static("private, no-cache"), | ||
| 412 | + ); | ||
| 413 | + Some(response) | ||
| 414 | +} | ||
crates/forge-web/src/views/diff.rsmodified+356 -5
| @@ -13,9 +13,13 @@ use std::collections::HashMap; | |||
| 13 | use forge_core::{Side, Thread}; | 13 | use forge_core::{Side, Thread}; |
| 14 | use forge_git::history::{CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind}; | 14 | use forge_git::history::{CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind}; |
| 15 | use topcoat::Result; | 15 | use topcoat::Result; |
| 16 | +use topcoat::context::Cx; | ||
| 17 | +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; | ||
| 18 | +use topcoat::router::request::uri; | ||
| 16 | use topcoat::view::{View, component, view}; | 19 | use topcoat::view::{View, component, view}; |
| 17 | 20 | ||
| 18 | use crate::i18n::Lang; | 21 | use crate::i18n::Lang; |
| 22 | +use crate::i18n::browse as b; | ||
| 19 | use crate::i18n::code::{self as g, K}; | 23 | use crate::i18n::code::{self as g, K}; |
| 20 | use crate::pages::commits::url_path; | 24 | use crate::pages::commits::url_path; |
| 21 | use crate::views::review_thread::{ThreadCtx, review_thread_in}; | 25 | use crate::views::review_thread::{ThreadCtx, review_thread_in}; |
| @@ -60,6 +64,94 @@ pub struct LineComments { | |||
| 60 | pub ctx: ThreadCtx, | 64 | pub ctx: ThreadCtx, |
| 61 | } | 65 | } |
| 62 | 66 | ||
| 67 | +/// Name of the cookie that remembers the viewer's unified or split choice. | ||
| 68 | +pub const DIFF_VIEW_COOKIE: &str = "forge_diff"; | ||
| 69 | + | ||
| 70 | +/// How a diff page shows its diff: unified or split, whitespace ignored or not, plus what the | ||
| 71 | +/// toolbar needs to build its links. The default has no toolbar and shows a plain unified diff. | ||
| 72 | +#[derive(Clone, Default)] | ||
| 73 | +pub struct DiffOpts { | ||
| 74 | + /// Draw the toolbar. | ||
| 75 | + pub enabled: bool, | ||
| 76 | + pub split: bool, | ||
| 77 | + pub ignore_ws: bool, | ||
| 78 | + /// Path of the page the toolbar links back to. | ||
| 79 | + pub path: String, | ||
| 80 | + /// The request's query pairs except the ones the toolbar owns. | ||
| 81 | + pub query: Vec<(String, String)>, | ||
| 82 | + /// `.patch` and `.diff` download links, when the page has them. | ||
| 83 | + pub downloads: Option<(String, String)>, | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +impl DiffOpts { | ||
| 87 | + /// Reads the request: `?view=split|unified` wins and is remembered in a cookie, else the | ||
| 88 | + /// cookie decides; `?w=1` ignores whitespace. `downloads` are the patch and diff links. | ||
| 89 | + pub fn from_cx(cx: &Cx, downloads: Option<(String, String)>) -> Self { | ||
| 90 | + let request = uri(cx); | ||
| 91 | + let mut view_param = None; | ||
| 92 | + let mut ignore_ws = false; | ||
| 93 | + let mut query = Vec::new(); | ||
| 94 | + if let Some(raw) = request.query() { | ||
| 95 | + for (key, value) in form_urlencoded::parse(raw.as_bytes()) { | ||
| 96 | + match key.as_ref() { | ||
| 97 | + "view" => view_param = Some(value.into_owned()), | ||
| 98 | + "w" => ignore_ws = value == "1", | ||
| 99 | + "comment" | "review_error" => {} | ||
| 100 | + _ => query.push((key.into_owned(), value.into_owned())), | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | + } | ||
| 104 | + let split = match view_param.as_deref() { | ||
| 105 | + Some(v @ ("split" | "unified")) => { | ||
| 106 | + let max_age = time::Duration::seconds(365 * 24 * 60 * 60); | ||
| 107 | + cookies(cx).add( | ||
| 108 | + Cookie::build((DIFF_VIEW_COOKIE, v.to_owned())) | ||
| 109 | + .path("/") | ||
| 110 | + .secure(true) | ||
| 111 | + .same_site(SameSite::Lax) | ||
| 112 | + .max_age(max_age) | ||
| 113 | + .build(), | ||
| 114 | + ); | ||
| 115 | + v == "split" | ||
| 116 | + } | ||
| 117 | + _ => cookies(cx) | ||
| 118 | + .get(DIFF_VIEW_COOKIE) | ||
| 119 | + .is_some_and(|c| c.value() == "split"), | ||
| 120 | + }; | ||
| 121 | + Self { | ||
| 122 | + enabled: true, | ||
| 123 | + split, | ||
| 124 | + ignore_ws, | ||
| 125 | + path: request.path().to_owned(), | ||
| 126 | + query, | ||
| 127 | + downloads, | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + /// The page URL for the given view and whitespace setting. | ||
| 132 | + pub fn href(&self, split: bool, ignore_ws: bool) -> String { | ||
| 133 | + let mut ser = form_urlencoded::Serializer::new(String::new()); | ||
| 134 | + for (k, v) in &self.query { | ||
| 135 | + ser.append_pair(k, v); | ||
| 136 | + } | ||
| 137 | + ser.append_pair("view", if split { "split" } else { "unified" }); | ||
| 138 | + if ignore_ws { | ||
| 139 | + ser.append_pair("w", "1"); | ||
| 140 | + } | ||
| 141 | + format!("{}?{}", self.path, ser.finish()) | ||
| 142 | + } | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// The toolbar above the diff, flattened for the view. | ||
| 146 | +struct Toolbar { | ||
| 147 | + unified_href: String, | ||
| 148 | + split_href: String, | ||
| 149 | + ws_href: String, | ||
| 150 | + split: bool, | ||
| 151 | + ignore_ws: bool, | ||
| 152 | + downloads: Option<(String, String)>, | ||
| 153 | +} | ||
| 154 | + | ||
| 63 | /// The inline comment form under an open line. | 155 | /// The inline comment form under an open line. |
| 64 | struct InlineForm { | 156 | struct InlineForm { |
| 65 | action: String, | 157 | action: String, |
| @@ -106,6 +198,143 @@ struct FileView { | |||
| 106 | has_blob: bool, | 198 | has_blob: bool, |
| 107 | blob_href: String, | 199 | blob_href: String, |
| 108 | rows: Vec<DiffRow>, | 200 | rows: Vec<DiffRow>, |
| 201 | + /// Rows for the split view; filled in place of `rows` when the diff is split. | ||
| 202 | + split_rows: Vec<SplitRow>, | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +/// One side of a split row. | ||
| 206 | +struct SplitSide { | ||
| 207 | + /// `add`, `del`, `ctx`, `ctx dup` (the repeated side of a context line) or `empty`. | ||
| 208 | + class: &'static str, | ||
| 209 | + num: String, | ||
| 210 | + code: String, | ||
| 211 | + anchor: Option<String>, | ||
| 212 | + plus_href: Option<String>, | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +impl SplitSide { | ||
| 216 | + fn empty() -> Self { | ||
| 217 | + Self { | ||
| 218 | + class: "empty", | ||
| 219 | + num: String::new(), | ||
| 220 | + code: String::new(), | ||
| 221 | + anchor: None, | ||
| 222 | + plus_href: None, | ||
| 223 | + } | ||
| 224 | + } | ||
| 225 | + | ||
| 226 | + fn from_row(row: DiffRow, class: &'static str, num: String) -> (Self, Option<RowBelow>) { | ||
| 227 | + ( | ||
| 228 | + Self { | ||
| 229 | + class, | ||
| 230 | + num, | ||
| 231 | + code: row.code, | ||
| 232 | + anchor: row.anchor, | ||
| 233 | + plus_href: row.plus_href, | ||
| 234 | + }, | ||
| 235 | + row.below, | ||
| 236 | + ) | ||
| 237 | + } | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +/// A row of the split table: a hunk header, or a left and a right side with what sits below. | ||
| 241 | +struct SplitRow { | ||
| 242 | + hunk: Option<String>, | ||
| 243 | + left: SplitSide, | ||
| 244 | + right: SplitSide, | ||
| 245 | + below: Option<RowBelow>, | ||
| 246 | +} | ||
| 247 | + | ||
| 248 | +fn merge_below(a: Option<RowBelow>, b: Option<RowBelow>) -> Option<RowBelow> { | ||
| 249 | + match (a, b) { | ||
| 250 | + (Some(mut a), Some(b)) => { | ||
| 251 | + a.threads.extend(b.threads); | ||
| 252 | + if a.form.is_none() { | ||
| 253 | + a.form = b.form; | ||
| 254 | + } | ||
| 255 | + Some(a) | ||
| 256 | + } | ||
| 257 | + (a, None) => a, | ||
| 258 | + (None, b) => b, | ||
| 259 | + } | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +/// Pairs each run of deleted lines with the added lines that follow it, side by side. | ||
| 263 | +fn flush_pairs(out: &mut Vec<SplitRow>, dels: &mut Vec<DiffRow>, adds: &mut Vec<DiffRow>) { | ||
| 264 | + let mut dels = std::mem::take(dels).into_iter(); | ||
| 265 | + let mut adds = std::mem::take(adds).into_iter(); | ||
| 266 | + loop { | ||
| 267 | + let (d, a) = (dels.next(), adds.next()); | ||
| 268 | + if d.is_none() && a.is_none() { | ||
| 269 | + break; | ||
| 270 | + } | ||
| 271 | + let (left, left_below) = match d { | ||
| 272 | + Some(row) => { | ||
| 273 | + let num = row.old.clone(); | ||
| 274 | + SplitSide::from_row(row, "del", num) | ||
| 275 | + } | ||
| 276 | + None => (SplitSide::empty(), None), | ||
| 277 | + }; | ||
| 278 | + let (right, right_below) = match a { | ||
| 279 | + Some(row) => { | ||
| 280 | + let num = row.new.clone(); | ||
| 281 | + SplitSide::from_row(row, "add", num) | ||
| 282 | + } | ||
| 283 | + None => (SplitSide::empty(), None), | ||
| 284 | + }; | ||
| 285 | + out.push(SplitRow { | ||
| 286 | + hunk: None, | ||
| 287 | + left, | ||
| 288 | + right, | ||
| 289 | + below: merge_below(left_below, right_below), | ||
| 290 | + }); | ||
| 291 | + } | ||
| 292 | +} | ||
| 293 | + | ||
| 294 | +fn split_rows(rows: Vec<DiffRow>) -> Vec<SplitRow> { | ||
| 295 | + let mut out = Vec::new(); | ||
| 296 | + let mut dels: Vec<DiffRow> = Vec::new(); | ||
| 297 | + let mut adds: Vec<DiffRow> = Vec::new(); | ||
| 298 | + for row in rows { | ||
| 299 | + match row.class { | ||
| 300 | + "diff-line del" => { | ||
| 301 | + if !adds.is_empty() { | ||
| 302 | + flush_pairs(&mut out, &mut dels, &mut adds); | ||
| 303 | + } | ||
| 304 | + dels.push(row); | ||
| 305 | + } | ||
| 306 | + "diff-line add" => adds.push(row), | ||
| 307 | + "diff-line hunk" => { | ||
| 308 | + flush_pairs(&mut out, &mut dels, &mut adds); | ||
| 309 | + out.push(SplitRow { | ||
| 310 | + hunk: Some(row.code), | ||
| 311 | + left: SplitSide::empty(), | ||
| 312 | + right: SplitSide::empty(), | ||
| 313 | + below: None, | ||
| 314 | + }); | ||
| 315 | + } | ||
| 316 | + _ => { | ||
| 317 | + flush_pairs(&mut out, &mut dels, &mut adds); | ||
| 318 | + let left = SplitSide { | ||
| 319 | + class: "ctx", | ||
| 320 | + num: row.old.clone(), | ||
| 321 | + code: row.code.clone(), | ||
| 322 | + anchor: None, | ||
| 323 | + plus_href: None, | ||
| 324 | + }; | ||
| 325 | + let new = row.new.clone(); | ||
| 326 | + let (right, below) = SplitSide::from_row(row, "ctx dup", new); | ||
| 327 | + out.push(SplitRow { | ||
| 328 | + hunk: None, | ||
| 329 | + left, | ||
| 330 | + right, | ||
| 331 | + below, | ||
| 332 | + }); | ||
| 333 | + } | ||
| 334 | + } | ||
| 335 | + } | ||
| 336 | + flush_pairs(&mut out, &mut dels, &mut adds); | ||
| 337 | + out | ||
| 109 | } | 338 | } |
| 110 | 339 | ||
| 111 | impl FileView { | 340 | impl FileView { |
| @@ -234,6 +463,7 @@ impl FileView { | |||
| 234 | has_blob: !blob_href.is_empty(), | 463 | has_blob: !blob_href.is_empty(), |
| 235 | blob_href, | 464 | blob_href, |
| 236 | rows, | 465 | rows, |
| 466 | + split_rows: Vec::new(), | ||
| 237 | } | 467 | } |
| 238 | } | 468 | } |
| 239 | } | 469 | } |
| @@ -262,15 +492,31 @@ pub async fn diff_section( | |||
| 262 | subject: &str, | 492 | subject: &str, |
| 263 | #[default] lang: DiffLang, | 493 | #[default] lang: DiffLang, |
| 264 | #[default] comments: LineComments, | 494 | #[default] comments: LineComments, |
| 495 | + #[default] opts: DiffOpts, | ||
| 265 | ) -> Result<impl View> { | 496 | ) -> Result<impl View> { |
| 266 | let lang = lang.0; | 497 | let lang = lang.0; |
| 267 | let mut comments = comments; | 498 | let mut comments = comments; |
| 268 | - let files: Vec<FileView> = diff | 499 | + let anchored = comments.anchors; |
| 500 | + let split = opts.split; | ||
| 501 | + let mut files: Vec<FileView> = diff | ||
| 269 | .files | 502 | .files |
| 270 | .iter() | 503 | .iter() |
| 271 | .enumerate() | 504 | .enumerate() |
| 272 | .map(|(i, file)| FileView::new(i, file, oid, parent, owner, repo, lang, &mut comments)) | 505 | .map(|(i, file)| FileView::new(i, file, oid, parent, owner, repo, lang, &mut comments)) |
| 273 | .collect(); | 506 | .collect(); |
| 507 | + if split { | ||
| 508 | + for file in &mut files { | ||
| 509 | + file.split_rows = split_rows(std::mem::take(&mut file.rows)); | ||
| 510 | + } | ||
| 511 | + } | ||
| 512 | + let toolbar = opts.enabled.then(|| Toolbar { | ||
| 513 | + unified_href: opts.href(false, opts.ignore_ws), | ||
| 514 | + split_href: opts.href(true, opts.ignore_ws), | ||
| 515 | + ws_href: opts.href(opts.split, !opts.ignore_ws), | ||
| 516 | + split: opts.split, | ||
| 517 | + ignore_ws: opts.ignore_ws, | ||
| 518 | + downloads: opts.downloads.clone(), | ||
| 519 | + }); | ||
| 274 | let nav: Vec<NavItem> = files | 520 | let nav: Vec<NavItem> = files |
| 275 | .iter() | 521 | .iter() |
| 276 | .map(|f| NavItem { | 522 | .map(|f| NavItem { |
| @@ -293,6 +539,9 @@ pub async fn diff_section( | |||
| 293 | Ok(view! { | 539 | Ok(view! { |
| 294 | <section class="diff-section"> | 540 | <section class="diff-section"> |
| 295 | <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> | 541 | <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> |
| 542 | + if let Some(bar) = toolbar { | ||
| 543 | + diff_toolbar(bar: bar, lang: lang) | ||
| 544 | + } | ||
| 296 | if truncated_files { | 545 | if truncated_files { |
| 297 | <p class="muted">(truncated_note.as_str())</p> | 546 | <p class="muted">(truncated_note.as_str())</p> |
| 298 | } | 547 | } |
| @@ -309,18 +558,48 @@ pub async fn diff_section( | |||
| 309 | } | 558 | } |
| 310 | </ul> | 559 | </ul> |
| 311 | for file in files.into_iter() { | 560 | for file in files.into_iter() { |
| 312 | - diff_file(file: file, lang: lang) | 561 | + diff_file(file: file, lang: lang, split: split, anchored: anchored) |
| 313 | } | 562 | } |
| 314 | } | 563 | } |
| 315 | </section> | 564 | </section> |
| 316 | }) | 565 | }) |
| 317 | } | 566 | } |
| 318 | 567 | ||
| 568 | +/// Unified or split, ignore whitespace, and the patch and diff downloads. | ||
| 319 | #[component] | 569 | #[component] |
| 320 | -async fn diff_file(file: FileView, lang: Lang) -> Result<impl View> { | 570 | +async fn diff_toolbar(bar: Toolbar, lang: Lang) -> Result<impl View> { |
| 571 | + let unified_on = if bar.split { "false" } else { "true" }; | ||
| 572 | + let split_on = if bar.split { "true" } else { "false" }; | ||
| 573 | + let ws_on = if bar.ignore_ws { "true" } else { "false" }; | ||
| 574 | + Ok(view! { | ||
| 575 | + <div class="diff-toolbar"> | ||
| 576 | + <div class="seg" role="group" aria-label=(b::t(lang, b::K::DiffView))> | ||
| 577 | + <a class="seg-item" href=(bar.unified_href.as_str()) aria-pressed=(unified_on)>(b::t(lang, b::K::Unified))</a> | ||
| 578 | + <a class="seg-item" href=(bar.split_href.as_str()) aria-pressed=(split_on)>(b::t(lang, b::K::Split))</a> | ||
| 579 | + </div> | ||
| 580 | + <a class="seg-item toggle" href=(bar.ws_href.as_str()) aria-pressed=(ws_on)>(b::t(lang, b::K::IgnoreWhitespace))</a> | ||
| 581 | + if let Some((patch, diff)) = bar.downloads { | ||
| 582 | + <span class="diff-downloads"> | ||
| 583 | + <a href=(patch.as_str()) title=(b::t(lang, b::K::PatchTitle))>(b::t(lang, b::K::PatchLink))</a> | ||
| 584 | + <a href=(diff.as_str()) title=(b::t(lang, b::K::DiffTitle))>(b::t(lang, b::K::DiffLink))</a> | ||
| 585 | + </span> | ||
| 586 | + } | ||
| 587 | + </div> | ||
| 588 | + }) | ||
| 589 | +} | ||
| 590 | + | ||
| 591 | +#[component] | ||
| 592 | +async fn diff_file(file: FileView, lang: Lang, split: bool, anchored: bool) -> Result<impl View> { | ||
| 321 | let add_label = format!("+{}", file.additions); | 593 | let add_label = format!("+{}", file.additions); |
| 322 | let del_label = format!("-{}", file.deletions); | 594 | let del_label = format!("-{}", file.deletions); |
| 323 | let rows = file.rows; | 595 | let rows = file.rows; |
| 596 | + let pairs = file.split_rows; | ||
| 597 | + let has_rows = !rows.is_empty() || !pairs.is_empty(); | ||
| 598 | + let table_class = match (split, anchored) { | ||
| 599 | + (true, true) => "diff-table diff-split anchored", | ||
| 600 | + (true, false) => "diff-table diff-split", | ||
| 601 | + _ => "diff-table", | ||
| 602 | + }; | ||
| 324 | Ok(view! { | 603 | Ok(view! { |
| 325 | <section class="diff-file" id=(file.anchor.as_str())> | 604 | <section class="diff-file" id=(file.anchor.as_str())> |
| 326 | <header class="diff-file-header"> | 605 | <header class="diff-file-header"> |
| @@ -340,12 +619,15 @@ async fn diff_file(file: FileView, lang: Lang) -> Result<impl View> { | |||
| 340 | <p class="muted diff-collapsed">(g::t(lang, K::DiffTooLarge))</p> | 619 | <p class="muted diff-collapsed">(g::t(lang, K::DiffTooLarge))</p> |
| 341 | } | 620 | } |
| 342 | } | 621 | } |
| 343 | - if !rows.is_empty() { | 622 | + if has_rows { |
| 344 | <div class="diff-file-body"> | 623 | <div class="diff-file-body"> |
| 345 | - <table class="diff-table"> | 624 | + <table class=(table_class)> |
| 346 | for row in rows.into_iter() { | 625 | for row in rows.into_iter() { |
| 347 | diff_line(row: row, lang: lang) | 626 | diff_line(row: row, lang: lang) |
| 348 | } | 627 | } |
| 628 | + for row in pairs.into_iter() { | ||
| 629 | + diff_split_line(row: row, lang: lang, anchored: anchored) | ||
| 630 | + } | ||
| 349 | </table> | 631 | </table> |
| 350 | </div> | 632 | </div> |
| 351 | } | 633 | } |
| @@ -354,6 +636,75 @@ async fn diff_file(file: FileView, lang: Lang) -> Result<impl View> { | |||
| 354 | }) | 636 | }) |
| 355 | } | 637 | } |
| 356 | 638 | ||
| 639 | +/// One split row as a `<tbody>`: the two sides, then, when either has threads or an open form, a | ||
| 640 | +/// full-width row holding them. A hunk header spans the table. | ||
| 641 | +#[component] | ||
| 642 | +async fn diff_split_line(row: SplitRow, lang: Lang, anchored: bool) -> Result<impl View> { | ||
| 643 | + let SplitRow { | ||
| 644 | + hunk, | ||
| 645 | + left, | ||
| 646 | + right, | ||
| 647 | + below, | ||
| 648 | + } = row; | ||
| 649 | + let (threads, form, ctx) = match below { | ||
| 650 | + Some(below) => (below.threads, below.form, Some(below.ctx)), | ||
| 651 | + None => (Vec::new(), None, None), | ||
| 652 | + }; | ||
| 653 | + let span = if anchored { "6" } else { "4" }; | ||
| 654 | + let is_hunk = hunk.is_some(); | ||
| 655 | + let hunk_text = hunk.unwrap_or_default(); | ||
| 656 | + let left_plus = format!("diff-plus side-{}", left.class); | ||
| 657 | + let left_ln = format!("diff-ln side-{}", left.class); | ||
| 658 | + let left_code = format!("diff-code side-{}", left.class); | ||
| 659 | + let right_plus = format!("diff-plus side-{}", right.class); | ||
| 660 | + let right_ln = format!("diff-ln side-{}", right.class); | ||
| 661 | + let right_code = format!("diff-code side-{}", right.class); | ||
| 662 | + Ok(view! { | ||
| 663 | + <tbody> | ||
| 664 | + if is_hunk { | ||
| 665 | + <tr class="diff-line hunk"> | ||
| 666 | + <td colspan=(span) class="diff-code">(hunk_text.as_str())</td> | ||
| 667 | + </tr> | ||
| 668 | + } else { | ||
| 669 | + <tr class="diff-split-row"> | ||
| 670 | + if anchored { | ||
| 671 | + <td class=(left_plus.as_str())> | ||
| 672 | + if let Some(href) = left.plus_href { | ||
| 673 | + <a href=(href.as_str()) title=(g::t(lang, K::CommentOnLine)) aria-label=(g::t(lang, K::CommentOnLine))>"+"</a> | ||
| 674 | + } | ||
| 675 | + </td> | ||
| 676 | + } | ||
| 677 | + <td class=(left_ln.as_str())>(left.num.as_str())</td> | ||
| 678 | + <td class=(left_code.as_str()) id=(left.anchor.as_deref())>(left.code.as_str())</td> | ||
| 679 | + if anchored { | ||
| 680 | + <td class=(right_plus.as_str())> | ||
| 681 | + if let Some(href) = right.plus_href { | ||
| 682 | + <a href=(href.as_str()) title=(g::t(lang, K::CommentOnLine)) aria-label=(g::t(lang, K::CommentOnLine))>"+"</a> | ||
| 683 | + } | ||
| 684 | + </td> | ||
| 685 | + } | ||
| 686 | + <td class=(right_ln.as_str())>(right.num.as_str())</td> | ||
| 687 | + <td class=(right_code.as_str()) id=(right.anchor.as_deref())>(right.code.as_str())</td> | ||
| 688 | + </tr> | ||
| 689 | + } | ||
| 690 | + if let Some(ctx) = ctx { | ||
| 691 | + <tr class="review-row"> | ||
| 692 | + <td colspan=(span)> | ||
| 693 | + <div class="review-threads"> | ||
| 694 | + for thread in threads.into_iter() { | ||
| 695 | + review_thread_in(lang: lang, thread: thread, ctx: ctx.clone(), show_hunk: false, return_to: "files") | ||
| 696 | + } | ||
| 697 | + if let Some(form) = form { | ||
| 698 | + inline_comment_form(form: form, lang: lang) | ||
| 699 | + } | ||
| 700 | + </div> | ||
| 701 | + </td> | ||
| 702 | + </tr> | ||
| 703 | + } | ||
| 704 | + </tbody> | ||
| 705 | + }) | ||
| 706 | +} | ||
| 707 | + | ||
| 357 | /// One diff line as a `<tbody>`: the line itself, then, when it has threads or an open form, a | 708 | /// One diff line as a `<tbody>`: the line itself, then, when it has threads or an open form, a |
| 358 | /// full-width row holding them. | 709 | /// full-width row holding them. |
| 359 | #[component] | 710 | #[component] |