From 6e3d1e1258daecc8c53d4740b91aa088491a2966 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 16:28:48 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20perf:=20star=20and=20watch=20answer?= =?UTF-8?q?=20with=20the=20repo=20head's=20parts=20instead=20of=20a=20redi?= =?UTF-8?q?rect=20to=20the=20whole=20page;=20live=20events=20carry=20a=20s?= =?UTF-8?q?equence,=20so=20a=20page=20never=20renders=20twice=20for=20a=20?= =?UTF-8?q?change=20it=20already=20shows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-runner/src/runner.rs | 8 +- .../src/pages/admin_health.rs | 2 + .../src/pages/releases_tests.rs | 9 +- .../src/pages/settings_live.rs | 2 +- crates/forge-web-app/src/ci/live.rs | 2 + crates/forge-web-app/src/layers.rs | 27 +++ crates/forge-web-app/src/live.rs | 88 ++++++++-- crates/forge-web-app/src/mail/live.rs | 1 + .../forge-web-app/src/test_support/fixture.rs | 17 +- crates/forge-web-app/src/test_support/mod.rs | 1 + crates/forge-web-app/src/views/mod.rs | 4 +- crates/forge-web-app/src/views/parts.rs | 24 ++- crates/forge-web-pages/src/pages/code_live.rs | 14 +- .../src/pages/notifications.rs | 15 +- crates/forge-web-pages/src/pages/ref_live.rs | 10 +- crates/forge-web-pages/src/pages/repo.rs | 166 ++++++++++++------ crates/forge-web-pages/src/pages/star.rs | 15 +- crates/forge-web-repo/src/pages/issue_view.rs | 1 + .../src/pages/repo_settings_live_tests.rs | 5 +- crates/forge-web/assets/nav.js | 67 ++++++- crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/routes.snap | 1 + style/_min.scss | 4 + style/_one.scss | 1 + style/_one_shell.scss | 6 +- 25 files changed, 378 insertions(+), 113 deletions(-) diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index 4f9e1ca..d66a28c 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -458,8 +458,12 @@ impl Runner { .map_err(|e| format!("artifacts: {e}"))?; for artifact in &found { patiently(&job.job_id, "artifact upload", || { - self.client - .upload_artifact(&job.job_id, &job.job_token, &artifact.name, &artifact.path) + self.client.upload_artifact( + &job.job_id, + &job.job_token, + &artifact.name, + &artifact.path, + ) }) .await .map_err(|e| format!("artifact {}: {e}", artifact.name))?; diff --git a/crates/forge-web-account/src/pages/admin_health.rs b/crates/forge-web-account/src/pages/admin_health.rs index 77b7cc3..8d81443 100644 --- a/crates/forge-web-account/src/pages/admin_health.rs +++ b/crates/forge-web-account/src/pages/admin_health.rs @@ -460,12 +460,14 @@ async fn health_view( text: needs_attention(lang, attention), href: None, class: "b health-sum bad", + part: None, } } else { SubPart { text: at(lang, A::Fine).to_owned(), href: None, class: "b health-sum ok", + part: None, } }; let sub = vec![summary]; diff --git a/crates/forge-web-account/src/pages/releases_tests.rs b/crates/forge-web-account/src/pages/releases_tests.rs index ff4325b..38952f1 100644 --- a/crates/forge-web-account/src/pages/releases_tests.rs +++ b/crates/forge-web-account/src/pages/releases_tests.rs @@ -11,6 +11,7 @@ use topcoat::router::{Body, HeaderMap, Router, to_bytes}; use crate::auth::SESSION_COOKIE; use crate::blobs::asset_key; use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError}; +use crate::test_support::fixture::seq_free; use crate::test_support::{app_router, create_session, test_state}; const CSRF: &str = "releases-test-csrf"; @@ -980,11 +981,11 @@ async fn live_streams_wake_on_changes_and_hide_drafts() { .await .expect("edited"); assert_eq!( - &list.next().await.expect("a frame").expect("data")[..], + &seq_free(&list.next().await.expect("a frame").expect("data"))[..], CHANGED ); assert_eq!( - &page.next().await.expect("a frame").expect("data")[..], + &seq_free(&page.next().await.expect("a frame").expect("data"))[..], CHANGED ); @@ -1000,13 +1001,13 @@ async fn live_streams_wake_on_changes_and_hide_drafts() { .await; assert_eq!(uploaded.status, 303, "body: {}", uploaded.text()); assert_eq!( - &list.next().await.expect("a frame").expect("data")[..], + &seq_free(&list.next().await.expect("a frame").expect("data"))[..], CHANGED ); let download = fx.download("v1.1/app.tar.gz").await; assert_eq!(download.status, 200); assert_eq!( - &list.next().await.expect("a frame").expect("data")[..], + &seq_free(&list.next().await.expect("a frame").expect("data"))[..], CHANGED ); diff --git a/crates/forge-web-account/src/pages/settings_live.rs b/crates/forge-web-account/src/pages/settings_live.rs index 940ac8f..6fa8ebe 100644 --- a/crates/forge-web-account/src/pages/settings_live.rs +++ b/crates/forge-web-account/src/pages/settings_live.rs @@ -344,7 +344,7 @@ mod tests { live.bump(&Topic::Account(owner.id.clone())); let changed = frames.next().await.expect("a frame").expect("data"); assert_eq!( - &changed[..], + &crate::test_support::fixture::seq_free(&changed)[..], b"event: changed\ndata: 1\n\n", "settings stream: changed event" ); diff --git a/crates/forge-web-app/src/ci/live.rs b/crates/forge-web-app/src/ci/live.rs index cd0871f..d7ce311 100644 --- a/crates/forge-web-app/src/ci/live.rs +++ b/crates/forge-web-app/src/ci/live.rs @@ -114,6 +114,7 @@ impl Signals { } pub fn bump(&self, key: &str) { + crate::live::next_live_seq(); let mut counters = self.counters(); let Some(tx) = counters.get(key) else { return; @@ -125,6 +126,7 @@ impl Signals { } fn close(&self, key: &str) { + crate::live::next_live_seq(); let removed = self.counters().remove(key); if let Some(tx) = removed { tx.send_modify(|generation| *generation = generation.wrapping_add(1)); diff --git a/crates/forge-web-app/src/layers.rs b/crates/forge-web-app/src/layers.rs index 7e81bb1..ef69d7e 100644 --- a/crates/forge-web-app/src/layers.rs +++ b/crates/forge-web-app/src/layers.rs @@ -7,6 +7,7 @@ use topcoat::router::request::{method, uri}; use crate::live::Topic; use crate::state::AppState; +pub use live_seq::LiveSeqLayer; pub use not_found_layer::NotFoundLayer; pub use org_write::OrgWriteLayer; pub use pull_write::PullWriteLayer; @@ -392,6 +393,32 @@ mod repo_settings_write { } } +mod live_seq { + use topcoat::Result; + use topcoat::context::Cx; + use topcoat::router::response::Response; + use topcoat::router::{Body, Layer, LayerFuture, Next, Path}; + + use crate::live::{LiveSeq, live_seq}; + + pub struct LiveSeqLayer; + + impl Layer for LiveSeqLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(record_seq(cx, body, next)) + } + } + + async fn record_seq(cx: &Cx, body: Body, next: Next<'_>) -> Result { + let cx = cx.with(LiveSeq(live_seq())); + next.run(&cx, body).await + } +} + mod not_found_layer { use http::header::ACCEPT; use topcoat::Result; diff --git a/crates/forge-web-app/src/live.rs b/crates/forge-web-app/src/live.rs index 15bf3f7..a99556c 100644 --- a/crates/forge-web-app/src/live.rs +++ b/crates/forge-web-app/src/live.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; use std::future::Future; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; use std::time::Duration; @@ -46,6 +47,27 @@ pub fn admin() -> &'static LiveHub { ADMIN.get_or_init(LiveHub::default) } +fn seq_counter() -> &'static AtomicU64 { + static LIVE_SEQ: OnceLock = OnceLock::new(); + LIVE_SEQ.get_or_init(|| { + let start = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| u64::try_from(d.as_micros()).unwrap_or(u64::MAX / 2)); + AtomicU64::new(start) + }) +} + +pub fn live_seq() -> u64 { + seq_counter().load(Ordering::SeqCst) +} + +pub fn next_live_seq() -> u64 { + seq_counter().fetch_add(1, Ordering::SeqCst) + 1 +} + +#[derive(Clone, Copy, Debug)] +pub struct LiveSeq(pub u64); + #[derive(Default)] pub struct LiveHub { topics: Mutex>>, @@ -66,6 +88,7 @@ impl LiveHub { } pub fn bump(&self, topic: &Topic) { + next_live_seq(); let mut topics = self.topics(); let Some(tx) = topics.get(topic) else { return; @@ -94,18 +117,23 @@ impl LiveHub { } } -struct Follow { +struct Follow { wakes: Vec>, read: F, - last: String, + last: T, + diff: Diff, } -fn wake_event() -> Result { - Ok(Event::new().event("changed").data("1")) +type Diff = fn(&T, &T) -> Option<&'static str>; + +fn named_event(name: &'static str, suffix: &str) -> Result { + Ok(Event::new() + .event(name) + .data(format!("{}{suffix}", live_seq()))) } -fn named_event(name: &'static str) -> Result { - Ok(Event::new().event(name).data("1")) +fn wake_event() -> Result { + named_event("changed", "") } async fn wait_any(wakes: &mut [watch::Receiver]) -> bool { @@ -149,27 +177,59 @@ where F: Fn() -> Fut + Send + 'static, Fut: Future> + Send, { - let events = named_changes(hub, topics.to_vec(), extra, "changed", read).await?; + let diff: Diff = |old, new| (old != new).then_some(""); + let events = named_changes(hub, topics.to_vec(), extra, "changed", read, diff).await?; events_response(cx, events) } -async fn named_changes( +pub async fn stream_changes_split( + cx: &Cx, + hub: &LiveHub, + topics: &[Topic], + extra: Vec>, + read: F, +) -> Result +where + F: Fn() -> Fut + Send + 'static, + Fut: Future> + Send, +{ + let diff: Diff<(String, String)> = |old, new| { + if old.1 != new.1 { + Some("") + } else if old.0 != new.0 { + Some(" head") + } else { + None + } + }; + let events = named_changes(hub, topics.to_vec(), extra, "changed", read, diff).await?; + events_response(cx, events) +} + +async fn named_changes( hub: &LiveHub, topics: Vec, extra: Vec>, name: &'static str, read: F, + diff: Diff, ) -> Result> + Send + 'static> where + T: Send + 'static, F: Fn() -> Fut + Send + 'static, - Fut: Future> + Send, + Fut: Future> + Send, { let mut wakes: Vec> = topics.iter().map(|topic| hub.subscribe(topic)).collect(); wakes.extend(extra); let last = read().await?; Ok(stream::unfold( - Follow { wakes, read, last }, + Follow { + wakes, + read, + last, + diff, + }, move |mut follow| async move { loop { if !wait_any(&mut follow.wakes).await { @@ -182,11 +242,11 @@ where return None; } }; - if now == follow.last { - continue; - } + let suffix = (follow.diff)(&follow.last, &now); follow.last = now; - return Some((named_event(name), follow)); + if let Some(suffix) = suffix { + return Some((named_event(name, suffix), follow)); + } } }, )) diff --git a/crates/forge-web-app/src/mail/live.rs b/crates/forge-web-app/src/mail/live.rs index 263b03f..ce772d3 100644 --- a/crates/forge-web-app/src/mail/live.rs +++ b/crates/forge-web-app/src/mail/live.rs @@ -13,6 +13,7 @@ pub fn subscribe() -> watch::Receiver { } pub fn bump() { + crate::live::next_live_seq(); sender().send_modify(|generation| *generation = generation.wrapping_add(1)); crate::live::admin().bump(&crate::live::Topic::AdminHealth); } diff --git a/crates/forge-web-app/src/test_support/fixture.rs b/crates/forge-web-app/src/test_support/fixture.rs index ec3fc9b..9f886a0 100644 --- a/crates/forge-web-app/src/test_support/fixture.rs +++ b/crates/forge-web-app/src/test_support/fixture.rs @@ -228,7 +228,22 @@ where loop { let bytes = next_frame(frames).await?; if !bytes.starts_with(b"retry: ") { - return Some(bytes); + return Some(seq_free(&bytes)); } } } + +pub fn seq_free(frame: &[u8]) -> Vec { + let text = String::from_utf8_lossy(frame); + let Some(data) = text + .strip_prefix("event: changed\ndata: ") + .and_then(|rest| rest.strip_suffix("\n\n")) + else { + return frame.to_vec(); + }; + let seq = data.strip_suffix(" head").unwrap_or(data); + if seq.is_empty() || !seq.bytes().all(|b| b.is_ascii_digit()) { + return frame.to_vec(); + } + format!("event: changed\ndata: 1{}\n\n", &data[seq.len()..]).into_bytes() +} diff --git a/crates/forge-web-app/src/test_support/mod.rs b/crates/forge-web-app/src/test_support/mod.rs index 8c626e3..3220de4 100644 --- a/crates/forge-web-app/src/test_support/mod.rs +++ b/crates/forge-web-app/src/test_support/mod.rs @@ -103,6 +103,7 @@ pub fn app_router(state: AppState) -> Router { .layer(crate::layers::PullWriteLayer) .layer(crate::layers::OrgWriteLayer) .layer(TowerLayer::new(crate::compression::ResponseCompression)) + .layer(crate::layers::LiveSeqLayer) .with(Compression::disable()) .build() } diff --git a/crates/forge-web-app/src/views/mod.rs b/crates/forge-web-app/src/views/mod.rs index 4fcb40a..4e2d944 100644 --- a/crates/forge-web-app/src/views/mod.rs +++ b/crates/forge-web-app/src/views/mod.rs @@ -41,6 +41,7 @@ use crate::i18n::misc::{self as mi, K as MK}; use crate::i18n::orgs::{self as o, K as OK}; use crate::i18n::s; use crate::i18n::{self, Key, Lang, t}; +use crate::live::LiveSeq; use crate::render::highlight::highlight_css; use crate::state::AppState; use crate::theme::Theme; @@ -613,9 +614,10 @@ pub async fn shell( unread, waiting: inbox.reviews + inbox.mentions + runs.failing > 0, }); + let live_seq = try_context::(cx).map(|seq| seq.0.to_string()); Ok(view! { - + diff --git a/crates/forge-web-app/src/views/parts.rs b/crates/forge-web-app/src/views/parts.rs index 9e6211d..9e30afe 100644 --- a/crates/forge-web-app/src/views/parts.rs +++ b/crates/forge-web-app/src/views/parts.rs @@ -226,9 +226,15 @@ pub struct SubPart { pub text: String, pub href: Option, pub class: &'static str, + pub part: Option<&'static str>, } impl SubPart { + pub fn with_part(mut self, part: &'static str) -> Self { + self.part = Some(part); + self + } + pub fn text(text: impl Into) -> Self { Self { text: text.into(), @@ -261,6 +267,18 @@ impl SubPart { } } +#[component] +pub async fn sub_part(cx: &Cx, part: SubPart) -> Result { + Ok(view! { + if let Some(href) = part.href { + (part.text) + } else { + (part.text) + } + } + .boxed()) +} + #[component] pub async fn head_sub( cx: &Cx, @@ -278,11 +296,7 @@ pub async fn head_sub( if n > 0 { } - if let Some(href) = part.href { - (part.text) - } else { - (part.text) - } + sub_part(part: part) } if has_pips { diff --git a/crates/forge-web-pages/src/pages/code_live.rs b/crates/forge-web-pages/src/pages/code_live.rs index 52cb44f..6fcc919 100644 --- a/crates/forge-web-pages/src/pages/code_live.rs +++ b/crates/forge-web-pages/src/pages/code_live.rs @@ -8,7 +8,7 @@ use topcoat::router::response::Response; use topcoat::router::{path_param, query_params, route}; use crate::auth::percent_encode; -use crate::live::{Topic, stream_changes_with}; +use crate::live::{Topic, stream_changes_split}; use crate::pages::refs::load_refs; use crate::pages::repo_ctx::{fork_count, load_repo}; use crate::pages::repo_side::runs_fingerprint; @@ -148,7 +148,7 @@ async fn repo_events(cx: &Cx) -> Result { }; let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone()); let path = ctx.path.clone(); - stream_changes_with(cx, &state.live.clone(), &topics, extra, move || { + stream_changes_split(cx, &state.live.clone(), &topics, extra, move || { let state = state.clone(); let repo_id = repo_id.clone(); let path = path.clone(); @@ -156,17 +156,17 @@ async fn repo_events(cx: &Cx) -> Result { let viewer = viewer.clone(); async move { let viewer_id = viewer.as_ref().map(|user| user.id.as_str()); - let mut out = header_fingerprint(&state, &repo_id, viewer_id).await?; + let head = header_fingerprint(&state, &repo_id, viewer_id).await?; + let mut rest = String::new(); if !branch.is_empty() { - let refs = refs_fingerprint(path, branch).await?; - out = format!("{out}\n{refs}"); + rest = refs_fingerprint(path, branch).await?; } if home { let extra = home_fingerprint(&state, &repo_id).await?; let runs = runs_fingerprint(&state, &repo_id).await?; - out = format!("{out}\n{extra}\n{runs}"); + rest = format!("{rest}\n{extra}\n{runs}"); } - Ok(out) + Ok((head, rest)) } }) .await diff --git a/crates/forge-web-pages/src/pages/notifications.rs b/crates/forge-web-pages/src/pages/notifications.rs index 165abf0..2a838c1 100644 --- a/crates/forge-web-pages/src/pages/notifications.rs +++ b/crates/forge-web-pages/src/pages/notifications.rs @@ -11,7 +11,7 @@ use topcoat::context::{Cx, context}; use topcoat::router::content::Form; use topcoat::router::content::sse::Event; use topcoat::router::error::{SeeOther, bad_request, not_found, see_other}; -use topcoat::router::response::Response; +use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{Body, StatusCode, page, path_param, query_params, route}; use topcoat::view::{View, component, view}; @@ -23,6 +23,7 @@ use crate::live::events_response; use crate::live::{Topic, stream_changes}; use crate::notify_hub::publish_unread; use crate::pages::issue_parts::parse_number; +use crate::pages::repo::{parts_response, wants_parts}; use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::pages::repo_transfer::transfer_list_for; use crate::pages::star::return_path; @@ -569,7 +570,7 @@ async fn set_subscription(cx: &Cx, pull: bool, form: &SubscriptionForm) -> Resul } #[route(POST "/{owner}/{repo}/watch")] -async fn set_watch(cx: &Cx, Form(form): Form) -> Result { +async fn set_watch(cx: &Cx, Form(form): Form) -> Result { let ctx = load_repo(cx, owner(cx), repo(cx)).await?; let (user, _) = require_csrf(cx, &form.csrf).await?; let level = match form.level.as_str() { @@ -581,12 +582,10 @@ async fn set_watch(cx: &Cx, Form(form): Form) -> Result { let state = context::(cx); state.store.set_watch(&user.id, &ctx.repo.id, level).await?; state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id); - Ok(see_other(repo_href( - &ctx.repo.owner_name, - &ctx.repo.name, - "", - "", - ))) + if wants_parts(cx) { + return parts_response(cx, &ctx).await; + } + see_other(repo_href(&ctx.repo.owner_name, &ctx.repo.name, "", "")).into_response(cx) } pub async fn repo_allows( diff --git a/crates/forge-web-pages/src/pages/ref_live.rs b/crates/forge-web-pages/src/pages/ref_live.rs index 1b6dba3..c606afb 100644 --- a/crates/forge-web-pages/src/pages/ref_live.rs +++ b/crates/forge-web-pages/src/pages/ref_live.rs @@ -78,7 +78,10 @@ mod tests { .expect("woken") .expect("a frame") .expect("data"); - assert_eq!(&first[..], b"event: changed\ndata: 1\n\n"); + assert_eq!( + &crate::test_support::fixture::seq_free(&first)[..], + b"event: changed\ndata: 1\n\n" + ); fx.live.bump(&Topic::CommitStatuses(repo.id.clone())); let second = tokio::time::timeout(Duration::from_secs(5), frames.next()) @@ -86,7 +89,10 @@ mod tests { .expect("woken") .expect("a frame") .expect("data"); - assert_eq!(&second[..], b"event: changed\ndata: 1\n\n"); + assert_eq!( + &crate::test_support::fixture::seq_free(&second)[..], + b"event: changed\ndata: 1\n\n" + ); } #[tokio::test] diff --git a/crates/forge-web-pages/src/pages/repo.rs b/crates/forge-web-pages/src/pages/repo.rs index 16496db..0dd8559 100644 --- a/crates/forge-web-pages/src/pages/repo.rs +++ b/crates/forge-web-pages/src/pages/repo.rs @@ -7,9 +7,12 @@ use forge_core::WatchLevel; use forge_core::time::stamp_ago; use forge_git::browse; use forge_git::repo::repo_path; +use http::{HeaderName, HeaderValue}; use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::router::error::not_found; +use topcoat::router::request::headers; +use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{page, path_param, route}; use topcoat::view::{Child, View, ViewExt, component, view}; @@ -26,7 +29,7 @@ use crate::pages::tree::{ entry_rows, last_commits, latest_bar, load_readme, read_dir, readme_sheet, tree_table, }; use crate::state::AppState; -use crate::views::parts::{SubPart, head_sub}; +use crate::views::parts::{SubPart, head_sub, sub_part}; use crate::views::{ https_clone_url, now_unix, ref_selector, relative_time, repo_href, repo_tabs, shell, ssh_clone_url, stamp_unix, tab_title, @@ -35,6 +38,14 @@ use crate::views::{ path_param!(owner); path_param!(repo); +pub fn watching_part(head: &RepoHead) -> SubPart { + SubPart::text(g::watching_count(head.lang, head.watchers)).with_part("repo-watching") +} + +pub fn forks_part(head: &RepoHead) -> SubPart { + SubPart::text(g::forks_count(head.lang, head.forks)).with_part("repo-forks") +} + #[component] pub async fn repo_head( cx: &Cx, @@ -44,6 +55,9 @@ pub async fn repo_head( #[default] pips: Vec<(String, String, &'static str)>, #[default] child: Child<'_>, ) -> Result { + let actions = head.clone(); + let watching = watching_part(&head); + let forking = forks_part(&head); let RepoHead { owner, name, @@ -56,14 +70,8 @@ pub async fn repo_head( open_issues, open_pulls, forked_from, - can_fork, - stars, - star, - watchers, - watch, - forks, - live, mirror, + live, lang, clone, .. @@ -73,32 +81,7 @@ pub async fn repo_head( let vis = i18n::visibility_label(lang, visibility); let shown_title = title.unwrap_or_else(|| tab_title(lang, active, &name)); let active = active.to_owned(); - let fork_control = match (can_fork, star.as_ref()) { - (true, Some(star)) => Some((repo_href(&owner, &name, "fork", ""), star.csrf.clone())), - _ => None, - }; - let star_control = match star { - Some(star) => { - let (path, label) = if star.starred { - ("unstar", g::star_label(lang, true, stars)) - } else { - ("star", g::star_label(lang, false, stars)) - }; - Some((repo_href(&owner, &name, path, ""), label, star.csrf)) - } - None => None, - }; - let anon_count = format!("\u{2605} {stars}"); - let watch_control = watch.map(|watch| { - let level = match watch.level { - WatchLevel::Participating => "participating", - WatchLevel::Watching => "watching", - WatchLevel::Ignoring => "ignoring", - }; - (repo_href(&owner, &name, "watch", ""), watch.csrf, level) - }); - let watch_count = g::watching_count(lang, watchers); - let fork_count = g::forks_count(lang, forks); + let parts_href = format!("/{owner}/{name}/parts/head"); let mut parts: Vec = Vec::new(); if is_code { if !description.is_empty() { @@ -107,8 +90,8 @@ pub async fn repo_head( if private { parts.push(SubPart::text(vis)); } - parts.push(SubPart::text(watch_count)); - parts.push(SubPart::text(fork_count)); + parts.push(watching); + parts.push(forking); if let Some((source_owner, source_name)) = forked_from { parts.push(SubPart::link( format!("{} {source_owner}/{source_name}", g::t(lang, K::ForkedFrom)), @@ -132,28 +115,12 @@ pub async fn repo_head( parts.extend(sub); let live_attr = (!live.is_empty()).then(|| live.clone()); Ok(view! { -
+

(shown_title.as_str())

if is_code { clone_popover(https: clone.https, ssh: clone.ssh, downloads: clone.downloads, lang: lang) - if let Some((action, label, csrf)) = star_control { -
- - -
- } else { - (anon_count.as_str()) - } - if let Some((action, csrf)) = fork_control { -
- - -
- } - if let Some((action, csrf, level)) = watch_control { - watch_form(lang: lang, action: action, csrf: csrf, level: level, watchers: watchers) - } + repo_actions(head: actions) } else if private { (vis) } @@ -169,6 +136,97 @@ pub async fn repo_head( .boxed()) } +#[component] +pub async fn repo_actions(cx: &Cx, head: RepoHead) -> Result { + let RepoHead { + owner, + name, + lang, + stars, + star, + can_fork, + watch, + watchers, + .. + } = head; + let fork_control = match (can_fork, star.as_ref()) { + (true, Some(star)) => Some((repo_href(&owner, &name, "fork", ""), star.csrf.clone())), + _ => None, + }; + let star_control = match star { + Some(star) => { + let (path, label) = if star.starred { + ("unstar", g::star_label(lang, true, stars)) + } else { + ("star", g::star_label(lang, false, stars)) + }; + Some((repo_href(&owner, &name, path, ""), label, star.csrf)) + } + None => None, + }; + let anon_count = format!("\u{2605} {stars}"); + let watch_control = watch.map(|watch| { + let level = match watch.level { + WatchLevel::Participating => "participating", + WatchLevel::Watching => "watching", + WatchLevel::Ignoring => "ignoring", + }; + (repo_href(&owner, &name, "watch", ""), watch.csrf, level) + }); + Ok(view! { + + if let Some((action, label, csrf)) = star_control { +
+ + +
+ } else { + (anon_count.as_str()) + } + if let Some((action, csrf)) = fork_control { +
+ + +
+ } + if let Some((action, csrf, level)) = watch_control { + watch_form(lang: lang, action: action, csrf: csrf, level: level, watchers: watchers) + } +
+ } + .boxed()) +} + +pub fn wants_parts(cx: &Cx) -> bool { + headers(cx).contains_key("x-forge-parts") +} + +pub async fn parts_response(cx: &Cx, ctx: &RepoCtx) -> Result { + let state = context::(cx); + let head = ctx.head(state, "code").await?; + let marker = ( + HeaderName::from_static("x-forge-parts"), + HeaderValue::from_static("1"), + ); + let watching = watching_part(&head); + let forking = forks_part(&head); + view! { + (marker) + repo_actions(head: head.clone()) + sub_part(part: watching) + sub_part(part: forking) + } + .first() + .await? + .into_response(cx) +} + +#[route(GET "/{owner}/{repo}/parts/head")] +async fn head_parts(cx: &Cx) -> Result { + let ctx = load_repo(cx, owner(cx), repo(cx)).await?; + parts_response(cx, &ctx).await +} + #[component] async fn clone_popover( cx: &Cx, diff --git a/crates/forge-web-pages/src/pages/star.rs b/crates/forge-web-pages/src/pages/star.rs index baceeb1..7cba5e9 100644 --- a/crates/forge-web-pages/src/pages/star.rs +++ b/crates/forge-web-pages/src/pages/star.rs @@ -3,11 +3,13 @@ use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::router::content::Form; -use topcoat::router::error::{SeeOther, see_other}; +use topcoat::router::error::see_other; use topcoat::router::request::headers; +use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{path_param, route}; use crate::auth::{require_csrf, safe_next}; +use crate::pages::repo::{parts_response, wants_parts}; use crate::pages::repo_ctx::load_repo; use crate::state::AppState; use crate::views::repo_href; @@ -22,16 +24,16 @@ struct StarForm { } #[route(POST "/{owner}/{repo}/star")] -async fn star_post(cx: &Cx, Form(form): Form) -> Result { +async fn star_post(cx: &Cx, Form(form): Form) -> Result { set_starred(cx, &form.csrf, true).await } #[route(POST "/{owner}/{repo}/unstar")] -async fn unstar_post(cx: &Cx, Form(form): Form) -> Result { +async fn unstar_post(cx: &Cx, Form(form): Form) -> Result { set_starred(cx, &form.csrf, false).await } -async fn set_starred(cx: &Cx, csrf: &str, starred: bool) -> Result { +async fn set_starred(cx: &Cx, csrf: &str, starred: bool) -> Result { let owner = owner(cx); let name = repo(cx); let ctx = load_repo(cx, owner, name).await?; @@ -44,8 +46,11 @@ async fn set_starred(cx: &Cx, csrf: &str, starred: bool) -> Result { } state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id); state.live.bump(&crate::live::Topic::User(user.id.clone())); + if wants_parts(cx) { + return parts_response(cx, &ctx).await; + } let home = repo_href(&ctx.repo.owner_name, &ctx.repo.name, "", ""); - Ok(see_other(return_path(cx).unwrap_or(home))) + see_other(return_path(cx).unwrap_or(home)).into_response(cx) } pub fn return_path(cx: &Cx) -> Option { diff --git a/crates/forge-web-repo/src/pages/issue_view.rs b/crates/forge-web-repo/src/pages/issue_view.rs index 27e77c2..05e7763 100644 --- a/crates/forge-web-repo/src/pages/issue_view.rs +++ b/crates/forge-web-repo/src/pages/issue_view.rs @@ -81,6 +81,7 @@ async fn issue_page( text: state_text.to_owned(), href: None, class: state_class, + part: None, }, SubPart::link(author.clone(), user_href(&author_login)), SubPart::text(opened.relative.clone()), diff --git a/crates/forge-web-repo/src/pages/repo_settings_live_tests.rs b/crates/forge-web-repo/src/pages/repo_settings_live_tests.rs index 3eca6b0..77ff306 100644 --- a/crates/forge-web-repo/src/pages/repo_settings_live_tests.rs +++ b/crates/forge-web-repo/src/pages/repo_settings_live_tests.rs @@ -116,7 +116,10 @@ async fn a_settings_write_wakes_the_open_settings_stream() { .await; assert_eq!(status, 303); let changed = frames.next().await.expect("a frame").expect("data"); - assert_eq!(&changed[..], b"event: changed\ndata: 1\n\n"); + assert_eq!( + &crate::test_support::fixture::seq_free(&changed)[..], + b"event: changed\ndata: 1\n\n" + ); } #[tokio::test] diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 0020131..10804c0 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -13,6 +13,12 @@ var userBusy = 0; // navigations and form posts on the wire (not live refreshes) var liveDirty = false; // a live change came while a navigation or a live fetch was on the wire var liveForced = false; // that change re-renders the page even with no stream of its own + var liveWant = 0; // newest live sequence a change asked for + var liveAny = 0; // changes without a sequence so far + var shownAny = 0; // how many of those the shown page covers + var pageSeq = Number(root.getAttribute('data-live-seq')) || 0; // live sequence the shown page was rendered at + var headBusy = false; // a head-part fetch is on the wire + var headAgain = false; // a head event came during that fetch: fetch once more after it var liveBusy = false; // a live fetch is on the wire: later changes wait for it, then share one fetch var inFlight = 0; // requests on the wire, drives aria-busy var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored @@ -177,10 +183,11 @@ function adopt(doc, keepFields, dd, jobs, logs) { document.title = doc.title; - ['lang', 'data-theme', 'data-accent-light', 'data-accent-dark', 'data-base-light', 'data-base-dark', 'data-sidebar', 'data-ui', 'data-rel-words', 'data-rel-now'].forEach(function (name) { + ['lang', 'data-theme', 'data-accent-light', 'data-accent-dark', 'data-base-light', 'data-base-dark', 'data-sidebar', 'data-ui', 'data-rel-words', 'data-rel-now', 'data-live-seq'].forEach(function (name) { if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); } else { root.removeAttribute(name); } }); + pageSeq = Number(root.getAttribute('data-live-seq')) || 0; syncStyles(doc); var kept = keepFields ? captureFields() : null; var nodes = Array.prototype.map.call(doc.body.childNodes, function (n) { return document.importNode(n, true); }); @@ -414,6 +421,40 @@ else { window.scrollTo(0, 0); } } + function focusables(el) { + return Array.prototype.filter.call(el.querySelectorAll('a[href], button, input, select, textarea'), function (n) { return !n.disabled; }); + } + + // Replaces each [data-part] element of the page with the one of the same name in `html`. Focus inside + // a replaced part moves to the same-index control of the new part. The URL and the page stay. + function swapParts(html) { + var doc = new DOMParser().parseFromString(html, 'text/html'); + Array.prototype.forEach.call(doc.querySelectorAll('[data-part]'), function (part) { + var old = document.querySelector('[data-part="' + part.getAttribute('data-part') + '"]'); + if (!old) { return; } + var at = old.contains(document.activeElement) ? focusables(old).indexOf(document.activeElement) : -1; + var next = document.importNode(part, true); + old.replaceWith(next); + var target = at >= 0 ? focusables(next)[at] : null; + if (target) { target.focus(); } + }); + } + + // A head part fetch: one in flight at a time. A head event that comes meanwhile is fetched once more after it. + function fetchHead(url) { + if (headBusy) { headAgain = true; return; } + headBusy = true; + fetch(url, { headers: { accept: 'text/html', 'x-forge-parts': '1' }, credentials: 'same-origin' }).then(function (r) { + return r.status < 400 ? r.text() : null; + }).then(function (html) { + var head = document.querySelector('[data-parts]'); + if (html !== null && head && head.getAttribute('data-parts') === url) { swapParts(html); } + }).catch(function () { }).then(function () { + headBusy = false; + if (headAgain) { headAgain = false; fetchHead(url); } + }); + } + // A live change keeps the reader's place in a diff. Before the swap: the first element marked // data-keep-anchor (a diff file, keyed by its path) that is still at least partly in view, and // its offset from the top of the view. After the swap: the same key, moved so it sits at that @@ -525,6 +566,7 @@ // how, keep (keep fields on a re-render of the same path), post, and the form for a POST or GET form. function load(o) { var mark = ++latest; + o.anyAt = liveAny; var user = o.how !== 'live'; if (user) { userBusy += 1; clearNote(); } busyStart(); @@ -536,7 +578,7 @@ if (final.origin !== location.origin || !html) { return { leave: true, url: final, redirected: r.redirected }; } - return r.text().then(function (text) { return { html: text, url: final, status: r.status, redirected: r.redirected }; }); + return r.text().then(function (text) { return { html: text, url: final, status: r.status, redirected: r.redirected, parts: r.headers.has('x-forge-parts') }; }); }, function () { // No answer at all: the server is down. return { down: true }; @@ -552,6 +594,7 @@ if (res.status === 404) { showGone(); } return; } + if (o.post && res.parts && res.status < 400) { swapParts(res.html); return; } var dest = new URL(res.url.href); dest.hash = o.dest.hash; // A form the server refused comes back as a page under the POST's URL, which may have no GET. @@ -565,6 +608,7 @@ var how = o.how === 'live' && res.url.pathname !== o.target.pathname ? 'nav' : o.how; var keep = !!o.keep && res.url.pathname === o.target.pathname; var finish = function () { + shownAny = Math.max(shownAny, o.anyAt); swap(res.html, dest, how, keep); if (pal.find) { paletteLand(); } // Other parts of this file follow page changes through this event (list memory, say). @@ -581,7 +625,7 @@ // A POST counts as done only when the server answered with a redirect to a page: the // post-redirect-get every successful form here ends in. Drafts listen for it. var r = o.result; - var ok = mark === latest && !!(r && r.html && r.redirected && r.status < 400); + var ok = mark === latest && !!(r && r.html && (r.redirected || r.parts) && r.status < 400); document.dispatchEvent(new CustomEvent('forge:submitted', { detail: { form: o.form, ok: ok } })); } if (o.form) { pending.delete(o.form); } @@ -665,7 +709,7 @@ var o = link.pending; link.pending = null; if (o) { hideBar(); load(o); return; } - refreshLive(); + refreshLive(true); if (link.post) { showBar(linkText('back')); } else { hideBar(); } } @@ -1102,13 +1146,15 @@ } var multipart = (form.enctype || '').toLowerCase().indexOf('multipart') === 0; + var headers = { accept: 'text/html' }; + if (form.closest('[data-part]')) { headers['x-forge-parts'] = '1'; } submitStart(form, submitter); load({ target: withoutHash(url), dest: url, init: { method: 'POST', - headers: { accept: 'text/html' }, + headers: headers, body: multipart ? data : new URLSearchParams(data) }, how: 'post', @@ -2640,6 +2686,15 @@ var job = document.querySelector('[data-live-log]'); var wrap = job ? job.closest('[data-live]') : null; if (wrap && wrap.getAttribute('data-live-state') === e.data) { return; } + var m = /^(\d+)( head)?$/.exec(e.data); + if (m) { + if (Number(m[1]) <= pageSeq) { return; } + var head = m[2] ? document.querySelector('[data-parts]') : null; + if (head) { fetchHead(head.getAttribute('data-parts')); return; } + liveWant = Math.max(liveWant, Number(m[1])); + } else { + liveAny += 1; + } // A code view or an issue page re-renders at once (data-live-now). Events that come while a fetch // is on the wire share the next one. if (document.querySelector('[data-live-code], [data-live-now]')) { refreshLive(); return; } @@ -2759,6 +2814,8 @@ if (document.querySelector('[data-once]')) { return; } // A rejected form is on screen: a re-render would replace its error. See load(). if (heldForm) { return; } + // Only sequence changes the page already shows are pending: nothing to render. + if (!force && liveAny <= shownAny && liveWant <= pageSeq) { liveDirty = false; return; } if (userBusy > 0 || liveBusy || selecting()) { liveDirty = true; if (force) { liveForced = true; } return; } liveDirty = false; liveForced = false; diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 5f8015d..8818f4f 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -163,6 +163,7 @@ pub async fn serve( .layer(TowerLayer::new( forge_web_app::compression::ResponseCompression, )) + .layer(forge_web_app::layers::LiveSeqLayer) .with(Compression::disable()) .build(); let internal_router = internal::router(state.clone()); diff --git a/crates/forge-web/src/routes.snap b/crates/forge-web/src/routes.snap index 1b8f70e..4ae37f8 100644 --- a/crates/forge-web/src/routes.snap +++ b/crates/forge-web/src/routes.snap @@ -328,6 +328,7 @@ route /{owner}/{repo}/issues/{number}/subscription Only([POST]) route /{owner}/{repo}/issues/{number}/tasks Only([POST]) route /{owner}/{repo}/labels.css Only([GET]) route /{owner}/{repo}/merge-queue/events Only([GET]) +route /{owner}/{repo}/parts/head Only([GET]) route /{owner}/{repo}/paths/{*rest} Only([GET]) route /{owner}/{repo}/pulls/events Only([GET]) route /{owner}/{repo}/pulls/{number}/auto-merge Only([POST]) diff --git a/style/_min.scss b/style/_min.scss index 23924fe..c01ab8d 100644 --- a/style/_min.scss +++ b/style/_min.scss @@ -254,6 +254,10 @@ summary.act { margin: 0; } +.head-actions { + display: contents; +} + // An action that opens in place. Its panel takes a line of its own under the links beside it. .reveal { diff --git a/style/_one.scss b/style/_one.scss index 0148246..eb2fe81 100644 --- a/style/_one.scss +++ b/style/_one.scss @@ -3546,6 +3546,7 @@ details.log-group { // keeps its red word on the pill. What opens from a reveal keeps its own kit. .head-title > :is(a.act, button.act), .head-title > form.act-form > button.act, +.head-actions > form.act-form > button.act, .head-title > details.reveal > summary.act { display: inline-flex; align-items: center; diff --git a/style/_one_shell.scss b/style/_one_shell.scss index 81777f1..4ad52a6 100644 --- a/style/_one_shell.scss +++ b/style/_one_shell.scss @@ -144,7 +144,7 @@ a > .ref-chip, // Beside a repo title, the watch button is one of the head's pills: the same height, radius, fill, // and 600 text as Star and Fork. The caret keeps its place at the end. -.head-title > .watch-control .watch-menu > summary { +.head-actions > .watch-control .watch-menu > summary { box-sizing: border-box; padding: 0 30px 0 18px; font-size: 15px; @@ -191,14 +191,14 @@ a > .ref-chip, } // In the head the watcher count is in the line under the title, so the watch pill stands alone. -.head-title > .watch-control > .hint { +.head-actions > .watch-control > .hint { display: none; } // On a phone the watch pill is its eye and chevron, so it shares the title's line with Star; its // level stays in the summary's label. @media (max-width: 700px) { - .head-title > .watch-control .watch-menu > summary > span { + .head-actions > .watch-control .watch-menu > summary > span { display: none; } }