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 {
458 .map_err(|e| format!("artifacts: {e}"))?;458 .map_err(|e| format!("artifacts: {e}"))?;
459 for artifact in &found {459 for artifact in &found {
460 patiently(&job.job_id, "artifact upload", || {460 patiently(&job.job_id, "artifact upload", || {
461- self.client461+ self.client.upload_artifact(
462- .upload_artifact(&job.job_id, &job.job_token, &artifact.name, &artifact.path)462+ &job.job_id,
463+ &job.job_token,
464+ &artifact.name,
465+ &artifact.path,
466+ )
463 })467 })
464 .await468 .await
465 .map_err(|e| format!("artifact {}: {e}", artifact.name))?;469 .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(
460 text: needs_attention(lang, attention),460 text: needs_attention(lang, attention),
461 href: None,461 href: None,
462 class: "b health-sum bad",462 class: "b health-sum bad",
463+ part: None,
463 }464 }
464 } else {465 } else {
465 SubPart {466 SubPart {
466 text: at(lang, A::Fine).to_owned(),467 text: at(lang, A::Fine).to_owned(),
467 href: None,468 href: None,
468 class: "b health-sum ok",469 class: "b health-sum ok",
470+ part: None,
469 }471 }
470 };472 };
471 let sub = vec![summary];473 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};
11 use crate::auth::SESSION_COOKIE;11 use crate::auth::SESSION_COOKIE;
12 use crate::blobs::asset_key;12 use crate::blobs::asset_key;
13 use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};13 use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};
14+use crate::test_support::fixture::seq_free;
14 use crate::test_support::{app_router, create_session, test_state};15 use crate::test_support::{app_router, create_session, test_state};
15 16
16 const CSRF: &str = "releases-test-csrf";17 const CSRF: &str = "releases-test-csrf";
@@ -980,11 +981,11 @@ async fn live_streams_wake_on_changes_and_hide_drafts() {
980 .await981 .await
981 .expect("edited");982 .expect("edited");
982 assert_eq!(983 assert_eq!(
983- &list.next().await.expect("a frame").expect("data")[..],984+ &seq_free(&list.next().await.expect("a frame").expect("data"))[..],
984 CHANGED985 CHANGED
985 );986 );
986 assert_eq!(987 assert_eq!(
987- &page.next().await.expect("a frame").expect("data")[..],988+ &seq_free(&page.next().await.expect("a frame").expect("data"))[..],
988 CHANGED989 CHANGED
989 );990 );
990 991
@@ -1000,13 +1001,13 @@ async fn live_streams_wake_on_changes_and_hide_drafts() {
1000 .await;1001 .await;
1001 assert_eq!(uploaded.status, 303, "body: {}", uploaded.text());1002 assert_eq!(uploaded.status, 303, "body: {}", uploaded.text());
1002 assert_eq!(1003 assert_eq!(
1003- &list.next().await.expect("a frame").expect("data")[..],1004+ &seq_free(&list.next().await.expect("a frame").expect("data"))[..],
1004 CHANGED1005 CHANGED
1005 );1006 );
1006 let download = fx.download("v1.1/app.tar.gz").await;1007 let download = fx.download("v1.1/app.tar.gz").await;
1007 assert_eq!(download.status, 200);1008 assert_eq!(download.status, 200);
1008 assert_eq!(1009 assert_eq!(
1009- &list.next().await.expect("a frame").expect("data")[..],1010+ &seq_free(&list.next().await.expect("a frame").expect("data"))[..],
1010 CHANGED1011 CHANGED
1011 );1012 );
1012 1013
crates/forge-web-account/src/pages/settings_live.rsmodified+1 -1
@@ -344,7 +344,7 @@ mod tests {
344 live.bump(&Topic::Account(owner.id.clone()));344 live.bump(&Topic::Account(owner.id.clone()));
345 let changed = frames.next().await.expect("a frame").expect("data");345 let changed = frames.next().await.expect("a frame").expect("data");
346 assert_eq!(346 assert_eq!(
347- &changed[..],347+ &crate::test_support::fixture::seq_free(&changed)[..],
348 b"event: changed\ndata: 1\n\n",348 b"event: changed\ndata: 1\n\n",
349 "settings stream: changed event"349 "settings stream: changed event"
350 );350 );
crates/forge-web-app/src/ci/live.rsmodified+2 -0
@@ -114,6 +114,7 @@ impl Signals {
114 }114 }
115 115
116 pub fn bump(&self, key: &str) {116 pub fn bump(&self, key: &str) {
117+ crate::live::next_live_seq();
117 let mut counters = self.counters();118 let mut counters = self.counters();
118 let Some(tx) = counters.get(key) else {119 let Some(tx) = counters.get(key) else {
119 return;120 return;
@@ -125,6 +126,7 @@ impl Signals {
125 }126 }
126 127
127 fn close(&self, key: &str) {128 fn close(&self, key: &str) {
129+ crate::live::next_live_seq();
128 let removed = self.counters().remove(key);130 let removed = self.counters().remove(key);
129 if let Some(tx) = removed {131 if let Some(tx) = removed {
130 tx.send_modify(|generation| *generation = generation.wrapping_add(1));132 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};
7 use crate::live::Topic;7 use crate::live::Topic;
8 use crate::state::AppState;8 use crate::state::AppState;
9 9
10+pub use live_seq::LiveSeqLayer;
10 pub use not_found_layer::NotFoundLayer;11 pub use not_found_layer::NotFoundLayer;
11 pub use org_write::OrgWriteLayer;12 pub use org_write::OrgWriteLayer;
12 pub use pull_write::PullWriteLayer;13 pub use pull_write::PullWriteLayer;
@@ -392,6 +393,32 @@ mod repo_settings_write {
392 }393 }
393 }394 }
394 395
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+
395 mod not_found_layer {422 mod not_found_layer {
396 use http::header::ACCEPT;423 use http::header::ACCEPT;
397 use topcoat::Result;424 use topcoat::Result;
crates/forge-web-app/src/live.rsmodified+74 -14
@@ -1,5 +1,6 @@
1 use std::collections::HashMap;1 use std::collections::HashMap;
2 use std::future::Future;2 use std::future::Future;
3+use std::sync::atomic::{AtomicU64, Ordering};
3 use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};4 use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
4 use std::time::Duration;5 use std::time::Duration;
5 6
@@ -46,6 +47,27 @@ pub fn admin() -> &'static LiveHub {
46 ADMIN.get_or_init(LiveHub::default)47 ADMIN.get_or_init(LiveHub::default)
47 }48 }
48 49
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+
49 #[derive(Default)]71 #[derive(Default)]
50 pub struct LiveHub {72 pub struct LiveHub {
51 topics: Mutex<HashMap<Topic, watch::Sender<u64>>>,73 topics: Mutex<HashMap<Topic, watch::Sender<u64>>>,
@@ -66,6 +88,7 @@ impl LiveHub {
66 }88 }
67 89
68 pub fn bump(&self, topic: &Topic) {90 pub fn bump(&self, topic: &Topic) {
91+ next_live_seq();
69 let mut topics = self.topics();92 let mut topics = self.topics();
70 let Some(tx) = topics.get(topic) else {93 let Some(tx) = topics.get(topic) else {
71 return;94 return;
@@ -94,18 +117,23 @@ impl LiveHub {
94 }117 }
95 }118 }
96 119
97-struct Follow<F> {120+struct Follow<T, F> {
98 wakes: Vec<watch::Receiver<u64>>,121 wakes: Vec<watch::Receiver<u64>>,
99 read: F,122 read: F,
100- last: String,123+ last: T,
124+ diff: Diff<T>,
101 }125 }
102 126
103-fn wake_event() -> Result<Event> {127+type Diff<T> = fn(&T, &T) -> Option<&'static str>;
104- Ok(Event::new().event("changed").data("1"))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())))
105 }133 }
106 134
107-fn named_event(name: &'static str) -> Result<Event> {135+fn wake_event() -> Result<Event> {
108- Ok(Event::new().event(name).data("1"))136+ named_event("changed", "")
109 }137 }
110 138
111 async fn wait_any(wakes: &mut [watch::Receiver<u64>]) -> bool {139 async fn wait_any(wakes: &mut [watch::Receiver<u64>]) -> bool {
@@ -149,27 +177,59 @@ where
149 F: Fn() -> Fut + Send + 'static,177 F: Fn() -> Fut + Send + 'static,
150 Fut: Future<Output = Result<String>> + Send,178 Fut: Future<Output = Result<String>> + Send,
151 {179 {
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?;
153 events_response(cx, events)182 events_response(cx, events)
154 }183 }
155 184
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>(
157 hub: &LiveHub,210 hub: &LiveHub,
158 topics: Vec<Topic>,211 topics: Vec<Topic>,
159 extra: Vec<watch::Receiver<u64>>,212 extra: Vec<watch::Receiver<u64>>,
160 name: &'static str,213 name: &'static str,
161 read: F,214 read: F,
215+ diff: Diff<T>,
162 ) -> Result<impl Stream<Item = Result<Event>> + Send + 'static>216 ) -> Result<impl Stream<Item = Result<Event>> + Send + 'static>
163 where217 where
218+ T: Send + 'static,
164 F: Fn() -> Fut + Send + 'static,219 F: Fn() -> Fut + Send + 'static,
165- Fut: Future<Output = Result<String>> + Send,220+ Fut: Future<Output = Result<T>> + Send,
166 {221 {
167 let mut wakes: Vec<watch::Receiver<u64>> =222 let mut wakes: Vec<watch::Receiver<u64>> =
168 topics.iter().map(|topic| hub.subscribe(topic)).collect();223 topics.iter().map(|topic| hub.subscribe(topic)).collect();
169 wakes.extend(extra);224 wakes.extend(extra);
170 let last = read().await?;225 let last = read().await?;
171 Ok(stream::unfold(226 Ok(stream::unfold(
172- Follow { wakes, read, last },227+ Follow {
228+ wakes,
229+ read,
230+ last,
231+ diff,
232+ },
173 move |mut follow| async move {233 move |mut follow| async move {
174 loop {234 loop {
175 if !wait_any(&mut follow.wakes).await {235 if !wait_any(&mut follow.wakes).await {
@@ -182,11 +242,11 @@ where
182 return None;242 return None;
183 }243 }
184 };244 };
185- if now == follow.last {245+ let suffix = (follow.diff)(&follow.last, &now);
186- continue;
187- }
188 follow.last = now;246 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+ }
190 }250 }
191 },251 },
192 ))252 ))
crates/forge-web-app/src/mail/live.rsmodified+1 -0
@@ -13,6 +13,7 @@ pub fn subscribe() -> watch::Receiver<u64> {
13 }13 }
14 14
15 pub fn bump() {15 pub fn bump() {
16+ crate::live::next_live_seq();
16 sender().send_modify(|generation| *generation = generation.wrapping_add(1));17 sender().send_modify(|generation| *generation = generation.wrapping_add(1));
17 crate::live::admin().bump(&crate::live::Topic::AdminHealth);18 crate::live::admin().bump(&crate::live::Topic::AdminHealth);
18 }19 }
crates/forge-web-app/src/test_support/fixture.rsmodified+16 -1
@@ -228,7 +228,22 @@ where
228 loop {228 loop {
229 let bytes = next_frame(frames).await?;229 let bytes = next_frame(frames).await?;
230 if !bytes.starts_with(b"retry: ") {230 if !bytes.starts_with(b"retry: ") {
231- return Some(bytes);231+ return Some(seq_free(&bytes));
232 }232 }
233 }233 }
234 }234 }
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 {
103 .layer(crate::layers::PullWriteLayer)103 .layer(crate::layers::PullWriteLayer)
104 .layer(crate::layers::OrgWriteLayer)104 .layer(crate::layers::OrgWriteLayer)
105 .layer(TowerLayer::new(crate::compression::ResponseCompression))105 .layer(TowerLayer::new(crate::compression::ResponseCompression))
106+ .layer(crate::layers::LiveSeqLayer)
106 .with(Compression::disable())107 .with(Compression::disable())
107 .build()108 .build()
108 }109 }
crates/forge-web-app/src/views/mod.rsmodified+3 -1
@@ -41,6 +41,7 @@ use crate::i18n::misc::{self as mi, K as MK};
41 use crate::i18n::orgs::{self as o, K as OK};41 use crate::i18n::orgs::{self as o, K as OK};
42 use crate::i18n::s;42 use crate::i18n::s;
43 use crate::i18n::{self, Key, Lang, t};43 use crate::i18n::{self, Key, Lang, t};
44+use crate::live::LiveSeq;
44 use crate::render::highlight::highlight_css;45 use crate::render::highlight::highlight_css;
45 use crate::state::AppState;46 use crate::state::AppState;
46 use crate::theme::Theme;47 use crate::theme::Theme;
@@ -613,9 +614,10 @@ pub async fn shell(
613 unread,614 unread,
614 waiting: inbox.reviews + inbox.mentions + runs.failing > 0,615 waiting: inbox.reviews + inbox.mentions + runs.failing > 0,
615 });616 });
617+ let live_seq = try_context::<LiveSeq>(cx).map(|seq| seq.0.to_string());
616 Ok(view! {618 Ok(view! {
617 <!DOCTYPE html>619 <!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())>
619 <head>621 <head>
620 <meta charset="utf-8">622 <meta charset="utf-8">
621 <meta name="viewport" content="width=device-width, initial-scale=1">623 <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 {
226 pub text: String,226 pub text: String,
227 pub href: Option<String>,227 pub href: Option<String>,
228 pub class: &'static str,228 pub class: &'static str,
229+ pub part: Option<&'static str>,
229 }230 }
230 231
231 impl SubPart {232 impl SubPart {
233+ pub fn with_part(mut self, part: &'static str) -> Self {
234+ self.part = Some(part);
235+ self
236+ }
237+
232 pub fn text(text: impl Into<String>) -> Self {238 pub fn text(text: impl Into<String>) -> Self {
233 Self {239 Self {
234 text: text.into(),240 text: text.into(),
@@ -261,6 +267,18 @@ impl SubPart {
261 }267 }
262 }268 }
263 269
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+
264 #[component]282 #[component]
265 pub async fn head_sub(283 pub async fn head_sub(
266 cx: &Cx,284 cx: &Cx,
@@ -278,11 +296,7 @@ pub async fn head_sub(
278 if n > 0 {296 if n > 0 {
279 <span class="sep" aria-hidden="true">"·"</span>297 <span class="sep" aria-hidden="true">"·"</span>
280 }298 }
281- if let Some(href) = part.href {299+ sub_part(part: part)
282- <a class=(part.class) href=(href)>(part.text)</a>
283- } else {
284- <span class=(part.class)>(part.text)</span>
285- }
286 }300 }
287 if has_pips {301 if has_pips {
288 <span class="pips">302 <span class="pips">
crates/forge-web-pages/src/pages/code_live.rsmodified+7 -7
@@ -8,7 +8,7 @@ use topcoat::router::response::Response;
8 use topcoat::router::{path_param, query_params, route};8 use topcoat::router::{path_param, query_params, route};
9 9
10 use crate::auth::percent_encode;10 use crate::auth::percent_encode;
11-use crate::live::{Topic, stream_changes_with};11+use crate::live::{Topic, stream_changes_split};
12 use crate::pages::refs::load_refs;12 use crate::pages::refs::load_refs;
13 use crate::pages::repo_ctx::{fork_count, load_repo};13 use crate::pages::repo_ctx::{fork_count, load_repo};
14 use crate::pages::repo_side::runs_fingerprint;14 use crate::pages::repo_side::runs_fingerprint;
@@ -148,7 +148,7 @@ async fn repo_events(cx: &Cx) -> Result<Response> {
148 };148 };
149 let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone());149 let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone());
150 let path = ctx.path.clone();150 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 || {
152 let state = state.clone();152 let state = state.clone();
153 let repo_id = repo_id.clone();153 let repo_id = repo_id.clone();
154 let path = path.clone();154 let path = path.clone();
@@ -156,17 +156,17 @@ async fn repo_events(cx: &Cx) -> Result<Response> {
156 let viewer = viewer.clone();156 let viewer = viewer.clone();
157 async move {157 async move {
158 let viewer_id = viewer.as_ref().map(|user| user.id.as_str());158 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();
160 if !branch.is_empty() {161 if !branch.is_empty() {
161- let refs = refs_fingerprint(path, branch).await?;162+ rest = refs_fingerprint(path, branch).await?;
162- out = format!("{out}\n{refs}");
163 }163 }
164 if home {164 if home {
165 let extra = home_fingerprint(&state, &repo_id).await?;165 let extra = home_fingerprint(&state, &repo_id).await?;
166 let runs = runs_fingerprint(&state, &repo_id).await?;166 let runs = runs_fingerprint(&state, &repo_id).await?;
167- out = format!("{out}\n{extra}\n{runs}");167+ rest = format!("{rest}\n{extra}\n{runs}");
168 }168 }
169- Ok(out)169+ Ok((head, rest))
170 }170 }
171 })171 })
172 .await172 .await
crates/forge-web-pages/src/pages/notifications.rsmodified+7 -8
@@ -11,7 +11,7 @@ use topcoat::context::{Cx, context};
11 use topcoat::router::content::Form;11 use topcoat::router::content::Form;
12 use topcoat::router::content::sse::Event;12 use topcoat::router::content::sse::Event;
13 use topcoat::router::error::{SeeOther, bad_request, not_found, see_other};13 use topcoat::router::error::{SeeOther, bad_request, not_found, see_other};
14-use topcoat::router::response::Response;14+use topcoat::router::response::{IntoResponse, Response};
15 use topcoat::router::{Body, StatusCode, page, path_param, query_params, route};15 use topcoat::router::{Body, StatusCode, page, path_param, query_params, route};
16 use topcoat::view::{View, component, view};16 use topcoat::view::{View, component, view};
17 17
@@ -23,6 +23,7 @@ use crate::live::events_response;
23 use crate::live::{Topic, stream_changes};23 use crate::live::{Topic, stream_changes};
24 use crate::notify_hub::publish_unread;24 use crate::notify_hub::publish_unread;
25 use crate::pages::issue_parts::parse_number;25 use crate::pages::issue_parts::parse_number;
26+use crate::pages::repo::{parts_response, wants_parts};
26 use crate::pages::repo_ctx::{RepoCtx, load_repo};27 use crate::pages::repo_ctx::{RepoCtx, load_repo};
27 use crate::pages::repo_transfer::transfer_list_for;28 use crate::pages::repo_transfer::transfer_list_for;
28 use crate::pages::star::return_path;29 use crate::pages::star::return_path;
@@ -569,7 +570,7 @@ async fn set_subscription(cx: &Cx, pull: bool, form: &SubscriptionForm) -> Resul
569 }570 }
570 571
571 #[route(POST "/{owner}/{repo}/watch")]572 #[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> {
573 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;574 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
574 let (user, _) = require_csrf(cx, &form.csrf).await?;575 let (user, _) = require_csrf(cx, &form.csrf).await?;
575 let level = match form.level.as_str() {576 let level = match form.level.as_str() {
@@ -581,12 +582,10 @@ async fn set_watch(cx: &Cx, Form(form): Form<WatchForm>) -> Result<SeeOther> {
581 let state = context::<AppState>(cx);582 let state = context::<AppState>(cx);
582 state.store.set_watch(&user.id, &ctx.repo.id, level).await?;583 state.store.set_watch(&user.id, &ctx.repo.id, level).await?;
583 state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id);584 state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id);
584- Ok(see_other(repo_href(585+ if wants_parts(cx) {
585- &ctx.repo.owner_name,586+ return parts_response(cx, &ctx).await;
586- &ctx.repo.name,587+ }
587- "",588+ see_other(repo_href(&ctx.repo.owner_name, &ctx.repo.name, "", "")).into_response(cx)
588- "",
589- )))
590 }589 }
591 590
592 pub async fn repo_allows(591 pub async fn repo_allows(
crates/forge-web-pages/src/pages/ref_live.rsmodified+8 -2
@@ -78,7 +78,10 @@ mod tests {
78 .expect("woken")78 .expect("woken")
79 .expect("a frame")79 .expect("a frame")
80 .expect("data");80 .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+ );
82 85
83 fx.live.bump(&Topic::CommitStatuses(repo.id.clone()));86 fx.live.bump(&Topic::CommitStatuses(repo.id.clone()));
84 let second = tokio::time::timeout(Duration::from_secs(5), frames.next())87 let second = tokio::time::timeout(Duration::from_secs(5), frames.next())
@@ -86,7 +89,10 @@ mod tests {
86 .expect("woken")89 .expect("woken")
87 .expect("a frame")90 .expect("a frame")
88 .expect("data");91 .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+ );
90 }96 }
91 97
92 #[tokio::test]98 #[tokio::test]
crates/forge-web-pages/src/pages/repo.rsmodified+112 -54
@@ -7,9 +7,12 @@ use forge_core::WatchLevel;
7 use forge_core::time::stamp_ago;7 use forge_core::time::stamp_ago;
8 use forge_git::browse;8 use forge_git::browse;
9 use forge_git::repo::repo_path;9 use forge_git::repo::repo_path;
10+use http::{HeaderName, HeaderValue};
10 use topcoat::Result;11 use topcoat::Result;
11 use topcoat::context::{Cx, context};12 use topcoat::context::{Cx, context};
12 use topcoat::router::error::not_found;13 use topcoat::router::error::not_found;
14+use topcoat::router::request::headers;
15+use topcoat::router::response::{IntoResponse, Response};
13 use topcoat::router::{page, path_param, route};16 use topcoat::router::{page, path_param, route};
14 use topcoat::view::{Child, View, ViewExt, component, view};17 use topcoat::view::{Child, View, ViewExt, component, view};
15 18
@@ -26,7 +29,7 @@ use crate::pages::tree::{
26 entry_rows, last_commits, latest_bar, load_readme, read_dir, readme_sheet, tree_table,29 entry_rows, last_commits, latest_bar, load_readme, read_dir, readme_sheet, tree_table,
27 };30 };
28 use crate::state::AppState;31 use crate::state::AppState;
29-use crate::views::parts::{SubPart, head_sub};32+use crate::views::parts::{SubPart, head_sub, sub_part};
30 use crate::views::{33 use crate::views::{
31 https_clone_url, now_unix, ref_selector, relative_time, repo_href, repo_tabs, shell,34 https_clone_url, now_unix, ref_selector, relative_time, repo_href, repo_tabs, shell,
32 ssh_clone_url, stamp_unix, tab_title,35 ssh_clone_url, stamp_unix, tab_title,
@@ -35,6 +38,14 @@ use crate::views::{
35 path_param!(owner);38 path_param!(owner);
36 path_param!(repo);39 path_param!(repo);
37 40
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+
38 #[component]49 #[component]
39 pub async fn repo_head(50 pub async fn repo_head(
40 cx: &Cx,51 cx: &Cx,
@@ -44,6 +55,9 @@ pub async fn repo_head(
44 #[default] pips: Vec<(String, String, &'static str)>,55 #[default] pips: Vec<(String, String, &'static str)>,
45 #[default] child: Child<'_>,56 #[default] child: Child<'_>,
46 ) -> Result<impl View> {57 ) -> Result<impl View> {
58+ let actions = head.clone();
59+ let watching = watching_part(&head);
60+ let forking = forks_part(&head);
47 let RepoHead {61 let RepoHead {
48 owner,62 owner,
49 name,63 name,
@@ -56,14 +70,8 @@ pub async fn repo_head(
56 open_issues,70 open_issues,
57 open_pulls,71 open_pulls,
58 forked_from,72 forked_from,
59- can_fork,
60- stars,
61- star,
62- watchers,
63- watch,
64- forks,
65- live,
66 mirror,73 mirror,
74+ live,
67 lang,75 lang,
68 clone,76 clone,
69 ..77 ..
@@ -73,32 +81,7 @@ pub async fn repo_head(
73 let vis = i18n::visibility_label(lang, visibility);81 let vis = i18n::visibility_label(lang, visibility);
74 let shown_title = title.unwrap_or_else(|| tab_title(lang, active, &name));82 let shown_title = title.unwrap_or_else(|| tab_title(lang, active, &name));
75 let active = active.to_owned();83 let active = active.to_owned();
76- let fork_control = match (can_fork, star.as_ref()) {84+ let parts_href = format!("/{owner}/{name}/parts/head");
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);
102 let mut parts: Vec<SubPart> = Vec::new();85 let mut parts: Vec<SubPart> = Vec::new();
103 if is_code {86 if is_code {
104 if !description.is_empty() {87 if !description.is_empty() {
@@ -107,8 +90,8 @@ pub async fn repo_head(
107 if private {90 if private {
108 parts.push(SubPart::text(vis));91 parts.push(SubPart::text(vis));
109 }92 }
110- parts.push(SubPart::text(watch_count));93+ parts.push(watching);
111- parts.push(SubPart::text(fork_count));94+ parts.push(forking);
112 if let Some((source_owner, source_name)) = forked_from {95 if let Some((source_owner, source_name)) = forked_from {
113 parts.push(SubPart::link(96 parts.push(SubPart::link(
114 format!("{} {source_owner}/{source_name}", g::t(lang, K::ForkedFrom)),97 format!("{} {source_owner}/{source_name}", g::t(lang, K::ForkedFrom)),
@@ -132,28 +115,12 @@ pub async fn repo_head(
132 parts.extend(sub);115 parts.extend(sub);
133 let live_attr = (!live.is_empty()).then(|| live.clone());116 let live_attr = (!live.is_empty()).then(|| live.clone());
134 Ok(view! {117 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())>
136 <div class="head-title">119 <div class="head-title">
137 <h1>(shown_title.as_str())</h1>120 <h1>(shown_title.as_str())</h1>
138 if is_code {121 if is_code {
139 clone_popover(https: clone.https, ssh: clone.ssh, downloads: clone.downloads, lang: lang)122 clone_popover(https: clone.https, ssh: clone.ssh, downloads: clone.downloads, lang: lang)
140- if let Some((action, label, csrf)) = star_control {123+ repo_actions(head: actions)
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- }
157 } else if private {124 } else if private {
158 <span class="hint">(vis)</span>125 <span class="hint">(vis)</span>
159 }126 }
@@ -169,6 +136,97 @@ pub async fn repo_head(
169 .boxed())136 .boxed())
170 }137 }
171 138
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+
172 #[component]230 #[component]
173 async fn clone_popover(231 async fn clone_popover(
174 cx: &Cx,232 cx: &Cx,
crates/forge-web-pages/src/pages/star.rsmodified+10 -5
@@ -3,11 +3,13 @@ use serde::Deserialize;
3 use topcoat::Result;3 use topcoat::Result;
4 use topcoat::context::{Cx, context};4 use topcoat::context::{Cx, context};
5 use topcoat::router::content::Form;5 use topcoat::router::content::Form;
6-use topcoat::router::error::{SeeOther, see_other};6+use topcoat::router::error::see_other;
7 use topcoat::router::request::headers;7 use topcoat::router::request::headers;
8+use topcoat::router::response::{IntoResponse, Response};
8 use topcoat::router::{path_param, route};9 use topcoat::router::{path_param, route};
9 10
10 use crate::auth::{require_csrf, safe_next};11 use crate::auth::{require_csrf, safe_next};
12+use crate::pages::repo::{parts_response, wants_parts};
11 use crate::pages::repo_ctx::load_repo;13 use crate::pages::repo_ctx::load_repo;
12 use crate::state::AppState;14 use crate::state::AppState;
13 use crate::views::repo_href;15 use crate::views::repo_href;
@@ -22,16 +24,16 @@ struct StarForm {
22 }24 }
23 25
24 #[route(POST "/{owner}/{repo}/star")]26 #[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> {
26 set_starred(cx, &form.csrf, true).await28 set_starred(cx, &form.csrf, true).await
27 }29 }
28 30
29 #[route(POST "/{owner}/{repo}/unstar")]31 #[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> {
31 set_starred(cx, &form.csrf, false).await33 set_starred(cx, &form.csrf, false).await
32 }34 }
33 35
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> {
35 let owner = owner(cx);37 let owner = owner(cx);
36 let name = repo(cx);38 let name = repo(cx);
37 let ctx = load_repo(cx, owner, name).await?;39 let ctx = load_repo(cx, owner, name).await?;
@@ -44,8 +46,11 @@ async fn set_starred(cx: &Cx, csrf: &str, starred: bool) -> Result<SeeOther> {
44 }46 }
45 state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id);47 state.live.bump_repo(&ctx.repo.owner_id, &ctx.repo.id);
46 state.live.bump(&crate::live::Topic::User(user.id.clone()));48 state.live.bump(&crate::live::Topic::User(user.id.clone()));
49+ if wants_parts(cx) {
50+ return parts_response(cx, &ctx).await;
51+ }
47 let home = repo_href(&ctx.repo.owner_name, &ctx.repo.name, "", "");52 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)
49 }54 }
50 55
51 pub fn return_path(cx: &Cx) -> Option<String> {56 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(
81 text: state_text.to_owned(),81 text: state_text.to_owned(),
82 href: None,82 href: None,
83 class: state_class,83 class: state_class,
84+ part: None,
84 },85 },
85 SubPart::link(author.clone(), user_href(&author_login)),86 SubPart::link(author.clone(), user_href(&author_login)),
86 SubPart::text(opened.relative.clone()),87 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() {
116 .await;116 .await;
117 assert_eq!(status, 303);117 assert_eq!(status, 303);
118 let changed = frames.next().await.expect("a frame").expect("data");118 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+ );
120 }123 }
121 124
122 #[tokio::test]125 #[tokio::test]
crates/forge-web/assets/nav.jsmodified+62 -5
@@ -13,6 +13,12 @@
13 var userBusy = 0; // navigations and form posts on the wire (not live refreshes)13 var userBusy = 0; // navigations and form posts on the wire (not live refreshes)
14 var liveDirty = false; // a live change came while a navigation or a live fetch was on the wire14 var liveDirty = false; // a live change came while a navigation or a live fetch was on the wire
15 var liveForced = false; // that change re-renders the page even with no stream of its own15 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
16 var liveBusy = false; // a live fetch is on the wire: later changes wait for it, then share one fetch22 var liveBusy = false; // a live fetch is on the wire: later changes wait for it, then share one fetch
17 var inFlight = 0; // requests on the wire, drives aria-busy23 var inFlight = 0; // requests on the wire, drives aria-busy
18 var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored24 var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored
@@ -177,10 +183,11 @@
177 183
178 function adopt(doc, keepFields, dd, jobs, logs) {184 function adopt(doc, keepFields, dd, jobs, logs) {
179 document.title = doc.title;185 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) {
181 if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); }187 if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); }
182 else { root.removeAttribute(name); }188 else { root.removeAttribute(name); }
183 });189 });
190+ pageSeq = Number(root.getAttribute('data-live-seq')) || 0;
184 syncStyles(doc);191 syncStyles(doc);
185 var kept = keepFields ? captureFields() : null;192 var kept = keepFields ? captureFields() : null;
186 var nodes = Array.prototype.map.call(doc.body.childNodes, function (n) { return document.importNode(n, true); });193 var nodes = Array.prototype.map.call(doc.body.childNodes, function (n) { return document.importNode(n, true); });
@@ -414,6 +421,40 @@
414 else { window.scrollTo(0, 0); }421 else { window.scrollTo(0, 0); }
415 }422 }
416 423
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+
417 // A live change keeps the reader's place in a diff. Before the swap: the first element marked458 // A live change keeps the reader's place in a diff. Before the swap: the first element marked
418 // data-keep-anchor (a diff file, keyed by its path) that is still at least partly in view, and459 // data-keep-anchor (a diff file, keyed by its path) that is still at least partly in view, and
419 // its offset from the top of the view. After the swap: the same key, moved so it sits at that460 // its offset from the top of the view. After the swap: the same key, moved so it sits at that
@@ -525,6 +566,7 @@
525 // how, keep (keep fields on a re-render of the same path), post, and the form for a POST or GET form.566 // how, keep (keep fields on a re-render of the same path), post, and the form for a POST or GET form.
526 function load(o) {567 function load(o) {
527 var mark = ++latest;568 var mark = ++latest;
569+ o.anyAt = liveAny;
528 var user = o.how !== 'live';570 var user = o.how !== 'live';
529 if (user) { userBusy += 1; clearNote(); }571 if (user) { userBusy += 1; clearNote(); }
530 busyStart();572 busyStart();
@@ -536,7 +578,7 @@
536 if (final.origin !== location.origin || !html) {578 if (final.origin !== location.origin || !html) {
537 return { leave: true, url: final, redirected: r.redirected };579 return { leave: true, url: final, redirected: r.redirected };
538 }580 }
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') }; });
540 }, function () {582 }, function () {
541 // No answer at all: the server is down.583 // No answer at all: the server is down.
542 return { down: true };584 return { down: true };
@@ -552,6 +594,7 @@
552 if (res.status === 404) { showGone(); }594 if (res.status === 404) { showGone(); }
553 return;595 return;
554 }596 }
597+ if (o.post && res.parts && res.status < 400) { swapParts(res.html); return; }
555 var dest = new URL(res.url.href);598 var dest = new URL(res.url.href);
556 dest.hash = o.dest.hash;599 dest.hash = o.dest.hash;
557 // A form the server refused comes back as a page under the POST's URL, which may have no GET.600 // A form the server refused comes back as a page under the POST's URL, which may have no GET.
@@ -565,6 +608,7 @@
565 var how = o.how === 'live' && res.url.pathname !== o.target.pathname ? 'nav' : o.how;608 var how = o.how === 'live' && res.url.pathname !== o.target.pathname ? 'nav' : o.how;
566 var keep = !!o.keep && res.url.pathname === o.target.pathname;609 var keep = !!o.keep && res.url.pathname === o.target.pathname;
567 var finish = function () {610 var finish = function () {
611+ shownAny = Math.max(shownAny, o.anyAt);
568 swap(res.html, dest, how, keep);612 swap(res.html, dest, how, keep);
569 if (pal.find) { paletteLand(); }613 if (pal.find) { paletteLand(); }
570 // Other parts of this file follow page changes through this event (list memory, say).614 // Other parts of this file follow page changes through this event (list memory, say).
@@ -581,7 +625,7 @@
581 // A POST counts as done only when the server answered with a redirect to a page: the625 // A POST counts as done only when the server answered with a redirect to a page: the
582 // post-redirect-get every successful form here ends in. Drafts listen for it.626 // post-redirect-get every successful form here ends in. Drafts listen for it.
583 var r = o.result;627 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);
585 document.dispatchEvent(new CustomEvent('forge:submitted', { detail: { form: o.form, ok: ok } }));629 document.dispatchEvent(new CustomEvent('forge:submitted', { detail: { form: o.form, ok: ok } }));
586 }630 }
587 if (o.form) { pending.delete(o.form); }631 if (o.form) { pending.delete(o.form); }
@@ -665,7 +709,7 @@
665 var o = link.pending;709 var o = link.pending;
666 link.pending = null;710 link.pending = null;
667 if (o) { hideBar(); load(o); return; }711 if (o) { hideBar(); load(o); return; }
668- refreshLive();712+ refreshLive(true);
669 if (link.post) { showBar(linkText('back')); } else { hideBar(); }713 if (link.post) { showBar(linkText('back')); } else { hideBar(); }
670 }714 }
671 715
@@ -1102,13 +1146,15 @@
1102 }1146 }
1103 1147
1104 var multipart = (form.enctype || '').toLowerCase().indexOf('multipart') === 0;1148 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'; }
1105 submitStart(form, submitter);1151 submitStart(form, submitter);
1106 load({1152 load({
1107 target: withoutHash(url),1153 target: withoutHash(url),
1108 dest: url,1154 dest: url,
1109 init: {1155 init: {
1110 method: 'POST',1156 method: 'POST',
1111- headers: { accept: 'text/html' },1157+ headers: headers,
1112 body: multipart ? data : new URLSearchParams(data)1158 body: multipart ? data : new URLSearchParams(data)
1113 },1159 },
1114 how: 'post',1160 how: 'post',
@@ -2640,6 +2686,15 @@
2640 var job = document.querySelector('[data-live-log]');2686 var job = document.querySelector('[data-live-log]');
2641 var wrap = job ? job.closest('[data-live]') : null;2687 var wrap = job ? job.closest('[data-live]') : null;
2642 if (wrap && wrap.getAttribute('data-live-state') === e.data) { return; }2688 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+ }
2643 // A code view or an issue page re-renders at once (data-live-now). Events that come while a fetch2698 // A code view or an issue page re-renders at once (data-live-now). Events that come while a fetch
2644 // is on the wire share the next one.2699 // is on the wire share the next one.
2645 if (document.querySelector('[data-live-code], [data-live-now]')) { refreshLive(); return; }2700 if (document.querySelector('[data-live-code], [data-live-now]')) { refreshLive(); return; }
@@ -2759,6 +2814,8 @@
2759 if (document.querySelector('[data-once]')) { return; }2814 if (document.querySelector('[data-once]')) { return; }
2760 // A rejected form is on screen: a re-render would replace its error. See load().2815 // A rejected form is on screen: a re-render would replace its error. See load().
2761 if (heldForm) { return; }2816 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; }
2762 if (userBusy > 0 || liveBusy || selecting()) { liveDirty = true; if (force) { liveForced = true; } return; }2819 if (userBusy > 0 || liveBusy || selecting()) { liveDirty = true; if (force) { liveForced = true; } return; }
2763 liveDirty = false;2820 liveDirty = false;
2764 liveForced = false;2821 liveForced = false;
crates/forge-web/src/boot.rsmodified+1 -0
@@ -163,6 +163,7 @@ pub async fn serve(
163 .layer(TowerLayer::new(163 .layer(TowerLayer::new(
164 forge_web_app::compression::ResponseCompression,164 forge_web_app::compression::ResponseCompression,
165 ))165 ))
166+ .layer(forge_web_app::layers::LiveSeqLayer)
166 .with(Compression::disable())167 .with(Compression::disable())
167 .build();168 .build();
168 let internal_router = internal::router(state.clone());169 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])
328 route /{owner}/{repo}/issues/{number}/tasks Only([POST])328 route /{owner}/{repo}/issues/{number}/tasks Only([POST])
329 route /{owner}/{repo}/labels.css Only([GET])329 route /{owner}/{repo}/labels.css Only([GET])
330 route /{owner}/{repo}/merge-queue/events Only([GET])330 route /{owner}/{repo}/merge-queue/events Only([GET])
331+route /{owner}/{repo}/parts/head Only([GET])
331 route /{owner}/{repo}/paths/{*rest} Only([GET])332 route /{owner}/{repo}/paths/{*rest} Only([GET])
332 route /{owner}/{repo}/pulls/events Only([GET])333 route /{owner}/{repo}/pulls/events Only([GET])
333 route /{owner}/{repo}/pulls/{number}/auto-merge Only([POST])334 route /{owner}/{repo}/pulls/{number}/auto-merge Only([POST])
style/_min.scssmodified+4 -0
@@ -254,6 +254,10 @@ summary.act {
254 margin: 0;254 margin: 0;
255 }255 }
256 256
257+.head-actions {
258+ display: contents;
259+}
260+
257 // An action that opens in place. Its panel takes a line of its own under the links beside it.261 // An action that opens in place. Its panel takes a line of its own under the links beside it.
258 262
259 .reveal {263 .reveal {
style/_one.scssmodified+1 -0
@@ -3546,6 +3546,7 @@ details.log-group {
3546 // keeps its red word on the pill. What opens from a reveal keeps its own kit.3546 // keeps its red word on the pill. What opens from a reveal keeps its own kit.
3547 .head-title > :is(a.act, button.act),3547 .head-title > :is(a.act, button.act),
3548 .head-title > form.act-form > button.act,3548 .head-title > form.act-form > button.act,
3549+.head-actions > form.act-form > button.act,
3549 .head-title > details.reveal > summary.act {3550 .head-title > details.reveal > summary.act {
3550 display: inline-flex;3551 display: inline-flex;
3551 align-items: center;3552 align-items: center;
style/_one_shell.scssmodified+3 -3
@@ -144,7 +144,7 @@ a > .ref-chip,
144 144
145 // Beside a repo title, the watch button is one of the head's pills: the same height, radius, fill,145 // Beside a repo title, the watch button is one of the head's pills: the same height, radius, fill,
146 // and 600 text as Star and Fork. The caret keeps its place at the end.146 // 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 {
148 box-sizing: border-box;148 box-sizing: border-box;
149 padding: 0 30px 0 18px;149 padding: 0 30px 0 18px;
150 font-size: 15px;150 font-size: 15px;
@@ -191,14 +191,14 @@ a > .ref-chip,
191 }191 }
192 192
193 // In the head the watcher count is in the line under the title, so the watch pill stands alone.193 // 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 {
195 display: none;195 display: none;
196 }196 }
197 197
198 // On a phone the watch pill is its eye and chevron, so it shares the title's line with Star; its198 // On a phone the watch pill is its eye and chevron, so it shares the title's line with Star; its
199 // level stays in the summary's label.199 // level stays in the summary's label.
200 @media (max-width: 700px) {200 @media (max-width: 700px) {
201- .head-title > .watch-control .watch-menu > summary > span {201+ .head-actions > .watch-control .watch-menu > summary > span {
202 display: none;202 display: none;
203 }203 }
204 }204 }