From 324720cbc8fd202ed81775b1b67e159aa066f380 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 29 Oct 2026 00:53:12 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20the=20signed-in=20topbar=20?= =?UTF-8?q?is=20a=20path=20bar=20and=20a=20live=20strip:=20the=20breadcrum?= =?UTF-8?q?b=20opens=20the=20palette=20in=20place,=20filled=20with=20the?= =?UTF-8?q?=20current=20path,=20with=20the=20repo's=20files,=20Tab=20compl?= =?UTF-8?q?etion=20and=20"/"=20to=20open;=20the=20strip=20shows=20the=20vi?= =?UTF-8?q?ewer's=20running=20and=20just-finished=20CI=20runs=20as=20pills?= =?UTF-8?q?;=20the=20profile=20corner=20moves=20to=20the=20foot=20of=20the?= =?UTF-8?q?=20sidebar=20(and=20the=20phone=20menu):=20a=20heat=20ring=20fi?= =?UTF-8?q?lls=20while=20a=20run=20goes,=20review,=20mention=20and=20faili?= =?UTF-8?q?ng-run=20chips=20replace=20the=20bell,=20and=20its=20menu=20ope?= =?UTF-8?q?ns=20on=20what=20waits=20on=20you,=20then=20theme,=20profile,?= =?UTF-8?q?=20settings=20and=20log=20out;=20all=20of=20it=20follows=20/-/a?= =?UTF-8?q?ctivity/stream=20live?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-core/src/store/mod.rs | 1 + crates/forge-core/src/store/notifications.rs | 4 +- crates/forge-core/src/store/shell_activity.rs | 362 ++++++++++++ crates/forge-web/assets/nav.js | 383 +++++++++++- crates/forge-web/src/ci/live.rs | 12 + crates/forge-web/src/i18n/browse.rs | 1 + crates/forge-web/src/i18n/misc.rs | 45 ++ crates/forge-web/src/pages/activity.rs | 182 ++++++ crates/forge-web/src/pages/ci_tests.rs | 17 +- crates/forge-web/src/pages/mod.rs | 1 + crates/forge-web/src/pages/notifications.rs | 6 +- .../forge-web/src/pages/settings_profile.rs | 2 +- crates/forge-web/src/views/mod.rs | 504 +++++++++++++--- style/_palette.scss | 48 +- style/_shell.scss | 559 +++++++++++++++++- style/main.scss | 22 + 16 files changed, 1975 insertions(+), 174 deletions(-) create mode 100644 crates/forge-core/src/store/shell_activity.rs create mode 100644 crates/forge-web/src/pages/activity.rs diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index d4d2880..2ffeb98 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -39,6 +39,7 @@ pub mod repo_listing; pub mod review_requests; pub mod reviews; pub mod server_settings; +pub mod shell_activity; pub mod signatures; pub mod snapshot; pub mod snippets; diff --git a/crates/forge-core/src/store/notifications.rs b/crates/forge-core/src/store/notifications.rs index b8748b2..caec50f 100644 --- a/crates/forge-core/src/store/notifications.rs +++ b/crates/forge-core/src/store/notifications.rs @@ -17,14 +17,14 @@ const MAX_NOTIFICATION_PAGE: u32 = 200; /// The condition under which the inbox owner may still read repo `r`: the read rule, or an /// instance admin. Takes the user id five times. A repo made private, or one the user was removed /// from, drops out of the inbox, the dashboard and the unread count at once. -fn readable_repo() -> String { +pub(super) fn readable_repo() -> String { format!( "({READABLE_BY_VIEWER} OR EXISTS (SELECT 1 FROM users ua WHERE ua.id = ? AND ua.is_admin = 1))" ) } /// The user id, bound once per `?` of `readable_repo`. -fn readable_params(user_id: &str) -> impl Iterator + '_ { +pub(super) fn readable_params(user_id: &str) -> impl Iterator + '_ { (0..5).map(move |_| Value::Text(user_id.to_string())) } diff --git a/crates/forge-core/src/store/shell_activity.rs b/crates/forge-core/src/store/shell_activity.rs new file mode 100644 index 0000000..e12c317 --- /dev/null +++ b/crates/forge-core/src/store/shell_activity.rs @@ -0,0 +1,362 @@ +//! Read-only queries behind the sidebar "profile corner": the signed-in user's inbox counts, the +//! items waiting on them, and the state of their own CI runs. Nothing here writes. + +use std::time::Duration; + +use turso::{Row, Value}; + +use super::notifications::{readable_params, readable_repo}; +use super::{Store, col_int, col_opt_text, col_text, fetch_all}; +use crate::ci::RunState; +use crate::error::{Error, Result}; +use crate::notifications::Reason; +use crate::time::stamp_ago; + +/// Most runs each of `ActorRuns::running` and `ActorRuns::finished` lists. +const MAX_ACTOR_RUNS: i64 = 5; + +/// How far back a failing run still counts toward `ActorRuns::failing`. +const FAILING_WINDOW: Duration = Duration::from_secs(7 * 24 * 60 * 60); + +/// Unread inbox rows of the two kinds the corner shows. +#[derive(Debug, Clone, Copy, Default)] +pub struct InboxKinds { + /// Unread review requests. + pub reviews: u64, + /// Unread mentions. + pub mentions: u64, +} + +/// An unread inbox row that is waiting on the user, as the corner lists it. +#[derive(Debug, Clone)] +pub struct WaitingItem { + /// Owner username of the repo. + pub owner: String, + /// Repo name. + pub repo: String, + /// Issue or pull number. + pub number: i64, + /// True when the number is a pull request. + pub is_pull: bool, + /// Title of the issue or pull. + pub title: String, + /// Why the user was notified (`ReviewRequested` or `Mention`). + pub reason: Reason, + /// When the inbox row last changed. + pub updated_at: String, +} + +/// The user's own CI runs, as the corner shows them. +#[derive(Debug, Clone)] +pub struct ActorRuns { + /// Queued or running runs, newest first, at most 5. + pub running: Vec, + /// Runs that finished recently, newest first, at most 5. + pub finished: Vec, + /// Refs whose newest run by this user failed within the last 7 days. + pub failing: u64, +} + +/// One CI run of the user, with its job progress. +#[derive(Debug, Clone)] +pub struct ActorRun { + /// 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, + /// Current run state. + pub state: RunState, + /// When the run was created. + pub created_at: String, + /// When the run finished, if it has. + pub finished_at: Option, + /// Jobs the run has. + pub jobs_total: u64, + /// Jobs in a final state (success, failure, cancelled, error or skipped). + pub jobs_done: u64, + /// Name of one job that is running now, if any. + pub current_job: Option, +} + +/// Runs one row per run: owner, repo, number, ref, state, times, job counts and a running job. +/// The caller appends the WHERE, ORDER BY and LIMIT. +const ACTOR_RUN_SELECT: &str = "SELECT o.username, r.name, ci_runs.number, ci_runs.git_ref, \ + ci_runs.state, ci_runs.created_at, ci_runs.finished_at, \ + (SELECT COUNT(*) FROM ci_jobs j WHERE j.run_id = ci_runs.id), \ + (SELECT COUNT(*) FROM ci_jobs j WHERE j.run_id = ci_runs.id \ + AND j.state IN ('success', 'failure', 'cancelled', 'error', 'skipped')), \ + (SELECT j.name FROM ci_jobs j WHERE j.run_id = ci_runs.id AND j.state = 'running' \ + ORDER BY j.name LIMIT 1) \ + FROM ci_runs \ + JOIN repos r ON r.id = ci_runs.repo_id \ + JOIN users o ON o.id = r.owner_id"; + +/// A count column as `u64`. Counts are never negative, so a negative value is a database error. +fn count_from(n: i64) -> Result { + u64::try_from(n).map_err(|_| Error::Database("negative count".into())) +} + +/// Maps a row of `ACTOR_RUN_SELECT`. +fn map_actor_run(row: &Row) -> Result { + Ok(ActorRun { + owner: col_text(row, 0)?, + repo: col_text(row, 1)?, + number: col_int(row, 2)?, + git_ref: col_text(row, 3)?, + state: col_text(row, 4)?.parse::()?, + created_at: col_text(row, 5)?, + finished_at: col_opt_text(row, 6)?, + jobs_total: count_from(col_int(row, 7)?)?, + jobs_done: count_from(col_int(row, 8)?)?, + current_job: col_opt_text(row, 9)?, + }) +} + +impl Store { + /// Unread review requests and mentions in the user's inbox, in repos the user can still read. + pub async fn inbox_kind_counts(&self, user_id: &str) -> Result { + let readable = readable_repo(); + let sql = format!( + "SELECT n.reason, COUNT(*) FROM notifications n JOIN repos r ON r.id = n.repo_id \ + WHERE n.user_id = ? AND n.unread = 1 \ + AND n.reason IN ('review_requested', 'mention') AND {readable} \ + GROUP BY n.reason" + ); + let mut params = vec![Value::Text(user_id.to_string())]; + params.extend(readable_params(user_id)); + let conn = self.read_conn().await; + let rows = fetch_all(&conn, &sql, params, |row| { + Ok((col_text(row, 0)?, col_int(row, 1)?)) + }) + .await?; + let mut kinds = InboxKinds::default(); + for (reason, n) in rows { + match reason.as_str() { + "review_requested" => kinds.reviews = count_from(n)?, + "mention" => kinds.mentions = count_from(n)?, + _ => {} + } + } + Ok(kinds) + } + + /// The user's newest unread review requests and mentions, newest first, at most `limit`. + pub async fn waiting_on(&self, user_id: &str, limit: u64) -> Result> { + let readable = readable_repo(); + let sql = format!( + "SELECT o.username, r.name, i.number, i.kind, i.title, n.reason, 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 IN ('review_requested', 'mention') AND {readable} \ + ORDER BY n.updated_at DESC, n.id DESC LIMIT ?" + ); + let mut params = vec![Value::Text(user_id.to_string())]; + params.extend(readable_params(user_id)); + params.push(Value::Integer(i64::try_from(limit).unwrap_or(i64::MAX))); + let conn = self.read_conn().await; + fetch_all(&conn, &sql, params, |row| { + let reason_text = col_text(row, 5)?; + let reason = Reason::parse(&reason_text).ok_or_else(|| { + Error::Database(format!("unknown notification reason {reason_text:?}")) + })?; + 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, + updated_at: col_text(row, 6)?, + }) + }) + .await + } + + /// The user's own CI runs: those still queued or running, those that finished within the last + /// `recent_secs` seconds, and how many refs are failing on their newest run. + pub async fn actor_runs(&self, actor_id: &str, recent_secs: i64) -> Result { + // Every query binds the viewer's readable-repo filter, so a run in a repo the actor can no + // longer read is left out. The placeholders are all plain `?`, bound in SQL order. + let readable = readable_repo(); + let conn = self.read_conn().await; + let mut params = vec![Value::Text(actor_id.to_string())]; + params.extend(readable_params(actor_id)); + params.push(Value::Integer(MAX_ACTOR_RUNS)); + let running = fetch_all( + &conn, + &format!( + "{ACTOR_RUN_SELECT} WHERE ci_runs.actor_id = ? \ + AND ci_runs.state IN ('queued', 'running') AND {readable} \ + ORDER BY ci_runs.created_at DESC, ci_runs.id DESC LIMIT ?" + ), + params, + map_actor_run, + ) + .await?; + + let recent = Duration::from_secs(u64::try_from(recent_secs).unwrap_or(0)); + let mut params = vec![ + Value::Text(actor_id.to_string()), + Value::Text(stamp_ago(recent)), + ]; + params.extend(readable_params(actor_id)); + params.push(Value::Integer(MAX_ACTOR_RUNS)); + let finished = fetch_all( + &conn, + &format!( + "{ACTOR_RUN_SELECT} WHERE ci_runs.actor_id = ? \ + AND ci_runs.finished_at >= ? AND {readable} \ + ORDER BY ci_runs.finished_at DESC, ci_runs.id DESC LIMIT ?" + ), + params, + map_actor_run, + ) + .await?; + + // Newest run per (repo, ref) among this actor's runs, then count the ones that failed. + let mut params = vec![Value::Text(actor_id.to_string())]; + params.extend(readable_params(actor_id)); + params.push(Value::Text(stamp_ago(FAILING_WINDOW))); + let failing = fetch_all( + &conn, + &format!( + "SELECT COUNT(*) FROM ( \ + SELECT ci_runs.state, ci_runs.created_at, 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 \ + WHERE ci_runs.actor_id = ? AND {readable} \ + ) WHERE rn = 1 AND state IN ('failure', 'error') AND created_at >= ?" + ), + params, + |row| col_int(row, 0), + ) + .await?; + let failing = match failing.first() { + Some(n) => count_from(*n)?, + None => 0, + }; + + Ok(ActorRuns { + running, + finished, + failing, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::Visibility; + use crate::time::now_stamp; + + /// Inserts one CI run row directly, with the columns the queries read. + #[allow(clippy::too_many_arguments)] + async fn insert_run( + store: &Store, + id: &str, + repo_id: &str, + number: i64, + git_ref: &str, + actor_id: &str, + state: &str, + created_at: &str, + ) { + store + .inner + .conn + .lock() + .await + .execute( + "INSERT INTO ci_runs (id, repo_id, number, trigger, git_ref, commit_oid, actor_id, \ + state, created_at) VALUES (?1, ?2, ?3, 'push', ?4, 'abc123', ?5, ?6, ?7)", + vec![ + Value::Text(id.to_string()), + Value::Text(repo_id.to_string()), + Value::Integer(number), + Value::Text(git_ref.to_string()), + Value::Text(actor_id.to_string()), + Value::Text(state.to_string()), + Value::Text(created_at.to_string()), + ], + ) + .await + .unwrap(); + } + + /// Inserts one CI job row of a run. + async fn insert_job(store: &Store, id: &str, run_id: &str, name: &str, state: &str) { + store + .inner + .conn + .lock() + .await + .execute( + "INSERT INTO ci_jobs (id, run_id, name, spec, state) VALUES (?1, ?2, ?3, '{}', ?4)", + vec![ + Value::Text(id.to_string()), + Value::Text(run_id.to_string()), + Value::Text(name.to_string()), + Value::Text(state.to_string()), + ], + ) + .await + .unwrap(); + } + + #[tokio::test] + async fn actor_runs_show_running_run_and_failing_ref() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let user = store + .create_user("Tahinli", None, "hash", false) + .await + .unwrap(); + let repo = store + .create_repo(&user.id, "proj", "", Visibility::Public, "main") + .await + .unwrap(); + let hour_ago = stamp_ago(Duration::from_secs(3600)); + // A failed run on dev an hour ago, and a running run on main with one job going. + insert_run( + &store, + "run1", + &repo.id, + 1, + "refs/heads/dev", + &user.id, + "failure", + &hour_ago, + ) + .await; + insert_run( + &store, + "run2", + &repo.id, + 2, + "refs/heads/main", + &user.id, + "running", + &now_stamp(), + ) + .await; + insert_job(&store, "job1", "run2", "build", "running").await; + insert_job(&store, "job2", "run2", "lint", "success").await; + + let runs = store.actor_runs(&user.id, 3600).await.unwrap(); + assert_eq!(runs.running.len(), 1); + let running = &runs.running[0]; + assert_eq!(running.number, 2); + assert_eq!(running.jobs_total, 2); + assert_eq!(running.jobs_done, 1); + assert_eq!(running.current_job.as_deref(), Some("build")); + assert_eq!(runs.failing, 1); + } +} diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index d6cc4c6..dbb4300 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -168,7 +168,15 @@ syncStyles(doc); var kept = keepFields ? captureFields() : null; var nodes = Array.prototype.map.call(doc.body.childNodes, function (n) { return document.importNode(n, true); }); - document.body.replaceChildren.apply(document.body, nodes); + // A live change must not shut the palette the reader is typing in. Taking an open modal dialog out + // of the page closes it for good, so everything else is replaced around it. + var palOpen = dd ? document.querySelector('body > dialog.palette[open]') : null; + if (palOpen) { + Array.prototype.slice.call(document.body.childNodes).forEach(function (n) { if (n !== palOpen) { n.remove(); } }); + nodes.forEach(function (n) { document.body.insertBefore(n, palOpen); }); + } else { + document.body.replaceChildren.apply(document.body, nodes); + } // Re-create scripts so they run (a parsed-in script does not). The guard above keeps this file // from starting twice. document.body.querySelectorAll('script').forEach(function (old) { @@ -185,6 +193,7 @@ followTail(); restoreJobs(jobs); syncUnread(); + syncActivity(); syncLive(); syncPush(); syncTick(); @@ -613,13 +622,14 @@ } // Dropdown menus: the
that float over the page (avatar menu, branch selector, clone - // popover, phone menu). Inline disclosures are not listed: a click outside leaves them open. - var DROPDOWN = 'details.menu, details.ref-select, details.clone, details.nav-toggle'; + // popover, phone menu, profile corner). Inline disclosures are not listed: a click outside leaves them open. + var DROPDOWN = 'details.menu, details.ref-select, details.clone, details.nav-toggle, details.corner'; - // Closes every open dropdown except `keep` (pass null to close them all). - function closeDropdowns(keep) { + // Closes every open dropdown that does not contain `from` (pass null to close them all). The corner + // sits inside the phone menu, so a click in the corner keeps the phone menu open too. + function closeDropdowns(from) { document.querySelectorAll(DROPDOWN).forEach(function (d) { - if (d.open && d !== keep) { d.open = false; } + if (d.open && !(from && d.contains(from))) { d.open = false; } }); } @@ -672,8 +682,7 @@ // A click outside an open dropdown closes it. A click inside one (a select, a form field) keeps // it open. Opening a dropdown by its summary closes the others: the browser toggles it after this. document.addEventListener('click', function (e) { - var inside = e.target && e.target.closest ? e.target.closest(DROPDOWN) : null; - closeDropdowns(inside); + closeDropdowns(e.target && e.target.nodeType === 1 ? e.target : null); }, false); // Escape closes the open dropdowns and returns focus to the summary of the one that held it. @@ -1223,14 +1232,14 @@ // A filtered view asked for in place: the URL is replaced (no history entry per change), fields // and caret come through the swap, and the scroll stays put. - // Live unread count. The bell is re-rendered by every swap, so it is looked up on each update. One - // EventSource serves the page and stays open across swaps. It is opened only while a bell is shown - // (signed-in pages) and closed when the bell is gone. The server pushes each change; nothing polls. - // The count shows twice: on the bell, and next to Notifications in the sidebar and the phone menu. + // Live unread count. The profile corner (data-unread-stream) is re-rendered by every swap, so it is + // looked up on each update. One EventSource serves the page and stays open across swaps. It is + // opened only while a corner is shown (signed-in pages) and closed when it is gone. The server + // pushes each change; nothing polls. Each `unread` event also tells the activity stream below to + // refresh. The count shows twice: as a dot on the menu toggle (has-dot), and next to Notifications + // in the sidebar and the phone menu. var unreadStream = null; - function bell() { return document.querySelector('a.bell'); } - // Shows the count in one link the way the server renders it: a span with the number, or no span at zero. function setCount(el, cls, n) { var badge = el.querySelector('.' + cls); @@ -1247,15 +1256,16 @@ } function setUnread(n) { - var el = bell(); - if (el) { setCount(el, 'bell-count', n); } + // The menu toggle carries a dot while anything is unread. + var toggles = document.querySelectorAll('details.nav-toggle > summary'); + for (var t = 0; t < toggles.length; t++) { toggles[t].classList.toggle('has-dot', n > 0); } // The sidebar's Notifications link (the sidebar and the phone menu hold one each), `.count` as the server renders it. var links = document.querySelectorAll('nav.side-links a[href="/notifications"]'); for (var i = 0; i < links.length; i++) { setCount(links[i], 'count', n); } } function syncUnread() { - if (!bell()) { + if (!document.querySelector('[data-unread-stream]')) { if (unreadStream) { unreadStream.close(); unreadStream = null; } return; } @@ -1263,11 +1273,208 @@ unreadStream = new EventSource('/notifications/stream'); unreadStream.addEventListener('unread', function (e) { setUnread(parseInt(e.data, 10) || 0); + refreshActivity(); }); } syncUnread(); + // The live activity: the profile corner (heat ring, chips, waiting list) and the live strip after + // the path bar. The server's activity JSON (GET /-/activity) is the source. A `changed` event of + // its stream, and every `unread` event above, fetches it again and redraws whatever is on the page. + // Nothing changes before the JSON says so. The stream stays open across swaps while a strip is + // shown, as the unread one does. A finished run leaves the strip when the server's window ends, so + // while any is listed the JSON is fetched again every 30 s. + var activityStream = null; + var activitySeq = 0; // a fetch's number: only the newest answer is drawn + var activityTimer = null; // the next refetch while finished runs are listed + var SVG_NS = 'http://www.w3.org/2000/svg'; + // The icons the server draws in the chips, as [element, attributes] pairs. + var CHIP_ICONS = { + review: [['path', { d: 'M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z' }], ['circle', { cx: '12', cy: '12', r: '3' }]], + mention: [['circle', { cx: '12', cy: '12', r: '4' }], ['path', { d: 'M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-3.92 7.94' }]], + failing: [['path', { d: 'M6 6l12 12M18 6 6 18' }]] + }; + + // An icon element built from CHIP_ICONS, the same markup the server writes. + function chipIcon(kind) { + var svg = document.createElementNS(SVG_NS, 'svg'); + svg.setAttribute('class', 'ico'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('aria-hidden', 'true'); + CHIP_ICONS[kind].forEach(function (part) { + var el = document.createElementNS(SVG_NS, part[0]); + Object.keys(part[1]).forEach(function (k) { el.setAttribute(k, part[1][k]); }); + svg.appendChild(el); + }); + return svg; + } + + // A link target from the server, used only when it is a path on this site. + function localHref(href) { + return typeof href === 'string' && href.charAt(0) === '/' && href.charAt(1) !== '/' ? href : ''; + } + + // The live strip: running pills first, then finished ones, two at most and a "+N" for the rest. + // The words "passed" and "failed" come from the strip's own data attributes. + function drawStrip(strip, json) { + var pills = []; + (json.running || []).forEach(function (run) { + pills.push({ cls: 'pill hot', run: run, text: run.job ? ' ' + run.job : '' }); + }); + (json.finished || []).forEach(function (run) { + var word = run.ok ? strip.getAttribute('data-passed') : strip.getAttribute('data-failed'); + pills.push({ cls: run.ok ? 'pill ok' : 'pill bad', run: run, text: ' ' + (word || '') }); + }); + var more = pills.length - 2; + strip.textContent = ''; + pills.slice(0, 2).forEach(function (pill) { + var a = document.createElement('a'); + a.className = pill.cls; + a.setAttribute('href', localHref(pill.run.href)); + var dot = document.createElement('span'); + dot.className = 'pill-dot'; + var b = document.createElement('b'); + b.textContent = String(pill.run.label || ''); + a.appendChild(dot); + a.appendChild(b); + a.appendChild(document.createTextNode(pill.text)); + strip.appendChild(a); + }); + if (more > 0) { + var rest = document.createElement('span'); + rest.className = 'pill more'; + rest.textContent = '+' + more; + strip.appendChild(rest); + } + } + + // The heat ring: lit while a run is going, filled to the newest run's share of its jobs (at least 8%). + function drawRing(ring, running) { + if (!running.length) { + ring.classList.remove('hot'); + ring.setAttribute('data-p', '0'); + return; + } + var run = running[0]; + var p = run.total ? Math.round(run.done / run.total * 100) : 0; + p = Math.min(100, Math.max(8, p)); + ring.classList.add('hot'); + // In steps of 5, as the server renders it; the stylesheet maps each step to --p. + ring.setAttribute('data-p', String(Math.round(p / 5) * 5)); + } + + // The chips: one per non-zero count. The titles come from the chip box's templates, with `{n}` + // standing for the count; the singular template is used for one. + function drawChips(box, json) { + var chips = [ + { kind: 'review', cls: 'chip chip-review', n: json.reviews, tpl: 'data-review' }, + { kind: 'mention', cls: 'chip chip-mention', n: json.mentions, tpl: 'data-mention' }, + { kind: 'failing', cls: 'chip chip-failing', n: json.failing, tpl: 'data-failing' } + ]; + box.textContent = ''; + chips.forEach(function (c) { + var n = Number(c.n) || 0; + if (n <= 0) { return; } + var tpl = box.getAttribute(c.tpl + (n === 1 ? '-one' : '')) || ''; + var chip = document.createElement('span'); + chip.className = c.cls; + chip.setAttribute('title', tpl.split('{n}').join(String(n))); + chip.appendChild(chipIcon(c.kind)); + chip.appendChild(document.createTextNode(String(n))); + box.appendChild(chip); + }); + } + + // The waiting list and its caption: built from the server's items, and removed when there are none. + // They sit before the menu's first link (All notifications). + function drawWaiting(menu, waiting) { + var cap = menu.querySelector('.corner-cap'); + var list = menu.querySelector('.corner-waiting'); + if (!waiting.length) { + if (cap) { cap.remove(); } + if (list) { list.remove(); } + return; + } + var anchor = menu.querySelector('.corner-link'); + if (!cap) { + cap = document.createElement('p'); + cap.className = 'corner-cap'; + cap.textContent = menu.getAttribute('data-cap') || ''; + menu.insertBefore(cap, anchor); + } + if (!list) { + list = document.createElement('ul'); + list.className = 'corner-waiting'; + menu.insertBefore(list, anchor); + } + list.textContent = ''; + waiting.forEach(function (item) { + var li = document.createElement('li'); + var a = document.createElement('a'); + a.setAttribute('href', localHref(item.href)); + var dot = document.createElement('span'); + dot.className = 'corner-dot ' + (item.kind === 'review' ? 'review' : 'mention'); + var text = document.createElement('span'); + text.className = 'corner-item'; + var title = document.createElement('span'); + title.textContent = String(item.title || ''); + var where = document.createElement('small'); + where.textContent = String(item.where || ''); + text.appendChild(title); + text.appendChild(where); + a.appendChild(dot); + a.appendChild(text); + li.appendChild(a); + list.appendChild(li); + }); + } + + // Redraws every strip, ring, chip box and waiting menu on the page from one activity JSON. The + // elements are looked up here each time, since a swap may have replaced them. + function drawActivity(json) { + var strips = document.querySelectorAll('.live-strip[data-activity]'); + for (var i = 0; i < strips.length; i++) { drawStrip(strips[i], json); } + var running = json.running || []; + var rings = document.querySelectorAll('.heat-ring'); + for (var r = 0; r < rings.length; r++) { drawRing(rings[r], running); } + var boxes = document.querySelectorAll('.corner-chips'); + for (var b = 0; b < boxes.length; b++) { drawChips(boxes[b], json); } + var menus = document.querySelectorAll('.corner-menu'); + for (var m = 0; m < menus.length; m++) { drawWaiting(menus[m], json.waiting || []); } + // Finished runs leave the strip when the server's window ends, so the JSON is asked for again. + clearTimeout(activityTimer); + activityTimer = null; + if (json.finished && json.finished.length) { activityTimer = setTimeout(refreshActivity, 30000); } + } + + // Fetches the activity JSON and draws it. Only the newest answer is drawn. A failed fetch leaves + // the page as it is. + function refreshActivity() { + if (!document.querySelector('.live-strip[data-activity]')) { return; } + var seq = ++activitySeq; + fetch('/-/activity', { headers: { accept: 'application/json' }, credentials: 'same-origin' }).then(function (r) { + if (!r.ok) { throw new Error('status ' + r.status); } + return r.json(); + }).then(function (json) { + if (seq === activitySeq) { drawActivity(json); } + }).catch(function () { }); + } + + // One EventSource serves the page's strip and stays open across swaps. It is opened only while a + // strip is shown and closed when it is gone. + function syncActivity() { + if (!document.querySelector('.live-strip[data-activity]')) { + if (activityStream) { activityStream.close(); activityStream = null; } + return; + } + if (activityStream || !window.EventSource) { return; } + activityStream = new EventSource('/-/activity/stream'); + activityStream.addEventListener('changed', function () { refreshActivity(); }); + } + + syncActivity(); + // 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 @@ -2507,8 +2714,10 @@ var PALETTE_TTL = 60000; // ms a fetched list stays fresh var PALETTE_MAX = 50; // options shown at once 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. var pal = { dlg: null, input: null, list: null, note: null, hits: [], sel: 0, str: null, - data: null, request: null, failed: false }; + data: null, request: null, failed: false, files: null, filesSrc: '', filesBusy: null }; // 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. @@ -2521,7 +2730,8 @@ empty: word('empty'), loading: word('loading'), failed: word('failed'), - heads: { repo: word('repos'), org: word('orgs'), page: word('pages') } + search: word('search-label'), + heads: { repo: word('repos'), org: word('orgs'), page: word('pages'), file: word('files') } }; } @@ -2564,6 +2774,42 @@ return pal.data ? items.concat(pal.data.items) : items; } + // The current repo's files, offered once the query starts with its "owner/repo/". The list is the + // file finder's own (the same fetch and cache), read on first need. Nothing is fetched before then. + function paletteFiles(q) { + var dlg = document.querySelector('dialog[data-finder]'); + if (!dlg || !window.__forgeFinder) { return []; } + var src = dlg.getAttribute('data-src') || ''; + var parts = src.split('/'); + if (parts.length < 3 || !parts[1] || !parts[2]) { return []; } + var repo = parts[1] + '/' + parts[2]; + if (q.indexOf(repo.toLowerCase() + '/') !== 0) { return []; } + if (pal.filesSrc !== src) { pal.filesSrc = src; pal.files = null; } + if (!pal.files && pal.filesBusy !== src) { + pal.filesBusy = src; + var sync = true; + window.__forgeFinder.list(dlg, function (data) { + if (pal.filesSrc !== src) { return; } + pal.filesBusy = null; + if (!data) { return; } + pal.files = data.paths.map(function (path) { + return { label: repo + '/' + path, href: window.__forgeFinder.href(dlg, path), kind: 'file' }; + }); + if (!sync && pal.dlg.open) { renderPalette(); } + }); + sync = false; + } + return pal.files || []; + } + + // The text a completed item leaves in the input: a tab's label is its repo, and a repo gets a "/". + function paletteCompletion(item) { + var label = item.label; + var at = label.indexOf(' \u00b7 '); + if (at >= 0) { label = label.slice(0, at); } + return label + (item.kind === 'repo' ? '/' : ''); + } + function paletteSelect(index) { var opts = pal.list.querySelectorAll('li[role="option"]'); if (!opts.length) { pal.input.removeAttribute('aria-activedescendant'); return; } @@ -2578,11 +2824,14 @@ // Filters and draws the list. Groups keep the order of their best match, so a page named exactly // like the query leads; with no query, the order is tabs, repos, orgs, then pages. function renderPalette() { - var q = pal.input.value.trim().toLowerCase(); + var raw = pal.input.value.trim(); + 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; var scored = []; - paletteItems().forEach(function (item, idx) { + paletteItems().concat(paletteFiles(q)).forEach(function (item, idx) { if (!Object.prototype.hasOwnProperty.call(pal.str.heads, item.kind)) { return; } - var s = paletteScore(q, item.label); + var s = pathMode ? (item.label.toLowerCase().indexOf(q) === 0 ? 3 : 0) : paletteScore(q, item.label); 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; }); @@ -2593,14 +2842,21 @@ if (!groups[kind]) { groups[kind] = []; kinds.push(kind); } groups[kind].push(h.item); }); + // A plain query (no "/") ends with a search option, under no heading. + if (raw && !pathMode) { + kinds.push('search'); + groups.search = [{ label: pal.str.search + ' \u201c' + raw + '\u201d', href: '/explore?q=' + encodeURIComponent(raw), kind: 'search' }]; + } pal.list.textContent = ''; pal.hits = []; kinds.forEach(function (kind) { - var head = document.createElement('li'); - head.className = 'palette-head'; - head.setAttribute('role', 'presentation'); - head.textContent = pal.str.heads[kind]; - pal.list.appendChild(head); + if (kind !== 'search') { + var head = document.createElement('li'); + head.className = 'palette-head'; + head.setAttribute('role', 'presentation'); + head.textContent = pal.str.heads[kind]; + pal.list.appendChild(head); + } groups[kind].forEach(function (item) { var n = pal.hits.length; pal.hits.push(item); @@ -2672,6 +2928,18 @@ 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); } } + // 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(); } + } + else if (e.key === 'Backspace' && (e.ctrlKey || e.altKey)) { + e.preventDefault(); + // Like a shell: "owner/repo/" goes back to "owner/", and "owner/repo/RE" to "owner/repo/". + pal.input.value = pal.input.value.replace(/\/+$/, '').replace(/[^\/]*$/, ''); + renderPalette(); + } }); // Hover selects; the check keeps a row that is already selected from being touched again. pal.list.addEventListener('mousemove', function (e) { @@ -2698,14 +2966,38 @@ dlg.setAttribute('aria-label', pal.str.label); pal.input.placeholder = pal.str.placeholder; pal.input.setAttribute('aria-label', pal.str.placeholder); + // Over the path bar when there is one: the dialog's top and left edges sit at the bar's, and it is + // at least 360px wide (never wider than the viewport). + var bar = document.querySelector('.pathbar'); + if (bar) { anchorPalette(dlg, bar.getBoundingClientRect()); } else { unanchorPalette(dlg); } if (typeof dlg.showModal !== 'function') { return; } dlg.showModal(); - pal.input.value = ''; + // 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.input.value = prefill; renderPalette(); pal.input.focus(); + pal.input.setSelectionRange(prefill.length, prefill.length); paletteFetch(); } + function anchorPalette(dlg, rect) { + var width = Math.min(Math.max(360, rect.width), window.innerWidth - 16); + var left = Math.max(8, Math.min(rect.left, window.innerWidth - width - 8)); + dlg.classList.add('anchored'); + dlg.style.top = Math.round(rect.bottom + 4) + 'px'; + dlg.style.left = Math.round(left) + 'px'; + dlg.style.width = Math.round(width) + 'px'; + } + + function unanchorPalette(dlg) { + dlg.classList.remove('anchored'); + dlg.style.top = ''; + dlg.style.left = ''; + dlg.style.width = ''; + } + // Ctrl+K and Cmd+K toggle the palette even while a text field has focus, since that is when a // jump is most likely. Other modifiers keep their own meaning. document.addEventListener('keydown', function (e) { @@ -2721,6 +3013,17 @@ 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. + 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; } + e.preventDefault(); + openPalette(); + }); + // Every relative time shows its exact moment on hover, in the reader's own time zone and language, // so one format holds across the site whatever title the server wrote. var relFormat = null, relLang = null; @@ -2957,20 +3260,36 @@ dlg.showModal(); els.input.value = ''; els.input.focus(); - var src = dlg.getAttribute('data-src'); - if (finderLists[src]) { renderFinder(dlg); return; } + if (finderLists[dlg.getAttribute('data-src')]) { renderFinder(dlg); return; } els.note.textContent = dlg.getAttribute('data-loading'); + loadFinderList(dlg, function (data) { + if (!dlg.isConnected) { return; } + if (data) { renderFinder(dlg); } else { els.note.textContent = dlg.getAttribute('data-failed'); } + }); + } + + // The dialog's file list, fetched once per source URL and kept. `done` gets the list, or null when + // the fetch fails. A list already held is passed on at once. The command palette reads it here too. + function loadFinderList(dlg, done) { + var src = dlg.getAttribute('data-src'); + if (finderLists[src]) { done(finderLists[src]); return; } fetch(src, { headers: { accept: 'application/json' }, credentials: 'same-origin' }).then(function (r) { if (!r.ok) { throw new Error('status ' + r.status); } return r.json(); }).then(function (json) { finderLists[src] = { paths: json.paths || [], truncated: !!json.truncated }; - if (dlg.isConnected) { renderFinder(dlg); } + done(finderLists[src]); }).catch(function () { - if (dlg.isConnected) { els.note.textContent = dlg.getAttribute('data-failed'); } + done(null); }); } + // For the command palette: the file list of a finder dialog, and the link to one of its files. + window.__forgeFinder = { + list: loadFinderList, + href: function (dlg, path) { return fileHref(dlg, path); } + }; + document.addEventListener('click', function (e) { var t = e.target; if (!t || !t.closest) { return; } diff --git a/crates/forge-web/src/ci/live.rs b/crates/forge-web/src/ci/live.rs index 83a0ab6..2f918db 100644 --- a/crates/forge-web/src/ci/live.rs +++ b/crates/forge-web/src/ci/live.rs @@ -15,6 +15,10 @@ use tokio::sync::watch; /// The one key of the runners signal: the admin pages follow all runners together. const RUNNERS_KEY: &str = "runners"; +/// The one key of the any-run signal: a page that lists runs of many repos follows them together. +/// It lives in the runs map, next to the per-run keys, which are run ids and never equal this. +const RUNS_ANY_KEY: &str = "*runs"; + /// The change counters of CI jobs and runs, each keyed by its id. #[derive(Default)] pub struct CiLive { @@ -82,6 +86,12 @@ impl CiLive { self.runs.subscribe(run_id) } + /// Subscribes to changes of any run of any repo: a run was created or changed state, or one of + /// its jobs did. Same rules as [`CiLive::subscribe_job`]. + pub fn subscribe_any_run(&self) -> watch::Receiver { + self.runs.subscribe(RUNS_ANY_KEY) + } + /// Subscribes to changes of repo `repo_id`: a run of the repo was created or changed state. /// Same rules as [`CiLive::subscribe_job`]. pub fn subscribe_repo(&self, repo_id: &str) -> watch::Receiver { @@ -108,12 +118,14 @@ impl CiLive { /// Wakes the subscribers of run `run_id`: one of its jobs or its own status changed. pub fn bump_run(&self, run_id: &str) { self.runs.bump(run_id); + self.runs.bump(RUNS_ANY_KEY); } /// Wakes the subscribers of repo `repo_id`: a run of the repo was created or changed state. /// Callers bump it next to the run bump, since the run signal does not know its repo. pub fn bump_repo(&self, repo_id: &str) { self.repos.bump(repo_id); + self.runs.bump(RUNS_ANY_KEY); } /// Wakes the subscribers of job `job_id` once more and drops its signal. Call it when the job diff --git a/crates/forge-web/src/i18n/browse.rs b/crates/forge-web/src/i18n/browse.rs index 6710081..73665b6 100644 --- a/crates/forge-web/src/i18n/browse.rs +++ b/crates/forge-web/src/i18n/browse.rs @@ -60,6 +60,7 @@ strings! { PaletteNoMatches => "No matches", "Eşleşme yok"; PaletteLoading => "Loading…", "Yükleniyor…"; PaletteFailed => "The list could not be loaded.", "Liste yüklenemedi."; + PaletteFiles => "Files", "Dosyalar"; BranchAuthorHeader => "Author", "Yazar"; BranchAheadBehindHeader => "Ahead / behind", "Önde / geride"; diff --git a/crates/forge-web/src/i18n/misc.rs b/crates/forge-web/src/i18n/misc.rs index 8335984..da1b128 100644 --- a/crates/forge-web/src/i18n/misc.rs +++ b/crates/forge-web/src/i18n/misc.rs @@ -171,6 +171,12 @@ pub enum K { // Top-bar user menu: the viewer's public profile and the settings editor. YourProfile, EditProfile, + // Profile corner, live strip and path bar search. + WaitingOnYou, + AllNotifications, + Passed, + Failed, + SearchPublicReposFor, } /// Every variant, for the coverage test below. @@ -320,6 +326,11 @@ const ALL: &[K] = &[ K::RefLabel, K::YourProfile, K::EditProfile, + K::WaitingOnYou, + K::AllNotifications, + K::Passed, + K::Failed, + K::SearchPublicReposFor, ]; pub fn t(lang: Lang, key: K) -> &'static str { @@ -640,6 +651,16 @@ pub fn t(lang: Lang, key: K) -> &'static str { (YourProfile, Tr) => "Profilin", (EditProfile, En) => "Edit profile", (EditProfile, Tr) => "Profili düzenle", + (WaitingOnYou, En) => "Waiting on you", + (WaitingOnYou, Tr) => "Seni bekleyenler", + (AllNotifications, En) => "All notifications", + (AllNotifications, Tr) => "Tüm bildirimler", + (Passed, En) => "passed", + (Passed, Tr) => "geçti", + (Failed, En) => "failed", + (Failed, Tr) => "başarısız", + (SearchPublicReposFor, En) => "Search public repositories for", + (SearchPublicReposFor, Tr) => "Herkese açık depolarda ara:", } } @@ -668,6 +689,30 @@ pub fn streak_days(lang: Lang, n: u64) -> String { } } +/// `2 review requests` / `1 review request`, and `2 inceleme isteği` in Turkish. +pub fn review_requests_count(lang: Lang, n: u64) -> String { + match lang { + Lang::En => format!("{n} review request{}", if n == 1 { "" } else { "s" }), + Lang::Tr => format!("{n} inceleme isteği"), + } +} + +/// `2 mentions` / `1 mention`, and `2 anılma` in Turkish. +pub fn mentions_count(lang: Lang, n: u64) -> String { + match lang { + Lang::En => format!("{n} mention{}", if n == 1 { "" } else { "s" }), + Lang::Tr => format!("{n} anılma"), + } +} + +/// `2 failing runs` / `1 failing run`, and `2 başarısız çalıştırma` in Turkish. +pub fn failing_runs_count(lang: Lang, n: u64) -> String { + match lang { + Lang::En => format!("{n} failing run{}", if n == 1 { "" } else { "s" }), + Lang::Tr => format!("{n} başarısız çalıştırma"), + } +} + /// `1 contribution` / `3 contributions`, and `3 katkı` in Turkish. pub fn contributions_count(lang: Lang, n: u64) -> String { match lang { diff --git a/crates/forge-web/src/pages/activity.rs b/crates/forge-web/src/pages/activity.rs new file mode 100644 index 0000000..929e81b --- /dev/null +++ b/crates/forge-web/src/pages/activity.rs @@ -0,0 +1,182 @@ +//! The profile corner's live data: `GET /-/activity` returns the signed-in viewer's inbox counts, the +//! reviews and mentions waiting on them, and the state of their own CI runs. `GET /-/activity/stream` +//! sends a `changed` event with that JSON whenever a CI run changes and the JSON differs from the +//! last one sent. Anonymous requests get a bare 401. + +use forge_core::ci::RunState; +use forge_core::store::shell_activity::ActorRun; +use forge_core::{Reason, User}; +use http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; +use serde_json::{Value, json}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::response::Response; +use topcoat::router::{Body, HeaderValue, StatusCode, route}; + +use crate::auth::current_user; +use crate::pages::ci_runs::{changed_stream, events_response, run_href}; +use crate::state::AppState; +use crate::views::repo_href; + +/// How far back a finished run still counts as recent in the activity JSON, in seconds. +const RECENT_SECS: i64 = 120; + +/// How many waiting items the activity JSON lists. +const WAITING_LIMIT: u64 = 5; + +/// One CI run as the activity JSON lists it: label, link, running job, job counts and start time. +fn run_json(run: &ActorRun) -> Value { + let title = format!("{}/{}", run.owner, run.repo); + json!({ + "label": format!("{title} #{}", run.number), + "href": run_href(&title, run.number), + "job": run.current_job, + "done": run.jobs_done, + "total": run.jobs_total, + "started": run.created_at, + }) +} + +/// The viewer's activity as JSON. `reviews` and `mentions` count unread inbox rows, `failing` counts +/// refs whose newest run failed, `running` and `finished` list the viewer's CI runs and `waiting` +/// lists the newest review requests and mentions. Reads only; the caller decides how to send it. +pub(crate) async fn activity_json(state: &AppState, user: &User) -> Result { + let kinds = state.store.inbox_kind_counts(&user.id).await?; + let runs = state.store.actor_runs(&user.id, RECENT_SECS).await?; + let waiting = state.store.waiting_on(&user.id, WAITING_LIMIT).await?; + + let running: Vec = runs.running.iter().map(run_json).collect(); + let finished: Vec = runs + .finished + .iter() + .map(|run| { + let mut item = run_json(run); + item["ok"] = json!(matches!(run.state, RunState::Success)); + item + }) + .collect(); + let waiting: Vec = waiting + .iter() + .map(|item| { + let kind = if matches!(item.reason, Reason::ReviewRequested) { + "review" + } else { + "mention" + }; + let section = if item.is_pull { "pulls" } else { "issues" }; + json!({ + "kind": kind, + "title": item.title, + "where": format!("{}/{}#{}", item.owner, item.repo, item.number), + "href": repo_href(&item.owner, &item.repo, section, &item.number.to_string()), + }) + }) + .collect(); + + Ok(json!({ + "reviews": kinds.reviews, + "mentions": kinds.mentions, + "failing": runs.failing, + "running": running, + "finished": finished, + "waiting": waiting, + })) +} + +/// `GET /-/activity`: the viewer's activity as JSON. Anonymous visitors get 401. +#[route(GET "/-/activity")] +async fn activity(cx: &Cx) -> Result { + let Some((user, _)) = current_user(cx).await? else { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(res); + }; + let state = app_context::(cx); + let body = activity_json(state, &user).await?; + let mut response = Response::new(Body::from(body.to_string().into_bytes())); + let headers = response.headers_mut(); + headers.insert( + CONTENT_TYPE, + HeaderValue::from_static("application/json; charset=utf-8"), + ); + headers.insert(CACHE_CONTROL, HeaderValue::from_static("private, no-cache")); + headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); + Ok(response) +} + +/// `GET /-/activity/stream`: a `changed` event with the viewer's activity JSON now, then one after +/// each CI run change that alters it. The viewer comes from the session only. Anonymous visitors +/// get a bare 401, as the notifications stream does. +#[route(GET "/-/activity/stream")] +async fn activity_stream(cx: &Cx) -> Result { + let Some((user, _)) = current_user(cx).await? else { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(res); + }; + let state = app_context::(cx).clone(); + // Subscribed before the first read, so a run change in between is sent. + let wake = state.ci_live.subscribe_any_run(); + let events = changed_stream(wake, true, move || { + let state = state.clone(); + let user = user.clone(); + async move { + // The JSON is the fingerprint: an event is sent only when the viewer's state changed. + let body = activity_json(&state, &user).await?.to_string(); + Ok(Some((body, false))) + } + }); + events_response(cx, events) +} + +#[cfg(test)] +mod tests { + use topcoat::router::request::Request; + use topcoat::router::{Body, to_bytes}; + + use crate::auth::SESSION_COOKIE; + + #[tokio::test] + async fn activity_gives_the_viewers_json_and_401_to_anonymous() { + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + let store = state.store.clone(); + let router = crate::test_support::app_router(state); + let user = store + .create_user("tahinli", None, "x", false) + .await + .expect("user"); + + let anon = router + .handle( + Request::builder() + .method("GET") + .uri("/-/activity") + .body(Body::empty()) + .expect("request"), + ) + .await; + assert_eq!(anon.status().as_u16(), 401); + + crate::test_support::create_session(&store, &user.id, "tok", "csrf").await; + let res = router + .handle( + Request::builder() + .method("GET") + .uri("/-/activity") + .header("cookie", format!("__Host-{SESSION_COOKIE}=tok")) + .body(Body::empty()) + .expect("request"), + ) + .await; + assert_eq!(res.status().as_u16(), 200); + let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); + let json: serde_json::Value = serde_json::from_slice(&bytes).expect("json"); + for key in [ + "reviews", "mentions", "failing", "running", "finished", "waiting", + ] { + assert!(json.get(key).is_some(), "missing {key}"); + } + assert_eq!(json["running"], serde_json::json!([])); + } +} diff --git a/crates/forge-web/src/pages/ci_tests.rs b/crates/forge-web/src/pages/ci_tests.rs index 6ada390..4016110 100644 --- a/crates/forge-web/src/pages/ci_tests.rs +++ b/crates/forge-web/src/pages/ci_tests.rs @@ -300,7 +300,9 @@ async fn run_list_pages_and_its_live_marker() { } let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await; let text = first.text(); - assert_eq!(text.matches("href=\"/tahinli/proj/ci/runs/").count(), 25); + // The topbar's live strip links the viewer's own running runs too; only the list counts. + let list = text.split_once("").map_or(text.as_str(), |(_, rest)| rest); + assert_eq!(list.matches("href=\"/tahinli/proj/ci/runs/").count(), 25); assert!(text.contains("?page=2"), "older link"); assert!(!text.contains(">Newer<")); let second = get( @@ -310,7 +312,8 @@ async fn run_list_pages_and_its_live_marker() { ) .await; let text = second.text(); - assert_eq!(text.matches("href=\"/tahinli/proj/ci/runs/").count(), 5); + let list = text.split_once("").map_or(text.as_str(), |(_, rest)| rest); + assert_eq!(list.matches("href=\"/tahinli/proj/ci/runs/").count(), 5); assert!(text.contains(">Newer<"), "newer link"); assert!(!text.contains("?page=3"), "no older link on the last page"); let bogus = get( @@ -320,13 +323,9 @@ async fn run_list_pages_and_its_live_marker() { ) .await; assert_eq!(bogus.status, 200); - assert_eq!( - bogus - .text() - .matches("href=\"/tahinli/proj/ci/runs/") - .count(), - 25 - ); + let text = bogus.text(); + let list = text.split_once("").map_or(text.as_str(), |(_, rest)| rest); + assert_eq!(list.matches("href=\"/tahinli/proj/ci/runs/").count(), 25); } { diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 5776848..4d0a1cb 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -2,6 +2,7 @@ #[cfg(test)] mod account_tools_tests; +pub mod activity; pub mod admin_backups; pub mod admin_health; #[cfg(test)] diff --git a/crates/forge-web/src/pages/notifications.rs b/crates/forge-web/src/pages/notifications.rs index d84beca..dd223c4 100644 --- a/crates/forge-web/src/pages/notifications.rs +++ b/crates/forge-web/src/pages/notifications.rs @@ -1406,18 +1406,18 @@ mod tests { } #[tokio::test] - async fn header_bell_shows_the_unread_count() { + async fn sidebar_shows_the_unread_count() { let site = site().await; let w = world(&site, Visibility::Public).await; let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await; let none = get(&site, "/", Some(&cookie)).await; assert!(none.body.contains("href=\"/notifications\"")); - assert!(!none.body.contains("bell-count")); + assert!(!none.body.contains("")); notify(&site, &w, Reason::Mention).await; let one = get(&site, "/", Some(&cookie)).await; - assert!(one.body.contains("1")); + assert!(one.body.contains("1")); } #[tokio::test] diff --git a/crates/forge-web/src/pages/settings_profile.rs b/crates/forge-web/src/pages/settings_profile.rs index 9e3fefe..0276d02 100644 --- a/crates/forge-web/src/pages/settings_profile.rs +++ b/crates/forge-web/src/pages/settings_profile.rs @@ -676,7 +676,7 @@ pub(crate) mod tests { let (status, _, body) = send(&fx.router, "GET", "/", true, None).await; assert_eq!(status, 200, "capitalization: nav"); assert!( - body.contains(""), + body.contains(""), "capitalization: nav {body}" ); let (status, _, body) = diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index a6063ba..23ccd54 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -9,8 +9,10 @@ pub mod review_thread; use std::sync::OnceLock; +use forge_core::ci::RunState; use forge_core::store::RepoSort; use forge_core::store::repo_listing::RepoScope; +use forge_core::store::shell_activity::{ActorRuns, InboxKinds}; use forge_core::{Error as CoreError, Session, User}; use hex::encode; use http::header::{ @@ -23,7 +25,7 @@ use topcoat::context::{Cx, try_app_context}; use topcoat::router::request::uri; use topcoat::router::response::{Response, response_headers}; use topcoat::router::{Body, Next, layer}; -use topcoat::view::{Child, Unescaped, View, component, view}; +use topcoat::view::{Child, Unescaped, View, ViewExt, component, view}; use crate::i18n::admin::{self as ad, K as AK}; use crate::i18n::browse as br; @@ -122,10 +124,277 @@ fn side_class(on: bool) -> &'static str { if on { "side-link on" } else { "side-link" } } -/// Page shell: sticky top bar (logo, page title, search, theme, bell and user menu), the signed-in -/// sidebar and `child` as the page content. `viewer` drives the chrome: the sidebar, bell and user -/// menu when signed in, Explore and Log in otherwise. `extra_stylesheet` adds one more stylesheet -/// link to the head (such as a repo's generated label colors). +/// First path segments that are pages of their own, not owners. A `-` prefix is the same. +const TOP_LEVEL_PAGES: &[&str] = &[ + "explore", + "notifications", + "settings", + "admin", + "new", + "snippets", + "login", + "logout", + "register", + "forgot", + "import", + "review-requests", + "setup", + "org", +]; + +/// Decodes `%XX` escapes. A malformed escape is kept as written. +fn percent_decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' + && let Some(hex) = s.get(i + 1..i + 3) + && let Ok(byte) = u8::from_str_radix(hex, 16) + { + out.push(byte); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// The path bar for a request path, as `(label, href)` pairs. The root and the global pages show +/// one segment: the page `title`. A repo path shows the owner, the repo and, for a `tree` or +/// `blob` path, one segment per path part. The last segment never links. Labels are decoded. +fn path_segments(path: &str, title: &str) -> Vec<(String, Option)> { + let parts: Vec = path + .trim_matches('/') + .split('/') + .filter(|part| !part.is_empty()) + .map(percent_decode) + .collect(); + let Some(owner) = parts.first() else { + return vec![(title.to_owned(), None)]; + }; + if owner.starts_with('-') || TOP_LEVEL_PAGES.contains(&owner.as_str()) { + return vec![(title.to_owned(), None)]; + } + let mut segments = vec![(owner.clone(), Some(user_href(owner)))]; + if let Some(repo) = parts.get(1) { + segments.push((repo.clone(), Some(repo_href(owner, repo, "", "")))); + match &parts[2..] { + [kind, git_ref, prefix @ ..] if matches!(kind.as_str(), "tree" | "blob") && !prefix.is_empty() => { + let mut at = git_ref.clone(); + for part in prefix { + at.push('/'); + at.push_str(part); + segments.push((part.clone(), Some(repo_href(owner, repo, "tree", &at)))); + } + } + // The repo's home: the repo name is the last segment already. + [] => {} + _ => segments.push((title.to_owned(), None)), + } + } + if let Some(last) = segments.last_mut() { + last.1 = None; + } + segments +} + +/// One segment of the path bar. +struct PathCrumb { + label: String, + href: Option, + class: &'static str, +} + +/// One pill of the live strip: a CI run of the viewer. +struct LivePill { + class: &'static str, + label: String, + /// The current job's name (with a leading space) or the outcome word; empty when there is none. + text: String, + href: String, +} + +/// The live strip's pills, at most two, and how many runs are left over. Running runs come first, +/// then the finished ones that passed or failed. +fn live_pills(lang: Lang, runs: &ActorRuns) -> (Vec, usize) { + let mut pills = Vec::new(); + for run in &runs.running { + let job = run.current_job.as_deref().unwrap_or(""); + pills.push(LivePill { + class: "pill hot", + label: format!("{} #{}", run.repo, run.number), + text: if job.is_empty() { String::new() } else { format!(" {job}") }, + href: repo_href(&run.owner, &run.repo, "ci", &format!("runs/{}", run.number)), + }); + } + for run in &runs.finished { + let (class, word) = match run.state { + RunState::Success => ("pill ok", mi::t(lang, MK::Passed)), + RunState::Failure | RunState::Error => ("pill bad", mi::t(lang, MK::Failed)), + _ => continue, + }; + pills.push(LivePill { + class, + label: format!("{} #{}", run.repo, run.number), + text: format!(" {word}"), + href: repo_href(&run.owner, &run.repo, "ci", &format!("runs/{}", run.number)), + }); + } + let more = pills.len().saturating_sub(2); + pills.truncate(2); + (pills, more) +} + +/// A count's phrase with its number replaced by `{n}`, for nav.js to fill in again. +fn count_template(phrase: &str, n: u64) -> String { + phrase.replacen(&n.to_string(), "{n}", 1) +} + +/// The heat ring's fill: the share of a run's jobs that are done, at least 8%. +fn heat_percent(done: u64, total: u64) -> u64 { + (done * 100).checked_div(total).map_or(8, |p| p.clamp(8, 100)) +} + +/// The viewer's runs when there is no viewer or no app context: none. +fn no_runs() -> ActorRuns { + ActorRuns { + running: Vec::new(), + finished: Vec::new(), + failing: 0, + } +} + +/// One item of the profile corner's waiting list. +#[derive(Clone)] +struct WaitingRow { + href: String, + title: String, + /// `owner/repo#number`. + repo: String, + /// `corner-dot review` or `corner-dot mention`. + dot_class: &'static str, +} + +/// What the profile corner shows: the viewer, their inbox counts, the newest running run's heat +/// (`None` when nothing runs) and the items waiting on them. +#[derive(Clone)] +struct ProfileCorner { + username: String, + avatar: String, + csrf: String, + back: String, + is_admin: bool, + theme: String, + reviews: u64, + mentions: u64, + failing: u64, + heat: Option, + waiting: Vec, +} + +/// The account corner at the foot of the signed-in sidebar and in the phone menu. It opens upward: +/// the heat ring, the chips, what waits on the viewer, the notifications link, the theme choice, +/// and the profile, settings, admin and log out links. +#[component] +async fn profile_corner(lang: Lang, corner: ProfileCorner) -> Result { + let ring_class = if corner.heat.is_some() { "heat-ring hot" } else { "heat-ring" }; + // The fill in steps of 5 (the stylesheet maps each step to --p): the CSP refuses style attributes. + let ring_step = (corner.heat.unwrap_or(0).min(100) + 2) / 5 * 5; + let review_chip = (corner.reviews > 0).then(|| { + (corner.reviews.to_string(), mi::review_requests_count(lang, corner.reviews)) + }); + let mention_chip = (corner.mentions > 0) + .then(|| (corner.mentions.to_string(), mi::mentions_count(lang, corner.mentions))); + let failing_chip = (corner.failing > 0) + .then(|| (corner.failing.to_string(), mi::failing_runs_count(lang, corner.failing))); + let waiting_label = mi::t(lang, MK::WaitingOnYou); + let all_label = mi::t(lang, MK::AllNotifications); + let theme_label = mi::t(lang, MK::ThemeLabel); + let match_label = mi::t(lang, MK::MatchSystem); + let light_label = mi::t(lang, MK::Light); + let dark_label = mi::t(lang, MK::Dark); + let auto_pressed = if corner.theme == "auto" { "true" } else { "false" }; + let light_pressed = if corner.theme == "light" { "true" } else { "false" }; + let dark_pressed = if corner.theme == "dark" { "true" } else { "false" }; + let has_waiting = !corner.waiting.is_empty(); + // The chips' titles as nav.js rebuilds them: the server's phrase with `{n}` for the count. The + // singular and plural forms are separate, as English puts "request" and "requests" apart. + let review_template = count_template(&mi::review_requests_count(lang, 2), 2); + let review_one = count_template(&mi::review_requests_count(lang, 1), 1); + let mention_template = count_template(&mi::mentions_count(lang, 2), 2); + let mention_one = count_template(&mi::mentions_count(lang, 1), 1); + let failing_template = count_template(&mi::failing_runs_count(lang, 2), 2); + let failing_one = count_template(&mi::failing_runs_count(lang, 1), 1); + let profile_href = user_href(&corner.username); + let profile_label = mi::t(lang, MK::YourProfile); + let settings_label = o::t(lang, OK::Settings); + let admin_label = ad::t(lang, AK::AdminArea); + let logout_label = t(lang, Key::LogOut); + Ok(view! { +
+ + + (corner.username.as_str()) + + if let Some((count, title)) = review_chip { + (count.as_str()) + } + if let Some((count, title)) = mention_chip { + (count.as_str()) + } + if let Some((count, title)) = failing_chip { + (count.as_str()) + } + + +
+ if has_waiting { +

(waiting_label)

+ + } + (all_label) +
+
(theme_label) +
+ + + + + +
+
+ (profile_label) + (settings_label) + if corner.is_admin { + (admin_label) + } +
+ + +
+
+
+ }) +} + +/// Page shell: sticky top bar (logo, path bar and, signed in, the live strip), the signed-in +/// sidebar with its profile corner, and `child` as the page content. `viewer` drives the chrome: +/// the sidebar, the live strip and the profile corner when signed in; search, theme, Explore and +/// Log in otherwise. `extra_stylesheet` adds one more stylesheet link to the head (such as a +/// repo's generated label colors). #[component] pub async fn shell( title: &str, @@ -134,9 +403,9 @@ pub async fn shell( #[default] child: Child<'_>, ) -> Result { let full_title = format!("{title} \u{b7} forge"); - // The bell count and the viewer's freshest repos for the sidebar, with the total: two queries, - // signed-in only. - let (unread, (listed, _)) = match viewer { + // The unread count, the viewer's freshest repos for the sidebar (with the total), the profile + // corner's inbox counts, their CI runs and the items waiting on them. Signed-in only. + let (unread, (listed, _), inbox, runs, waiting) = match viewer { Some((user, _)) => match try_app_context::(__cx) { Some(state) => ( state.store.unread_count(&user.id).await?, @@ -151,10 +420,13 @@ pub async fn shell( SIDE_REPOS, ) .await?, + state.store.inbox_kind_counts(&user.id).await?, + state.store.actor_runs(&user.id, 120).await?, + state.store.waiting_on(&user.id, 5).await?, ), - None => (0, (Vec::new(), 0)), + None => (0, (Vec::new(), 0), InboxKinds::default(), no_runs(), Vec::new()), }, - None => (0, (Vec::new(), 0)), + None => (0, (Vec::new(), 0), InboxKinds::default(), no_runs(), Vec::new()), }; let unread_badge = (unread > 0).then(|| unread.to_string()); let side_repos: Vec = listed @@ -180,14 +452,6 @@ pub async fn shell( .map(|(user, _)| format!("/{}?tab=repositories", enc(&user.username))) .unwrap_or_default(); let signed_in = viewer.is_some(); - let nav = viewer.map(|(user, session)| { - ( - user.username.clone(), - session.csrf_token.clone(), - avatar_url(&user.username, user.avatar_hash.as_deref()), - user.is_admin, - ) - }); // Both kinds of visitor post to `/-/theme`. Signed-in users send their CSRF token and get the // stored preference saved. Anonymous visitors get the cookie. Either way the browser comes // back to the page it was on. @@ -284,11 +548,66 @@ pub async fn shell( let anonymous = viewer.is_none(); let search_label = o::t(lang, OK::SearchPublicRepos); let palette_label = br::t(lang, br::K::PaletteOpen).to_owned(); - let notif_label = t(lang, Key::Notifications); let menu_label = t(lang, Key::SiteMenu); + let toggle_class = if unread > 0 { "icon-btn has-dot" } else { "icon-btn" }; let side_repos_menu = side_repos.clone(); let unread_menu = unread_badge.clone(); let unread_aside = unread_badge.clone(); + // The path bar: one segment per part of the request path, the last one unlinked. + let segments = path_segments(uri(__cx).path(), title); + let path_attr = segments + .iter() + .map(|(label, _)| label.as_str()) + .collect::>() + .join("/"); + let crumbs: Vec = segments + .into_iter() + .enumerate() + .map(|(i, (label, href))| PathCrumb { + class: if i == 0 && href.is_some() { "pathbar-seg owner" } else { "pathbar-seg" }, + label, + href, + }) + .collect(); + let (pills, more) = live_pills(lang, &runs); + let more_label = format!("+{more}"); + let search_for_label = mi::t(lang, MK::SearchPublicReposFor); + // The profile corner, the signed-in sidebar's account menu. The sidebar and the phone menu + // each get their own copy. + let heat = runs.running.first().map(|run| heat_percent(run.jobs_done, run.jobs_total)); + let waiting_rows: Vec = waiting + .iter() + .map(|item| WaitingRow { + href: repo_href( + &item.owner, + &item.repo, + if item.is_pull { "pulls" } else { "issues" }, + &item.number.to_string(), + ), + title: item.title.clone(), + repo: format!("{}/{}#{}", item.owner, item.repo, item.number), + dot_class: if matches!(item.reason, forge_core::notifications::Reason::ReviewRequested) { + "corner-dot review" + } else { + "corner-dot mention" + }, + }) + .collect(); + let corner = viewer.map(|(user, session)| ProfileCorner { + username: user.username.clone(), + avatar: avatar_url(&user.username, user.avatar_hash.as_deref()), + csrf: session.csrf_token.clone(), + back: back.clone().unwrap_or_else(|| "/".to_owned()), + is_admin: user.is_admin, + theme: theme_pref.to_owned(), + reviews: inbox.reviews, + mentions: inbox.mentions, + failing: runs.failing, + heat, + waiting: waiting_rows, + }); + let corner_panel = corner.clone(); + let corner_aside = corner; Ok(view! { @@ -316,7 +635,7 @@ pub async fn shell(
if signed_in { } @@ -332,71 +654,64 @@ pub async fn shell( "forge" - + if signed_in { +
+ for pill in pills.iter() { + (pill.label.as_str())(pill.text.as_str()) } - - - if let Some((username, csrf, avatar_src, is_admin)) = nav { - // The palette's strings ride on its button, so nav.js builds the dialog in the viewer's language. - - - - if let Some(badge) = unread_badge { - (badge.as_str()) + if more > 0 { + (more_label.as_str()) } +
+ } else { + + + - - } else { + + (t(lang, Key::Explore)) (t(lang, Key::LogIn)) } @@ -421,6 +736,9 @@ pub async fn shell( } else { side_nav(lang: lang, current: current, profile_repos_href: profile_repos_href.as_str(), unread: unread_aside, repos: side_repos) } + if let Some(corner) = corner_aside { + profile_corner(lang: lang, corner: corner) + } }
@@ -445,7 +763,9 @@ pub async fn shell( - }) + } + // Boxed: the shell's view is part of every page's view, and inline it overflows the stack of a deep page. + .boxed()) } /// The signed-in global links and the viewer's repos. The sidebar shows it, and so does the phone @@ -1392,6 +1712,30 @@ mod tests { ); } + #[test] + fn path_segments_follow_the_request_path() { + assert_eq!( + path_segments("/tahinli/forge/blob/main/src/main.rs", "main.rs"), + vec![ + ("tahinli".to_owned(), Some("/tahinli".to_owned())), + ("forge".to_owned(), Some("/tahinli/forge".to_owned())), + ("src".to_owned(), Some("/tahinli/forge/tree/main/src".to_owned())), + ("main.rs".to_owned(), None), + ] + ); + assert_eq!( + path_segments("/tahinli/forge", "tahinli/forge"), + vec![ + ("tahinli".to_owned(), Some("/tahinli".to_owned())), + ("forge".to_owned(), None), + ] + ); + assert_eq!( + path_segments("/explore", "Explore"), + vec![("Explore".to_owned(), None)] + ); + } + #[test] fn csp_allows_the_raw_origin_for_images_and_falls_back_otherwise() { let origin = origin_of("https://raw.forge.test:8443/some/path/"); diff --git a/style/_palette.scss b/style/_palette.scss index 474344b..b0ac93c 100644 --- a/style/_palette.scss +++ b/style/_palette.scss @@ -1,44 +1,8 @@ // Command palette (Ctrl+K): a dialog over the page with a search row, one scrolling list grouped by // kind, and a footer note. It follows the branch switcher's command palette look. -// The topbar button that opens it: a search icon and the shortcut, sized like the other top bar links. -.palette-open { - display: inline-flex; - align-items: center; - flex: none; - align-self: center; // buttons default to flex-start, which lifts it off the top bar's centre line - gap: 6px; - height: 36px; - padding: 0 8px; - 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); - } - - kbd { - padding: 0 5px; - font-family: var(--mono); - font-size: 0.6875rem; - line-height: 18px; - color: var(--text-2); - background: var(--surface-2); - border: 1px solid var(--border-strong); - border-radius: var(--radius-sm); - } -} - -// Phones have no keyboard, so the shortcut hint goes and the button is only the icon. -@media (max-width: 600px) { - .palette-open kbd { - display: none; - } -} +// The path bar's edit button (_shell.scss .pathbar-edit) opens it. The dialog is in the top layer, +// so it sits over the page and the path bar without any positioning of its own. dialog.palette { width: min(560px, calc(100vw - 32px)); @@ -68,6 +32,14 @@ dialog.palette { flex: 1 1 auto; } +// Opened from the path bar, the dialog sits under it: fixed, with its top and left set inline by +// nav.js. The auto margins of a modal and its bottom inset are cleared so only those two apply. +.palette.anchored { + margin: 0; + position: fixed; + inset: auto; +} + // The search row is part of the palette, not a field inside it: no box, only the divider below. .palette-search { flex: none; diff --git a/style/_shell.scss b/style/_shell.scss index 9cf20ae..a624f02 100644 --- a/style/_shell.scss +++ b/style/_shell.scss @@ -150,19 +150,216 @@ margin: 0; } -.topbar .bell { +// Path bar: the breadcrumb of the page, and the click target that opens the Ctrl K palette. +// The bar fills the top bar's free space; its edit button covers the rest of it. + +.pathbar { + display: flex; + align-items: center; + flex: 1 1 auto; + min-width: 0; + max-width: 640px; + height: 32px; + box-sizing: border-box; + padding: 0 0 0 4px; + overflow: hidden; + border: 1px solid transparent; + border-radius: var(--radius-sm); + font-family: var(--mono); + font-size: 12.5px; + color: var(--muted); + + &:hover { + border-color: var(--border); + } +} + +.pathbar-segs { + display: flex; + align-items: center; + flex: 0 1 auto; + min-width: 0; + margin: 0; + padding: 0; + overflow: hidden; + list-style: none; + white-space: nowrap; + + li { + display: flex; + align-items: center; + min-width: 0; + + & + li::before { + content: "/"; + flex: none; + padding: 0 6px; + color: var(--border-strong); + } + } +} + +.pathbar-seg { + min-width: 0; + overflow: hidden; + padding: 2px 4px; + border-radius: var(--radius-sm); + color: var(--muted); + text-overflow: ellipsis; + text-decoration: none; + white-space: nowrap; + + &:hover { + color: var(--text); + background: var(--surface-2); + text-decoration: none; + } + + &.owner { + color: var(--accent-ink); + } + + &.last { + color: var(--text); + font-weight: 600; + + &:hover { + background: none; + } + } +} + +.pathbar-edit { + display: flex; + align-items: center; + justify-content: flex-end; + flex: 1 1 0; + height: 100%; + min-width: 0; + margin: 0; + padding: 0 6px; + border: 0; + background: transparent; + color: var(--muted); + font: inherit; + cursor: text; + + kbd { + flex: none; + padding: 0 5px; + font-family: var(--mono); + font-size: 11px; + line-height: 18px; + color: var(--text-2); + background: var(--surface-2); + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + opacity: 0; + } + + &:hover kbd, + &:focus-visible kbd { + opacity: 1; + } +} + +// Live strip: what is running or just finished, at the end of the top bar. + +.live-strip { + display: flex; + align-items: center; + gap: 6px; + flex: none; + min-width: 0; + margin-left: auto; +} + +.pill { + display: inline-flex; + align-items: center; + gap: 6px; + flex: 0 1 auto; + min-width: 0; + height: 26px; + box-sizing: border-box; + padding: 0 10px; + overflow: hidden; + border: 1px solid var(--border); + border-radius: var(--radius-full); + background: var(--surface); color: var(--text-2); + font-size: 12.5px; + white-space: nowrap; + text-decoration: none; + + b { + font-weight: 600; + color: var(--text); + } + + &:hover { + background: var(--surface-2); + text-decoration: none; + } +} + +.pill-dot { + flex: none; + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--muted); } -.topbar .bell-count { +.pill.ok .pill-dot { + background: var(--ok); +} + +.pill.bad .pill-dot { + background: var(--danger); +} + +.pill.hot { + border-color: color-mix(in srgb, var(--heat-3) 45%, var(--border)); + background: linear-gradient( + 90deg, + color-mix(in srgb, var(--heat-3) 18%, var(--surface)), + color-mix(in srgb, var(--heat-3) 6%, var(--surface)) + ); + + .pill-dot { + background: var(--heat-4); + animation: pill-pulse 1.6s ease-out infinite; + } +} + +.pill.more { + color: var(--muted); + border-style: dashed; +} + +@keyframes pill-pulse { + 0% { + box-shadow: 0 0 0 0 var(--heat-glow); + } + + 70%, + 100% { + box-shadow: 0 0 0 6px transparent; + } +} + +// A dot on the menu button when there are unread notifications (the bell's count moved here). +.nav-toggle summary.has-dot::after { + content: ""; position: absolute; - top: -6px; - right: -6px; - min-width: 1.2rem; - padding: 0 0.3rem; + top: 5px; + right: 5px; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--heat-3); box-shadow: 0 0 0 2px var(--bg); - font-size: 0.6875rem; - line-height: 1.2rem; } // The shared button keeps its natural width in columns; in the top bar it sits on the centre line. @@ -338,6 +535,305 @@ } } +// Profile corner: the signed-in user at the bottom of the sidebar. Its menu opens upward. + +.corner { + position: relative; + margin-top: auto; + padding-top: 8px; + border-top: 1px solid var(--border); +} + +.nav-panel .corner { + margin-top: 12px; +} + +// The phone panel scrolls, so a menu opening upward would be cut at its top: it opens in place. +.nav-panel .corner-menu { + position: static; + margin-top: 6px; + box-shadow: none; +} + +.corner-btn { + display: flex; + align-items: center; + gap: 8px; + padding: 8px; + border-radius: var(--radius-md); + color: var(--text); + cursor: pointer; + list-style: none; + + &:hover { + background: var(--surface-2); + } + + &::-webkit-details-marker { + display: none; + } +} + +.corner-name { + min-width: 0; + overflow: hidden; + font-size: 14px; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} + +// The avatar inside a ring: the ring fills with the running run's progress (--p), and glows while hot. +.heat-ring { + display: grid; + flex: none; + place-items: center; + width: 34px; + height: 34px; + border-radius: 50%; + background: conic-gradient( + var(--heat-2) 0%, + var(--heat-3) calc(var(--p, 8%) * 0.6), + var(--heat-4) var(--p, 8%), + var(--border) var(--p, 8%) + ); + + &:not(.hot) { + background: var(--border); + } + + &.hot { + filter: drop-shadow(0 0 5px var(--heat-glow)); + } + + .avatar { + box-sizing: border-box; + width: 28px; + height: 28px; + border: 2px solid var(--bg); + border-radius: 50%; + } +} + +// The fill arrives as data-p in steps of 5: the CSP refuses style attributes. +@for $i from 0 through 20 { + .heat-ring[data-p="#{$i * 5}"] { + --p: #{$i * 5}%; + } +} + +.corner-chips { + display: flex; + align-items: center; + gap: 4px; + margin-left: auto; +} + +// Chips count what waits on the user. They never take the accent. +.chip { + display: inline-flex; + align-items: center; + gap: 3px; + flex: none; + height: 20px; + box-sizing: border-box; + padding: 0 6px; + border: 1px solid var(--border); + border-radius: var(--radius-full); + background: var(--surface-2); + color: var(--text-2); + font-size: 11px; + font-weight: 700; + font-variant-numeric: tabular-nums; + + .ico { + width: 12px; + height: 12px; + } +} + +.chip-review { + color: var(--important); + background: color-mix(in srgb, var(--important) 12%, var(--surface)); + border-color: color-mix(in srgb, var(--important) 35%, transparent); +} + +.chip-mention { + color: var(--info); + background: color-mix(in srgb, var(--info) 12%, var(--surface)); + border-color: color-mix(in srgb, var(--info) 35%, transparent); +} + +.chip-failing { + color: var(--danger); + background: var(--danger-bg); + border-color: color-mix(in srgb, var(--danger) 35%, transparent); +} + +.corner-menu { + position: absolute; + left: 8px; + right: 8px; + bottom: calc(100% + 6px); + z-index: 40; + display: grid; + gap: 2px; + box-sizing: border-box; + padding: 6px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); + box-shadow: var(--shadow); +} + +.corner-cap { + margin: 0; + padding: 6px 10px 2px; + font-size: 11.5px; + font-weight: 600; + color: var(--muted); +} + +.corner-waiting { + display: grid; + gap: 2px; + margin: 0; + padding: 0; + list-style: none; + + a { + display: flex; + align-items: flex-start; + gap: 8px; + padding: 6px 10px; + border-radius: var(--radius-md); + color: var(--text); + text-decoration: none; + + &:hover { + background: var(--surface-2); + text-decoration: none; + } + } +} + +.corner-dot { + flex: none; + width: 7px; + height: 7px; + margin-top: 6px; + border-radius: 50%; + background: var(--muted); + + &.review { + background: var(--important); + } + + &.mention { + background: var(--info); + } +} + +.corner-item { + display: flex; + flex-direction: column; + min-width: 0; + + span { + overflow: hidden; + font-size: 13.5px; + line-height: 1.3; + text-overflow: ellipsis; + white-space: nowrap; + } + + small { + overflow: hidden; + font-family: var(--mono); + font-size: 11.5px; + color: var(--muted); + text-overflow: ellipsis; + white-space: nowrap; + } +} + +// `button.corner-link` too (Log out): the extra element in the selector outweighs `button.link-button`. +.corner-link, +button.corner-link.link-button { + display: block; + width: 100%; + box-sizing: border-box; + margin: 0; + padding: 8px 10px; + border: 0; + border-radius: var(--radius-md); + background: none; + color: var(--text); + font: inherit; + font-size: 14px; + text-align: left; + text-decoration: none; + cursor: pointer; + + &:hover { + background: var(--surface-2); + text-decoration: none; + } +} + +.corner-rule { + width: auto; + margin: 4px 6px; + border: 0; + border-top: 1px solid var(--border); +} + +.corner-theme { + display: flex; + align-items: center; + justify-content: space-between; + padding: 4px 6px 4px 10px; + font-size: 14px; + color: var(--muted); + + span { + color: var(--text-2); + } +} + +.corner-theme-set { + display: flex; + gap: 2px; + margin: 0; + + button { + display: grid; + place-items: center; + width: 28px; + height: 26px; + padding: 0; + border: 0; + border-radius: var(--radius-sm); + background: none; + color: var(--muted); + cursor: pointer; + + &:hover { + color: var(--text); + } + + &[aria-pressed="true"] { + background: var(--surface-2); + color: var(--text); + } + } + + .ico { + width: 16px; + height: 16px; + } +} + // Page column and footer .shell > main { @@ -371,6 +867,24 @@ .top-search { flex: 1 1 0; } + + // Phones: the path bar shows only the last segment, and the live strip goes (its counts are in the menu). + .pathbar-segs li:not(:last-child) { + display: none; + } + + .pathbar-segs li + li::before { + display: none; + } + + // Phones have no keyboard, so the shortcut hint goes. + .pathbar-edit kbd { + display: none; + } + + .live-strip { + display: none; + } } // Narrow phones: the search field no longer fits beside the other top bar items, so it becomes an @@ -413,7 +927,9 @@ position: sticky; top: var(--topbar-h); align-self: start; - display: block; + // A column, so the profile corner sits at its bottom (margin-top: auto). + display: flex; + flex-direction: column; box-sizing: border-box; // Ends at the viewport's bottom while the site banner still shows above it (--shell-top, nav.js). height: calc(100vh - max(var(--topbar-h), var(--shell-top, 0px))); @@ -424,6 +940,27 @@ border-right: 1px solid var(--border); } + // The profile corner stays above a repo page's fixed tabs, which end where it starts: 50px of + // corner, its rule and the sidebar's 24px bottom padding. + .shell-sidebar .corner { + position: relative; + z-index: 6; + } + + .shell:has(> .shell-sidebar .corner) .repo-tabs { + bottom: 76px; + } + + // The sticky sidebar is its own stacking layer, under the fixed tabs, so the open menu would sit + // behind them: while it is open the sidebar rises above the tabs, see-through so they still show. + .shell-sidebar:has(.corner[open]) { + z-index: 6; + } + + .shell:has(.repo-tabs) .shell-sidebar:has(.corner[open]) { + background: transparent; + } + // A repo page: its tabs become the sidebar, fixed under the top bar, and the global links go. .shell:has(.repo-tabs) .shell-sidebar .side-links, .shell:has(.repo-tabs) .shell-sidebar .side-group { @@ -536,4 +1073,8 @@ html[aria-busy="true"] body::before { transform: scaleX(1); opacity: 0.45; } + + .pill.hot .pill-dot { + animation: none; + } } diff --git a/style/main.scss b/style/main.scss index 83150ae..dde0cc0 100644 --- a/style/main.scss +++ b/style/main.scss @@ -85,6 +85,14 @@ --note: #2B6CB0; --tip: #1D7A62; --important: #6A4BB0; + // Heat: the live strip and the profile ring (0 is the empty track, 4 the hottest). Chips never use the accent. + --heat-0: #ECE7E1; + --heat-1: #F6C9A8; + --heat-2: #EE9A60; + --heat-3: #D4652A; + --heat-4: #9C3A10; + --heat-glow: rgba(220, 100, 30, .35); + --info: #2B6CB0; --warning: #9A6200; --shadow: 0 10px 28px rgba(30, 36, 32, .10); // Radius scale: sm chips/badges, md every control (buttons, inputs, selects, textareas), @@ -123,6 +131,13 @@ --note: #8AB4F0; --tip: #7CCBAE; --important: #C4A7FF; + --heat-0: #24211E; + --heat-1: #5A2614; + --heat-2: #9A3A16; + --heat-3: #D9662A; + --heat-4: #FFB066; + --heat-glow: rgba(255, 150, 70, .55); + --info: #8AB4F0; --warning: #E6B765; --shadow: 0 10px 28px rgba(0, 0, 0, .45); color-scheme: dark; @@ -152,6 +167,13 @@ --note: #8AB4F0; --tip: #7CCBAE; --important: #C4A7FF; + --heat-0: #24211E; + --heat-1: #5A2614; + --heat-2: #9A3A16; + --heat-3: #D9662A; + --heat-4: #FFB066; + --heat-glow: rgba(255, 150, 70, .55); + --info: #8AB4F0; --warning: #E6B765; --shadow: 0 10px 28px rgba(0, 0, 0, .45); color-scheme: dark;