From 474bafa36136c5889a020f39578b2d833ff57484 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 1 Nov 2026 00:30:25 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20r=20reruns=20the=20selected?= =?UTF-8?q?=20finished=20run=20in=20the=20CI=20list=20and=20/=20focuses=20?= =?UTF-8?q?the=20page's=20search=20field,=20or=20opens=20the=20palette=20w?= =?UTF-8?q?hen=20it=20has=20none;=20the=20palette=20lists=20Copy=20clone?= =?UTF-8?q?=20URL=20and=20Assign=20to=20me,=20and=20text=20typed=20after?= =?UTF-8?q?=20the=20opening=20path=20searches=20the=20page's=20actions=20b?= =?UTF-8?q?y=20name;=20a=20run=20page's=20log=20appends=20line=20by=20line?= =?UTF-8?q?=20while=20its=20job=20runs,=20with=20no=20ANSI=20codes=20and?= =?UTF-8?q?=20only=20whole=20lines;=20each=20Needs=20you=20section=20has?= =?UTF-8?q?=20a=20paged=20full=20list;=20the=20row=20you=20click=20grows?= =?UTF-8?q?=20into=20each=20page's=20real=20title,=20not=20only=20an=20h1;?= =?UTF-8?q?=20=E2=9A=A1=20perf:=20a=20long=20job=20log's=20line=20count=20?= =?UTF-8?q?resumes=20from=20a=20cache=20rather=20than=20rescanning=20the?= =?UTF-8?q?=20file;=20=F0=9F=90=9B=20fix:=20a=20palette=20action=20still?= =?UTF-8?q?=20runs=20after=20a=20live=20update=20replaced=20its=20button,?= =?UTF-8?q?=20and=20says=20so=20if=20it=20is=20gone;=20on=20issue=20and=20?= =?UTF-8?q?pull=20pages=20the=20palette=20opens=20with=20the=20repo=20path?= =?UTF-8?q?,=20not=20the=20title;=20=F0=9F=92=84=20style:=20muted=20labels?= =?UTF-8?q?=20pass=204.5:1=20in=20the=20fern=20and=20spark=20light=20theme?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-core/src/store/needs.rs | 299 ++++++++++------ crates/forge-web/assets/nav.js | 65 +++- crates/forge-web/src/accent_palette.rs | 4 +- crates/forge-web/src/i18n/code.rs | 12 + crates/forge-web/src/i18n/issues.rs | 4 + crates/forge-web/src/i18n/needs.rs | 48 +++ crates/forge-web/src/pages/ci_job.rs | 92 ++++- crates/forge-web/src/pages/ci_runs.rs | 35 +- crates/forge-web/src/pages/issue_parts.rs | 20 +- crates/forge-web/src/pages/issue_view.rs | 3 +- crates/forge-web/src/pages/needs_you.rs | 394 ++++++++++++++++------ crates/forge-web/src/pages/pull_view.rs | 3 +- crates/forge-web/src/pages/repo.rs | 2 + style/_kb_rerun.scss | 52 +++ style/_needs.scss | 24 ++ style/main.scss | 1 + 16 files changed, 816 insertions(+), 242 deletions(-) create mode 100644 style/_kb_rerun.scss diff --git a/crates/forge-core/src/store/needs.rs b/crates/forge-core/src/store/needs.rs index 166ada6..a387e28 100644 --- a/crates/forge-core/src/store/needs.rs +++ b/crates/forge-core/src/store/needs.rs @@ -1,15 +1,17 @@ //! What is waiting on the signed-in user, for the `/needs-you` page: their failing CI runs, their -//! own open pull requests that carry a review verdict, and their assigned open issues. Reads only. -//! Every query applies the viewer's readable-repo rule (`readable_repo`), as the other per-user -//! lists do. Review requests and mentions come from `review_requests_for_user` and `waiting_on`. +//! own open pull requests that carry a review verdict, their assigned open issues and their unread +//! mentions. Reads only. Every query applies the viewer's readable-repo rule (`readable_repo`), as +//! the other per-user lists do. Review requests come from `review_requests_for_user`. use std::time::Duration; use turso::Value; use super::notifications::{readable_params, readable_repo}; +use super::shell_activity::WaitingItem; use super::{Store, col_int, col_text, fetch_all}; use crate::error::Result; +use crate::notifications::Reason; use crate::time::stamp_ago; /// How far back a failing run counts. The same window as the profile corner's failing count. @@ -48,7 +50,7 @@ pub struct OwnPull { pub number: i64, /// Title of the pull request. pub title: String, - /// The verdict from `review_summary`. + /// The verdict from the latest review of each reviewer. pub verdict: Verdict, /// When the pull request last changed. pub updated_at: String, @@ -69,29 +71,112 @@ pub struct AssignedIssue { pub updated_at: String, } +/// The failing runs query without its page, newest first. +fn failing_runs_sql(readable: &str) -> String { + format!( + "SELECT owner, name, number, git_ref, created_at FROM ( \ + SELECT ci_runs.state, ci_runs.created_at, ci_runs.number, ci_runs.git_ref, \ + o.username AS owner, r.name AS name, ROW_NUMBER() OVER ( \ + PARTITION BY ci_runs.repo_id, ci_runs.git_ref ORDER BY ci_runs.number DESC) AS rn \ + FROM ci_runs JOIN repos r ON r.id = ci_runs.repo_id \ + JOIN users o ON o.id = r.owner_id \ + WHERE ci_runs.actor_id = ? AND {readable} \ + ) WHERE rn = 1 AND state IN ('failure', 'error') AND created_at >= ? \ + ORDER BY created_at DESC, number DESC" + ) +} + +/// The open pull requests with a verdict, without their page, newest first. Each row's last +/// column is 1 when the latest review of some reviewer asks for changes, 0 when all approve. +fn own_pulls_sql(readable: &str) -> String { + format!( + "SELECT o.username, r.name, i.number, i.title, i.updated_at, v.changes_requested \ + FROM issues i \ + JOIN repos r ON r.id = i.repo_id \ + JOIN users o ON o.id = r.owner_id \ + JOIN ( SELECT issue_id, MAX(CASE WHEN state = 'changes_requested' THEN 1 ELSE 0 END) \ + AS changes_requested FROM ( \ + SELECT issue_id, state, ROW_NUMBER() OVER ( \ + PARTITION BY issue_id, author_id ORDER BY submitted_at DESC, id DESC) AS rn \ + FROM pull_reviews WHERE state IN ('approved', 'changes_requested') \ + ) WHERE rn = 1 GROUP BY issue_id ) v ON v.issue_id = i.id \ + WHERE i.kind = 'pull' AND i.state = 'open' AND i.author_id = ? AND {readable} \ + ORDER BY i.updated_at DESC, i.number DESC" + ) +} + +/// The assigned open issues without their page, newest first. +fn assigned_issues_sql(readable: &str) -> String { + format!( + "SELECT o.username, r.name, i.number, i.title, i.updated_at FROM issue_assignees ia \ + JOIN issues i ON i.id = ia.issue_id AND i.kind = 'issue' AND i.state = 'open' \ + JOIN repos r ON r.id = i.repo_id \ + JOIN users o ON o.id = r.owner_id \ + WHERE ia.user_id = ? AND {readable} \ + ORDER BY i.updated_at DESC, i.number DESC" + ) +} + +/// The unread mentions without their page, newest first. The same rule as `waiting_on`, with the +/// reason fixed to a mention. +fn mentions_sql(readable: &str) -> String { + format!( + "SELECT o.username, r.name, i.number, i.kind, i.title, n.updated_at \ + FROM notifications n \ + JOIN repos r ON r.id = n.repo_id \ + JOIN users o ON o.id = r.owner_id \ + JOIN issues i ON i.id = n.issue_id \ + WHERE n.user_id = ? AND n.unread = 1 \ + AND n.reason = 'mention' AND {readable} \ + ORDER BY n.updated_at DESC, n.id DESC" + ) +} + +/// Binds the viewer id, then the readable-repo parameters, as every query here does. +fn viewer_params(user_id: &str) -> Vec { + let mut params = vec![Value::Text(user_id.to_string())]; + params.extend(readable_params(user_id)); + params +} + +/// `base` with its page: `LIMIT` and `OFFSET` are the last two placeholders. +fn paged(base: &str) -> String { + format!("{base} LIMIT ? OFFSET ?") +} + impl Store { + /// The number of rows a query without its page returns. + async fn count_rows(&self, base: &str, params: Vec) -> Result { + let conn = self.read_conn().await; + let counts = fetch_all( + &conn, + &format!("SELECT COUNT(*) FROM ({base})"), + params, + |row| col_int(row, 0), + ) + .await?; + Ok(counts + .first() + .and_then(|n| u64::try_from(*n).ok()) + .unwrap_or(0)) + } + /// The user's newest run per (repo, ref) when it failed within the failing window, newest - /// first, at most `limit`. Runs in repos the user cannot read are left out. - pub async fn failing_runs(&self, actor_id: &str, limit: i64) -> Result> { - let readable = readable_repo(); - let mut params = vec![Value::Text(actor_id.to_string())]; - params.extend(readable_params(actor_id)); + /// first, one page at a time. Runs in repos the user cannot read are left out. + pub async fn failing_runs( + &self, + actor_id: &str, + limit: i64, + offset: i64, + ) -> Result> { + let mut params = viewer_params(actor_id); params.push(Value::Text(stamp_ago(FAILING_WINDOW))); params.push(Value::Integer(limit)); + params.push(Value::Integer(offset)); let conn = self.read_conn().await; fetch_all( &conn, - &format!( - "SELECT owner, name, number, git_ref, created_at FROM ( \ - SELECT ci_runs.state, ci_runs.created_at, ci_runs.number, ci_runs.git_ref, \ - o.username AS owner, r.name AS name, ROW_NUMBER() OVER ( \ - PARTITION BY ci_runs.repo_id, ci_runs.git_ref ORDER BY ci_runs.number DESC) AS rn \ - FROM ci_runs JOIN repos r ON r.id = ci_runs.repo_id \ - JOIN users o ON o.id = r.owner_id \ - WHERE ci_runs.actor_id = ? AND {readable} \ - ) WHERE rn = 1 AND state IN ('failure', 'error') AND created_at >= ? \ - ORDER BY created_at DESC, number DESC LIMIT ?" - ), + &paged(&failing_runs_sql(&readable_repo())), params, |row| { Ok(FailingRun { @@ -106,91 +191,71 @@ impl Store { .await } + /// How many failing runs `failing_runs` lists in all. + pub async fn failing_runs_total(&self, actor_id: &str) -> Result { + let mut params = viewer_params(actor_id); + params.push(Value::Text(stamp_ago(FAILING_WINDOW))); + self.count_rows(&failing_runs_sql(&readable_repo()), params) + .await + } + /// Open pull requests the user authored that have a changes-requested or an approving review, - /// newest first, at most `limit`. The verdict is `review_summary`'s, so a pull with a change - /// request is listed as such even when someone else approved it. Pulls in repos the user cannot - /// read are left out. + /// newest first, one page at a time. A pull with a change request is listed as changes + /// requested even when someone else approved it. Pulls in repos the user cannot read are left + /// out. pub async fn own_pulls_with_verdict( &self, author_id: &str, - limit: usize, + limit: i64, + offset: i64, ) -> Result> { - let readable = readable_repo(); - let mut params = vec![Value::Text(author_id.to_string())]; - params.extend(readable_params(author_id)); - // Candidates: the pulls with at least one approving or changes-requesting review. Each is - // then checked with `review_summary`, which ignores dismissed and comment-only reviews. - let candidates = { - let conn = self.read_conn().await; - fetch_all( - &conn, - &format!( - "SELECT i.id, o.username, r.name, i.number, i.title, i.updated_at FROM issues i \ - JOIN repos r ON r.id = i.repo_id \ - JOIN users o ON o.id = r.owner_id \ - WHERE i.kind = 'pull' AND i.state = 'open' AND i.author_id = ? AND {readable} \ - AND EXISTS (SELECT 1 FROM pull_reviews pr WHERE pr.issue_id = i.id \ - AND pr.state IN ('approved', 'changes_requested')) \ - ORDER BY i.updated_at DESC, i.number DESC" - ), - params, - |row| { - Ok(( - col_text(row, 0)?, - col_text(row, 1)?, - col_text(row, 2)?, - col_int(row, 3)?, - col_text(row, 4)?, - col_text(row, 5)?, - )) - }, - ) - .await? - }; - - let mut out = Vec::new(); - for (id, owner, repo, number, title, updated_at) in candidates { - if out.len() >= limit { - break; - } - let summary = self.review_summary(&id).await?; - let verdict = if !summary.changes_requested_by.is_empty() { - Verdict::ChangesRequested - } else if !summary.approved_by.is_empty() { - Verdict::Approved - } else { - continue; - }; - out.push(OwnPull { - owner, - repo, - number, - title, - verdict, - updated_at, - }); - } - Ok(out) + let mut params = viewer_params(author_id); + params.push(Value::Integer(limit)); + params.push(Value::Integer(offset)); + let conn = self.read_conn().await; + fetch_all( + &conn, + &paged(&own_pulls_sql(&readable_repo())), + params, + |row| { + Ok(OwnPull { + owner: col_text(row, 0)?, + repo: col_text(row, 1)?, + number: col_int(row, 2)?, + title: col_text(row, 3)?, + updated_at: col_text(row, 4)?, + verdict: if col_int(row, 5)? == 1 { + Verdict::ChangesRequested + } else { + Verdict::Approved + }, + }) + }, + ) + .await + } + + /// How many pull requests `own_pulls_with_verdict` lists in all. + pub async fn own_pulls_total(&self, author_id: &str) -> Result { + self.count_rows(&own_pulls_sql(&readable_repo()), viewer_params(author_id)) + .await } - /// Open issues assigned to the user, newest first, at most `limit`. Pull requests are not + /// Open issues assigned to the user, newest first, one page at a time. Pull requests are not /// listed. Issues in repos the user cannot read are left out. - pub async fn assigned_issues(&self, user_id: &str, limit: i64) -> Result> { - let readable = readable_repo(); - let mut params = vec![Value::Text(user_id.to_string())]; - params.extend(readable_params(user_id)); + pub async fn assigned_issues( + &self, + user_id: &str, + limit: i64, + offset: i64, + ) -> Result> { + let mut params = viewer_params(user_id); params.push(Value::Integer(limit)); + params.push(Value::Integer(offset)); let conn = self.read_conn().await; fetch_all( &conn, - &format!( - "SELECT o.username, r.name, i.number, i.title, i.updated_at FROM issue_assignees ia \ - JOIN issues i ON i.id = ia.issue_id AND i.kind = 'issue' AND i.state = 'open' \ - JOIN repos r ON r.id = i.repo_id \ - JOIN users o ON o.id = r.owner_id \ - WHERE ia.user_id = ? AND {readable} \ - ORDER BY i.updated_at DESC, i.number DESC LIMIT ?" - ), + &paged(&assigned_issues_sql(&readable_repo())), params, |row| { Ok(AssignedIssue { @@ -204,6 +269,49 @@ impl Store { ) .await } + + /// How many issues `assigned_issues` lists in all. + pub async fn assigned_issues_total(&self, user_id: &str) -> Result { + self.count_rows(&assigned_issues_sql(&readable_repo()), viewer_params(user_id)) + .await + } + + /// The user's unread mentions, newest first, one page at a time. Mentions in repos the user + /// cannot read are left out. + pub async fn mentions_waiting( + &self, + user_id: &str, + limit: i64, + offset: i64, + ) -> Result> { + let mut params = viewer_params(user_id); + params.push(Value::Integer(limit)); + params.push(Value::Integer(offset)); + let conn = self.read_conn().await; + fetch_all( + &conn, + &paged(&mentions_sql(&readable_repo())), + params, + |row| { + Ok(WaitingItem { + owner: col_text(row, 0)?, + repo: col_text(row, 1)?, + number: col_int(row, 2)?, + is_pull: col_text(row, 3)? == "pull", + title: col_text(row, 4)?, + reason: Reason::Mention, + updated_at: col_text(row, 5)?, + }) + }, + ) + .await + } + + /// How many mentions `mentions_waiting` lists in all. + pub async fn mentions_total(&self, user_id: &str) -> Result { + self.count_rows(&mentions_sql(&readable_repo()), viewer_params(user_id)) + .await + } } #[cfg(test)] @@ -232,13 +340,14 @@ mod tests { .set_issue_assignees(&issue.id, &tahinli.id, &["bob".to_string()]) .await .unwrap(); - assert_eq!(store.assigned_issues(&bob.id, 8).await.unwrap().len(), 1); + assert_eq!(store.assigned_issues(&bob.id, 8, 0).await.unwrap().len(), 1); // Once the repo is private and bob is not a collaborator, the assignment stays but is hidden. store .set_repo_visibility(&repo.id, Visibility::Private) .await .unwrap(); - assert!(store.assigned_issues(&bob.id, 8).await.unwrap().is_empty()); + assert!(store.assigned_issues(&bob.id, 8, 0).await.unwrap().is_empty()); + assert_eq!(store.assigned_issues_total(&bob.id).await.unwrap(), 0); } } diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index e2c19ea..364adb1 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -360,6 +360,20 @@ // comes here: live refreshes, back and forward and form posts never animate. var MORPH_NAME = 'forge-row'; + // The title a row grows into, by page: commit, issue and pull, CI run and job, a repo's title row, + // and the active tab for the Code tab, which has no title row. Most specific first: the first of + // these that is visible wins, not the first in the page, where the repo's title and tabs come first. + var TITLE_SELECTORS = ['.commit-summary-title', '.issue-heading', '.ci-tl-title', '.ci-job-title', '.repo-title', '.repo-tabs .tab.active']; + + function pageTitle() { + for (var i = 0; i < TITLE_SELECTORS.length; i++) { + var el = document.querySelector(TITLE_SELECTORS[i]); + var box = el ? el.getBoundingClientRect() : null; + if (box && box.width > 0 && box.height > 0) { return el; } + } + return null; + } + function morph(row, run) { if (!row || !document.startViewTransition || motionHeld()) { run(); return undefined; } row.style.viewTransitionName = MORPH_NAME; @@ -372,7 +386,7 @@ // The old row leaves the page now, so its name goes with it. row.style.viewTransitionName = ''; try { run(); } catch (err) { reject(err); return; } - title = document.querySelector('main h1'); + title = pageTitle(); if (title) { title.style.viewTransitionName = MORPH_NAME; } resolve(); } @@ -3155,7 +3169,9 @@ for (var i = 0; i < els.length; i++) { var url = els[i].getAttribute('data-live'); if (!url) { continue; } - var tail = els[i].querySelector('[data-live-log]'); + // A stream's own tail is its element or one inside it with no other data-live in between. + var tail = els[i].hasAttribute('data-live-log') ? els[i] : els[i].querySelector('[data-live-log]'); + if (tail && tail.closest('[data-live]') !== els[i]) { tail = null; } if (tail) { url += (url.indexOf('?') < 0 ? '?' : '&') + 'from=' + encodeURIComponent(tail.getAttribute('data-offset') || '0'); } @@ -4174,14 +4190,17 @@ // Still the text the palette opened with (a repo's path): no query yet, so actions are listed. var idle = !!pal.prefill && pal.input.value === pal.prefill; var q = raw.toLowerCase(); + var typed = pal.prefill && !idle && q.indexOf(pal.prefill.toLowerCase()) === 0 ? q.slice(pal.prefill.length) : ''; // With a "/" the query is a path: an item matches when its label starts with it. var pathMode = q.indexOf('/') >= 0; var scored = []; paletteItems().concat(paletteFiles(q)).forEach(function (item, idx) { if (!Object.prototype.hasOwnProperty.call(pal.str.heads, item.kind)) { return; } var s = pathMode ? (item.label.toLowerCase().indexOf(q) === 0 ? 3 : 0) : paletteScore(q, item.label); - // Above a path match (3), which would otherwise fill the list and cut the actions off. + // Above a path match (3), which would otherwise fill the list and cut the actions off. Text typed + // after the opening path searches the page's actions by name. if (item.kind === 'action' && idle) { s = 4; } + else if (item.kind === 'action' && typed) { var m = paletteScore(typed, item.label); s = m ? m + 3 : 0; } if (s > 0) { scored.push({ item: item, score: s, idx: idx }); } }); scored.sort(function (a, b) { return b.score - a.score || a.idx - b.idx; }); @@ -4310,8 +4329,14 @@ function paletteRun(item) { if (!item) { return; } if (item.kind !== 'action') { paletteGo(item.href); return; } - if (pal.busy || !item.el.isConnected) { return; } + if (pal.busy) { return; } var el = item.el; + // A live update may have replaced the control while the palette was open: use the one there now. + if (!el.isConnected) { + var now = paletteActions().filter(function (a) { return a.label === item.label && a.mode === item.mode; })[0]; + if (!now) { paletteNote(pal.str.refused, 'is-bad'); return; } + el = now.el; + } if (item.mode === 'post') { paletteSubmit(el); return; } pal.reload = null; if (item.mode === 'go' || (item.mode === 'confirm' && el.tagName === 'A')) { @@ -4398,6 +4423,8 @@ dlg.showModal(); // The path bar's path comes in as a prefix when it has owner and repo, ready to narrow down. var path = (opener.getAttribute('data-path') || '').replace(/\/+$/, ''); + // An issue or a pull adds its title after the path: only owner and repo are a path to narrow. + if (path.indexOf(' \u00b7 ') >= 0) { path = path.split('/').slice(0, 2).join('/'); } var prefill = path.split('/').filter(Boolean).length >= 2 ? path + '/' : ''; pal.prefill = prefill; pal.input.value = prefill; @@ -4438,13 +4465,19 @@ if (t.closest('[data-palette-open]')) { e.preventDefault(); openPalette(); } }); - // "/" opens the palette when no field has the keyboard and no other dialog is open. Nothing else on - // the site uses "/" as a key. + // "/" focuses the page's own search or filter field when it has one in main, and otherwise opens the + // palette, when no field has the keyboard and no other dialog is open. Nothing else on the site uses + // "/" as a key. document.addEventListener('keydown', function (e) { if (e.key !== '/' || e.ctrlKey || e.metaKey || e.altKey || e.isComposing) { return; } var t = e.target; if (t && (t.isContentEditable || t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT')) { return; } - if (document.querySelector('dialog[open]') || !document.querySelector('[data-palette-open]')) { return; } + if (document.querySelector('dialog[open]')) { return; } + var field = Array.prototype.filter.call(document.querySelectorAll('main input[type="search"]'), function (f) { + return f.offsetParent !== null && !f.disabled; + })[0]; + if (field) { e.preventDefault(); field.focus(); return; } + if (!document.querySelector('[data-palette-open]')) { return; } e.preventDefault(); openPalette(); }); @@ -5540,16 +5573,18 @@ // ---- keyboard rows ---------------------------------------------------------------------------------- // Rows marked data-kb-row (lists of commits, issues, pulls, CI runs, repos, notifications) take the // keys: j and k move the selection, Enter opens the row's first link, x ticks its checkbox if it has -// one, and ? lists the keys. The selection is remembered by that link's address, so a live swap +// one, r reruns the row when it has a form marked data-kb-rerun (a finished CI run, for a writer), +// and ? lists the keys. / focuses the search field of the page (the "/" handler above, which opens the +// palette when there is none). The selection is remembered by that link's address, so a live swap // that keeps the row keeps it selected; otherwise it clears quietly. Nothing fires while typing, -// with a modifier held, or while a dialog (the palette included) is open. r and / are not bound -// here: r has no row form to post to, and / already opens the palette (see the report). +// with a modifier held, or while a dialog (the palette included) is open. r only posts: the page +// changes when the server answers. (function () { 'use strict'; var KB_TEXT = { - en: { next: 'Next row', prev: 'Previous row', open: 'Open the row', pick: 'Select the row', keys: 'Show these keys', close: 'Close', title: 'Keyboard' }, - tr: { next: 'Sonraki satır', prev: 'Önceki satır', open: 'Satırı aç', pick: 'Satırı seç', keys: 'Bu tuşları göster', close: 'Kapat', title: 'Klavye' } + en: { next: 'Next row', prev: 'Previous row', open: 'Open the row', pick: 'Select the row', rerun: 'Re-run the row', find: 'Focus the search', keys: 'Show these keys', close: 'Close', title: 'Keyboard' }, + tr: { next: 'Sonraki satır', prev: 'Önceki satır', open: 'Satırı aç', pick: 'Satırı seç', rerun: 'Satırı yeniden çalıştır', find: 'Aramaya odaklan', keys: 'Bu tuşları göster', close: 'Kapat', title: 'Klavye' } }; var selKey = null; // the address of the selected row's first link @@ -5603,7 +5638,7 @@ h.textContent = T.title; dlg.appendChild(h); var dl = document.createElement('dl'); - [['j', T.next], ['k', T.prev], ['Enter', T.open], ['x', T.pick], ['?', T.keys]].forEach(function (pair) { + [['j', T.next], ['k', T.prev], ['Enter', T.open], ['x', T.pick], ['r', T.rerun], ['/', T.find], ['?', T.keys]].forEach(function (pair) { var dt = document.createElement('dt'); var kbd = document.createElement('kbd'); kbd.textContent = pair[0]; @@ -5644,6 +5679,10 @@ var cur = selectedRow(); var cb = cur ? cur.querySelector('input[type="checkbox"]') : null; if (cb && !cb.disabled) { e.preventDefault(); cb.click(); } + } else if (e.key === 'r') { + var sel = selectedRow(); + var rerun = sel ? sel.querySelector('form[data-kb-rerun]') : null; + if (rerun) { e.preventDefault(); rerun.requestSubmit(); } } }, false); diff --git a/crates/forge-web/src/accent_palette.rs b/crates/forge-web/src/accent_palette.rs index 62db6fe..628e740 100644 --- a/crates/forge-web/src/accent_palette.rs +++ b/crates/forge-web/src/accent_palette.rs @@ -382,7 +382,7 @@ pub const BASES: &[Base] = &[ surface_2: "#EEF2EC", text: "#1E2420", text_2: "#3A433D", - muted: "#69736B", + muted: "#667068", border: "#DDE3DB", border_strong: "#C5CFC3", code_bg: "#EEF2EC", @@ -415,7 +415,7 @@ pub const BASES: &[Base] = &[ surface_2: "#F0F0F0", text: "#18181B", text_2: "#3F3F46", - muted: "#71717A", + muted: "#6C6C75", border: "#E4E4E7", border_strong: "#D4D4D8", code_bg: "#F0F0F0", diff --git a/crates/forge-web/src/i18n/code.rs b/crates/forge-web/src/i18n/code.rs index 6e36655..578e8d3 100644 --- a/crates/forge-web/src/i18n/code.rs +++ b/crates/forge-web/src/i18n/code.rs @@ -21,6 +21,9 @@ pub enum K { ShowingFirst, ShowingFirstEnd, CloneTitle, + CopyCloneUrl, + CloneCopied, + CloneCopyFailed, SshRequiresKey, BranchesTitle, FilterRefs, @@ -160,6 +163,12 @@ pub fn t(lang: Lang, key: K) -> &'static str { (ShowingFirstEnd, Tr) => " gösteriliyor)", (CloneTitle, En) => "Clone", (CloneTitle, Tr) => "Klonla", + (CopyCloneUrl, En) => "Copy clone URL", + (CopyCloneUrl, Tr) => "Klon adresini kopyala", + (CloneCopied, En) => "Copied", + (CloneCopied, Tr) => "Kopyalandı", + (CloneCopyFailed, En) => "Copy failed", + (CloneCopyFailed, Tr) => "Kopyalanamadı", (SshRequiresKey, En) => "SSH (requires an ed25519 or ECDSA key on your account)", (SshRequiresKey, Tr) => "SSH (hesabınızda bir ed25519 veya ECDSA anahtarı olmalı)", (BranchesTitle, En) => "Branches", @@ -557,6 +566,9 @@ mod tests { K::ShowingFirst, K::ShowingFirstEnd, K::CloneTitle, + K::CopyCloneUrl, + K::CloneCopied, + K::CloneCopyFailed, K::SshRequiresKey, K::BranchesTitle, K::FilterRefs, diff --git a/crates/forge-web/src/i18n/issues.rs b/crates/forge-web/src/i18n/issues.rs index de52d13..dcc3cb8 100644 --- a/crates/forge-web/src/i18n/issues.rs +++ b/crates/forge-web/src/i18n/issues.rs @@ -98,6 +98,7 @@ pub enum K { CommaUsernames, SaveAssignees, NoOneAssigned, + AssignToMe, MilestoneBox, NoneOption, SaveMilestone, @@ -365,6 +366,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::SaveAssignees, Lang::Tr) => "Atananları kaydet", (K::NoOneAssigned, Lang::En) => "No one assigned.", (K::NoOneAssigned, Lang::Tr) => "Kimse atanmadı.", + (K::AssignToMe, Lang::En) => "Assign to me", + (K::AssignToMe, Lang::Tr) => "Bana ata", (K::MilestoneBox, Lang::En) => "Milestone", (K::MilestoneBox, Lang::Tr) => "Kilometre taşı", (K::NoneOption, Lang::En) => "None", @@ -990,6 +993,7 @@ mod tests { K::CommaUsernames, K::SaveAssignees, K::NoOneAssigned, + K::AssignToMe, K::MilestoneBox, K::NoneOption, K::SaveMilestone, diff --git a/crates/forge-web/src/i18n/needs.rs b/crates/forge-web/src/i18n/needs.rs index 4c4916c..8d6ee9d 100644 --- a/crates/forge-web/src/i18n/needs.rs +++ b/crates/forge-web/src/i18n/needs.rs @@ -13,9 +13,34 @@ pub enum K { ChangesRequested, Approved, AllReviewRequests, + AllFailedRuns, + AllYourPulls, + AllAssignedIssues, + AllMentions, + BackToNeedsYou, AllClear, } +/// Every key, for the coverage test. +#[cfg(test)] +pub const ALL: &[K] = &[ + K::NeedsYou, + K::FailedRuns, + K::ReviewsRequested, + K::YourPulls, + K::AssignedIssues, + K::Mentions, + K::ChangesRequested, + K::Approved, + K::AllReviewRequests, + K::AllFailedRuns, + K::AllYourPulls, + K::AllAssignedIssues, + K::AllMentions, + K::BackToNeedsYou, + K::AllClear, +]; + pub fn t(lang: Lang, key: K) -> &'static str { use K::*; use Lang::*; @@ -38,7 +63,30 @@ pub fn t(lang: Lang, key: K) -> &'static str { (Approved, Tr) => "Onaylandı", (AllReviewRequests, En) => "All review requests", (AllReviewRequests, Tr) => "Tüm inceleme istekleri", + (AllFailedRuns, En) => "All failed runs", + (AllFailedRuns, Tr) => "Tüm başarısız çalıştırmalar", + (AllYourPulls, En) => "All your pull requests", + (AllYourPulls, Tr) => "Tüm pull request'leriniz", + (AllAssignedIssues, En) => "All assigned issues", + (AllAssignedIssues, Tr) => "Size atanan tüm sorunlar", + (AllMentions, En) => "All mentions", + (AllMentions, Tr) => "Tüm bahsetmeler", + (BackToNeedsYou, En) => "Back to Needs you", + (BackToNeedsYou, Tr) => "Sizi bekleyenlere dön", (AllClear, En) => "Nothing is waiting on you.", (AllClear, Tr) => "Sizi bekleyen bir şey yok.", } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_key_has_english_and_turkish() { + for key in ALL { + assert!(!t(Lang::En, *key).is_empty(), "{key:?} has no English"); + assert!(!t(Lang::Tr, *key).is_empty(), "{key:?} has no Turkish"); + } + } +} diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index 4233dcb..9e9d97d 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -6,8 +6,9 @@ //! keeps following it until the job is terminal and the file is read to its end. Artifacts are blobs //! under `ci/` and are always served as attachments. +use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use bytes::Bytes; @@ -35,7 +36,7 @@ use crate::i18n::{ }; use crate::pages::ci_runs::{ age_text, can_write, changed_event, duration_text, events_response, job_href, run_href, - state_text, + state_text, strip_ansi, }; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable}; @@ -88,16 +89,38 @@ pub(crate) struct Tail { pub(crate) first_line: u64, } +/// Most logs the newline cache keeps. A full cache drops an arbitrary entry. +const NEWLINE_CACHE_LIMIT: usize = 256; + +/// For each log, the offset up to which its newlines were last counted, and that count. +fn newline_cache() -> &'static Mutex> { + static CACHE: OnceLock>> = OnceLock::new(); + CACHE.get_or_init(|| Mutex::new(HashMap::new())) +} + /// The number of newlines in the first `end` bytes of the file, so a cut log keeps true line numbers. +/// Counting resumes from the cached count of this log when that count covers a prefix of `end`. +/// Logs only grow, so a shorter file, or a cached offset past `end`, counts from zero. async fn newlines_before(path: &Path, end: u64) -> Result { let mut file = tokio::fs::File::open(path) .await .map_err(forge_core::Error::Io)?; - let mut left = end; - let mut count = 0u64; + let len = file.metadata().await.map_err(forge_core::Error::Io)?.len(); + let cached = newline_cache() + .lock() + .expect("newline cache") + .get(path) + .copied(); + let (mut at, mut count) = match cached { + Some((offset, count)) if offset <= end && offset <= len => (offset, count), + _ => (0, 0), + }; + file.seek(SeekFrom::Start(at)) + .await + .map_err(forge_core::Error::Io)?; let mut buf = vec![0u8; CHUNK_BYTES]; - while left > 0 { - let want = usize::try_from(left).map_or(CHUNK_BYTES, |n| n.min(CHUNK_BYTES)); + while at < end { + let want = usize::try_from(end - at).map_or(CHUNK_BYTES, |n| n.min(CHUNK_BYTES)); let n = file .read(&mut buf[..want]) .await @@ -106,8 +129,16 @@ async fn newlines_before(path: &Path, end: u64) -> Result { break; } count += buf[..n].iter().filter(|byte| **byte == b'\n').count() as u64; - left -= n as u64; + at += n as u64; } + let mut map = newline_cache().lock().expect("newline cache"); + if !map.contains_key(path) + && map.len() >= NEWLINE_CACHE_LIMIT + && let Some(old) = map.keys().next().cloned() + { + map.remove(&old); + } + map.insert(path.to_path_buf(), (at, count)); Ok(count) } @@ -348,7 +379,7 @@ async fn job_body(

(g::t(lang, K::RunNumber)) (job.run_number)

-

(job.name.as_str())

+

(job.name.as_str())

(job.state.as_str()) if !job.runner.is_empty() { @@ -545,6 +576,9 @@ async fn job_events(cx: &Cx) -> Result { primed: false, pending_fingerprint: None, pending_log: None, + plain: uri(cx) + .query() + .is_some_and(|query| query.split('&').any(|pair| pair == "plain=1")), viewer: ctx.viewer.as_ref().map(|(user, _)| user.clone()), repo_id: ctx.repo.id.clone(), }; @@ -578,6 +612,8 @@ struct JobFollow { pending_fingerprint: Option, /// The text and the offset past it. pending_log: Option<(String, u64)>, + /// `?plain=1`: the log lines are sent with their ANSI sequences stripped (the run page's log). + plain: bool, /// The viewer the stream opened for, and the repo, so each send is checked for read access. viewer: Option, repo_id: String, @@ -595,6 +631,11 @@ fn job_stream(follow: JobFollow) -> impl Stream> + Send + ' return Some((changed_event(fingerprint), f)); } if let Some((text, end)) = f.pending_log.take() { + let text = if f.plain { + text.split('\n').map(strip_ansi).collect::>().join("\n") + } else { + text + }; let event = Event::new().event("log").data(text).id(end.to_string()); return Some((Ok(event), f)); } @@ -617,7 +658,7 @@ fn job_stream(follow: JobFollow) -> impl Stream> + Send + ' f.fingerprint = Some(fingerprint.clone()); f.pending_fingerprint = Some(fingerprint); } - match read_log(&f.path, f.offset).await { + match read_log(&f.path, f.offset, f.plain).await { Ok(Some((text, end))) => { f.offset = end; f.more = true; @@ -634,8 +675,14 @@ fn job_stream(follow: JobFollow) -> impl Stream> + Send + ' } /// The whole text of the log from `offset`, at most `LOG_EVENT_BYTES`, and the offset past it. None -/// when there is nothing new (no file, no bytes past `offset`, or only part of a character). -async fn read_log(path: &Path, offset: u64) -> std::io::Result> { +/// when there is nothing new (no file, no bytes past `offset`, or only part of a character). With +/// `whole_lines`, the read ends at the last newline, so an ANSI sequence is never cut in two by a +/// chunk; the job page's render at the end of the job shows a last line with no newline. +async fn read_log( + path: &Path, + offset: u64, + whole_lines: bool, +) -> std::io::Result> { let mut file = match tokio::fs::File::open(path).await { Ok(file) => file, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), @@ -647,7 +694,12 @@ async fn read_log(path: &Path, offset: u64) -> std::io::Result, + /// The POST target that reruns this run and the writer's CSRF token. Set for a writer once the run + /// has finished, as the run page's Re-run button is. + rerun: Option<(String, String)>, meta: RowMeta, } @@ -468,6 +471,8 @@ struct JobLog { name: String, href: String, log_href: String, + /// The job's event stream (plain lines) while the job is not finished; None once it is. + live: Option, /// The POST target that runs this job again, for a writer once the job has finished. rerun: Option, text: String, @@ -1409,6 +1414,14 @@ async fn runs_split(cx: &Cx, number: Option<&str>, job: Option<&str>) -> Result< run_href(&title, number) } }; + let writer = can_write(&ctx); + let csrf = if writer { + current_user(cx) + .await? + .map(|(_, session)| session.csrf_token.clone()) + } else { + None + }; let rows: Vec = runs .iter() .zip(&timings) @@ -1458,18 +1471,15 @@ async fn runs_split(cx: &Cx, number: Option<&str>, job: Option<&str>) -> Result< String::new() }, est, + // The same condition as the run page's Re-run button: a writer, and a finished run. + rerun: csrf + .as_ref() + .filter(|_| run_finished(&run.state)) + .map(|token| (format!("{}/rerun", run_href(&title, run.number)), token.clone())), meta: row_meta(run, jobs, &actor, lang), } }) .collect(); - let writer = can_write(&ctx); - let csrf = if writer { - current_user(cx) - .await? - .map(|(_, session)| session.csrf_token.clone()) - } else { - None - }; let manual = if writer { let refs = load_refs(ctx.path.clone()).await?; Some(ManualRun { @@ -1653,6 +1663,7 @@ async fn run_detail( Some(JobLog { name: job.name.clone(), log_href: format!("{href}/log.txt"), + live: (!job.state.is_terminal()).then(|| format!("{href}/events?plain=1")), href, rerun: lines[index].rerun.clone(), // Line for line, so line numbers and the byte offset of the stream still match. @@ -1862,6 +1873,12 @@ async fn runs_body( (row.meta.head.as_str())(row.meta.hint.as_str()) + if let Some((action, token)) = row.rerun.as_ref() { +

+ + +
+ } } @@ -2240,7 +2257,7 @@ async fn run_body( if log.truncated {

(g::t(lang, K::LogTruncated))

} -
(log.text.as_str())
+
(log.text.as_str())
} else {

(g::t(lang, K::NoJobs))

} diff --git a/crates/forge-web/src/pages/issue_parts.rs b/crates/forge-web/src/pages/issue_parts.rs index 3ad616c..f7546b7 100644 --- a/crates/forge-web/src/pages/issue_parts.rs +++ b/crates/forge-web/src/pages/issue_parts.rs @@ -1080,12 +1080,20 @@ pub(crate) async fn assignees_box( action: String, csrf: String, names: Vec, + assign_next: Option, ) -> Result { let text = names.join(", "); Ok(view! {

(g::t(lang, K::Assignees))

if write { + if let Some(next) = assign_next { +
+ + + +
+ }
@@ -1212,6 +1220,7 @@ pub(crate) async fn item_sidebar( write: bool, base: String, csrf: String, + viewer: Option, sidebar: Sidebar, notify: Option, ) -> Result { @@ -1224,13 +1233,22 @@ pub(crate) async fn item_sidebar( locked, lock_reason, } = sidebar; + // "Assign to me" posts the whole list with the viewer added, since the route replaces it. + let assign_next = match viewer { + Some(me) if write && !assignees.iter().any(|a| *a == me) => { + let mut next = assignees.clone(); + next.push(me); + Some(next.join(", ")) + } + _ => None, + }; let labels_action = format!("{base}/labels"); let assignees_action = format!("{base}/assignees"); let milestone_action = format!("{base}/milestone"); let lock_action = format!("{base}/lock"); Ok(view! { labels_box(lang: lang, write: write, action: labels_action, csrf: csrf.clone(), labels: labels) - assignees_box(lang: lang, write: write, action: assignees_action, csrf: csrf.clone(), names: assignees) + assignees_box(lang: lang, write: write, action: assignees_action, csrf: csrf.clone(), names: assignees, assign_next: assign_next) milestone_box(lang: lang, write: write, action: milestone_action, csrf: csrf.clone(), options: milestones, current: current_milestone, none_selected: none_selected) lock_box(lang: lang, write: write, action: lock_action, csrf: csrf.clone(), locked: locked, reason: lock_reason) diff --git a/crates/forge-web/src/pages/issue_view.rs b/crates/forge-web/src/pages/issue_view.rs index 973d6f3..d18bebd 100644 --- a/crates/forge-web/src/pages/issue_view.rs +++ b/crates/forge-web/src/pages/issue_view.rs @@ -56,6 +56,7 @@ async fn issue_page( let discussion = load_discussion(lang, state, &ctx, &issue, ItemKind::Issue, "").await?; let sidebar = load_sidebar(state, &ctx.repo.id, &issue).await?; + let viewer_login = ctx.viewer.as_ref().map(|(u, _)| u.username.clone()); let pinned = state.store.is_pinned(&ctx.repo.id, &issue.id).await?; let pin_action = format!("{issue_href}/pin"); let notify = notify_box_for(state, &ctx, lang, &issue.id, &issue_href).await?; @@ -123,7 +124,7 @@ async fn issue_page(
) diff --git a/crates/forge-web/src/pages/needs_you.rs b/crates/forge-web/src/pages/needs_you.rs index 044f03d..b027f79 100644 --- a/crates/forge-web/src/pages/needs_you.rs +++ b/crates/forge-web/src/pages/needs_you.rs @@ -2,15 +2,16 @@ //! when empty: their failed CI runs, review requests, their own pull requests with a review verdict, //! assigned issues and unread mentions. Every row comes from a store query that applies the viewer's //! repo access, except review requests, which are checked per repo here as `/review-requests` does. -//! `/needs-you/events` wakes the page on the viewer's review-request and inbox topics. +//! `?section=` shows one section as a full list, 15 rows a page. `/needs-you/events` wakes the +//! page on the viewer's review-request and inbox topics. use forge_core::authz::{Action, authorize}; use forge_core::store::needs::Verdict; -use forge_core::{Reason, User}; +use forge_core::User; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::response::Response; -use topcoat::router::{Body, StatusCode, page, route}; +use topcoat::router::{Body, StatusCode, page, query_params, route}; use topcoat::view::{View, component, view}; use crate::auth::{current_user, require_user}; @@ -20,13 +21,168 @@ use crate::i18n::{self, Lang}; use crate::live::{Topic, stream_wakes}; use crate::pages::ci_runs::run_href; use crate::state::AppState; +use crate::views::repo_list::{PageLink, pager, pager_links}; use crate::views::{empty_state, rel_time, repo_href, shell}; -/// Most rows one section lists. +/// Most rows one section lists on the overview. const SECTION_ROWS: usize = 8; -/// How many waiting inbox rows are read before the mentions are picked out of them. -const WAITING_READ: u64 = 200; +/// Rows on one page of a section's full list. +const PER_PAGE: u64 = 15; + +#[query_params(error = bad_request)] +struct NeedsQuery { + section: Option, + page: Option, +} + +/// The sections that have a full list at `?section=`. +#[derive(Clone, Copy)] +enum Section { + Runs, + Pulls, + Issues, + Mentions, +} + +impl Section { + /// The section a `section` query value names. Anything else is not a section. + fn parse(raw: &str) -> Option { + match raw { + "runs" => Some(Self::Runs), + "pulls" => Some(Self::Pulls), + "issues" => Some(Self::Issues), + "mentions" => Some(Self::Mentions), + _ => None, + } + } + + fn slug(self) -> &'static str { + match self { + Self::Runs => "runs", + Self::Pulls => "pulls", + Self::Issues => "issues", + Self::Mentions => "mentions", + } + } + + /// The overview's full-list link for this section. + fn href(self) -> &'static str { + match self { + Self::Runs => "/needs-you?section=runs", + Self::Pulls => "/needs-you?section=pulls", + Self::Issues => "/needs-you?section=issues", + Self::Mentions => "/needs-you?section=mentions", + } + } + + fn heading(self) -> K { + match self { + Self::Runs => K::FailedRuns, + Self::Pulls => K::YourPulls, + Self::Issues => K::AssignedIssues, + Self::Mentions => K::Mentions, + } + } + + fn all_key(self) -> K { + match self { + Self::Runs => K::AllFailedRuns, + Self::Pulls => K::AllYourPulls, + Self::Issues => K::AllAssignedIssues, + Self::Mentions => K::AllMentions, + } + } + + /// How many rows the section has in all, for its pager. + async fn total(self, state: &AppState, user_id: &str) -> Result { + Ok(match self { + Self::Runs => state.store.failing_runs_total(user_id).await?, + Self::Pulls => state.store.own_pulls_total(user_id).await?, + Self::Issues => state.store.assigned_issues_total(user_id).await?, + Self::Mentions => state.store.mentions_total(user_id).await?, + }) + } + + /// One page of the section's rows, newest first. + async fn rows( + self, + state: &AppState, + user: &User, + lang: Lang, + limit: i64, + offset: i64, + ) -> Result> { + Ok(match self { + Self::Runs => state + .store + .failing_runs(&user.id, limit, offset) + .await? + .iter() + .map(|run| { + let title = format!("{}/{}", run.owner, run.repo); + NeedRow { + href: run_href(&title, run.number), + title: format!("{title} #{}", run.number), + detail: run.git_ref.clone(), + badge: None, + stamp: run.created_at.clone(), + } + }) + .collect(), + Self::Pulls => state + .store + .own_pulls_with_verdict(&user.id, limit, offset) + .await? + .iter() + .map(|pull| NeedRow { + href: repo_href(&pull.owner, &pull.repo, "pulls", &pull.number.to_string()), + title: pull.title.clone(), + detail: format!("{}/{} #{}", pull.owner, pull.repo, pull.number), + badge: Some(match pull.verdict { + Verdict::ChangesRequested => ni::t(lang, K::ChangesRequested), + Verdict::Approved => ni::t(lang, K::Approved), + }), + stamp: pull.updated_at.clone(), + }) + .collect(), + Self::Issues => state + .store + .assigned_issues(&user.id, limit, offset) + .await? + .iter() + .map(|issue| NeedRow { + href: repo_href( + &issue.owner, + &issue.repo, + "issues", + &issue.number.to_string(), + ), + title: issue.title.clone(), + detail: format!("{}/{} #{}", issue.owner, issue.repo, issue.number), + badge: None, + stamp: issue.updated_at.clone(), + }) + .collect(), + Self::Mentions => state + .store + .mentions_waiting(&user.id, limit, offset) + .await? + .iter() + .map(|item| { + let section = if item.is_pull { "pulls" } else { "issues" }; + NeedRow { + href: repo_href(&item.owner, &item.repo, section, &item.number.to_string()), + title: item.title.clone(), + detail: format!("{}/{} #{}", item.owner, item.repo, item.number), + badge: None, + stamp: item.updated_at.clone(), + } + }) + .collect(), + }) + } +} /// One row of a section. pub(crate) struct NeedRow { @@ -37,38 +193,56 @@ pub(crate) struct NeedRow { stamp: String, } -/// One section: its heading, at most `SECTION_ROWS` rows, and the link to its full list if it has one. +/// The pager under a full list: the page shown, the page count and the links from `pager_links`. +pub(crate) struct NeedPager { + page: u64, + pages: u64, + links: Vec, + prev: Option, + next: Option, +} + +impl NeedPager { + /// The pager of an overview section, which has none: one page, so the pager shows nothing. + fn single() -> Self { + Self { + page: 1, + pages: 1, + links: Vec::new(), + prev: None, + next: None, + } + } +} + +/// One section: its heading, its rows, the link to its full list if it has one, and its pager. pub(crate) struct NeedSection { heading: &'static str, more: Option<(&'static str, &'static str)>, rows: Vec, + pager: NeedPager, +} + +/// Adds an overview section for `rows`, unless there are none. +fn push_section(sections: &mut Vec, lang: Lang, section: Section, rows: Vec) { + if rows.is_empty() { + return; + } + sections.push(NeedSection { + heading: ni::t(lang, section.heading()), + more: Some((section.href(), ni::t(lang, section.all_key()))), + rows, + pager: NeedPager::single(), + }); } -/// The sections that have rows, in page order. +/// The sections that have rows, in page order, each capped at `SECTION_ROWS`. async fn load_sections(state: &AppState, user: &User, lang: Lang) -> Result> { let mut sections = Vec::new(); let limit = SECTION_ROWS as i64; - let runs = state.store.failing_runs(&user.id, limit).await?; - if !runs.is_empty() { - sections.push(NeedSection { - heading: ni::t(lang, K::FailedRuns), - more: None, - rows: runs - .iter() - .map(|run| { - let title = format!("{}/{}", run.owner, run.repo); - NeedRow { - href: run_href(&title, run.number), - title: format!("{title} #{}", run.number), - detail: run.git_ref.clone(), - badge: None, - stamp: run.created_at.clone(), - } - }) - .collect(), - }); - } + let runs = Section::Runs.rows(state, user, lang, limit, 0).await?; + push_section(&mut sections, lang, Section::Runs, runs); let mut reviews = Vec::new(); for item in state.store.review_requests_for_user(&user.id).await? { @@ -115,94 +289,72 @@ async fn load_sections(state: &AppState, user: &User, lang: Lang) -> Result ni::t(lang, K::ChangesRequested), - Verdict::Approved => ni::t(lang, K::Approved), - }), - stamp: pull.updated_at.clone(), - }) - .collect(), - }); - } + let pulls = Section::Pulls.rows(state, user, lang, limit, 0).await?; + push_section(&mut sections, lang, Section::Pulls, pulls); - let issues = state.store.assigned_issues(&user.id, limit).await?; - if !issues.is_empty() { - sections.push(NeedSection { - heading: ni::t(lang, K::AssignedIssues), - more: None, - rows: issues - .iter() - .map(|issue| NeedRow { - href: repo_href( - &issue.owner, - &issue.repo, - "issues", - &issue.number.to_string(), - ), - title: issue.title.clone(), - detail: format!("{}/{} #{}", issue.owner, issue.repo, issue.number), - badge: None, - stamp: issue.updated_at.clone(), - }) - .collect(), - }); - } + let issues = Section::Issues.rows(state, user, lang, limit, 0).await?; + push_section(&mut sections, lang, Section::Issues, issues); - let mentions: Vec<_> = state - .store - .waiting_on(&user.id, WAITING_READ) - .await? - .into_iter() - .filter(|item| matches!(item.reason, Reason::Mention)) - .take(SECTION_ROWS) - .collect(); - if !mentions.is_empty() { - sections.push(NeedSection { - heading: ni::t(lang, K::Mentions), - more: None, - rows: mentions - .iter() - .map(|item| { - let section = if item.is_pull { "pulls" } else { "issues" }; - NeedRow { - href: repo_href(&item.owner, &item.repo, section, &item.number.to_string()), - title: item.title.clone(), - detail: format!("{}/{} #{}", item.owner, item.repo, item.number), - badge: None, - stamp: item.updated_at.clone(), - } - }) - .collect(), - }); - } + let mentions = Section::Mentions.rows(state, user, lang, limit, 0).await?; + push_section(&mut sections, lang, Section::Mentions, mentions); Ok(sections) } -/// One section of the page: its head, its rows as a compact list, and its full-list link. +/// One section as a full list: the page the query asks for, clamped to the pages there are. +async fn load_full( + state: &AppState, + user: &User, + lang: Lang, + section: Section, + requested: Option<&str>, +) -> Result { + let total = section.total(state, &user.id).await?; + let pages = total.div_ceil(PER_PAGE).max(1); + let page = requested + .and_then(|p| p.parse::().ok()) + .unwrap_or(1) + .clamp(1, pages); + let offset = (page - 1) * PER_PAGE; + let rows = section + .rows(state, user, lang, PER_PAGE as i64, offset as i64) + .await?; + let slug = section.slug(); + let (links, prev, next) = pager_links(page, pages, |n| { + format!("/needs-you?section={slug}&page={n}") + }); + Ok(NeedSection { + heading: ni::t(lang, section.heading()), + more: None, + rows, + pager: NeedPager { + page, + pages, + links, + prev, + next, + }, + }) +} + +/// One section of the page: its head, its rows as a compact list, its full-list link and its pager. #[component] pub(crate) async fn need_section(lang: Lang, section: NeedSection) -> Result { let NeedSection { heading, more, rows, + pager: NeedPager { + page, + pages, + links, + prev, + next, + }, } = section; Ok(view! {
@@ -222,41 +374,69 @@ pub(crate) async fn need_section(lang: Lang, section: NeedSection) -> Result(text) } + pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang)
}) } -/// The page's sections, the only ones with rows, or the one-line empty state. +/// The page's sections, the only ones with rows, or the one-line empty state. With a valid +/// `section` query, that one section as a full list instead. #[page("/needs-you")] async fn needs_you(cx: &Cx) -> Result { let viewer = require_user(cx).await?; let state = app_context::(cx); let user = &viewer.0; let lang = i18n::lang(cx, Some(user)); - let sections = load_sections(state, user, lang).await?; - let empty = sections.is_empty(); + let query = query_params::(cx)?; + let section = query.section.as_deref().and_then(Section::parse); + let (sections, full) = match section { + Some(section) => ( + Vec::new(), + Some(load_full(state, user, lang, section, query.page.as_deref()).await?), + ), + None => (load_sections(state, user, lang).await?, None), + }; + let live = match (section, &full) { + (Some(section), Some(full)) => format!( + "/needs-you/events?section={}&page={}", + section.slug(), + full.pager.page + ), + _ => "/needs-you/events".to_owned(), + }; + let grid = full.is_none() && !sections.is_empty(); + let empty = full.is_none() && sections.is_empty(); + let back = full.as_ref().map(|_| ni::t(lang, K::BackToNeedsYou)); let heading = ni::t(lang, K::NeedsYou); Ok(view! { shell(title: heading, viewer: Some(&viewer), -
+

(heading)

+ if let Some(back) = back { + (back) + }
if empty { empty_state(title: ni::t(lang, K::AllClear)) } - if !empty { + if grid {
for section in sections.into_iter() { need_section(lang: lang, section: section) }
} + if let Some(section) = full { +
+ need_section(lang: lang, section: section) +
+ } ) }) } /// The page's stream: a wake on the viewer's review-request or inbox topic. Anonymous visitors get -/// a bare 401. +/// a bare 401. The query of a section view is ignored here, so the same stream serves both. #[route(GET "/needs-you/events")] async fn needs_you_events(cx: &Cx) -> Result { let Some((user, _)) = current_user(cx).await? else { diff --git a/crates/forge-web/src/pages/pull_view.rs b/crates/forge-web/src/pages/pull_view.rs index fe4028f..9876be6 100644 --- a/crates/forge-web/src/pages/pull_view.rs +++ b/crates/forge-web/src/pages/pull_view.rs @@ -624,6 +624,7 @@ async fn pull_conversation( ) .await?; let sidebar = load_sidebar(state, &ctx.repo.id, &pr.issue).await?; + let viewer_login = ctx.viewer.as_ref().map(|(u, _)| u.username.clone()); let notify = notify_box_for(state, &ctx, lang, &pr.issue.id, &href).await?; let reviewers = load_reviewers(cx, state, &ctx, &pr.issue, &href).await?; let csrf = csrf_of(&ctx); @@ -933,7 +934,7 @@ async fn pull_conversation( } diff --git a/crates/forge-web/src/pages/repo.rs b/crates/forge-web/src/pages/repo.rs index c4625e0..79b4fa3 100644 --- a/crates/forge-web/src/pages/repo.rs +++ b/crates/forge-web/src/pages/repo.rs @@ -248,6 +248,8 @@ async fn clone_popover(
+ +

(g::t(lang, K::SshRequiresKey))

diff --git a/style/_kb_rerun.scss b/style/_kb_rerun.scss new file mode 100644 index 0000000..99a77b2 --- /dev/null +++ b/style/_kb_rerun.scss @@ -0,0 +1,52 @@ +// The Re-run control of a CI run row, which r reruns from the keyboard. It is a small quiet button in +// the row's top corner, shown on the hovered, focused or selected row. It sits over the row's corner, +// so the row keeps its height, and the title leaves room for it. + +.ci-run-list > li { + position: relative; +} + +.ci-row-rerun-form { + position: absolute; + top: 8px; + right: 8px; + margin: 0; + opacity: 0; + transition: opacity 120ms ease; + + li:hover &, + li:focus-within &, + li.kb-sel & { + opacity: 1; + } + + @media (hover: none) { + opacity: 1; + } +} + +li:has(> .ci-row-rerun-form) .ci-row-title { + padding-right: 64px; +} + +.ci-row-rerun { + padding: 1px 8px; + font-size: 0.75rem; + line-height: 1.5; + color: var(--muted); + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); + cursor: pointer; + + &:hover { + color: var(--text); + border-color: var(--border-strong); + } +} + +@media (prefers-reduced-motion: reduce) { + .ci-row-rerun-form { + transition: none; + } +} diff --git a/style/_needs.scss b/style/_needs.scss index 96458fd..511f5c7 100644 --- a/style/_needs.scss +++ b/style/_needs.scss @@ -41,6 +41,30 @@ } } +.needs-back { + display: inline-block; + color: var(--muted); + text-decoration: none; + + &:hover { + color: var(--text); + text-decoration: underline; + } +} + +// A section's full list: its rows scroll inside the card when they run past the window, and the +// pager stays under them. +.needs-full { + .needs-section { + margin-bottom: 0; + } + + .notif-list { + max-height: calc(100vh - 220px); + overflow-y: auto; + } +} + @media (min-width: 900px) { .needs-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); diff --git a/style/main.scss b/style/main.scss index 65bfe49..3c87bba 100644 --- a/style/main.scss +++ b/style/main.scss @@ -8059,6 +8059,7 @@ button.ci-job-last { @import "timeline"; @import "density"; @import "keyboard"; +@import "kb_rerun"; @import "review_flow"; @import "commit_page"; @import "commit_line";