diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index bbcf79e..a025765 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -1080,3 +1080,288 @@ load({ target: withoutHash(url), dest: url, init: GET_INIT, how: 'query', keep: true, post: false, form: null }); }; })(); + +// Code browsing: line selection on blobs and blame, the permalink copy and `y` shortcut, the file +// finder (`t`) and the inline confirmations on the branches page. Everything is event driven: +// delegated listeners, plus one observer that re-applies the line highlight after a soft swap. +(function () { + 'use strict'; + if (window.__forgeBrowse) { return; } + window.__forgeBrowse = true; + + var anchorLine = 0; // first line of the current selection (the shift-click anchor) + var finderLists = {}; // finder source URL -> { paths, truncated } + + function typing(el) { + if (!el || !el.tagName) { return false; } + var tag = el.tagName; + return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable; + } + + // ---- line selection ------------------------------------------------------------------------- + + function parseRange(hash) { + var m = /^#L(\d+)(?:-L?(\d+))?$/.exec(hash || ''); + if (!m) { return null; } + var a = parseInt(m[1], 10), b = m[2] ? parseInt(m[2], 10) : a; + return a <= b ? [a, b] : [b, a]; + } + + function applyLines(scroll) { + var host = document.querySelector('[data-lines]'); + if (!host) { return; } + host.querySelectorAll('tr.line-hl').forEach(function (tr) { tr.classList.remove('line-hl'); }); + var range = parseRange(location.hash); + if (!range) { return; } + var first = null; + for (var n = range[0]; n <= range[1] && n - range[0] < 5000; n++) { + var row = document.getElementById('L' + n); + if (!row || !host.contains(row)) { continue; } + row.classList.add('line-hl'); + if (!first) { first = row; } + } + anchorLine = range[0]; + if (first && scroll) { first.scrollIntoView({ block: 'center' }); } + } + + function selectLine(n, extend) { + var from = n, to = n; + if (extend && anchorLine) { + from = Math.min(anchorLine, n); + to = Math.max(anchorLine, n); + } + var hash = from === to ? '#L' + from : '#L' + from + '-L' + to; + history.replaceState(history.state, '', location.pathname + location.search + hash); + applyLines(false); + if (!extend) { anchorLine = n; } + } + + document.addEventListener('click', function (e) { + var a = e.target && e.target.closest ? e.target.closest('[data-lines] .ln a') : null; + if (!a || e.button !== 0 || e.metaKey || e.ctrlKey || e.altKey) { return; } + var tr = a.closest('tr'); + var n = tr ? parseInt((tr.id || '').slice(1), 10) : NaN; + if (!n) { return; } + e.preventDefault(); + selectLine(n, e.shiftKey); + }, false); + + window.addEventListener('hashchange', function () { applyLines(true); }); + + // ---- permalink ------------------------------------------------------------------------------ + + function permalinkPath() { + var host = document.querySelector('[data-permalink]'); + return host ? host.getAttribute('data-permalink') : null; + } + + function copyText(text) { + if (navigator.clipboard && navigator.clipboard.writeText) { + return navigator.clipboard.writeText(text); + } + return new Promise(function (resolve, reject) { + var ta = document.createElement('textarea'); + ta.value = text; + ta.setAttribute('readonly', ''); + document.body.appendChild(ta); + ta.select(); + var ok = false; + try { ok = document.execCommand('copy'); } catch (err) { ok = false; } + ta.remove(); + if (ok) { resolve(); } else { reject(new Error('copy failed')); } + }); + } + + document.addEventListener('click', function (e) { + var btn = e.target && e.target.closest ? e.target.closest('[data-copy-permalink]') : null; + if (!btn) { return; } + var path = permalinkPath(); + if (!path) { return; } + var label = btn.textContent; + copyText(location.origin + path + location.hash).then(function () { + btn.textContent = btn.getAttribute('data-copied') || label; + setTimeout(function () { btn.textContent = label; }, 1500); + }, function () { }); + }, false); + + // ---- file finder ---------------------------------------------------------------------------- + + function finderEls(dlg) { + return { + input: dlg.querySelector('[data-finder-input]'), + list: dlg.querySelector('[data-finder-list]'), + note: dlg.querySelector('[data-finder-note]') + }; + } + + function fuzzy(q, p) { + var pl = p.toLowerCase(); + var base = pl.lastIndexOf('/') + 1; + var sub = pl.indexOf(q, base); + var idx = [], i; + if (sub >= 0) { + for (i = 0; i < q.length; i++) { idx.push(sub + i); } + return { score: 200 - (pl.length - sub) * 0.1 - pl.length * 0.01, idx: idx }; + } + var qi = 0, score = 0, prev = -2; + for (i = 0; i < pl.length && qi < q.length; i++) { + if (pl.charCodeAt(i) === q.charCodeAt(qi)) { + idx.push(i); + var s = 1; + if (i === prev + 1) { s += 5; } + if (i === 0 || '/._-'.indexOf(pl.charAt(i - 1)) >= 0) { s += 4; } + if (i >= base) { s += 2; } + score += s; + prev = i; + qi++; + } + } + if (qi < q.length) { return null; } + return { score: score - pl.length * 0.05, idx: idx }; + } + + function highlighted(path, idx) { + var frag = document.createDocumentFragment(); + var at = 0; + idx.forEach(function (k) { + if (k > at) { frag.appendChild(document.createTextNode(path.slice(at, k))); } + var m = document.createElement('mark'); + m.textContent = path.charAt(k); + frag.appendChild(m); + at = k + 1; + }); + if (at < path.length) { frag.appendChild(document.createTextNode(path.slice(at))); } + return frag; + } + + function fileHref(dlg, path) { + var base = dlg.getAttribute('data-base') || ''; + return base + path.split('/').map(encodeURIComponent).join('/'); + } + + function setSelected(dlg, index) { + var els = finderEls(dlg); + var items = els.list.children; + if (!items.length) { return; } + index = Math.max(0, Math.min(items.length - 1, index)); + for (var i = 0; i < items.length; i++) { + items[i].setAttribute('aria-selected', i === index ? 'true' : 'false'); + } + els.input.setAttribute('aria-activedescendant', items[index].id); + items[index].scrollIntoView({ block: 'nearest' }); + dlg.__sel = index; + } + + function renderFinder(dlg) { + var els = finderEls(dlg); + var data = finderLists[dlg.getAttribute('data-src')]; + els.list.textContent = ''; + if (!data) { return; } + var q = els.input.value.trim().toLowerCase(); + var hits = []; + if (!q) { + hits = data.paths.slice(0, 50).map(function (p) { return { path: p, idx: [] }; }); + } else { + for (var i = 0; i < data.paths.length; i++) { + var m = fuzzy(q, data.paths[i]); + if (m) { hits.push({ path: data.paths[i], score: m.score, idx: m.idx }); } + } + hits.sort(function (a, b) { return b.score - a.score; }); + hits = hits.slice(0, 50); + } + hits.forEach(function (hit, n) { + var li = document.createElement('li'); + li.id = 'finder-opt-' + n; + li.setAttribute('role', 'option'); + var a = document.createElement('a'); + a.href = fileHref(dlg, hit.path); + a.appendChild(highlighted(hit.path, hit.idx)); + li.appendChild(a); + els.list.appendChild(li); + }); + if (hits.length) { + els.note.textContent = data.truncated ? dlg.getAttribute('data-truncated') : els.note.getAttribute('data-hint'); + setSelected(dlg, 0); + } else { + els.note.textContent = dlg.getAttribute('data-empty'); + els.input.removeAttribute('aria-activedescendant'); + } + } + + function openFinder() { + var dlg = document.querySelector('dialog[data-finder]'); + if (!dlg || dlg.open || typeof dlg.showModal !== 'function') { return; } + var els = finderEls(dlg); + if (!els.note.getAttribute('data-hint')) { els.note.setAttribute('data-hint', els.note.textContent); } + dlg.showModal(); + els.input.value = ''; + els.input.focus(); + var src = dlg.getAttribute('data-src'); + if (finderLists[src]) { renderFinder(dlg); return; } + els.note.textContent = dlg.getAttribute('data-loading'); + fetch(src, { headers: { accept: 'application/json' }, credentials: 'same-origin' }).then(function (r) { + if (!r.ok) { throw new Error('status ' + r.status); } + return r.json(); + }).then(function (json) { + finderLists[src] = { paths: json.paths || [], truncated: !!json.truncated }; + if (dlg.isConnected) { renderFinder(dlg); } + }).catch(function () { + if (dlg.isConnected) { els.note.textContent = dlg.getAttribute('data-failed'); } + }); + } + + document.addEventListener('click', function (e) { + var t = e.target; + if (!t || !t.closest) { return; } + if (t.closest('[data-finder-open]')) { e.preventDefault(); openFinder(); return; } + // The backdrop is the dialog element itself; the box fills the rest. + if (t.tagName === 'DIALOG' && t.hasAttribute('data-finder')) { t.close(); return; } + var link = t.closest('dialog[data-finder] a'); + if (link) { link.closest('dialog').close(); } + var cancel = t.closest('[data-close-details]'); + if (cancel) { + var det = cancel.closest('details'); + if (det) { det.open = false; } + } + }, false); + + document.addEventListener('input', function (e) { + var input = e.target && e.target.closest ? e.target.closest('[data-finder-input]') : null; + if (input) { renderFinder(input.closest('dialog')); } + }, false); + + document.addEventListener('keydown', function (e) { + var input = e.target && e.target.closest ? e.target.closest('[data-finder-input]') : null; + if (input) { + var dlg = input.closest('dialog'); + var sel = dlg.__sel || 0; + if (e.key === 'ArrowDown') { e.preventDefault(); setSelected(dlg, sel + 1); } + else if (e.key === 'ArrowUp') { e.preventDefault(); setSelected(dlg, sel - 1); } + else if (e.key === 'Enter') { + e.preventDefault(); + var item = dlg.querySelector('[data-finder-list] li[aria-selected="true"] a'); + if (item) { dlg.close(); item.click(); } + } + return; + } + if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || typing(e.target)) { return; } + if (document.querySelector('dialog[open]')) { return; } + if (e.key === 't' && document.querySelector('dialog[data-finder]')) { + e.preventDefault(); + openFinder(); + } else if (e.key === 'y') { + var path = permalinkPath(); + if (path && location.pathname !== path && window.__forgeQuery) { + e.preventDefault(); + window.__forgeQuery(path + location.hash); + } + } + }, false); + + // ---- soft swaps ----------------------------------------------------------------------------- + + // A soft swap replaces the body's children; the new page's highlight is applied once the URL has + // been updated (observer callbacks run after the swap function returns). + new MutationObserver(function () { applyLines(true); }).observe(document.body, { childList: true }); + applyLines(true); +})(); diff --git a/crates/forge-web/src/internal.rs b/crates/forge-web/src/internal.rs index 14286b0..81aa87a 100644 --- a/crates/forge-web/src/internal.rs +++ b/crates/forge-web/src/internal.rs @@ -606,7 +606,11 @@ pub async fn evaluate_pre_receive( /// Whether `actor_id` may push straight to a `restrict_push` branch: an instance admin, the owner /// of a person-owned repo, or someone whose effective role is Admin (a collaborator Admin, or an /// org owner or admin team on an org-owned repo). Pull request merges do not go through here. -async fn may_push_directly(store: &Store, repo: &Repo, actor_id: &str) -> forge_core::Result { +pub(crate) async fn may_push_directly( + store: &Store, + repo: &Repo, + actor_id: &str, +) -> forge_core::Result { let Some(actor) = store.user_by_id(actor_id).await? else { return Ok(false); }; diff --git a/crates/forge-web/src/pages/blame.rs b/crates/forge-web/src/pages/blame.rs new file mode 100644 index 0000000..1f3a1b0 --- /dev/null +++ b/crates/forge-web/src/pages/blame.rs @@ -0,0 +1,282 @@ +//! Page: blame at `/{owner}/{repo}/blame/{*rest}` (`ref/path`). Consecutive lines from the same +//! commit form a group showing the short oid, author, age and summary, with links to the commit +//! and to "blame prior to this commit". Large files and slow runs get a friendly message. + +use std::time::Duration; + +use forge_git::blame::{Blame, blame}; +use forge_git::browse::EntryKind; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::error::not_found; +use topcoat::router::{page, path_param}; +use topcoat::view::{Unescaped, View, component, view}; + +use crate::i18n::browse as b; +use crate::i18n::code::{self as g, K}; +use crate::i18n::{self, Lang}; +use crate::pages::blob::{Line, text_lines}; +use crate::pages::repo::repo_head; +use crate::pages::repo_ctx::load_repo; +use crate::pages::tree::{MAX_BLOB_BYTES, path_crumbs, read_file, resolve}; +use crate::render::emoji::emojify; +use crate::state::AppState; +use crate::views::{ + Crumb, breadcrumb, human_size, iso_time, now_unix, relative_time, repo_href, shell, short_oid, +}; + +path_param!(owner); +path_param!(repo); +path_param!(*rest); + +/// How long a blame may run before it is stopped. +const BLAME_TIMEOUT: Duration = Duration::from_secs(10); + +/// Why no blame is shown. +enum Problem { + TooLarge, + Timeout, + NotText, + Failed, +} + +/// The cell shown on the first row of a group. +struct Meta { + rows: usize, + short: String, + commit_href: String, + author: String, + summary: String, + iso: String, + age: String, + prior_href: Option, +} + +/// One line of the blame table. `meta` is set on the first line of each group. +struct Row { + line: Line, + meta: Option, + first: bool, +} + +fn build_rows( + lang: Lang, + owner: &str, + name: &str, + blame: &Blame, + lines: Vec, + now: i64, +) -> Vec { + let mut lines = lines.into_iter(); + let mut rows = Vec::with_capacity(blame.total as usize); + for group in &blame.groups { + let commit = blame.commits.get(&group.commit); + let mut meta = Some(Meta { + rows: group.lines as usize, + short: short_oid(&group.commit).to_owned(), + commit_href: repo_href(owner, name, "commit", &group.commit), + author: commit.map(|c| c.author.clone()).unwrap_or_default(), + summary: commit + .map(|c| emojify(&c.summary).into_owned()) + .unwrap_or_default(), + iso: commit.map(|c| iso_time(c.author_time)).unwrap_or_default(), + age: commit + .map(|c| relative_time(lang, c.author_time, now)) + .unwrap_or_default(), + prior_href: commit + .and_then(|c| c.previous.as_ref()) + .map(|(oid, file)| repo_href(owner, name, "blame", &format!("{oid}/{file}"))), + }); + for i in 0..group.lines { + let Some(line) = lines.next() else { + return rows; + }; + rows.push(Row { + line, + meta: meta.take(), + first: i == 0, + }); + } + } + rows +} + +#[component] +async fn blame_table(rows: Vec, lang: Lang) -> Result { + Ok(view! { +
+ + + for row in rows.into_iter() { + + if let Some(meta) = row.meta { + + } + + + + } + +
+
+ (meta.short.as_str()) + (meta.author.as_str()) + +
+ (meta.summary.as_str()) + if let Some(prior) = meta.prior_href { + (b::t(lang, b::K::BlamePrior)) + } +
(row.line.num.as_str()) + if row.line.highlighted { + (Unescaped::new_unchecked(row.line.code)) + } else { + (row.line.code) + } +
+
+ }) +} + +#[page("/{owner}/{repo}/blame/{*rest}")] +async fn blame_page(cx: &Cx) -> Result { + let owner = path_param::(cx); + let name = path_param::(cx); + let rest = path_param::(cx).collect::>().join("/"); + + let ctx = load_repo(cx, owner, name).await?; + let state = app_context::(cx); + let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); + let repo = &ctx.repo; + + let Some((ref_name, commit, file)) = resolve(ctx.path.clone(), rest).await? else { + return Err(not_found().into()); + }; + let Some(blob) = read_file(ctx.path.clone(), commit.clone(), file.clone()).await? else { + return Err(not_found().into()); + }; + let file_name = file.rsplit('/').next().unwrap_or(&file).to_owned(); + + let mut rows: Vec = Vec::new(); + let mut problem = None; + let text_kind = matches!(blob.kind, EntryKind::Blob | EntryKind::Executable); + if !text_kind || blob.is_binary { + problem = Some(Problem::NotText); + } else if blob.truncated || blob.size > MAX_BLOB_BYTES as u64 { + problem = Some(Problem::TooLarge); + } else { + let run = blame(&state.git, &ctx.path, &commit, &file, false); + match tokio::time::timeout(BLAME_TIMEOUT, run).await { + Ok(Ok(result)) => { + let text = String::from_utf8_lossy(&blob.data).into_owned(); + let lines = text_lines(&text, &file_name); + rows = build_rows( + lang, + &repo.owner_name, + &repo.name, + &result, + lines, + now_unix(), + ); + } + Ok(Err(e)) => { + tracing::warn!(error = %e, "blame failed"); + problem = Some(Problem::Failed); + } + Err(_) => { + tracing::warn!("blame timed out"); + problem = Some(Problem::Timeout); + } + } + } + + let blob_href = repo_href( + &repo.owner_name, + &repo.name, + "blob", + &format!("{ref_name}/{file}"), + ); + let history = repo_href( + &repo.owner_name, + &repo.name, + "commits", + &format!("{ref_name}/{file}"), + ); + let crumbs: Vec = path_crumbs(repo, &ref_name, "blob", &file); + let title = format!( + "{}/{} \u{b7} {} \u{b7} {file}", + repo.owner_name, + repo.name, + b::t(lang, b::K::BlameTitle) + ); + let size = human_size(lang, blob.size); + let message = problem.map(|p| match p { + Problem::TooLarge => b::blame_limit(lang, &human_size(lang, MAX_BLOB_BYTES as u64)), + Problem::Timeout => b::t(lang, b::K::BlameTimeout).to_owned(), + Problem::NotText => b::t(lang, b::K::BlameNotText).to_owned(), + Problem::Failed => b::t(lang, b::K::BlameFailed).to_owned(), + }); + let has_rows = !rows.is_empty(); + + let header = ctx.head(state, "code").await?; + Ok(view! { + shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), + repo_head(head: header) +
+ breadcrumb(lang: lang, crumbs: crumbs) +
+
+
+ (b::t(lang, b::K::BlameTitle)) " \u{b7} " (size) + +
+ if let Some(text) = message { +

(text)

+ } + if has_rows { + blame_table(rows: rows, lang: lang) + } +
+ ) + }) +} + +#[cfg(test)] +mod tests { + use forge_core::Visibility; + + use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get}; + + #[tokio::test] + async fn blame_groups_lines_by_commit() { + let fx = Fixture::new(Visibility::Public).await; + let (status, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/blame/main/a.txt")).await; + assert_eq!(status, 200); + let html = String::from_utf8(body).unwrap(); + // Lines 1 and 3 came from the root commit, line 2 and 4 from the modifying commit. + assert!(html.contains("blame-meta")); + assert!(html.contains(&format!("/{OWNER}/{REPO}/commit/{}", fx.root))); + assert!(html.contains(&format!("/{OWNER}/{REPO}/commit/{}", fx.modified))); + assert!(html.contains("Modify a.txt and add new.txt")); + // The modifying commit has a parent, so it offers blame prior to it. + assert!(html.contains(&format!("/{OWNER}/{REPO}/blame/{}/a.txt", fx.root))); + assert!(html.contains("id=\"L4\"")); + } + + #[tokio::test] + async fn blame_of_a_missing_file_is_404() { + let fx = Fixture::new(Visibility::Public).await; + let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/blame/main/nope.txt")).await; + assert_eq!(status, 404); + } + + #[tokio::test] + async fn private_repo_blame_is_404_for_anonymous() { + let fx = Fixture::new(Visibility::Private).await; + let (status, _, _) = get(&fx.router, &format!("/{OWNER}/{REPO}/blame/main/a.txt")).await; + assert_eq!(status, 404); + } +} diff --git a/crates/forge-web/src/pages/blob.rs b/crates/forge-web/src/pages/blob.rs index c3b9af8..295f3a6 100644 --- a/crates/forge-web/src/pages/blob.rs +++ b/crates/forge-web/src/pages/blob.rs @@ -9,10 +9,12 @@ use topcoat::router::error::not_found; use topcoat::router::{page, path_param, query_params}; use topcoat::view::{Unescaped, View, component, view}; +use crate::i18n::browse as b; use crate::i18n::code::{self as g, K}; use crate::i18n::{self}; use crate::lfs::has_object; use crate::lfs_pointer; +use crate::pages::finder::file_finder; use crate::pages::media::media_url; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; @@ -60,7 +62,7 @@ fn extension(name: &str) -> String { .unwrap_or_default() } -fn text_lines(text: &str, file_name: &str) -> Vec { +pub fn text_lines(text: &str, file_name: &str) -> Vec { let plain: Vec<&str> = text.lines().collect(); let highlighted = highlight_lines(file_name, text).filter(|h| h.len() == plain.len()); plain @@ -120,7 +122,7 @@ async fn blob_page(cx: &Cx) -> Result { let Some((ref_name, commit, file)) = resolve(ctx.path.clone(), rest).await? else { return Err(not_found().into()); }; - let Some(blob) = read_file(ctx.path.clone(), commit, file.clone()).await? else { + let Some(blob) = read_file(ctx.path.clone(), commit.clone(), file.clone()).await? else { return Err(not_found().into()); }; @@ -235,11 +237,28 @@ async fn blob_page(cx: &Cx) -> Result { } else { Some((g::t(lang, K::SourceToggle), format!("{base}?plain=1"))) }; + let blame = repo_href( + &repo.owner_name, + &repo.name, + "blame", + &format!("{ref_name}/{file}"), + ); + // The same file pinned to this exact commit, for sharing and for the `y` shortcut. + let permalink = repo_href( + &repo.owner_name, + &repo.name, + "blob", + &format!("{commit}/{file}"), + ); + let finder_owner = repo.owner_name.clone(); + let finder_repo = repo.name.clone(); + let finder_ref = ref_name.clone(); let crumbs: Vec = path_crumbs(repo, &ref_name, "blob", &file); let title = format!("{}/{} \u{b7} {file}", repo.owner_name, repo.name); let size = human_size(lang, blob.size); let kind = viewer.kind; + let is_text = kind == "text"; let note = viewer.note; let html = viewer.html; let lines = viewer.lines; @@ -254,14 +273,20 @@ async fn blob_page(cx: &Cx) -> Result { repo_head(head: header)
breadcrumb(lang: lang, crumbs: crumbs) + file_finder(lang: lang, owner: finder_owner, repo: finder_repo, ref_name: finder_ref)
-
+
(size)