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] = &[
495495 ];
496496
497497 /// 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+
498506 pub fn t(lang: Lang, key: Key) -> &'static str {
499507 use Key::*;
500508 use Lang::*;
crates/forge-web/src/advisories/scan.rsmodified+1 -1
@@ -10,7 +10,7 @@ use forge_core::store::advisories::ScanOutcome;
1010 use forge_core::{Error, Repo, Result};
1111 use forge_git::browse::{EntryKind, default_branch_commit, read_text_blob, read_tree};
1212
13-use crate::pages::repo_settings_live::bump_settings;
13+use crate::live::bump_settings;
1414 use crate::state::AppState;
1515
1616 /// 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(
114114 if let Err(e) = state.store.touch_token(&token_id).await {
115115 return Err(internal(e));
116116 }
117- crate::pages::settings_live::bump_account(state, &user.id);
117+ crate::live::bump_account(state, &user.id);
118118 Ok(Some(user))
119119 }
120120
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>
5959 if let Err(e) = state.store.touch_token(&token_id).await {
6060 return Err(Box::new(failure(PackageError::Internal(e.to_string()))));
6161 }
62- crate::pages::settings_live::bump_account(state, &user.id);
62+ crate::live::bump_account(state, &user.id);
6363 Ok(Some(user))
6464 }
6565
crates/forge-web/src/auth.rsmodified+1 -1
@@ -111,7 +111,7 @@ pub async fn logout(cx: &Cx, session: &Session) -> forge_core::Result<()> {
111111 let state = context::<AppState>(cx);
112112 state.store.delete_session(&session.id).await?;
113113 // 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);
115115 session_jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/"));
116116 Ok(())
117117 }
crates/forge-web/src/automerge.rsmodified+2 -2
@@ -15,7 +15,7 @@ use crate::state::AppState;
1515 /// `sha`. Called after a commit status for `sha` was written. Failures are logged: the status
1616 /// that triggered this has already been stored.
1717 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;
1919 let pulls = match state.store.auto_merge_pulls_for_head(repo_id, sha).await {
2020 Ok(pulls) => pulls,
2121 Err(e) => {
@@ -55,7 +55,7 @@ async fn evaluate_logged(state: &AppState, repo: &Repo, pr: &PullRequest) {
5555 tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "auto-merge: evaluation failed");
5656 }
5757 // 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);
5959 }
6060
6161 /// 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};
2929
3030 use crate::api::{self, Refusal};
3131 use crate::ci::{artifact_key, log_path};
32-use crate::pages::admin_runners::bytes_text;
33-use crate::pages::repo::https_clone_url;
3432 use crate::self_update;
3533 use crate::state::AppState;
34+use crate::views::{bytes_text, https_clone_url};
3635
3736 path_param!(job_id);
3837 path_param!(artifact_name);
crates/forge-web/src/git_auth.rsmodified+1 -1
@@ -81,7 +81,7 @@ pub async fn user_from_basic(
8181 .touch_token(&access.id)
8282 .await
8383 .map_err(internal)?;
84- crate::pages::settings_live::bump_account(state, &user.id);
84+ crate::live::bump_account(state, &user.id);
8585 Ok(Some(user))
8686 }
8787
crates/forge-web/src/internal.rsmodified+1 -1
@@ -170,7 +170,7 @@ async fn hook_endpoint(
170170 // A wiki push changes neither the code repo's refs nor its CI, pull requests or events.
171171 // It still goes to the standby.
172172 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);
174174 crate::replication::enqueue_repo(state, &req.repo_id);
175175 HookResponse::allow()
176176 }
crates/forge-web/src/live.rsmodified+241 -16
@@ -26,16 +26,18 @@
2626 use std::collections::HashMap;
2727 use std::future::Future;
2828 use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
29+use std::time::Duration;
2930
3031 use futures_util::future::select_all;
31-use futures_util::{Stream, stream};
32+use futures_util::{Stream, StreamExt, stream};
3233 use tokio::sync::watch;
3334 use topcoat::Result;
3435 use topcoat::context::Cx;
35-use topcoat::router::content::sse::Event;
36-use topcoat::router::response::Response;
36+use topcoat::router::HeaderValue;
37+use topcoat::router::content::sse::{Event, KeepAlive, Sse};
38+use topcoat::router::response::{IntoResponse, Response};
3739
38-use crate::pages::ci_runs::events_response;
40+use crate::state::AppState;
3941
4042 /// What a live page follows. Add a variant when a page needs a new signal.
4143 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
@@ -48,10 +50,10 @@ pub enum Topic {
4850 /// One issue: its body, comments, events, state, labels, reactions. Keyed by issue id.
4951 Issue(String),
5052 /// 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.
5254 PullList(String),
5355 /// 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.
5557 Pull(String),
5658 /// A repo's own state that its header shows: stars, watchers, forks, its name, description,
5759 /// archived flag and default branch, the tab switches, and the mirror's last sync. Keyed by repo
@@ -67,7 +69,7 @@ pub enum Topic {
6769 /// A user's review requests: a pull request asked the user to review, a request was withdrawn,
6870 /// the user submitted a review, or a pull request with the user's request closed or merged.
6971 /// 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.
7173 ReviewRequests(String),
7274 /// A user's import jobs: a job was queued, started, progressed or finished. Keyed by user id.
7375 /// Bumped by the importer when a job's state changes. Streamed only to that user.
@@ -76,13 +78,13 @@ pub enum Topic {
7678 Explore,
7779 /// The discussions of a repo as a list: a discussion was opened, or any discussion of the repo
7880 /// 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.
8082 Discussions(String),
8183 /// 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.
8385 Discussion(String),
8486 /// 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.
8688 Wiki(String),
8789 /// The snippet list: a snippet was created, changed or deleted. Global; each viewer's list is
8890 /// fingerprinted, so a bump that changes nothing the viewer sees sends nothing.
@@ -90,7 +92,7 @@ pub enum Topic {
9092 /// One snippet: its files, title, visibility and revisions. Keyed by snippet id.
9193 Snippet(String),
9294 /// 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.
9496 Org(String),
9597 /// The account list of the admin area: an account was registered, edited, suspended, lifted,
9698 /// given or lost admin rights, or deleted. Global. Admin pages only, on [`admin`].
@@ -129,7 +131,7 @@ pub enum Topic {
129131 /// The server settings that pages render (every `Kind::Live` setting, such as the banner, the
130132 /// registration mode or the limits): one was saved or reset. Global. Every page holds
131133 /// `/-/alive`, anonymous viewers included, and follows it there (see
132- /// [`crate::pages::settings_live::alive_response`]). Bumped by the server settings after a save
134+ /// `settings_live::alive_response`). Bumped by the server settings after a save
133135 /// or reset.
134136 ServerSettings,
135137 }
@@ -212,7 +214,7 @@ struct Follow<F> {
212214 }
213215
214216 /// 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> {
216218 Ok(Event::new().event("changed").data("1"))
217219 }
218220
@@ -237,7 +239,7 @@ pub fn stream_wakes(cx: &Cx, hub: &LiveHub, topics: &[Topic]) -> Result<Response
237239 if !wait_any(&mut wakes).await {
238240 return None;
239241 }
240- Some((changed_event(), wakes))
242+ Some((wake_event(), wakes))
241243 });
242244 events_response(cx, events)
243245 }
@@ -317,10 +319,233 @@ where
317319 ))
318320 }
319321
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+
320547 #[cfg(test)]
321548 mod tests {
322- use std::time::Duration;
323-
324549 use super::*;
325550
326551 #[tokio::test]
crates/forge-web/src/merge_queue.rsmodified+2 -2
@@ -420,7 +420,7 @@ async fn fail(
420420 .await
421421 {
422422 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);
424424 notify::dispatch(
425425 state,
426426 repo,
@@ -441,5 +441,5 @@ async fn fail(
441441 /// Wakes the queue pages of `repo_id`, and the pull page and list of the entry's pull request.
442442 fn notify_entry(state: &AppState, repo: &Repo, entry: &QueueEntry) {
443443 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);
445445 }
crates/forge-web/src/mirrors/mod.rsmodified+1 -1
@@ -23,7 +23,7 @@ use serde_json::json;
2323
2424 use crate::audit::{self, Actor, Target};
2525 use crate::live::Topic;
26-use crate::pages::repo_settings_live::bump_settings;
26+use crate::live::bump_settings;
2727 use crate::post_update::after_ref_update;
2828 use crate::state::AppState;
2929 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() {
290290 assert!(body.contains("site-banner warning"), "{body}");
291291 assert!(body.contains("Maintenance tonight"));
292292 }
293- let hash = crate::pages::banner::banner_hash("Maintenance tonight", "warning");
293+ let hash = crate::views::banner_hash("Maintenance tonight", "warning");
294294 let req = Request::builder()
295295 .method("GET")
296296 .uri("/explore")
crates/forge-web/src/pages/activity.rsmodified+2 -1
@@ -14,7 +14,8 @@ use topcoat::router::response::Response;
1414 use topcoat::router::{Body, HeaderValue, StatusCode, route};
1515
1616 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;
1819 use crate::state::AppState;
1920 use crate::views::repo_href;
2021 use futures_util::Stream;
crates/forge-web/src/pages/admin_mail.rsmodified+3 -3
@@ -31,12 +31,12 @@ use crate::audit::{self, Actor, Target};
3131 use crate::auth::check_csrf;
3232 use crate::i18n::admin::{self as g, K};
3333 use crate::i18n::{self, Key, Lang};
34+use crate::live::{changed_event, events_response};
3435 use crate::mail::{enqueue, live, templates};
3536 use crate::pages::admin_server::{
3637 MAIL_KEYS, Row, refusal, save_topic, setting_lines, setting_rows,
3738 };
3839 use crate::pages::admin_users::admin_only;
39-use crate::pages::ci_runs::{changed_event, events_response};
4040 use crate::state::AppState;
4141 use crate::views::parts::{confirm_act, head, post_act};
4242 use crate::views::{enc, rel_time, shell};
@@ -230,7 +230,7 @@ async fn mail_view(
230230 <form method="post" action="/admin/mail" class="srv-form">
231231 <input type="hidden" name="csrf" value=(csrf.as_str())>
232232 <section class="sec">
233- <h2>(crate::pages::passkeys::s(lang, "Delivery", "Teslimat"))</h2>
233+ <h2>(crate::i18n::s(lang, "Delivery", "Teslimat"))</h2>
234234 setting_lines(lang: lang, rows: data.transport)
235235 </section>
236236 <section class="sec" id="smtp">
@@ -263,7 +263,7 @@ async fn mail_view(
263263 </div>
264264 </section>
265265 <section class="sec">
266- <h2>(crate::pages::passkeys::s(lang, "Sending", "Gönderim"))</h2>
266+ <h2>(crate::i18n::s(lang, "Sending", "Gönderim"))</h2>
267267 <div class="fields">
268268 <div class="field">
269269 <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};
2626 use crate::audit::{self, Actor, Target};
2727 use crate::auth::check_csrf;
2828 use crate::i18n::admin::{self as g, K};
29+use crate::i18n::s;
2930 use crate::i18n::{self, Key, Lang};
3031 use crate::live::{Topic, stream_changes};
3132 use crate::pages::admin_backups::backups_rail;
@@ -35,7 +36,6 @@ use crate::pages::admin_server::{
3536 };
3637 use crate::pages::admin_users::admin_only;
3738 use crate::pages::issues_list::list_href;
38-use crate::pages::passkeys::s;
3939 use crate::state::AppState;
4040 use crate::views::find::{Finder, finder_field};
4141 use crate::views::parts::{head, post_act};
@@ -277,7 +277,7 @@ async fn replication_view(
277277 </section>
278278 if data.enabled {
279279 <section class="sec">
280- <h2>(crate::pages::passkeys::s(lang, "Status", "Durum"))</h2>
280+ <h2>(crate::i18n::s(lang, "Status", "Durum"))</h2>
281281 <div class="line" data-kb-row="">
282282 <span class="name">(g::t(lang, K::Database))</span>
283283 <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;
3232 use crate::i18n::admin::{self as g, K};
3333 use crate::i18n::releases_ci as rc;
3434 use crate::i18n::{self, Key, Lang};
35+use crate::live::events_response;
3536 use crate::pages::admin_users::admin_only;
36-use crate::pages::ci_runs::{
37- age_text, duration_text, events_response, job_href, run_href, state_text,
38-};
37+use crate::pages::ci_runs::{age_text, duration_text, job_href, run_href, state_text};
3938 use crate::pages::repo_mirrors::stamp_in_tz;
4039 use crate::state::AppState;
4140 use crate::views::parts::{SubPart, confirm_act, head, post_act, reveal};
4241 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};
4443
4544 path_param!(runner_id);
4645 path_param!(token_hash);
@@ -1014,12 +1013,6 @@ fn identity_rows(lang: Lang, fields: &[FieldRow]) -> Vec<(&'static str, String)>
10141013 .collect()
10151014 }
10161015
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-
10231016 fn or_dash(text: String) -> String {
10241017 if text.is_empty() {
10251018 "-".to_owned()
@@ -1835,10 +1828,7 @@ async fn runners_events(cx: &Cx) -> Result<Response> {
18351828 let wake = state.ci_live.subscribe_runners();
18361829 let events = futures_util::stream::unfold(wake, |mut wake| async move {
18371830 wake.changed().await.ok()?;
1838- Some((
1839- crate::pages::ci_runs::changed_event("runners".to_owned()),
1840- wake,
1841- ))
1831+ Some((crate::live::changed_event("runners".to_owned()), wake))
18421832 });
18431833 events_response(cx, events)
18441834 }
crates/forge-web/src/pages/admin_server.rsmodified+2 -2
@@ -31,11 +31,11 @@ use topcoat::view::{View, component, view};
3131 use crate::audit::{self, Actor, Target};
3232 use crate::auth::check_csrf;
3333 use crate::i18n::admin::{self as g, K};
34+use crate::i18n::s;
3435 use crate::i18n::{self, Key, Lang};
3536 use crate::live::Topic;
37+use crate::live::{changed_event, events_response};
3638 use crate::pages::admin_users::admin_only;
37-use crate::pages::ci_runs::{changed_event, events_response};
38-use crate::pages::passkeys::s;
3939 use crate::self_update;
4040 use crate::state::AppState;
4141 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};
2222 use crate::i18n::accounts::{A, t as at};
2323 use crate::i18n::admin::{self as g, K};
2424 use crate::i18n::orgs::{self as og, K as OG};
25+use crate::i18n::s;
2526 use crate::i18n::{self, Key, Lang};
2627 use crate::live::{Topic, stream_changes};
2728 use crate::pages::admin_users::admin_only;
28-use crate::pages::passkeys::s;
2929 use crate::state::AppState;
3030 use crate::views::parts::{SubPart, confirm_act, head, post_act};
3131 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,
662662 {
663663 Ok(()) => {
664664 // A suspension ends the user's sessions: their open tabs must see it.
665- crate::pages::settings_live::bump_account(
666- context::<AppState>(cx),
667- &target.id,
668- );
665+ crate::live::bump_account(context::<AppState>(cx), &target.id);
669666 audit(
670667 AuditAction::UserSuspended,
671668 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};
1818 use crate::auth::{check_csrf, current_user, hash_password_async};
1919 use crate::i18n::admin::{self as g, K};
2020 use crate::i18n::orgs::{self as og, K as OG};
21+use crate::i18n::s;
2122 use crate::i18n::{self, Key, Lang};
2223 use crate::live::{Topic, stream_changes};
2324 use crate::pages::issues_list::list_href;
24-use crate::pages::passkeys::s;
2525 use crate::state::AppState;
2626 use crate::views::find::{Finder, finder_field};
2727 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>
657657 match store.delete_user(&target.id, &ghost.id).await {
658658 Ok(_) => {
659659 // 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);
661661 audit::record(
662662 store,
663663 Some(cx),
crates/forge-web/src/pages/assets.rsmodified+1 -12
@@ -2,8 +2,6 @@
22 //! highlighting classes at `/assets/highlight.css`, and the colours of the hue choices at
33 //! `/theme/custom.css`.
44
5-use std::sync::OnceLock;
6-
75 use topcoat::Result;
86 use topcoat::context::Cx;
97 use topcoat::router::request::uri;
@@ -12,7 +10,6 @@ use topcoat::router::{HeaderMap, StatusCode, header, route};
1210
1311 use crate::accent;
1412 use crate::custom_colour;
15-use crate::render::highlight::highlight_css;
1613 use crate::views::{NAV_SCRIPT_HREF, STYLESHEET_HREF, highlight_href};
1714
1815 /// 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 {
3128
3229 const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css"));
3330
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-
4231 /// Immutable when the URL carries the current content hash, so a changed file gets a new URL.
4332 #[route(GET "/assets/main.css")]
4433 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
8271 .expect("static header value"),
8372 );
8473 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()))
8675 }
8776
8877 /// 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};
1414
1515 use crate::auth::require_user;
1616 use crate::i18n::admin::{self as g, K};
17+use crate::i18n::s;
1718 use crate::i18n::{self, Lang, audit_names};
1819 use crate::live::{Topic, stream_changes};
1920 use crate::pages::admin_users::admin_only;
2021 use crate::pages::issues_list::list_href;
21-use crate::pages::passkeys::s;
2222 use crate::pages::settings_security::security_rail_for;
2323 use crate::state::AppState;
2424 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;
1313 use topcoat::router::{path_param_segment, query_params, route};
1414
1515 use crate::state::AppState;
16-
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-];
16+use crate::views::default_svg;
2317
2418 const CACHE_IMMUTABLE: &str = "public, max-age=31536000, immutable";
2519 /// Without a matching `?v=`, the browser revalidates: the ETag gives a cheap 304.
@@ -34,52 +28,6 @@ struct AvatarQuery {
3428 v: Option<String>,
3529 }
3630
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-
8331 /// True when an `If-None-Match` header lists `etag` (quoted), `*`, or its weak form.
8432 fn etag_matches(if_none_match: &str, etag: &str) -> bool {
8533 if_none_match
@@ -150,16 +98,16 @@ mod tests {
15098
15199 #[test]
152100 fn default_svg_escapes_the_letter_and_is_stable() {
153- let svg = super::default_svg("<");
101+ let svg = crate::views::default_svg("<");
154102 assert!(svg.contains(">&lt;</text>"), "{svg}");
155- assert_eq!(svg, super::default_svg("<"));
156- let url = super::default_data_url("<");
103+ assert_eq!(svg, crate::views::default_svg("<"));
104+ let url = crate::views::default_data_url("<");
157105 assert!(url.starts_with("data:image/svg+xml,%3Csvg"), "{url}");
158106 assert!(
159107 !url.contains('<') && !url.contains('#') && !url.contains('"'),
160108 "{url}"
161109 );
162- assert!(super::PALETTE.iter().any(|c| svg.contains(c)));
110+ assert!(crate::views::PALETTE.iter().any(|c| svg.contains(c)));
163111 }
164112
165113 #[test]
crates/forge-web/src/pages/banner.rsmodified+4 -60
@@ -4,14 +4,11 @@
44 //! in the `forge_banner` cookie for a signed-out visitor, and as the `banner_dismissed` account
55 //! preference for a signed-in user.
66
7-use std::collections::HashMap;
87 use std::time::Duration;
98
10-use forge_core::config::BannerConfig;
11-use forge_core::token::hash_token;
129 use serde::Deserialize;
1310 use topcoat::Result;
14-use topcoat::context::{Cx, context, try_context};
11+use topcoat::context::{Cx, context};
1512 use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
1613 use topcoat::router::content::Form;
1714 use topcoat::router::error::{SeeOther, see_other};
@@ -20,64 +17,10 @@ use topcoat::router::route;
2017 use crate::auth::current_user;
2118 use crate::pages::theme_cookie::safe_back;
2219 use crate::state::AppState;
23-
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";
20+use crate::views::{BANNER_COOKIE, BANNER_PREF};
2921
3022 const BANNER_COOKIE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60);
3123
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-
8124 #[derive(Deserialize)]
8225 struct DismissForm {
8326 #[serde(default)]
@@ -112,7 +55,8 @@ async fn dismiss(cx: &Cx, Form(form): Form<DismissForm>) -> Result<SeeOther> {
11255
11356 #[cfg(test)]
11457 mod tests {
115- use super::*;
58+ use crate::views::view_for;
59+ use forge_core::config::BannerConfig;
11660
11761 fn config(message: &str, level: &str, expires: &str) -> BannerConfig {
11862 BannerConfig {
crates/forge-web/src/pages/blame.rsmodified+2 -2
@@ -14,9 +14,9 @@ use topcoat::view::{Unescaped, View, component, view};
1414
1515 use crate::i18n::browse as b;
1616 use crate::i18n::code::{self as g, K};
17+use crate::i18n::s;
1718 use crate::i18n::{self, Lang};
1819 use crate::pages::blob::{Line, text_lines};
19-use crate::pages::passkeys::s;
2020 use crate::pages::ref_live;
2121 use crate::pages::repo::repo_head;
2222 use crate::pages::repo_ctx::load_repo;
@@ -240,7 +240,7 @@ async fn blame_page(cx: &Cx) -> Result<impl View> {
240240 <div class="sheet-tools">
241241 <strong>(file_name)</strong>
242242 <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"))>
244244 <a href=(source_href.as_str())>(crate::i18n::code::t(lang, crate::i18n::code::K::SourceToggle))</a>
245245 <a href="" aria-current="page">(b::t(lang, b::K::BlameLink))</a>
246246 </nav>
crates/forge-web/src/pages/blob.rsmodified+1 -1
@@ -12,13 +12,13 @@ use topcoat::view::{Unescaped, View, component, view};
1212 use crate::i18n::browse as b;
1313 use crate::i18n::code::{self as g, K};
1414 use crate::i18n::misc::{self as mi, K as MK};
15+use crate::i18n::s;
1516 use crate::i18n::{self};
1617 use crate::lfs::has_object;
1718 use crate::lfs_pointer;
1819 use crate::pages::code_live::{follows_branch, live_url};
1920 use crate::pages::finder::file_finder;
2021 use crate::pages::media::media_url;
21-use crate::pages::passkeys::s;
2222 use crate::pages::refs::{load_refs, ref_links};
2323 use crate::pages::repo::repo_head;
2424 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;
2121 use crate::i18n::code::{self as g, K};
2222 use crate::i18n::{self, Lang};
2323 use crate::internal::{is_zero_oid, may_push_directly};
24-use crate::pages::commits::url_path;
2524 use crate::pages::ref_live;
2625 use crate::pages::refs::ref_rows;
2726 use crate::pages::repo::repo_head;
@@ -31,6 +30,7 @@ use crate::post_update::after_ref_update;
3130 use crate::state::AppState;
3231 use crate::views::commit_line::commit_line;
3332 use crate::views::parts::{confirm_act, reveal};
33+use crate::views::url_path;
3434 use crate::views::{alert, iso_time, now_unix, relative_time, repo_href, shell};
3535
3636 path_param!(owner);
crates/forge-web/src/pages/ci_job.rsmodified+4 -3
@@ -34,9 +34,10 @@ use crate::i18n::{
3434 self, Lang,
3535 releases_ci::{self as g, K},
3636 };
37+use crate::live::{changed_event, events_response};
3738 use crate::pages::ci_runs::{
38- age_text, can_write, changed_event, commit_reachable_for, dock_bars, duration_text,
39- events_response, job_href, run_href, state_text, strip_ansi,
39+ age_text, can_write, commit_reachable_for, dock_bars, duration_text, job_href, run_href,
40+ state_text, strip_ansi,
4041 };
4142 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};
4243 use crate::state::AppState;
@@ -480,7 +481,7 @@ async fn job_body(
480481 <strong>(g::t(lang, K::Log))</strong>
481482 <div class="ci-tl-tools">
482483 <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>
484485 <label class="find-opt"><input type="checkbox" data-log-case="true"><span>"Aa"</span></label>
485486 <span class="ci-logcount" data-log-count="true" data-none=(g::t(lang, K::LogNoMatches)) aria-live="polite"></span>
486487 <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 @@
1111 use std::collections::{HashMap, HashSet};
1212 use std::future::Future;
1313 use std::path::Path;
14-use std::time::Duration;
1514
1615 use forge_core::ci::{CiJob, CiRun, JobSample, JobState, JobStep, RunState, StepSample, StepState};
1716 use forge_core::{Action, Denied, Store, User, authorize};
1817 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};
2019 use serde::Deserialize;
2120 use time::OffsetDateTime;
2221 use time::format_description::well_known::Rfc3339;
@@ -25,7 +24,7 @@ use tokio::sync::watch;
2524 use topcoat::Result;
2625 use topcoat::context::{Cx, context};
2726 use topcoat::router::content::Form;
28-use topcoat::router::content::sse::{Event, KeepAlive, Sse};
27+use topcoat::router::content::sse::Event;
2928 use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};
3029 use topcoat::router::request::uri;
3130 use topcoat::router::response::{IntoResponse, Response};
@@ -39,6 +38,7 @@ use crate::i18n::{
3938 self, Lang,
4039 releases_ci::{self as g, K},
4140 };
41+use crate::live::{Status, changed_event, changed_stream, events_response};
4242 use crate::pages::admin_runners::confirm_post;
4343 use crate::pages::ci_estimate::{self, Est, Step};
4444 use crate::pages::ci_fail::{self, FailFirst, fail_first_block};
@@ -2465,7 +2465,7 @@ async fn run_head(
24652465 if run.can_cancel && run.stopping {
24662466 <button type="button" class="ci-stopping" disabled="disabled">(g::t(lang, K::StoppingButton))</button>
24672467 } 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![])
24692469 }
24702470 if rerun_failed_shown {
24712471 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(
26432643 if let Some(log) = run.log.as_ref() {
26442644 <div class="ci-tl-tools">
26452645 <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>
26472647 <label class="find-opt"><input type="checkbox" data-log-case="true"><span>"Aa"</span></label>
26482648 <span class="ci-logcount" data-log-count="true" data-none=(g::t(lang, K::LogNoMatches)) aria-live="polite"></span>
26492649 <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(
26772677 // Only the end of a long log is sent: say where it starts and where the rest is.
26782678 if log.truncated {
26792679 <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: "))
26812681 <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>
26832683 </p>
26842684 }
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>
26862686 } else {
26872687 <p class="hint">(g::t(lang, K::NoJobs))</p>
26882688 }
@@ -2860,13 +2860,6 @@ async fn manual_run_post(cx: &Cx, Form(form): Form<ManualForm>) -> Result<SeeOth
28602860 Ok(see_other(run_href(&title, run.number)))
28612861 }
28622862
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-
28702863 pub(crate) async fn run_status(store: &Store, run_id: &str) -> Result<Status> {
28712864 Ok(store
28722865 .run_by_id(run_id)
@@ -2874,75 +2867,6 @@ pub(crate) async fn run_status(store: &Store, run_id: &str) -> Result<Status> {
28742867 .map(|run| (run.state.as_str().to_owned(), run_finished(&run.state))))
28752868 }
28762869
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-
29462870 /// One `changed` event per wake of `wake`. The repo list has no status to compare, so each wake is
29472871 /// sent. The stream ends when the signal closes.
29482872 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>>
29522876 })
29532877 }
29542878
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-
30462879 /// The live `changed` stream of a run that is not finished. It is sent on every change to the run
30472880 /// or to one of its jobs, so the page can render its rows again.
30482881 #[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};
1717 use topcoat::view::{View, view};
1818
1919 use crate::i18n::code::{self as g, K};
20+use crate::i18n::s;
2021 use crate::i18n::{self, Lang};
21-use crate::pages::passkeys::s;
2222 use crate::pages::ref_live;
2323 use crate::pages::repo::repo_head;
2424 use crate::pages::repo_ctx::load_repo;
@@ -28,7 +28,7 @@ use crate::signatures::{self, SigBadge};
2828 use crate::state::AppState;
2929 use crate::views::commit_line::commit_line;
3030 use crate::views::commit_status::{StatusLang, StatusSummary, commit_status, status_list};
31-use crate::views::shell;
31+use crate::views::{shell, url_path};
3232
3333 path_param!(owner);
3434 path_param!(repo);
@@ -88,20 +88,6 @@ pub(crate) fn iso_time(at: i64) -> String {
8888 )
8989 }
9090
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-
10591 /// Seven-character abbreviation, as shown in lists.
10692 pub(crate) fn short_oid(oid: &str) -> &str {
10793 oid.get(..7).unwrap_or(oid)
@@ -594,10 +580,11 @@ pub(crate) mod test_support {
594580 mod tests {
595581 use forge_core::Visibility;
596582
583+ use super::iso_time;
597584 use super::test_support::{Fixture, OWNER, REPO, get, git};
598- use super::{iso_time, url_path};
599585 use crate::i18n::Lang;
600586 use crate::views::relative_time;
587+ use crate::views::url_path;
601588
602589 #[test]
603590 fn dates_and_relative_units_format() {
crates/forge-web/src/pages/compare.rsmodified+2 -1
@@ -30,7 +30,7 @@ use crate::i18n;
3030 use crate::i18n::pulls::{self as g, K};
3131 use crate::notify::{self, Activity};
3232 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};
3434 use crate::pages::ref_live;
3535 use crate::pages::repo::repo_head;
3636 use crate::pages::repo_ctx::{RepoCtx, load_repo};
@@ -39,6 +39,7 @@ use crate::templates;
3939 use crate::views::commit_line::commit_line;
4040 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};
4141 use crate::views::parts::reveal;
42+use crate::views::url_path;
4243 use crate::views::{alert, repo_href, shell, user_facing_message};
4344 use crate::webhooks::emit::{Sender, emit_pull};
4445
crates/forge-web/src/pages/discussion_settings.rsmodified+1 -1
@@ -32,7 +32,7 @@ pub(crate) async fn discussions_switch(
3232 csrf: String,
3333 enabled: bool,
3434 ) -> 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");
3636 Ok(view! {
3737 <form method="post" action=(action.as_str()) id="discussions">
3838 <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::{
1919 discussion_by_number, discussions_href, ensure_enabled, is_author, may_converse,
2020 };
2121 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};
2323 use crate::pages::repo::repo_head;
2424 use crate::pages::repo_ctx::{RepoCtx, load_repo};
2525 use crate::pages::tree::link_context;
2626 use crate::render::markdown::{LinkContext, render_markdown};
2727 use crate::state::AppState;
28+use crate::views::When;
2829 use crate::views::parts::{SubPart, confirm_act, post_act, reveal};
2930 use crate::views::{avatar_url, display_name, now_unix, shell, user_href, user_link};
3031
crates/forge-web/src/pages/discussions.rsmodified+1 -1
@@ -21,12 +21,12 @@ use crate::i18n::community::{self as g, K};
2121 use crate::i18n::{self, Lang};
2222 use crate::pages::discussion_live::list_live_url;
2323 use crate::pages::issue_meta::{can_triage, form_field, form_pairs, refusal_message};
24-use crate::pages::issue_parts::When;
2524 use crate::pages::issues_list::list_href;
2625 use crate::pages::repo::repo_head;
2726 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
2827 use crate::render::markdown::mentioned_usernames;
2928 use crate::state::AppState;
29+use crate::views::When;
3030 use crate::views::parts::{RailItem, SubPart, rail};
3131 use crate::views::{alert, csrf_field, now_unix, repo_href, shell, user_link};
3232
crates/forge-web/src/pages/edit_history.rsmodified+2 -1
@@ -17,12 +17,13 @@ use topcoat::view::{View, component, view};
1717
1818 use crate::i18n::issues::{self as g, K};
1919 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};
2121 use crate::pages::issues_live::item_live_url;
2222 use crate::pages::pull_live::pull_live_url;
2323 use crate::pages::repo::repo_head;
2424 use crate::pages::repo_ctx::{RepoCtx, load_repo};
2525 use crate::state::AppState;
26+use crate::views::When;
2627 use crate::views::parts::SubPart;
2728 use crate::views::{display_name, now_unix, repo_href, shell};
2829
crates/forge-web/src/pages/explore.rsmodified+2 -2
@@ -301,7 +301,7 @@ async fn explore_body(
301301 explore_href(&Finder::default(), sort, 1)
302302 };
303303 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")
305305 } else {
306306 g::t(lang, K::SearchPublicRepos)
307307 };
@@ -311,7 +311,7 @@ async fn explore_body(
311311 (_, n) => format!("{n} organizations"),
312312 };
313313 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.")
315315 } else {
316316 g::t(lang, K::NoPublicReposMatch)
317317 };
crates/forge-web/src/pages/home.rsmodified+1 -1
@@ -16,10 +16,10 @@ use crate::i18n::authoring::{self as ga};
1616 use crate::i18n::migrate::{self as mg, K as MGK};
1717 use crate::i18n::needs::{self as ni, K as NK};
1818 use crate::i18n::orgs::{self as g, K};
19+use crate::i18n::s;
1920 use crate::i18n::{self, Lang};
2021 use crate::pages::ci_runs::run_href;
2122 use crate::pages::org_new::may_create_org;
22-use crate::pages::passkeys::s;
2323 use crate::pages::repo_settings::{notice_banner_for, take_notice};
2424 use crate::state::AppState;
2525 use crate::views::parts::head;
crates/forge-web/src/pages/import.rsmodified+3 -3
@@ -27,7 +27,7 @@ use crate::importer::{
2727 parse_remote, source_ref,
2828 };
2929 use crate::live::{Topic, stream_changes};
30-use crate::pages::ci_runs::{changed_event, events_response};
30+use crate::live::{changed_event, events_response};
3131 use crate::pages::new_repo::{owner_choices, repo_owner};
3232 use crate::pages::repo_ctx::still_readable;
3333 use crate::state::AppState;
@@ -173,7 +173,7 @@ pub(crate) async fn newrepo_tabs(cx: &Cx, lang: Lang, active: &str) -> Result<im
173173 <nav class="tabs" aria-label=(g::t(lang, K::ImportTitle))>
174174 <a href="/new" aria-current=(create.then_some("page"))>(g::t(lang, K::TabCreate))</a>
175175 <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>
177177 </nav>
178178 })
179179 }
@@ -186,7 +186,7 @@ async fn source_tabs(cx: &Cx, lang: Lang, base: &str, active: Source) -> Result<
186186 let forgejo = format!("{base}?source=forgejo");
187187 Ok(view! {
188188 <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>
190190 <nav class="choice" aria-label=(g::t(lang, K::TabImport))>
191191 <a href=(git.as_str()) aria-current=((active == Source::Git).then_some("page"))>(g::t(lang, K::SrcGit))</a>
192192 <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};
3030 use crate::views::review_thread::{ThreadCtx, review_thread_in};
3131 use crate::views::user_facing_message;
3232 use crate::views::{
33- alert, avatar_url, avatar_url_unknown, display_name, iso_time, now_unix, relative_time,
34- repo_href, short_oid, user_href, user_link,
33+ When, alert, avatar_url, avatar_url_unknown, display_name, now_unix, repo_href, short_oid,
34+ stamp_unix, user_href, user_link,
3535 };
3636 use crate::webhooks::emit::{Sender, emit_comment, emit_item_action};
3737
@@ -170,58 +170,6 @@ pub(crate) async fn comment_for(
170170 }
171171 }
172172
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-
225173 pub(crate) fn is_hex_oid(s: &str) -> bool {
226174 (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
227175 }
@@ -1055,7 +1003,7 @@ pub(crate) fn reaction_bar_for(
10551003 /// The hover text of a reaction: who made it, and how many more beyond the first names.
10561004 /// A reaction's name in the viewer's language, for its picker button.
10571005 fn reaction_label(lang: Lang, reaction: Reaction) -> &'static str {
1058- use crate::pages::passkeys::s;
1006+ use crate::i18n::s;
10591007 match reaction {
10601008 Reaction::PlusOne => "+1",
10611009 Reaction::MinusOne => "-1",
crates/forge-web/src/pages/issues_list.rsmodified+1 -1
@@ -17,11 +17,11 @@ use topcoat::view::{View, component, view};
1717
1818 use crate::auth::{require_csrf, require_user};
1919 use crate::i18n::issues::{self as g, K};
20+use crate::i18n::s;
2021 use crate::i18n::{self, Lang};
2122 use crate::notify::{self, Activity};
2223 use crate::pages::issue_meta::{can_triage, form_all, form_field, form_pairs};
2324 use crate::pages::issues_live::list_live_url;
24-use crate::pages::passkeys::s;
2525 use crate::pages::repo::repo_head;
2626 use crate::pages::repo_ctx::{RepoHead, load_repo};
2727 use crate::state::AppState;
crates/forge-web/src/pages/login.rsmodified+2 -1
@@ -21,8 +21,9 @@ use crate::auth::{
2121 set_pending_login, two_factor_enabled, verify_password_async, verify_second_factor,
2222 };
2323 use crate::client_ip::client_ip;
24+use crate::i18n::s;
2425 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};
2627 use crate::state::AppState;
2728 use crate::throttle::{self, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT};
2829 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};
2828 use crate::auth::require_csrf;
2929 use crate::i18n::merge_queue::{self as g, K};
3030 use crate::i18n::{self, Lang};
31+use crate::live::{changed_event, events_response};
3132 use crate::merge_queue as queue;
32-use crate::pages::ci_runs::{changed_event, events_response};
3333 use crate::pages::issue_parts::parse_number;
3434 use crate::pages::pulls_merge::ERR_NOT_OPEN;
3535 use crate::pages::repo::repo_head;
@@ -361,8 +361,7 @@ async fn queue_body(
361361 ) -> Result<impl View> {
362362 let remove_label = g::t(lang, K::RemoveFromQueue);
363363 let remove_note =
364- crate::pages::passkeys::s(lang, "Remove it from the queue?", "Sıradan çıkarılsın mı?")
365- .to_owned();
364+ crate::i18n::s(lang, "Remove it from the queue?", "Sıradan çıkarılsın mı?").to_owned();
366365 Ok(view! {
367366 repo_head(head: head, title: Some(g::t(lang, K::MergeQueueTitle).to_owned()))
368367 <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};
2727 use crate::i18n::alerts as alert_text;
2828 use crate::i18n::misc::{self as g, K};
2929 use crate::i18n::{self, Key, Lang};
30+use crate::live::events_response;
3031 use crate::live::{Topic, stream_changes};
3132 use crate::notify_hub::publish_unread;
32-use crate::pages::ci_runs::events_response;
33-use crate::pages::issue_parts::{parse_number, stamp_unix};
33+use crate::pages::issue_parts::parse_number;
3434 use crate::pages::repo_ctx::{RepoCtx, load_repo};
3535 use crate::pages::repo_transfer::transfer_list_for;
3636 use crate::pages::star::return_path;
3737 use crate::state::AppState;
3838 use crate::views::parts::{RailItem, head, post_act, rail};
39+use crate::views::stamp_unix;
3940 use crate::views::{csrf_field, display_name, iso_time, now_unix, relative_time, repo_href, shell};
4041
4142 /// 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
822823 }
823824 // The page's button shows the viewer's subscription, so the page and its stream are woken.
824825 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);
826827 } else {
827828 state
828829 .live
crates/forge-web/src/pages/org_members.rsmodified+1 -2
@@ -22,7 +22,6 @@ use crate::pages::org_ctx::{
2222 load_org, member_role_word, notice_href, org_notice, org_tab_counts, org_tabs,
2323 parse_member_role, require_form_csrf, require_member, require_owner, take_notice,
2424 };
25-use crate::pages::passkeys;
2625 use crate::state::AppState;
2726 use crate::views::parts::{PeopleList, PersonRow, SubPart, head, people_list};
2827 use crate::views::{avatar_url, display_name, shell};
@@ -100,7 +99,7 @@ async fn members_body(
10099 username_label: g::t(lang, K::Username).to_owned(),
101100 role_label: g::t(lang, K::Role).to_owned(),
102101 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(),
104103 empty: None,
105104 };
106105 Ok(view! {
crates/forge-web/src/pages/org_settings.rsmodified+3 -3
@@ -96,7 +96,7 @@ async fn settings_body(
9696 <form id="org-settings-form" method="post" action=(save_action.as_str())>
9797 <input type="hidden" name="csrf" value=(csrf.as_str())>
9898 <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>
100100 <div class="field">
101101 <label for="org-display-name">(g::t(lang, K::DisplayNameLabel))</label>
102102 <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(
107107 </div>
108108 </section>
109109 <section class="sec">
110- <h2>(crate::pages::passkeys::s(lang, "Members", "Üyeler"))</h2>
110+ <h2>(crate::i18n::s(lang, "Members", "Üyeler"))</h2>
111111 <div class="field">
112112 <label for="org-default-role">(g::t(lang, K::DefaultRoleLabel))</label>
113113 <select id="org-default-role" name="default_repo_role">
@@ -157,7 +157,7 @@ async fn settings_body(
157157 </div>
158158 <div class="acts asks">
159159 <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>
161161 </div>
162162 </form>
163163 </details>
crates/forge-web/src/pages/org_teams.rsmodified+2 -3
@@ -22,7 +22,6 @@ use crate::pages::org_ctx::{
2222 OrgCtx, TEAM_ROLES, load_org, notice_href, org_notice, org_tab_counts, org_tabs,
2323 require_form_csrf, require_member, require_owner, take_notice,
2424 };
25-use crate::pages::passkeys;
2625 use crate::state::AppState;
2726 use crate::views::parts::{SubPart, confirm_act, head, reveal};
2827 use crate::views::{avatar_url, display_name, repo_href, shell};
@@ -350,7 +349,7 @@ async fn team_body(
350349 </summary>
351350 <div class="opened">
352351 <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>
354353 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())])
355354 </div>
356355 </div>
@@ -394,7 +393,7 @@ async fn team_body(
394393 </summary>
395394 <div class="opened">
396395 <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>
398397 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())])
399398 </div>
400399 </div>
crates/forge-web/src/pages/packages.rsmodified+1 -1
@@ -20,9 +20,9 @@ use topcoat::view::{Unescaped, View, component, view};
2020 use crate::auth::{current_user, require_csrf};
2121 use crate::i18n::packages::{self as pk, K};
2222 use crate::i18n::{self, Lang};
23+use crate::live::{changed_event, events_response};
2324 use crate::oci::manifests;
2425 use crate::package_ops::{self, PackageError};
25-use crate::pages::ci_runs::{changed_event, events_response};
2626 use crate::pages::packages_oci::{self, oci_package_view};
2727 use crate::render::markdown::render_markdown;
2828 use crate::state::AppState;
crates/forge-web/src/pages/palette.rsmodified+1 -1
@@ -29,10 +29,10 @@ use crate::auth::current_user;
2929 use crate::i18n::code::{self, K as CK};
3030 use crate::i18n::orgs::{self as g, K};
3131 use crate::i18n::repo_admin::{self as ra, K as RK};
32+use crate::i18n::s;
3233 use crate::i18n::{self, Lang};
3334 use crate::pages::admin_server::{PAGES, page_of};
3435 use crate::pages::org_new::may_create_org;
35-use crate::pages::passkeys::s;
3636 use crate::state::AppState;
3737 use crate::views::{
3838 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::{
3838 check_pre_csrf, clear_pending_login, clear_pre_csrf, login, require_csrf, safe_next,
3939 };
4040 use crate::client_ip::client_ip;
41-use crate::i18n::{self, Key, Lang, t};
41+use crate::i18n::{self, Key, Lang, s, t};
4242 use crate::mail::account::{PasskeyChange, send_passkey_notice};
4343 use crate::state::AppState;
4444 use crate::throttle::{self, LOGIN_IP_LIMIT};
@@ -50,14 +50,6 @@ const CEREMONY_TTL: Duration = Duration::from_secs(5 * 60);
5050 /// Ceremonies held at once. A start past this is refused until old ones expire.
5151 const CEREMONY_CAP: usize = 4096;
5252
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-
6153 // ---- relying party ----
6254
6355 /// 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(
379379 action: Option<BranchAction>,
380380 error: Option<String>,
381381 ) -> Result<impl View> {
382- let heading = crate::pages::passkeys::s(lang, "Branch", "Dal");
382+ let heading = crate::i18n::s(lang, "Branch", "Dal");
383383 Ok(view! {
384384 <section class="sec">
385385 <h2>(heading)</h2>
@@ -396,7 +396,7 @@ pub(crate) async fn branch_box(
396396 <p>(g::t(lang, K::BranchPrefix)) " " <code>(a.branch.as_str())</code> " " (g::t(lang, K::BranchStillHere))</p>
397397 <div class="acts">
398398 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()))
400400 </div>
401401 }
402402 }
crates/forge-web/src/pages/pull_files.rsmodified+2 -3
@@ -27,7 +27,6 @@ use crate::i18n::pulls::{self as g, K};
2727 use crate::i18n::{self, Lang};
2828 use crate::pages::edit_history::thread_edit_counts;
2929 use crate::pages::issue_parts::{check_write, csrf_of, may_converse, parse_number, triage, viewer};
30-use crate::pages::passkeys;
3130 use crate::pages::pull_reviews::{error_text_in, pull_diff, suggest_states};
3231 use crate::pages::pull_view::{commits_of, frame_in, is_merged, pull_header};
3332 use crate::pages::repo_ctx::{RepoCtx, load_repo};
@@ -214,7 +213,7 @@ async fn files_rail(
214213 let mark = g::t(lang, K::ViewedMark);
215214 let changed = g::t(lang, K::ChangedSinceViewed);
216215 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");
218217 Ok(view! {
219218 <nav class="rail" aria-label=(viewed_files)>
220219 <h2>(heading) " " <span>(done_text.as_str())</span></h2>
@@ -359,7 +358,7 @@ async fn review_bar(
359358 let comment = g::t(lang, K::CommentChoice).trim();
360359 let approve = review_strings::t(lang, review_strings::K::ApproveChoice).trim();
361360 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");
363362 let threads_text = match lang {
364363 Lang::Tr => format!("{open_threads} açık konu"),
365364 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 @@
55 //! Every write reaches a topic through one of these paths:
66 //! - A POST under `/{o}/{r}/pulls/...` (comment, review, label, merge, draft, branch, ...): the
77 //! [`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`.
9-//! - A push, a mergeability refresh or an auto-merge: [`bump_repo_pulls`], from the call site.
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: [`crate::live::bump_repo_pulls`], from the
10+//! call site.
1011 //!
11-//! The bump helpers are the one place each topic is bumped from. A new write path calls one of
12-//! them; it does not bump a topic directly.
12+//! The bump helpers in [`crate::live`] are the one place each topic is bumped from. A new write
13+//! path calls one of them; it does not bump a topic directly.
1314 //!
1415 //! What a stream compares is a fingerprint of what the page shows ([`pull_fingerprint`],
1516 //! [`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};
2324 use topcoat::router::response::Response;
2425 use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};
2526
26-use crate::live::{Topic, stream_changes};
27+use crate::live::{Topic, bump_list, bump_pull, bump_repo_pulls, stream_changes};
2728 use crate::pages::issue_parts::parse_number;
2829 use crate::pages::repo_ctx::load_repo;
2930 use crate::state::AppState;
@@ -32,49 +33,6 @@ path_param!(owner);
3233 path_param!(repo);
3334 path_param!(number);
3435
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-
7836 // Fingerprints. Each reads what the page shows; any change to it changes the string.
7937
8038 /// 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};
2525 use crate::pages::commits::{CommitRow, now_secs};
2626 use crate::pages::issue_meta::item_href;
2727 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,
2929 item_head_tools, item_sidebar, load_discussion, load_sidebar, lock_message, may_change,
3030 may_converse, parse_number, post_comment, reachable_among, triage, viewer,
3131 };
@@ -42,6 +42,7 @@ use crate::pages::pulls_merge::{
4242 use crate::pages::repo_ctx::{RepoCtx, load_repo};
4343 use crate::pages::review_requests::{load_reviewers, reviewers_box};
4444 use crate::state::AppState;
45+use crate::views::When;
4546 use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary, commit_status};
4647 use crate::views::diff::LIMITS;
4748 use crate::views::parts::{confirm_act, post_act, reveal};
@@ -512,7 +513,7 @@ async fn review_box(
512513 lang: Lang,
513514 ) -> Result<impl View> {
514515 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");
516517 Ok(view! {
517518 <section class="sec">
518519 <h2>(heading)</h2>
crates/forge-web/src/pages/pulls_list.rsmodified+1 -1
@@ -14,11 +14,11 @@ use topcoat::view::{View, view};
1414
1515 use crate::i18n::merge_queue as mq;
1616 use crate::i18n::pulls::{self as g, K};
17+use crate::i18n::s;
1718 use crate::i18n::{self, Lang};
1819 use crate::pages::issues_list::{
1920 AssigneeView, LabelView, ListQuery, MilestoneView, Selection, SortOption, list_href, stamp_unix,
2021 };
21-use crate::pages::passkeys::s;
2222 use crate::pages::repo::repo_head;
2323 use crate::pages::repo_ctx::load_repo;
2424 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};
2727
2828 use crate::api::{self, json};
2929 use crate::auth::{current_user, require_csrf, require_user};
30-use crate::pages::ci_runs::events_response;
30+use crate::live::events_response;
3131 use crate::state::AppState;
3232 use crate::web_push::{self, Alert, crypto};
3333 use crate::webhooks::client::{WebhookPolicy, validate_url};
crates/forge-web/src/pages/releases.rsmodified+1 -1
@@ -36,7 +36,6 @@ use crate::i18n::{
3636 self, Key, Lang,
3737 releases_ci::{self as g, K},
3838 };
39-use crate::pages::issue_parts::When;
4039 use crate::pages::refs::load_refs;
4140 use crate::pages::releases_live;
4241 use crate::pages::repo::repo_head;
@@ -44,6 +43,7 @@ use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
4443 use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};
4544 use crate::render::markdown::render_markdown;
4645 use crate::state::AppState;
46+use crate::views::When;
4747 use crate::views::parts::{confirm_act, reveal};
4848 use crate::views::repo_list::{PageLink, pager, pager_links};
4949 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};
55 use std::path::PathBuf;
66 use std::time::Duration;
77
8-use forge_core::Config;
98 use forge_core::Repo as RepoRecord;
109 use forge_core::WatchLevel;
1110 use forge_core::time::stamp_before;
@@ -18,13 +17,12 @@ use topcoat::router::{page, path_param, route};
1817 use topcoat::view::{Child, View, ViewExt, component, view};
1918
2019 use crate::i18n::code::{self as g, K};
20+use crate::i18n::s;
2121 use crate::i18n::{self, Lang};
2222 use crate::pages::code_live::{follows_branch, home_live_url};
2323 use crate::pages::finder::file_finder;
24-use crate::pages::issue_parts::stamp_unix;
2524 use crate::pages::notifications::watch_form;
2625 use crate::pages::packages;
27-use crate::pages::passkeys::s;
2826 use crate::pages::refs::{load_refs, ref_links};
2927 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
3028 use crate::pages::repo_side::{StripFacts, code_sub, commit_strip, run_pips, run_rows, tree_facts};
@@ -33,50 +31,14 @@ use crate::pages::tree::{
3331 };
3432 use crate::state::AppState;
3533 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+};
3738
3839 path_param!(owner);
3940 path_param!(repo);
4041
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-
8042 /// Head of every repo page: the title with its actions right beside it, the sub line and the tabs.
8143 /// The Code tab's head is the repo itself: its name, Clone, Star, Fork and the rest in a menu. Any
8244 /// 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};
2525 use crate::auth::{require_csrf, require_user};
2626 use crate::i18n::repo_admin::{self as g, K};
2727 use crate::i18n::{self, Lang};
28-use crate::pages::passkeys;
2928 use crate::pages::repo::repo_head;
3029 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
3130 use crate::pages::repo_settings::settings_frame;
@@ -194,7 +193,7 @@ async fn collaborators_body(
194193 role_action,
195194 remove_action,
196195 remove_note: Some(
197- passkeys::s(
196+ crate::i18n::s(
198197 lang,
199198 "They lose access to this repo at once.",
200199 "Bu repoya erişimi hemen kaybeder.",
@@ -209,7 +208,7 @@ async fn collaborators_body(
209208 username_label: g::t(lang, K::Username).to_owned(),
210209 role_label: g::t(lang, K::Role).to_owned(),
211210 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(),
213212 empty: Some(g::t(lang, K::NoCollaborators).to_owned()),
214213 };
215214 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};
2121
2222 use crate::auth::current_user;
2323 use crate::i18n::{self, Lang};
24-use crate::pages::repo::{https_clone_url, ssh_clone_url};
2524 use crate::pages::repo_mirrors::redacted_url;
2625 use crate::state::AppState;
2726 use crate::views::repo_href;
27+use crate::views::{https_clone_url, ssh_clone_url};
2828
2929 pub struct RepoCtx {
3030 pub repo: Repo,
crates/forge-web/src/pages/repo_secrets.rsmodified+1 -1
@@ -203,7 +203,7 @@ async fn secrets_body(
203203 <section class="sec">
204204 <h2>(g::t(lang, K::AddOrUpdate))</h2>
205205 <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,
207207 if let Some(message) = error {
208208 alert(message: message.as_str())
209209 }
crates/forge-web/src/pages/repo_security.rsmodified+1 -1
@@ -139,7 +139,7 @@ async fn security_body(
139139 <div class="line" data-kb-row="">
140140 <span class="name" title=(row.summary.as_str())>(row.advisory.as_str())</span>
141141 <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>
143143 if row.open {
144144 post_act(label: g::t(lang, K::Dismiss), action: row.dismiss_action.as_str(), csrf: csrf.as_str(), fields: row.fields.clone())
145145 }
crates/forge-web/src/pages/repo_settings.rsmodified+2 -3
@@ -35,7 +35,6 @@ use crate::i18n::merge_queue as mq;
3535 use crate::i18n::repo_admin::{self as g, K};
3636 use crate::i18n::{self, Lang};
3737 use crate::pages::discussion_settings::discussions_switch;
38-use crate::pages::passkeys;
3938 use crate::pages::refs::load_refs;
4039 use crate::pages::repo::repo_head;
4140 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
@@ -824,7 +823,7 @@ async fn branch_rule_form(
824823 </form>
825824 <div class="acts rule-acts">
826825 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>
828827 } else {
829828 <button type="submit" form=(form_id.as_str()) class="primary">(g::t(lang, K::AddRule))</button>
830829 }
@@ -1435,7 +1434,7 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i
14351434 .iter()
14361435 .any(|rule| rule.pattern == pattern);
14371436 let checked = if taken {
1438- Err(passkeys::s(
1437+ Err(crate::i18n::s(
14391438 lang,
14401439 "A rule for this pattern already exists. Pick it in the list to change it.",
14411440 "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;
2222 use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};
2323
2424 use crate::auth::require_user;
25-use crate::live::{LiveHub, Topic, stream_wakes};
25+use crate::live::{Topic, bump_settings, stream_wakes};
2626 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo};
2727 use crate::state::AppState;
2828
@@ -47,11 +47,6 @@ pub async fn settings_head(ctx: &RepoCtx, state: &AppState) -> Result<RepoHead>
4747 Ok(head)
4848 }
4949
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-
5550 /// The settings stream: the settings pages, and the refs their branch picker lists. Admins only,
5651 /// as the settings page is.
5752 #[route(GET "/{owner}/{repo}/settings/live")]
@@ -135,7 +130,7 @@ async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Respons
135130 state.live.bump(&crate::live::Topic::Repo(repo_id.clone()));
136131 // The merge gate of a pull page reads the branch protection rules, so every pull of the
137132 // 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;
139134 }
140135 result
141136 }
crates/forge-web/src/pages/repo_side.rsmodified+1 -1
@@ -14,10 +14,10 @@ use forge_git::{browse, history};
1414 use topcoat::Result;
1515
1616 use crate::i18n::Lang;
17+use crate::i18n::s;
1718 use crate::i18n::timeline as tl;
1819 use crate::pages::ci_runs::run_href;
1920 use crate::pages::packages::PackageLink;
20-use crate::pages::passkeys::s;
2121 use crate::pages::releases::LatestRelease;
2222 use crate::pages::tree::LatestBar;
2323 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};
2222 use crate::auth::require_csrf;
2323 use crate::i18n::Lang;
2424 use crate::i18n::repo_admin::{self as g, K};
25-use crate::pages::repo_settings_live::bump_settings;
25+use crate::live::bump_settings;
2626 use crate::state::AppState;
2727 use crate::views::parts::{confirm_act, post_act, reveal};
2828 use crate::views::{alert, rel_time};
crates/forge-web/src/pages/repo_webhooks.rsmodified+4 -4
@@ -543,7 +543,7 @@ async fn hook_form(
543543 }
544544 <input type="hidden" name="csrf" value=(csrf.as_str())>
545545 <section class="sec">
546- <h2>(crate::pages::passkeys::s(lang, "Endpoint", "Uç nokta"))</h2>
546+ <h2>(crate::i18n::s(lang, "Endpoint", "Uç nokta"))</h2>
547547 <div class="field">
548548 <label for="hook-url">(g::t(lang, K::PayloadUrl))</label>
549549 <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(
557557 </div>
558558 </section>
559559 <section class="sec">
560- <h2>(crate::pages::passkeys::s(lang, "Delivery", "Teslimat"))</h2>
560+ <h2>(crate::i18n::s(lang, "Delivery", "Teslimat"))</h2>
561561 <div class="field" role="group" aria-labelledby="hook-events-title">
562562 <span class="field-label" id="hook-events-title">(g::t(lang, K::Events))</span>
563563 <div class="checks">
@@ -570,7 +570,7 @@ async fn hook_form(
570570 </div>
571571 </div>
572572 <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>
574574 <div class="checks">
575575 <label class="switch">
576576 <input type="checkbox" name="active" value="on" checked=(active)>
@@ -701,7 +701,7 @@ async fn hook_body(
701701 frame_top(head: head, title: title.clone(), heading: heading, notice: notice, archived: archived, lang: lang,
702702 if archived {
703703 <section class="sec">
704- <h2>(crate::pages::passkeys::s(lang, "Endpoint", "Uç nokta"))</h2>
704+ <h2>(crate::i18n::s(lang, "Endpoint", "Uç nokta"))</h2>
705705 <p class="state">(draft.url.as_str())</p>
706706 </section>
707707 } else {
crates/forge-web/src/pages/settings_appearance.rsmodified+1 -7
@@ -23,8 +23,8 @@ use crate::auth::{require_csrf, require_user};
2323 use crate::custom_colour;
2424 use crate::i18n::accents::{accent_name, base_name};
2525 use crate::i18n::misc::{self as g, K};
26+use crate::i18n::s;
2627 use crate::i18n::{self, Lang};
27-use crate::pages::passkeys::s;
2828 use crate::state::AppState;
2929 use crate::views::parts::{SubPart, head};
3030 use crate::views::shell;
@@ -169,12 +169,6 @@ struct AppearancePage {
169169 sound_on: bool,
170170 }
171171
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-
178172 /// The label of a language code. The two native names stay as they are in every language.
179173 fn language_label(lang: Lang, code: &str) -> &'static str {
180174 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};
2727 use crate::exporter;
2828 use crate::i18n::migrate::{self as g, K};
2929 use crate::i18n::{self, Key, Lang};
30-use crate::pages::ci_runs::{changed_event, events_response};
30+use crate::live::{changed_event, events_response};
3131 use crate::state::AppState;
3232 use crate::views::parts::{RailItem, SubPart, confirm_act, head, rail};
3333 use crate::views::{alert, csrf_field, human_size, rel_time, shell};
@@ -63,7 +63,7 @@ fn signature(exports: &[DataExport]) -> String {
6363 fn data_rail_items(lang: Lang, delete: bool) -> Vec<RailItem> {
6464 vec![
6565 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(),
6767 val: String::new(),
6868 href: "/settings/export".to_owned(),
6969 current: !delete,
@@ -100,7 +100,7 @@ async fn export_sheet(
100100 Ok(view! {
101101 <div class="sheet export-page" data-live=(live.as_deref()) data-live-state=(if building { "building" } else { "idle" })>
102102 <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>
104104 if empty {
105105 <p class="state">(g::t(lang, K::ExportNone))</p>
106106 }
@@ -124,7 +124,7 @@ async fn export_sheet(
124124 <a class="act" href=(format!("/settings/export/{}/download", export.id))>(g::t(lang, K::ExportDownload))</a>
125125 }
126126 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)
128128 }
129129 </div>
130130 if export.state == ExportState::Building {
@@ -228,7 +228,7 @@ async fn data_body(
228228 }
229229 )
230230 <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)
232232 if delete {
233233 delete_sheet(lang: lang, csrf: csrf, two_factor_on: two_factor_on, owned_repos: owned_repos, error: delete_error)
234234 } else {
crates/forge-web/src/pages/settings_gpg.rsmodified+1 -1
@@ -13,8 +13,8 @@ use topcoat::view::{View, component, view};
1313
1414 use crate::audit::{self, Actor, Target};
1515 use crate::auth::{require_csrf, require_user};
16+use crate::i18n::s;
1617 use crate::i18n::{self, Key, Lang, t};
17-use crate::pages::passkeys::s;
1818 use crate::pages::settings_keys::{AddQuery, KeyKind, KeysDraft, keys_page_view};
1919 use crate::signatures;
2020 use crate::state::AppState;
crates/forge-web/src/pages/settings_keys.rsmodified+2 -2
@@ -14,8 +14,8 @@ use topcoat::view::{View, component, view};
1414
1515 use crate::audit::{self, Actor, Target};
1616 use crate::auth::{require_csrf, require_user};
17+use crate::i18n::s;
1718 use crate::i18n::{self, Key, Lang, t, unsupported_key_type};
18-use crate::pages::passkeys::s;
1919 use crate::pages::settings_gpg::gpg_section;
2020 use crate::pages::settings_tokens::tokens_section;
2121 use crate::state::AppState;
@@ -251,7 +251,7 @@ pub(crate) async fn keys_page_view(
251251 }
252252
253253 fn pk_title(lang: Lang) -> &'static str {
254- crate::pages::passkeys::s(lang, "Keys", "Anahtarlar")
254+ crate::i18n::s(lang, "Keys", "Anahtarlar")
255255 }
256256
257257 #[component]
crates/forge-web/src/pages/settings_live.rsmodified+1 -7
@@ -34,15 +34,9 @@ use topcoat::router::response::Response;
3434 use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route};
3535
3636 use crate::auth::current_user;
37-use crate::live::{LiveHub, Topic, stream_wakes};
38-use crate::pages::ci_runs::events_response;
37+use crate::live::{LiveHub, Topic, bump_account, events_response, stream_wakes};
3938 use crate::state::AppState;
4039
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-
4640 /// The change stream of the viewer's settings. The viewer comes from the session only, so a user
4741 /// can follow only their own settings. Without a session: 401.
4842 #[route(GET "/settings/events")]
crates/forge-web/src/pages/settings_notifications.rsmodified+1 -1
@@ -16,8 +16,8 @@ use topcoat::view::{View, component, view};
1616
1717 use crate::auth::{require_csrf, require_user};
1818 use crate::i18n::push as push_text;
19+use crate::i18n::s;
1920 use crate::i18n::{self, Key, Lang, t};
20-use crate::pages::passkeys::s;
2121 use crate::state::AppState;
2222 use crate::views::parts::{SubPart, confirm_act, head};
2323 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::{
2424 };
2525 use crate::i18n::packages::{self as pk, K as PK};
2626 use crate::i18n::releases_ci::{self as rc, K as RC};
27+use crate::i18n::s;
2728 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};
2930 use crate::pages::settings_export;
3031 use crate::pages::settings_sessions::session_label;
3132 use crate::state::AppState;
@@ -1007,7 +1008,7 @@ async fn account_delete(cx: &Cx, Form(form): Form<DeleteAccountForm>) -> Result<
10071008 let ghost = state.store.ensure_ghost_user().await?;
10081009 match state.store.delete_user(&user_id, &ghost.id).await {
10091010 Ok(_) => {
1010- crate::pages::settings_live::bump_account(state, &user_id);
1011+ crate::live::bump_account(state, &user_id);
10111012 // The account row is gone, so the entry names no actor; the username is kept.
10121013 audit::record(
10131014 &state.store,
crates/forge-web/src/pages/settings_tokens.rsmodified+1 -1
@@ -21,8 +21,8 @@ use crate::audit::{self, Actor, Target};
2121 use crate::auth::{require_csrf, require_user};
2222 use crate::i18n::packages::{self as pk, K as PK};
2323 use crate::i18n::releases_ci::{self as rc, K as RC};
24+use crate::i18n::s;
2425 use crate::i18n::{self, Key, Lang, t, token_name_length};
25-use crate::pages::passkeys::s;
2626 use crate::pages::settings_keys::{AddQuery, KeyKind, KeysDraft, keys_page_view};
2727 use crate::state::AppState;
2828 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;
1818 use topcoat::router::route;
1919
2020 use crate::auth::current_user;
21+use crate::live::events_response;
2122 use crate::pages::activity::activity_changes;
22-use crate::pages::ci_runs::events_response;
2323 use crate::pages::notifications::unread_changes;
2424 use crate::pages::settings_live::alive_stream;
2525 use crate::state::AppState;
crates/forge-web/src/pages/tree.rsmodified+1 -1
@@ -17,10 +17,10 @@ use topcoat::view::{Unescaped, View, component, view};
1717
1818 use crate::i18n::code::{self as g, K};
1919 use crate::i18n::misc::{self as mi, K as MK};
20+use crate::i18n::s;
2021 use crate::i18n::{self, Lang};
2122 use crate::pages::code_live::{follows_branch, live_url};
2223 use crate::pages::finder::file_finder;
23-use crate::pages::passkeys::s;
2424 use crate::pages::refs::{load_refs, ref_links};
2525 use crate::pages::repo::repo_head;
2626 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};
1313
1414 use crate::auth::require_csrf;
1515 use crate::state::AppState;
16-
17-/// Key of the diff view: `split` or `unified`.
18-pub const DIFF_VIEW: &str = "diff_view";
16+use crate::views::diff::DIFF_VIEW;
1917
2018 #[derive(Deserialize)]
2119 struct PrefForm {
crates/forge-web/src/pages/wiki.rsmodified+2 -1
@@ -24,9 +24,10 @@ use crate::auth::{require_csrf, require_user};
2424 use crate::i18n::community::{self as g, K};
2525 use crate::i18n::{self, Lang};
2626 use crate::live::Topic;
27+use crate::live::bump_wiki;
2728 use crate::pages::repo::repo_head;
2829 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};
3031 use crate::render::markdown::render_markdown;
3132 use crate::state::AppState;
3233 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 {
3939 format!("/{owner}/{repo}/wiki/{page}/events")
4040 }
4141
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-
4742 /// The head commit of the wiki's main branch, or empty for a wiki with no pages.
4843 async fn head_fingerprint(dir: PathBuf) -> Result<String> {
4944 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(
113113 }
114114 let synced = pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await;
115115 // 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;
117117 synced
118118 }
119119
@@ -234,7 +234,7 @@ async fn apply_commit_refs(
234234 if closed {
235235 state.live.bump_issue(&repo.id, &issue.id);
236236 // 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);
238238 emit_item_action(state, repo, sender, false, number, "closed").await;
239239 notify::dispatch(
240240 state,
@@ -257,7 +257,7 @@ async fn apply_commit_refs(
257257 .add_event(&issue.id, actor, "referenced", json!({"commit": oid}))
258258 .await?;
259259 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);
261261 }
262262 }
263263 Ok(())
crates/forge-web/src/pulls_sync.rsmodified+3 -3
@@ -58,14 +58,14 @@ pub async fn sync_pulls_for_ref(
5858 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: head update failed");
5959 }
6060 // 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);
6262 }
6363 let bases = state.store.open_pulls_for_base(&repo.id, branch).await?;
6464 for (number, issue_id) in bases {
6565 if let Err(e) = sync_base(state, repo, actor_id, number, &issue_id, old, new).await {
6666 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: base update failed");
6767 }
68- crate::pages::pull_live::bump_pull(state, &repo.id, &issue_id);
68+ crate::live::bump_pull(state, &repo.id, &issue_id);
6969 }
7070 Ok(())
7171 }
@@ -348,7 +348,7 @@ pub async fn refresh_mergeability(
348348 &files,
349349 )
350350 .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);
352352 Ok(())
353353 }
354354
crates/forge-web/src/ssh_backend.rsmodified+1 -1
@@ -85,7 +85,7 @@ impl GitBackend for SshBackend {
8585 if let Err(e) = self.state.store.touch_ssh_key(&key.id).await {
8686 tracing::warn!(error = %e, "could not record ssh key use");
8787 }
88- crate::pages::settings_live::bump_account(&self.state, &key.user_id);
88+ crate::live::bump_account(&self.state, &key.user_id);
8989 // A key that belongs to an organization is refused here, not only in `authorize`.
9090 match self.state.store.user_by_id(&key.user_id).await {
9191 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(
154154 /// A status description in the viewer's language. CI's own descriptions are stored in English;
155155 /// what an outside tool reports stays as it sent it.
156156 fn description_text(lang: Lang, text: &str) -> &str {
157- use crate::pages::passkeys::s;
157+ use crate::i18n::s;
158158 match text {
159159 "Waiting for approval" => s(lang, "Waiting for approval", "Onay bekliyor"),
160160 "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;
2323 use crate::i18n::browse as b;
2424 use crate::i18n::code::{self as g, K};
2525 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;
2826 use crate::state::AppState;
2927 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";
3032
3133 /// Per-diff limits used by the commit and pull-request pages.
3234 pub const LIMITS: DiffLimits = DiffLimits {
crates/forge-web/src/views/find.rsmodified+1 -1
@@ -9,7 +9,7 @@ use topcoat::context::Cx;
99 use topcoat::view::{View, component, view};
1010
1111 use crate::i18n::Lang;
12-use crate::pages::passkeys::s;
12+use crate::i18n::s;
1313
1414 /// The longest search kept, in characters.
1515 pub const MAX_QUERY_CHARS: usize = 100;
crates/forge-web/src/views/mod.rsmodified+247 -13
@@ -11,11 +11,15 @@ pub mod repo_list;
1111 pub mod review_thread;
1212 pub mod timeline;
1313
14+use std::collections::HashMap;
1415 use std::sync::OnceLock;
1516
1617 use forge_core::ci::RunState;
18+use forge_core::config::BannerConfig;
1719 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};
1923 use hex::encode;
2024 use http::header::{
2125 CONTENT_SECURITY_POLICY, REFERRER_POLICY, X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS,
@@ -24,6 +28,7 @@ use http::{HeaderValue, Uri};
2428 use sha2::{Digest, Sha256};
2529 use topcoat::Result;
2630 use topcoat::context::{Cx, try_context};
31+use topcoat::cookie::{Cookies, cookies};
2732 use topcoat::router::request::uri;
2833 use topcoat::router::response::{Response, response_headers};
2934 use topcoat::router::{Body, Next, layer};
@@ -39,9 +44,9 @@ use crate::i18n::migrate::{self as mg, K as MGK};
3944 use crate::i18n::misc::{self as mi, K as MK};
4045 use crate::i18n::orgs::{self as o, K as OK};
4146 use crate::i18n::packages::{self as pk, K as PK};
47+use crate::i18n::s;
4248 use crate::i18n::{self, Key, Lang, t};
43-use crate::pages::assets::highlight_css_text;
44-use crate::pages::passkeys::s;
49+use crate::render::highlight::highlight_css;
4550 use crate::state::AppState;
4651
4752 /// 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 {
168173 fn repo_section_label(lang: Lang, kind: &str) -> Option<String> {
169174 match kind {
170175 "issues" | "pulls" | "ci" | "commits" | "branches" | "tags" | "releases"
171- | "discussions" | "wiki" | "security" | "settings" => {
172- Some(crate::pages::repo::tab_title(lang, kind, ""))
173- }
176+ | "discussions" | "wiki" | "security" | "settings" => Some(tab_title(lang, kind, "")),
174177 "milestones" => Some(s(lang, "Milestones", "Kilometre taşları").to_owned()),
175178 "labels" => Some(s(lang, "Labels", "Etiketler").to_owned()),
176179 _ => None,
@@ -576,8 +579,8 @@ pub async fn shell(
576579 (Some((user, _)), Some(state)) => Some(state.store.user_prefs(&user.id).await?),
577580 _ => None,
578581 };
579- let banner = crate::pages::banner::current(cx, prefs.as_ref());
580- let sound_attr = crate::pages::settings_appearance::sound_attr(prefs.as_ref());
582+ let banner = current_banner(cx, prefs.as_ref());
583+ let sound_attr = sound_attr(prefs.as_ref());
581584 let banner_back = back.clone().unwrap_or_else(|| "/".to_owned());
582585 let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss);
583586 // 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(
769772 data-orgs=(o::t(lang, OK::Organizations)) data-pages=(br::t(lang, br::K::PalettePages))
770773 data-empty=(br::t(lang, br::K::PaletteNoMatches)) data-loading=(br::t(lang, br::K::PaletteLoading))
771774 data-failed=(br::t(lang, br::K::PaletteFailed))
772- data-key-move=(crate::pages::passkeys::s(lang, "move", "gezin"))
773- data-key-open=(crate::pages::passkeys::s(lang, "open", "aç"))
774- data-key-close=(crate::pages::passkeys::s(lang, "close", "kapat"))
775+ data-key-move=(crate::i18n::s(lang, "move", "gezin"))
776+ data-key-open=(crate::i18n::s(lang, "open", "aç"))
777+ data-key-close=(crate::i18n::s(lang, "close", "kapat"))
775778 data-search-label=(search_for_label) data-files=(br::t(lang, br::K::PaletteFiles))
776779 data-actions=(br::t(lang, br::K::PaletteActions)) data-done=(br::t(lang, br::K::PaletteDone))
777780 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> {
9991002 }
10001003
10011004 pub fn settings_items(lang: Lang) -> Vec<NavItem> {
1002- let pk = crate::pages::passkeys::s;
1005+ let pk = crate::i18n::s;
10031006 let item = |key, href: &'static str, label| NavItem {
10041007 key,
10051008 href: href.to_owned(),
@@ -1115,7 +1118,7 @@ pub fn display_name(lang: Lang, username: &str) -> String {
11151118 pub fn avatar_url(username: &str, hash: Option<&str>) -> String {
11161119 match hash {
11171120 Some(hash) => format!("/avatars/{}?v={hash}", enc(username)),
1118- None => crate::pages::avatars::default_data_url(username),
1121+ None => default_data_url(username),
11191122 }
11201123 }
11211124
@@ -1642,6 +1645,237 @@ pub async fn ref_selector(
16421645 })
16431646 }
16441647
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+
16451879 #[cfg(test)]
16461880 mod tests {
16471881 use super::*;
crates/forge-web/src/views/parts.rsmodified+1 -1
@@ -6,7 +6,7 @@ use topcoat::context::Cx;
66 use topcoat::view::{Child, View, ViewExt, component, view};
77
88 use crate::i18n::Lang;
9-use crate::pages::passkeys::s;
9+use crate::i18n::s;
1010
1111 /// The width class of a strip segment holding `part` of `total`: `fr1` to `fr40`, since a page may
1212 /// 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};
99
1010 use crate::i18n::orgs::{self as g, K};
1111 use crate::i18n::{self, Lang};
12-use crate::pages::issue_parts::When;
13-use crate::views::repo_href;
12+use crate::views::{When, repo_href};
1413
1514 /// The fact a row leads with when the repo is private ("Private · "); public says nothing, it is
1615 /// the usual case.
crates/forge-web/src/views/review_thread.rsmodified+1 -2
@@ -14,10 +14,9 @@ use topcoat::view::{Unescaped, View, component, view};
1414
1515 use crate::i18n::Lang;
1616 use crate::i18n::pulls_review::{self as g, K};
17-use crate::pages::issue_parts::When;
1817 use crate::render::markdown::{LinkContext, render_markdown};
1918 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};
2120
2221 /// What the Apply control of a suggestion shows. A root without a state shows the diff only.
2322 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
crates/forge-web/src/webhooks/emit.rsmodified+1 -1
@@ -446,7 +446,7 @@ async fn enqueue(
446446 Ok(_) => {
447447 queued += 1;
448448 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);
450450 }
451451 Err(e) => {
452452 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;
2020 use tokio::sync::Notify;
2121
2222 use super::client::{HookClient, SendOutcome, WebhookPolicy, sign, validate_url};
23-use crate::pages::repo_settings_live::bump_settings;
23+use crate::live::bump_settings;
2424 use crate::state::AppState;
2525
2626 /// Handle that wakes the worker. `emit` calls `notify_one` after queueing deliveries.