forge
Explore
Log in

Don't you dare go Hollow

Star and watch answer with the repo head's parts instead of a redirect to the whole page

Browse files at this commit

6e3d1e1258daecc8c53d4740b91aa088491a2966Ahmet Kaan GümüşParent: 7b1d61e
Some checks failed
Show checks
  • ✗ci/buildjob was cancelledDetails
  • perf
    • star and watch answer with the repo head's parts instead of a redirect to the whole page
    • live events carry a sequence, so a page never renders twice for a change it already shows
Show full message
⚡ perf: star and watch answer with the repo head's parts instead of a redirect to the whole page; live events carry a sequence, so a page never renders twice for a change it already shows
crates/forge-runner/src/runner.rsmodified+6 -2
@@ -458,8 +458,12 @@ impl Runner {
458458 .map_err(|e| format!("artifacts: {e}"))?;
459459 for artifact in &found {
460460 patiently(&job.job_id, "artifact upload", || {
461- self.client
462- .upload_artifact(&job.job_id, &job.job_token, &artifact.name, &artifact.path)
461+ self.client.upload_artifact(
462+ &job.job_id,
463+ &job.job_token,
464+ &artifact.name,
465+ &artifact.path,
466+ )
463467 })
464468 .await
465469 .map_err(|e| format!("artifact {}: {e}", artifact.name))?;
crates/forge-web-account/src/pages/admin_health.rsmodified+2 -0
@@ -460,12 +460,14 @@ async fn health_view(
460460 text: needs_attention(lang, attention),
461461 href: None,
462462 class: "b health-sum bad",
463+ part: None,
463464 }
464465 } else {
465466 SubPart {
466467 text: at(lang, A::Fine).to_owned(),
467468 href: None,
468469 class: "b health-sum ok",
470+ part: None,
469471 }
470472 };
471473 let sub = vec![summary];
crates/forge-web-account/src/pages/releases_tests.rsmodified+5 -4
@@ -11,6 +11,7 @@ use topcoat::router::{Body, HeaderMap, Router, to_bytes};
1111 use crate::auth::SESSION_COOKIE;
1212 use crate::blobs::asset_key;
1313 use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};
14+use crate::test_support::fixture::seq_free;
1415 use crate::test_support::{app_router, create_session, test_state};
1516
1617 const CSRF: &str = "releases-test-csrf";
@@ -980,11 +981,11 @@ async fn live_streams_wake_on_changes_and_hide_drafts() {
980981 .await
981982 .expect("edited");
982983 assert_eq!(
983- &list.next().await.expect("a frame").expect("data")[..],
984+ &seq_free(&list.next().await.expect("a frame").expect("data"))[..],
984985 CHANGED
985986 );
986987 assert_eq!(
987- &page.next().await.expect("a frame").expect("data")[..],
988+ &seq_free(&page.next().await.expect("a frame").expect("data"))[..],
988989 CHANGED
989990 );
990991
@@ -1000,13 +1001,13 @@ async fn live_streams_wake_on_changes_and_hide_drafts() {
10001001 .await;
10011002 assert_eq!(uploaded.status, 303, "body: {}", uploaded.text());
10021003 assert_eq!(
1003- &list.next().await.expect("a frame").expect("data")[..],
1004+ &seq_free(&list.next().await.expect("a frame").expect("data"))[..],
10041005 CHANGED
10051006 );
10061007 let download = fx.download("v1.1/app.tar.gz").await;
10071008 assert_eq!(download.status, 200);
10081009 assert_eq!(
1009- &list.next().await.expect("a frame").expect("data")[..],
1010+ &seq_free(&list.next().await.expect("a frame").expect("data"))[..],
10101011 CHANGED
10111012 );
10121013
crates/forge-web-account/src/pages/settings_live.rsmodified+1 -1
@@ -344,7 +344,7 @@ mod tests {
344344 live.bump(&Topic::Account(owner.id.clone()));
345345 let changed = frames.next().await.expect("a frame").expect("data");
346346 assert_eq!(
347- &changed[..],
347+ &crate::test_support::fixture::seq_free(&changed)[..],
348348 b"event: changed\ndata: 1\n\n",
349349 "settings stream: changed event"
350350 );
crates/forge-web-app/src/ci/live.rsmodified+2 -0
@@ -114,6 +114,7 @@ impl Signals {
114114 }
115115
116116 pub fn bump(&self, key: &str) {
117+ crate::live::next_live_seq();
117118 let mut counters = self.counters();
118119 let Some(tx) = counters.get(key) else {
119120 return;
@@ -125,6 +126,7 @@ impl Signals {
125126 }
126127
127128 fn close(&self, key: &str) {
129+ crate::live::next_live_seq();
128130 let removed = self.counters().remove(key);
129131 if let Some(tx) = removed {
130132 tx.send_modify(|generation| *generation = generation.wrapping_add(1));
crates/forge-web-app/src/layers.rsmodified+27 -0
@@ -7,6 +7,7 @@ use topcoat::router::request::{method, uri};
77 use crate::live::Topic;
88 use crate::state::AppState;
99
10+pub use live_seq::LiveSeqLayer;
1011 pub use not_found_layer::NotFoundLayer;
1112 pub use org_write::OrgWriteLayer;
1213 pub use pull_write::PullWriteLayer;
@@ -392,6 +393,32 @@ mod repo_settings_write {
392393 }
393394 }
394395
396+mod live_seq {
397+ use topcoat::Result;
398+ use topcoat::context::Cx;
399+ use topcoat::router::response::Response;
400+ use topcoat::router::{Body, Layer, LayerFuture, Next, Path};
401+
402+ use crate::live::{LiveSeq, live_seq};
403+
404+ pub struct LiveSeqLayer;
405+
406+ impl Layer for LiveSeqLayer {
407+ fn path(&self) -> Option<&Path> {
408+ None
409+ }
410+
411+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
412+ Box::pin(record_seq(cx, body, next))
413+ }
414+ }
415+
416+ async fn record_seq(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> {
417+ let cx = cx.with(LiveSeq(live_seq()));
418+ next.run(&cx, body).await
419+ }
420+}
421+
395422 mod not_found_layer {
396423 use http::header::ACCEPT;
397424 use topcoat::Result;
crates/forge-web-app/src/live.rsmodified+74 -14
@@ -1,5 +1,6 @@
11 use std::collections::HashMap;
22 use std::future::Future;
3+use std::sync::atomic::{AtomicU64, Ordering};
34 use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
45 use std::time::Duration;
56
@@ -46,6 +47,27 @@ pub fn admin() -> &'static LiveHub {
4647 ADMIN.get_or_init(LiveHub::default)
4748 }
4849
50+fn seq_counter() -> &'static AtomicU64 {
51+ static LIVE_SEQ: OnceLock<AtomicU64> = OnceLock::new();
52+ LIVE_SEQ.get_or_init(|| {
53+ let start = std::time::SystemTime::now()
54+ .duration_since(std::time::UNIX_EPOCH)
55+ .map_or(0, |d| u64::try_from(d.as_micros()).unwrap_or(u64::MAX / 2));
56+ AtomicU64::new(start)
57+ })
58+}
59+
60+pub fn live_seq() -> u64 {
61+ seq_counter().load(Ordering::SeqCst)
62+}
63+
64+pub fn next_live_seq() -> u64 {
65+ seq_counter().fetch_add(1, Ordering::SeqCst) + 1
66+}
67+
68+#[derive(Clone, Copy, Debug)]
69+pub struct LiveSeq(pub u64);
70+
4971 #[derive(Default)]
5072 pub struct LiveHub {
5173 topics: Mutex<HashMap<Topic, watch::Sender<u64>>>,
@@ -66,6 +88,7 @@ impl LiveHub {
6688 }
6789
6890 pub fn bump(&self, topic: &Topic) {
91+ next_live_seq();
6992 let mut topics = self.topics();
7093 let Some(tx) = topics.get(topic) else {
7194 return;
@@ -94,18 +117,23 @@ impl LiveHub {
94117 }
95118 }
96119
97-struct Follow<F> {
120+struct Follow<T, F> {
98121 wakes: Vec<watch::Receiver<u64>>,
99122 read: F,
100- last: String,
123+ last: T,
124+ diff: Diff<T>,
101125 }
102126
103-fn wake_event() -> Result<Event> {
104- Ok(Event::new().event("changed").data("1"))
127+type Diff<T> = fn(&T, &T) -> Option<&'static str>;
128+
129+fn named_event(name: &'static str, suffix: &str) -> Result<Event> {
130+ Ok(Event::new()
131+ .event(name)
132+ .data(format!("{}{suffix}", live_seq())))
105133 }
106134
107-fn named_event(name: &'static str) -> Result<Event> {
108- Ok(Event::new().event(name).data("1"))
135+fn wake_event() -> Result<Event> {
136+ named_event("changed", "")
109137 }
110138
111139 async fn wait_any(wakes: &mut [watch::Receiver<u64>]) -> bool {
@@ -149,27 +177,59 @@ where
149177 F: Fn() -> Fut + Send + 'static,
150178 Fut: Future<Output = Result<String>> + Send,
151179 {
152- let events = named_changes(hub, topics.to_vec(), extra, "changed", read).await?;
180+ let diff: Diff<String> = |old, new| (old != new).then_some("");
181+ let events = named_changes(hub, topics.to_vec(), extra, "changed", read, diff).await?;
153182 events_response(cx, events)
154183 }
155184
156-async fn named_changes<F, Fut>(
185+pub async fn stream_changes_split<F, Fut>(
186+ cx: &Cx,
187+ hub: &LiveHub,
188+ topics: &[Topic],
189+ extra: Vec<watch::Receiver<u64>>,
190+ read: F,
191+) -> Result<Response>
192+where
193+ F: Fn() -> Fut + Send + 'static,
194+ Fut: Future<Output = Result<(String, String)>> + Send,
195+{
196+ let diff: Diff<(String, String)> = |old, new| {
197+ if old.1 != new.1 {
198+ Some("")
199+ } else if old.0 != new.0 {
200+ Some(" head")
201+ } else {
202+ None
203+ }
204+ };
205+ let events = named_changes(hub, topics.to_vec(), extra, "changed", read, diff).await?;
206+ events_response(cx, events)
207+}
208+
209+async fn named_changes<T, F, Fut>(
157210 hub: &LiveHub,
158211 topics: Vec<Topic>,
159212 extra: Vec<watch::Receiver<u64>>,
160213 name: &'static str,
161214 read: F,
215+ diff: Diff<T>,
162216 ) -> Result<impl Stream<Item = Result<Event>> + Send + 'static>
163217 where
218+ T: Send + 'static,
164219 F: Fn() -> Fut + Send + 'static,
165- Fut: Future<Output = Result<String>> + Send,
220+ Fut: Future<Output = Result<T>> + Send,
166221 {
167222 let mut wakes: Vec<watch::Receiver<u64>> =
168223 topics.iter().map(|topic| hub.subscribe(topic)).collect();
169224 wakes.extend(extra);
170225 let last = read().await?;
171226 Ok(stream::unfold(
172- Follow { wakes, read, last },
227+ Follow {
228+ wakes,
229+ read,
230+ last,
231+ diff,
232+ },
173233 move |mut follow| async move {
174234 loop {
175235 if !wait_any(&mut follow.wakes).await {
@@ -182,11 +242,11 @@ where
182242 return None;
183243 }
184244 };
185- if now == follow.last {
186- continue;
187- }
245+ let suffix = (follow.diff)(&follow.last, &now);
188246 follow.last = now;
189- return Some((named_event(name), follow));
247+ if let Some(suffix) = suffix {
248+ return Some((named_event(name, suffix), follow));
249+ }
190250 }
191251 },
192252 ))
crates/forge-web-app/src/mail/live.rsmodified+1 -0
@@ -13,6 +13,7 @@ pub fn subscribe() -> watch::Receiver<u64> {
1313 }
1414
1515 pub fn bump() {
16+ crate::live::next_live_seq();
1617 sender().send_modify(|generation| *generation = generation.wrapping_add(1));
1718 crate::live::admin().bump(&crate::live::Topic::AdminHealth);
1819 }
crates/forge-web-app/src/test_support/fixture.rsmodified+16 -1
@@ -228,7 +228,22 @@ where
228228 loop {
229229 let bytes = next_frame(frames).await?;
230230 if !bytes.starts_with(b"retry: ") {
231- return Some(bytes);
231+ return Some(seq_free(&bytes));
232232 }
233233 }
234234 }
235+
236+pub fn seq_free(frame: &[u8]) -> Vec<u8> {
237+ let text = String::from_utf8_lossy(frame);
238+ let Some(data) = text
239+ .strip_prefix("event: changed\ndata: ")
240+ .and_then(|rest| rest.strip_suffix("\n\n"))
241+ else {
242+ return frame.to_vec();
243+ };
244+ let seq = data.strip_suffix(" head").unwrap_or(data);
245+ if seq.is_empty() || !seq.bytes().all(|b| b.is_ascii_digit()) {
246+ return frame.to_vec();
247+ }
248+ format!("event: changed\ndata: 1{}\n\n", &data[seq.len()..]).into_bytes()
249+}
crates/forge-web-app/src/test_support/mod.rsmodified+1 -0
@@ -103,6 +103,7 @@ pub fn app_router(state: AppState) -> Router {
103103 .layer(crate::layers::PullWriteLayer)
104104 .layer(crate::layers::OrgWriteLayer)
105105 .layer(TowerLayer::new(crate::compression::ResponseCompression))
106+ .layer(crate::layers::LiveSeqLayer)
106107 .with(Compression::disable())
107108 .build()
108109 }
crates/forge-web-app/src/views/mod.rsmodified+3 -1
@@ -41,6 +41,7 @@ use crate::i18n::misc::{self as mi, K as MK};
4141 use crate::i18n::orgs::{self as o, K as OK};
4242 use crate::i18n::s;
4343 use crate::i18n::{self, Key, Lang, t};
44+use crate::live::LiveSeq;
4445 use crate::render::highlight::highlight_css;
4546 use crate::state::AppState;
4647 use crate::theme::Theme;
@@ -613,9 +614,10 @@ pub async fn shell(
613614 unread,
614615 waiting: inbox.reviews + inbox.mentions + runs.failing > 0,
615616 });
617+ let live_seq = try_context::<LiveSeq>(cx).map(|seq| seq.0.to_string());
616618 Ok(view! {
617619 <!DOCTYPE html>
618- <html lang=(lang.code()) data-theme=(theme_attr) data-sound=(sound_attr)data-accent-light=(accent_light_id) data-accent-dark=(accent_dark_id) data-base-light=(base_light_id) data-base-dark=(base_dark_id) data-sidebar=(sidebar_side) data-rel-words=(rel_words_attr.as_str()) data-rel-now=(rel_now_attr.as_str())>
620+ <html lang=(lang.code()) data-live-seq=(live_seq) data-theme=(theme_attr) data-sound=(sound_attr)data-accent-light=(accent_light_id) data-accent-dark=(accent_dark_id) data-base-light=(base_light_id) data-base-dark=(base_dark_id) data-sidebar=(sidebar_side) data-rel-words=(rel_words_attr.as_str()) data-rel-now=(rel_now_attr.as_str())>
619621 <head>
620622 <meta charset="utf-8">
621623 <meta name="viewport" content="width=device-width, initial-scale=1">
crates/forge-web-app/src/views/parts.rsmodified+19 -5
@@ -226,9 +226,15 @@ pub struct SubPart {
226226 pub text: String,
227227 pub href: Option<String>,
228228 pub class: &'static str,
229+ pub part: Option<&'static str>,
229230 }
230231
231232 impl SubPart {
233+ pub fn with_part(mut self, part: &'static str) -> Self {
234+ self.part = Some(part);
235+ self
236+ }
237+
232238 pub fn text(text: impl Into<String>) -> Self {
233239 Self {
234240 text: text.into(),
@@ -261,6 +267,18 @@ impl SubPart {
261267 }
262268 }
263269
270+#[component]
271+pub async fn sub_part(cx: &Cx, part: SubPart) -> Result<impl View> {
272+ Ok(view! {
273+ if let Some(href) = part.href {
274+ <a class=(part.class) href=(href) data-part=(part.part)>(part.text)</a>
275+ } else {
276+ <span class=(part.class) data-part=(part.part)>(part.text)</span>
277+ }
278+ }
279+ .boxed())
280+}
281+
264282 #[component]
265283 pub async fn head_sub(
266284 cx: &Cx,
@@ -278,11 +296,7 @@ pub async fn head_sub(
278296 if n > 0 {
279297 <span class="sep" aria-hidden="true">"·"</span>
280298 }
281- if let Some(href) = part.href {
282- <a class=(part.class) href=(href)>(part.text)</a>
283- } else {
284- <span class=(part.class)>(part.text)</span>
285- }
299+ sub_part(part: part)
286300 }
287301 if has_pips {
288302 <span class="pips">
crates/forge-web-pages/src/pages/code_live.rsmodified+7 -7
@@ -8,7 +8,7 @@ use topcoat::router::response::Response;
88 use topcoat::router::{path_param, query_params, route};
99
1010 use crate::auth::percent_encode;
11-use crate::live::{Topic, stream_changes_with};
11+use crate::live::{Topic, stream_changes_split};
1212 use crate::pages::refs::load_refs;
1313 use crate::pages::repo_ctx::{fork_count, load_repo};
1414 use crate::pages::repo_side::runs_fingerprint;
@@ -148,7 +148,7 @@ async fn repo_events(cx: &Cx) -> Result<Response> {
148148 };
149149 let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone());
150150 let path = ctx.path.clone();
151- stream_changes_with(cx, &state.live.clone(), &topics, extra, move || {
151+ stream_changes_split(cx, &state.live.clone(), &topics, extra, move || {
152152 let state = state.clone();
153153 let repo_id = repo_id.clone();
154154 let path = path.clone();
@@ -156,17 +156,17 @@ async fn repo_events(cx: &Cx) -> Result<Response> {
156156 let viewer = viewer.clone();
157157 async move {
158158 let viewer_id = viewer.as_ref().map(|user| user.id.as_str());
159- let mut out = header_fingerprint(&state, &repo_id, viewer_id).await?;
159+ let head = header_fingerprint(&state, &repo_id, viewer_id).await?;
160+ let mut rest = String::new();
160161 if !branch.is_empty() {
161- let refs = refs_fingerprint(path, branch).await?;
162- out = format!("{out}\n{refs}");
162+ rest = refs_fingerprint(path, branch).await?;
163163 }
164164 if home {
165165 let extra = home_fingerprint(&state, &repo_id).await?;
166166 let runs = runs_fingerprint(&state, &repo_id).await?;
167- out = format!("{out}\n{extra}\n{runs}");
167+ rest = format!("{rest}\n{extra}\n{runs}");
168168 }
169- Ok(out)
169+ Ok((head, rest))
170170 }
171171 })
172172 .await
crates/forge-web-pages/src/pages/notifications.rsmodified+7 -8
@@ -11,7 +11,7 @@ use topcoat::context::{Cx, context};
1111 use topcoat::router::content::Form;
1212 use topcoat::router::content::sse::Event;
1313 use topcoat::router::error::{SeeOther, bad_request, not_found, see_other};
14-use topcoat::router::response::Response;
14+use topcoat::router::response::{IntoResponse, Response};
1515 use topcoat::router::{Body, StatusCode, page, path_param, query_params, route};
1616 use topcoat::view::{View, component, view};
1717
@@ -23,6 +23,7 @@ use crate::live::events_response;
2323 use crate::live::{Topic, stream_changes};
2424 use crate::notify_hub::publish_unread;
2525 use crate::pages::issue_parts::parse_number;
26+use crate::pages::repo::{parts_response, wants_parts};
2627 use crate::pages::repo_ctx::{RepoCtx, load_repo};
2728 use crate::pages::repo_transfer::transfer_list_for;
2829 use crate::pages::star::return_path;
@@ -569,7 +570,7 @@ async fn set_subscription(cx: &Cx, pull: bool, form: &SubscriptionForm) -> Resul
569570 }
570571
571572 #[route(POST "/{owner}/{repo}/watch")]
572-async fn set_watch(cx: &Cx, Form(form): Form<WatchForm>) -> Result<SeeOther> {
573+async fn set_watch(cx: &Cx, Form(form): Form<WatchForm>) -> Result<Response> {
573574 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
574575 let (user, _) = require_csrf(cx, &form.csrf).await?;
575576 let level = match form.level.as_str() {
@@ -581,12 +582,10 @@ async fn set_watch(cx: &Cx, Form(form): Form<WatchForm>) -> Result<SeeOther> {
581582 let state = context::<AppState>(cx);
582583 state.store.set_watch(&user.id, &ctx.repo.id, level).await?;
583584 state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id);
584- Ok(see_other(repo_href(
585- &ctx.repo.owner_name,
586- &ctx.repo.name,
587- "",
588- "",
589- )))
585+ if wants_parts(cx) {
586+ return parts_response(cx, &ctx).await;
587+ }
588+ see_other(repo_href(&ctx.repo.owner_name, &ctx.repo.name, "", "")).into_response(cx)
590589 }
591590
592591 pub async fn repo_allows(
crates/forge-web-pages/src/pages/ref_live.rsmodified+8 -2
@@ -78,7 +78,10 @@ mod tests {
7878 .expect("woken")
7979 .expect("a frame")
8080 .expect("data");
81- assert_eq!(&first[..], b"event: changed\ndata: 1\n\n");
81+ assert_eq!(
82+ &crate::test_support::fixture::seq_free(&first)[..],
83+ b"event: changed\ndata: 1\n\n"
84+ );
8285
8386 fx.live.bump(&Topic::CommitStatuses(repo.id.clone()));
8487 let second = tokio::time::timeout(Duration::from_secs(5), frames.next())
@@ -86,7 +89,10 @@ mod tests {
8689 .expect("woken")
8790 .expect("a frame")
8891 .expect("data");
89- assert_eq!(&second[..], b"event: changed\ndata: 1\n\n");
92+ assert_eq!(
93+ &crate::test_support::fixture::seq_free(&second)[..],
94+ b"event: changed\ndata: 1\n\n"
95+ );
9096 }
9197
9298 #[tokio::test]
crates/forge-web-pages/src/pages/repo.rsmodified+112 -54
@@ -7,9 +7,12 @@ use forge_core::WatchLevel;
77 use forge_core::time::stamp_ago;
88 use forge_git::browse;
99 use forge_git::repo::repo_path;
10+use http::{HeaderName, HeaderValue};
1011 use topcoat::Result;
1112 use topcoat::context::{Cx, context};
1213 use topcoat::router::error::not_found;
14+use topcoat::router::request::headers;
15+use topcoat::router::response::{IntoResponse, Response};
1316 use topcoat::router::{page, path_param, route};
1417 use topcoat::view::{Child, View, ViewExt, component, view};
1518
@@ -26,7 +29,7 @@ use crate::pages::tree::{
2629 entry_rows, last_commits, latest_bar, load_readme, read_dir, readme_sheet, tree_table,
2730 };
2831 use crate::state::AppState;
29-use crate::views::parts::{SubPart, head_sub};
32+use crate::views::parts::{SubPart, head_sub, sub_part};
3033 use crate::views::{
3134 https_clone_url, now_unix, ref_selector, relative_time, repo_href, repo_tabs, shell,
3235 ssh_clone_url, stamp_unix, tab_title,
@@ -35,6 +38,14 @@ use crate::views::{
3538 path_param!(owner);
3639 path_param!(repo);
3740
41+pub fn watching_part(head: &RepoHead) -> SubPart {
42+ SubPart::text(g::watching_count(head.lang, head.watchers)).with_part("repo-watching")
43+}
44+
45+pub fn forks_part(head: &RepoHead) -> SubPart {
46+ SubPart::text(g::forks_count(head.lang, head.forks)).with_part("repo-forks")
47+}
48+
3849 #[component]
3950 pub async fn repo_head(
4051 cx: &Cx,
@@ -44,6 +55,9 @@ pub async fn repo_head(
4455 #[default] pips: Vec<(String, String, &'static str)>,
4556 #[default] child: Child<'_>,
4657 ) -> Result<impl View> {
58+ let actions = head.clone();
59+ let watching = watching_part(&head);
60+ let forking = forks_part(&head);
4761 let RepoHead {
4862 owner,
4963 name,
@@ -56,14 +70,8 @@ pub async fn repo_head(
5670 open_issues,
5771 open_pulls,
5872 forked_from,
59- can_fork,
60- stars,
61- star,
62- watchers,
63- watch,
64- forks,
65- live,
6673 mirror,
74+ live,
6775 lang,
6876 clone,
6977 ..
@@ -73,32 +81,7 @@ pub async fn repo_head(
7381 let vis = i18n::visibility_label(lang, visibility);
7482 let shown_title = title.unwrap_or_else(|| tab_title(lang, active, &name));
7583 let active = active.to_owned();
76- let fork_control = match (can_fork, star.as_ref()) {
77- (true, Some(star)) => Some((repo_href(&owner, &name, "fork", ""), star.csrf.clone())),
78- _ => None,
79- };
80- let star_control = match star {
81- Some(star) => {
82- let (path, label) = if star.starred {
83- ("unstar", g::star_label(lang, true, stars))
84- } else {
85- ("star", g::star_label(lang, false, stars))
86- };
87- Some((repo_href(&owner, &name, path, ""), label, star.csrf))
88- }
89- None => None,
90- };
91- let anon_count = format!("\u{2605} {stars}");
92- let watch_control = watch.map(|watch| {
93- let level = match watch.level {
94- WatchLevel::Participating => "participating",
95- WatchLevel::Watching => "watching",
96- WatchLevel::Ignoring => "ignoring",
97- };
98- (repo_href(&owner, &name, "watch", ""), watch.csrf, level)
99- });
100- let watch_count = g::watching_count(lang, watchers);
101- let fork_count = g::forks_count(lang, forks);
84+ let parts_href = format!("/{owner}/{name}/parts/head");
10285 let mut parts: Vec<SubPart> = Vec::new();
10386 if is_code {
10487 if !description.is_empty() {
@@ -107,8 +90,8 @@ pub async fn repo_head(
10790 if private {
10891 parts.push(SubPart::text(vis));
10992 }
110- parts.push(SubPart::text(watch_count));
111- parts.push(SubPart::text(fork_count));
93+ parts.push(watching);
94+ parts.push(forking);
11295 if let Some((source_owner, source_name)) = forked_from {
11396 parts.push(SubPart::link(
11497 format!("{} {source_owner}/{source_name}", g::t(lang, K::ForkedFrom)),
@@ -132,28 +115,12 @@ pub async fn repo_head(
132115 parts.extend(sub);
133116 let live_attr = (!live.is_empty()).then(|| live.clone());
134117 Ok(view! {
135- <section class="head repo-head" data-live=(live_attr.as_deref())>
118+ <section class="head repo-head" data-live=(live_attr.as_deref()) data-parts=(parts_href.as_str())>
136119 <div class="head-title">
137120 <h1>(shown_title.as_str())</h1>
138121 if is_code {
139122 clone_popover(https: clone.https, ssh: clone.ssh, downloads: clone.downloads, lang: lang)
140- if let Some((action, label, csrf)) = star_control {
141- <form method="post" action=(action.as_str()) class="act-form">
142- <input type="hidden" name="csrf" value=(csrf.as_str())>
143- <button type="submit" data-palette-action="post">(label.as_str())</button>
144- </form>
145- } else {
146- <span class="hint" aria-label=(g::t(lang, K::StarsAria))>(anon_count.as_str())</span>
147- }
148- if let Some((action, csrf)) = fork_control {
149- <form method="post" action=(action.as_str()) class="act-form">
150- <input type="hidden" name="csrf" value=(csrf.as_str())>
151- <button type="submit">(g::t(lang, K::ForkButton))</button>
152- </form>
153- }
154- if let Some((action, csrf, level)) = watch_control {
155- watch_form(lang: lang, action: action, csrf: csrf, level: level, watchers: watchers)
156- }
123+ repo_actions(head: actions)
157124 } else if private {
158125 <span class="hint">(vis)</span>
159126 }
@@ -169,6 +136,97 @@ pub async fn repo_head(
169136 .boxed())
170137 }
171138
139+#[component]
140+pub async fn repo_actions(cx: &Cx, head: RepoHead) -> Result<impl View> {
141+ let RepoHead {
142+ owner,
143+ name,
144+ lang,
145+ stars,
146+ star,
147+ can_fork,
148+ watch,
149+ watchers,
150+ ..
151+ } = head;
152+ let fork_control = match (can_fork, star.as_ref()) {
153+ (true, Some(star)) => Some((repo_href(&owner, &name, "fork", ""), star.csrf.clone())),
154+ _ => None,
155+ };
156+ let star_control = match star {
157+ Some(star) => {
158+ let (path, label) = if star.starred {
159+ ("unstar", g::star_label(lang, true, stars))
160+ } else {
161+ ("star", g::star_label(lang, false, stars))
162+ };
163+ Some((repo_href(&owner, &name, path, ""), label, star.csrf))
164+ }
165+ None => None,
166+ };
167+ let anon_count = format!("\u{2605} {stars}");
168+ let watch_control = watch.map(|watch| {
169+ let level = match watch.level {
170+ WatchLevel::Participating => "participating",
171+ WatchLevel::Watching => "watching",
172+ WatchLevel::Ignoring => "ignoring",
173+ };
174+ (repo_href(&owner, &name, "watch", ""), watch.csrf, level)
175+ });
176+ Ok(view! {
177+ <span class="head-actions" data-part="repo-actions">
178+ if let Some((action, label, csrf)) = star_control {
179+ <form method="post" action=(action.as_str()) class="act-form">
180+ <input type="hidden" name="csrf" value=(csrf.as_str())>
181+ <button type="submit" data-palette-action="post">(label.as_str())</button>
182+ </form>
183+ } else {
184+ <span class="hint" aria-label=(g::t(lang, K::StarsAria))>(anon_count.as_str())</span>
185+ }
186+ if let Some((action, csrf)) = fork_control {
187+ <form method="post" action=(action.as_str()) class="act-form">
188+ <input type="hidden" name="csrf" value=(csrf.as_str())>
189+ <button type="submit">(g::t(lang, K::ForkButton))</button>
190+ </form>
191+ }
192+ if let Some((action, csrf, level)) = watch_control {
193+ watch_form(lang: lang, action: action, csrf: csrf, level: level, watchers: watchers)
194+ }
195+ </span>
196+ }
197+ .boxed())
198+}
199+
200+pub fn wants_parts(cx: &Cx) -> bool {
201+ headers(cx).contains_key("x-forge-parts")
202+}
203+
204+pub async fn parts_response(cx: &Cx, ctx: &RepoCtx) -> Result<Response> {
205+ let state = context::<AppState>(cx);
206+ let head = ctx.head(state, "code").await?;
207+ let marker = (
208+ HeaderName::from_static("x-forge-parts"),
209+ HeaderValue::from_static("1"),
210+ );
211+ let watching = watching_part(&head);
212+ let forking = forks_part(&head);
213+ view! {
214+ (marker)
215+ repo_actions(head: head.clone())
216+ sub_part(part: watching)
217+ sub_part(part: forking)
218+ }
219+ .first()
220+ .await?
221+ .into_response(cx)
222+}
223+
224+#[route(GET "/{owner}/{repo}/parts/head")]
225+async fn head_parts(cx: &Cx) -> Result<Response> {
226+ let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
227+ parts_response(cx, &ctx).await
228+}
229+
172230 #[component]
173231 async fn clone_popover(
174232 cx: &Cx,
crates/forge-web-pages/src/pages/star.rsmodified+10 -5
@@ -3,11 +3,13 @@ use serde::Deserialize;
33 use topcoat::Result;
44 use topcoat::context::{Cx, context};
55 use topcoat::router::content::Form;
6-use topcoat::router::error::{SeeOther, see_other};
6+use topcoat::router::error::see_other;
77 use topcoat::router::request::headers;
8+use topcoat::router::response::{IntoResponse, Response};
89 use topcoat::router::{path_param, route};
910
1011 use crate::auth::{require_csrf, safe_next};
12+use crate::pages::repo::{parts_response, wants_parts};
1113 use crate::pages::repo_ctx::load_repo;
1214 use crate::state::AppState;
1315 use crate::views::repo_href;
@@ -22,16 +24,16 @@ struct StarForm {
2224 }
2325
2426 #[route(POST "/{owner}/{repo}/star")]
25-async fn star_post(cx: &Cx, Form(form): Form<StarForm>) -> Result<SeeOther> {
27+async fn star_post(cx: &Cx, Form(form): Form<StarForm>) -> Result<Response> {
2628 set_starred(cx, &form.csrf, true).await
2729 }
2830
2931 #[route(POST "/{owner}/{repo}/unstar")]
30-async fn unstar_post(cx: &Cx, Form(form): Form<StarForm>) -> Result<SeeOther> {
32+async fn unstar_post(cx: &Cx, Form(form): Form<StarForm>) -> Result<Response> {
3133 set_starred(cx, &form.csrf, false).await
3234 }
3335
34-async fn set_starred(cx: &Cx, csrf: &str, starred: bool) -> Result<SeeOther> {
36+async fn set_starred(cx: &Cx, csrf: &str, starred: bool) -> Result<Response> {
3537 let owner = owner(cx);
3638 let name = repo(cx);
3739 let ctx = load_repo(cx, owner, name).await?;
@@ -44,8 +46,11 @@ async fn set_starred(cx: &Cx, csrf: &str, starred: bool) -> Result<SeeOther> {
4446 }
4547 state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id);
4648 state.live.bump(&crate::live::Topic::User(user.id.clone()));
49+ if wants_parts(cx) {
50+ return parts_response(cx, &ctx).await;
51+ }
4752 let home = repo_href(&ctx.repo.owner_name, &ctx.repo.name, "", "");
48- Ok(see_other(return_path(cx).unwrap_or(home)))
53+ see_other(return_path(cx).unwrap_or(home)).into_response(cx)
4954 }
5055
5156 pub fn return_path(cx: &Cx) -> Option<String> {
crates/forge-web-repo/src/pages/issue_view.rsmodified+1 -0
@@ -81,6 +81,7 @@ async fn issue_page(
8181 text: state_text.to_owned(),
8282 href: None,
8383 class: state_class,
84+ part: None,
8485 },
8586 SubPart::link(author.clone(), user_href(&author_login)),
8687 SubPart::text(opened.relative.clone()),
crates/forge-web-repo/src/pages/repo_settings_live_tests.rsmodified+4 -1
@@ -116,7 +116,10 @@ async fn a_settings_write_wakes_the_open_settings_stream() {
116116 .await;
117117 assert_eq!(status, 303);
118118 let changed = frames.next().await.expect("a frame").expect("data");
119- assert_eq!(&changed[..], b"event: changed\ndata: 1\n\n");
119+ assert_eq!(
120+ &crate::test_support::fixture::seq_free(&changed)[..],
121+ b"event: changed\ndata: 1\n\n"
122+ );
120123 }
121124
122125 #[tokio::test]
crates/forge-web/assets/nav.jsmodified+62 -5
@@ -13,6 +13,12 @@
1313 var userBusy = 0; // navigations and form posts on the wire (not live refreshes)
1414 var liveDirty = false; // a live change came while a navigation or a live fetch was on the wire
1515 var liveForced = false; // that change re-renders the page even with no stream of its own
16+ var liveWant = 0; // newest live sequence a change asked for
17+ var liveAny = 0; // changes without a sequence so far
18+ var shownAny = 0; // how many of those the shown page covers
19+ var pageSeq = Number(root.getAttribute('data-live-seq')) || 0; // live sequence the shown page was rendered at
20+ var headBusy = false; // a head-part fetch is on the wire
21+ var headAgain = false; // a head event came during that fetch: fetch once more after it
1622 var liveBusy = false; // a live fetch is on the wire: later changes wait for it, then share one fetch
1723 var inFlight = 0; // requests on the wire, drives aria-busy
1824 var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored
@@ -177,10 +183,11 @@
177183
178184 function adopt(doc, keepFields, dd, jobs, logs) {
179185 document.title = doc.title;
180- ['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) {
186+ ['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) {
181187 if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); }
182188 else { root.removeAttribute(name); }
183189 });
190+ pageSeq = Number(root.getAttribute('data-live-seq')) || 0;
184191 syncStyles(doc);
185192 var kept = keepFields ? captureFields() : null;
186193 var nodes = Array.prototype.map.call(doc.body.childNodes, function (n) { return document.importNode(n, true); });
@@ -414,6 +421,40 @@
414421 else { window.scrollTo(0, 0); }
415422 }
416423
424+ function focusables(el) {
425+ return Array.prototype.filter.call(el.querySelectorAll('a[href], button, input, select, textarea'), function (n) { return !n.disabled; });
426+ }
427+
428+ // Replaces each [data-part] element of the page with the one of the same name in `html`. Focus inside
429+ // a replaced part moves to the same-index control of the new part. The URL and the page stay.
430+ function swapParts(html) {
431+ var doc = new DOMParser().parseFromString(html, 'text/html');
432+ Array.prototype.forEach.call(doc.querySelectorAll('[data-part]'), function (part) {
433+ var old = document.querySelector('[data-part="' + part.getAttribute('data-part') + '"]');
434+ if (!old) { return; }
435+ var at = old.contains(document.activeElement) ? focusables(old).indexOf(document.activeElement) : -1;
436+ var next = document.importNode(part, true);
437+ old.replaceWith(next);
438+ var target = at >= 0 ? focusables(next)[at] : null;
439+ if (target) { target.focus(); }
440+ });
441+ }
442+
443+ // A head part fetch: one in flight at a time. A head event that comes meanwhile is fetched once more after it.
444+ function fetchHead(url) {
445+ if (headBusy) { headAgain = true; return; }
446+ headBusy = true;
447+ fetch(url, { headers: { accept: 'text/html', 'x-forge-parts': '1' }, credentials: 'same-origin' }).then(function (r) {
448+ return r.status < 400 ? r.text() : null;
449+ }).then(function (html) {
450+ var head = document.querySelector('[data-parts]');
451+ if (html !== null && head && head.getAttribute('data-parts') === url) { swapParts(html); }
452+ }).catch(function () { }).then(function () {
453+ headBusy = false;
454+ if (headAgain) { headAgain = false; fetchHead(url); }
455+ });
456+ }
457+
417458 // A live change keeps the reader's place in a diff. Before the swap: the first element marked
418459 // data-keep-anchor (a diff file, keyed by its path) that is still at least partly in view, and
419460 // its offset from the top of the view. After the swap: the same key, moved so it sits at that
@@ -525,6 +566,7 @@
525566 // how, keep (keep fields on a re-render of the same path), post, and the form for a POST or GET form.
526567 function load(o) {
527568 var mark = ++latest;
569+ o.anyAt = liveAny;
528570 var user = o.how !== 'live';
529571 if (user) { userBusy += 1; clearNote(); }
530572 busyStart();
@@ -536,7 +578,7 @@
536578 if (final.origin !== location.origin || !html) {
537579 return { leave: true, url: final, redirected: r.redirected };
538580 }
539- return r.text().then(function (text) { return { html: text, url: final, status: r.status, redirected: r.redirected }; });
581+ return r.text().then(function (text) { return { html: text, url: final, status: r.status, redirected: r.redirected, parts: r.headers.has('x-forge-parts') }; });
540582 }, function () {
541583 // No answer at all: the server is down.
542584 return { down: true };
@@ -552,6 +594,7 @@
552594 if (res.status === 404) { showGone(); }
553595 return;
554596 }
597+ if (o.post && res.parts && res.status < 400) { swapParts(res.html); return; }
555598 var dest = new URL(res.url.href);
556599 dest.hash = o.dest.hash;
557600 // A form the server refused comes back as a page under the POST's URL, which may have no GET.
@@ -565,6 +608,7 @@
565608 var how = o.how === 'live' && res.url.pathname !== o.target.pathname ? 'nav' : o.how;
566609 var keep = !!o.keep && res.url.pathname === o.target.pathname;
567610 var finish = function () {
611+ shownAny = Math.max(shownAny, o.anyAt);
568612 swap(res.html, dest, how, keep);
569613 if (pal.find) { paletteLand(); }
570614 // Other parts of this file follow page changes through this event (list memory, say).
@@ -581,7 +625,7 @@
581625 // A POST counts as done only when the server answered with a redirect to a page: the
582626 // post-redirect-get every successful form here ends in. Drafts listen for it.
583627 var r = o.result;
584- var ok = mark === latest && !!(r && r.html && r.redirected && r.status < 400);
628+ var ok = mark === latest && !!(r && r.html && (r.redirected || r.parts) && r.status < 400);
585629 document.dispatchEvent(new CustomEvent('forge:submitted', { detail: { form: o.form, ok: ok } }));
586630 }
587631 if (o.form) { pending.delete(o.form); }
@@ -665,7 +709,7 @@
665709 var o = link.pending;
666710 link.pending = null;
667711 if (o) { hideBar(); load(o); return; }
668- refreshLive();
712+ refreshLive(true);
669713 if (link.post) { showBar(linkText('back')); } else { hideBar(); }
670714 }
671715
@@ -1102,13 +1146,15 @@
11021146 }
11031147
11041148 var multipart = (form.enctype || '').toLowerCase().indexOf('multipart') === 0;
1149+ var headers = { accept: 'text/html' };
1150+ if (form.closest('[data-part]')) { headers['x-forge-parts'] = '1'; }
11051151 submitStart(form, submitter);
11061152 load({
11071153 target: withoutHash(url),
11081154 dest: url,
11091155 init: {
11101156 method: 'POST',
1111- headers: { accept: 'text/html' },
1157+ headers: headers,
11121158 body: multipart ? data : new URLSearchParams(data)
11131159 },
11141160 how: 'post',
@@ -2640,6 +2686,15 @@
26402686 var job = document.querySelector('[data-live-log]');
26412687 var wrap = job ? job.closest('[data-live]') : null;
26422688 if (wrap && wrap.getAttribute('data-live-state') === e.data) { return; }
2689+ var m = /^(\d+)( head)?$/.exec(e.data);
2690+ if (m) {
2691+ if (Number(m[1]) <= pageSeq) { return; }
2692+ var head = m[2] ? document.querySelector('[data-parts]') : null;
2693+ if (head) { fetchHead(head.getAttribute('data-parts')); return; }
2694+ liveWant = Math.max(liveWant, Number(m[1]));
2695+ } else {
2696+ liveAny += 1;
2697+ }
26432698 // A code view or an issue page re-renders at once (data-live-now). Events that come while a fetch
26442699 // is on the wire share the next one.
26452700 if (document.querySelector('[data-live-code], [data-live-now]')) { refreshLive(); return; }
@@ -2759,6 +2814,8 @@
27592814 if (document.querySelector('[data-once]')) { return; }
27602815 // A rejected form is on screen: a re-render would replace its error. See load().
27612816 if (heldForm) { return; }
2817+ // Only sequence changes the page already shows are pending: nothing to render.
2818+ if (!force && liveAny <= shownAny && liveWant <= pageSeq) { liveDirty = false; return; }
27622819 if (userBusy > 0 || liveBusy || selecting()) { liveDirty = true; if (force) { liveForced = true; } return; }
27632820 liveDirty = false;
27642821 liveForced = false;
crates/forge-web/src/boot.rsmodified+1 -0
@@ -163,6 +163,7 @@ pub async fn serve(
163163 .layer(TowerLayer::new(
164164 forge_web_app::compression::ResponseCompression,
165165 ))
166+ .layer(forge_web_app::layers::LiveSeqLayer)
166167 .with(Compression::disable())
167168 .build();
168169 let internal_router = internal::router(state.clone());
crates/forge-web/src/routes.snapmodified+1 -0
@@ -328,6 +328,7 @@ route /{owner}/{repo}/issues/{number}/subscription Only([POST])
328328 route /{owner}/{repo}/issues/{number}/tasks Only([POST])
329329 route /{owner}/{repo}/labels.css Only([GET])
330330 route /{owner}/{repo}/merge-queue/events Only([GET])
331+route /{owner}/{repo}/parts/head Only([GET])
331332 route /{owner}/{repo}/paths/{*rest} Only([GET])
332333 route /{owner}/{repo}/pulls/events Only([GET])
333334 route /{owner}/{repo}/pulls/{number}/auto-merge Only([POST])
style/_min.scssmodified+4 -0
@@ -254,6 +254,10 @@ summary.act {
254254 margin: 0;
255255 }
256256
257+.head-actions {
258+ display: contents;
259+}
260+
257261 // An action that opens in place. Its panel takes a line of its own under the links beside it.
258262
259263 .reveal {
style/_one.scssmodified+1 -0
@@ -3546,6 +3546,7 @@ details.log-group {
35463546 // keeps its red word on the pill. What opens from a reveal keeps its own kit.
35473547 .head-title > :is(a.act, button.act),
35483548 .head-title > form.act-form > button.act,
3549+.head-actions > form.act-form > button.act,
35493550 .head-title > details.reveal > summary.act {
35503551 display: inline-flex;
35513552 align-items: center;
style/_one_shell.scssmodified+3 -3
@@ -144,7 +144,7 @@ a > .ref-chip,
144144
145145 // Beside a repo title, the watch button is one of the head's pills: the same height, radius, fill,
146146 // and 600 text as Star and Fork. The caret keeps its place at the end.
147-.head-title > .watch-control .watch-menu > summary {
147+.head-actions > .watch-control .watch-menu > summary {
148148 box-sizing: border-box;
149149 padding: 0 30px 0 18px;
150150 font-size: 15px;
@@ -191,14 +191,14 @@ a > .ref-chip,
191191 }
192192
193193 // In the head the watcher count is in the line under the title, so the watch pill stands alone.
194-.head-title > .watch-control > .hint {
194+.head-actions > .watch-control > .hint {
195195 display: none;
196196 }
197197
198198 // On a phone the watch pill is its eye and chevron, so it shares the title's line with Star; its
199199 // level stays in the summary's label.
200200 @media (max-width: 700px) {
201- .head-title > .watch-control .watch-menu > summary > span {
201+ .head-actions > .watch-control .watch-menu > summary > span {
202202 display: none;
203203 }
204204 }