forge
Explore
Log in

Don't you dare go Hollow

The text picker, live bumps, event streams and view helpers move out of pages into forge-web-base i18n, live and views, so the infrastructure modules stop depending on pages

Browse files at this commit

372b0ec2104bdd46dba49707e8d6bff3d953c0a9Ahmet Kaan GümüşParent: bf7a72c
  • refactor
    • the text picker, live bumps, event streams and view helpers move out of pages into forge-web-base i18n, live and views, so the infrastructure modules stop depending on pages
Show full message
♻️ refactor: the text picker, live bumps, event streams and view helpers move out of pages into forge-web-base i18n, live and views, so the infrastructure modules stop depending on pages
crates/forge-web-base/src/i18n/mod.rsmodified+8 -0
@@ -495,6 +495,14 @@ pub const ALL: &[Key] = &[
495 ];495 ];
496 496
497 /// The phrase a key names, in a user's language.497 /// The phrase a key names, in a user's language.
498+/// Picks the English or Turkish text.
499+pub fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str {
500+ match lang {
501+ Lang::En => en,
502+ Lang::Tr => tr,
503+ }
504+}
505+
498 pub fn t(lang: Lang, key: Key) -> &'static str {506 pub fn t(lang: Lang, key: Key) -> &'static str {
499 use Key::*;507 use Key::*;
500 use Lang::*;508 use Lang::*;
crates/forge-web/src/advisories/scan.rsmodified+1 -1
@@ -10,7 +10,7 @@ use forge_core::store::advisories::ScanOutcome;
10 use forge_core::{Error, Repo, Result};10 use forge_core::{Error, Repo, Result};
11 use forge_git::browse::{EntryKind, default_branch_commit, read_text_blob, read_tree};11 use forge_git::browse::{EntryKind, default_branch_commit, read_text_blob, read_tree};
12 12
13-use crate::pages::repo_settings_live::bump_settings;13+use crate::live::bump_settings;
14 use crate::state::AppState;14 use crate::state::AppState;
15 15
16 /// Deepest directory searched for lockfiles. The root is depth 0.16 /// Deepest directory searched for lockfiles. The root is depth 0.
crates/forge-web/src/api/mod.rsmodified+1 -1
@@ -114,7 +114,7 @@ pub async fn authenticate(
114 if let Err(e) = state.store.touch_token(&token_id).await {114 if let Err(e) = state.store.touch_token(&token_id).await {
115 return Err(internal(e));115 return Err(internal(e));
116 }116 }
117- crate::pages::settings_live::bump_account(state, &user.id);117+ crate::live::bump_account(state, &user.id);
118 Ok(Some(user))118 Ok(Some(user))
119 }119 }
120 120
crates/forge-web/src/api/packages.rsmodified+1 -1
@@ -59,7 +59,7 @@ async fn caller(cx: &Cx, scope_required: bool) -> Result<Option<User>, Refusal>
59 if let Err(e) = state.store.touch_token(&token_id).await {59 if let Err(e) = state.store.touch_token(&token_id).await {
60 return Err(Box::new(failure(PackageError::Internal(e.to_string()))));60 return Err(Box::new(failure(PackageError::Internal(e.to_string()))));
61 }61 }
62- crate::pages::settings_live::bump_account(state, &user.id);62+ crate::live::bump_account(state, &user.id);
63 Ok(Some(user))63 Ok(Some(user))
64 }64 }
65 65
crates/forge-web/src/auth.rsmodified+1 -1
@@ -111,7 +111,7 @@ pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> {
111 let state = context::<AppState>(cx);111 let state = context::<AppState>(cx);
112 state.store.delete_session(&session.id).await?;112 state.store.delete_session(&session.id).await?;
113 // The user's other tabs may show this session (a page that now leaves for the login page).113 // The user's other tabs may show this session (a page that now leaves for the login page).
114- crate::pages::settings_live::bump_account(state, &session.user_id);114+ crate::live::bump_account(state, &session.user_id);
115 session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/"));115 session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/"));
116 Ok(())116 Ok(())
117 }117 }
crates/forge-web/src/automerge.rsmodified+2 -2
@@ -15,7 +15,7 @@ use crate::state::AppState;
15 /// `sha`. Called after a commit status for `sha` was written. Failures are logged: the status15 /// `sha`. Called after a commit status for `sha` was written. Failures are logged: the status
16 /// that triggered this has already been stored.16 /// that triggered this has already been stored.
17 pub async fn on_status(state: &AppState, repo_id: &str, sha: &str) {17 pub async fn on_status(state: &AppState, repo_id: &str, sha: &str) {
18- crate::pages::pull_live::bump_head(state, repo_id, sha).await;18+ crate::live::bump_head(state, repo_id, sha).await;
19 let pulls = match state.store.auto_merge_pulls_for_head(repo_id, sha).await {19 let pulls = match state.store.auto_merge_pulls_for_head(repo_id, sha).await {
20 Ok(pulls) => pulls,20 Ok(pulls) => pulls,
21 Err(e) => {21 Err(e) => {
@@ -55,7 +55,7 @@ async fn evaluate_logged(state: &AppState, repo: &Repo, pr: &PullRequest) {
55 tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "auto-merge: evaluation failed");55 tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "auto-merge: evaluation failed");
56 }56 }
57 // The evaluation may have merged the pull or left it as it was; either way its page re-reads.57 // The evaluation may have merged the pull or left it as it was; either way its page re-reads.
58- crate::pages::pull_live::bump_pull(state, &repo.id, &pr.issue.id);58+ crate::live::bump_pull(state, &repo.id, &pr.issue.id);
59 }59 }
60 60
61 /// Merges `pr` when auto-merge is on and nothing blocks it any more. Returns whether it merged.61 /// Merges `pr` when auto-merge is on and nothing blocks it any more. Returns whether it merged.
crates/forge-web/src/ci/api.rsmodified+1 -2
@@ -29,10 +29,9 @@ use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route};
29 29
30 use crate::api::{self, Refusal};30 use crate::api::{self, Refusal};
31 use crate::ci::{artifact_key, log_path};31 use crate::ci::{artifact_key, log_path};
32-use crate::pages::admin_runners::bytes_text;
33-use crate::pages::repo::https_clone_url;
34 use crate::self_update;32 use crate::self_update;
35 use crate::state::AppState;33 use crate::state::AppState;
34+use crate::views::{bytes_text, https_clone_url};
36 35
37 path_param!(job_id);36 path_param!(job_id);
38 path_param!(artifact_name);37 path_param!(artifact_name);
crates/forge-web/src/git_auth.rsmodified+1 -1
@@ -81,7 +81,7 @@ pub async fn user_from_basic(
81 .touch_token(&access.id)81 .touch_token(&access.id)
82 .await82 .await
83 .map_err(internal)?;83 .map_err(internal)?;
84- crate::pages::settings_live::bump_account(state, &user.id);84+ crate::live::bump_account(state, &user.id);
85 Ok(Some(user))85 Ok(Some(user))
86 }86 }
87 87
crates/forge-web/src/internal.rsmodified+1 -1
@@ -170,7 +170,7 @@ async fn hook_endpoint(
170 // A wiki push changes neither the code repo's refs nor its CI, pull requests or events.170 // A wiki push changes neither the code repo's refs nor its CI, pull requests or events.
171 // It still goes to the standby.171 // It still goes to the standby.
172 record_wiki_push(&state.store, &req).await;172 record_wiki_push(&state.store, &req).await;
173- crate::pages::wiki_live::bump_wiki(state, &req.repo_id);173+ crate::live::bump_wiki(state, &req.repo_id);
174 crate::replication::enqueue_repo(state, &req.repo_id);174 crate::replication::enqueue_repo(state, &req.repo_id);
175 HookResponse::allow()175 HookResponse::allow()
176 }176 }
crates/forge-web/src/live.rsmodified+241 -16
@@ -26,16 +26,18 @@
26 use std::collections::HashMap;26 use std::collections::HashMap;
27 use std::future::Future;27 use std::future::Future;
28 use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};28 use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
29+use std::time::Duration;
29 30
30 use futures_util::future::select_all;31 use futures_util::future::select_all;
31-use futures_util::{Stream, stream};32+use futures_util::{Stream, StreamExt, stream};
32 use tokio::sync::watch;33 use tokio::sync::watch;
33 use topcoat::Result;34 use topcoat::Result;
34 use topcoat::context::Cx;35 use topcoat::context::Cx;
35-use topcoat::router::content::sse::Event;36+use topcoat::router::HeaderValue;
36-use topcoat::router::response::Response;37+use topcoat::router::content::sse::{Event, KeepAlive, Sse};
38+use topcoat::router::response::{IntoResponse, Response};
37 39
38-use crate::pages::ci_runs::events_response;40+use crate::state::AppState;
39 41
40 /// What a live page follows. Add a variant when a page needs a new signal.42 /// What a live page follows. Add a variant when a page needs a new signal.
41 #[derive(Clone, Debug, PartialEq, Eq, Hash)]43 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
@@ -48,10 +50,10 @@ pub enum Topic {
48 /// One issue: its body, comments, events, state, labels, reactions. Keyed by issue id.50 /// One issue: its body, comments, events, state, labels, reactions. Keyed by issue id.
49 Issue(String),51 Issue(String),
50 /// The pull request list of a repo: a pull opened, or any pull in the repo changed. Keyed by52 /// The pull request list of a repo: a pull opened, or any pull in the repo changed. Keyed by
51- /// repo id. Bumped by [`crate::pages::pull_live`].53+ /// repo id. Bumped by the `pull_live` page.
52 PullList(String),54 PullList(String),
53 /// One pull request, its conversation, commits and files. Keyed by the pull's issue id.55 /// One pull request, its conversation, commits and files. Keyed by the pull's issue id.
54- /// Bumped by [`crate::pages::pull_live`].56+ /// Bumped by the `pull_live` page.
55 Pull(String),57 Pull(String),
56 /// A repo's own state that its header shows: stars, watchers, forks, its name, description,58 /// A repo's own state that its header shows: stars, watchers, forks, its name, description,
57 /// archived flag and default branch, the tab switches, and the mirror's last sync. Keyed by repo59 /// archived flag and default branch, the tab switches, and the mirror's last sync. Keyed by repo
@@ -67,7 +69,7 @@ pub enum Topic {
67 /// A user's review requests: a pull request asked the user to review, a request was withdrawn,69 /// A user's review requests: a pull request asked the user to review, a request was withdrawn,
68 /// the user submitted a review, or a pull request with the user's request closed or merged.70 /// the user submitted a review, or a pull request with the user's request closed or merged.
69 /// Keyed by the reviewer's user id. Streamed only to that user. Bumped by71 /// Keyed by the reviewer's user id. Streamed only to that user. Bumped by
70- /// [`crate::pages::review_requests`] and [`crate::pages::pull_live`].72+ /// the `review_requests` page and the `pull_live` page.
71 ReviewRequests(String),73 ReviewRequests(String),
72 /// A user's import jobs: a job was queued, started, progressed or finished. Keyed by user id.74 /// A user's import jobs: a job was queued, started, progressed or finished. Keyed by user id.
73 /// Bumped by the importer when a job's state changes. Streamed only to that user.75 /// Bumped by the importer when a job's state changes. Streamed only to that user.
@@ -76,13 +78,13 @@ pub enum Topic {
76 Explore,78 Explore,
77 /// The discussions of a repo as a list: a discussion was opened, or any discussion of the repo79 /// The discussions of a repo as a list: a discussion was opened, or any discussion of the repo
78 /// changed (a comment, a reaction, an answer, a lock, a category). Keyed by repo id. Bumped by80 /// changed (a comment, a reaction, an answer, a lock, a category). Keyed by repo id. Bumped by
79- /// [`crate::pages::discussion_live`].81+ /// the `discussion_live` page.
80 Discussions(String),82 Discussions(String),
81 /// One discussion: its body, comments, reactions, answer and lock state. Keyed by discussion83 /// One discussion: its body, comments, reactions, answer and lock state. Keyed by discussion
82- /// id. Bumped by [`crate::pages::discussion_live`].84+ /// id. Bumped by the `discussion_live` page.
83 Discussion(String),85 Discussion(String),
84 /// A repo's wiki: a page was saved, or a push changed the wiki's main branch. Keyed by repo id.86 /// A repo's wiki: a page was saved, or a push changed the wiki's main branch. Keyed by repo id.
85- /// Bumped by [`crate::pages::wiki_live`] and by the wiki push hook.87+ /// Bumped by the `wiki_live` page and by the wiki push hook.
86 Wiki(String),88 Wiki(String),
87 /// The snippet list: a snippet was created, changed or deleted. Global; each viewer's list is89 /// The snippet list: a snippet was created, changed or deleted. Global; each viewer's list is
88 /// fingerprinted, so a bump that changes nothing the viewer sees sends nothing.90 /// fingerprinted, so a bump that changes nothing the viewer sees sends nothing.
@@ -90,7 +92,7 @@ pub enum Topic {
90 /// One snippet: its files, title, visibility and revisions. Keyed by snippet id.92 /// One snippet: its files, title, visibility and revisions. Keyed by snippet id.
91 Snippet(String),93 Snippet(String),
92 /// An organization's pages: its members, teams, team members and linked repos, and settings.94 /// An organization's pages: its members, teams, team members and linked repos, and settings.
93- /// Keyed by the org's user id. Bumped by [`crate::pages::org_live`] after a POST under the org.95+ /// Keyed by the org's user id. Bumped by the `org_live` page after a POST under the org.
94 Org(String),96 Org(String),
95 /// The account list of the admin area: an account was registered, edited, suspended, lifted,97 /// The account list of the admin area: an account was registered, edited, suspended, lifted,
96 /// given or lost admin rights, or deleted. Global. Admin pages only, on [`admin`].98 /// given or lost admin rights, or deleted. Global. Admin pages only, on [`admin`].
@@ -129,7 +131,7 @@ pub enum Topic {
129 /// The server settings that pages render (every `Kind::Live` setting, such as the banner, the131 /// The server settings that pages render (every `Kind::Live` setting, such as the banner, the
130 /// registration mode or the limits): one was saved or reset. Global. Every page holds132 /// registration mode or the limits): one was saved or reset. Global. Every page holds
131 /// `/-/alive`, anonymous viewers included, and follows it there (see133 /// `/-/alive`, anonymous viewers included, and follows it there (see
132- /// [`crate::pages::settings_live::alive_response`]). Bumped by the server settings after a save134+ /// `settings_live::alive_response`). Bumped by the server settings after a save
133 /// or reset.135 /// or reset.
134 ServerSettings,136 ServerSettings,
135 }137 }
@@ -212,7 +214,7 @@ struct Follow<F> {
212 }214 }
213 215
214 /// The `changed` event of a live page. The data is not read by the client.216 /// The `changed` event of a live page. The data is not read by the client.
215-fn changed_event() -> Result<Event> {217+fn wake_event() -> Result<Event> {
216 Ok(Event::new().event("changed").data("1"))218 Ok(Event::new().event("changed").data("1"))
217 }219 }
218 220
@@ -237,7 +239,7 @@ pub fn stream_wakes(cx: &Cx, hub: &LiveHub, topics: &[Topic]) -> Result<Response
237 if !wait_any(&mut wakes).await {239 if !wait_any(&mut wakes).await {
238 return None;240 return None;
239 }241 }
240- Some((changed_event(), wakes))242+ Some((wake_event(), wakes))
241 });243 });
242 events_response(cx, events)244 events_response(cx, events)
243 }245 }
@@ -317,10 +319,233 @@ where
317 ))319 ))
318 }320 }
319 321
322+/// Wakes the settings pages of `user_id`. Called after a write that changes what they show.
323+pub fn bump_account(state: &AppState, user_id: &str) {
324+ state.live.bump(&Topic::Account(user_id.to_owned()));
325+}
326+
327+/// Bumps the settings topic of a repo, after a write that changes one of its settings pages.
328+pub fn bump_settings(hub: &LiveHub, repo_id: &str) {
329+ hub.bump(&Topic::RepoSettings(repo_id.to_owned()));
330+}
331+
332+/// A write changed the wiki of `repo_id`: a page was saved, or a push moved its main branch.
333+pub fn bump_wiki(state: &AppState, repo_id: &str) {
334+ state.live.bump(&Topic::Wiki(repo_id.to_owned()));
335+}
336+
337+// Bumps. Each one wakes the streams of the topics it names; none of them reads more than the
338+// ids it needs. A failed lookup is logged and leaves the streams as they were.
339+
340+/// A write changed one pull request: its page and the list both follow it.
341+pub fn bump_pull(state: &AppState, repo_id: &str, issue_id: &str) {
342+ state.live.bump(&Topic::Pull(issue_id.to_owned()));
343+ bump_list(state, repo_id);
344+}
345+
346+/// A pull request was opened, or the list changed for another reason. Only the list follows.
347+pub fn bump_list(state: &AppState, repo_id: &str) {
348+ state.live.bump(&Topic::PullList(repo_id.to_owned()));
349+}
350+
351+/// A change that may touch any pull of the repo (a push, a label or milestone edit, a merge run
352+/// by auto-merge): the list and every pull page of the repo.
353+pub async fn bump_repo_pulls(state: &AppState, repo_id: &str) {
354+ bump_list(state, repo_id);
355+ match state.store.pull_refs(repo_id).await {
356+ Ok(refs) => {
357+ for (issue_id, _) in refs {
358+ state.live.bump(&Topic::Pull(issue_id));
359+ }
360+ }
361+ Err(e) => tracing::error!(error = %e, repo_id, "live: listing pulls to bump failed"),
362+ }
363+}
364+
365+/// A commit status was written for `sha`: the pulls whose head is that commit, and the list.
366+pub async fn bump_head(state: &AppState, repo_id: &str, sha: &str) {
367+ bump_list(state, repo_id);
368+ match state.store.pulls_for_head_oid(repo_id, sha).await {
369+ Ok(refs) => {
370+ for (issue_id, _) in refs {
371+ state.live.bump(&Topic::Pull(issue_id));
372+ }
373+ }
374+ Err(e) => {
375+ tracing::error!(error = %e, repo_id, "live: listing pulls for a head to bump failed")
376+ }
377+ }
378+}
379+
380+/// How often an idle event stream sends a `: keepalive` comment, so a reverse proxy does not drop
381+/// the connection. This is not a poll: events follow the change signals.
382+const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30);
383+
384+/// A run's or job's status word and whether it is terminal. `None` when the row is gone.
385+pub(crate) type Status = Option<(String, bool)>;
386+
387+/// One `changed` event carrying the status word.
388+pub fn changed_event(status: String) -> Result<Event> {
389+ Ok(Event::new().event("changed").data(status))
390+}
391+
392+/// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event
393+/// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when
394+/// the status differs from the last one sent. The stream ends after the terminal status is sent,
395+/// when the row is gone, or when the signal closes. Subscribe `wake` before the first read, so a
396+/// change in between is not lost.
397+pub fn changed_stream<F, Fut>(
398+ wake: watch::Receiver<u64>,
399+ only_on_status: bool,
400+ name: &'static str,
401+ read: F,
402+) -> impl Stream<Item = Result<Event>> + Send + 'static
403+where
404+ F: Fn() -> Fut + Send + 'static,
405+ Fut: Future<Output = Result<Status>> + Send,
406+{
407+ struct Follow<F> {
408+ wake: watch::Receiver<u64>,
409+ only_on_status: bool,
410+ read: F,
411+ /// The status last read, sent or not.
412+ last: Option<String>,
413+ /// Set once a terminal status is read. Nothing follows it.
414+ done: bool,
415+ /// False until the first read. Every later read waits for a wake first.
416+ primed: bool,
417+ }
418+ stream::unfold(
419+ Follow {
420+ wake,
421+ only_on_status,
422+ read,
423+ last: None,
424+ done: false,
425+ primed: false,
426+ },
427+ move |mut follow| async move {
428+ loop {
429+ if follow.done {
430+ return None;
431+ }
432+ if follow.primed && follow.wake.changed().await.is_err() {
433+ return None;
434+ }
435+ follow.primed = true;
436+ let (status, terminal) = match (follow.read)().await {
437+ Ok(Some(found)) => found,
438+ Ok(None) => return None,
439+ Err(e) => {
440+ tracing::error!(error = %e, "ci: live stream could not read the status");
441+ return None;
442+ }
443+ };
444+ follow.done = terminal;
445+ let changed = follow.last.as_deref() != Some(status.as_str());
446+ let send = changed || !follow.only_on_status;
447+ follow.last = Some(status.clone());
448+ if send {
449+ return Some((Ok(Event::new().event(name).data(status)), follow));
450+ }
451+ }
452+ },
453+ )
454+}
455+
456+/// Open event streams one client address (IPv6 by /64) may hold. A page holds one or two, so this
457+/// is many tabs; past it a script that opens streams in a loop is refused.
458+const MAX_STREAMS_PER_CLIENT: usize = 64;
459+/// Open event streams server-wide. Each is a task and a socket that stay until the client leaves.
460+const MAX_STREAMS: usize = 4096;
461+
462+/// Open streams per client address, and their sum.
463+static OPEN_STREAMS: Mutex<(usize, Option<HashMap<std::net::IpAddr, usize>>)> =
464+ Mutex::new((0, None));
465+
466+/// One open event stream, counted against its client's and the server's cap until dropped.
467+/// `ip` is `None` for an uncounted stream.
468+struct StreamSlot {
469+ ip: Option<std::net::IpAddr>,
470+}
471+
472+impl StreamSlot {
473+ /// A slot for this request's client, or `None` when a cap is reached. Without the app state
474+ /// (unit tests of a bare router) nothing is counted.
475+ fn take(cx: &Cx) -> Option<StreamSlot> {
476+ if topcoat::context::try_context::<AppState>(cx).is_none() {
477+ return Some(StreamSlot { ip: None });
478+ }
479+ let ip = crate::client_ip::client_ip(cx);
480+ let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner());
481+ let (total, per_client) = &mut *open;
482+ let count = per_client
483+ .get_or_insert_with(HashMap::new)
484+ .entry(ip)
485+ .or_insert(0);
486+ if *total >= MAX_STREAMS || *count >= MAX_STREAMS_PER_CLIENT {
487+ return None;
488+ }
489+ *count += 1;
490+ *total += 1;
491+ Some(StreamSlot { ip: Some(ip) })
492+ }
493+}
494+
495+impl Drop for StreamSlot {
496+ fn drop(&mut self) {
497+ let Some(ip) = self.ip else {
498+ return;
499+ };
500+ let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner());
501+ let (total, per_client) = &mut *open;
502+ *total = total.saturating_sub(1);
503+ if let Some(map) = per_client.as_mut()
504+ && let Some(count) = map.get_mut(&ip)
505+ {
506+ *count = count.saturating_sub(1);
507+ if *count == 0 {
508+ map.remove(&ip);
509+ }
510+ }
511+ }
512+}
513+
514+/// How long the browser waits before it reconnects a dropped event stream. The browser's default is
515+/// a few seconds; one second makes a page come back as soon as a server restart is done.
516+pub(crate) const STREAM_RETRY: Duration = Duration::from_secs(1);
517+
518+/// The response of an event stream: keep-alive comments while idle, no buffering by a reverse
519+/// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`.
520+pub fn events_response(
521+ cx: &Cx,
522+ events: impl Stream<Item = Result<Event>> + Send + 'static,
523+) -> Result<Response> {
524+ // Past the cap the stream is refused: the page keeps working, only without live updates.
525+ let Some(slot) = StreamSlot::take(cx) else {
526+ let mut res = Response::new(topcoat::router::Body::from("too many open live streams"));
527+ *res.status_mut() = http::StatusCode::TOO_MANY_REQUESTS;
528+ return Ok(res);
529+ };
530+ // The slot lives as long as the stream: it is given back when the client goes away.
531+ let events = events.map(move |event| {
532+ let _held = &slot;
533+ event
534+ });
535+ let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY))));
536+ let events = Sse::new(retry.chain(events)).keep_alive(
537+ KeepAlive::new()
538+ .interval(STREAM_KEEP_ALIVE)
539+ .text("keepalive"),
540+ );
541+ let mut res = events.into_response(cx)?;
542+ res.headers_mut()
543+ .insert("x-accel-buffering", HeaderValue::from_static("no"));
544+ Ok(res)
545+}
546+
320 #[cfg(test)]547 #[cfg(test)]
321 mod tests {548 mod tests {
322- use std::time::Duration;
323-
324 use super::*;549 use super::*;
325 550
326 #[tokio::test]551 #[tokio::test]
crates/forge-web/src/merge_queue.rsmodified+2 -2
@@ -420,7 +420,7 @@ async fn fail(
420 .await420 .await
421 {421 {
422 Ok(_) => {422 Ok(_) => {
423- crate::pages::pull_live::bump_pull(state, &repo.id, &pr.issue.id);423+ crate::live::bump_pull(state, &repo.id, &pr.issue.id);
424 notify::dispatch(424 notify::dispatch(
425 state,425 state,
426 repo,426 repo,
@@ -441,5 +441,5 @@ async fn fail(
441 /// Wakes the queue pages of `repo_id`, and the pull page and list of the entry's pull request.441 /// Wakes the queue pages of `repo_id`, and the pull page and list of the entry's pull request.
442 fn notify_entry(state: &AppState, repo: &Repo, entry: &QueueEntry) {442 fn notify_entry(state: &AppState, repo: &Repo, entry: &QueueEntry) {
443 state.ci_live.bump_queue(&repo.id);443 state.ci_live.bump_queue(&repo.id);
444- crate::pages::pull_live::bump_pull(state, &repo.id, &entry.issue_id);444+ crate::live::bump_pull(state, &repo.id, &entry.issue_id);
445 }445 }
crates/forge-web/src/mirrors/mod.rsmodified+1 -1
@@ -23,7 +23,7 @@ use serde_json::json;
23 23
24 use crate::audit::{self, Actor, Target};24 use crate::audit::{self, Actor, Target};
25 use crate::live::Topic;25 use crate::live::Topic;
26-use crate::pages::repo_settings_live::bump_settings;26+use crate::live::bump_settings;
27 use crate::post_update::after_ref_update;27 use crate::post_update::after_ref_update;
28 use crate::state::AppState;28 use crate::state::AppState;
29 use crate::webhooks::client::{WebhookPolicy, is_forbidden_ip, validate_url};29 use crate::webhooks::client::{WebhookPolicy, is_forbidden_ip, validate_url};
crates/forge-web/src/pages/account_tools_tests.rsmodified+1 -1
@@ -290,7 +290,7 @@ async fn banner_shows_on_pages_and_a_dismissal_hides_it() {
290 assert!(body.contains("site-banner warning"), "{body}");290 assert!(body.contains("site-banner warning"), "{body}");
291 assert!(body.contains("Maintenance tonight"));291 assert!(body.contains("Maintenance tonight"));
292 }292 }
293- let hash = crate::pages::banner::banner_hash("Maintenance tonight", "warning");293+ let hash = crate::views::banner_hash("Maintenance tonight", "warning");
294 let req = Request::builder()294 let req = Request::builder()
295 .method("GET")295 .method("GET")
296 .uri("/explore")296 .uri("/explore")
crates/forge-web/src/pages/activity.rsmodified+2 -1
@@ -14,7 +14,8 @@ use topcoat::router::response::Response;
14 use topcoat::router::{Body, HeaderValue, StatusCode, route};14 use topcoat::router::{Body, HeaderValue, StatusCode, route};
15 15
16 use crate::auth::current_user;16 use crate::auth::current_user;
17-use crate::pages::ci_runs::{changed_stream, events_response, run_href};17+use crate::live::{changed_stream, events_response};
18+use crate::pages::ci_runs::run_href;
18 use crate::state::AppState;19 use crate::state::AppState;
19 use crate::views::repo_href;20 use crate::views::repo_href;
20 use futures_util::Stream;21 use futures_util::Stream;
crates/forge-web/src/pages/admin_mail.rsmodified+3 -3
@@ -31,12 +31,12 @@ use crate::audit::{self, Actor, Target};
31 use crate::auth::check_csrf;31 use crate::auth::check_csrf;
32 use crate::i18n::admin::{self as g, K};32 use crate::i18n::admin::{self as g, K};
33 use crate::i18n::{self, Key, Lang};33 use crate::i18n::{self, Key, Lang};
34+use crate::live::{changed_event, events_response};
34 use crate::mail::{enqueue, live, templates};35 use crate::mail::{enqueue, live, templates};
35 use crate::pages::admin_server::{36 use crate::pages::admin_server::{
36 MAIL_KEYS, Row, refusal, save_topic, setting_lines, setting_rows,37 MAIL_KEYS, Row, refusal, save_topic, setting_lines, setting_rows,
37 };38 };
38 use crate::pages::admin_users::admin_only;39 use crate::pages::admin_users::admin_only;
39-use crate::pages::ci_runs::{changed_event, events_response};
40 use crate::state::AppState;40 use crate::state::AppState;
41 use crate::views::parts::{confirm_act, head, post_act};41 use crate::views::parts::{confirm_act, head, post_act};
42 use crate::views::{enc, rel_time, shell};42 use crate::views::{enc, rel_time, shell};
@@ -230,7 +230,7 @@ async fn mail_view(
230 <form method="post" action="/admin/mail" class="srv-form">230 <form method="post" action="/admin/mail" class="srv-form">
231 <input type="hidden" name="csrf" value=(csrf.as_str())>231 <input type="hidden" name="csrf" value=(csrf.as_str())>
232 <section class="sec">232 <section class="sec">
233- <h2>(crate::pages::passkeys::s(lang, "Delivery", "Teslimat"))</h2>233+ <h2>(crate::i18n::s(lang, "Delivery", "Teslimat"))</h2>
234 setting_lines(lang: lang, rows: data.transport)234 setting_lines(lang: lang, rows: data.transport)
235 </section>235 </section>
236 <section class="sec" id="smtp">236 <section class="sec" id="smtp">
@@ -263,7 +263,7 @@ async fn mail_view(
263 </div>263 </div>
264 </section>264 </section>
265 <section class="sec">265 <section class="sec">
266- <h2>(crate::pages::passkeys::s(lang, "Sending", "Gönderim"))</h2>266+ <h2>(crate::i18n::s(lang, "Sending", "Gönderim"))</h2>
267 <div class="fields">267 <div class="fields">
268 <div class="field">268 <div class="field">
269 <label for="mail-from-addr">(g::t(lang, K::FromAddress))</label>269 <label for="mail-from-addr">(g::t(lang, K::FromAddress))</label>
crates/forge-web/src/pages/admin_replication.rsmodified+2 -2
@@ -26,6 +26,7 @@ use topcoat::view::{View, component, view};
26 use crate::audit::{self, Actor, Target};26 use crate::audit::{self, Actor, Target};
27 use crate::auth::check_csrf;27 use crate::auth::check_csrf;
28 use crate::i18n::admin::{self as g, K};28 use crate::i18n::admin::{self as g, K};
29+use crate::i18n::s;
29 use crate::i18n::{self, Key, Lang};30 use crate::i18n::{self, Key, Lang};
30 use crate::live::{Topic, stream_changes};31 use crate::live::{Topic, stream_changes};
31 use crate::pages::admin_backups::backups_rail;32 use crate::pages::admin_backups::backups_rail;
@@ -35,7 +36,6 @@ use crate::pages::admin_server::{
35 };36 };
36 use crate::pages::admin_users::admin_only;37 use crate::pages::admin_users::admin_only;
37 use crate::pages::issues_list::list_href;38 use crate::pages::issues_list::list_href;
38-use crate::pages::passkeys::s;
39 use crate::state::AppState;39 use crate::state::AppState;
40 use crate::views::find::{Finder, finder_field};40 use crate::views::find::{Finder, finder_field};
41 use crate::views::parts::{head, post_act};41 use crate::views::parts::{head, post_act};
@@ -277,7 +277,7 @@ async fn replication_view(
277 </section>277 </section>
278 if data.enabled {278 if data.enabled {
279 <section class="sec">279 <section class="sec">
280- <h2>(crate::pages::passkeys::s(lang, "Status", "Durum"))</h2>280+ <h2>(crate::i18n::s(lang, "Status", "Durum"))</h2>
281 <div class="line" data-kb-row="">281 <div class="line" data-kb-row="">
282 <span class="name">(g::t(lang, K::Database))</span>282 <span class="name">(g::t(lang, K::Database))</span>
283 <span class="val"><span class=(data.db_dot) aria-hidden="true"></span> (data.db_health)</span>283 <span class="val"><span class=(data.db_dot) aria-hidden="true"></span> (data.db_health)</span>
crates/forge-web/src/pages/admin_runners.rsmodified+4 -14
@@ -32,15 +32,14 @@ use crate::ci::runner_log::Line;
32 use crate::i18n::admin::{self as g, K};32 use crate::i18n::admin::{self as g, K};
33 use crate::i18n::releases_ci as rc;33 use crate::i18n::releases_ci as rc;
34 use crate::i18n::{self, Key, Lang};34 use crate::i18n::{self, Key, Lang};
35+use crate::live::events_response;
35 use crate::pages::admin_users::admin_only;36 use crate::pages::admin_users::admin_only;
36-use crate::pages::ci_runs::{37+use crate::pages::ci_runs::{age_text, duration_text, job_href, run_href, state_text};
37- age_text, duration_text, events_response, job_href, run_href, state_text,
38-};
39 use crate::pages::repo_mirrors::stamp_in_tz;38 use crate::pages::repo_mirrors::stamp_in_tz;
40 use crate::state::AppState;39 use crate::state::AppState;
41 use crate::views::parts::{SubPart, confirm_act, head, post_act, reveal};40 use crate::views::parts::{SubPart, confirm_act, head, post_act, reveal};
42 use crate::views::repo_list::{PageLink, pager, pager_links};41 use crate::views::repo_list::{PageLink, pager, pager_links};
43-use crate::views::{alert, enc, now_unix, relative_time, shell};42+use crate::views::{alert, bytes_text, enc, now_unix, relative_time, shell};
44 43
45 path_param!(runner_id);44 path_param!(runner_id);
46 path_param!(token_hash);45 path_param!(token_hash);
@@ -1014,12 +1013,6 @@ fn identity_rows(lang: Lang, fields: &[FieldRow]) -> Vec<(&'static str, String)>
1014 .collect()1013 .collect()
1015 }1014 }
1016 1015
1017-/// A byte count in GiB with one decimal, such as `3.7 GiB`.
1018-pub(crate) fn bytes_text(bytes: u64) -> String {
1019- let gib = bytes as f64 / (1u64 << 30) as f64;
1020- format!("{gib:.1} GiB")
1021-}
1022-
1023 fn or_dash(text: String) -> String {1016 fn or_dash(text: String) -> String {
1024 if text.is_empty() {1017 if text.is_empty() {
1025 "-".to_owned()1018 "-".to_owned()
@@ -1835,10 +1828,7 @@ async fn runners_events(cx: &Cx) -> Result<Response> {
1835 let wake = state.ci_live.subscribe_runners();1828 let wake = state.ci_live.subscribe_runners();
1836 let events = futures_util::stream::unfold(wake, |mut wake| async move {1829 let events = futures_util::stream::unfold(wake, |mut wake| async move {
1837 wake.changed().await.ok()?;1830 wake.changed().await.ok()?;
1838- Some((1831+ Some((crate::live::changed_event("runners".to_owned()), wake))
1839- crate::pages::ci_runs::changed_event("runners".to_owned()),
1840- wake,
1841- ))
1842 });1832 });
1843 events_response(cx, events)1833 events_response(cx, events)
1844 }1834 }
crates/forge-web/src/pages/admin_server.rsmodified+2 -2
@@ -31,11 +31,11 @@ use topcoat::view::{View, component, view};
31 use crate::audit::{self, Actor, Target};31 use crate::audit::{self, Actor, Target};
32 use crate::auth::check_csrf;32 use crate::auth::check_csrf;
33 use crate::i18n::admin::{self as g, K};33 use crate::i18n::admin::{self as g, K};
34+use crate::i18n::s;
34 use crate::i18n::{self, Key, Lang};35 use crate::i18n::{self, Key, Lang};
35 use crate::live::Topic;36 use crate::live::Topic;
37+use crate::live::{changed_event, events_response};
36 use crate::pages::admin_users::admin_only;38 use crate::pages::admin_users::admin_only;
37-use crate::pages::ci_runs::{changed_event, events_response};
38-use crate::pages::passkeys::s;
39 use crate::self_update;39 use crate::self_update;
40 use crate::state::AppState;40 use crate::state::AppState;
41 use crate::views::find::{Finder, finder_field};41 use crate::views::find::{Finder, finder_field};
crates/forge-web/src/pages/admin_user_detail.rsmodified+2 -5
@@ -22,10 +22,10 @@ use crate::auth::{check_csrf, two_factor_enabled};
22 use crate::i18n::accounts::{A, t as at};22 use crate::i18n::accounts::{A, t as at};
23 use crate::i18n::admin::{self as g, K};23 use crate::i18n::admin::{self as g, K};
24 use crate::i18n::orgs::{self as og, K as OG};24 use crate::i18n::orgs::{self as og, K as OG};
25+use crate::i18n::s;
25 use crate::i18n::{self, Key, Lang};26 use crate::i18n::{self, Key, Lang};
26 use crate::live::{Topic, stream_changes};27 use crate::live::{Topic, stream_changes};
27 use crate::pages::admin_users::admin_only;28 use crate::pages::admin_users::admin_only;
28-use crate::pages::passkeys::s;
29 use crate::state::AppState;29 use crate::state::AppState;
30 use crate::views::parts::{SubPart, confirm_act, head, post_act};30 use crate::views::parts::{SubPart, confirm_act, head, post_act};
31 use crate::views::{alert, enc, rel_time, rel_time_or_never, shell, user_facing_message};31 use crate::views::{alert, enc, rel_time, rel_time_or_never, shell, user_facing_message};
@@ -662,10 +662,7 @@ async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome,
662 {662 {
663 Ok(()) => {663 Ok(()) => {
664 // A suspension ends the user's sessions: their open tabs must see it.664 // A suspension ends the user's sessions: their open tabs must see it.
665- crate::pages::settings_live::bump_account(665+ crate::live::bump_account(context::<AppState>(cx), &target.id);
666- context::<AppState>(cx),
667- &target.id,
668- );
669 audit(666 audit(
670 AuditAction::UserSuspended,667 AuditAction::UserSuspended,
671 serde_json::json!({ "reason": form.reason.trim() }),668 serde_json::json!({ "reason": form.reason.trim() }),
crates/forge-web/src/pages/admin_users.rsmodified+2 -2
@@ -18,10 +18,10 @@ use crate::audit::{self, Actor, Target};
18 use crate::auth::{check_csrf, current_user, hash_password_async};18 use crate::auth::{check_csrf, current_user, hash_password_async};
19 use crate::i18n::admin::{self as g, K};19 use crate::i18n::admin::{self as g, K};
20 use crate::i18n::orgs::{self as og, K as OG};20 use crate::i18n::orgs::{self as og, K as OG};
21+use crate::i18n::s;
21 use crate::i18n::{self, Key, Lang};22 use crate::i18n::{self, Key, Lang};
22 use crate::live::{Topic, stream_changes};23 use crate::live::{Topic, stream_changes};
23 use crate::pages::issues_list::list_href;24 use crate::pages::issues_list::list_href;
24-use crate::pages::passkeys::s;
25 use crate::state::AppState;25 use crate::state::AppState;
26 use crate::views::find::{Finder, finder_field};26 use crate::views::find::{Finder, finder_field};
27 use crate::views::parts::{RailItem, head, rail, reveal};27 use crate::views::parts::{RailItem, head, rail, reveal};
@@ -657,7 +657,7 @@ async fn user_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl View>
657 match store.delete_user(&target.id, &ghost.id).await {657 match store.delete_user(&target.id, &ghost.id).await {
658 Ok(_) => {658 Ok(_) => {
659 // Their sessions and keys are gone: any open tab of theirs must leave.659 // Their sessions and keys are gone: any open tab of theirs must leave.
660- crate::pages::settings_live::bump_account(context::<AppState>(cx), &target.id);660+ crate::live::bump_account(context::<AppState>(cx), &target.id);
661 audit::record(661 audit::record(
662 store,662 store,
663 Some(cx),663 Some(cx),
crates/forge-web/src/pages/assets.rsmodified+1 -12
@@ -2,8 +2,6 @@
2 //! highlighting classes at `/assets/highlight.css`, and the colours of the hue choices at2 //! highlighting classes at `/assets/highlight.css`, and the colours of the hue choices at
3 //! `/theme/custom.css`.3 //! `/theme/custom.css`.
4 4
5-use std::sync::OnceLock;
6-
7 use topcoat::Result;5 use topcoat::Result;
8 use topcoat::context::Cx;6 use topcoat::context::Cx;
9 use topcoat::router::request::uri;7 use topcoat::router::request::uri;
@@ -12,7 +10,6 @@ use topcoat::router::{HeaderMap, StatusCode, header, route};
12 10
13 use crate::accent;11 use crate::accent;
14 use crate::custom_colour;12 use crate::custom_colour;
15-use crate::render::highlight::highlight_css;
16 use crate::views::{NAV_SCRIPT_HREF, STYLESHEET_HREF, highlight_href};13 use crate::views::{NAV_SCRIPT_HREF, STYLESHEET_HREF, highlight_href};
17 14
18 /// Immutable only when the request names the current version (`href` is the URL the pages link).15 /// Immutable only when the request names the current version (`href` is the URL the pages link).
@@ -31,14 +28,6 @@ fn cache_for(cx: &Cx, href: &str) -> topcoat::router::HeaderValue {
31 28
32 const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css"));29 const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css"));
33 30
34-/// Highlight classes, built once on first use.
35-static HIGHLIGHT_CSS: OnceLock<String> = OnceLock::new();
36-
37-/// The highlight classes, shared by the route and the page links (which hash them).
38-pub fn highlight_css_text() -> &'static str {
39- HIGHLIGHT_CSS.get_or_init(highlight_css).as_str()
40-}
41-
42 /// Immutable when the URL carries the current content hash, so a changed file gets a new URL.31 /// Immutable when the URL carries the current content hash, so a changed file gets a new URL.
43 #[route(GET "/assets/main.css")]32 #[route(GET "/assets/main.css")]
44 async fn main_css(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {33 async fn main_css(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
@@ -82,7 +71,7 @@ async fn highlight_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static
82 .expect("static header value"),71 .expect("static header value"),
83 );72 );
84 headers.insert(header::CACHE_CONTROL, cache_for(cx, highlight_href()));73 headers.insert(header::CACHE_CONTROL, cache_for(cx, highlight_href()));
85- Ok((StatusCode::OK, headers, highlight_css_text()))74+ Ok((StatusCode::OK, headers, crate::views::highlight_css_text()))
86 }75 }
87 76
88 /// The colours of the hue choices on one page. The query names the four choices: `al` and `ad` for77 /// The colours of the hue choices on one page. The query names the four choices: `al` and `ad` for
crates/forge-web/src/pages/audit_log.rsmodified+1 -1
@@ -14,11 +14,11 @@ use topcoat::view::{View, component, view};
14 14
15 use crate::auth::require_user;15 use crate::auth::require_user;
16 use crate::i18n::admin::{self as g, K};16 use crate::i18n::admin::{self as g, K};
17+use crate::i18n::s;
17 use crate::i18n::{self, Lang, audit_names};18 use crate::i18n::{self, Lang, audit_names};
18 use crate::live::{Topic, stream_changes};19 use crate::live::{Topic, stream_changes};
19 use crate::pages::admin_users::admin_only;20 use crate::pages::admin_users::admin_only;
20 use crate::pages::issues_list::list_href;21 use crate::pages::issues_list::list_href;
21-use crate::pages::passkeys::s;
22 use crate::pages::settings_security::security_rail_for;22 use crate::pages::settings_security::security_rail_for;
23 use crate::state::AppState;23 use crate::state::AppState;
24 use crate::views::find::{Finder, finder_field};24 use crate::views::find::{Finder, finder_field};
crates/forge-web/src/pages/avatars.rsmodified+5 -57
@@ -13,13 +13,7 @@ use topcoat::router::request::headers;
13 use topcoat::router::{path_param_segment, query_params, route};13 use topcoat::router::{path_param_segment, query_params, route};
14 14
15 use crate::state::AppState;15 use crate::state::AppState;
16-16+use crate::views::default_svg;
17-/// Background colors for the generated default avatar, picked by the user id hash. Muted sage,
18-/// olive and teal tones, so the default avatars sit with the sage accent. Each keeps white text
19-/// readable (4.5:1 or better).
20-const PALETTE: [&str; 8] = [
21- "#5E7D63", "#4A6750", "#3F5F46", "#4E6E68", "#3E6B63", "#5B6B4E", "#56705F", "#4F6A55",
22-];
23 17
24 const CACHE_IMMUTABLE: &str = "public, max-age=31536000, immutable";18 const CACHE_IMMUTABLE: &str = "public, max-age=31536000, immutable";
25 /// Without a matching `?v=`, the browser revalidates: the ETag gives a cheap 304.19 /// Without a matching `?v=`, the browser revalidates: the ETag gives a cheap 304.
@@ -34,52 +28,6 @@ struct AvatarQuery {
34 v: Option<String>,28 v: Option<String>,
35 }29 }
36 30
37-/// The generated default avatar: the first letter of the username on a palette color picked by
38-/// the username, so a page can draw it inline without asking the server.
39-pub fn default_svg(username: &str) -> String {
40- let digest = Sha256::digest(username.as_bytes());
41- let color = PALETTE[usize::from(digest[0]) % PALETTE.len()];
42- let letter = username
43- .chars()
44- .next()
45- .map_or_else(|| "?".to_owned(), |c| c.to_uppercase().collect());
46- let letter = xml_escape(&letter);
47- format!(
48- r##"<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256"><rect width="256" height="256" fill="{color}"/><text x="128" y="128" dy="0.35em" text-anchor="middle" font-family="sans-serif" font-size="128" fill="#ffffff">{letter}</text></svg>"##
49- )
50-}
51-
52-/// The generated default avatar as a `data:` URL, for an `<img>` of an account known to have no
53-/// photo: the page shows it at once, with no request.
54-pub fn default_data_url(username: &str) -> String {
55- let svg = default_svg(username);
56- let mut out = String::with_capacity(svg.len() + 40);
57- out.push_str("data:image/svg+xml,");
58- for byte in svg.bytes() {
59- if byte.is_ascii_alphanumeric() || b" -_.~/=:;,'()".contains(&byte) {
60- out.push(char::from(byte));
61- } else {
62- out.push_str(&format!("%{byte:02X}"));
63- }
64- }
65- out
66-}
67-
68-fn xml_escape(text: &str) -> String {
69- let mut out = String::with_capacity(text.len());
70- for c in text.chars() {
71- match c {
72- '&' => out.push_str("&amp;"),
73- '<' => out.push_str("&lt;"),
74- '>' => out.push_str("&gt;"),
75- '"' => out.push_str("&quot;"),
76- '\'' => out.push_str("&apos;"),
77- other => out.push(other),
78- }
79- }
80- out
81-}
82-
83 /// True when an `If-None-Match` header lists `etag` (quoted), `*`, or its weak form.31 /// True when an `If-None-Match` header lists `etag` (quoted), `*`, or its weak form.
84 fn etag_matches(if_none_match: &str, etag: &str) -> bool {32 fn etag_matches(if_none_match: &str, etag: &str) -> bool {
85 if_none_match33 if_none_match
@@ -150,16 +98,16 @@ mod tests {
150 98
151 #[test]99 #[test]
152 fn default_svg_escapes_the_letter_and_is_stable() {100 fn default_svg_escapes_the_letter_and_is_stable() {
153- let svg = super::default_svg("<");101+ let svg = crate::views::default_svg("<");
154 assert!(svg.contains(">&lt;</text>"), "{svg}");102 assert!(svg.contains(">&lt;</text>"), "{svg}");
155- assert_eq!(svg, super::default_svg("<"));103+ assert_eq!(svg, crate::views::default_svg("<"));
156- let url = super::default_data_url("<");104+ let url = crate::views::default_data_url("<");
157 assert!(url.starts_with("data:image/svg+xml,%3Csvg"), "{url}");105 assert!(url.starts_with("data:image/svg+xml,%3Csvg"), "{url}");
158 assert!(106 assert!(
159 !url.contains('<') && !url.contains('#') && !url.contains('"'),107 !url.contains('<') && !url.contains('#') && !url.contains('"'),
160 "{url}"108 "{url}"
161 );109 );
162- assert!(super::PALETTE.iter().any(|c| svg.contains(c)));110+ assert!(crate::views::PALETTE.iter().any(|c| svg.contains(c)));
163 }111 }
164 112
165 #[test]113 #[test]
crates/forge-web/src/pages/banner.rsmodified+4 -60
@@ -4,14 +4,11 @@
4 //! in the `forge_banner` cookie for a signed-out visitor, and as the `banner_dismissed` account4 //! in the `forge_banner` cookie for a signed-out visitor, and as the `banner_dismissed` account
5 //! preference for a signed-in user.5 //! preference for a signed-in user.
6 6
7-use std::collections::HashMap;
8 use std::time::Duration;7 use std::time::Duration;
9 8
10-use forge_core::config::BannerConfig;
11-use forge_core::token::hash_token;
12 use serde::Deserialize;9 use serde::Deserialize;
13 use topcoat::Result;10 use topcoat::Result;
14-use topcoat::context::{Cx, context, try_context};11+use topcoat::context::{Cx, context};
15 use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};12 use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
16 use topcoat::router::content::Form;13 use topcoat::router::content::Form;
17 use topcoat::router::error::{SeeOther, see_other};14 use topcoat::router::error::{SeeOther, see_other};
@@ -20,64 +17,10 @@ use topcoat::router::route;
20 use crate::auth::current_user;17 use crate::auth::current_user;
21 use crate::pages::theme_cookie::safe_back;18 use crate::pages::theme_cookie::safe_back;
22 use crate::state::AppState;19 use crate::state::AppState;
23-20+use crate::views::{BANNER_COOKIE, BANNER_PREF};
24-/// Name of the dismissal cookie.
25-pub const BANNER_COOKIE: &str = "forge_banner";
26-
27-/// Account preference key holding the dismissed hash of a signed-in user.
28-pub const BANNER_PREF: &str = "banner_dismissed";
29 21
30 const BANNER_COOKIE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60);22 const BANNER_COOKIE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60);
31 23
32-/// What the shell draws.
33-#[derive(Debug, Clone, PartialEq, Eq)]
34-pub struct BannerView {
35- pub message: String,
36- pub warning: bool,
37- pub hash: String,
38- /// Unix seconds when the banner expires, or `None` for never. The page drops it at that time.
39- pub expires: Option<i64>,
40-}
41-
42-/// Short stable id of a message and level.
43-pub fn banner_hash(message: &str, level: &str) -> String {
44- hash_token(&format!("{level}\n{message}"))[..16].to_owned()
45-}
46-
47-/// The banner to show at `now`, or `None` when it is off, expired or dismissed (`dismissed` is the
48-/// stored hash).
49-pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Option<BannerView> {
50- if !config.active_at(now) {
51- return None;
52- }
53- let message = config.message.trim().to_owned();
54- let hash = banner_hash(&message, &config.level);
55- if dismissed == Some(hash.as_str()) {
56- return None;
57- }
58- Some(BannerView {
59- message,
60- warning: config.level == "warning",
61- hash,
62- expires: config.expires_unix(),
63- })
64-}
65-
66-/// The banner for this request, read from the live settings. `prefs` is a signed-in viewer's
67-/// account preferences; without them the dismissal comes from the cookie.
68-pub fn current(cx: &Cx, prefs: Option<&HashMap<String, String>>) -> Option<BannerView> {
69- let state = try_context::<AppState>(cx)?;
70- let live = state.live();
71- if live.banner.message.trim().is_empty() {
72- return None;
73- }
74- let dismissed = match prefs {
75- Some(prefs) => prefs.get(BANNER_PREF).cloned(),
76- None => cookies(cx).get(BANNER_COOKIE).map(|c| c.value().to_owned()),
77- };
78- view_for(&live.banner, crate::views::now_unix(), dismissed.as_deref())
79-}
80-
81 #[derive(Deserialize)]24 #[derive(Deserialize)]
82 struct DismissForm {25 struct DismissForm {
83 #[serde(default)]26 #[serde(default)]
@@ -112,7 +55,8 @@ async fn dismiss(cx: &Cx, Form(form): Form<DismissForm>) -> Result<SeeOther> {
112 55
113 #[cfg(test)]56 #[cfg(test)]
114 mod tests {57 mod tests {
115- use super::*;58+ use crate::views::view_for;
59+ use forge_core::config::BannerConfig;
116 60
117 fn config(message: &str, level: &str, expires: &str) -> BannerConfig {61 fn config(message: &str, level: &str, expires: &str) -> BannerConfig {
118 BannerConfig {62 BannerConfig {
crates/forge-web/src/pages/blame.rsmodified+2 -2
@@ -14,9 +14,9 @@ use topcoat::view::{Unescaped, View, component, view};
14 14
15 use crate::i18n::browse as b;15 use crate::i18n::browse as b;
16 use crate::i18n::code::{self as g, K};16 use crate::i18n::code::{self as g, K};
17+use crate::i18n::s;
17 use crate::i18n::{self, Lang};18 use crate::i18n::{self, Lang};
18 use crate::pages::blob::{Line, text_lines};19 use crate::pages::blob::{Line, text_lines};
19-use crate::pages::passkeys::s;
20 use crate::pages::ref_live;20 use crate::pages::ref_live;
21 use crate::pages::repo::repo_head;21 use crate::pages::repo::repo_head;
22 use crate::pages::repo_ctx::load_repo;22 use crate::pages::repo_ctx::load_repo;
@@ -240,7 +240,7 @@ async fn blame_page(cx: &Cx) -> Result<impl View> {
240 <div class="sheet-tools">240 <div class="sheet-tools">
241 <strong>(file_name)</strong>241 <strong>(file_name)</strong>
242 <span class="mono">(size)</span>242 <span class="mono">(size)</span>
243- <nav class="sub" aria-label=(crate::pages::passkeys::s(lang, "View", "Görünüm"))>243+ <nav class="sub" aria-label=(crate::i18n::s(lang, "View", "Görünüm"))>
244 <a href=(source_href.as_str())>(crate::i18n::code::t(lang, crate::i18n::code::K::SourceToggle))</a>244 <a href=(source_href.as_str())>(crate::i18n::code::t(lang, crate::i18n::code::K::SourceToggle))</a>
245 <a href="" aria-current="page">(b::t(lang, b::K::BlameLink))</a>245 <a href="" aria-current="page">(b::t(lang, b::K::BlameLink))</a>
246 </nav>246 </nav>
crates/forge-web/src/pages/blob.rsmodified+1 -1
@@ -12,13 +12,13 @@ use topcoat::view::{Unescaped, View, component, view};
12 use crate::i18n::browse as b;12 use crate::i18n::browse as b;
13 use crate::i18n::code::{self as g, K};13 use crate::i18n::code::{self as g, K};
14 use crate::i18n::misc::{self as mi, K as MK};14 use crate::i18n::misc::{self as mi, K as MK};
15+use crate::i18n::s;
15 use crate::i18n::{self};16 use crate::i18n::{self};
16 use crate::lfs::has_object;17 use crate::lfs::has_object;
17 use crate::lfs_pointer;18 use crate::lfs_pointer;
18 use crate::pages::code_live::{follows_branch, live_url};19 use crate::pages::code_live::{follows_branch, live_url};
19 use crate::pages::finder::file_finder;20 use crate::pages::finder::file_finder;
20 use crate::pages::media::media_url;21 use crate::pages::media::media_url;
21-use crate::pages::passkeys::s;
22 use crate::pages::refs::{load_refs, ref_links};22 use crate::pages::refs::{load_refs, ref_links};
23 use crate::pages::repo::repo_head;23 use crate::pages::repo::repo_head;
24 use crate::pages::repo_ctx::load_repo;24 use crate::pages::repo_ctx::load_repo;
crates/forge-web/src/pages/branches.rsmodified+1 -1
@@ -21,7 +21,6 @@ use crate::i18n::browse as b;
21 use crate::i18n::code::{self as g, K};21 use crate::i18n::code::{self as g, K};
22 use crate::i18n::{self, Lang};22 use crate::i18n::{self, Lang};
23 use crate::internal::{is_zero_oid, may_push_directly};23 use crate::internal::{is_zero_oid, may_push_directly};
24-use crate::pages::commits::url_path;
25 use crate::pages::ref_live;24 use crate::pages::ref_live;
26 use crate::pages::refs::ref_rows;25 use crate::pages::refs::ref_rows;
27 use crate::pages::repo::repo_head;26 use crate::pages::repo::repo_head;
@@ -31,6 +30,7 @@ use crate::post_update::after_ref_update;
31 use crate::state::AppState;30 use crate::state::AppState;
32 use crate::views::commit_line::commit_line;31 use crate::views::commit_line::commit_line;
33 use crate::views::parts::{confirm_act, reveal};32 use crate::views::parts::{confirm_act, reveal};
33+use crate::views::url_path;
34 use crate::views::{alert, iso_time, now_unix, relative_time, repo_href, shell};34 use crate::views::{alert, iso_time, now_unix, relative_time, repo_href, shell};
35 35
36 path_param!(owner);36 path_param!(owner);
crates/forge-web/src/pages/ci_job.rsmodified+4 -3
@@ -34,9 +34,10 @@ use crate::i18n::{
34 self, Lang,34 self, Lang,
35 releases_ci::{self as g, K},35 releases_ci::{self as g, K},
36 };36 };
37+use crate::live::{changed_event, events_response};
37 use crate::pages::ci_runs::{38 use crate::pages::ci_runs::{
38- age_text, can_write, changed_event, commit_reachable_for, dock_bars, duration_text,39+ age_text, can_write, commit_reachable_for, dock_bars, duration_text, job_href, run_href,
39- events_response, job_href, run_href, state_text, strip_ansi,40+ state_text, strip_ansi,
40 };41 };
41 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};42 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};
42 use crate::state::AppState;43 use crate::state::AppState;
@@ -480,7 +481,7 @@ async fn job_body(
480 <strong>(g::t(lang, K::Log))</strong>481 <strong>(g::t(lang, K::Log))</strong>
481 <div class="ci-tl-tools">482 <div class="ci-tl-tools">
482 <input type="search" class="ci-logsearch" data-log-q="true" placeholder=(g::t(lang, K::LogSearch)) aria-label=(g::t(lang, K::LogSearch)) autocomplete="off" spellcheck="false">483 <input type="search" class="ci-logsearch" data-log-q="true" placeholder=(g::t(lang, K::LogSearch)) aria-label=(g::t(lang, K::LogSearch)) autocomplete="off" spellcheck="false">
483- <label class="find-opt"><input type="checkbox" data-log-exact="true"><span>(crate::pages::passkeys::s(lang, "Exact", "Tam"))</span></label>484+ <label class="find-opt"><input type="checkbox" data-log-exact="true"><span>(crate::i18n::s(lang, "Exact", "Tam"))</span></label>
484 <label class="find-opt"><input type="checkbox" data-log-case="true"><span>"Aa"</span></label>485 <label class="find-opt"><input type="checkbox" data-log-case="true"><span>"Aa"</span></label>
485 <span class="ci-logcount" data-log-count="true" data-none=(g::t(lang, K::LogNoMatches)) aria-live="polite"></span>486 <span class="ci-logcount" data-log-count="true" data-none=(g::t(lang, K::LogNoMatches)) aria-live="polite"></span>
486 <button type="button" class="act" data-log-prev="true" aria-label=(g::t(lang, K::LogPrev))>"\u{2191}"</button>487 <button type="button" class="act" data-log-prev="true" aria-label=(g::t(lang, K::LogPrev))>"\u{2191}"</button>
crates/forge-web/src/pages/ci_runs.rsmodified+8 -175
@@ -11,12 +11,11 @@
11 use std::collections::{HashMap, HashSet};11 use std::collections::{HashMap, HashSet};
12 use std::future::Future;12 use std::future::Future;
13 use std::path::Path;13 use std::path::Path;
14-use std::time::Duration;
15 14
16 use forge_core::ci::{CiJob, CiRun, JobSample, JobState, JobStep, RunState, StepSample, StepState};15 use forge_core::ci::{CiJob, CiRun, JobSample, JobState, JobStep, RunState, StepSample, StepState};
17 use forge_core::{Action, Denied, Store, User, authorize};16 use forge_core::{Action, Denied, Store, User, authorize};
18 use forge_git::browse::{RefInfo, RefKind, commit_reachable, reachable_commits, read_commit};17 use forge_git::browse::{RefInfo, RefKind, commit_reachable, reachable_commits, read_commit};
19-use futures_util::{Stream, StreamExt, stream};18+use futures_util::{Stream, stream};
20 use serde::Deserialize;19 use serde::Deserialize;
21 use time::OffsetDateTime;20 use time::OffsetDateTime;
22 use time::format_description::well_known::Rfc3339;21 use time::format_description::well_known::Rfc3339;
@@ -25,7 +24,7 @@ use tokio::sync::watch;
25 use topcoat::Result;24 use topcoat::Result;
26 use topcoat::context::{Cx, context};25 use topcoat::context::{Cx, context};
27 use topcoat::router::content::Form;26 use topcoat::router::content::Form;
28-use topcoat::router::content::sse::{Event, KeepAlive, Sse};27+use topcoat::router::content::sse::Event;
29 use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};28 use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};
30 use topcoat::router::request::uri;29 use topcoat::router::request::uri;
31 use topcoat::router::response::{IntoResponse, Response};30 use topcoat::router::response::{IntoResponse, Response};
@@ -39,6 +38,7 @@ use crate::i18n::{
39 self, Lang,38 self, Lang,
40 releases_ci::{self as g, K},39 releases_ci::{self as g, K},
41 };40 };
41+use crate::live::{Status, changed_event, changed_stream, events_response};
42 use crate::pages::admin_runners::confirm_post;42 use crate::pages::admin_runners::confirm_post;
43 use crate::pages::ci_estimate::{self, Est, Step};43 use crate::pages::ci_estimate::{self, Est, Step};
44 use crate::pages::ci_fail::{self, FailFirst, fail_first_block};44 use crate::pages::ci_fail::{self, FailFirst, fail_first_block};
@@ -2465,7 +2465,7 @@ async fn run_head(
2465 if run.can_cancel && run.stopping {2465 if run.can_cancel && run.stopping {
2466 <button type="button" class="ci-stopping" disabled="disabled">(g::t(lang, K::StoppingButton))</button>2466 <button type="button" class="ci-stopping" disabled="disabled">(g::t(lang, K::StoppingButton))</button>
2467 } else if run.can_cancel {2467 } else if run.can_cancel {
2468- confirm_post(lang: lang, csrf: csrf.as_str(), action: cancel_action.as_str(), label: g::t(lang, K::Cancel), message: crate::pages::passkeys::s(lang, "Cancel this run?", "Bu çalıştırma iptal edilsin mi?").to_owned(), confirm: crate::pages::passkeys::s(lang, "Yes, cancel", "Evet, iptal et"), fields: vec![])2468+ confirm_post(lang: lang, csrf: csrf.as_str(), action: cancel_action.as_str(), label: g::t(lang, K::Cancel), message: crate::i18n::s(lang, "Cancel this run?", "Bu çalıştırma iptal edilsin mi?").to_owned(), confirm: crate::i18n::s(lang, "Yes, cancel", "Evet, iptal et"), fields: vec![])
2469 }2469 }
2470 if rerun_failed_shown {2470 if rerun_failed_shown {
2471 action_button(action: format!("{}/rerun-failed", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::RerunFailed), primary: true)2471 action_button(action: format!("{}/rerun-failed", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::RerunFailed), primary: true)
@@ -2643,7 +2643,7 @@ async fn run_log(
2643 if let Some(log) = run.log.as_ref() {2643 if let Some(log) = run.log.as_ref() {
2644 <div class="ci-tl-tools">2644 <div class="ci-tl-tools">
2645 <input type="search" class="ci-logsearch" data-log-q="true" placeholder=(g::t(lang, K::LogSearch)) aria-label=(g::t(lang, K::LogSearch)) autocomplete="off" spellcheck="false">2645 <input type="search" class="ci-logsearch" data-log-q="true" placeholder=(g::t(lang, K::LogSearch)) aria-label=(g::t(lang, K::LogSearch)) autocomplete="off" spellcheck="false">
2646- <label class="find-opt"><input type="checkbox" data-log-exact="true"><span>(crate::pages::passkeys::s(lang, "Exact", "Tam"))</span></label>2646+ <label class="find-opt"><input type="checkbox" data-log-exact="true"><span>(crate::i18n::s(lang, "Exact", "Tam"))</span></label>
2647 <label class="find-opt"><input type="checkbox" data-log-case="true"><span>"Aa"</span></label>2647 <label class="find-opt"><input type="checkbox" data-log-case="true"><span>"Aa"</span></label>
2648 <span class="ci-logcount" data-log-count="true" data-none=(g::t(lang, K::LogNoMatches)) aria-live="polite"></span>2648 <span class="ci-logcount" data-log-count="true" data-none=(g::t(lang, K::LogNoMatches)) aria-live="polite"></span>
2649 <button type="button" class="act" data-log-prev="true" aria-label=(g::t(lang, K::LogPrev))>"\u{2191}"</button>2649 <button type="button" class="act" data-log-prev="true" aria-label=(g::t(lang, K::LogPrev))>"\u{2191}"</button>
@@ -2677,12 +2677,12 @@ async fn run_log(
2677 // Only the end of a long log is sent: say where it starts and where the rest is.2677 // Only the end of a long log is sent: say where it starts and where the rest is.
2678 if log.truncated {2678 if log.truncated {
2679 <p class="log-cut">2679 <p class="log-cut">
2680- (crate::pages::passkeys::s(lang, "Showing from line ", "Şu satırdan itibaren gösteriliyor: "))2680+ (crate::i18n::s(lang, "Showing from line ", "Şu satırdan itibaren gösteriliyor: "))
2681 <span class="num">(log.first_line.as_str())</span>2681 <span class="num">(log.first_line.as_str())</span>
2682- " \u{b7} " <a class="act" href=(log.log_href.as_str())>(crate::pages::passkeys::s(lang, "Full log", "Tam günlük"))</a>2682+ " \u{b7} " <a class="act" href=(log.log_href.as_str())>(crate::i18n::s(lang, "Full log", "Tam günlük"))</a>
2683 </p>2683 </p>
2684 }2684 }
2685- <pre class="ci-log ci-tl-code" data-fail-at=(run.failing.as_ref().filter(|_| !log.at_step).and_then(FailFirst::line_no).map(|no| no.to_string())) data-empty=(crate::pages::passkeys::s(lang, "No output yet.", "Henüz çıktı yok.")) data-live=(log.live.as_deref()) data-live-log="true" data-offset=(log.offset.as_str()) data-first=(log.first_line.as_str()) data-log-start=(log.at_step.then_some("true"))>(log.text.as_str())</pre>2685+ <pre class="ci-log ci-tl-code" data-fail-at=(run.failing.as_ref().filter(|_| !log.at_step).and_then(FailFirst::line_no).map(|no| no.to_string())) data-empty=(crate::i18n::s(lang, "No output yet.", "Henüz çıktı yok.")) data-live=(log.live.as_deref()) data-live-log="true" data-offset=(log.offset.as_str()) data-first=(log.first_line.as_str()) data-log-start=(log.at_step.then_some("true"))>(log.text.as_str())</pre>
2686 } else {2686 } else {
2687 <p class="hint">(g::t(lang, K::NoJobs))</p>2687 <p class="hint">(g::t(lang, K::NoJobs))</p>
2688 }2688 }
@@ -2860,13 +2860,6 @@ async fn manual_run_post(cx: &Cx, Form(form): Form<ManualForm>) -> Result<SeeOth
2860 Ok(see_other(run_href(&title, run.number)))2860 Ok(see_other(run_href(&title, run.number)))
2861 }2861 }
2862 2862
2863-/// How often an idle event stream sends a `: keepalive` comment, so a reverse proxy does not drop
2864-/// the connection. This is not a poll: events follow the change signals.
2865-const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30);
2866-
2867-/// A run's or job's status word and whether it is terminal. `None` when the row is gone.
2868-pub(crate) type Status = Option<(String, bool)>;
2869-
2870 pub(crate) async fn run_status(store: &Store, run_id: &str) -> Result<Status> {2863 pub(crate) async fn run_status(store: &Store, run_id: &str) -> Result<Status> {
2871 Ok(store2864 Ok(store
2872 .run_by_id(run_id)2865 .run_by_id(run_id)
@@ -2874,75 +2867,6 @@ pub(crate) async fn run_status(store: &Store, run_id: &str) -> Result<Status> {
2874 .map(|run| (run.state.as_str().to_owned(), run_finished(&run.state))))2867 .map(|run| (run.state.as_str().to_owned(), run_finished(&run.state))))
2875 }2868 }
2876 2869
2877-/// One `changed` event carrying the status word.
2878-pub(crate) fn changed_event(status: String) -> Result<Event> {
2879- Ok(Event::new().event("changed").data(status))
2880-}
2881-
2882-/// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event
2883-/// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when
2884-/// the status differs from the last one sent. The stream ends after the terminal status is sent,
2885-/// when the row is gone, or when the signal closes. Subscribe `wake` before the first read, so a
2886-/// change in between is not lost.
2887-pub(crate) fn changed_stream<F, Fut>(
2888- wake: watch::Receiver<u64>,
2889- only_on_status: bool,
2890- name: &'static str,
2891- read: F,
2892-) -> impl Stream<Item = Result<Event>> + Send + 'static
2893-where
2894- F: Fn() -> Fut + Send + 'static,
2895- Fut: Future<Output = Result<Status>> + Send,
2896-{
2897- struct Follow<F> {
2898- wake: watch::Receiver<u64>,
2899- only_on_status: bool,
2900- read: F,
2901- /// The status last read, sent or not.
2902- last: Option<String>,
2903- /// Set once a terminal status is read. Nothing follows it.
2904- done: bool,
2905- /// False until the first read. Every later read waits for a wake first.
2906- primed: bool,
2907- }
2908- stream::unfold(
2909- Follow {
2910- wake,
2911- only_on_status,
2912- read,
2913- last: None,
2914- done: false,
2915- primed: false,
2916- },
2917- move |mut follow| async move {
2918- loop {
2919- if follow.done {
2920- return None;
2921- }
2922- if follow.primed && follow.wake.changed().await.is_err() {
2923- return None;
2924- }
2925- follow.primed = true;
2926- let (status, terminal) = match (follow.read)().await {
2927- Ok(Some(found)) => found,
2928- Ok(None) => return None,
2929- Err(e) => {
2930- tracing::error!(error = %e, "ci: live stream could not read the status");
2931- return None;
2932- }
2933- };
2934- follow.done = terminal;
2935- let changed = follow.last.as_deref() != Some(status.as_str());
2936- let send = changed || !follow.only_on_status;
2937- follow.last = Some(status.clone());
2938- if send {
2939- return Some((Ok(Event::new().event(name).data(status)), follow));
2940- }
2941- }
2942- },
2943- )
2944-}
2945-
2946 /// One `changed` event per wake of `wake`. The repo list has no status to compare, so each wake is2870 /// One `changed` event per wake of `wake`. The repo list has no status to compare, so each wake is
2947 /// sent. The stream ends when the signal closes.2871 /// sent. The stream ends when the signal closes.
2948 fn repo_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>> + Send + 'static {2872 fn repo_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>> + Send + 'static {
@@ -2952,97 +2876,6 @@ fn repo_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>>
2952 })2876 })
2953 }2877 }
2954 2878
2955-/// Open event streams one client address (IPv6 by /64) may hold. A page holds one or two, so this
2956-/// is many tabs; past it a script that opens streams in a loop is refused.
2957-const MAX_STREAMS_PER_CLIENT: usize = 64;
2958-/// Open event streams server-wide. Each is a task and a socket that stay until the client leaves.
2959-const MAX_STREAMS: usize = 4096;
2960-
2961-/// Open streams per client address, and their sum.
2962-static OPEN_STREAMS: std::sync::Mutex<(usize, Option<HashMap<std::net::IpAddr, usize>>)> =
2963- std::sync::Mutex::new((0, None));
2964-
2965-/// One open event stream, counted against its client's and the server's cap until dropped.
2966-/// `ip` is `None` for an uncounted stream.
2967-struct StreamSlot {
2968- ip: Option<std::net::IpAddr>,
2969-}
2970-
2971-impl StreamSlot {
2972- /// A slot for this request's client, or `None` when a cap is reached. Without the app state
2973- /// (unit tests of a bare router) nothing is counted.
2974- fn take(cx: &Cx) -> Option<StreamSlot> {
2975- if topcoat::context::try_context::<AppState>(cx).is_none() {
2976- return Some(StreamSlot { ip: None });
2977- }
2978- let ip = crate::client_ip::client_ip(cx);
2979- let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner());
2980- let (total, per_client) = &mut *open;
2981- let count = per_client
2982- .get_or_insert_with(HashMap::new)
2983- .entry(ip)
2984- .or_insert(0);
2985- if *total >= MAX_STREAMS || *count >= MAX_STREAMS_PER_CLIENT {
2986- return None;
2987- }
2988- *count += 1;
2989- *total += 1;
2990- Some(StreamSlot { ip: Some(ip) })
2991- }
2992-}
2993-
2994-impl Drop for StreamSlot {
2995- fn drop(&mut self) {
2996- let Some(ip) = self.ip else {
2997- return;
2998- };
2999- let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner());
3000- let (total, per_client) = &mut *open;
3001- *total = total.saturating_sub(1);
3002- if let Some(map) = per_client.as_mut()
3003- && let Some(count) = map.get_mut(&ip)
3004- {
3005- *count = count.saturating_sub(1);
3006- if *count == 0 {
3007- map.remove(&ip);
3008- }
3009- }
3010- }
3011-}
3012-
3013-/// How long the browser waits before it reconnects a dropped event stream. The browser's default is
3014-/// a few seconds; one second makes a page come back as soon as a server restart is done.
3015-pub(crate) const STREAM_RETRY: Duration = Duration::from_secs(1);
3016-
3017-/// The response of an event stream: keep-alive comments while idle, no buffering by a reverse
3018-/// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`.
3019-pub(crate) fn events_response(
3020- cx: &Cx,
3021- events: impl Stream<Item = Result<Event>> + Send + 'static,
3022-) -> Result<Response> {
3023- // Past the cap the stream is refused: the page keeps working, only without live updates.
3024- let Some(slot) = StreamSlot::take(cx) else {
3025- let mut res = Response::new(topcoat::router::Body::from("too many open live streams"));
3026- *res.status_mut() = http::StatusCode::TOO_MANY_REQUESTS;
3027- return Ok(res);
3028- };
3029- // The slot lives as long as the stream: it is given back when the client goes away.
3030- let events = events.map(move |event| {
3031- let _held = &slot;
3032- event
3033- });
3034- let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY))));
3035- let events = Sse::new(retry.chain(events)).keep_alive(
3036- KeepAlive::new()
3037- .interval(STREAM_KEEP_ALIVE)
3038- .text("keepalive"),
3039- );
3040- let mut res = events.into_response(cx)?;
3041- res.headers_mut()
3042- .insert("x-accel-buffering", HeaderValue::from_static("no"));
3043- Ok(res)
3044-}
3045-
3046 /// The live `changed` stream of a run that is not finished. It is sent on every change to the run2879 /// The live `changed` stream of a run that is not finished. It is sent on every change to the run
3047 /// or to one of its jobs, so the page can render its rows again.2880 /// or to one of its jobs, so the page can render its rows again.
3048 #[route(GET "/{owner}/{repo}/ci/runs/{run_number}/events")]2881 #[route(GET "/{owner}/{repo}/ci/runs/{run_number}/events")]
crates/forge-web/src/pages/commits.rsmodified+4 -17
@@ -17,8 +17,8 @@ use topcoat::router::{page, path_param, query_params};
17 use topcoat::view::{View, view};17 use topcoat::view::{View, view};
18 18
19 use crate::i18n::code::{self as g, K};19 use crate::i18n::code::{self as g, K};
20+use crate::i18n::s;
20 use crate::i18n::{self, Lang};21 use crate::i18n::{self, Lang};
21-use crate::pages::passkeys::s;
22 use crate::pages::ref_live;22 use crate::pages::ref_live;
23 use crate::pages::repo::repo_head;23 use crate::pages::repo::repo_head;
24 use crate::pages::repo_ctx::load_repo;24 use crate::pages::repo_ctx::load_repo;
@@ -28,7 +28,7 @@ use crate::signatures::{self, SigBadge};
28 use crate::state::AppState;28 use crate::state::AppState;
29 use crate::views::commit_line::commit_line;29 use crate::views::commit_line::commit_line;
30 use crate::views::commit_status::{StatusLang, StatusSummary, commit_status, status_list};30 use crate::views::commit_status::{StatusLang, StatusSummary, commit_status, status_list};
31-use crate::views::shell;31+use crate::views::{shell, url_path};
32 32
33 path_param!(owner);33 path_param!(owner);
34 path_param!(repo);34 path_param!(repo);
@@ -88,20 +88,6 @@ pub(crate) fn iso_time(at: i64) -> String {
88 )88 )
89 }89 }
90 90
91-/// Percent-encodes each byte outside the unreserved set, keeping `/` as the separator.
92-pub(crate) fn url_path(path: &str) -> String {
93- let mut out = String::with_capacity(path.len());
94- for b in path.bytes() {
95- match b {
96- b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
97- out.push(char::from(b));
98- }
99- _ => out.push_str(&format!("%{b:02X}")),
100- }
101- }
102- out
103-}
104-
105 /// Seven-character abbreviation, as shown in lists.91 /// Seven-character abbreviation, as shown in lists.
106 pub(crate) fn short_oid(oid: &str) -> &str {92 pub(crate) fn short_oid(oid: &str) -> &str {
107 oid.get(..7).unwrap_or(oid)93 oid.get(..7).unwrap_or(oid)
@@ -594,10 +580,11 @@ pub(crate) mod test_support {
594 mod tests {580 mod tests {
595 use forge_core::Visibility;581 use forge_core::Visibility;
596 582
583+ use super::iso_time;
597 use super::test_support::{Fixture, OWNER, REPO, get, git};584 use super::test_support::{Fixture, OWNER, REPO, get, git};
598- use super::{iso_time, url_path};
599 use crate::i18n::Lang;585 use crate::i18n::Lang;
600 use crate::views::relative_time;586 use crate::views::relative_time;
587+ use crate::views::url_path;
601 588
602 #[test]589 #[test]
603 fn dates_and_relative_units_format() {590 fn dates_and_relative_units_format() {
crates/forge-web/src/pages/compare.rsmodified+2 -1
@@ -30,7 +30,7 @@ use crate::i18n;
30 use crate::i18n::pulls::{self as g, K};30 use crate::i18n::pulls::{self as g, K};
31 use crate::notify::{self, Activity};31 use crate::notify::{self, Activity};
32 use crate::pages::commit::Download;32 use crate::pages::commit::Download;
33-use crate::pages::commits::{CommitRow, blocking, now_secs, short_oid, url_path};33+use crate::pages::commits::{CommitRow, blocking, now_secs, short_oid};
34 use crate::pages::ref_live;34 use crate::pages::ref_live;
35 use crate::pages::repo::repo_head;35 use crate::pages::repo::repo_head;
36 use crate::pages::repo_ctx::{RepoCtx, load_repo};36 use crate::pages::repo_ctx::{RepoCtx, load_repo};
@@ -39,6 +39,7 @@ use crate::templates;
39 use crate::views::commit_line::commit_line;39 use crate::views::commit_line::commit_line;
40 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};40 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};
41 use crate::views::parts::reveal;41 use crate::views::parts::reveal;
42+use crate::views::url_path;
42 use crate::views::{alert, repo_href, shell, user_facing_message};43 use crate::views::{alert, repo_href, shell, user_facing_message};
43 use crate::webhooks::emit::{Sender, emit_pull};44 use crate::webhooks::emit::{Sender, emit_pull};
44 45
crates/forge-web/src/pages/discussion_settings.rsmodified+1 -1
@@ -32,7 +32,7 @@ pub(crate) async fn discussions_switch(
32 csrf: String,32 csrf: String,
33 enabled: bool,33 enabled: bool,
34 ) -> Result<impl View> {34 ) -> Result<impl View> {
35- let switch_label = crate::pages::passkeys::s(lang, "Discussions", "Tartışmalar");35+ let switch_label = crate::i18n::s(lang, "Discussions", "Tartışmalar");
36 Ok(view! {36 Ok(view! {
37 <form method="post" action=(action.as_str()) id="discussions">37 <form method="post" action=(action.as_str()) id="discussions">
38 <input type="hidden" name="csrf" value=(csrf.as_str())>38 <input type="hidden" name="csrf" value=(csrf.as_str())>
crates/forge-web/src/pages/discussion_view.rsmodified+2 -1
@@ -19,12 +19,13 @@ use crate::pages::discussions::{
19 discussion_by_number, discussions_href, ensure_enabled, is_author, may_converse,19 discussion_by_number, discussions_href, ensure_enabled, is_author, may_converse,
20 };20 };
21 use crate::pages::issue_meta::can_triage;21 use crate::pages::issue_meta::can_triage;
22-use crate::pages::issue_parts::{ReactionBar, When, csrf_of, reaction_bar_for, reaction_row};22+use crate::pages::issue_parts::{ReactionBar, csrf_of, reaction_bar_for, reaction_row};
23 use crate::pages::repo::repo_head;23 use crate::pages::repo::repo_head;
24 use crate::pages::repo_ctx::{RepoCtx, load_repo};24 use crate::pages::repo_ctx::{RepoCtx, load_repo};
25 use crate::pages::tree::link_context;25 use crate::pages::tree::link_context;
26 use crate::render::markdown::{LinkContext, render_markdown};26 use crate::render::markdown::{LinkContext, render_markdown};
27 use crate::state::AppState;27 use crate::state::AppState;
28+use crate::views::When;
28 use crate::views::parts::{SubPart, confirm_act, post_act, reveal};29 use crate::views::parts::{SubPart, confirm_act, post_act, reveal};
29 use crate::views::{avatar_url, display_name, now_unix, shell, user_href, user_link};30 use crate::views::{avatar_url, display_name, now_unix, shell, user_href, user_link};
30 31
crates/forge-web/src/pages/discussions.rsmodified+1 -1
@@ -21,12 +21,12 @@ use crate::i18n::community::{self as g, K};
21 use crate::i18n::{self, Lang};21 use crate::i18n::{self, Lang};
22 use crate::pages::discussion_live::list_live_url;22 use crate::pages::discussion_live::list_live_url;
23 use crate::pages::issue_meta::{can_triage, form_field, form_pairs, refusal_message};23 use crate::pages::issue_meta::{can_triage, form_field, form_pairs, refusal_message};
24-use crate::pages::issue_parts::When;
25 use crate::pages::issues_list::list_href;24 use crate::pages::issues_list::list_href;
26 use crate::pages::repo::repo_head;25 use crate::pages::repo::repo_head;
27 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};26 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
28 use crate::render::markdown::mentioned_usernames;27 use crate::render::markdown::mentioned_usernames;
29 use crate::state::AppState;28 use crate::state::AppState;
29+use crate::views::When;
30 use crate::views::parts::{RailItem, SubPart, rail};30 use crate::views::parts::{RailItem, SubPart, rail};
31 use crate::views::{alert, csrf_field, now_unix, repo_href, shell, user_link};31 use crate::views::{alert, csrf_field, now_unix, repo_href, shell, user_link};
32 32
crates/forge-web/src/pages/edit_history.rsmodified+2 -1
@@ -17,12 +17,13 @@ use topcoat::view::{View, component, view};
17 17
18 use crate::i18n::issues::{self as g, K};18 use crate::i18n::issues::{self as g, K};
19 use crate::i18n::{self, Lang};19 use crate::i18n::{self, Lang};
20-use crate::pages::issue_parts::{ItemKind, When, item_for, parse_number};20+use crate::pages::issue_parts::{ItemKind, item_for, parse_number};
21 use crate::pages::issues_live::item_live_url;21 use crate::pages::issues_live::item_live_url;
22 use crate::pages::pull_live::pull_live_url;22 use crate::pages::pull_live::pull_live_url;
23 use crate::pages::repo::repo_head;23 use crate::pages::repo::repo_head;
24 use crate::pages::repo_ctx::{RepoCtx, load_repo};24 use crate::pages::repo_ctx::{RepoCtx, load_repo};
25 use crate::state::AppState;25 use crate::state::AppState;
26+use crate::views::When;
26 use crate::views::parts::SubPart;27 use crate::views::parts::SubPart;
27 use crate::views::{display_name, now_unix, repo_href, shell};28 use crate::views::{display_name, now_unix, repo_href, shell};
28 29
crates/forge-web/src/pages/explore.rsmodified+2 -2
@@ -301,7 +301,7 @@ async fn explore_body(
301 explore_href(&Finder::default(), sort, 1)301 explore_href(&Finder::default(), sort, 1)
302 };302 };
303 let placeholder = if on_orgs {303 let placeholder = if on_orgs {
304- crate::pages::passkeys::s(lang, "Search organizations", "Kuruluşlarda ara")304+ crate::i18n::s(lang, "Search organizations", "Kuruluşlarda ara")
305 } else {305 } else {
306 g::t(lang, K::SearchPublicRepos)306 g::t(lang, K::SearchPublicRepos)
307 };307 };
@@ -311,7 +311,7 @@ async fn explore_body(
311 (_, n) => format!("{n} organizations"),311 (_, n) => format!("{n} organizations"),
312 };312 };
313 let empty_text = if on_orgs {313 let empty_text = if on_orgs {
314- crate::pages::passkeys::s(lang, "No organization matches.", "Eşleşen kuruluş yok.")314+ crate::i18n::s(lang, "No organization matches.", "Eşleşen kuruluş yok.")
315 } else {315 } else {
316 g::t(lang, K::NoPublicReposMatch)316 g::t(lang, K::NoPublicReposMatch)
317 };317 };
crates/forge-web/src/pages/home.rsmodified+1 -1
@@ -16,10 +16,10 @@ use crate::i18n::authoring::{self as ga};
16 use crate::i18n::migrate::{self as mg, K as MGK};16 use crate::i18n::migrate::{self as mg, K as MGK};
17 use crate::i18n::needs::{self as ni, K as NK};17 use crate::i18n::needs::{self as ni, K as NK};
18 use crate::i18n::orgs::{self as g, K};18 use crate::i18n::orgs::{self as g, K};
19+use crate::i18n::s;
19 use crate::i18n::{self, Lang};20 use crate::i18n::{self, Lang};
20 use crate::pages::ci_runs::run_href;21 use crate::pages::ci_runs::run_href;
21 use crate::pages::org_new::may_create_org;22 use crate::pages::org_new::may_create_org;
22-use crate::pages::passkeys::s;
23 use crate::pages::repo_settings::{notice_banner_for, take_notice};23 use crate::pages::repo_settings::{notice_banner_for, take_notice};
24 use crate::state::AppState;24 use crate::state::AppState;
25 use crate::views::parts::head;25 use crate::views::parts::head;
crates/forge-web/src/pages/import.rsmodified+3 -3
@@ -27,7 +27,7 @@ use crate::importer::{
27 parse_remote, source_ref,27 parse_remote, source_ref,
28 };28 };
29 use crate::live::{Topic, stream_changes};29 use crate::live::{Topic, stream_changes};
30-use crate::pages::ci_runs::{changed_event, events_response};30+use crate::live::{changed_event, events_response};
31 use crate::pages::new_repo::{owner_choices, repo_owner};31 use crate::pages::new_repo::{owner_choices, repo_owner};
32 use crate::pages::repo_ctx::still_readable;32 use crate::pages::repo_ctx::still_readable;
33 use crate::state::AppState;33 use crate::state::AppState;
@@ -173,7 +173,7 @@ pub(crate) async fn newrepo_tabs(cx: &Cx, lang: Lang, active: &str) -> Result<im
173 <nav class="tabs" aria-label=(g::t(lang, K::ImportTitle))>173 <nav class="tabs" aria-label=(g::t(lang, K::ImportTitle))>
174 <a href="/new" aria-current=(create.then_some("page"))>(g::t(lang, K::TabCreate))</a>174 <a href="/new" aria-current=(create.then_some("page"))>(g::t(lang, K::TabCreate))</a>
175 <a href="/new/import" aria-current=(import.then_some("page"))>(g::t(lang, K::TabImport))</a>175 <a href="/new/import" aria-current=(import.then_some("page"))>(g::t(lang, K::TabImport))</a>
176- <a href="/import" aria-current=(history.then_some("page"))>(crate::pages::passkeys::s(lang, "Import history", "İçe aktarma geçmişi"))</a>176+ <a href="/import" aria-current=(history.then_some("page"))>(crate::i18n::s(lang, "Import history", "İçe aktarma geçmişi"))</a>
177 </nav>177 </nav>
178 })178 })
179 }179 }
@@ -186,7 +186,7 @@ async fn source_tabs(cx: &Cx, lang: Lang, base: &str, active: Source) -> Result<
186 let forgejo = format!("{base}?source=forgejo");186 let forgejo = format!("{base}?source=forgejo");
187 Ok(view! {187 Ok(view! {
188 <div class="field">188 <div class="field">
189- <span class="field-label">(crate::pages::passkeys::s(lang, "Source", "Kaynak"))</span>189+ <span class="field-label">(crate::i18n::s(lang, "Source", "Kaynak"))</span>
190 <nav class="choice" aria-label=(g::t(lang, K::TabImport))>190 <nav class="choice" aria-label=(g::t(lang, K::TabImport))>
191 <a href=(git.as_str()) aria-current=((active == Source::Git).then_some("page"))>(g::t(lang, K::SrcGit))</a>191 <a href=(git.as_str()) aria-current=((active == Source::Git).then_some("page"))>(g::t(lang, K::SrcGit))</a>
192 <a href=(github.as_str()) aria-current=((active == Source::GitHub).then_some("page"))>(g::t(lang, K::SrcGitHub))</a>192 <a href=(github.as_str()) aria-current=((active == Source::GitHub).then_some("page"))>(g::t(lang, K::SrcGitHub))</a>
crates/forge-web/src/pages/issue_parts.rsmodified+3 -55
@@ -30,8 +30,8 @@ use crate::views::parts::{confirm_act, post_act, reveal};
30 use crate::views::review_thread::{ThreadCtx, review_thread_in};30 use crate::views::review_thread::{ThreadCtx, review_thread_in};
31 use crate::views::user_facing_message;31 use crate::views::user_facing_message;
32 use crate::views::{32 use crate::views::{
33- alert, avatar_url, avatar_url_unknown, display_name, iso_time, now_unix, relative_time,33+ When, alert, avatar_url, avatar_url_unknown, display_name, now_unix, repo_href, short_oid,
34- repo_href, short_oid, user_href, user_link,34+ stamp_unix, user_href, user_link,
35 };35 };
36 use crate::webhooks::emit::{Sender, emit_comment, emit_item_action};36 use crate::webhooks::emit::{Sender, emit_comment, emit_item_action};
37 37
@@ -170,58 +170,6 @@ pub(crate) async fn comment_for(
170 }170 }
171 }171 }
172 172
173-// Times
174-
175-/// A stored timestamp shown as an absolute `title` and a relative label.
176-#[derive(Clone)]
177-pub(crate) struct When {
178- pub(crate) iso: String,
179- pub(crate) absolute: String,
180- pub(crate) relative: String,
181-}
182-
183-impl When {
184- pub(crate) fn new(lang: Lang, stamp: &str, tz: &str, now: i64) -> Self {
185- let unix = stamp_unix(stamp);
186- Self {
187- iso: iso_time(unix),
188- absolute: forge_core::tz::format_in_tz(unix, tz),
189- relative: relative_time(lang, unix, now),
190- }
191- }
192-}
193-
194-/// Unix seconds of a stored RFC 3339 UTC stamp (`YYYY-MM-DDTHH:MM:SS[.frac]Z`). Malformed input is 0.
195-pub(crate) fn stamp_unix(stamp: &str) -> i64 {
196- let field = |range: std::ops::Range<usize>| {
197- stamp
198- .get(range)
199- .and_then(|digits| digits.parse::<i64>().ok())
200- };
201- let (Some(y), Some(mo), Some(d), Some(h), Some(mi), Some(s)) = (
202- field(0..4),
203- field(5..7),
204- field(8..10),
205- field(11..13),
206- field(14..16),
207- field(17..19),
208- ) else {
209- return 0;
210- };
211- days_from_civil(y, mo, d) * 86_400 + h * 3_600 + mi * 60 + s
212-}
213-
214-/// Days since 1970-01-01 for a civil date (Howard Hinnant's days-from-civil).
215-fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
216- let y = if month <= 2 { year - 1 } else { year };
217- let era = y.div_euclid(400);
218- let yoe = y - era * 400;
219- let mp = (month + 9) % 12;
220- let doy = (153 * mp + 2) / 5 + day - 1;
221- let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
222- era * 146_097 + doe - 719_468
223-}
224-
225 pub(crate) fn is_hex_oid(s: &str) -> bool {173 pub(crate) fn is_hex_oid(s: &str) -> bool {
226 (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())174 (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
227 }175 }
@@ -1055,7 +1003,7 @@ pub(crate) fn reaction_bar_for(
1055 /// The hover text of a reaction: who made it, and how many more beyond the first names.1003 /// The hover text of a reaction: who made it, and how many more beyond the first names.
1056 /// A reaction's name in the viewer's language, for its picker button.1004 /// A reaction's name in the viewer's language, for its picker button.
1057 fn reaction_label(lang: Lang, reaction: Reaction) -> &'static str {1005 fn reaction_label(lang: Lang, reaction: Reaction) -> &'static str {
1058- use crate::pages::passkeys::s;1006+ use crate::i18n::s;
1059 match reaction {1007 match reaction {
1060 Reaction::PlusOne => "+1",1008 Reaction::PlusOne => "+1",
1061 Reaction::MinusOne => "-1",1009 Reaction::MinusOne => "-1",
crates/forge-web/src/pages/issues_list.rsmodified+1 -1
@@ -17,11 +17,11 @@ use topcoat::view::{View, component, view};
17 17
18 use crate::auth::{require_csrf, require_user};18 use crate::auth::{require_csrf, require_user};
19 use crate::i18n::issues::{self as g, K};19 use crate::i18n::issues::{self as g, K};
20+use crate::i18n::s;
20 use crate::i18n::{self, Lang};21 use crate::i18n::{self, Lang};
21 use crate::notify::{self, Activity};22 use crate::notify::{self, Activity};
22 use crate::pages::issue_meta::{can_triage, form_all, form_field, form_pairs};23 use crate::pages::issue_meta::{can_triage, form_all, form_field, form_pairs};
23 use crate::pages::issues_live::list_live_url;24 use crate::pages::issues_live::list_live_url;
24-use crate::pages::passkeys::s;
25 use crate::pages::repo::repo_head;25 use crate::pages::repo::repo_head;
26 use crate::pages::repo_ctx::{RepoHead, load_repo};26 use crate::pages::repo_ctx::{RepoHead, load_repo};
27 use crate::state::AppState;27 use crate::state::AppState;
crates/forge-web/src/pages/login.rsmodified+2 -1
@@ -21,8 +21,9 @@ use crate::auth::{
21 set_pending_login, two_factor_enabled, verify_password_async, verify_second_factor,21 set_pending_login, two_factor_enabled, verify_password_async, verify_second_factor,
22 };22 };
23 use crate::client_ip::client_ip;23 use crate::client_ip::client_ip;
24+use crate::i18n::s;
24 use crate::i18n::{self, Key, Lang, t};25 use crate::i18n::{self, Key, Lang, t};
25-use crate::pages::passkeys::{available as passkeys_available, login_passkey, s};26+use crate::pages::passkeys::{available as passkeys_available, login_passkey};
26 use crate::state::AppState;27 use crate::state::AppState;
27 use crate::throttle::{self, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT};28 use crate::throttle::{self, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT};
28 use crate::views::parts::head;29 use crate::views::parts::head;
crates/forge-web/src/pages/merge_queue.rsmodified+2 -3
@@ -28,8 +28,8 @@ use topcoat::view::{View, component, view};
28 use crate::auth::require_csrf;28 use crate::auth::require_csrf;
29 use crate::i18n::merge_queue::{self as g, K};29 use crate::i18n::merge_queue::{self as g, K};
30 use crate::i18n::{self, Lang};30 use crate::i18n::{self, Lang};
31+use crate::live::{changed_event, events_response};
31 use crate::merge_queue as queue;32 use crate::merge_queue as queue;
32-use crate::pages::ci_runs::{changed_event, events_response};
33 use crate::pages::issue_parts::parse_number;33 use crate::pages::issue_parts::parse_number;
34 use crate::pages::pulls_merge::ERR_NOT_OPEN;34 use crate::pages::pulls_merge::ERR_NOT_OPEN;
35 use crate::pages::repo::repo_head;35 use crate::pages::repo::repo_head;
@@ -361,8 +361,7 @@ async fn queue_body(
361 ) -> Result<impl View> {361 ) -> Result<impl View> {
362 let remove_label = g::t(lang, K::RemoveFromQueue);362 let remove_label = g::t(lang, K::RemoveFromQueue);
363 let remove_note =363 let remove_note =
364- crate::pages::passkeys::s(lang, "Remove it from the queue?", "Sıradan çıkarılsın mı?")364+ crate::i18n::s(lang, "Remove it from the queue?", "Sıradan çıkarılsın mı?").to_owned();
365- .to_owned();
366 Ok(view! {365 Ok(view! {
367 repo_head(head: head, title: Some(g::t(lang, K::MergeQueueTitle).to_owned()))366 repo_head(head: head, title: Some(g::t(lang, K::MergeQueueTitle).to_owned()))
368 <nav class="tabs" aria-label=(g::t(lang, K::MergeQueueNav))>367 <nav class="tabs" aria-label=(g::t(lang, K::MergeQueueNav))>
crates/forge-web/src/pages/notifications.rsmodified+4 -3
@@ -27,15 +27,16 @@ use crate::auth::{current_user, percent_encode, require_csrf, require_user};
27 use crate::i18n::alerts as alert_text;27 use crate::i18n::alerts as alert_text;
28 use crate::i18n::misc::{self as g, K};28 use crate::i18n::misc::{self as g, K};
29 use crate::i18n::{self, Key, Lang};29 use crate::i18n::{self, Key, Lang};
30+use crate::live::events_response;
30 use crate::live::{Topic, stream_changes};31 use crate::live::{Topic, stream_changes};
31 use crate::notify_hub::publish_unread;32 use crate::notify_hub::publish_unread;
32-use crate::pages::ci_runs::events_response;33+use crate::pages::issue_parts::parse_number;
33-use crate::pages::issue_parts::{parse_number, stamp_unix};
34 use crate::pages::repo_ctx::{RepoCtx, load_repo};34 use crate::pages::repo_ctx::{RepoCtx, load_repo};
35 use crate::pages::repo_transfer::transfer_list_for;35 use crate::pages::repo_transfer::transfer_list_for;
36 use crate::pages::star::return_path;36 use crate::pages::star::return_path;
37 use crate::state::AppState;37 use crate::state::AppState;
38 use crate::views::parts::{RailItem, head, post_act, rail};38 use crate::views::parts::{RailItem, head, post_act, rail};
39+use crate::views::stamp_unix;
39 use crate::views::{csrf_field, display_name, iso_time, now_unix, relative_time, repo_href, shell};40 use crate::views::{csrf_field, display_name, iso_time, now_unix, relative_time, repo_href, shell};
40 41
41 /// Rows per inbox page. Older rows come behind the older link, so one page stays short.42 /// Rows per inbox page. Older rows come behind the older link, so one page stays short.
@@ -822,7 +823,7 @@ async fn set_subscription(cx: &Cx, pull: bool, form: &SubscriptionForm) -> Resul
822 }823 }
823 // The page's button shows the viewer's subscription, so the page and its stream are woken.824 // The page's button shows the viewer's subscription, so the page and its stream are woken.
824 if pull {825 if pull {
825- crate::pages::pull_live::bump_pull(state, &ctx.repo.id, &issue.id);826+ crate::live::bump_pull(state, &ctx.repo.id, &issue.id);
826 } else {827 } else {
827 state828 state
828 .live829 .live
crates/forge-web/src/pages/org_members.rsmodified+1 -2
@@ -22,7 +22,6 @@ use crate::pages::org_ctx::{
22 load_org, member_role_word, notice_href, org_notice, org_tab_counts, org_tabs,22 load_org, member_role_word, notice_href, org_notice, org_tab_counts, org_tabs,
23 parse_member_role, require_form_csrf, require_member, require_owner, take_notice,23 parse_member_role, require_form_csrf, require_member, require_owner, take_notice,
24 };24 };
25-use crate::pages::passkeys;
26 use crate::state::AppState;25 use crate::state::AppState;
27 use crate::views::parts::{PeopleList, PersonRow, SubPart, head, people_list};26 use crate::views::parts::{PeopleList, PersonRow, SubPart, head, people_list};
28 use crate::views::{avatar_url, display_name, shell};27 use crate::views::{avatar_url, display_name, shell};
@@ -100,7 +99,7 @@ async fn members_body(
100 username_label: g::t(lang, K::Username).to_owned(),99 username_label: g::t(lang, K::Username).to_owned(),
101 role_label: g::t(lang, K::Role).to_owned(),100 role_label: g::t(lang, K::Role).to_owned(),
102 save_label: g::t(lang, K::Save).to_owned(),101 save_label: g::t(lang, K::Save).to_owned(),
103- open_label: passkeys::s(lang, "Open profile", "Profili aç").to_owned(),102+ open_label: crate::i18n::s(lang, "Open profile", "Profili aç").to_owned(),
104 empty: None,103 empty: None,
105 };104 };
106 Ok(view! {105 Ok(view! {
crates/forge-web/src/pages/org_settings.rsmodified+3 -3
@@ -96,7 +96,7 @@ async fn settings_body(
96 <form id="org-settings-form" method="post" action=(save_action.as_str())>96 <form id="org-settings-form" method="post" action=(save_action.as_str())>
97 <input type="hidden" name="csrf" value=(csrf.as_str())>97 <input type="hidden" name="csrf" value=(csrf.as_str())>
98 <section class="sec">98 <section class="sec">
99- <h2>(crate::pages::passkeys::s(lang, "Details", "Ayrıntılar"))</h2>99+ <h2>(crate::i18n::s(lang, "Details", "Ayrıntılar"))</h2>
100 <div class="field">100 <div class="field">
101 <label for="org-display-name">(g::t(lang, K::DisplayNameLabel))</label>101 <label for="org-display-name">(g::t(lang, K::DisplayNameLabel))</label>
102 <input id="org-display-name" type="text" name="display_name" maxlength="80" value=(display_name.as_str())>102 <input id="org-display-name" type="text" name="display_name" maxlength="80" value=(display_name.as_str())>
@@ -107,7 +107,7 @@ async fn settings_body(
107 </div>107 </div>
108 </section>108 </section>
109 <section class="sec">109 <section class="sec">
110- <h2>(crate::pages::passkeys::s(lang, "Members", "Üyeler"))</h2>110+ <h2>(crate::i18n::s(lang, "Members", "Üyeler"))</h2>
111 <div class="field">111 <div class="field">
112 <label for="org-default-role">(g::t(lang, K::DefaultRoleLabel))</label>112 <label for="org-default-role">(g::t(lang, K::DefaultRoleLabel))</label>
113 <select id="org-default-role" name="default_repo_role">113 <select id="org-default-role" name="default_repo_role">
@@ -157,7 +157,7 @@ async fn settings_body(
157 </div>157 </div>
158 <div class="acts asks">158 <div class="acts asks">
159 <button type="submit" class="danger small">(g::t(lang, K::DeleteOrg))</button>159 <button type="submit" class="danger small">(g::t(lang, K::DeleteOrg))</button>
160- <button type="button" class="act" data-close-details="">(crate::pages::passkeys::s(lang, "Cancel", "Vazgeç"))</button>160+ <button type="button" class="act" data-close-details="">(crate::i18n::s(lang, "Cancel", "Vazgeç"))</button>
161 </div>161 </div>
162 </form>162 </form>
163 </details>163 </details>
crates/forge-web/src/pages/org_teams.rsmodified+2 -3
@@ -22,7 +22,6 @@ use crate::pages::org_ctx::{
22 OrgCtx, TEAM_ROLES, load_org, notice_href, org_notice, org_tab_counts, org_tabs,22 OrgCtx, TEAM_ROLES, load_org, notice_href, org_notice, org_tab_counts, org_tabs,
23 require_form_csrf, require_member, require_owner, take_notice,23 require_form_csrf, require_member, require_owner, take_notice,
24 };24 };
25-use crate::pages::passkeys;
26 use crate::state::AppState;25 use crate::state::AppState;
27 use crate::views::parts::{SubPart, confirm_act, head, reveal};26 use crate::views::parts::{SubPart, confirm_act, head, reveal};
28 use crate::views::{avatar_url, display_name, repo_href, shell};27 use crate::views::{avatar_url, display_name, repo_href, shell};
@@ -350,7 +349,7 @@ async fn team_body(
350 </summary>349 </summary>
351 <div class="opened">350 <div class="opened">
352 <div class="acts">351 <div class="acts">
353- <a class="act" href=(format!("/{}", member.username.as_str()))>(passkeys::s(lang, "Open profile", "Profili aç"))</a>352+ <a class="act" href=(format!("/{}", member.username.as_str()))>(crate::i18n::s(lang, "Open profile", "Profili aç"))</a>
354 confirm_act(lang: lang, label: g::t(lang, K::Remove), action: remove_member_action.as_str(), csrf: csrf.as_str(), fields: vec![("user_id".to_owned(), member.user_id.clone())])353 confirm_act(lang: lang, label: g::t(lang, K::Remove), action: remove_member_action.as_str(), csrf: csrf.as_str(), fields: vec![("user_id".to_owned(), member.user_id.clone())])
355 </div>354 </div>
356 </div>355 </div>
@@ -394,7 +393,7 @@ async fn team_body(
394 </summary>393 </summary>
395 <div class="opened">394 <div class="opened">
396 <div class="acts">395 <div class="acts">
397- <a class="act" href=(repo.href.as_str())>(passkeys::s(lang, "Open repository", "Depoyu aç"))</a>396+ <a class="act" href=(repo.href.as_str())>(crate::i18n::s(lang, "Open repository", "Depoyu aç"))</a>
398 confirm_act(lang: lang, label: g::t(lang, K::Unlink), action: remove_repo_action.as_str(), csrf: csrf.as_str(), fields: vec![("repo_id".to_owned(), repo.repo_id.clone())])397 confirm_act(lang: lang, label: g::t(lang, K::Unlink), action: remove_repo_action.as_str(), csrf: csrf.as_str(), fields: vec![("repo_id".to_owned(), repo.repo_id.clone())])
399 </div>398 </div>
400 </div>399 </div>
crates/forge-web/src/pages/packages.rsmodified+1 -1
@@ -20,9 +20,9 @@ use topcoat::view::{Unescaped, View, component, view};
20 use crate::auth::{current_user, require_csrf};20 use crate::auth::{current_user, require_csrf};
21 use crate::i18n::packages::{self as pk, K};21 use crate::i18n::packages::{self as pk, K};
22 use crate::i18n::{self, Lang};22 use crate::i18n::{self, Lang};
23+use crate::live::{changed_event, events_response};
23 use crate::oci::manifests;24 use crate::oci::manifests;
24 use crate::package_ops::{self, PackageError};25 use crate::package_ops::{self, PackageError};
25-use crate::pages::ci_runs::{changed_event, events_response};
26 use crate::pages::packages_oci::{self, oci_package_view};26 use crate::pages::packages_oci::{self, oci_package_view};
27 use crate::render::markdown::render_markdown;27 use crate::render::markdown::render_markdown;
28 use crate::state::AppState;28 use crate::state::AppState;
crates/forge-web/src/pages/palette.rsmodified+1 -1
@@ -29,10 +29,10 @@ use crate::auth::current_user;
29 use crate::i18n::code::{self, K as CK};29 use crate::i18n::code::{self, K as CK};
30 use crate::i18n::orgs::{self as g, K};30 use crate::i18n::orgs::{self as g, K};
31 use crate::i18n::repo_admin::{self as ra, K as RK};31 use crate::i18n::repo_admin::{self as ra, K as RK};
32+use crate::i18n::s;
32 use crate::i18n::{self, Lang};33 use crate::i18n::{self, Lang};
33 use crate::pages::admin_server::{PAGES, page_of};34 use crate::pages::admin_server::{PAGES, page_of};
34 use crate::pages::org_new::may_create_org;35 use crate::pages::org_new::may_create_org;
35-use crate::pages::passkeys::s;
36 use crate::state::AppState;36 use crate::state::AppState;
37 use crate::views::{37 use crate::views::{
38 admin_items, enc, global_items, profile_items, repo_href, settings_items, user_href,38 admin_items, enc, global_items, profile_items, repo_href, settings_items, user_href,
crates/forge-web/src/pages/passkeys.rsmodified+1 -9
@@ -38,7 +38,7 @@ use crate::auth::{
38 check_pre_csrf, clear_pending_login, clear_pre_csrf, login, require_csrf, safe_next,38 check_pre_csrf, clear_pending_login, clear_pre_csrf, login, require_csrf, safe_next,
39 };39 };
40 use crate::client_ip::client_ip;40 use crate::client_ip::client_ip;
41-use crate::i18n::{self, Key, Lang, t};41+use crate::i18n::{self, Key, Lang, s, t};
42 use crate::mail::account::{PasskeyChange, send_passkey_notice};42 use crate::mail::account::{PasskeyChange, send_passkey_notice};
43 use crate::state::AppState;43 use crate::state::AppState;
44 use crate::throttle::{self, LOGIN_IP_LIMIT};44 use crate::throttle::{self, LOGIN_IP_LIMIT};
@@ -50,14 +50,6 @@ const CEREMONY_TTL: Duration = Duration::from_secs(5 * 60);
50 /// Ceremonies held at once. A start past this is refused until old ones expire.50 /// Ceremonies held at once. A start past this is refused until old ones expire.
51 const CEREMONY_CAP: usize = 4096;51 const CEREMONY_CAP: usize = 4096;
52 52
53-/// Picks the English or Turkish text.
54-pub fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str {
55- match lang {
56- Lang::En => en,
57- Lang::Tr => tr,
58- }
59-}
60-
61 // ---- relying party ----53 // ---- relying party ----
62 54
63 /// Why passkeys cannot be offered on this server.55 /// Why passkeys cannot be offered on this server.
crates/forge-web/src/pages/pull_branch.rsmodified+2 -2
@@ -379,7 +379,7 @@ pub(crate) async fn branch_box(
379 action: Option<BranchAction>,379 action: Option<BranchAction>,
380 error: Option<String>,380 error: Option<String>,
381 ) -> Result<impl View> {381 ) -> Result<impl View> {
382- let heading = crate::pages::passkeys::s(lang, "Branch", "Dal");382+ let heading = crate::i18n::s(lang, "Branch", "Dal");
383 Ok(view! {383 Ok(view! {
384 <section class="sec">384 <section class="sec">
385 <h2>(heading)</h2>385 <h2>(heading)</h2>
@@ -396,7 +396,7 @@ pub(crate) async fn branch_box(
396 <p>(g::t(lang, K::BranchPrefix)) " " <code>(a.branch.as_str())</code> " " (g::t(lang, K::BranchStillHere))</p>396 <p>(g::t(lang, K::BranchPrefix)) " " <code>(a.branch.as_str())</code> " " (g::t(lang, K::BranchStillHere))</p>
397 <div class="acts">397 <div class="acts">
398 confirm_act(lang: lang, label: g::t(lang, K::DeleteBranch), action: a.action.as_str(), csrf: a.csrf.as_str(),398 confirm_act(lang: lang, label: g::t(lang, K::DeleteBranch), action: a.action.as_str(), csrf: a.csrf.as_str(),
399- note: Some(crate::pages::passkeys::s(lang, "The branch is removed from the repo. Its commits stay in the pull request.", "Dal depodan kaldırılır. Commit'leri çekme isteğinde kalır.").to_owned()))399+ note: Some(crate::i18n::s(lang, "The branch is removed from the repo. Its commits stay in the pull request.", "Dal depodan kaldırılır. Commit'leri çekme isteğinde kalır.").to_owned()))
400 </div>400 </div>
401 }401 }
402 }402 }
crates/forge-web/src/pages/pull_files.rsmodified+2 -3
@@ -27,7 +27,6 @@ use crate::i18n::pulls::{self as g, K};
27 use crate::i18n::{self, Lang};27 use crate::i18n::{self, Lang};
28 use crate::pages::edit_history::thread_edit_counts;28 use crate::pages::edit_history::thread_edit_counts;
29 use crate::pages::issue_parts::{check_write, csrf_of, may_converse, parse_number, triage, viewer};29 use crate::pages::issue_parts::{check_write, csrf_of, may_converse, parse_number, triage, viewer};
30-use crate::pages::passkeys;
31 use crate::pages::pull_reviews::{error_text_in, pull_diff, suggest_states};30 use crate::pages::pull_reviews::{error_text_in, pull_diff, suggest_states};
32 use crate::pages::pull_view::{commits_of, frame_in, is_merged, pull_header};31 use crate::pages::pull_view::{commits_of, frame_in, is_merged, pull_header};
33 use crate::pages::repo_ctx::{RepoCtx, load_repo};32 use crate::pages::repo_ctx::{RepoCtx, load_repo};
@@ -214,7 +213,7 @@ async fn files_rail(
214 let mark = g::t(lang, K::ViewedMark);213 let mark = g::t(lang, K::ViewedMark);
215 let changed = g::t(lang, K::ChangedSinceViewed);214 let changed = g::t(lang, K::ChangedSinceViewed);
216 let viewed_files = g::t(lang, K::ViewedFiles);215 let viewed_files = g::t(lang, K::ViewedFiles);
217- let heading = passkeys::s(lang, "Files", "Dosyalar");216+ let heading = crate::i18n::s(lang, "Files", "Dosyalar");
218 Ok(view! {217 Ok(view! {
219 <nav class="rail" aria-label=(viewed_files)>218 <nav class="rail" aria-label=(viewed_files)>
220 <h2>(heading) " " <span>(done_text.as_str())</span></h2>219 <h2>(heading) " " <span>(done_text.as_str())</span></h2>
@@ -359,7 +358,7 @@ async fn review_bar(
359 let comment = g::t(lang, K::CommentChoice).trim();358 let comment = g::t(lang, K::CommentChoice).trim();
360 let approve = review_strings::t(lang, review_strings::K::ApproveChoice).trim();359 let approve = review_strings::t(lang, review_strings::K::ApproveChoice).trim();
361 let changes = review_strings::t(lang, review_strings::K::RequestChangesChoice).trim();360 let changes = review_strings::t(lang, review_strings::K::RequestChangesChoice).trim();
362- let next_text = passkeys::s(lang, "Next file", "Sonraki dosya");361+ let next_text = crate::i18n::s(lang, "Next file", "Sonraki dosya");
363 let threads_text = match lang {362 let threads_text = match lang {
364 Lang::Tr => format!("{open_threads} açık konu"),363 Lang::Tr => format!("{open_threads} açık konu"),
365 Lang::En if open_threads == 1 => "1 open thread".to_owned(),364 Lang::En if open_threads == 1 => "1 open thread".to_owned(),
crates/forge-web/src/pages/pull_live.rsmodified+6 -48
@@ -5,11 +5,12 @@
5 //! Every write reaches a topic through one of these paths:5 //! Every write reaches a topic through one of these paths:
6 //! - A POST under `/{o}/{r}/pulls/...` (comment, review, label, merge, draft, branch, ...): the6 //! - A POST under `/{o}/{r}/pulls/...` (comment, review, label, merge, draft, branch, ...): the
7 //! [`PullWriteLayer`] bumps after the handler ran, so no route calls a bump itself.7 //! [`PullWriteLayer`] bumps after the handler ran, so no route calls a bump itself.
8-//! - A commit status (CI or the status API): [`bump_head`], from `automerge::on_status`.8+//! - A commit status (CI or the status API): [`crate::live::bump_head`], from `automerge::on_status`.
9-//! - A push, a mergeability refresh or an auto-merge: [`bump_repo_pulls`], from the call site.9+//! - A push, a mergeability refresh or an auto-merge: [`crate::live::bump_repo_pulls`], from the
10+//! call site.
10 //!11 //!
11-//! The bump helpers are the one place each topic is bumped from. A new write path calls one of12+//! The bump helpers in [`crate::live`] are the one place each topic is bumped from. A new write
12-//! them; it does not bump a topic directly.13+//! path calls one of them; it does not bump a topic directly.
13 //!14 //!
14 //! What a stream compares is a fingerprint of what the page shows ([`pull_fingerprint`],15 //! What a stream compares is a fingerprint of what the page shows ([`pull_fingerprint`],
15 //! [`list_fingerprint`]). A bump that changes none of it sends nothing, so over-bumping is cheap.16 //! [`list_fingerprint`]). A bump that changes none of it sends nothing, so over-bumping is cheap.
@@ -23,7 +24,7 @@ use topcoat::router::request::{method, uri};
23 use topcoat::router::response::Response;24 use topcoat::router::response::Response;
24 use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};25 use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};
25 26
26-use crate::live::{Topic, stream_changes};27+use crate::live::{Topic, bump_list, bump_pull, bump_repo_pulls, stream_changes};
27 use crate::pages::issue_parts::parse_number;28 use crate::pages::issue_parts::parse_number;
28 use crate::pages::repo_ctx::load_repo;29 use crate::pages::repo_ctx::load_repo;
29 use crate::state::AppState;30 use crate::state::AppState;
@@ -32,49 +33,6 @@ path_param!(owner);
32 path_param!(repo);33 path_param!(repo);
33 path_param!(number);34 path_param!(number);
34 35
35-// Bumps. Each one wakes the streams of the topics it names; none of them reads more than the
36-// ids it needs. A failed lookup is logged and leaves the streams as they were.
37-
38-/// A write changed one pull request: its page and the list both follow it.
39-pub fn bump_pull(state: &AppState, repo_id: &str, issue_id: &str) {
40- state.live.bump(&Topic::Pull(issue_id.to_owned()));
41- bump_list(state, repo_id);
42-}
43-
44-/// A pull request was opened, or the list changed for another reason. Only the list follows.
45-pub fn bump_list(state: &AppState, repo_id: &str) {
46- state.live.bump(&Topic::PullList(repo_id.to_owned()));
47-}
48-
49-/// A change that may touch any pull of the repo (a push, a label or milestone edit, a merge run
50-/// by auto-merge): the list and every pull page of the repo.
51-pub async fn bump_repo_pulls(state: &AppState, repo_id: &str) {
52- bump_list(state, repo_id);
53- match state.store.pull_refs(repo_id).await {
54- Ok(refs) => {
55- for (issue_id, _) in refs {
56- state.live.bump(&Topic::Pull(issue_id));
57- }
58- }
59- Err(e) => tracing::error!(error = %e, repo_id, "live: listing pulls to bump failed"),
60- }
61-}
62-
63-/// A commit status was written for `sha`: the pulls whose head is that commit, and the list.
64-pub async fn bump_head(state: &AppState, repo_id: &str, sha: &str) {
65- bump_list(state, repo_id);
66- match state.store.pulls_for_head_oid(repo_id, sha).await {
67- Ok(refs) => {
68- for (issue_id, _) in refs {
69- state.live.bump(&Topic::Pull(issue_id));
70- }
71- }
72- Err(e) => {
73- tracing::error!(error = %e, repo_id, "live: listing pulls for a head to bump failed")
74- }
75- }
76-}
77-
78 // Fingerprints. Each reads what the page shows; any change to it changes the string.36 // Fingerprints. Each reads what the page shows; any change to it changes the string.
79 37
80 /// What one pull request page shows, as one string. `viewer` is the reader: a pending review is38 /// What one pull request page shows, as one string. `viewer` is the reader: a pending review is
crates/forge-web/src/pages/pull_view.rsmodified+3 -2
@@ -25,7 +25,7 @@ use crate::i18n::{self, Lang};
25 use crate::pages::commits::{CommitRow, now_secs};25 use crate::pages::commits::{CommitRow, now_secs};
26 use crate::pages::issue_meta::item_href;26 use crate::pages::issue_meta::item_href;
27 use crate::pages::issue_parts::{27 use crate::pages::issue_parts::{
28- CommentForm, ItemKind, Posted, When, check_write, comment_form, csrf_of, discussion_timeline,28+ CommentForm, ItemKind, Posted, check_write, comment_form, csrf_of, discussion_timeline,
29 item_head_tools, item_sidebar, load_discussion, load_sidebar, lock_message, may_change,29 item_head_tools, item_sidebar, load_discussion, load_sidebar, lock_message, may_change,
30 may_converse, parse_number, post_comment, reachable_among, triage, viewer,30 may_converse, parse_number, post_comment, reachable_among, triage, viewer,
31 };31 };
@@ -42,6 +42,7 @@ use crate::pages::pulls_merge::{
42 use crate::pages::repo_ctx::{RepoCtx, load_repo};42 use crate::pages::repo_ctx::{RepoCtx, load_repo};
43 use crate::pages::review_requests::{load_reviewers, reviewers_box};43 use crate::pages::review_requests::{load_reviewers, reviewers_box};
44 use crate::state::AppState;44 use crate::state::AppState;
45+use crate::views::When;
45 use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary, commit_status};46 use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary, commit_status};
46 use crate::views::diff::LIMITS;47 use crate::views::diff::LIMITS;
47 use crate::views::parts::{confirm_act, post_act, reveal};48 use crate::views::parts::{confirm_act, post_act, reveal};
@@ -512,7 +513,7 @@ async fn review_box(
512 lang: Lang,513 lang: Lang,
513 ) -> Result<impl View> {514 ) -> Result<impl View> {
514 let dismiss_text = g::t(lang, K::DismissButton);515 let dismiss_text = g::t(lang, K::DismissButton);
515- let heading = crate::pages::passkeys::s(lang, "Reviews", "İncelemeler");516+ let heading = crate::i18n::s(lang, "Reviews", "İncelemeler");
516 Ok(view! {517 Ok(view! {
517 <section class="sec">518 <section class="sec">
518 <h2>(heading)</h2>519 <h2>(heading)</h2>
crates/forge-web/src/pages/pulls_list.rsmodified+1 -1
@@ -14,11 +14,11 @@ use topcoat::view::{View, view};
14 14
15 use crate::i18n::merge_queue as mq;15 use crate::i18n::merge_queue as mq;
16 use crate::i18n::pulls::{self as g, K};16 use crate::i18n::pulls::{self as g, K};
17+use crate::i18n::s;
17 use crate::i18n::{self, Lang};18 use crate::i18n::{self, Lang};
18 use crate::pages::issues_list::{19 use crate::pages::issues_list::{
19 AssigneeView, LabelView, ListQuery, MilestoneView, Selection, SortOption, list_href, stamp_unix,20 AssigneeView, LabelView, ListQuery, MilestoneView, Selection, SortOption, list_href, stamp_unix,
20 };21 };
21-use crate::pages::passkeys::s;
22 use crate::pages::repo::repo_head;22 use crate::pages::repo::repo_head;
23 use crate::pages::repo_ctx::load_repo;23 use crate::pages::repo_ctx::load_repo;
24 use crate::state::AppState;24 use crate::state::AppState;
crates/forge-web/src/pages/push.rsmodified+1 -1
@@ -27,7 +27,7 @@ use topcoat::router::{Body, HeaderMap, StatusCode, header, route};
27 27
28 use crate::api::{self, json};28 use crate::api::{self, json};
29 use crate::auth::{current_user, require_csrf, require_user};29 use crate::auth::{current_user, require_csrf, require_user};
30-use crate::pages::ci_runs::events_response;30+use crate::live::events_response;
31 use crate::state::AppState;31 use crate::state::AppState;
32 use crate::web_push::{self, Alert, crypto};32 use crate::web_push::{self, Alert, crypto};
33 use crate::webhooks::client::{WebhookPolicy, validate_url};33 use crate::webhooks::client::{WebhookPolicy, validate_url};
crates/forge-web/src/pages/releases.rsmodified+1 -1
@@ -36,7 +36,6 @@ use crate::i18n::{
36 self, Key, Lang,36 self, Key, Lang,
37 releases_ci::{self as g, K},37 releases_ci::{self as g, K},
38 };38 };
39-use crate::pages::issue_parts::When;
40 use crate::pages::refs::load_refs;39 use crate::pages::refs::load_refs;
41 use crate::pages::releases_live;40 use crate::pages::releases_live;
42 use crate::pages::repo::repo_head;41 use crate::pages::repo::repo_head;
@@ -44,6 +43,7 @@ use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
44 use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};43 use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};
45 use crate::render::markdown::render_markdown;44 use crate::render::markdown::render_markdown;
46 use crate::state::AppState;45 use crate::state::AppState;
46+use crate::views::When;
47 use crate::views::parts::{confirm_act, reveal};47 use crate::views::parts::{confirm_act, reveal};
48 use crate::views::repo_list::{PageLink, pager, pager_links};48 use crate::views::repo_list::{PageLink, pager, pager_links};
49 use crate::views::{alert, empty_state, enc, now_unix, shell, user_link};49 use crate::views::{alert, empty_state, enc, now_unix, shell, user_link};
crates/forge-web/src/pages/repo.rsmodified+5 -43
@@ -5,7 +5,6 @@ use std::collections::{HashMap, HashSet};
5 use std::path::PathBuf;5 use std::path::PathBuf;
6 use std::time::Duration;6 use std::time::Duration;
7 7
8-use forge_core::Config;
9 use forge_core::Repo as RepoRecord;8 use forge_core::Repo as RepoRecord;
10 use forge_core::WatchLevel;9 use forge_core::WatchLevel;
11 use forge_core::time::stamp_before;10 use forge_core::time::stamp_before;
@@ -18,13 +17,12 @@ use topcoat::router::{page, path_param, route};
18 use topcoat::view::{Child, View, ViewExt, component, view};17 use topcoat::view::{Child, View, ViewExt, component, view};
19 18
20 use crate::i18n::code::{self as g, K};19 use crate::i18n::code::{self as g, K};
20+use crate::i18n::s;
21 use crate::i18n::{self, Lang};21 use crate::i18n::{self, Lang};
22 use crate::pages::code_live::{follows_branch, home_live_url};22 use crate::pages::code_live::{follows_branch, home_live_url};
23 use crate::pages::finder::file_finder;23 use crate::pages::finder::file_finder;
24-use crate::pages::issue_parts::stamp_unix;
25 use crate::pages::notifications::watch_form;24 use crate::pages::notifications::watch_form;
26 use crate::pages::packages;25 use crate::pages::packages;
27-use crate::pages::passkeys::s;
28 use crate::pages::refs::{load_refs, ref_links};26 use crate::pages::refs::{load_refs, ref_links};
29 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};27 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
30 use crate::pages::repo_side::{StripFacts, code_sub, commit_strip, run_pips, run_rows, tree_facts};28 use crate::pages::repo_side::{StripFacts, code_sub, commit_strip, run_pips, run_rows, tree_facts};
@@ -33,50 +31,14 @@ use crate::pages::tree::{
33 };31 };
34 use crate::state::AppState;32 use crate::state::AppState;
35 use crate::views::parts::{SubPart, head_sub};33 use crate::views::parts::{SubPart, head_sub};
36-use crate::views::{now_unix, ref_selector, relative_time, repo_href, repo_tabs, shell};34+use crate::views::{
35+ https_clone_url, now_unix, ref_selector, relative_time, repo_href, repo_tabs, shell,
36+ ssh_clone_url, stamp_unix, tab_title,
37+};
37 38
38 path_param!(owner);39 path_param!(owner);
39 path_param!(repo);40 path_param!(repo);
40 41
41-/// HTTPS clone URL: `{base_url}/{owner}/{repo}.git`.
42-pub fn https_clone_url(config: &Config, owner: &str, name: &str) -> String {
43- format!(
44- "{}/{owner}/{name}.git",
45- config.base_url.trim_end_matches('/')
46- )
47-}
48-
49-/// SSH clone URL. Port 22 uses the scp-like form `git@host:owner/repo.git`.
50-pub fn ssh_clone_url(config: &Config, owner: &str, name: &str) -> String {
51- let host = &config.ssh_public_host;
52- if config.ssh_public_port == 22 {
53- format!("git@{host}:{owner}/{name}.git")
54- } else {
55- format!(
56- "ssh://git@{host}:{}/{owner}/{name}.git",
57- config.ssh_public_port
58- )
59- }
60-}
61-
62-/// The title a repo page shows when it gives none: the tab it is on.
63-pub(crate) fn tab_title(lang: Lang, active: &str, repo: &str) -> String {
64- match active {
65- "issues" => g::t(lang, K::TabIssues).to_owned(),
66- "pulls" => g::t(lang, K::TabPulls).to_owned(),
67- "ci" => g::t(lang, K::TabCi).to_owned(),
68- "commits" => g::t(lang, K::TabCommits).to_owned(),
69- "branches" => g::t(lang, K::BranchesTitle).to_owned(),
70- "tags" => g::t(lang, K::TagsTitle).to_owned(),
71- "releases" => g::t(lang, K::TabReleases).to_owned(),
72- "discussions" => g::t(lang, K::TabDiscussions).to_owned(),
73- "wiki" => g::t(lang, K::TabWiki).to_owned(),
74- "security" => i18n::t(lang, i18n::Key::Security).to_owned(),
75- "settings" => g::t(lang, K::TabSettings).to_owned(),
76- _ => repo.to_owned(),
77- }
78-}
79-
80 /// Head of every repo page: the title with its actions right beside it, the sub line and the tabs.42 /// Head of every repo page: the title with its actions right beside it, the sub line and the tabs.
81 /// The Code tab's head is the repo itself: its name, Clone, Star, Fork and the rest in a menu. Any43 /// The Code tab's head is the repo itself: its name, Clone, Star, Fork and the rest in a menu. Any
82 /// other tab's head is that tab (or `title`), and `child` holds the page's own actions. `sub` is44 /// other tab's head is that tab (or `title`), and `child` holds the page's own actions. `sub` is
crates/forge-web/src/pages/repo_collaborators.rsmodified+2 -3
@@ -25,7 +25,6 @@ use crate::audit::{self, Actor, Target};
25 use crate::auth::{require_csrf, require_user};25 use crate::auth::{require_csrf, require_user};
26 use crate::i18n::repo_admin::{self as g, K};26 use crate::i18n::repo_admin::{self as g, K};
27 use crate::i18n::{self, Lang};27 use crate::i18n::{self, Lang};
28-use crate::pages::passkeys;
29 use crate::pages::repo::repo_head;28 use crate::pages::repo::repo_head;
30 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};29 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
31 use crate::pages::repo_settings::settings_frame;30 use crate::pages::repo_settings::settings_frame;
@@ -194,7 +193,7 @@ async fn collaborators_body(
194 role_action,193 role_action,
195 remove_action,194 remove_action,
196 remove_note: Some(195 remove_note: Some(
197- passkeys::s(196+ crate::i18n::s(
198 lang,197 lang,
199 "They lose access to this repo at once.",198 "They lose access to this repo at once.",
200 "Bu repoya erişimi hemen kaybeder.",199 "Bu repoya erişimi hemen kaybeder.",
@@ -209,7 +208,7 @@ async fn collaborators_body(
209 username_label: g::t(lang, K::Username).to_owned(),208 username_label: g::t(lang, K::Username).to_owned(),
210 role_label: g::t(lang, K::Role).to_owned(),209 role_label: g::t(lang, K::Role).to_owned(),
211 save_label: g::t(lang, K::SaveRole).to_owned(),210 save_label: g::t(lang, K::SaveRole).to_owned(),
212- open_label: passkeys::s(lang, "Open profile", "Profili aç").to_owned(),211+ open_label: crate::i18n::s(lang, "Open profile", "Profili aç").to_owned(),
213 empty: Some(g::t(lang, K::NoCollaborators).to_owned()),212 empty: Some(g::t(lang, K::NoCollaborators).to_owned()),
214 };213 };
215 Ok(view! {214 Ok(view! {
crates/forge-web/src/pages/repo_ctx.rsmodified+1 -1
@@ -21,10 +21,10 @@ use topcoat::router::{Body, Layer, LayerFuture, Next, Path, StatusCode};
21 21
22 use crate::auth::current_user;22 use crate::auth::current_user;
23 use crate::i18n::{self, Lang};23 use crate::i18n::{self, Lang};
24-use crate::pages::repo::{https_clone_url, ssh_clone_url};
25 use crate::pages::repo_mirrors::redacted_url;24 use crate::pages::repo_mirrors::redacted_url;
26 use crate::state::AppState;25 use crate::state::AppState;
27 use crate::views::repo_href;26 use crate::views::repo_href;
27+use crate::views::{https_clone_url, ssh_clone_url};
28 28
29 pub struct RepoCtx {29 pub struct RepoCtx {
30 pub repo: Repo,30 pub repo: Repo,
crates/forge-web/src/pages/repo_secrets.rsmodified+1 -1
@@ -203,7 +203,7 @@ async fn secrets_body(
203 <section class="sec">203 <section class="sec">
204 <h2>(g::t(lang, K::AddOrUpdate))</h2>204 <h2>(g::t(lang, K::AddOrUpdate))</h2>
205 <div class="acts">205 <div class="acts">
206- reveal(label: crate::pages::passkeys::s(lang, "Add secret", "Gizli anahtar ekle"), id: Some("add-secret"), open: add_open,206+ reveal(label: crate::i18n::s(lang, "Add secret", "Gizli anahtar ekle"), id: Some("add-secret"), open: add_open,
207 if let Some(message) = error {207 if let Some(message) = error {
208 alert(message: message.as_str())208 alert(message: message.as_str())
209 }209 }
crates/forge-web/src/pages/repo_security.rsmodified+1 -1
@@ -139,7 +139,7 @@ async fn security_body(
139 <div class="line" data-kb-row="">139 <div class="line" data-kb-row="">
140 <span class="name" title=(row.summary.as_str())>(row.advisory.as_str())</span>140 <span class="name" title=(row.summary.as_str())>(row.advisory.as_str())</span>
141 <span class="val"><code>(row.package.as_str())</code> " " <code>(row.version.as_str())</code> " · " (row.severity.as_str()) " · " <span class=(row.state_class)>(row.state_text)</span> " · " rel_time(lang: lang, stamp: row.created_at.as_str())</span>141 <span class="val"><code>(row.package.as_str())</code> " " <code>(row.version.as_str())</code> " · " (row.severity.as_str()) " · " <span class=(row.state_class)>(row.state_text)</span> " · " rel_time(lang: lang, stamp: row.created_at.as_str())</span>
142- <a class="act" href=(row.osv_href.as_str()) rel="noopener noreferrer">(crate::pages::passkeys::s(lang, "osv.dev", "osv.dev"))</a>142+ <a class="act" href=(row.osv_href.as_str()) rel="noopener noreferrer">(crate::i18n::s(lang, "osv.dev", "osv.dev"))</a>
143 if row.open {143 if row.open {
144 post_act(label: g::t(lang, K::Dismiss), action: row.dismiss_action.as_str(), csrf: csrf.as_str(), fields: row.fields.clone())144 post_act(label: g::t(lang, K::Dismiss), action: row.dismiss_action.as_str(), csrf: csrf.as_str(), fields: row.fields.clone())
145 }145 }
crates/forge-web/src/pages/repo_settings.rsmodified+2 -3
@@ -35,7 +35,6 @@ use crate::i18n::merge_queue as mq;
35 use crate::i18n::repo_admin::{self as g, K};35 use crate::i18n::repo_admin::{self as g, K};
36 use crate::i18n::{self, Lang};36 use crate::i18n::{self, Lang};
37 use crate::pages::discussion_settings::discussions_switch;37 use crate::pages::discussion_settings::discussions_switch;
38-use crate::pages::passkeys;
39 use crate::pages::refs::load_refs;38 use crate::pages::refs::load_refs;
40 use crate::pages::repo::repo_head;39 use crate::pages::repo::repo_head;
41 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};40 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
@@ -824,7 +823,7 @@ async fn branch_rule_form(
824 </form>823 </form>
825 <div class="acts rule-acts">824 <div class="acts rule-acts">
826 if rule_id.is_some() {825 if rule_id.is_some() {
827- <button type="submit" form=(form_id.as_str()) class="primary">(passkeys::s(lang, "Save changes", "Değişiklikleri kaydet"))</button>826+ <button type="submit" form=(form_id.as_str()) class="primary">(crate::i18n::s(lang, "Save changes", "Değişiklikleri kaydet"))</button>
828 } else {827 } else {
829 <button type="submit" form=(form_id.as_str()) class="primary">(g::t(lang, K::AddRule))</button>828 <button type="submit" form=(form_id.as_str()) class="primary">(g::t(lang, K::AddRule))</button>
830 }829 }
@@ -1435,7 +1434,7 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i
1435 .iter()1434 .iter()
1436 .any(|rule| rule.pattern == pattern);1435 .any(|rule| rule.pattern == pattern);
1437 let checked = if taken {1436 let checked = if taken {
1438- Err(passkeys::s(1437+ Err(crate::i18n::s(
1439 lang,1438 lang,
1440 "A rule for this pattern already exists. Pick it in the list to change it.",1439 "A rule for this pattern already exists. Pick it in the list to change it.",
1441 "Bu desen için zaten bir kural var. Değiştirmek için listeden onu seç.",1440 "Bu desen için zaten bir kural var. Değiştirmek için listeden onu seç.",
crates/forge-web/src/pages/repo_settings_live.rsmodified+2 -7
@@ -22,7 +22,7 @@ use topcoat::router::response::Response;
22 use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};22 use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};
23 23
24 use crate::auth::require_user;24 use crate::auth::require_user;
25-use crate::live::{LiveHub, Topic, stream_wakes};25+use crate::live::{Topic, bump_settings, stream_wakes};
26 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};26 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
27 use crate::state::AppState;27 use crate::state::AppState;
28 28
@@ -47,11 +47,6 @@ pub async fn settings_head(ctx: &RepoCtx, state: &AppState) -> Result<RepoHead>
47 Ok(head)47 Ok(head)
48 }48 }
49 49
50-/// Bumps the settings topic of a repo, after a write that changes one of its settings pages.
51-pub fn bump_settings(hub: &LiveHub, repo_id: &str) {
52- hub.bump(&Topic::RepoSettings(repo_id.to_owned()));
53-}
54-
55 /// The settings stream: the settings pages, and the refs their branch picker lists. Admins only,50 /// The settings stream: the settings pages, and the refs their branch picker lists. Admins only,
56 /// as the settings page is.51 /// as the settings page is.
57 #[route(GET "/{owner}/{repo}/settings/live")]52 #[route(GET "/{owner}/{repo}/settings/live")]
@@ -135,7 +130,7 @@ async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Respons
135 state.live.bump(&crate::live::Topic::Repo(repo_id.clone()));130 state.live.bump(&crate::live::Topic::Repo(repo_id.clone()));
136 // The merge gate of a pull page reads the branch protection rules, so every pull of the131 // The merge gate of a pull page reads the branch protection rules, so every pull of the
137 // repo may show a different gate. A pull's stream sends nothing when its fingerprint holds.132 // repo may show a different gate. A pull's stream sends nothing when its fingerprint holds.
138- crate::pages::pull_live::bump_repo_pulls(state, &repo_id).await;133+ crate::live::bump_repo_pulls(state, &repo_id).await;
139 }134 }
140 result135 result
141 }136 }
crates/forge-web/src/pages/repo_side.rsmodified+1 -1
@@ -14,10 +14,10 @@ use forge_git::{browse, history};
14 use topcoat::Result;14 use topcoat::Result;
15 15
16 use crate::i18n::Lang;16 use crate::i18n::Lang;
17+use crate::i18n::s;
17 use crate::i18n::timeline as tl;18 use crate::i18n::timeline as tl;
18 use crate::pages::ci_runs::run_href;19 use crate::pages::ci_runs::run_href;
19 use crate::pages::packages::PackageLink;20 use crate::pages::packages::PackageLink;
20-use crate::pages::passkeys::s;
21 use crate::pages::releases::LatestRelease;21 use crate::pages::releases::LatestRelease;
22 use crate::pages::tree::LatestBar;22 use crate::pages::tree::LatestBar;
23 use crate::repo_stats::{LangShare, languages, license_file, license_id};23 use crate::repo_stats::{LangShare, languages, license_file, license_id};
crates/forge-web/src/pages/repo_transfer.rsmodified+1 -1
@@ -22,7 +22,7 @@ use crate::audit::{self, Actor, Target};
22 use crate::auth::require_csrf;22 use crate::auth::require_csrf;
23 use crate::i18n::Lang;23 use crate::i18n::Lang;
24 use crate::i18n::repo_admin::{self as g, K};24 use crate::i18n::repo_admin::{self as g, K};
25-use crate::pages::repo_settings_live::bump_settings;25+use crate::live::bump_settings;
26 use crate::state::AppState;26 use crate::state::AppState;
27 use crate::views::parts::{confirm_act, post_act, reveal};27 use crate::views::parts::{confirm_act, post_act, reveal};
28 use crate::views::{alert, rel_time};28 use crate::views::{alert, rel_time};
crates/forge-web/src/pages/repo_webhooks.rsmodified+4 -4
@@ -543,7 +543,7 @@ async fn hook_form(
543 }543 }
544 <input type="hidden" name="csrf" value=(csrf.as_str())>544 <input type="hidden" name="csrf" value=(csrf.as_str())>
545 <section class="sec">545 <section class="sec">
546- <h2>(crate::pages::passkeys::s(lang, "Endpoint", "Uç nokta"))</h2>546+ <h2>(crate::i18n::s(lang, "Endpoint", "Uç nokta"))</h2>
547 <div class="field">547 <div class="field">
548 <label for="hook-url">(g::t(lang, K::PayloadUrl))</label>548 <label for="hook-url">(g::t(lang, K::PayloadUrl))</label>
549 <input id="hook-url" type="url" name="url" value=(url.as_str()) autocomplete="off" spellcheck="false" required=(true)>549 <input id="hook-url" type="url" name="url" value=(url.as_str()) autocomplete="off" spellcheck="false" required=(true)>
@@ -557,7 +557,7 @@ async fn hook_form(
557 </div>557 </div>
558 </section>558 </section>
559 <section class="sec">559 <section class="sec">
560- <h2>(crate::pages::passkeys::s(lang, "Delivery", "Teslimat"))</h2>560+ <h2>(crate::i18n::s(lang, "Delivery", "Teslimat"))</h2>
561 <div class="field" role="group" aria-labelledby="hook-events-title">561 <div class="field" role="group" aria-labelledby="hook-events-title">
562 <span class="field-label" id="hook-events-title">(g::t(lang, K::Events))</span>562 <span class="field-label" id="hook-events-title">(g::t(lang, K::Events))</span>
563 <div class="checks">563 <div class="checks">
@@ -570,7 +570,7 @@ async fn hook_form(
570 </div>570 </div>
571 </div>571 </div>
572 <div class="field">572 <div class="field">
573- <span class="field-label">(crate::pages::passkeys::s(lang, "State", "Durum"))</span>573+ <span class="field-label">(crate::i18n::s(lang, "State", "Durum"))</span>
574 <div class="checks">574 <div class="checks">
575 <label class="switch">575 <label class="switch">
576 <input type="checkbox" name="active" value="on" checked=(active)>576 <input type="checkbox" name="active" value="on" checked=(active)>
@@ -701,7 +701,7 @@ async fn hook_body(
701 frame_top(head: head, title: title.clone(), heading: heading, notice: notice, archived: archived, lang: lang,701 frame_top(head: head, title: title.clone(), heading: heading, notice: notice, archived: archived, lang: lang,
702 if archived {702 if archived {
703 <section class="sec">703 <section class="sec">
704- <h2>(crate::pages::passkeys::s(lang, "Endpoint", "Uç nokta"))</h2>704+ <h2>(crate::i18n::s(lang, "Endpoint", "Uç nokta"))</h2>
705 <p class="state">(draft.url.as_str())</p>705 <p class="state">(draft.url.as_str())</p>
706 </section>706 </section>
707 } else {707 } else {
crates/forge-web/src/pages/settings_appearance.rsmodified+1 -7
@@ -23,8 +23,8 @@ use crate::auth::{require_csrf, require_user};
23 use crate::custom_colour;23 use crate::custom_colour;
24 use crate::i18n::accents::{accent_name, base_name};24 use crate::i18n::accents::{accent_name, base_name};
25 use crate::i18n::misc::{self as g, K};25 use crate::i18n::misc::{self as g, K};
26+use crate::i18n::s;
26 use crate::i18n::{self, Lang};27 use crate::i18n::{self, Lang};
27-use crate::pages::passkeys::s;
28 use crate::state::AppState;28 use crate::state::AppState;
29 use crate::views::parts::{SubPart, head};29 use crate::views::parts::{SubPart, head};
30 use crate::views::shell;30 use crate::views::shell;
@@ -169,12 +169,6 @@ struct AppearancePage {
169 sound_on: bool,169 sound_on: bool,
170 }170 }
171 171
172-/// The `data-sound` value the shell puts on `<html>`: `on` when the viewer wants the tone.
173-pub fn sound_attr(prefs: Option<&HashMap<String, String>>) -> Option<&'static str> {
174- let stored = prefs.and_then(|p| p.get(SOUND))?;
175- (stored == "on").then_some("on")
176-}
177-
178 /// The label of a language code. The two native names stay as they are in every language.172 /// The label of a language code. The two native names stay as they are in every language.
179 fn language_label(lang: Lang, code: &str) -> &'static str {173 fn language_label(lang: Lang, code: &str) -> &'static str {
180 match code {174 match code {
crates/forge-web/src/pages/settings_export.rsmodified+5 -5
@@ -27,7 +27,7 @@ use crate::auth::{require_csrf, require_user, two_factor_enabled};
27 use crate::exporter;27 use crate::exporter;
28 use crate::i18n::migrate::{self as g, K};28 use crate::i18n::migrate::{self as g, K};
29 use crate::i18n::{self, Key, Lang};29 use crate::i18n::{self, Key, Lang};
30-use crate::pages::ci_runs::{changed_event, events_response};30+use crate::live::{changed_event, events_response};
31 use crate::state::AppState;31 use crate::state::AppState;
32 use crate::views::parts::{RailItem, SubPart, confirm_act, head, rail};32 use crate::views::parts::{RailItem, SubPart, confirm_act, head, rail};
33 use crate::views::{alert, csrf_field, human_size, rel_time, shell};33 use crate::views::{alert, csrf_field, human_size, rel_time, shell};
@@ -63,7 +63,7 @@ fn signature(exports: &[DataExport]) -> String {
63 fn data_rail_items(lang: Lang, delete: bool) -> Vec<RailItem> {63 fn data_rail_items(lang: Lang, delete: bool) -> Vec<RailItem> {
64 vec![64 vec![
65 RailItem {65 RailItem {
66- name: crate::pages::passkeys::s(lang, "Export", "Dışa aktar").to_owned(),66+ name: crate::i18n::s(lang, "Export", "Dışa aktar").to_owned(),
67 val: String::new(),67 val: String::new(),
68 href: "/settings/export".to_owned(),68 href: "/settings/export".to_owned(),
69 current: !delete,69 current: !delete,
@@ -100,7 +100,7 @@ async fn export_sheet(
100 Ok(view! {100 Ok(view! {
101 <div class="sheet export-page" data-live=(live.as_deref()) data-live-state=(if building { "building" } else { "idle" })>101 <div class="sheet export-page" data-live=(live.as_deref()) data-live-state=(if building { "building" } else { "idle" })>
102 <section class="sec">102 <section class="sec">
103- <h2>(crate::pages::passkeys::s(lang, "Your archives", "Arşivleriniz"))</h2>103+ <h2>(crate::i18n::s(lang, "Your archives", "Arşivleriniz"))</h2>
104 if empty {104 if empty {
105 <p class="state">(g::t(lang, K::ExportNone))</p>105 <p class="state">(g::t(lang, K::ExportNone))</p>
106 }106 }
@@ -124,7 +124,7 @@ async fn export_sheet(
124 <a class="act" href=(format!("/settings/export/{}/download", export.id))>(g::t(lang, K::ExportDownload))</a>124 <a class="act" href=(format!("/settings/export/{}/download", export.id))>(g::t(lang, K::ExportDownload))</a>
125 }125 }
126 if export.state != ExportState::Building {126 if export.state != ExportState::Building {
127- confirm_act(lang: lang, label: crate::pages::passkeys::s(lang, "Delete", "Sil"), action: delete.as_str(), csrf: csrf)127+ confirm_act(lang: lang, label: crate::i18n::s(lang, "Delete", "Sil"), action: delete.as_str(), csrf: csrf)
128 }128 }
129 </div>129 </div>
130 if export.state == ExportState::Building {130 if export.state == ExportState::Building {
@@ -228,7 +228,7 @@ async fn data_body(
228 }228 }
229 )229 )
230 <div class="work">230 <div class="work">
231- rail(label: crate::pages::passkeys::s(lang, "Data", "Veri"), items: items)231+ rail(label: crate::i18n::s(lang, "Data", "Veri"), items: items)
232 if delete {232 if delete {
233 delete_sheet(lang: lang, csrf: csrf, two_factor_on: two_factor_on, owned_repos: owned_repos, error: delete_error)233 delete_sheet(lang: lang, csrf: csrf, two_factor_on: two_factor_on, owned_repos: owned_repos, error: delete_error)
234 } else {234 } else {
crates/forge-web/src/pages/settings_gpg.rsmodified+1 -1
@@ -13,8 +13,8 @@ use topcoat::view::{View, component, view};
13 13
14 use crate::audit::{self, Actor, Target};14 use crate::audit::{self, Actor, Target};
15 use crate::auth::{require_csrf, require_user};15 use crate::auth::{require_csrf, require_user};
16+use crate::i18n::s;
16 use crate::i18n::{self, Key, Lang, t};17 use crate::i18n::{self, Key, Lang, t};
17-use crate::pages::passkeys::s;
18 use crate::pages::settings_keys::{AddQuery, KeyKind, KeysDraft, keys_page_view};18 use crate::pages::settings_keys::{AddQuery, KeyKind, KeysDraft, keys_page_view};
19 use crate::signatures;19 use crate::signatures;
20 use crate::state::AppState;20 use crate::state::AppState;
crates/forge-web/src/pages/settings_keys.rsmodified+2 -2
@@ -14,8 +14,8 @@ use topcoat::view::{View, component, view};
14 14
15 use crate::audit::{self, Actor, Target};15 use crate::audit::{self, Actor, Target};
16 use crate::auth::{require_csrf, require_user};16 use crate::auth::{require_csrf, require_user};
17+use crate::i18n::s;
17 use crate::i18n::{self, Key, Lang, t, unsupported_key_type};18 use crate::i18n::{self, Key, Lang, t, unsupported_key_type};
18-use crate::pages::passkeys::s;
19 use crate::pages::settings_gpg::gpg_section;19 use crate::pages::settings_gpg::gpg_section;
20 use crate::pages::settings_tokens::tokens_section;20 use crate::pages::settings_tokens::tokens_section;
21 use crate::state::AppState;21 use crate::state::AppState;
@@ -251,7 +251,7 @@ pub(crate) async fn keys_page_view(
251 }251 }
252 252
253 fn pk_title(lang: Lang) -> &'static str {253 fn pk_title(lang: Lang) -> &'static str {
254- crate::pages::passkeys::s(lang, "Keys", "Anahtarlar")254+ crate::i18n::s(lang, "Keys", "Anahtarlar")
255 }255 }
256 256
257 #[component]257 #[component]
crates/forge-web/src/pages/settings_live.rsmodified+1 -7
@@ -34,15 +34,9 @@ use topcoat::router::response::Response;
34 use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route};34 use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route};
35 35
36 use crate::auth::current_user;36 use crate::auth::current_user;
37-use crate::live::{LiveHub, Topic, stream_wakes};37+use crate::live::{LiveHub, Topic, bump_account, events_response, stream_wakes};
38-use crate::pages::ci_runs::events_response;
39 use crate::state::AppState;38 use crate::state::AppState;
40 39
41-/// Wakes the settings pages of `user_id`. Called after a write that changes what they show.
42-pub fn bump_account(state: &AppState, user_id: &str) {
43- state.live.bump(&Topic::Account(user_id.to_owned()));
44-}
45-
46 /// The change stream of the viewer's settings. The viewer comes from the session only, so a user40 /// The change stream of the viewer's settings. The viewer comes from the session only, so a user
47 /// can follow only their own settings. Without a session: 401.41 /// can follow only their own settings. Without a session: 401.
48 #[route(GET "/settings/events")]42 #[route(GET "/settings/events")]
crates/forge-web/src/pages/settings_notifications.rsmodified+1 -1
@@ -16,8 +16,8 @@ use topcoat::view::{View, component, view};
16 16
17 use crate::auth::{require_csrf, require_user};17 use crate::auth::{require_csrf, require_user};
18 use crate::i18n::push as push_text;18 use crate::i18n::push as push_text;
19+use crate::i18n::s;
19 use crate::i18n::{self, Key, Lang, t};20 use crate::i18n::{self, Key, Lang, t};
20-use crate::pages::passkeys::s;
21 use crate::state::AppState;21 use crate::state::AppState;
22 use crate::views::parts::{SubPart, confirm_act, head};22 use crate::views::parts::{SubPart, confirm_act, head};
23 use crate::views::{csrf_field, rel_time, shell};23 use crate::views::{csrf_field, rel_time, shell};
crates/forge-web/src/pages/settings_security.rsmodified+3 -2
@@ -24,8 +24,9 @@ use crate::auth::{
24 };24 };
25 use crate::i18n::packages::{self as pk, K as PK};25 use crate::i18n::packages::{self as pk, K as PK};
26 use crate::i18n::releases_ci::{self as rc, K as RC};26 use crate::i18n::releases_ci::{self as rc, K as RC};
27+use crate::i18n::s;
27 use crate::i18n::{self, Key, Lang, password_too_long, password_too_short, t};28 use crate::i18n::{self, Key, Lang, password_too_long, password_too_short, t};
28-use crate::pages::passkeys::{PasskeyPanel, build_panel, passkeys_panel, s};29+use crate::pages::passkeys::{PasskeyPanel, build_panel, passkeys_panel};
29 use crate::pages::settings_export;30 use crate::pages::settings_export;
30 use crate::pages::settings_sessions::session_label;31 use crate::pages::settings_sessions::session_label;
31 use crate::state::AppState;32 use crate::state::AppState;
@@ -1007,7 +1008,7 @@ async fn account_delete(cx: &Cx, Form(form): Form<DeleteAccountForm>) -> Result<
1007 let ghost = state.store.ensure_ghost_user().await?;1008 let ghost = state.store.ensure_ghost_user().await?;
1008 match state.store.delete_user(&user_id, &ghost.id).await {1009 match state.store.delete_user(&user_id, &ghost.id).await {
1009 Ok(_) => {1010 Ok(_) => {
1010- crate::pages::settings_live::bump_account(state, &user_id);1011+ crate::live::bump_account(state, &user_id);
1011 // The account row is gone, so the entry names no actor; the username is kept.1012 // The account row is gone, so the entry names no actor; the username is kept.
1012 audit::record(1013 audit::record(
1013 &state.store,1014 &state.store,
crates/forge-web/src/pages/settings_tokens.rsmodified+1 -1
@@ -21,8 +21,8 @@ use crate::audit::{self, Actor, Target};
21 use crate::auth::{require_csrf, require_user};21 use crate::auth::{require_csrf, require_user};
22 use crate::i18n::packages::{self as pk, K as PK};22 use crate::i18n::packages::{self as pk, K as PK};
23 use crate::i18n::releases_ci::{self as rc, K as RC};23 use crate::i18n::releases_ci::{self as rc, K as RC};
24+use crate::i18n::s;
24 use crate::i18n::{self, Key, Lang, t, token_name_length};25 use crate::i18n::{self, Key, Lang, t, token_name_length};
25-use crate::pages::passkeys::s;
26 use crate::pages::settings_keys::{AddQuery, KeyKind, KeysDraft, keys_page_view};26 use crate::pages::settings_keys::{AddQuery, KeyKind, KeysDraft, keys_page_view};
27 use crate::state::AppState;27 use crate::state::AppState;
28 use crate::views::parts::confirm_act;28 use crate::views::parts::confirm_act;
crates/forge-web/src/pages/shell_events.rsmodified+1 -1
@@ -18,8 +18,8 @@ use topcoat::router::response::Response;
18 use topcoat::router::route;18 use topcoat::router::route;
19 19
20 use crate::auth::current_user;20 use crate::auth::current_user;
21+use crate::live::events_response;
21 use crate::pages::activity::activity_changes;22 use crate::pages::activity::activity_changes;
22-use crate::pages::ci_runs::events_response;
23 use crate::pages::notifications::unread_changes;23 use crate::pages::notifications::unread_changes;
24 use crate::pages::settings_live::alive_stream;24 use crate::pages::settings_live::alive_stream;
25 use crate::state::AppState;25 use crate::state::AppState;
crates/forge-web/src/pages/tree.rsmodified+1 -1
@@ -17,10 +17,10 @@ use topcoat::view::{Unescaped, View, component, view};
17 17
18 use crate::i18n::code::{self as g, K};18 use crate::i18n::code::{self as g, K};
19 use crate::i18n::misc::{self as mi, K as MK};19 use crate::i18n::misc::{self as mi, K as MK};
20+use crate::i18n::s;
20 use crate::i18n::{self, Lang};21 use crate::i18n::{self, Lang};
21 use crate::pages::code_live::{follows_branch, live_url};22 use crate::pages::code_live::{follows_branch, live_url};
22 use crate::pages::finder::file_finder;23 use crate::pages::finder::file_finder;
23-use crate::pages::passkeys::s;
24 use crate::pages::refs::{load_refs, ref_links};24 use crate::pages::refs::{load_refs, ref_links};
25 use crate::pages::repo::repo_head;25 use crate::pages::repo::repo_head;
26 use crate::pages::repo_ctx::load_repo;26 use crate::pages::repo_ctx::load_repo;
crates/forge-web/src/pages/user_prefs.rsmodified+1 -3
@@ -13,9 +13,7 @@ use topcoat::router::{Body, route};
13 13
14 use crate::auth::require_csrf;14 use crate::auth::require_csrf;
15 use crate::state::AppState;15 use crate::state::AppState;
16-16+use crate::views::diff::DIFF_VIEW;
17-/// Key of the diff view: `split` or `unified`.
18-pub const DIFF_VIEW: &str = "diff_view";
19 17
20 #[derive(Deserialize)]18 #[derive(Deserialize)]
21 struct PrefForm {19 struct PrefForm {
crates/forge-web/src/pages/wiki.rsmodified+2 -1
@@ -24,9 +24,10 @@ use crate::auth::{require_csrf, require_user};
24 use crate::i18n::community::{self as g, K};24 use crate::i18n::community::{self as g, K};
25 use crate::i18n::{self, Lang};25 use crate::i18n::{self, Lang};
26 use crate::live::Topic;26 use crate::live::Topic;
27+use crate::live::bump_wiki;
27 use crate::pages::repo::repo_head;28 use crate::pages::repo::repo_head;
28 use crate::pages::repo_ctx::{RepoCtx, load_repo};29 use crate::pages::repo_ctx::{RepoCtx, load_repo};
29-use crate::pages::wiki_live::{bump_wiki, page_live_url, wiki_live_url};30+use crate::pages::wiki_live::{page_live_url, wiki_live_url};
30 use crate::render::markdown::render_markdown;31 use crate::render::markdown::render_markdown;
31 use crate::state::AppState;32 use crate::state::AppState;
32 use crate::views::parts::{RailItem, rail};33 use crate::views::parts::{RailItem, rail};
crates/forge-web/src/pages/wiki_live.rsmodified+0 -5
@@ -39,11 +39,6 @@ pub fn page_live_url(owner: &str, repo: &str, page: &str) -> String {
39 format!("/{owner}/{repo}/wiki/{page}/events")39 format!("/{owner}/{repo}/wiki/{page}/events")
40 }40 }
41 41
42-/// A write changed the wiki of `repo_id`: a page was saved, or a push moved its main branch.
43-pub fn bump_wiki(state: &AppState, repo_id: &str) {
44- state.live.bump(&Topic::Wiki(repo_id.to_owned()));
45-}
46-
47 /// The head commit of the wiki's main branch, or empty for a wiki with no pages.42 /// The head commit of the wiki's main branch, or empty for a wiki with no pages.
48 async fn head_fingerprint(dir: PathBuf) -> Result<String> {43 async fn head_fingerprint(dir: PathBuf) -> Result<String> {
49 let head = tokio::task::spawn_blocking(move || wiki::head_commit(&dir)).await??;44 let head = tokio::task::spawn_blocking(move || wiki::head_commit(&dir)).await??;
crates/forge-web/src/post_update.rsmodified+3 -3
@@ -113,7 +113,7 @@ pub async fn after_ref_update(
113 }113 }
114 let synced = pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await;114 let synced = pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await;
115 // A push can move, merge or open any pull of the repo, so every pull page is woken.115 // A push can move, merge or open any pull of the repo, so every pull page is woken.
116- crate::pages::pull_live::bump_repo_pulls(state, &repo.id).await;116+ crate::live::bump_repo_pulls(state, &repo.id).await;
117 synced117 synced
118 }118 }
119 119
@@ -234,7 +234,7 @@ async fn apply_commit_refs(
234 if closed {234 if closed {
235 state.live.bump_issue(&repo.id, &issue.id);235 state.live.bump_issue(&repo.id, &issue.id);
236 // A pull is an issue row too, so a keyword can close one.236 // A pull is an issue row too, so a keyword can close one.
237- crate::pages::pull_live::bump_pull(state, &repo.id, &issue.id);237+ crate::live::bump_pull(state, &repo.id, &issue.id);
238 emit_item_action(state, repo, sender, false, number, "closed").await;238 emit_item_action(state, repo, sender, false, number, "closed").await;
239 notify::dispatch(239 notify::dispatch(
240 state,240 state,
@@ -257,7 +257,7 @@ async fn apply_commit_refs(
257 .add_event(&issue.id, actor, "referenced", json!({"commit": oid}))257 .add_event(&issue.id, actor, "referenced", json!({"commit": oid}))
258 .await?;258 .await?;
259 state.live.bump_issue(&repo.id, &issue.id);259 state.live.bump_issue(&repo.id, &issue.id);
260- crate::pages::pull_live::bump_pull(state, &repo.id, &issue.id);260+ crate::live::bump_pull(state, &repo.id, &issue.id);
261 }261 }
262 }262 }
263 Ok(())263 Ok(())
crates/forge-web/src/pulls_sync.rsmodified+3 -3
@@ -58,14 +58,14 @@ pub async fn sync_pulls_for_ref(
58 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: head update failed");58 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: head update failed");
59 }59 }
60 // Open pull request pages show the new head, commits and mergeability.60 // Open pull request pages show the new head, commits and mergeability.
61- crate::pages::pull_live::bump_pull(state, &repo.id, &issue_id);61+ crate::live::bump_pull(state, &repo.id, &issue_id);
62 }62 }
63 let bases = state.store.open_pulls_for_base(&repo.id, branch).await?;63 let bases = state.store.open_pulls_for_base(&repo.id, branch).await?;
64 for (number, issue_id) in bases {64 for (number, issue_id) in bases {
65 if let Err(e) = sync_base(state, repo, actor_id, number, &issue_id, old, new).await {65 if let Err(e) = sync_base(state, repo, actor_id, number, &issue_id, old, new).await {
66 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: base update failed");66 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: base update failed");
67 }67 }
68- crate::pages::pull_live::bump_pull(state, &repo.id, &issue_id);68+ crate::live::bump_pull(state, &repo.id, &issue_id);
69 }69 }
70 Ok(())70 Ok(())
71 }71 }
@@ -348,7 +348,7 @@ pub async fn refresh_mergeability(
348 &files,348 &files,
349 )349 )
350 .await?;350 .await?;
351- crate::pages::pull_live::bump_pull(state, &base_repo.id, &pr.issue.id);351+ crate::live::bump_pull(state, &base_repo.id, &pr.issue.id);
352 Ok(())352 Ok(())
353 }353 }
354 354
crates/forge-web/src/ssh_backend.rsmodified+1 -1
@@ -85,7 +85,7 @@ impl GitBackend for SshBackend {
85 if let Err(e) = self.state.store.touch_ssh_key(&key.id).await {85 if let Err(e) = self.state.store.touch_ssh_key(&key.id).await {
86 tracing::warn!(error = %e, "could not record ssh key use");86 tracing::warn!(error = %e, "could not record ssh key use");
87 }87 }
88- crate::pages::settings_live::bump_account(&self.state, &key.user_id);88+ crate::live::bump_account(&self.state, &key.user_id);
89 // A key that belongs to an organization is refused here, not only in `authorize`.89 // A key that belongs to an organization is refused here, not only in `authorize`.
90 match self.state.store.user_by_id(&key.user_id).await {90 match self.state.store.user_by_id(&key.user_id).await {
91 Ok(Some(owner)) if !owner.is_org() => Some(key.user_id),91 Ok(Some(owner)) if !owner.is_org() => Some(key.user_id),
crates/forge-web/src/views/commit_status.rsmodified+1 -1
@@ -154,7 +154,7 @@ pub async fn checks_summary(
154 /// A status description in the viewer's language. CI's own descriptions are stored in English;154 /// A status description in the viewer's language. CI's own descriptions are stored in English;
155 /// what an outside tool reports stays as it sent it.155 /// what an outside tool reports stays as it sent it.
156 fn description_text(lang: Lang, text: &str) -> &str {156 fn description_text(lang: Lang, text: &str) -> &str {
157- use crate::pages::passkeys::s;157+ use crate::i18n::s;
158 match text {158 match text {
159 "Waiting for approval" => s(lang, "Waiting for approval", "Onay bekliyor"),159 "Waiting for approval" => s(lang, "Waiting for approval", "Onay bekliyor"),
160 "Waiting for other jobs" => s(lang, "Waiting for other jobs", "Diğer işleri bekliyor"),160 "Waiting for other jobs" => s(lang, "Waiting for other jobs", "Diğer işleri bekliyor"),
crates/forge-web/src/views/diff.rsmodified+4 -2
@@ -23,10 +23,12 @@ use crate::i18n::Lang;
23 use crate::i18n::browse as b;23 use crate::i18n::browse as b;
24 use crate::i18n::code::{self as g, K};24 use crate::i18n::code::{self as g, K};
25 use crate::i18n::pulls_review::{self as pr_g, K as PrK};25 use crate::i18n::pulls_review::{self as pr_g, K as PrK};
26-use crate::pages::commits::url_path;
27-use crate::pages::user_prefs::DIFF_VIEW;
28 use crate::state::AppState;26 use crate::state::AppState;
29 use crate::views::review_thread::{ThreadCtx, review_thread_in};27 use crate::views::review_thread::{ThreadCtx, review_thread_in};
28+use crate::views::url_path;
29+
30+/// Key of the diff view: `split` or `unified`.
31+pub const DIFF_VIEW: &str = "diff_view";
30 32
31 /// Per-diff limits used by the commit and pull-request pages.33 /// Per-diff limits used by the commit and pull-request pages.
32 pub const LIMITS: DiffLimits = DiffLimits {34 pub const LIMITS: DiffLimits = DiffLimits {
crates/forge-web/src/views/find.rsmodified+1 -1
@@ -9,7 +9,7 @@ use topcoat::context::Cx;
9 use topcoat::view::{View, component, view};9 use topcoat::view::{View, component, view};
10 10
11 use crate::i18n::Lang;11 use crate::i18n::Lang;
12-use crate::pages::passkeys::s;12+use crate::i18n::s;
13 13
14 /// The longest search kept, in characters.14 /// The longest search kept, in characters.
15 pub const MAX_QUERY_CHARS: usize = 100;15 pub const MAX_QUERY_CHARS: usize = 100;
crates/forge-web/src/views/mod.rsmodified+247 -13
@@ -11,11 +11,15 @@ pub mod repo_list;
11 pub mod review_thread;11 pub mod review_thread;
12 pub mod timeline;12 pub mod timeline;
13 13
14+use std::collections::HashMap;
14 use std::sync::OnceLock;15 use std::sync::OnceLock;
15 16
16 use forge_core::ci::RunState;17 use forge_core::ci::RunState;
18+use forge_core::config::BannerConfig;
17 use forge_core::store::shell_activity::{ActorRun, ActorRuns, InboxKinds};19 use forge_core::store::shell_activity::{ActorRun, ActorRuns, InboxKinds};
18-use forge_core::{Error as CoreError, Session, User};20+use forge_core::store::user_prefs::SOUND;
21+use forge_core::token::hash_token;
22+use forge_core::{Config, Error as CoreError, Session, User};
19 use hex::encode;23 use hex::encode;
20 use http::header::{24 use http::header::{
21 CONTENT_SECURITY_POLICY, REFERRER_POLICY, X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS,25 CONTENT_SECURITY_POLICY, REFERRER_POLICY, X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS,
@@ -24,6 +28,7 @@ use http::{HeaderValue, Uri};
24 use sha2::{Digest, Sha256};28 use sha2::{Digest, Sha256};
25 use topcoat::Result;29 use topcoat::Result;
26 use topcoat::context::{Cx, try_context};30 use topcoat::context::{Cx, try_context};
31+use topcoat::cookie::{Cookies, cookies};
27 use topcoat::router::request::uri;32 use topcoat::router::request::uri;
28 use topcoat::router::response::{Response, response_headers};33 use topcoat::router::response::{Response, response_headers};
29 use topcoat::router::{Body, Next, layer};34 use topcoat::router::{Body, Next, layer};
@@ -39,9 +44,9 @@ use crate::i18n::migrate::{self as mg, K as MGK};
39 use crate::i18n::misc::{self as mi, K as MK};44 use crate::i18n::misc::{self as mi, K as MK};
40 use crate::i18n::orgs::{self as o, K as OK};45 use crate::i18n::orgs::{self as o, K as OK};
41 use crate::i18n::packages::{self as pk, K as PK};46 use crate::i18n::packages::{self as pk, K as PK};
47+use crate::i18n::s;
42 use crate::i18n::{self, Key, Lang, t};48 use crate::i18n::{self, Key, Lang, t};
43-use crate::pages::assets::highlight_css_text;49+use crate::render::highlight::highlight_css;
44-use crate::pages::passkeys::s;
45 use crate::state::AppState;50 use crate::state::AppState;
46 51
47 /// Stylesheet URL. The version is a hash of the compiled CSS (build.rs), so a changed stylesheet52 /// Stylesheet URL. The version is a hash of the compiled CSS (build.rs), so a changed stylesheet
@@ -168,9 +173,7 @@ fn step_label(lang: Lang, word: &str) -> String {
168 fn repo_section_label(lang: Lang, kind: &str) -> Option<String> {173 fn repo_section_label(lang: Lang, kind: &str) -> Option<String> {
169 match kind {174 match kind {
170 "issues" | "pulls" | "ci" | "commits" | "branches" | "tags" | "releases"175 "issues" | "pulls" | "ci" | "commits" | "branches" | "tags" | "releases"
171- | "discussions" | "wiki" | "security" | "settings" => {176+ | "discussions" | "wiki" | "security" | "settings" => Some(tab_title(lang, kind, "")),
172- Some(crate::pages::repo::tab_title(lang, kind, ""))
173- }
174 "milestones" => Some(s(lang, "Milestones", "Kilometre taşları").to_owned()),177 "milestones" => Some(s(lang, "Milestones", "Kilometre taşları").to_owned()),
175 "labels" => Some(s(lang, "Labels", "Etiketler").to_owned()),178 "labels" => Some(s(lang, "Labels", "Etiketler").to_owned()),
176 _ => None,179 _ => None,
@@ -576,8 +579,8 @@ pub async fn shell(
576 (Some((user, _)), Some(state)) => Some(state.store.user_prefs(&user.id).await?),579 (Some((user, _)), Some(state)) => Some(state.store.user_prefs(&user.id).await?),
577 _ => None,580 _ => None,
578 };581 };
579- let banner = crate::pages::banner::current(cx, prefs.as_ref());582+ let banner = current_banner(cx, prefs.as_ref());
580- let sound_attr = crate::pages::settings_appearance::sound_attr(prefs.as_ref());583+ let sound_attr = sound_attr(prefs.as_ref());
581 let banner_back = back.clone().unwrap_or_else(|| "/".to_owned());584 let banner_back = back.clone().unwrap_or_else(|| "/".to_owned());
582 let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss);585 let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss);
583 // The admin area and the user settings swap the global links for their own list. Signed-in only.586 // The admin area and the user settings swap the global links for their own list. Signed-in only.
@@ -769,9 +772,9 @@ pub async fn shell(
769 data-orgs=(o::t(lang, OK::Organizations)) data-pages=(br::t(lang, br::K::PalettePages))772 data-orgs=(o::t(lang, OK::Organizations)) data-pages=(br::t(lang, br::K::PalettePages))
770 data-empty=(br::t(lang, br::K::PaletteNoMatches)) data-loading=(br::t(lang, br::K::PaletteLoading))773 data-empty=(br::t(lang, br::K::PaletteNoMatches)) data-loading=(br::t(lang, br::K::PaletteLoading))
771 data-failed=(br::t(lang, br::K::PaletteFailed))774 data-failed=(br::t(lang, br::K::PaletteFailed))
772- data-key-move=(crate::pages::passkeys::s(lang, "move", "gezin"))775+ data-key-move=(crate::i18n::s(lang, "move", "gezin"))
773- data-key-open=(crate::pages::passkeys::s(lang, "open", "aç"))776+ data-key-open=(crate::i18n::s(lang, "open", "aç"))
774- data-key-close=(crate::pages::passkeys::s(lang, "close", "kapat"))777+ data-key-close=(crate::i18n::s(lang, "close", "kapat"))
775 data-search-label=(search_for_label) data-files=(br::t(lang, br::K::PaletteFiles))778 data-search-label=(search_for_label) data-files=(br::t(lang, br::K::PaletteFiles))
776 data-actions=(br::t(lang, br::K::PaletteActions)) data-done=(br::t(lang, br::K::PaletteDone))779 data-actions=(br::t(lang, br::K::PaletteActions)) data-done=(br::t(lang, br::K::PaletteDone))
777 data-action-failed=(br::t(lang, br::K::PaletteActionFailed))>780 data-action-failed=(br::t(lang, br::K::PaletteActionFailed))>
@@ -999,7 +1002,7 @@ pub fn global_items(lang: Lang, can_create_org: bool) -> Vec<NavItem> {
999 }1002 }
1000 1003
1001 pub fn settings_items(lang: Lang) -> Vec<NavItem> {1004 pub fn settings_items(lang: Lang) -> Vec<NavItem> {
1002- let pk = crate::pages::passkeys::s;1005+ let pk = crate::i18n::s;
1003 let item = |key, href: &'static str, label| NavItem {1006 let item = |key, href: &'static str, label| NavItem {
1004 key,1007 key,
1005 href: href.to_owned(),1008 href: href.to_owned(),
@@ -1115,7 +1118,7 @@ pub fn display_name(lang: Lang, username: &str) -> String {
1115 pub fn avatar_url(username: &str, hash: Option<&str>) -> String {1118 pub fn avatar_url(username: &str, hash: Option<&str>) -> String {
1116 match hash {1119 match hash {
1117 Some(hash) => format!("/avatars/{}?v={hash}", enc(username)),1120 Some(hash) => format!("/avatars/{}?v={hash}", enc(username)),
1118- None => crate::pages::avatars::default_data_url(username),1121+ None => default_data_url(username),
1119 }1122 }
1120 }1123 }
1121 1124
@@ -1642,6 +1645,237 @@ pub async fn ref_selector(
1642 })1645 })
1643 }1646 }
1644 1647
1648+/// A stored timestamp shown as an absolute `title` and a relative label.
1649+#[derive(Clone)]
1650+pub struct When {
1651+ pub(crate) iso: String,
1652+ pub(crate) absolute: String,
1653+ pub(crate) relative: String,
1654+}
1655+
1656+impl When {
1657+ pub(crate) fn new(lang: Lang, stamp: &str, tz: &str, now: i64) -> Self {
1658+ let unix = stamp_unix(stamp);
1659+ Self {
1660+ iso: iso_time(unix),
1661+ absolute: forge_core::tz::format_in_tz(unix, tz),
1662+ relative: relative_time(lang, unix, now),
1663+ }
1664+ }
1665+}
1666+
1667+/// Unix seconds of a stored RFC 3339 UTC stamp (`YYYY-MM-DDTHH:MM:SS[.frac]Z`). Malformed input is 0.
1668+pub fn stamp_unix(stamp: &str) -> i64 {
1669+ let field = |range: std::ops::Range<usize>| {
1670+ stamp
1671+ .get(range)
1672+ .and_then(|digits| digits.parse::<i64>().ok())
1673+ };
1674+ let (Some(y), Some(mo), Some(d), Some(h), Some(mi), Some(s)) = (
1675+ field(0..4),
1676+ field(5..7),
1677+ field(8..10),
1678+ field(11..13),
1679+ field(14..16),
1680+ field(17..19),
1681+ ) else {
1682+ return 0;
1683+ };
1684+ days_from_civil(y, mo, d) * 86_400 + h * 3_600 + mi * 60 + s
1685+}
1686+
1687+/// Days since 1970-01-01 for a civil date (Howard Hinnant's days-from-civil).
1688+fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
1689+ let y = if month <= 2 { year - 1 } else { year };
1690+ let era = y.div_euclid(400);
1691+ let yoe = y - era * 400;
1692+ let mp = (month + 9) % 12;
1693+ let doy = (153 * mp + 2) / 5 + day - 1;
1694+ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
1695+ era * 146_097 + doe - 719_468
1696+}
1697+
1698+/// Percent-encodes each byte outside the unreserved set, keeping `/` as the separator.
1699+pub fn url_path(path: &str) -> String {
1700+ let mut out = String::with_capacity(path.len());
1701+ for b in path.bytes() {
1702+ match b {
1703+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
1704+ out.push(char::from(b));
1705+ }
1706+ _ => out.push_str(&format!("%{b:02X}")),
1707+ }
1708+ }
1709+ out
1710+}
1711+
1712+/// Highlight classes, built once on first use.
1713+static HIGHLIGHT_CSS: OnceLock<String> = OnceLock::new();
1714+
1715+/// The highlight classes, shared by the route and the page links (which hash them).
1716+pub fn highlight_css_text() -> &'static str {
1717+ HIGHLIGHT_CSS.get_or_init(highlight_css).as_str()
1718+}
1719+
1720+/// Background colors for the generated default avatar, picked by the user id hash. Muted sage,
1721+/// olive and teal tones, so the default avatars sit with the sage accent. Each keeps white text
1722+/// readable (4.5:1 or better).
1723+pub const PALETTE: [&str; 8] = [
1724+ "#5E7D63", "#4A6750", "#3F5F46", "#4E6E68", "#3E6B63", "#5B6B4E", "#56705F", "#4F6A55",
1725+];
1726+
1727+/// The generated default avatar: the first letter of the username on a palette color picked by
1728+/// the username, so a page can draw it inline without asking the server.
1729+pub fn default_svg(username: &str) -> String {
1730+ let digest = Sha256::digest(username.as_bytes());
1731+ let color = PALETTE[usize::from(digest[0]) % PALETTE.len()];
1732+ let letter = username
1733+ .chars()
1734+ .next()
1735+ .map_or_else(|| "?".to_owned(), |c| c.to_uppercase().collect());
1736+ let letter = xml_escape(&letter);
1737+ format!(
1738+ r##"<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256"><rect width="256" height="256" fill="{color}"/><text x="128" y="128" dy="0.35em" text-anchor="middle" font-family="sans-serif" font-size="128" fill="#ffffff">{letter}</text></svg>"##
1739+ )
1740+}
1741+
1742+/// The generated default avatar as a `data:` URL, for an `<img>` of an account known to have no
1743+/// photo: the page shows it at once, with no request.
1744+pub fn default_data_url(username: &str) -> String {
1745+ let svg = default_svg(username);
1746+ let mut out = String::with_capacity(svg.len() + 40);
1747+ out.push_str("data:image/svg+xml,");
1748+ for byte in svg.bytes() {
1749+ if byte.is_ascii_alphanumeric() || b" -_.~/=:;,'()".contains(&byte) {
1750+ out.push(char::from(byte));
1751+ } else {
1752+ out.push_str(&format!("%{byte:02X}"));
1753+ }
1754+ }
1755+ out
1756+}
1757+
1758+fn xml_escape(text: &str) -> String {
1759+ let mut out = String::with_capacity(text.len());
1760+ for c in text.chars() {
1761+ match c {
1762+ '&' => out.push_str("&amp;"),
1763+ '<' => out.push_str("&lt;"),
1764+ '>' => out.push_str("&gt;"),
1765+ '"' => out.push_str("&quot;"),
1766+ '\'' => out.push_str("&apos;"),
1767+ other => out.push(other),
1768+ }
1769+ }
1770+ out
1771+}
1772+
1773+/// Name of the dismissal cookie.
1774+pub const BANNER_COOKIE: &str = "forge_banner";
1775+
1776+/// Account preference key holding the dismissed hash of a signed-in user.
1777+pub const BANNER_PREF: &str = "banner_dismissed";
1778+
1779+/// What the shell draws.
1780+#[derive(Debug, Clone, PartialEq, Eq)]
1781+pub struct BannerView {
1782+ pub message: String,
1783+ pub warning: bool,
1784+ pub hash: String,
1785+ /// Unix seconds when the banner expires, or `None` for never. The page drops it at that time.
1786+ pub expires: Option<i64>,
1787+}
1788+
1789+/// Short stable id of a message and level.
1790+pub fn banner_hash(message: &str, level: &str) -> String {
1791+ hash_token(&format!("{level}\n{message}"))[..16].to_owned()
1792+}
1793+
1794+/// The banner to show at `now`, or `None` when it is off, expired or dismissed (`dismissed` is the
1795+/// stored hash).
1796+pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Option<BannerView> {
1797+ if !config.active_at(now) {
1798+ return None;
1799+ }
1800+ let message = config.message.trim().to_owned();
1801+ let hash = banner_hash(&message, &config.level);
1802+ if dismissed == Some(hash.as_str()) {
1803+ return None;
1804+ }
1805+ Some(BannerView {
1806+ message,
1807+ warning: config.level == "warning",
1808+ hash,
1809+ expires: config.expires_unix(),
1810+ })
1811+}
1812+
1813+/// The banner for this request, read from the live settings. `prefs` is a signed-in viewer's
1814+/// account preferences; without them the dismissal comes from the cookie.
1815+pub fn current_banner(cx: &Cx, prefs: Option<&HashMap<String, String>>) -> Option<BannerView> {
1816+ let state = try_context::<AppState>(cx)?;
1817+ let live = state.live();
1818+ if live.banner.message.trim().is_empty() {
1819+ return None;
1820+ }
1821+ let dismissed = match prefs {
1822+ Some(prefs) => prefs.get(BANNER_PREF).cloned(),
1823+ None => cookies(cx).get(BANNER_COOKIE).map(|c| c.value().to_owned()),
1824+ };
1825+ view_for(&live.banner, now_unix(), dismissed.as_deref())
1826+}
1827+
1828+/// The title a repo page shows when it gives none: the tab it is on.
1829+pub fn tab_title(lang: Lang, active: &str, repo: &str) -> String {
1830+ match active {
1831+ "issues" => g::t(lang, K::TabIssues).to_owned(),
1832+ "pulls" => g::t(lang, K::TabPulls).to_owned(),
1833+ "ci" => g::t(lang, K::TabCi).to_owned(),
1834+ "commits" => g::t(lang, K::TabCommits).to_owned(),
1835+ "branches" => g::t(lang, K::BranchesTitle).to_owned(),
1836+ "tags" => g::t(lang, K::TagsTitle).to_owned(),
1837+ "releases" => g::t(lang, K::TabReleases).to_owned(),
1838+ "discussions" => g::t(lang, K::TabDiscussions).to_owned(),
1839+ "wiki" => g::t(lang, K::TabWiki).to_owned(),
1840+ "security" => i18n::t(lang, i18n::Key::Security).to_owned(),
1841+ "settings" => g::t(lang, K::TabSettings).to_owned(),
1842+ _ => repo.to_owned(),
1843+ }
1844+}
1845+
1846+/// The `data-sound` value the shell puts on `<html>`: `on` when the viewer wants the tone.
1847+pub fn sound_attr(prefs: Option<&HashMap<String, String>>) -> Option<&'static str> {
1848+ let stored = prefs.and_then(|p| p.get(SOUND))?;
1849+ (stored == "on").then_some("on")
1850+}
1851+
1852+/// A byte count in GiB with one decimal, such as `3.7 GiB`.
1853+pub fn bytes_text(bytes: u64) -> String {
1854+ let gib = bytes as f64 / (1u64 << 30) as f64;
1855+ format!("{gib:.1} GiB")
1856+}
1857+
1858+/// HTTPS clone URL: `{base_url}/{owner}/{repo}.git`.
1859+pub fn https_clone_url(config: &Config, owner: &str, name: &str) -> String {
1860+ format!(
1861+ "{}/{owner}/{name}.git",
1862+ config.base_url.trim_end_matches('/')
1863+ )
1864+}
1865+
1866+/// SSH clone URL. Port 22 uses the scp-like form `git@host:owner/repo.git`.
1867+pub fn ssh_clone_url(config: &Config, owner: &str, name: &str) -> String {
1868+ let host = &config.ssh_public_host;
1869+ if config.ssh_public_port == 22 {
1870+ format!("git@{host}:{owner}/{name}.git")
1871+ } else {
1872+ format!(
1873+ "ssh://git@{host}:{}/{owner}/{name}.git",
1874+ config.ssh_public_port
1875+ )
1876+ }
1877+}
1878+
1645 #[cfg(test)]1879 #[cfg(test)]
1646 mod tests {1880 mod tests {
1647 use super::*;1881 use super::*;
crates/forge-web/src/views/parts.rsmodified+1 -1
@@ -6,7 +6,7 @@ use topcoat::context::Cx;
6 use topcoat::view::{Child, View, ViewExt, component, view};6 use topcoat::view::{Child, View, ViewExt, component, view};
7 7
8 use crate::i18n::Lang;8 use crate::i18n::Lang;
9-use crate::pages::passkeys::s;9+use crate::i18n::s;
10 10
11 /// The width class of a strip segment holding `part` of `total`: `fr1` to `fr40`, since a page may11 /// The width class of a strip segment holding `part` of `total`: `fr1` to `fr40`, since a page may
12 /// not set inline styles. A segment with nothing in it still shows.12 /// not set inline styles. A segment with nothing in it still shows.
crates/forge-web/src/views/repo_list.rsmodified+1 -2
@@ -9,8 +9,7 @@ use topcoat::view::{View, component, view};
9 9
10 use crate::i18n::orgs::{self as g, K};10 use crate::i18n::orgs::{self as g, K};
11 use crate::i18n::{self, Lang};11 use crate::i18n::{self, Lang};
12-use crate::pages::issue_parts::When;12+use crate::views::{When, repo_href};
13-use crate::views::repo_href;
14 13
15 /// The fact a row leads with when the repo is private ("Private · "); public says nothing, it is14 /// The fact a row leads with when the repo is private ("Private · "); public says nothing, it is
16 /// the usual case.15 /// the usual case.
crates/forge-web/src/views/review_thread.rsmodified+1 -2
@@ -14,10 +14,9 @@ use topcoat::view::{Unescaped, View, component, view};
14 14
15 use crate::i18n::Lang;15 use crate::i18n::Lang;
16 use crate::i18n::pulls_review::{self as g, K};16 use crate::i18n::pulls_review::{self as g, K};
17-use crate::pages::issue_parts::When;
18 use crate::render::markdown::{LinkContext, render_markdown};17 use crate::render::markdown::{LinkContext, render_markdown};
19 use crate::views::parts::{confirm_act, post_act, reveal};18 use crate::views::parts::{confirm_act, post_act, reveal};
20-use crate::views::{avatar_url_unknown, display_name, now_unix, user_href, user_link};19+use crate::views::{When, avatar_url_unknown, display_name, now_unix, user_href, user_link};
21 20
22 /// What the Apply control of a suggestion shows. A root without a state shows the diff only.21 /// What the Apply control of a suggestion shows. A root without a state shows the diff only.
23 #[derive(Clone, Copy, Debug, PartialEq, Eq)]22 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
crates/forge-web/src/webhooks/emit.rsmodified+1 -1
@@ -446,7 +446,7 @@ async fn enqueue(
446 Ok(_) => {446 Ok(_) => {
447 queued += 1;447 queued += 1;
448 state.webhook_waker.notify_one();448 state.webhook_waker.notify_one();
449- crate::pages::repo_settings_live::bump_settings(&state.live, &hook.repo_id);449+ crate::live::bump_settings(&state.live, &hook.repo_id);
450 }450 }
451 Err(e) => {451 Err(e) => {
452 tracing::error!(error = %e, hook_id = %hook.id, event = event.as_str(), "webhooks: enqueue failed");452 tracing::error!(error = %e, hook_id = %hook.id, event = event.as_str(), "webhooks: enqueue failed");
crates/forge-web/src/webhooks/worker.rsmodified+1 -1
@@ -20,7 +20,7 @@ use time::format_description::well_known::Rfc3339;
20 use tokio::sync::Notify;20 use tokio::sync::Notify;
21 21
22 use super::client::{HookClient, SendOutcome, WebhookPolicy, sign, validate_url};22 use super::client::{HookClient, SendOutcome, WebhookPolicy, sign, validate_url};
23-use crate::pages::repo_settings_live::bump_settings;23+use crate::live::bump_settings;
24 use crate::state::AppState;24 use crate::state::AppState;
25 25
26 /// Handle that wakes the worker. `emit` calls `notify_one` after queueing deliveries.26 /// Handle that wakes the worker. `emit` calls `notify_one` after queueing deliveries.