diff --git a/crates/forge-core/migrations/0070_pull_viewed_files.sql b/crates/forge-core/migrations/0070_pull_viewed_files.sql new file mode 100644 index 0000000..da8630b --- /dev/null +++ b/crates/forge-core/migrations/0070_pull_viewed_files.sql @@ -0,0 +1,13 @@ +-- Files a signed-in reviewer marked Viewed on a pull request's Files tab. One row per user, pull +-- request and path. `blob` is the file's blob id at the head when it was marked: a later push that +-- changes the file no longer matches, and the page shows it as changed since it was viewed. Rows go +-- with the user and with the pull request's issue (ON DELETE CASCADE). Applied by store/migrate.rs. + +CREATE TABLE pull_viewed_files ( + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + issue_id TEXT NOT NULL REFERENCES issues(id) ON DELETE CASCADE, + path TEXT NOT NULL, + blob TEXT NOT NULL, + viewed_at TEXT NOT NULL, + PRIMARY KEY (user_id, issue_id, path) +); diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index 409e927..2512f77 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -557,6 +557,20 @@ pub struct CiJob { pub oom_kills: Option, } +/// One job's duration in a recent successful run of a repo, for the CI time estimate. Only the +/// newest five successful runs per branch and per repo are sampled, so the ranks are 1 for the newest. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JobSample { + pub git_ref: String, + /// The run's place among the repo's successful runs on its branch, newest first. + pub branch_rank: i64, + /// The run's place among the repo's successful runs on any branch, newest first. + pub repo_rank: i64, + pub job: String, + /// The job's duration in seconds. + pub secs: i64, +} + /// A job of one runner, with the run and repo it belongs to, for the runner's admin page. The /// run's page is `/{owner}/{repo}/ci/runs/{run_number}`. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index 43ff8da..d552e7d 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -14,7 +14,7 @@ use super::{ finish, insert_err, missing_row, new_id, }; use crate::ci::{ - CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY, + CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, MAX_RUNNER_CONCURRENCY, MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, RunState, RunnerJob, RunnerReport, RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field, }; @@ -1678,6 +1678,58 @@ impl Store { jobs_of_run(&conn, run_id).await } + /// The durations of finished jobs that the CI time estimate learns from: each successful run's + /// jobs for the newest five successful runs of each branch in `git_refs`, and for the newest five + /// successful runs on any branch. One query, bounded by the refs given. + pub async fn recent_job_samples( + &self, + repo_id: &str, + git_refs: &[String], + ) -> Result> { + let mut params: Vec = Vec::with_capacity(git_refs.len() + 1); + params.push(Value::Text(repo_id.to_string())); + params.extend(git_refs.iter().map(|git_ref| Value::Text(git_ref.clone()))); + let scope = if git_refs.is_empty() { + "done.repo_rank <= 5".to_owned() + } else { + let marks: Vec = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect(); + format!( + "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5", + marks.join(", ") + ) + }; + let sql = format!( + "WITH done AS ( \ + SELECT id, git_ref, \ + ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \ + ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \ + FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \ + ) \ + SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, j.started_at, \ + j.finished_at \ + FROM done JOIN ci_jobs j ON j.run_id = done.id \ + WHERE ({scope}) \ + AND j.state = 'success' AND j.started_at IS NOT NULL AND j.finished_at IS NOT NULL" + ); + let conn = self.read_conn().await; + let rows = fetch_all(&conn, &sql, params, |row| { + let started = col_opt_text(row, 4)?.as_deref().and_then(stamp_to_unix); + let finished = col_opt_text(row, 5)?.as_deref().and_then(stamp_to_unix); + Ok(match (started, finished) { + (Some(start), Some(end)) => Some(JobSample { + git_ref: col_text(row, 0)?, + branch_rank: col_int(row, 1)?, + repo_rank: col_int(row, 2)?, + job: col_text(row, 3)?, + secs: (end - start).max(0), + }), + _ => None, + }) + }) + .await?; + Ok(rows.into_iter().flatten().collect()) + } + /// The jobs a runner holds or held: every running one, then its `recent` newest finished jobs /// (by start time). Each carries its run's number and its repo's owner and name. pub async fn runner_jobs(&self, runner_id: &str, recent: usize) -> Result> { diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index cb0f194..a63b57c 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -109,6 +109,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (67, include_str!("../../migrations/0067_coauthored_commits.sql")), (68, include_str!("../../migrations/0068_ci_jobs_runner.sql")), (69, include_str!("../../migrations/0069_user_prefs.sql")), + (70, include_str!("../../migrations/0070_pull_viewed_files.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 9498999..2586862 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -21,6 +21,7 @@ pub mod mail; pub mod merge_queue; pub mod migrate; pub mod mirrors; +pub mod needs; pub mod notifications; pub mod notifications_extra; pub mod oci; @@ -29,6 +30,7 @@ pub mod packages; pub mod passkeys; pub mod pinned; pub mod profile_pins; +pub mod pull_viewed; pub mod pulls; pub mod pulls_list_extra; pub mod push_recent; diff --git a/crates/forge-core/src/store/needs.rs b/crates/forge-core/src/store/needs.rs new file mode 100644 index 0000000..166ada6 --- /dev/null +++ b/crates/forge-core/src/store/needs.rs @@ -0,0 +1,244 @@ +//! 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`. + +use std::time::Duration; + +use turso::Value; + +use super::notifications::{readable_params, readable_repo}; +use super::{Store, col_int, col_text, fetch_all}; +use crate::error::Result; +use crate::time::stamp_ago; + +/// How far back a failing run counts. The same window as the profile corner's failing count. +const FAILING_WINDOW: Duration = Duration::from_secs(7 * 24 * 60 * 60); + +/// A ref whose newest run by the user failed within `FAILING_WINDOW`. +#[derive(Debug, Clone)] +pub struct FailingRun { + /// Owner username of the repo. + pub owner: String, + /// Repo name. + pub repo: String, + /// Run number within the repo. + pub number: i64, + /// Git ref the run ran on. + pub git_ref: String, + /// When the run was created. + pub created_at: String, +} + +/// The review verdict on a pull request. Changes requested wins over approval. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + ChangesRequested, + Approved, +} + +/// An open pull request the user authored, with a review verdict. +#[derive(Debug, Clone)] +pub struct OwnPull { + /// Owner username of the repo. + pub owner: String, + /// Repo name. + pub repo: String, + /// Pull request number. + pub number: i64, + /// Title of the pull request. + pub title: String, + /// The verdict from `review_summary`. + pub verdict: Verdict, + /// When the pull request last changed. + pub updated_at: String, +} + +/// An open issue assigned to the user. +#[derive(Debug, Clone)] +pub struct AssignedIssue { + /// Owner username of the repo. + pub owner: String, + /// Repo name. + pub repo: String, + /// Issue number. + pub number: i64, + /// Title of the issue. + pub title: String, + /// When the issue last changed. + pub updated_at: String, +} + +impl Store { + /// 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)); + params.push(Value::Text(stamp_ago(FAILING_WINDOW))); + params.push(Value::Integer(limit)); + 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 ?" + ), + params, + |row| { + Ok(FailingRun { + owner: col_text(row, 0)?, + repo: col_text(row, 1)?, + number: col_int(row, 2)?, + git_ref: col_text(row, 3)?, + created_at: col_text(row, 4)?, + }) + }, + ) + .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. + pub async fn own_pulls_with_verdict( + &self, + author_id: &str, + limit: usize, + ) -> 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) + } + + /// Open issues assigned to the user, newest first, at most `limit`. 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)); + params.push(Value::Integer(limit)); + 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 ?" + ), + params, + |row| { + Ok(AssignedIssue { + 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)?, + }) + }, + ) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::Visibility; + + #[tokio::test] + async fn assigned_issues_hide_a_repo_the_viewer_cannot_read() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "hash", false) + .await + .unwrap(); + let bob = store.create_user("bob", None, "hash", false).await.unwrap(); + let repo = store + .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main") + .await + .unwrap(); + let issue = store + .create_issue(&repo.id, &tahinli.id, "bug", "") + .await + .unwrap(); + store + .set_issue_assignees(&issue.id, &tahinli.id, &["bob".to_string()]) + .await + .unwrap(); + assert_eq!(store.assigned_issues(&bob.id, 8).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()); + } +} diff --git a/crates/forge-core/src/store/pull_viewed.rs b/crates/forge-core/src/store/pull_viewed.rs new file mode 100644 index 0000000..6d8c90c --- /dev/null +++ b/crates/forge-core/src/store/pull_viewed.rs @@ -0,0 +1,133 @@ +//! Files a reviewer marked Viewed on a pull request's Files tab (migration 0070). One row per user, +//! pull request and path, holding the blob id the mark was made for. The web layer compares that +//! blob with the file's current one; this store only keeps the rows. Rows go with the user and +//! with the pull request's issue (ON DELETE CASCADE). + +use std::collections::HashMap; + +use super::{Store, col_text, db_err, fetch_all}; +use crate::error::Result; +use crate::time::now_stamp; + +impl Store { + /// The viewer's marks on one pull request as `path -> blob`. + pub async fn pull_viewed_files( + &self, + user_id: &str, + issue_id: &str, + ) -> Result> { + let conn = self.read_conn().await; + let rows = fetch_all( + &conn, + "SELECT path, blob FROM pull_viewed_files WHERE user_id = ?1 AND issue_id = ?2", + (user_id.to_string(), issue_id.to_string()), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await?; + Ok(rows.into_iter().collect()) + } + + /// Marks `path` viewed at `blob`, replacing an earlier mark of the same path. + pub async fn set_pull_file_viewed( + &self, + user_id: &str, + issue_id: &str, + path: &str, + blob: &str, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO pull_viewed_files (user_id, issue_id, path, blob, viewed_at) \ + VALUES (?1, ?2, ?3, ?4, ?5) \ + ON CONFLICT (user_id, issue_id, path) DO UPDATE SET \ + blob = excluded.blob, viewed_at = excluded.viewed_at", + ( + user_id.to_string(), + issue_id.to_string(), + path.to_string(), + blob.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Removes the viewer's mark on `path`. A path that was never marked is not an error. + pub async fn clear_pull_file_viewed( + &self, + user_id: &str, + issue_id: &str, + path: &str, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM pull_viewed_files WHERE user_id = ?1 AND issue_id = ?2 AND path = ?3", + ( + user_id.to_string(), + issue_id.to_string(), + path.to_string(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Visibility; + + #[tokio::test] + async fn marks_are_per_user_and_replaced_by_the_newer_blob() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let alice = store + .create_user("alice", None, "hash", false) + .await + .unwrap(); + let bob = store.create_user("bob", None, "hash", false).await.unwrap(); + let repo = store + .create_repo(&alice.id, "app", "", Visibility::Public, "main") + .await + .unwrap(); + let issue = store + .create_issue(&repo.id, &alice.id, "Change", "") + .await + .unwrap(); + + store + .set_pull_file_viewed(&alice.id, &issue.id, "src/a.rs", "old") + .await + .unwrap(); + store + .set_pull_file_viewed(&alice.id, &issue.id, "src/a.rs", "new") + .await + .unwrap(); + let marks = store.pull_viewed_files(&alice.id, &issue.id).await.unwrap(); + assert_eq!(marks.len(), 1); + assert_eq!(marks.get("src/a.rs").map(String::as_str), Some("new")); + assert!( + store + .pull_viewed_files(&bob.id, &issue.id) + .await + .unwrap() + .is_empty() + ); + + store + .clear_pull_file_viewed(&alice.id, &issue.id, "src/a.rs") + .await + .unwrap(); + assert!( + store + .pull_viewed_files(&alice.id, &issue.id) + .await + .unwrap() + .is_empty() + ); + } +} diff --git a/crates/forge-core/src/store/user_prefs.rs b/crates/forge-core/src/store/user_prefs.rs index b0b7b03..659df0b 100644 --- a/crates/forge-core/src/store/user_prefs.rs +++ b/crates/forge-core/src/store/user_prefs.rs @@ -8,6 +8,15 @@ use super::{Store, col_text, db_err, fetch_all}; use crate::error::Result; use crate::time::now_stamp; +/// Key of the row density: `comfortable` (the default, no row) or `compact`. +pub const DENSITY: &str = "density"; +/// The densities a user may store. +pub const DENSITIES: &[&str] = &["comfortable", "compact"]; +/// Key of the run-finished tone: `on` or `off` (the default, no row). +pub const SOUND: &str = "sound"; +/// The sound values a user may store. +pub const SOUND_VALUES: &[&str] = &["on", "off"]; + impl Store { /// All of a user's preferences as `key -> value`. pub async fn user_prefs(&self, user_id: &str) -> Result> { @@ -53,3 +62,25 @@ impl Store { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::Store; + + #[tokio::test] + async fn density_and_sound_round_trip_and_replace() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let user = store.create_user("tahinli", None, "unused", false).await.unwrap(); + + assert!(store.user_prefs(&user.id).await.unwrap().is_empty()); + store.set_user_pref(&user.id, DENSITY, "compact").await.unwrap(); + store.set_user_pref(&user.id, SOUND, "on").await.unwrap(); + store.set_user_pref(&user.id, DENSITY, "comfortable").await.unwrap(); + + let prefs = store.user_prefs(&user.id).await.unwrap(); + assert_eq!(prefs.get(DENSITY).map(String::as_str), Some("comfortable")); + assert_eq!(prefs.get(SOUND).map(String::as_str), Some("on")); + } +} diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 63704cf..8cb26c8 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -332,8 +332,10 @@ var listTop = how === 'live' && oldList ? oldList.scrollTop : null; // A fit pane keeps its scroll when the page stays put (a live change, a post, a filter), by its place in the page. var paneTops = how === 'live' || how === 'post' || how === 'query' ? paneScrolls() : null; + var bars = how === 'live' ? barSegments() : null; adopt(doc, keepFields, dd, how === 'live' ? captureJobs() : null); placeRun(listTop); + if (bars) { growBars(bars); } if (paneTops) { setPaneScrolls(paneTops); } if (tailAt) { var nextTail = document.querySelector('[data-live-log]'); @@ -391,6 +393,47 @@ }); } + // A live swap replaces the run list's bars, so a running job's segment would jump to its new width. + // The old width of each segment is kept by its key (the run's link and the job's id); the new + // element starts at that width and moves to the one the server sent, in the CSS transition of + // .live-grow. A segment whose start moved (the ticker's rest box) is not carried. + function motionHeld() { + return !!(reducedMotion && reducedMotion.matches); + } + + function barKey(el) { + var row = el.closest('.ci-row'); + return row ? row.getAttribute('href') + '|' + el.getAttribute('data-key') : null; + } + + function barSegments() { + if (motionHeld()) { return null; } + var old = {}; + Array.prototype.forEach.call(document.querySelectorAll('.ci-run-list .ci-seg[data-key]'), function (el) { + var key = barKey(el); + if (key) { old[key] = { x: el.getAttribute('x'), w: parseFloat(el.getAttribute('width')) || 0 }; } + }); + return old; + } + + function growBars(old) { + Array.prototype.forEach.call(document.querySelectorAll('.ci-run-list .ci-seg[data-key]'), function (el) { + var key = barKey(el); + var was = key ? old[key] : null; + if (!was || el.getAttribute('x') !== was.x) { return; } + var to = parseFloat(el.getAttribute('width')) || 0; + if (Math.abs(to - was.w) < 0.5) { return; } + el.classList.add('live-grow'); + el.style.width = was.w + 'px'; + el.getBoundingClientRect(); + el.style.width = to + 'px'; + setTimeout(function () { + el.classList.remove('live-grow'); + el.style.width = ''; + }, 650); + }); + } + // The runs list scrolls inside its card: bring the selected row into view there. scrollIntoView // would also scroll the page, so the list's own scrollTop is set instead. function placeRun(keepTop) { @@ -2436,6 +2479,7 @@ clearTimeout(activityTimer); activityTimer = null; if (json.finished && json.finished.length) { activityTimer = setTimeout(refreshActivity, 30000); } + soundFromActivity(json); } // Fetches the activity JSON and draws it. Only the newest answer is drawn. A failed fetch leaves @@ -2451,6 +2495,98 @@ }).catch(function () { }); } + // ---- run tones ---------------------------------------------------------------------------------- + // Two tones, made with Web Audio, when one of the viewer's own CI runs passes or fails (the + // activity JSON's `finished` list). Only when the account's sound switch is on (`data-sound="on"` + // on ). The first answer on a page only records the runs already finished, so a page load + // never replays them. A cancelled run makes no sound, nor does a visible tab on that run's page. + // Open tabs share one localStorage claim per run, so only one of them plays. + var CLAIM_PREFIX = 'forge-tone:'; + var CLAIM_MAX_AGE = 3600000; // ms: older claims are dropped when a new one is made + var toneTab = Math.random().toString(36).slice(2); + var finishedKeys = null; // the runs the newest answer listed; null until the first one + var toneCtx = null; // the AudioContext, made on first use + + // The two notes of an outcome: rising C5 then G5 for a pass, falling for a failure. Each note is a + // short sine with a quick fade in and out, so nothing clicks. + function playTones(outcome) { + var AC = window.AudioContext || window.webkitAudioContext; + if (!AC) { return; } + try { toneCtx = toneCtx || new AC(); } catch (err) { return; } + if (toneCtx.state === 'suspended') { toneCtx.resume().catch(function () { }); } + var freqs = outcome === 'passed' ? [523.25, 783.99] : [783.99, 523.25]; + var start = toneCtx.currentTime + 0.02; + freqs.forEach(function (hz, i) { + var at = start + i * 0.14; + var osc = toneCtx.createOscillator(), gain = toneCtx.createGain(); + osc.type = 'sine'; + osc.frequency.value = hz; + gain.gain.setValueAtTime(0.0001, at); + gain.gain.exponentialRampToValueAtTime(0.15, at + 0.02); + gain.gain.exponentialRampToValueAtTime(0.0001, at + 0.16); + osc.connect(gain); + gain.connect(toneCtx.destination); + osc.start(at); + osc.stop(at + 0.18); + }); + } + + // One tab plays for a run. Each tab writes its id under the run's key when the key is free, waits + // a moment, and plays only if its id is still there. The key stays, so no later answer plays it. + function claimTone(key, outcome) { + var name = CLAIM_PREFIX + key; + try { + if (localStorage.getItem(name) !== null) { return; } + var mine = toneTab + ':' + Date.now(); + localStorage.setItem(name, mine); + for (var i = localStorage.length - 1; i >= 0; i--) { + var old = localStorage.key(i); + if (old.indexOf(CLAIM_PREFIX) === 0 && Date.now() - parseInt(localStorage.getItem(old).split(':').pop(), 10) > CLAIM_MAX_AGE) { + localStorage.removeItem(old); + } + } + setTimeout(function () { + try { if (localStorage.getItem(name) === mine) { playTones(outcome); } } catch (err) { } + }, 80); + } catch (err) { } + } + + // Whether the run's own page is on screen in a visible tab: its result is already in view. + function onRunPage(href) { + try { + return document.visibilityState === 'visible' && new URL(href, location.href).pathname === location.pathname; + } catch (err) { return false; } + } + + // Called with each activity answer. The first answer only records the finished runs; a later one + // plays for each run it lists that the previous answer did not. + function soundFromActivity(json) { + var list = json.finished || []; + var keys = list.map(function (item) { return item.href + '|' + item.started; }); + var known = finishedKeys || []; + var first = finishedKeys === null; + finishedKeys = keys; + if (first || root.getAttribute('data-sound') !== 'on') { return; } + list.forEach(function (item, i) { + if (known.indexOf(keys[i]) >= 0) { return; } + if (item.outcome !== 'passed' && item.outcome !== 'failed') { return; } + if (onRunPage(item.href)) { return; } + claimTone(keys[i], item.outcome); + }); + } + + // The settings page's Play buttons: a preview of each tone, whatever the switch says. + document.addEventListener('click', function (e) { + var b = e.target && e.target.closest ? e.target.closest('[data-sound-play]') : null; + if (b) { playTones(b.getAttribute('data-sound-play')); } + }); + + // Signed-out visitors keep their density in localStorage. Signed in, the shell has set + // `data-density` on already, so nothing is read here. + if (!signedIn && !root.hasAttribute('data-density')) { + try { if (localStorage.getItem('forge-density') === 'compact') { root.setAttribute('data-density', 'compact'); } } catch (err) { } + } + // The CI log (a job page's [data-live-log]). The server sends the raw text; this turns it into // numbered lines (#L12 anchors) with ANSI colours as spans, `::group::name` / `::endgroup::` // sections as
, and a search box with highlight and next/previous. Streamed bytes go @@ -2571,6 +2707,12 @@ function logTop(ci) { return ci.stack[ci.stack.length - 1]; } + // Where a new line goes: the open group, or the chunk's wrapper while the group is the one the chunk began in. + function logHost(ci) { + var top = logTop(ci); + return ci.wrap && ci.wrap.parentNode === top ? ci.wrap : top; + } + // Adds text to the log: completes the open line, then makes a line for each newline. function logFeed(pre, text) { var ci = pre._ci; @@ -2580,7 +2722,7 @@ if (pieces[i] !== '' || ci.cur || ends) { if (!ci.cur) { var el = logLineEl(ci.next); - logTop(ci).appendChild(el); + logHost(ci).appendChild(el); ci.cur = { el: el, raw: '', start: ansiCopy(ci.st) }; } ci.cur.raw += pieces[i]; @@ -3021,11 +3163,48 @@ if (!pre || !text) { return; } if (offset) { pre.setAttribute('data-offset', offset); } var atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 24; - if (pre._ci) { logFeed(pre, text); logRefind(pre); } + if (pre._ci) { + // A small chunk's new lines go into a wrapper that fades in once; a burst appears at once. + var wrap = logFades(text) ? logWrap(pre) : null; + pre._ci.wrap = wrap; + logFeed(pre, text); + pre._ci.wrap = null; + if (wrap) { logSettle(wrap); } + logRefind(pre); + } else { pre.appendChild(document.createTextNode(text)); } if (atEnd) { pre.scrollTop = pre.scrollHeight; } } + // A chunk fades in when it is at most 64 KiB in UTF-8 and the reader does not ask for reduced motion. + // A UTF-16 unit is at least one byte and at most three, so the length alone settles most chunks. + var LOG_FADE_MAX = 65536; + function logFades(text) { + if (motionHeld() || text.length > LOG_FADE_MAX) { return false; } + if (text.length <= 21845) { return true; } + return new Blob([text]).size <= LOG_FADE_MAX; + } + + // The wrapper goes at the end of the open container, where this chunk's lines will be added. + function logWrap(pre) { + var wrap = document.createElement('div'); + wrap.className = 'll-chunk'; + logTop(pre._ci).appendChild(wrap); + return wrap; + } + + // Once the fade is over the wrapper's lines move up into its parent and the wrapper is removed, so + // wrappers never pile up. A chunk that added no lines (it only finished the open line) has none to show. + function logSettle(wrap) { + if (!wrap.firstChild) { wrap.remove(); return; } + setTimeout(function () { + var p = wrap.parentNode; + if (!p) { return; } + while (wrap.firstChild) { p.insertBefore(wrap.firstChild, wrap); } + wrap.remove(); + }, 200); + } + // A re-render replaces the text the reader is selecting (a log line to copy, say), so a live change // waits while a button is held or text on the page is selected, and is sent once the selection is // gone. A selection inside a field does not count: fields keep their state across a re-render. @@ -3281,6 +3460,16 @@ return (root.getAttribute('data-fs') || '{s}s').replace('{s}', secs); } + // The words after the elapsed time of a run with an expected total: "about 12m left", or the + // data-over words once past it. Whole minutes from a minute, else seconds, as the server words it. + function leftWords(el, left, root) { + if (left <= 0) { return el.getAttribute('data-over') || ''; } + var t = left >= 60 + ? (el.getAttribute('data-lm') || '{m}m').replace('{m}', Math.ceil(left / 60)) + : (root.getAttribute('data-fs') || '{s}s').replace('{s}', Math.floor(left)); + return (el.getAttribute('data-left') || '{t}').replace('{t}', t); + } + function place(offset, span, width) { if (span <= 0) { return 0; } return Math.round(Math.min(Math.max(offset, 0), span) * width / span); @@ -3298,7 +3487,19 @@ Array.prototype.forEach.call(live, function (el) { var since = el.getAttribute('data-since'); if (since !== null) { - var text = fmtDuration(now - parseInt(since, 10), root); + var secs = now - parseInt(since, 10); + var text = fmtDuration(secs, root); + var expected = el.getAttribute('data-expected'); + if (expected !== null) { + // A run with an estimate: its bar fills to the expected total and never goes past full. + var total = parseInt(expected, 10) || 0; + var elapsed = Math.max(0, Math.floor(secs)); + if (el.hasAttribute('data-est')) { + el.value = total > 0 && elapsed < total ? Math.round(elapsed * 100 / total) : 100; + return; + } + text += ' · ' + leftWords(el, total - elapsed, root); + } var pre = el.getAttribute('data-pre'); if (pre !== null) { text = pre + text + (el.getAttribute('data-post') || ''); } if (el.textContent !== text) { el.textContent = text; } @@ -3778,8 +3979,11 @@ var PALETTE_WORD = /[\s\/._\-·]/; // a character that starts a word, for the word-start match // files: the current repo's file items, once its finder list is loaded (filesSrc names the finder // it came from); filesBusy names the source being fetched. + // acts: the actions this page offers, read from its live elements at each open. busy: a state change + // is on the wire. reload: the page a sent change answered with, shown once the palette closes. var pal = { dlg: null, input: null, list: null, note: null, hits: [], sel: 0, str: null, - data: null, request: null, failed: false, files: null, filesSrc: '', filesBusy: null }; + data: null, request: null, failed: false, files: null, filesSrc: '', filesBusy: null, + acts: [], busy: false, reload: null, prefill: '' }; // The words the palette shows, read from the topbar button: the server writes them in the viewer's // language, so this script carries no text of its own. @@ -3793,10 +3997,40 @@ loading: word('loading'), failed: word('failed'), search: word('search-label'), - heads: { repo: word('repos'), org: word('orgs'), page: word('pages'), file: word('files') } + done: word('done'), + refused: word('action-failed'), + heads: { action: word('actions'), repo: word('repos'), org: word('orgs'), page: word('pages'), file: word('files') } }; } + // An action's label: the control's own text, without its icons and key hints, unless the control + // names itself with data-palette-label. + function paletteText(el) { + var named = el.getAttribute('data-palette-label'); + if (named) { return named.trim(); } + var copy = el.cloneNode(true); + Array.prototype.forEach.call(copy.querySelectorAll('svg, kbd, script, style'), function (n) { n.parentNode.removeChild(n); }); + return copy.textContent.replace(/\s+/g, ' ').trim(); + } + + // The actions of this page: its elements with data-palette-action, read from the live page at each + // open. The server renders a control only for a viewer who may use it, so the list holds only those. + // A mode says what Enter does: go follows a link, click clicks the control, post sends its form the + // way the control would, and confirm leads to a destructive control without running it. + function paletteActions() { + var out = [], seen = {}; + Array.prototype.forEach.call(document.querySelectorAll('[data-palette-action]'), function (el) { + var mode = el.getAttribute('data-palette-action'); + if (mode !== 'go' && mode !== 'click' && mode !== 'post' && mode !== 'confirm') { return; } + if (el.disabled) { return; } + var label = paletteText(el); + if (!label || seen[label]) { return; } + seen[label] = true; + out.push({ label: label, href: '', kind: 'action', mode: mode, el: el }); + }); + return out; + } + // How well the lowercased query matches a label: 3 for a prefix, 2 for a match at a word start, // 1 for the letters in order anywhere, 0 for no match. A shorter label wins within a tier, and the // bonus stays under 0.5 so it never lifts a label into the tier above. An empty query matches all. @@ -3833,7 +4067,8 @@ }); } } - return pal.data ? items.concat(pal.data.items) : items; + if (pal.data) { items = items.concat(pal.data.items); } + return pal.acts.concat(items); } // The current repo's files, offered once the query starts with its "owner/repo/". The list is the @@ -3887,6 +4122,8 @@ // like the query leads; with no query, the order is tabs, repos, orgs, then pages. function renderPalette() { var raw = pal.input.value.trim(); + // 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(); // With a "/" the query is a path: an item matches when its label starts with it. var pathMode = q.indexOf('/') >= 0; @@ -3894,6 +4131,8 @@ 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. + if (item.kind === 'action' && idle) { s = 4; } 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; }); @@ -3904,6 +4143,9 @@ if (!groups[kind]) { groups[kind] = []; kinds.push(kind); } groups[kind].push(h.item); }); + // Actions of this page are listed above the destinations whenever they match. + var actAt = kinds.indexOf('action'); + if (actAt > 0) { kinds.splice(actAt, 1); kinds.unshift('action'); } // A plain query (no "/") ends with a search option, under no heading. if (raw && !pathMode) { kinds.push('search'); @@ -3931,9 +4173,16 @@ pal.list.appendChild(li); }); }); + pal.note.className = 'palette-note muted small'; if (pal.hits.length) { pal.note.textContent = pal.str.hint; paletteSelect(0); + // With no query Enter must not run an action: the selection starts on the first destination. + if ((!raw || idle) && pal.hits[0].kind === 'action') { + for (var k = 0; k < pal.hits.length; k++) { + if (pal.hits[k].kind !== 'action') { paletteSelect(k); break; } + } + } } else { pal.note.textContent = pal.failed ? pal.str.failed : (pal.data ? pal.str.empty : pal.str.loading); pal.input.removeAttribute('aria-activedescendant'); @@ -3962,6 +4211,7 @@ // a sidebar link does; a link the browser must handle itself goes through location. function paletteGo(href) { if (!href) { return; } + pal.reload = null; pal.dlg.close(); var url = pageUrl(href); if (!url) { location.assign(href); return; } @@ -3969,6 +4219,62 @@ load({ target: withoutHash(url), dest: url, init: GET_INIT, how: 'nav', keep: false, post: false, form: null }); } + // Shows a line in the palette's footer, in the colour of its state. + function paletteNote(text, state) { + pal.note.textContent = text; + pal.note.className = 'palette-note muted small' + (state ? ' ' + state : ''); + } + + // Sends a state-changing control's form as the control itself would: its csrf field and other + // inputs, its formaction if it has one, and its own name and value. The palette says done only when + // the server answered with a redirect and no error notice; a refusal shows the server's own message. + // The page is reloaded once the palette closes, so it shows the new state. + function paletteSubmit(el) { + var form = el.form || el.closest('form'); + var action = el.getAttribute('formaction') || (form ? form.getAttribute('action') : '') || location.href; + var url = pageUrl(action); + if (!form || !url) { return; } + var data = new FormData(form); + if (el.name) { data.append(el.name, el.value); } + pal.busy = true; + paletteNote(pal.str.loading, ''); + fetch(url.href, { method: 'POST', headers: { accept: 'text/html' }, credentials: 'same-origin', body: new URLSearchParams(data) }).then(function (r) { + return r.text().then(function (text) { return { ok: r.redirected && r.status < 400, url: r.url, html: text }; }); + }).then(function (res) { + pal.busy = false; + var doc = new DOMParser().parseFromString(res.html, 'text/html'); + var alert = doc.querySelector('main [role="alert"], main .alert'); + if (res.ok && !alert) { + pal.reload = pageUrl(res.url); + paletteNote(pal.str.done, 'is-ok'); + } else { + paletteNote(alert ? alert.textContent.replace(/\s+/g, ' ').trim() : pal.str.refused, 'is-bad'); + } + }, function () { + pal.busy = false; + paletteNote(pal.str.refused, 'is-bad'); + }); + } + + // Runs what Enter or a click picked: a destination is followed, an action is carried out by its mode. + // A destructive control is never clicked from here: the palette closes on it, so the reader confirms. + function paletteRun(item) { + if (!item) { return; } + if (item.kind !== 'action') { paletteGo(item.href); return; } + if (pal.busy || !item.el.isConnected) { return; } + var el = item.el; + if (item.mode === 'post') { paletteSubmit(el); return; } + pal.reload = null; + if (item.mode === 'go' || (item.mode === 'confirm' && el.tagName === 'A')) { + paletteGo(el.getAttribute('href')); + return; + } + pal.dlg.close(); + if (item.mode === 'click') { el.click(); return; } + el.scrollIntoView({ block: 'center' }); + el.focus(); + } + // Built once. Its markup is static; every word in it arrives through the button's data attributes. function buildPalette() { var dlg = document.createElement('dialog'); @@ -3989,12 +4295,12 @@ if (e.isComposing) { return; } if (e.key === 'ArrowDown') { e.preventDefault(); paletteSelect(pal.sel + 1); } else if (e.key === 'ArrowUp') { e.preventDefault(); paletteSelect(pal.sel - 1); } - else if (e.key === 'Enter') { e.preventDefault(); if (pal.hits[pal.sel]) { paletteGo(pal.hits[pal.sel].href); } } + else if (e.key === 'Enter') { e.preventDefault(); paletteRun(pal.hits[pal.sel]); } // Tab completes the input to the selected item; Ctrl or Alt with Backspace drops the last path segment. else if (e.key === 'Tab') { e.preventDefault(); var item = pal.hits[pal.sel]; - if (item && item.kind !== 'search') { pal.input.value = paletteCompletion(item); renderPalette(); } + if (item && item.kind !== 'search' && item.kind !== 'action') { pal.input.value = paletteCompletion(item); renderPalette(); } } else if (e.key === 'Backspace' && (e.ctrlKey || e.altKey)) { e.preventDefault(); @@ -4010,10 +4316,16 @@ }); pal.list.addEventListener('click', function (e) { var li = e.target && e.target.closest ? e.target.closest('li[role="option"]') : null; - if (li) { paletteGo(pal.hits[Number(li.getAttribute('data-n'))].href); } + if (li) { paletteRun(pal.hits[Number(li.getAttribute('data-n'))]); } }); // The backdrop is the dialog element itself; the box fills the rest. dlg.addEventListener('click', function (e) { if (e.target === dlg) { dlg.close(); } }); + // A change sent from the palette shows on the page once the palette is closed, by a page load. + dlg.addEventListener('close', function () { + var next = pal.reload; + pal.reload = null; + if (next) { load({ target: withoutHash(next), dest: next, init: GET_INIT, how: 'nav', keep: false, post: false, form: null }); } + }); } function openPalette() { @@ -4025,6 +4337,7 @@ // A page swap removes body children, the dialog among them, so it is put back on each open. if (dlg.parentNode !== document.body) { document.body.appendChild(dlg); } pal.str = paletteStrings(opener); + pal.acts = paletteActions(); dlg.setAttribute('aria-label', pal.str.label); pal.input.placeholder = pal.str.placeholder; pal.input.setAttribute('aria-label', pal.str.placeholder); @@ -4037,6 +4350,7 @@ // 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(/\/+$/, ''); var prefill = path.split('/').filter(Boolean).length >= 2 ? path + '/' : ''; + pal.prefill = prefill; pal.input.value = prefill; renderPalette(); pal.input.focus(); @@ -5173,3 +5487,212 @@ }).observe(document.body, { childList: true, subtree: true }); reveal(); })(); + +// ---- 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 +// 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). +(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' } + }; + + var selKey = null; // the address of the selected row's first link + + function lang() { + return (document.documentElement.getAttribute('lang') || '').toLowerCase().indexOf('tr') === 0 ? 'tr' : 'en'; + } + + function rows() { + return Array.prototype.filter.call(document.querySelectorAll('[data-kb-row]'), function (r) { + return r.offsetParent !== null; + }); + } + + function selectedRow() { + return document.querySelector('[data-kb-row].kb-sel'); + } + + function keyOf(row) { + var a = row.querySelector('a[href]'); + return a ? a.getAttribute('href') : null; + } + + function select(row) { + var cur = selectedRow(); + if (cur) { cur.classList.remove('kb-sel'); } + if (!row) { selKey = null; return; } + row.classList.add('kb-sel'); + selKey = keyOf(row); + row.scrollIntoView({ block: 'nearest' }); + } + + // j and k stop at the ends of the list rather than wrapping. With nothing selected, j takes the first row. + function step(dir) { + var list = rows(); + if (!list.length) { return; } + var at = list.indexOf(selectedRow()); + var next = at < 0 ? (dir > 0 ? 0 : list.length - 1) : Math.min(list.length - 1, Math.max(0, at + dir)); + select(list[next]); + } + + function openHelp() { + var T = KB_TEXT[lang()]; + var old = document.getElementById('kb-help'); + if (old) { old.parentNode.removeChild(old); } + var dlg = document.createElement('dialog'); + dlg.id = 'kb-help'; + dlg.className = 'kb-help'; + dlg.setAttribute('aria-label', T.title); + var h = document.createElement('h2'); + 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) { + var dt = document.createElement('dt'); + var kbd = document.createElement('kbd'); + kbd.textContent = pair[0]; + dt.appendChild(kbd); + var dd = document.createElement('dd'); + dd.textContent = pair[1]; + dl.appendChild(dt); + dl.appendChild(dd); + }); + dlg.appendChild(dl); + var form = document.createElement('form'); + form.method = 'dialog'; + var btn = document.createElement('button'); + btn.type = 'submit'; + btn.className = 'button'; + btn.textContent = T.close; + form.appendChild(btn); + dlg.appendChild(form); + document.body.appendChild(dlg); + if (dlg.showModal) { dlg.showModal(); } + } + + document.addEventListener('keydown', function (e) { + var t = e.target; + if (e.isComposing || (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))) { return; } + if (e.ctrlKey || e.metaKey || e.altKey || document.querySelector('dialog[open]')) { return; } + if (e.key === '?') { e.preventDefault(); openHelp(); return; } + if (e.shiftKey) { return; } + if (e.key === 'j') { step(1); } + else if (e.key === 'k') { step(-1); } + else if (e.key === 'Enter') { + // A focused link or button keeps its own Enter; only a bare page takes the selected row. + var row = selectedRow(); + if (!row || (t && /^(A|BUTTON|SUMMARY)$/.test(t.tagName))) { return; } + var a = row.querySelector('a[href]'); + if (a) { e.preventDefault(); a.click(); } + } else if (e.key === 'x') { + var cur = selectedRow(); + var cb = cur ? cur.querySelector('input[type="checkbox"]') : null; + if (cb && !cb.disabled) { e.preventDefault(); cb.click(); } + } + }, false); + + // After a live swap or a page change the rows are new nodes: the selection moves to the row with the + // same address, or clears when there is none. + document.addEventListener('forge:swapped', function () { + if (!selKey) { return; } + var hit = rows().filter(function (r) { return keyOf(r) === selKey; })[0]; + if (hit) { hit.classList.add('kb-sel'); } else { selKey = null; } + }, false); +})(); + +// ---- pull request files: viewed marks --------------------------------------------------------------- +// The Viewed panel (data-viewed-panel) on the Files tab. A checkbox posts its new state to the +// pull's viewed route, and the page reloads only once the server answered; a refused post re-enables +// the box and changes nothing. Viewed files are collapsed by their heading (is-viewed). v toggles the +// focused row and n focuses the next unviewed one. Neither fires while typing, with a modifier held, +// or while a dialog is open. Neither key is bound elsewhere: j, k, Enter, x and ? belong to the row +// keys above and / to the palette. +(function () { + 'use strict'; + + var panel = document.querySelector('[data-viewed-panel]'); + if (!panel) { return; } + var rows = Array.prototype.slice.call(panel.querySelectorAll('[data-viewed-row]')); + var sections = Array.prototype.slice.call(document.querySelectorAll('section.diff-file')); + var focus = -1; + + function sectionOf(row) { + var label = row.getAttribute('data-label'); + return sections.filter(function (s) { return s.getAttribute('data-keep-anchor') === label; })[0] || null; + } + + function boxOf(row) { return row.querySelector('[data-viewed-toggle]'); } + + rows.forEach(function (row) { + var sec = sectionOf(row); + if (sec) { sec.classList.toggle('is-viewed', row.getAttribute('data-state') === 'viewed'); } + }); + + // The box keeps its old state until the server answers. The box is the new state's request: a + // checked box asks to clear the mark (viewed 0), an unchecked one asks to set it (viewed 1). + function post(box) { + if (!box || box.disabled) { return; } + box.disabled = true; + var body = new URLSearchParams(); + body.set('csrf', panel.getAttribute('data-csrf')); + body.set('path', box.getAttribute('data-path')); + body.set('viewed', box.checked ? '0' : '1'); + fetch(panel.getAttribute('data-action'), { method: 'POST', body: body, credentials: 'same-origin' }) + .then(function (res) { + if (!res.ok) { throw new Error('status ' + res.status); } + window.location.reload(); + }) + .catch(function () { box.disabled = false; }); + } + + panel.addEventListener('click', function (e) { + var box = e.target && e.target.closest ? e.target.closest('[data-viewed-toggle]') : null; + if (!box) { return; } + e.preventDefault(); + post(box); + }); + + function focusRow(i) { + rows.forEach(function (r) { r.classList.remove('is-focus'); }); + focus = i; + rows[i].classList.add('is-focus'); + var sec = sectionOf(rows[i]); + if (sec) { sec.scrollIntoView({ block: 'start' }); } + } + + // The next row after the focused one that is not viewed, wrapping; -1 when every file is viewed. + function nextUnviewed() { + var n = rows.length; + for (var k = 1; k <= n; k++) { + var i = (focus + k + n) % n; + if (rows[i].getAttribute('data-state') !== 'viewed') { return i; } + } + return -1; + } + + document.addEventListener('keydown', function (e) { + if ((e.key !== 'v' && e.key !== 'n') || e.ctrlKey || e.metaKey || e.altKey || e.isComposing) { return; } + var t = e.target; + if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) { return; } + if (document.querySelector('dialog[open]')) { return; } + if (e.key === 'n') { + var next = nextUnviewed(); + if (next < 0) { return; } + e.preventDefault(); + focusRow(next); + } else { + if (focus < 0) { return; } + var box = boxOf(rows[focus]); + if (!box || box.disabled) { return; } + e.preventDefault(); + post(box); + } + }); +})(); diff --git a/crates/forge-web/src/ci/release.rs b/crates/forge-web/src/ci/release.rs index 5b305a3..1d77efc 100644 --- a/crates/forge-web/src/ci/release.rs +++ b/crates/forge-web/src/ci/release.rs @@ -25,6 +25,7 @@ use tokio::io::AsyncWriteExt; use super::api::fit_to_cap; use super::{artifact_key, log_path, schedule, status_creator}; use crate::release_ops::{self, CreateRelease, ReleaseError}; +use crate::render::commit_message::CommitMessage; use crate::state::AppState; /// Most commits listed in the notes. Older commits are left out. @@ -299,10 +300,48 @@ async fn changelog( Ok(bullets(&commits, footer.as_deref())) } -/// One `- subject (shortsha)` line per commit, newest first, then the footer. Commits that would -/// push the notes past the body limit are left out. +/// Note sections in output order. Commit kinds map to them through `section_of`. +const SECTIONS: [&str; 7] = [ + "Features", + "Fixes", + "Performance", + "Style", + "CI", + "Documentation", + "Other", +]; + +/// The index in `SECTIONS` for a commit kind. Unknown kinds go to `Other`. +fn section_of(kind: &str) -> usize { + match kind { + "feat" => 0, + "fix" => 1, + "perf" => 2, + "style" | "ui" | "ux" => 3, + "ci" => 4, + "docs" => 5, + _ => 6, + } +} + +/// The notes body. When at least one subject is structured, the clauses are grouped under +/// `SECTIONS`; otherwise one `- subject (shortsha)` line per commit, newest first. Commits that +/// would push the notes past the body limit are left out, and the footer is kept in the count. fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String { let footer_len = footer.map_or(0, |f| f.chars().count() + 2); + let structured = commits + .iter() + .any(|commit| CommitMessage::parse(&commit.summary).is_some()); + let body = if structured { + grouped_bullets(commits, footer_len) + } else { + flat_bullets(commits, footer_len) + }; + with_footer(&body, footer) +} + +/// One `- subject (shortsha)` line per commit, newest first. +fn flat_bullets(commits: &[CommitInfo], footer_len: usize) -> String { let mut body = String::new(); let mut used = 0usize; for commit in commits { @@ -315,6 +354,58 @@ fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String { used += len; body.push_str(&line); } + body +} + +/// Lines grouped under `SECTIONS`, in commit order within each section. A heading costs its +/// `### name` line and the blank line after the section, and is counted once per section. +fn grouped_bullets(commits: &[CommitInfo], footer_len: usize) -> String { + let mut sections: Vec> = vec![Vec::new(); SECTIONS.len()]; + let mut used = 0usize; + 'commits: for commit in commits { + let short = commit.oid.get(..7).unwrap_or(&commit.oid); + let clauses: Vec<(usize, String)> = match CommitMessage::parse(&commit.summary) { + Some(message) => message + .groups + .iter() + .flat_map(|group| { + let section = section_of(&group.kind); + group.clauses.iter().map(move |clause| (section, clause.clone())) + }) + .collect(), + None => vec![(section_of(""), commit.summary.clone())], + }; + for (section, text) in clauses { + let line = format!("- {text} ({short})\n"); + let mut len = line.chars().count(); + if sections[section].is_empty() { + len += SECTIONS[section].chars().count() + 6; + } + if used + len + footer_len > MAX_BODY_CHARS { + break 'commits; + } + used += len; + sections[section].push(line); + } + } + let mut body = String::new(); + for (name, lines) in SECTIONS.iter().zip(§ions) { + if lines.is_empty() { + continue; + } + if !body.is_empty() { + body.push('\n'); + } + body.push_str(&format!("### {name}\n")); + for line in lines { + body.push_str(line); + } + } + body +} + +/// The body without trailing whitespace, then the footer after a blank line. +fn with_footer(body: &str, footer: Option<&str>) -> String { let mut body = body.trim_end().to_owned(); if let Some(footer) = footer { if !body.is_empty() { @@ -553,11 +644,8 @@ title = "forge {tag}" let release = release_named(&fx, "v1.1").await.expect("release made"); let short = &oid[..7]; - assert!( - release - .body - .starts_with(&format!("- fix: two ({short})\n- feat: one (")) - ); + assert!(release.body.starts_with("### Features\n- one (")); + assert!(release.body.contains(&format!("### Fixes\n- two ({short})"))); assert!(release.body.ends_with("Full changelog: v1.0...v1.1")); assert!( !release.body.contains("- change ("), @@ -729,8 +817,8 @@ title = "forge {tag}" on_run_finished(&fx.state, &run_of(&fx, 2).await).await; let release = release_named(&fx, "v1.1").await.expect("release made"); - assert!(release.body.starts_with("- fix: two (")); - assert!(release.body.contains("- feat: one (")); + assert!(release.body.starts_with("### Features\n- one (")); + assert!(release.body.contains("### Fixes\n- two (")); assert!(release.body.ends_with("Full changelog: v1.0...v1.1")); assert!(release_named(&fx, "v1.0").await.is_none()); } @@ -759,4 +847,45 @@ title = "forge {tag}" ); assert_eq!(bullets(&[], None), ""); } + + fn info(oid: &str, summary: &str) -> CommitInfo { + CommitInfo { + oid: oid.to_owned(), + parents: Vec::new(), + author_name: String::new(), + author_email: String::new(), + author_time: 0, + committer_name: String::new(), + committer_email: String::new(), + committer_time: 0, + summary: summary.to_owned(), + message: String::new(), + } + } + + #[test] + fn bullets_group_structured_commits_in_section_order() { + let commits = vec![ + info("aaaaaaa1111", "🐛 fix: b; ✨ feat: a"), + info("bbbbbbb2222", "Update the readme"), + info("ccccccc3333", "✨ feat: c"), + ]; + assert_eq!( + bullets(&commits, None), + "### Features\n- a (aaaaaaa)\n- c (ccccccc)\n\n### Fixes\n- b (aaaaaaa)\n\n### Other\n- Update the readme (bbbbbbb)" + ); + } + + #[test] + fn bullets_count_headings_and_footer_in_the_limit() { + let long = "x".repeat(1000); + let commits: Vec = (0..200) + .map(|i| info(&format!("{i:07}abcdef"), &format!("✨ feat: {long}{i}"))) + .collect(); + let footer = "Full changelog: a...b"; + let body = bullets(&commits, Some(footer)); + assert!(body.chars().count() <= MAX_BODY_CHARS); + assert!(body.starts_with("### Features\n- ")); + assert!(body.ends_with(footer)); + } } diff --git a/crates/forge-web/src/i18n/browse.rs b/crates/forge-web/src/i18n/browse.rs index 6bc4ae2..adf732c 100644 --- a/crates/forge-web/src/i18n/browse.rs +++ b/crates/forge-web/src/i18n/browse.rs @@ -62,6 +62,9 @@ strings! { PaletteLoading => "Loading…", "Yükleniyor…"; PaletteFailed => "The list could not be loaded.", "Liste yüklenemedi."; PaletteFiles => "Files", "Dosyalar"; + PaletteActions => "Actions on this page", "Bu sayfadaki işlemler"; + PaletteDone => "Done", "Tamamlandı"; + PaletteActionFailed => "The action did not go through.", "İşlem gerçekleşmedi."; BranchAuthorHeader => "Author", "Yazar"; BranchAheadBehindHeader => "Ahead / behind", "Önde / geride"; diff --git a/crates/forge-web/src/i18n/code.rs b/crates/forge-web/src/i18n/code.rs index 005a13e..fb88a03 100644 --- a/crates/forge-web/src/i18n/code.rs +++ b/crates/forge-web/src/i18n/code.rs @@ -75,6 +75,7 @@ pub enum K { AddSingleComment, CancelLink, ThisCommit, + ShowFullMessage, CommitStatusPrefix, StateSuccess, StateFailure, @@ -91,6 +92,7 @@ pub enum K { CoAuthorAnd, CoAuthorsLabel, RootCommit, + CommitChangesLabel, ParentLabel, BrowseFiles, SigVerified, @@ -266,6 +268,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (CancelLink, Tr) => "İptal", (ThisCommit, En) => "this commit", (ThisCommit, Tr) => "bu commit", + (ShowFullMessage, En) => "Show full message", + (ShowFullMessage, Tr) => "Tam mesajı göster", (CommitStatusPrefix, En) => "Commit status: ", (CommitStatusPrefix, Tr) => "Commit durumu: ", (StateSuccess, En) => "success", @@ -298,6 +302,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (CoAuthorsLabel, Tr) => "Ortak yazarlar", (RootCommit, En) => "Root commit (no parents)", (RootCommit, Tr) => "Kök commit (üst commit yok)", + (CommitChangesLabel, En) => "Changes in this commit", + (CommitChangesLabel, Tr) => "Bu commit'teki değişiklikler", (ParentLabel, En) => "Parent: ", (ParentLabel, Tr) => "Üst commit: ", (BrowseFiles, En) => "Browse files at this commit", @@ -605,6 +611,7 @@ mod tests { K::AddSingleComment, K::CancelLink, K::ThisCommit, + K::ShowFullMessage, K::CommitStatusPrefix, K::StateSuccess, K::StateFailure, @@ -621,6 +628,7 @@ mod tests { K::CoAuthorAnd, K::CoAuthorsLabel, K::RootCommit, + K::CommitChangesLabel, K::ParentLabel, K::BrowseFiles, K::SigVerified, diff --git a/crates/forge-web/src/i18n/misc.rs b/crates/forge-web/src/i18n/misc.rs index d32570a..9f53b0d 100644 --- a/crates/forge-web/src/i18n/misc.rs +++ b/crates/forge-web/src/i18n/misc.rs @@ -42,6 +42,23 @@ pub enum K { SidebarLeft, SidebarRight, ChooseSidebar, + // Appearance: row density, and the run-finished tone. + DensityLabel, + DensityComfortable, + DensityCompact, + DensityHelp, + ChooseDensity, + SoundLabel, + SoundSwitch, + SoundOwnRuns, + SoundPassed, + SoundPassedNote, + SoundFailed, + SoundFailedNote, + SoundPlay, + SoundFootOwn, + SoundFootTones, + ChooseSound, // Notifications: row kinds. KindOpenIssue, KindClosedIssue, @@ -211,6 +228,22 @@ const ALL: &[K] = &[ K::SidebarLeft, K::SidebarRight, K::ChooseSidebar, + K::DensityLabel, + K::DensityComfortable, + K::DensityCompact, + K::DensityHelp, + K::ChooseDensity, + K::SoundLabel, + K::SoundSwitch, + K::SoundOwnRuns, + K::SoundPassed, + K::SoundPassedNote, + K::SoundFailed, + K::SoundFailedNote, + K::SoundPlay, + K::SoundFootOwn, + K::SoundFootTones, + K::ChooseSound, K::KindOpenIssue, K::KindClosedIssue, K::KindOpenPull, @@ -399,6 +432,38 @@ pub fn t(lang: Lang, key: K) -> &'static str { (SidebarRight, Tr) => "Sağ", (ChooseSidebar, En) => "Choose a sidebar position from the list.", (ChooseSidebar, Tr) => "Listeden bir kenar çubuğu konumu seçin.", + (DensityLabel, En) => "Density", + (DensityLabel, Tr) => "Yoğunluk", + (DensityComfortable, En) => "Comfortable", + (DensityComfortable, Tr) => "Rahat", + (DensityCompact, En) => "Compact", + (DensityCompact, Tr) => "Sıkı", + (DensityHelp, En) => "Saved to your account. Compact shows more rows on a screen.", + (DensityHelp, Tr) => "Hesabınıza kaydedilir. Sıkı görünüm ekranda daha çok satır gösterir.", + (ChooseDensity, En) => "Choose Comfortable or Compact.", + (ChooseDensity, Tr) => "Rahat ya da Sıkı seçin.", + (SoundLabel, En) => "Sound", + (SoundLabel, Tr) => "Ses", + (SoundSwitch, En) => "Play a tone when my run finishes", + (SoundSwitch, Tr) => "Çalıştırmam bitince bir ses çal", + (SoundOwnRuns, En) => "Only your own runs", + (SoundOwnRuns, Tr) => "Yalnızca kendi çalıştırmalarınız", + (SoundPassed, En) => "Run passed", + (SoundPassed, Tr) => "Çalıştırma başarılı", + (SoundPassedNote, En) => "two rising notes", + (SoundPassedNote, Tr) => "yükselen iki nota", + (SoundFailed, En) => "Run failed", + (SoundFailed, Tr) => "Çalıştırma başarısız", + (SoundFailedNote, En) => "two falling notes", + (SoundFailedNote, Tr) => "alçalan iki nota", + (SoundPlay, En) => "Play", + (SoundPlay, Tr) => "Çal", + (SoundFootOwn, En) => "Never for a page you are looking at.", + (SoundFootOwn, Tr) => "Baktığınız sayfa için asla çalmaz.", + (SoundFootTones, En) => "Tones are made in the browser, with no audio files.", + (SoundFootTones, Tr) => "Sesler tarayıcıda üretilir, ses dosyası yoktur.", + (ChooseSound, En) => "Choose on or off.", + (ChooseSound, Tr) => "Açık ya da kapalı seçin.", (KindOpenIssue, En) => "Open issue", (KindOpenIssue, Tr) => "Açık sorun", (KindClosedIssue, En) => "Closed issue", diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index 48a0c36..c6212ac 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -31,6 +31,7 @@ pub mod link; pub mod merge_queue; pub mod migrate; pub mod misc; +pub mod needs; pub mod orgs; pub mod packages; pub mod pulls; diff --git a/crates/forge-web/src/i18n/needs.rs b/crates/forge-web/src/i18n/needs.rs new file mode 100644 index 0000000..4c4916c --- /dev/null +++ b/crates/forge-web/src/i18n/needs.rs @@ -0,0 +1,44 @@ +//! Strings for the `/needs-you` page and its command palette entry. + +use super::Lang; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum K { + NeedsYou, + FailedRuns, + ReviewsRequested, + YourPulls, + AssignedIssues, + Mentions, + ChangesRequested, + Approved, + AllReviewRequests, + AllClear, +} + +pub fn t(lang: Lang, key: K) -> &'static str { + use K::*; + use Lang::*; + match (key, lang) { + (NeedsYou, En) => "Needs you", + (NeedsYou, Tr) => "Sizi bekleyenler", + (FailedRuns, En) => "Your failed runs", + (FailedRuns, Tr) => "Başarısız çalıştırmalarınız", + (ReviewsRequested, En) => "Reviews requested", + (ReviewsRequested, Tr) => "İstenen incelemeler", + (YourPulls, En) => "Your pull requests", + (YourPulls, Tr) => "Pull request'leriniz", + (AssignedIssues, En) => "Assigned issues", + (AssignedIssues, Tr) => "Size atanan sorunlar", + (Mentions, En) => "Mentions", + (Mentions, Tr) => "Bahsetmeler", + (ChangesRequested, En) => "Changes requested", + (ChangesRequested, Tr) => "Değişiklik istendi", + (Approved, En) => "Approved", + (Approved, Tr) => "Onaylandı", + (AllReviewRequests, En) => "All review requests", + (AllReviewRequests, Tr) => "Tüm inceleme istekleri", + (AllClear, En) => "Nothing is waiting on you.", + (AllClear, Tr) => "Sizi bekleyen bir şey yok.", + } +} diff --git a/crates/forge-web/src/i18n/pulls.rs b/crates/forge-web/src/i18n/pulls.rs index a5943a8..39d0c21 100644 --- a/crates/forge-web/src/i18n/pulls.rs +++ b/crates/forge-web/src/i18n/pulls.rs @@ -38,6 +38,10 @@ pub enum K { RequestChangesChoice, SubmitReview, DiscardPending, + ViewedFiles, + ViewedHint, + ViewedMark, + ChangedSinceViewed, // pull_branch.rs BranchErrProtected, @@ -147,6 +151,14 @@ pub fn t(lang: Lang, key: K) -> &'static str { (SubmitReview, Tr) => "İncelemeyi gönder", (DiscardPending, En) => "Discard pending comments", (DiscardPending, Tr) => "Bekleyen yorumları sil", + (ViewedFiles, En) => "Viewed files", + (ViewedFiles, Tr) => "Görüntülenen dosyalar", + (ViewedHint, En) => "v marks the focused file, n moves to the next unviewed one.", + (ViewedHint, Tr) => "v odaktaki dosyayı işaretler, n görülmemiş sonrakine geçer.", + (ViewedMark, En) => "Mark as viewed", + (ViewedMark, Tr) => "Görüntülendi olarak işaretle", + (ChangedSinceViewed, En) => "Changed since you viewed", + (ChangedSinceViewed, Tr) => "Görüntülediğinizden beri değişti", (BranchErrProtected, En) => "This branch is protected, so it cannot be deleted.", (BranchErrProtected, Tr) => "Bu dal korumalı olduğu için silinemez.", @@ -248,6 +260,15 @@ pub fn commit_count(lang: Lang, count: usize) -> String { } } +/// The Viewed panel's count line: "2 of 16 viewed", or "2 / 16 görüldü" in Turkish, which needs no +/// plural suffix. +pub fn viewed_count(lang: Lang, done: usize, total: usize) -> String { + match lang { + Lang::En => format!("{done} of {total} viewed"), + Lang::Tr => format!("{done} / {total} görüldü"), + } +} + /// The review bar's pending comment line. pub fn pending_comments(lang: Lang, count: usize) -> String { match (lang, count) { @@ -334,6 +355,10 @@ mod tests { K::RequestChangesChoice, K::SubmitReview, K::DiscardPending, + K::ViewedFiles, + K::ViewedHint, + K::ViewedMark, + K::ChangedSinceViewed, K::BranchErrProtected, K::BranchErrDefault, K::BranchErrMoved, diff --git a/crates/forge-web/src/i18n/releases_ci.rs b/crates/forge-web/src/i18n/releases_ci.rs index 5fbab1e..41170a8 100644 --- a/crates/forge-web/src/i18n/releases_ci.rs +++ b/crates/forge-web/src/i18n/releases_ci.rs @@ -90,6 +90,13 @@ pub enum K { StateStopping, StoppingButton, + // The failure block at the top of a failed run. + FailHeading, + FailLine, + FailOpenLog, + FailNoLog, + FailNoError, + // Release notices, shown after a release action. RelSaved, RelDeleted, @@ -144,6 +151,9 @@ pub enum K { TargetMoveHelp, TargetLockedHelp, ReplaceAsset, + + // CI time estimate: a running run past its expected total. + TakingLonger, } pub fn t(lang: Lang, key: K) -> &'static str { @@ -275,6 +285,16 @@ pub fn t(lang: Lang, key: K) -> &'static str { (CopyDone, Tr) => "Kopyalandı", (CopyFailed, En) => "Copy failed", (CopyFailed, Tr) => "Kopyalanamadı", + (FailHeading, En) => "Failed job", + (FailHeading, Tr) => "Başarısız iş", + (FailLine, En) => "line", + (FailLine, Tr) => "satır", + (FailOpenLog, En) => "Open in full log", + (FailOpenLog, Tr) => "Tam günlükte aç", + (FailNoLog, En) => "This job wrote no log.", + (FailNoLog, Tr) => "Bu iş günlük yazmadı.", + (FailNoError, En) => "No error line found. The last lines of the log are shown.", + (FailNoError, Tr) => "Hata satırı bulunamadı. Günlüğün son satırları gösteriliyor.", (Duration, En) => "Duration", (Duration, Tr) => "Süre", (LogTruncated, En) => "Showing the last 512 KiB of the log. The full log is linked above.", @@ -465,6 +485,24 @@ pub fn t(lang: Lang, key: K) -> &'static str { } (ReplaceAsset, En) => "Replace", (ReplaceAsset, Tr) => "Değiştir", + (TakingLonger, En) => "taking longer than usual", + (TakingLonger, Tr) => "normalden uzun sürüyor", + } +} + +/// "about 12m left", with `t` the time: a number of minutes or seconds, or the `{t}` placeholder. +pub fn time_left(lang: Lang, t: &str) -> String { + match lang { + Lang::En => format!("about {t} left"), + Lang::Tr => format!("yaklaşık {t} kaldı"), + } +} + +/// "12m", or "12 dk" in Turkish: a minutes count, or the `{m}` placeholder. +pub fn minutes_only(lang: Lang, m: impl Display) -> String { + match lang { + Lang::En => format!("{m}m"), + Lang::Tr => format!("{m} dk"), } } @@ -629,6 +667,11 @@ mod tests { K::StateSkipped, K::StateStopping, K::StoppingButton, + K::FailHeading, + K::FailLine, + K::FailOpenLog, + K::FailNoLog, + K::FailNoError, K::RelSaved, K::RelDeleted, K::RelAssetUploaded, @@ -678,6 +721,7 @@ mod tests { K::TargetMoveHelp, K::TargetLockedHelp, K::ReplaceAsset, + K::TakingLonger, ]; #[test] diff --git a/crates/forge-web/src/pages/blame.rs b/crates/forge-web/src/pages/blame.rs index fbcb3f2..8d4e63b 100644 --- a/crates/forge-web/src/pages/blame.rs +++ b/crates/forge-web/src/pages/blame.rs @@ -22,6 +22,7 @@ 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::commit_line::commit_line; use crate::views::{ Crumb, breadcrumb, human_size, iso_time, now_unix, relative_time, repo_href, shell, short_oid, }; @@ -117,7 +118,7 @@ async fn blame_table(rows: Vec, lang: Lang) -> Result { (meta.author.as_str()) - (meta.summary.as_str()) + commit_line(subject: meta.summary.clone(), no_tag: true) if let Some(prior) = meta.prior_href { (b::t(lang, b::K::BlamePrior)) } diff --git a/crates/forge-web/src/pages/branches.rs b/crates/forge-web/src/pages/branches.rs index 2c8e1be..939e473 100644 --- a/crates/forge-web/src/pages/branches.rs +++ b/crates/forge-web/src/pages/branches.rs @@ -29,6 +29,7 @@ use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::pages::tree::{LastCommit, last_commit_view}; use crate::post_update::after_ref_update; use crate::state::AppState; +use crate::views::commit_line::commit_line; use crate::views::{alert, empty_state, iso_time, now_unix, relative_time, repo_href, shell}; path_param!(owner); @@ -164,7 +165,7 @@ async fn branch_table( if let Some(last) = row.last { - (last.summary.as_str()) + commit_line(subject: last.summary.clone()) } else { } diff --git a/crates/forge-web/src/pages/ci_estimate.rs b/crates/forge-web/src/pages/ci_estimate.rs new file mode 100644 index 0000000..b2e4e75 --- /dev/null +++ b/crates/forge-web/src/pages/ci_estimate.rs @@ -0,0 +1,248 @@ +//! The time left of a running CI run, estimated from its own past runs. The functions are pure: the +//! store hands in the samples, the run's jobs go in as steps, and the answers are unix seconds, +//! seconds or the page's words. The estimate of a job is the median of its last five successful runs +//! on the branch, or on any branch when the branch has fewer than `MIN_SAMPLES`. Failed and cancelled +//! runs are never sampled. + +use std::collections::{HashMap, HashSet}; + +use forge_core::ci::{JobSample, JobState}; +use serde::Deserialize; + +use crate::i18n::Lang; +use crate::i18n::releases_ci as rc; + +/// Samples a job needs before its estimate is trusted: a guess from fewer is worse than none. +pub const MIN_SAMPLES: usize = 3; + +/// One job of a run, as the estimate reads it. Times are unix seconds. +pub struct Step { + pub name: String, + pub needs: Vec, + pub state: JobState, + pub started: Option, + pub finished: Option, +} + +/// The `needs` of a job spec, read from its JSON. A spec that does not read has none. +pub fn needs_of(spec_json: &str) -> Vec { + #[derive(Deserialize, Default)] + #[serde(default)] + struct Needs { + needs: Vec, + } + serde_json::from_str::(spec_json) + .map(|spec| spec.needs) + .unwrap_or_default() +} + +/// The expected duration of `job` on `git_ref`, in seconds: the median of its durations in the newest +/// five successful runs on that branch, or in the newest five on any branch when the branch has fewer +/// than `MIN_SAMPLES`. None when neither has enough. +pub fn job_expected(samples: &[JobSample], git_ref: &str, job: &str) -> Option { + let on_branch: Vec = samples + .iter() + .filter(|s| s.job == job && s.git_ref == git_ref && s.branch_rank <= 5) + .map(|s| s.secs) + .collect(); + if on_branch.len() >= MIN_SAMPLES { + return Some(median(on_branch)); + } + let any: Vec = samples + .iter() + .filter(|s| s.job == job && s.repo_rank <= 5) + .map(|s| s.secs) + .collect(); + (any.len() >= MIN_SAMPLES).then(|| median(any)) +} + +/// The median of a list of seconds: the middle one, or the mean of the two middle ones. Zero for none. +fn median(mut secs: Vec) -> i64 { + secs.sort_unstable(); + let mid = secs.len() / 2; + match secs.len() { + 0 => 0, + n if n % 2 == 1 => secs[mid], + _ => (secs[mid - 1] + secs[mid]) / 2, + } +} + +/// The unix second a run is expected to end, from its steps and the expected duration `expected` gives +/// each job. A finished job ends when it did. A running job is due at its start plus its duration. A job +/// not yet started begins once its needs have ended, or now. None when a job still to run has no +/// expected duration, or the needs form a cycle. +pub fn expected_end( + now: i64, + steps: &[Step], + expected: impl Fn(&str) -> Option, +) -> Option { + let names: HashSet<&str> = steps.iter().map(|step| step.name.as_str()).collect(); + let mut ends: HashMap<&str, i64> = HashMap::new(); + let mut pending: Vec<&Step> = steps.iter().collect(); + while !pending.is_empty() { + let mut waiting = Vec::new(); + for &step in &pending { + let ready = step + .needs + .iter() + .all(|need| ends.contains_key(need.as_str()) || !names.contains(need.as_str())); + if !ready { + waiting.push(step); + continue; + } + let end = step_end(now, step, &ends, &expected)?; + ends.insert(step.name.as_str(), end); + } + if waiting.len() == pending.len() { + return None; + } + pending = waiting; + } + ends.values().copied().max() +} + +/// When one step ends, given the ends of the steps placed before it. +fn step_end( + now: i64, + step: &Step, + ends: &HashMap<&str, i64>, + expected: &impl Fn(&str) -> Option, +) -> Option { + if step.state.is_terminal() { + return Some(step.finished.unwrap_or(0)); + } + let duration = expected(step.name.as_str())?; + let start = match step.started { + Some(started) => started, + None => step + .needs + .iter() + .filter_map(|need| ends.get(need.as_str()).copied()) + .fold(now, i64::max), + }; + Some(start + duration) +} + +/// The expected end of a run whose jobs are `steps`, on `git_ref`, judged from the `samples` of the +/// repo's successful runs. +pub fn run_end(now: i64, steps: &[Step], samples: &[JobSample], git_ref: &str) -> Option { + expected_end(now, steps, |name| job_expected(samples, git_ref, name)) +} + +/// How far a run is through its expected total, with `elapsed` and `total` in seconds: the bar's +/// fraction, never past full, and the seconds left. Past the estimate there is no time left. +pub fn progress(elapsed: i64, total: i64) -> (f64, Option) { + if total <= 0 || elapsed >= total { + return (1.0, None); + } + (elapsed.max(0) as f64 / total as f64, Some(total - elapsed)) +} + +/// A live run's estimate as its page draws it, every value already text. The ticker rewrites the +/// words from the templates. +pub struct Est { + /// The expected total in seconds, counted from the origin the page shows the elapsed time from. + pub expected: String, + /// The bar's fill, 0 to 100. + pub pct: String, + /// The words after the elapsed time: "about 12m left", or "taking longer than usual". + pub phrase: String, + /// The phrase for seconds left, with `{t}` for the time. + pub left: String, + /// The words past the estimate. + pub over: String, + /// The minutes form of a time, with `{m}`. + pub minutes: String, +} + +/// The estimate of a run that began at `origin`, is `now` by the clock, and is expected to end at +/// `end`. +pub fn estimate(lang: Lang, origin: i64, now: i64, end: i64) -> Est { + let total = (end - origin).max(0); + let (fraction, left) = progress(now - origin, total); + let phrase = match left { + Some(secs) => rc::time_left(lang, &left_text(lang, secs)), + None => rc::t(lang, rc::K::TakingLonger).to_owned(), + }; + Est { + expected: total.to_string(), + pct: ((fraction * 100.0).round() as u32).to_string(), + phrase, + left: rc::time_left(lang, "{t}"), + over: rc::t(lang, rc::K::TakingLonger).to_owned(), + minutes: rc::minutes_only(lang, "{m}"), + } +} + +/// Seconds left as the page words them: whole minutes rounded up from a minute, else seconds. +fn left_text(lang: Lang, secs: i64) -> String { + if secs >= 60 { + rc::minutes_only(lang, (secs + 59) / 60) + } else { + rc::duration_seconds(lang, secs) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample(git_ref: &str, branch_rank: i64, repo_rank: i64, secs: i64) -> JobSample { + JobSample { + git_ref: git_ref.to_owned(), + branch_rank, + repo_rank, + job: "test".to_owned(), + secs, + } + } + + #[test] + fn job_estimate_needs_three_samples_and_falls_back_to_any_branch() { + let two = [sample("main", 1, 1, 60), sample("main", 2, 2, 80)]; + assert_eq!(job_expected(&two, "main", "test"), None); + + let three = [ + sample("main", 1, 1, 60), + sample("main", 2, 2, 100), + sample("main", 3, 3, 90), + ]; + assert_eq!(job_expected(&three, "main", "test"), Some(90)); + + // The branch has two; the repo's newest five on any branch give the median 100. + let fallback = [ + sample("main", 1, 1, 60), + sample("main", 2, 2, 80), + sample("dev", 1, 3, 100), + sample("dev", 2, 4, 120), + sample("dev", 3, 5, 110), + ]; + assert_eq!(job_expected(&fallback, "main", "test"), Some(100)); + } + + #[test] + fn a_queued_job_waits_for_its_need_and_progress_never_goes_negative() { + // a started at 100 and is due at 150; b needs a, so it is due at 150 + 30. + let steps = [ + Step { + name: "a".to_owned(), + needs: Vec::new(), + state: JobState::Running, + started: Some(100), + finished: None, + }, + Step { + name: "b".to_owned(), + needs: vec!["a".to_owned()], + state: JobState::Queued, + started: None, + finished: None, + }, + ]; + let end = expected_end(120, &steps, |name| Some(if name == "a" { 50 } else { 30 })); + assert_eq!(end, Some(180)); + + assert_eq!(progress(30, 60), (0.5, Some(30))); + assert_eq!(progress(90, 60), (1.0, None)); + } +} diff --git a/crates/forge-web/src/pages/ci_fail.rs b/crates/forge-web/src/pages/ci_fail.rs new file mode 100644 index 0000000..1f19c04 --- /dev/null +++ b/crates/forge-web/src/pages/ci_fail.rs @@ -0,0 +1,181 @@ +//! The failure block at the top of a failed run's page: the first failed job, its message, the lines of +//! its log around the first error, and a link to that line in the job page's numbered log. Steps are +//! not stored, so the failed job is the unit. The log is untrusted: its lines are rendered as text. + +use std::ops::Range; + +use topcoat::Result; +use topcoat::view::{View, component, view}; + +use crate::ci::log_path; +use crate::i18n::{ + Lang, + releases_ci::{self as g, K}, +}; +use crate::pages::ci_job::log_tail; +use crate::pages::ci_runs::{job_href, strip_ansi}; +use crate::state::AppState; + +/// Most lines the block shows. +const WINDOW: usize = 30; +/// Lines kept before the first error. +const BEFORE: usize = 5; +/// Lines shown when no line matches an error pattern. +const FALLBACK: usize = 20; +/// Patterns that mark an error line. Matching is case-sensitive, which keeps prose such as "error +/// handling" out. `FAILED` also covers `test result: FAILED`. +const PATTERNS: [&str; 6] = [ + "error:", + "error[E", + "FAILED", + "panicked at", + "npm ERR!", + "fatal:", +]; + +/// The index of the first line that matches an error pattern. +fn first_error(lines: &[String]) -> Option { + lines + .iter() + .position(|line| PATTERNS.iter().any(|pattern| line.contains(pattern))) +} + +/// The indices of the lines to show for a failed step's log: at most 30 lines, starting 5 lines before +/// the first line that matches an error pattern. With no match, the last 20 lines. +pub(crate) fn error_range(lines: &[String]) -> Range { + let len = lines.len(); + match first_error(lines) { + Some(hit) => { + let start = hit.saturating_sub(BEFORE).min(len.saturating_sub(WINDOW)); + start..(start + WINDOW).min(len) + } + None => len.saturating_sub(FALLBACK)..len, + } +} + +/// One shown line: its number in the whole job log, its text without ANSI codes, and whether it is +/// the first error. +#[derive(Clone)] +pub(crate) struct FailLine { + no: u64, + text: String, + hit: bool, +} + +/// The values of the failure block, read once per run page. +#[derive(Clone)] +pub(crate) struct FailFirst { + job_name: String, + job_href: String, + message: String, + has_log: bool, + /// The job's number for the first error line, when a line matched. + line_no: Option, + lines: Vec, +} + +/// Reads the failed job's log tail (the same bounded read as the job page) and picks the lines to show. +pub(crate) async fn read( + state: &AppState, + title: &str, + job_id: &str, + job_name: &str, + message: &str, +) -> Result { + let tail = log_tail(&log_path(&state.config.data_dir, job_id)).await?; + let mut all: Vec = tail.text.lines().map(strip_ansi).collect(); + while all.last().is_some_and(|line| line.trim().is_empty()) { + all.pop(); + } + let hit = first_error(&all); + let range = error_range(&all); + let start = range.start; + let lines = all[range] + .iter() + .enumerate() + .map(|(k, text)| { + let index = start + k; + FailLine { + no: tail.first_line + index as u64, + text: text.clone(), + hit: hit == Some(index), + } + }) + .collect(); + Ok(FailFirst { + job_name: job_name.to_owned(), + job_href: job_href(title, job_id), + message: message.to_owned(), + has_log: !all.is_empty(), + line_no: hit.map(|index| tail.first_line + index as u64), + lines, + }) +} + +/// The failure block. The job's name links to its page; the first error links to its line there. +#[component] +pub(crate) async fn fail_first_block(lang: Lang, fail: FailFirst) -> Result { + let line_href = fail + .line_no + .map(|no| format!("{}#L{no}", fail.job_href)); + Ok(view! { +
+

+ (g::t(lang, K::FailHeading)) + " " (fail.job_name.as_str()) +

+ if !fail.message.is_empty() { +

(fail.message.as_str())

+ } + if !fail.has_log { +

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

+ } else { + if let (Some(href), Some(no)) = (line_href.as_ref(), fail.line_no) { +

(g::t(lang, K::FailOpenLog)) " \u{b7} " (g::t(lang, K::FailLine)) " " (no)

+ } else { +

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

+ } +
+ for line in fail.lines.iter() { +
(line.no)(line.text.as_str())
+ } +
+ } +
+ }) +} + +#[cfg(test)] +mod tests { + use super::{FALLBACK, WINDOW, error_range}; + + fn lines(count: usize) -> Vec { + (0..count).map(|i| format!("line {i}")).collect() + } + + #[test] + fn the_first_error_opens_a_window_of_at_most_thirty_lines() { + let mut log = lines(40); + log[12] = "error[E0425]: cannot find value".to_owned(); + log[20] = "error: later one".to_owned(); + let range = error_range(&log); + assert_eq!(range, 7..37); + assert!(range.len() <= WINDOW); + assert!(range.contains(&12)); + } + + #[test] + fn a_match_near_the_end_keeps_a_full_window() { + let mut log = lines(40); + log[39] = "thread 'x' panicked at src/lib.rs:3".to_owned(); + assert_eq!(error_range(&log), 10..40); + } + + #[test] + fn without_an_error_the_last_lines_are_shown() { + let log = lines(100); + assert_eq!(error_range(&log), (100 - FALLBACK)..100); + assert_eq!(error_range(&lines(5)), 0..5); + assert_eq!(error_range(&[]), 0..0); + } +} diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index 0ce6c4d..3e0613c 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -81,11 +81,11 @@ fn whole_utf8_len(buf: &[u8]) -> usize { /// What the job page shows of a log: the text, whether the start was cut, the byte offset just /// past the text, and the number of its first line in the whole log. -struct Tail { - text: String, +pub(crate) struct Tail { + pub(crate) text: String, truncated: bool, offset: u64, - first_line: u64, + pub(crate) first_line: u64, } /// The number of newlines in the first `end` bytes of the file, so a cut log keeps true line numbers. @@ -112,7 +112,7 @@ async fn newlines_before(path: &Path, end: u64) -> Result { } /// The last `TAIL_BYTES` of a log, from a line boundary. A log that does not exist yet is empty. -async fn log_tail(path: &Path) -> Result { +pub(crate) async fn log_tail(path: &Path) -> Result { let mut file = match tokio::fs::File::open(path).await { Ok(file) => file, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { @@ -377,7 +377,7 @@ async fn job_body(
- +
} @@ -393,7 +393,7 @@ async fn job_body( - +