diff --git a/crates/forge-core/src/store/contributions.rs b/crates/forge-core/src/store/contributions.rs index 57c9fca..28a253b 100644 --- a/crates/forge-core/src/store/contributions.rs +++ b/crates/forge-core/src/store/contributions.rs @@ -73,7 +73,8 @@ impl Store { /// Events are grouped by minute and each minute is placed on its local day, so zones with /// half-hour or quarter-hour offsets and DST changes land on the right day. /// A contribution is a push (ref deletions are left out), an issue or pull request opened - /// (pull requests are `issues` rows with `kind = 'pull'`), or a comment. + /// (pull requests are `issues` rows with `kind = 'pull'`), or a comment. Only public repos count: + /// a repo made private takes its contributions off the calendar. pub async fn contribution_counts( &self, user_id: &str, @@ -84,15 +85,17 @@ impl Store { let sql = "SELECT minute, COUNT(*) FROM ( \ SELECT substr(created_at, 1, 16) AS minute FROM push_events \ WHERE actor_id = ?1 AND created_at >= ?2 AND new_oid NOT IN (?3, ?4) \ + AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ UNION ALL \ SELECT substr(created_at, 1, 16) FROM issues \ WHERE author_id = ?1 AND created_at >= ?2 AND kind IN ('issue', 'pull') \ + AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ UNION ALL \ - SELECT substr(created_at, 1, 16) FROM comments \ - WHERE author_id = ?1 AND created_at >= ?2 \ + SELECT substr(c.created_at, 1, 16) FROM comments c JOIN issues i ON i.id = c.issue_id \ + WHERE c.author_id = ?1 AND c.created_at >= ?2 AND i.repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ UNION ALL \ SELECT substr(created_at, 1, 16) FROM coauthored_commits \ - WHERE user_id = ?1 AND created_at >= ?2 \ + WHERE user_id = ?1 AND created_at >= ?2 AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ ) GROUP BY minute"; let params = vec![ Value::Text(user_id.to_string()), @@ -133,22 +136,24 @@ impl Store { 0, '', '' FROM push_events p \ JOIN repos r ON r.id = p.repo_id JOIN users o ON o.id = r.owner_id \ WHERE p.actor_id = ?1 AND p.created_at >= ?2 AND p.created_at < ?3 \ - AND p.new_oid NOT IN (?4, ?5) \ + AND p.new_oid NOT IN (?4, ?5) AND r.visibility = 'public' \ UNION ALL \ SELECT i.kind, o.username, r.name, i.created_at, '', i.number, i.title, '' FROM issues i \ JOIN repos r ON r.id = i.repo_id JOIN users o ON o.id = r.owner_id \ WHERE i.author_id = ?1 AND i.created_at >= ?2 AND i.created_at < ?3 \ - AND i.kind IN ('issue', 'pull') \ + AND i.kind IN ('issue', 'pull') AND r.visibility = 'public' \ UNION ALL \ SELECT 'comment', o.username, r.name, c.created_at, '', i.number, i.title, '' \ FROM comments c JOIN issues i ON i.id = c.issue_id \ JOIN repos r ON r.id = i.repo_id JOIN users o ON o.id = r.owner_id \ WHERE c.author_id = ?1 AND c.created_at >= ?2 AND c.created_at < ?3 \ + AND r.visibility = 'public' \ UNION ALL \ SELECT 'coauthored', o.username, r.name, k.created_at, '', 0, k.summary, k.commit_oid \ FROM coauthored_commits k \ JOIN repos r ON r.id = k.repo_id JOIN users o ON o.id = r.owner_id \ WHERE k.user_id = ?1 AND k.created_at >= ?2 AND k.created_at < ?3 \ + AND r.visibility = 'public' \ ORDER BY created_at DESC LIMIT ?6"; let params = vec![ Value::Text(user_id.to_string()), @@ -405,4 +410,47 @@ mod tests { .is_empty() ); } + #[tokio::test] + async fn private_repos_are_left_out() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "x", false) + .await + .unwrap(); + let demo = store + .create_repo(&tahinli.id, "demo", "", Visibility::Public, "main") + .await + .unwrap(); + let at = "2026-03-01T10:00:00.000000000Z"; + store + .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", ZERO, OID, at) + .await + .unwrap(); + let since = "2026-03-01T00:00:00.000000000Z"; + let until = "2026-03-02T00:00:00.000000000Z"; + assert_eq!( + store.contribution_counts(&tahinli.id, since, "UTC").await.unwrap().len(), + 1 + ); + + store + .set_repo_visibility(&demo.id, Visibility::Private) + .await + .unwrap(); + assert!( + store + .contribution_counts(&tahinli.id, since, "UTC") + .await + .unwrap() + .is_empty() + ); + assert!( + store + .contributions_between(&tahinli.id, since, until) + .await + .unwrap() + .is_empty() + ); + } } diff --git a/crates/forge-core/src/store/notifications.rs b/crates/forge-core/src/store/notifications.rs index a5521b2..b8748b2 100644 --- a/crates/forge-core/src/store/notifications.rs +++ b/crates/forge-core/src/store/notifications.rs @@ -4,6 +4,7 @@ use turso::transaction::Transaction; use turso::{Row, Value}; use super::issues::finish; +use super::repo_listing::READABLE_BY_VIEWER; use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id}; use crate::error::{Error, Result}; use crate::model::Id; @@ -13,6 +14,20 @@ use crate::time::now_stamp; /// Largest page `list_notifications` returns, whatever the caller asks for. const MAX_NOTIFICATION_PAGE: u32 = 200; +/// The condition under which the inbox owner may still read repo `r`: the read rule, or an +/// instance admin. Takes the user id five times. A repo made private, or one the user was removed +/// from, drops out of the inbox, the dashboard and the unread count at once. +fn readable_repo() -> String { + format!( + "({READABLE_BY_VIEWER} OR EXISTS (SELECT 1 FROM users ua WHERE ua.id = ? AND ua.is_admin = 1))" + ) +} + +/// The user id, bound once per `?` of `readable_repo`. +fn readable_params(user_id: &str) -> impl Iterator + '_ { + (0..5).map(move |_| Value::Text(user_id.to_string())) +} + /// Inbox rows joined with their repo, owner, issue or pull, and last actor. `?` placeholders /// are appended to by `list_notifications`. const NOTIFICATION_SELECT: &str = "SELECT n.id, n.repo_id, o.username, r.name, n.issue_id, \ @@ -301,8 +316,12 @@ impl Store { before: Option<&str>, limit: u32, ) -> Result> { - let mut sql = format!("{NOTIFICATION_SELECT} WHERE n.user_id = ?"); + let mut sql = format!( + "{NOTIFICATION_SELECT} WHERE n.user_id = ? AND {}", + readable_repo() + ); let mut params = vec![Value::Text(user_id.to_string())]; + params.extend(readable_params(user_id)); if unread_only { sql.push_str(" AND n.unread = 1"); } @@ -318,20 +337,29 @@ impl Store { fetch_all(&conn, &sql, params, map_notification).await } - /// Number of unread inbox rows of the user, issues and discussions together. + /// Number of unread inbox rows of the user, issues and discussions together. Rows of repos the + /// user can no longer read are left out. pub async fn unread_count(&self, user_id: &str) -> Result { + let readable = readable_repo(); + let sql = format!( + "SELECT (SELECT COUNT(*) FROM notifications n JOIN repos r ON r.id = n.repo_id \ + WHERE n.user_id = ? AND n.unread = 1 AND {readable}) + \ + (SELECT COUNT(*) FROM discussion_notifications n JOIN repos r ON r.id = n.repo_id \ + WHERE n.user_id = ? AND n.unread = 1 AND {readable}) + \ + (SELECT COUNT(*) FROM advisory_notifications n JOIN repos r ON r.id = n.repo_id \ + WHERE n.user_id = ? AND n.unread = 1 AND {readable}) + \ + (SELECT COUNT(*) FROM admin_notifications WHERE user_id = ? AND unread = 1)" + ); + let mut params = Vec::new(); + for _ in 0..3 { + params.push(Value::Text(user_id.to_string())); + params.extend(readable_params(user_id)); + } + params.push(Value::Text(user_id.to_string())); let conn = self.read_conn().await; - let n = fetch_opt( - &conn, - "SELECT (SELECT COUNT(*) FROM notifications WHERE user_id = ?1 AND unread = 1) + \ - (SELECT COUNT(*) FROM discussion_notifications WHERE user_id = ?1 AND unread = 1) + \ - (SELECT COUNT(*) FROM advisory_notifications WHERE user_id = ?1 AND unread = 1) + \ - (SELECT COUNT(*) FROM admin_notifications WHERE user_id = ?1 AND unread = 1)", - (user_id.to_string(),), - |row| col_int(row, 0), - ) - .await? - .unwrap_or(0); + let n = fetch_opt(&conn, &sql, params, |row| col_int(row, 0)) + .await? + .unwrap_or(0); u64::try_from(n).map_err(|_| Error::Database("negative count".into())) } diff --git a/crates/forge-core/src/store/repo_listing.rs b/crates/forge-core/src/store/repo_listing.rs index dded9db..25d27ae 100644 --- a/crates/forge-core/src/store/repo_listing.rs +++ b/crates/forge-core/src/store/repo_listing.rs @@ -9,7 +9,7 @@ use super::{ map_repo, }; use crate::error::Result; -use crate::model::User; +use crate::model::{Repo, User}; /// Whose repos a profile tab lists. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -31,7 +31,7 @@ const STARS: &str = "(SELECT COUNT(*) FROM stars s WHERE s.repo_id = r.id)"; /// public repos, the viewer's own repos, repos where the viewer is a collaborator, and repos of an /// org where the viewer's org role (`Store::org_repo_role`) is some role: an org owner, a member /// when the default repo role is not `none`, or a member of a team covering the repo. -const READABLE_BY_VIEWER: &str = "(r.visibility = 'public' OR r.owner_id = ? \ +pub(crate) const READABLE_BY_VIEWER: &str = "(r.visibility = 'public' OR r.owner_id = ? \ OR EXISTS (SELECT 1 FROM collaborators c WHERE c.repo_id = r.id AND c.user_id = ?) \ OR EXISTS (SELECT 1 FROM org_members m WHERE m.org_id = r.owner_id AND m.user_id = ? AND ( \ m.role = 'owner' \ @@ -94,6 +94,30 @@ impl Store { Ok(u64::try_from(n).unwrap_or(0)) } + /// Up to `limit` repos the signed-in `viewer` is part of: their own, ones they collaborate on, and + /// org repos they reach. Sorted by owner and name, for the command palette. Other public repos are + /// left out (Explore lists them), and so are an admin's: on a big instance they would push the + /// viewer's own repos past the limit. The rule is `READABLE_BY_VIEWER` without its public clause. + pub async fn list_viewer_repos(&self, viewer: &User, limit: u64) -> Result> { + let where_sql = READABLE_BY_VIEWER.replacen("r.visibility = 'public' OR ", "", 1); + debug_assert_ne!(where_sql, READABLE_BY_VIEWER, "the public clause moved"); + let params: Vec = (0..4).map(|_| Value::Text(viewer.id.clone())).collect(); + let limit = i64::try_from(limit).unwrap_or(i64::MAX); + let mut params = params; + params.push(Value::Integer(limit)); + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {REPO_COLS} FROM repos r JOIN users u ON u.id = r.owner_id \ + WHERE {where_sql} ORDER BY u.username_folded ASC, r.name_folded ASC LIMIT ?" + ), + params, + map_repo, + ) + .await + } + /// One page of the repos `from_sql` (which joins `repos r` and its owner `users u`) yields /// under `where_sql`, in `sort` order, with the total match count. `page` is 1-based and is /// clamped to the last page; `per_page` to 1..=100. diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 82ee8b1..475379d 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -175,6 +175,8 @@ syncTick(); syncRel(); syncBannerExpiry(); + syncShellTop(); + syncDrafts(); } // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place. @@ -363,18 +365,20 @@ var user = o.how !== 'live'; if (user) { userBusy += 1; clearNote(); } busyStart(); - fetch(o.target.href, o.init).then(function (r) { + // A link the reader hovered may already be on its way (takePrefetch); a POST never is. + (o.how === 'nav' && !o.form && takePrefetch(o.target.href) || fetch(o.target.href, o.init)).then(function (r) { if (RESTART.indexOf(r.status) >= 0) { return { down: true }; } var final = new URL(r.url || o.target.href); var html = /^\s*text\/html/i.test(r.headers.get('content-type') || ''); if (final.origin !== location.origin || !html) { return { leave: true, url: final, redirected: r.redirected }; } - return r.text().then(function (text) { return { html: text, url: final, status: r.status }; }); + return r.text().then(function (text) { return { html: text, url: final, status: r.status, redirected: r.redirected }; }); }, function () { // No answer at all: the server is down. return { down: true }; }).then(function (res) { + o.result = res; if (mark !== latest) { return; } if (res.down) { if (o.how !== 'live') { outage(o); } return; } if (res.leave) { leave(res, o); return; } @@ -389,11 +393,21 @@ // navigation: it gets a history entry, so the address bar shows where the page now is. var how = o.how === 'live' && res.url.pathname !== o.target.pathname ? 'nav' : o.how; swap(res.html, dest, how, !!o.keep && res.url.pathname === o.target.pathname); + // Other parts of this file follow page changes through this event (list memory, say). + document.dispatchEvent(new CustomEvent('forge:swapped', { detail: { how: how, url: dest } })); }).catch(function () { if (mark !== latest || o.how === 'live') { return; } if (o.post) { o.form.submit(); } else { location.assign(o.dest.href); } }).then(function () { busyEnd(); + if (o.post) { + submitDone(o, mark === latest); + // A POST counts as done only when the server answered with a redirect to a page: the + // post-redirect-get every successful form here ends in. Drafts listen for it. + var r = o.result; + var ok = mark === latest && !!(r && r.html && r.redirected && r.status < 400); + document.dispatchEvent(new CustomEvent('forge:submitted', { detail: { form: o.form, ok: ok } })); + } if (o.form) { pending.delete(o.form); } if (o.how === 'live') { liveBusy = false; } if (user) { userBusy -= 1; } @@ -583,7 +597,7 @@ } // Dropdown menus: the
that float over the page (avatar menu, branch selector, clone - // popover, phone menu). Inline disclosures are not listed here and keep their state. + // popover, phone menu). Inline disclosures are not listed: a click outside leaves them open. var DROPDOWN = 'details.menu, details.ref-select, details.clone, details.nav-toggle'; // Closes every open dropdown except `keep` (pass null to close them all). @@ -593,11 +607,13 @@ }); } - // Each dropdown gets a key that survives a re-render: its id when it has one, else its summary - // text plus a count for repeats (two menus with the same text stay apart, in document order). + // Each
gets a key that survives a re-render: its id when it has one, else its summary + // text plus a count for repeats (two with the same text stay apart, in document order). A live swap + // keeps every one as the reader left it: a menu stays open, and so does an inline editor (a branch + // rule) the server renders closed, or a form it renders open that the reader closed. function dropdownKeys() { var seen = Object.create(null); - return Array.prototype.map.call(document.querySelectorAll(DROPDOWN), function (d) { + return Array.prototype.map.call(document.querySelectorAll('details'), function (d) { if (d.id) { return { key: 'id:' + d.id, el: d }; } var s = d.querySelector('summary'); var text = s ? s.textContent.replace(/\s+/g, ' ').trim() : ''; @@ -606,21 +622,22 @@ }); } - // Before a live swap: the keys of the open dropdowns, and the key of the one holding focus. + // Before a live swap: whether each
is open, and the key of the open one holding focus + // (the innermost, as nested ones come later in document order). function captureDropdowns() { var active = document.activeElement; - var out = { open: [], focus: null }; + var out = { open: Object.create(null), focus: null }; dropdownKeys().forEach(function (item) { - if (!item.el.open) { return; } - out.open.push(item.key); - if (active && item.el.contains(active)) { out.focus = item.key; } + out.open[item.key] = item.el.open; + if (item.el.open && active && item.el.contains(active)) { out.focus = item.key; } }); return out; } function openDropdowns(kept) { dropdownKeys().forEach(function (item) { - if (kept.open.indexOf(item.key) >= 0) { item.el.open = true; } + var was = kept.open[item.key]; + if (was !== undefined && item.el.open !== was) { item.el.open = was; } }); } @@ -658,6 +675,83 @@ } }, false); + // Inline disclosures (a branch rule, a review thread, a delivery, a
in markdown) slide + // open and shut instead of jumping. The details' height is animated from where it is to where it + // goes, clipped only while it moves, so an open one never clips what it holds. Closing keeps it open + // until the slide ends. A click during a slide turns it around. Floating panels (menus, popovers, + // inline confirms) are left to the browser, as is a reader who asks for reduced motion. + var FLOATING = DROPDOWN + ', details.row-menu, details.confirm-inline, details.commit-status, details.reaction-picker'; + var reducedMotion = window.matchMedia ? window.matchMedia('(prefers-reduced-motion: reduce)') : null; + + function slideDetails(d) { + var opening = d.__closing || !d.open; + var from = d.getBoundingClientRect().height; + if (d.__slide) { d.__slide.cancel(); } + d.open = false; + var shut = d.getBoundingClientRect().height; + d.open = true; + var to = opening ? d.getBoundingClientRect().height : shut; + d.__closing = !opening; + d.style.overflow = 'hidden'; + var slide = d.animate({ height: [from + 'px', to + 'px'] }, { duration: 200, easing: 'cubic-bezier(0.2, 0, 0, 1)' }); + d.__slide = slide; + slide.onfinish = function () { + d.__slide = null; + d.style.overflow = ''; + if (d.__closing) { d.__closing = false; d.open = false; } + }; + } + + document.addEventListener('click', function (e) { + if (e.defaultPrevented || !e.target || !e.target.closest) { return; } + var summary = e.target.closest('summary'); + var d = summary && summary.parentElement; + if (!d || d.tagName !== 'DETAILS' || d.querySelector('summary') !== summary) { return; } + if (d.matches(FLOATING) || (reducedMotion && reducedMotion.matches)) { return; } + // A link or control inside the summary does its own thing. + var control = e.target.closest('a, button, input, select, textarea'); + if (control && summary.contains(control)) { return; } + e.preventDefault(); + slideDetails(d); + }, false); + + // Plays a one-shot motion class (see _motion.scss) on the reader's own action. + function play(el, cls) { + el.classList.remove(cls); + void el.offsetWidth; + el.classList.add(cls); + setTimeout(function () { el.classList.remove(cls); }, 400); + } + + // A menu or popover the reader opens drops in. Only a click opens it this way: a live swap that + // keeps one open sets `open` directly and plays nothing. + document.addEventListener('click', function (e) { + var summary = e.target && e.target.closest ? e.target.closest('summary') : null; + var d = summary && summary.parentElement; + if (d && d.tagName === 'DETAILS' && !d.open && d.matches(FLOATING)) { play(d, 'pop'); } + }, false); + + // Dismissing the site banner folds it away, then the dismissal is sent. This runs before the + // soft submit below, which then sends it. + document.addEventListener('submit', function (e) { + var form = e.target; + var banner = form && form.closest ? form.closest('.site-banner') : null; + if (!banner || form.__folded || (reducedMotion && reducedMotion.matches)) { return; } + e.preventDefault(); + e.stopPropagation(); + banner.style.overflow = 'hidden'; + banner.animate({ + height: [banner.offsetHeight + 'px', '0px'], + paddingTop: [getComputedStyle(banner).paddingTop, '0px'], + paddingBottom: [getComputedStyle(banner).paddingBottom, '0px'], + opacity: [1, 0] + }, { duration: 180, easing: 'cubic-bezier(0.2, 0, 0, 1)', fill: 'forwards' }).onfinish = function () { + form.__folded = true; + form.requestSubmit(); + syncShellTop(); + }; + }, true); + // Branch rule form: a suggested check context is added to the required checks field. document.addEventListener('click', function (e) { var chip = e.target && e.target.closest ? e.target.closest('[data-check-add]') : null; @@ -684,6 +778,13 @@ // A fragment on the page already shown: the browser scrolls by itself. if (url.pathname + url.search === shown && url.hash) { return; } e.preventDefault(); + // A link that only changes what part of this page shows (a calendar day) swaps in place: the + // reader's scroll stays, and its anchor, meant for a full page load, is not followed. + if (a.hasAttribute('data-keep-scroll') && url.pathname === location.pathname) { + var here = withoutHash(url); + load({ target: here, dest: here, init: GET_INIT, how: 'query', keep: true, post: false, form: null }); + return; + } saveScroll(); load({ target: withoutHash(url), dest: url, init: GET_INIT, how: 'nav', keep: false, post: false, form: null }); }, true); @@ -716,6 +817,7 @@ } var multipart = (form.enctype || '').toLowerCase().indexOf('multipart') === 0; + submitStart(form, submitter); load({ target: withoutHash(url), dest: url, @@ -727,7 +829,8 @@ how: 'post', keep: true, post: true, - form: form + form: form, + submitter: submitter }); }, false); @@ -782,6 +885,7 @@ var max = parseFloat(field.max); if (!isNaN(min)) { next = Math.max(min, next); } if (!isNaN(max)) { next = Math.min(max, next); } + if (String(next) !== field.value) { play(field, 'tick'); } field.value = String(next); field.dispatchEvent(new Event('input', { bubbles: true })); }); @@ -1833,23 +1937,42 @@ // is removed here, so an open page does not keep one that is gone. One timer is armed for the // banner on the page; a swap re-arms it. setTimeout takes a 32-bit delay, so a longer wait is armed // again when this one fires. - var bannerTimer = null; + var expiryTimer = null; function syncBannerExpiry() { - if (bannerTimer) { clearTimeout(bannerTimer); } - bannerTimer = null; + if (expiryTimer) { clearTimeout(expiryTimer); } + expiryTimer = null; var banner = document.querySelector('.site-banner[data-expires]'); if (!banner) { return; } var wait = (parseInt(banner.getAttribute('data-expires'), 10) || 0) * 1000 - Date.now(); - if (wait <= 0) { banner.remove(); return; } - bannerTimer = setTimeout(syncBannerExpiry, Math.min(wait, 2147483647)); + if (wait <= 0) { banner.remove(); syncShellTop(); return; } + expiryTimer = setTimeout(syncBannerExpiry, Math.min(wait, 2147483647)); + } + + // A repo's tabs are a fixed column (see _shell.scss). They start where the page body starts, so + // whatever sits above it (the site banner) shows, and they rise with it to the top bar on scroll. + var shellFrame = 0; + + function syncShellTop() { + shellFrame = 0; + var shell = document.querySelector('.shell'); + if (!shell) { return; } + document.documentElement.style.setProperty('--shell-top', Math.round(shell.getBoundingClientRect().top) + 'px'); } + function queueShellTop() { + if (!shellFrame) { shellFrame = requestAnimationFrame(syncShellTop); } + } + + window.addEventListener('scroll', queueShellTop, { passive: true }); + window.addEventListener('resize', queueShellTop); + function syncRel() { var now = document.documentElement.getAttribute('data-rel-now'); relSkew = now === null ? 0 : (parseInt(now, 10) || 0) * 1000 - Date.now(); if (relTimer) { clearTimeout(relTimer); relTimer = null; } relUpdate(); + relTitles(); } function fmtDuration(secs, root) { @@ -1921,6 +2044,8 @@ syncTick(); syncRel(); syncBannerExpiry(); + syncShellTop(); + syncDrafts(); window.__forgeQuery = function (href) { var url = pageUrl(href); @@ -1928,6 +2053,662 @@ load({ target: withoutHash(url), dest: url, init: GET_INIT, how: 'query', keep: true, post: false, form: null }); }; placeRun(); + + // Hover prefetch: a link the pointer rests on for a moment starts its page request early, so the + // click that often follows finds the answer already on its way. Only what the click handler would + // soft-navigate is fetched, and never a path that writes when viewed or serves a file. + var PREFETCH_DELAY = 80; // ms the pointer must rest on a link before its request starts + var PREFETCH_TTL = 10000; // ms a finished or running prefetch is still used by a click + var PREFETCH_MAX = 4; // stored prefetches; the oldest is dropped first + var NO_PREFETCH = /\/-\/|\/(live|events|stream|open|download)$|\/(archive|raw|actions|attachments|artifacts)\/|\.zip$|\.tar\.gz$|\/releases\/download\/|^\/(logout|notifications)(\/|$)/; + var prefetches = []; // { key, promise, at }: the request for a URL without its hash + var prefetchTimer = null; + var prefetchLink = null; + + // Touch screens have no hover, and a saver asks for less data: neither gets prefetches. + function prefetchAllowed() { + var conn = navigator.connection; + if (conn && conn.saveData) { return false; } + return !(window.matchMedia && window.matchMedia('(hover: none)').matches); + } + + // The URL to prefetch for link `a`, or null. The same rules as the click handler apply, so a + // prefetch never fetches a page a click would not show. + function prefetchUrl(a) { + if (a.target || a.hasAttribute('download') || a.hasAttribute('data-hard') || a.hasAttribute('data-no-prefetch')) { return null; } + var href = a.getAttribute('href') || ''; + if (href.charAt(0) !== '/' || href.charAt(1) === '/') { return null; } + var url = pageUrl(href); + if (!url || NO_PREFETCH.test(url.pathname)) { return null; } + if (url.pathname + url.search === shown) { return null; } + return withoutHash(url); + } + + function startPrefetch(url) { + var key = url.href; + // A page fetched while a form is on its way may show the state before the write. + if (userBusy > 0) { return; } + for (var i = prefetches.length - 1; i >= 0; i--) { + if (prefetches[i].key === key) { prefetches.splice(i, 1); } + } + // A prefetch that fails is asked again when the click takes it, so a blip while hovering never + // reads as an outage. Nothing surfaces from one nobody clicks. + var promise = fetch(key, GET_INIT).catch(function () { return fetch(key, GET_INIT); }); + promise.catch(function () {}); + prefetches.push({ key: key, promise: promise, at: Date.now() }); + while (prefetches.length > PREFETCH_MAX) { prefetches.shift(); } + } + + // Returns a pending fetch Promise for `href` started on hover, or null. Taken once: a + // Response body can be read only once, so the entry goes whether or not it is still fresh. + function takePrefetch(href) { + for (var i = 0; i < prefetches.length; i++) { + if (prefetches[i].key !== href) { continue; } + var hit = prefetches.splice(i, 1)[0]; + return Date.now() - hit.at < PREFETCH_TTL ? hit.promise : null; + } + return null; + } + + document.addEventListener('mouseover', function (e) { + var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; + if (!a || a === prefetchLink) { return; } + clearTimeout(prefetchTimer); + prefetchTimer = null; + prefetchLink = a; + var url = prefetchUrl(a); + if (!url || !prefetchAllowed()) { return; } + prefetchTimer = setTimeout(function () { + prefetchTimer = null; + startPrefetch(url); + }, PREFETCH_DELAY); + }, true); + + // Leaving the link (not moving between its children) cancels a prefetch that has not started yet. + document.addEventListener('mouseout', function (e) { + var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; + if (!a || a !== prefetchLink || (e.relatedTarget && a.contains(e.relatedTarget))) { return; } + clearTimeout(prefetchTimer); + prefetchTimer = null; + prefetchLink = null; + }, true); + + // A write can change every page, so no prefetch made before a form goes out is kept. + document.addEventListener('submit', function () { + prefetches.length = 0; + clearTimeout(prefetchTimer); + prefetchTimer = null; + prefetchLink = null; + }, true); + + // Submit feedback + // The button shows busy only when the answer is slow (after BUSY_MS), so a quick reply never flickers. + // The tick comes only once the server redirected to a page without an error: nothing looks saved first. + var BUSY_MS = 150; + var TICK_MS = 2200; + var SUBMIT_SEL = 'button[type=submit], button:not([type]), input[type=submit]'; + + function buttonLabel(b) { + return ((b.tagName === 'INPUT' ? b.value : b.textContent) || '').replace(/\s+/g, ' ').trim(); + } + + // The page's forms with this action and method, in document order. + function sameForms(action, method) { + return Array.prototype.filter.call(document.querySelectorAll('form'), function (f) { + return f.getAttribute('action') === action && (f.getAttribute('method') || 'get').toLowerCase() === method; + }); + } + + // Which form and button a POST came from. Taken before the swap: the old form is gone by the answer. + function submitKey(form, btn) { + var action = form.getAttribute('action'); + var method = (form.getAttribute('method') || 'get').toLowerCase(); + return { + action: action, + method: method, + index: sameForms(action, method).indexOf(form), + name: btn ? btn.name : '', + value: btn ? btn.value : '', + text: btn ? buttonLabel(btn) : '', + dirty: form.hasAttribute('data-dirty-form'), + banner: !!(form.closest && form.closest('.site-banner')) + }; + } + + function submitStart(form, submitter) { + var btn = submitter || form.querySelector(SUBMIT_SEL); + var busy = { timer: null, btn: btn, key: submitKey(form, btn) }; + busy.timer = setTimeout(function () { + if (!btn) { return; } + btn.classList.add('is-busy'); + btn.setAttribute('aria-busy', 'true'); + }, BUSY_MS); + form.__busy = busy; + } + + // The button a finished POST came from, in the page now shown: the same-index form with the same + // action and method, then its button by name and value, then by text, then its first submit button. + function doneButton(key) { + var form = sameForms(key.action, key.method)[key.index]; + if (!form) { return null; } + var buttons = form.querySelectorAll('button, input[type=submit]'); + var i; + if (key.name) { + for (i = 0; i < buttons.length; i++) { + if (buttons[i].name === key.name && buttons[i].value === key.value) { return buttons[i]; } + } + } + if (key.text) { + for (i = 0; i < buttons.length; i++) { + if (buttonLabel(buttons[i]) === key.text) { return buttons[i]; } + } + } + return form.querySelector(SUBMIT_SEL); + } + + function showTick(btn, word) { + var svgNs = 'http://www.w3.org/2000/svg'; + var tick = document.createElement('span'); + tick.className = 'done-tick'; + tick.setAttribute('role', 'status'); + var svg = document.createElementNS(svgNs, 'svg'); + svg.setAttribute('class', 'ico'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('aria-hidden', 'true'); + var path = document.createElementNS(svgNs, 'path'); + path.setAttribute('d', 'M5 12.5l4.5 4.5L19 7.5'); + svg.appendChild(path); + tick.appendChild(svg); + tick.appendChild(document.createTextNode(word)); + btn.insertAdjacentElement('afterend', tick); + setTimeout(function () { tick.remove(); }, TICK_MS); + } + + function submitDone(o, current) { + var form = o.form; + var busy = form && form.__busy; + if (!busy) { return; } + form.__busy = null; + clearTimeout(busy.timer); + if (busy.btn && document.documentElement.contains(busy.btn)) { + busy.btn.classList.remove('is-busy'); + busy.btn.removeAttribute('aria-busy'); + } + var r = o.result; + if (!current || !r || !r.html || !r.redirected || !(r.status < 400)) { return; } + // A refusal sent back on the query (merge_error, branch_error, error...) is not a success. + if (/[?&]\w*error=/.test(r.url.search)) { return; } + var key = busy.key; + if (key.banner || document.querySelector('main .alert, main [role="alert"]')) { return; } + var word = document.body.getAttribute(key.dirty ? 'data-done-saved' : 'data-done-ok'); + var target = doneButton(key); + if (target && word) { showTick(target, word); } + } + + // Comment drafts. Free text in a POST form (comments, bodies, wiki pages, the profile about) is kept + // in localStorage as the reader types, so a closed tab, a crash or a navigation keeps it. An empty + // field with a draft gets the text back, with a note to discard it. A successful post clears them. + function draftConfig() { + // A function, not a var: syncDrafts runs at startup, above this block, and needs these values. + return { + prefix: 'forge-draft:', + maxAge: 7 * 24 * 60 * 60 * 1000, + max: 50, + fields: 'form[method="post"] textarea[name="body"], form[method="post"] textarea[name="content"], form[method="post"] textarea[name="about"]' + }; + } + var draftTimers = new WeakMap(); // a field's pending save: typing again restarts its 400 ms wait + var draftsOnSubmit = new WeakMap(); // a form being posted: the draft keys it held when it was sent + + function draftText(name) { + return (document.body && document.body.getAttribute('data-draft-' + name)) || ''; + } + + // Each field's key: its page, the action it posts to, its name, and its occurrence among the same. + function draftFields() { + var cfg = draftConfig(); + var seen = Object.create(null); + return Array.prototype.map.call(document.querySelectorAll(cfg.fields), function (el) { + var base = cfg.prefix + location.pathname + '|' + ((el.form && el.form.getAttribute('action')) || '') + '|' + el.name; + var n = seen[base] || 0; + seen[base] = n + 1; + return { el: el, k: base + '#' + n }; + }); + } + + function draftKey(el) { + var items = draftFields(); + for (var i = 0; i < items.length; i++) { + if (items[i].el === el) { return items[i].k; } + } + return null; + } + + function readDraft(key) { + try { + var rec = JSON.parse(localStorage.getItem(key)); + return rec && typeof rec.v === 'string' && typeof rec.at === 'number' ? rec : null; + } catch (err) { return null; } + } + + // An empty text removes the draft. Storage can refuse (private mode, a full quota): the draft is then + // not kept, and the page works as before. + function setDraft(key, text) { + try { + if (text === '') { localStorage.removeItem(key); } + else { localStorage.setItem(key, JSON.stringify({ v: text, at: Date.now() })); } + } catch (err) { } + } + + // A draft older than the limit is no draft: it is removed as it is found. + function freshDraft(key) { + var rec = readDraft(key); + if (!rec) { return null; } + if (Date.now() - rec.at > draftConfig().maxAge) { setDraft(key, ''); return null; } + return rec; + } + + // At startup: drop drafts older than the limit and, past the cap, the oldest ones. + function pruneDrafts() { + var cfg = draftConfig(); + try { + var live = []; + for (var i = localStorage.length - 1; i >= 0; i--) { + var key = localStorage.key(i); + if (!key || key.indexOf(cfg.prefix) !== 0) { continue; } + var rec = freshDraft(key); + if (rec) { live.push({ k: key, at: rec.at }); } + } + live.sort(function (a, b) { return b.at - a.at; }); + live.slice(cfg.max).forEach(function (d) { setDraft(d.k, ''); }); + } catch (err) { } + } + + // Puts each stored draft into the empty field it belongs to, once per field, with a note under it. + function restoreDrafts() { + draftFields().forEach(function (item) { + var el = item.el; + if (el.hasAttribute('data-draft-done') || el.value !== '') { return; } + var rec = freshDraft(item.k); + if (!rec) { return; } + el.setAttribute('data-draft-done', ''); + el.value = rec.v; + // The input event lets the dirty-form logic see the field as changed. + el.dispatchEvent(new Event('input', { bubbles: true })); + var note = document.createElement('p'); + note.className = 'draft-note'; + note.appendChild(document.createTextNode(draftText('restored') + ' · ')); + var discard = document.createElement('button'); + discard.type = 'button'; + discard.className = 'link-button'; + discard.setAttribute('data-draft-discard', ''); + discard.textContent = draftText('discard'); + note.appendChild(discard); + el.insertAdjacentElement('afterend', note); + }); + } + + // A swap adopts the new body before its history entry is pushed, so the restore waits a tick and + // the keys then carry the page's own path. + function syncDrafts() { setTimeout(restoreDrafts, 0); } + + pruneDrafts(); + + // A save waits 400 ms after the last keystroke. The key is taken at the keystroke, so a save still + // lands under the page it was typed on when the reader leaves within that wait. + document.addEventListener('input', function (e) { + var el = e.target; + if (!el || !el.matches || !el.matches(draftConfig().fields)) { return; } + var key = draftKey(el); + if (!key) { return; } + clearTimeout(draftTimers.get(el)); + draftTimers.set(el, setTimeout(function () { setDraft(key, el.value); }, 400)); + }); + + // The keys a form holds are taken as it is sent: after a swap the old form is detached. + document.addEventListener('submit', function (e) { + var form = e.target; + if (!form || !form.matches || !form.matches('form[method="post"]')) { return; } + var items = draftFields().filter(function (item) { return form.contains(item.el); }); + // A save still waiting would land after a confirmed post cleared the draft: it is made now. + items.forEach(function (item) { + clearTimeout(draftTimers.get(item.el)); + setDraft(item.k, item.el.value); + }); + draftsOnSubmit.set(form, items.map(function (item) { return item.k; })); + }, true); + + // A post the server confirmed clears the drafts it held. A failed one keeps them. + document.addEventListener('forge:submitted', function (e) { + var form = e.detail ? e.detail.form : null; + var keys = form ? draftsOnSubmit.get(form) : null; + if (!keys) { return; } + draftsOnSubmit.delete(form); + if (e.detail.ok) { keys.forEach(function (k) { setDraft(k, ''); }); } + }); + + // Discard: the field is emptied, its draft removed, and the note goes. + document.addEventListener('click', function (e) { + var btn = e.target && e.target.closest ? e.target.closest('button[data-draft-discard]') : null; + if (!btn) { return; } + var note = btn.parentNode; + var field = note.previousElementSibling; + if (field && field.matches(draftConfig().fields)) { + clearTimeout(draftTimers.get(field)); + var key = draftKey(field); + if (key) { setDraft(key, ''); } + field.value = ''; + field.dispatchEvent(new Event('input', { bubbles: true })); + } + note.remove(); + }); + + // List memory: a list page keeps its filters (per path, in sessionStorage) and its scroll position + // when the reader leaves and comes back. Paging parameters are not filters. + var LIST_PAGE = /^\/[^\/]+\/[^\/]+\/(issues|pulls|ci|commits\/.*|releases|tags|branches|discussions|labels|milestones|merge-queue|search)$|^\/(explore|notifications|review-requests|admin\/users|admin\/runners|admin\/audit|settings\/security\/log|org\/[^\/]+\/members)$/; + var LIST_PAGING = ['page', 'before', 'after', 'cursor']; + var LIST_Y_TTL = 30 * 60 * 1000; // ms a remembered scroll position is still used + + function listStore(key, value) { + try { + if (value === null) { sessionStorage.removeItem(key); } else { sessionStorage.setItem(key, value); } + } catch (err) { } + } + + function listLoad(key) { + try { return sessionStorage.getItem(key); } catch (err) { return null; } + } + + // The filters of a list page's search, with a leading `?`, or '' when there are none. + function listFilters(search) { + var params = new URLSearchParams(search); + LIST_PAGING.forEach(function (key) { params.delete(key); }); + var text = params.toString(); + return text ? '?' + text : ''; + } + + // An empty filter set forgets the page: a cleared list comes back clear. + function rememberList(path, search) { + if (!LIST_PAGE.test(path)) { return; } + var filters = listFilters(search); + listStore('forge-list:' + path, filters || null); + } + + rememberList(location.pathname, location.search); + + document.addEventListener('forge:swapped', function (e) { + var url = e.detail.url; + rememberList(url.pathname, url.search); + // Only a navigation lands at the top of a list the reader had scrolled; back and forward have their own place. + if (e.detail.how !== 'nav' || !LIST_PAGE.test(url.pathname) || url.hash) { return; } + var saved = null; + try { saved = JSON.parse(listLoad('forge-list-y:' + url.pathname + url.search) || 'null'); } catch (err) { saved = null; } + if (!saved || typeof saved.y !== 'number' || Date.now() - saved.t > LIST_Y_TTL) { return; } + // Only when the page is tall enough to reach the place; a shorter page would scroll to its end. + if (document.documentElement.scrollHeight - window.innerHeight < saved.y) { return; } + window.scrollTo(0, saved.y); + }); + + // Runs before the navigation handler below: a link to a list's bare path goes to its remembered + // filters, unless the reader is on that list already (then the bare link clears them). + window.addEventListener('click', function (e) { + if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; } + var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; + if (!a || a.target || a.hasAttribute('download') || a.hasAttribute('data-hard')) { return; } + var href = a.getAttribute('href') || ''; + if (href.charAt(0) !== '/' || href.charAt(1) === '/') { return; } + var url = pageUrl(href); + if (!url) { return; } + // Leaving a list by a link: its scroll position is kept for when the reader comes back. + if (LIST_PAGE.test(location.pathname) && !(url.pathname + url.search === shown && url.hash)) { + listStore('forge-list-y:' + shown, JSON.stringify({ y: window.scrollY, t: Date.now() })); + } + if (href === url.pathname && url.pathname !== location.pathname && LIST_PAGE.test(href)) { + var kept = listLoad('forge-list:' + href); + if (kept) { a.setAttribute('href', href + kept); } + } + }, true); + + // Command palette + // Ctrl+K (Cmd+K on a Mac, or the topbar button) opens a dialog that jumps to the viewer's repos, + // orgs and pages. The server list is fetched on the first open and kept for a minute; on a repo + // page that repo's tabs are read from the page instead, so they never wait for the server. + var PALETTE_TTL = 60000; // ms a fetched list stays fresh + var PALETTE_MAX = 50; // options shown at once + var PALETTE_WORD = /[\s\/._\-·]/; // a character that starts a word, for the word-start match + var pal = { dlg: null, input: null, list: null, note: null, hits: [], sel: 0, str: null, + data: null, request: null, failed: false }; + + // The words the palette shows, read from the topbar button: the server writes them in the viewer's + // language, so this script carries no text of its own. + function paletteStrings(opener) { + function word(name) { return opener.getAttribute('data-' + name) || ''; } + return { + label: opener.getAttribute('aria-label') || '', + placeholder: word('placeholder'), + hint: word('hint'), + empty: word('empty'), + loading: word('loading'), + failed: word('failed'), + heads: { repo: word('repos'), org: word('orgs'), page: word('pages') } + }; + } + + // How well the lowercased query matches a label: 3 for a prefix, 2 for a match at a word start, + // 1 for the letters in order anywhere, 0 for no match. A shorter label wins within a tier, and the + // bonus stays under 0.5 so it never lifts a label into the tier above. An empty query matches all. + function paletteScore(q, label) { + if (!q) { return 1; } + var s = label.toLowerCase(); + var bonus = 1 / (s.length + 2); + var at = s.indexOf(q); + while (at >= 0) { + if (at === 0) { return 3 + bonus; } + if (PALETTE_WORD.test(s.charAt(at - 1))) { return 2 + bonus; } + at = s.indexOf(q, at + 1); + } + var qi = 0; + for (var i = 0; i < s.length && qi < q.length; i++) { + if (s.charAt(i) === q.charAt(qi)) { qi++; } + } + return qi === q.length ? 1 + bonus : 0; + } + + // The destinations to filter: the current repo's tabs first, then the fetched list. + function paletteItems() { + var items = []; + var tabs = document.querySelectorAll('.repo-tabs a'); + if (tabs.length) { + // The first tab is the repo's Code link, so its path starts with owner/name. + var parts = tabs[0].pathname.split('/'); + var repo = parts.length >= 3 ? parts[1] + '/' + parts[2] : ''; + if (repo) { + Array.prototype.forEach.call(tabs, function (a) { + // Counts sit in a span at the end of the tab ("Issues 3"); the name is the rest. + var name = a.textContent.replace(/\s+/g, ' ').trim().replace(/ \d+$/, ''); + items.push({ label: repo + ' · ' + name, href: a.getAttribute('href') || '', kind: 'repo' }); + }); + } + } + return pal.data ? items.concat(pal.data.items) : items; + } + + function paletteSelect(index) { + var opts = pal.list.querySelectorAll('li[role="option"]'); + if (!opts.length) { pal.input.removeAttribute('aria-activedescendant'); return; } + pal.sel = Math.max(0, Math.min(opts.length - 1, index)); + for (var i = 0; i < opts.length; i++) { + opts[i].setAttribute('aria-selected', i === pal.sel ? 'true' : 'false'); + } + pal.input.setAttribute('aria-activedescendant', opts[pal.sel].id); + opts[pal.sel].scrollIntoView({ block: 'nearest' }); + } + + // Filters and draws the list. Groups keep the order of their best match, so a page named exactly + // like the query leads; with no query, the order is tabs, repos, orgs, then pages. + function renderPalette() { + var q = pal.input.value.trim().toLowerCase(); + var scored = []; + paletteItems().forEach(function (item, idx) { + if (!Object.prototype.hasOwnProperty.call(pal.str.heads, item.kind)) { return; } + var s = paletteScore(q, item.label); + if (s > 0) { scored.push({ item: item, score: s, idx: idx }); } + }); + scored.sort(function (a, b) { return b.score - a.score || a.idx - b.idx; }); + scored = scored.slice(0, PALETTE_MAX); + var kinds = [], groups = {}; + scored.forEach(function (h) { + var kind = h.item.kind; + if (!groups[kind]) { groups[kind] = []; kinds.push(kind); } + groups[kind].push(h.item); + }); + pal.list.textContent = ''; + pal.hits = []; + kinds.forEach(function (kind) { + var head = document.createElement('li'); + head.className = 'palette-head'; + head.setAttribute('role', 'presentation'); + head.textContent = pal.str.heads[kind]; + pal.list.appendChild(head); + groups[kind].forEach(function (item) { + var n = pal.hits.length; + pal.hits.push(item); + var li = document.createElement('li'); + li.id = 'palette-opt-' + n; + li.setAttribute('role', 'option'); + li.setAttribute('aria-selected', 'false'); + li.setAttribute('data-n', String(n)); + li.textContent = item.label; + pal.list.appendChild(li); + }); + }); + if (pal.hits.length) { + pal.note.textContent = pal.str.hint; + paletteSelect(0); + } else { + pal.note.textContent = pal.failed ? pal.str.failed : (pal.data ? pal.str.empty : pal.str.loading); + pal.input.removeAttribute('aria-activedescendant'); + } + } + + // Fetches the server list unless a fresh one is held or a request is already on the wire. + function paletteFetch() { + if (pal.request || (pal.data && Date.now() - pal.data.at < PALETTE_TTL)) { return; } + pal.failed = false; + pal.request = fetch('/-/palette', { headers: { accept: 'application/json' }, credentials: 'same-origin' }).then(function (r) { + if (!r.ok) { throw new Error('status ' + r.status); } + return r.json(); + }).then(function (json) { + pal.data = { at: Date.now(), items: Array.isArray(json.items) ? json.items : [] }; + pal.request = null; + if (pal.dlg.open) { renderPalette(); } + }).catch(function () { + pal.request = null; + pal.failed = true; + if (pal.dlg.open) { renderPalette(); } + }); + } + + // Leaves the palette for a destination. The dialog closes first, then the page loads the same way + // a sidebar link does; a link the browser must handle itself goes through location. + function paletteGo(href) { + if (!href) { return; } + pal.dlg.close(); + var url = pageUrl(href); + if (!url) { location.assign(href); return; } + saveScroll(); + load({ target: withoutHash(url), dest: url, init: GET_INIT, how: 'nav', keep: false, post: false, form: null }); + } + + // Built once. Its markup is static; every word in it arrives through the button's data attributes. + function buildPalette() { + var dlg = document.createElement('dialog'); + dlg.className = 'palette'; + dlg.innerHTML = '
' + + '' + + '
    ' + + '

    '; + pal.dlg = dlg; + pal.input = dlg.querySelector('.palette-input'); + pal.list = dlg.querySelector('.palette-list'); + pal.note = dlg.querySelector('.palette-note'); + + pal.input.addEventListener('input', renderPalette); + pal.input.addEventListener('keydown', function (e) { + if (e.isComposing) { return; } + if (e.key === 'ArrowDown') { e.preventDefault(); paletteSelect(pal.sel + 1); } + else if (e.key === 'ArrowUp') { e.preventDefault(); paletteSelect(pal.sel - 1); } + else if (e.key === 'Enter') { e.preventDefault(); if (pal.hits[pal.sel]) { paletteGo(pal.hits[pal.sel].href); } } + }); + // Hover selects; the check keeps a row that is already selected from being touched again. + pal.list.addEventListener('mousemove', function (e) { + var li = e.target && e.target.closest ? e.target.closest('li[role="option"]') : null; + if (li && Number(li.getAttribute('data-n')) !== pal.sel) { paletteSelect(Number(li.getAttribute('data-n'))); } + }); + pal.list.addEventListener('click', function (e) { + var li = e.target && e.target.closest ? e.target.closest('li[role="option"]') : null; + if (li) { paletteGo(pal.hits[Number(li.getAttribute('data-n'))].href); } + }); + // The backdrop is the dialog element itself; the box fills the rest. + dlg.addEventListener('click', function (e) { if (e.target === dlg) { dlg.close(); } }); + } + + function openPalette() { + var opener = document.querySelector('[data-palette-open]'); + if (!opener) { return; } + if (!pal.dlg) { buildPalette(); } + var dlg = pal.dlg; + if (dlg.open) { return; } + // A page swap removes body children, the dialog among them, so it is put back on each open. + if (dlg.parentNode !== document.body) { document.body.appendChild(dlg); } + pal.str = paletteStrings(opener); + dlg.setAttribute('aria-label', pal.str.label); + pal.input.placeholder = pal.str.placeholder; + pal.input.setAttribute('aria-label', pal.str.placeholder); + if (typeof dlg.showModal !== 'function') { return; } + dlg.showModal(); + pal.input.value = ''; + renderPalette(); + pal.input.focus(); + paletteFetch(); + } + + // Ctrl+K and Cmd+K toggle the palette even while a text field has focus, since that is when a + // jump is most likely. Other modifiers keep their own meaning. + document.addEventListener('keydown', function (e) { + if (!(e.ctrlKey || e.metaKey) || e.altKey || e.shiftKey || (e.key !== 'k' && e.key !== 'K')) { return; } + if (!document.querySelector('[data-palette-open]')) { return; } + e.preventDefault(); + if (pal.dlg && pal.dlg.open) { pal.dlg.close(); } else { openPalette(); } + }); + + document.addEventListener('click', function (e) { + var t = e.target; + if (!t || !t.closest) { return; } + if (t.closest('[data-palette-open]')) { e.preventDefault(); openPalette(); } + }); + + // Every relative time shows its exact moment on hover, in the reader's own time zone and language, + // so one format holds across the site whatever title the server wrote. + var relFormat = null, relLang = null; + + function relTitles() { + var lang = root.getAttribute('lang') || ''; + if (!relFormat || relLang !== lang) { + try { + relFormat = new Intl.DateTimeFormat(lang || undefined, { dateStyle: 'medium', timeStyle: 'short' }); + relLang = lang; + } catch (err) { return; } + } + Array.prototype.forEach.call(document.querySelectorAll('time[data-rel][datetime]'), function (el) { + var at = Date.parse(el.getAttribute('datetime') || ''); + if (isNaN(at)) { return; } + var exact = relFormat.format(at); + if (el.getAttribute('title') !== exact) { el.setAttribute('title', exact); } + }); + } })(); // Code browsing: line selection on blobs and blame, the permalink copy and `y` shortcut, the file diff --git a/crates/forge-web/src/i18n/admin.rs b/crates/forge-web/src/i18n/admin.rs index 96b2180..92e3e93 100644 --- a/crates/forge-web/src/i18n/admin.rs +++ b/crates/forge-web/src/i18n/admin.rs @@ -107,6 +107,7 @@ pub enum K { MailTransportInUse, MailQueueIntro, MailNothingMatches, + MailQueueEmpty, MailPort, MailSettingsSaved, MovedToGhost, @@ -116,6 +117,10 @@ pub enum K { NoRunnersYet, NoRunnerWithId, NoRunsYet, + BackupsEmptyHint, + ReplicationConfigHint, + ReposEmptyHint, + RunnersEmptyHint, Older, OwnLogIntro, PasswordStoredHint, @@ -419,6 +424,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { } (MailNothingMatches, En) => "No message is in this state.", (MailNothingMatches, Tr) => "Bu durumda ileti yok.", + (MailQueueEmpty, En) => "Nothing waiting to be sent.", + (MailQueueEmpty, Tr) => "Gönderilmeyi bekleyen ileti yok.", (MailHost, En) => "Host", (MailHost, Tr) => "Sunucu", (MailIntro, En) => { @@ -445,6 +452,22 @@ pub fn t(lang: Lang, key: K) -> &'static str { (NoRunnerWithId, Tr) => "Bu kimlikte bir çalıştırıcı yok. Hiçbir şey değiştirilmedi.", (NoRunsYet, En) => "No runs yet.", (NoRunsYet, Tr) => "Henüz çalıştırma yok.", + (BackupsEmptyHint, En) => "Scheduled and manual runs are listed here.", + (BackupsEmptyHint, Tr) => "Zamanlanmış ve elle başlatılan çalıştırmalar burada listelenir.", + (ReplicationConfigHint, En) => { + "Replication is set under [replication] in the config file. See docs/backup.md." + } + (ReplicationConfigHint, Tr) => { + "Replikasyon, yapılandırma dosyasındaki [replication] bölümünde ayarlanır. Bkz. docs/backup.md." + } + (ReposEmptyHint, En) => "Each repo is copied to the standby and listed here.", + (ReposEmptyHint, Tr) => "Her depo yedek sunucuya kopyalanır ve burada listelenir.", + (RunnersEmptyHint, En) => { + "Create a registration token below, then run this command on the runner machine." + } + (RunnersEmptyHint, Tr) => { + "Aşağıdan bir kayıt belirteci oluşturun, ardından bu komutu çalıştırıcı makinesinde çalıştırın." + } (Older, En) => "Older", (Older, Tr) => "Daha eski", (OwnLogIntro, En) => { @@ -896,6 +919,11 @@ mod tests { K::NoRunnersYet, K::NoRunnerWithId, K::NoRunsYet, + K::BackupsEmptyHint, + K::ReplicationConfigHint, + K::ReposEmptyHint, + K::RunnersEmptyHint, + K::MailQueueEmpty, K::Older, K::OwnLogIntro, K::PasswordStoredHint, diff --git a/crates/forge-web/src/i18n/browse.rs b/crates/forge-web/src/i18n/browse.rs index 9f7569b..6710081 100644 --- a/crates/forge-web/src/i18n/browse.rs +++ b/crates/forge-web/src/i18n/browse.rs @@ -53,6 +53,14 @@ strings! { FinderFailed => "The file list could not be loaded.", "Dosya listesi yüklenemedi."; FinderTruncated => "Very large tree: only the first files are searchable.", "Çok büyük ağaç: yalnızca ilk dosyalar aranabilir."; + PaletteOpen => "Open command palette", "Komut paletini aç"; + PalettePlaceholder => "Jump to…", "Şuraya git…"; + PaletteRepos => "Repositories", "Depolar"; + PalettePages => "Pages", "Sayfalar"; + PaletteNoMatches => "No matches", "Eşleşme yok"; + PaletteLoading => "Loading…", "Yükleniyor…"; + PaletteFailed => "The list could not be loaded.", "Liste yüklenemedi."; + BranchAuthorHeader => "Author", "Yazar"; BranchAheadBehindHeader => "Ahead / behind", "Önde / geride"; BranchActionsHeader => "Actions", "İşlemler"; diff --git a/crates/forge-web/src/i18n/code.rs b/crates/forge-web/src/i18n/code.rs index 141aad9..6c6711d 100644 --- a/crates/forge-web/src/i18n/code.rs +++ b/crates/forge-web/src/i18n/code.rs @@ -521,18 +521,18 @@ pub fn forks_count(lang: Lang, forks: u64) -> String { } /// The mirror status after a successful sync. -pub fn mirror_synced(lang: Lang, at: &str) -> String { +pub fn mirror_synced(lang: Lang) -> (&'static str, &'static str) { match lang { - Lang::En => format!("last synced {at}"), - Lang::Tr => format!("son eşitleme: {at}"), + Lang::En => ("last synced ", ""), + Lang::Tr => ("son eşitleme: ", ""), } } /// The mirror status after a failed sync. -pub fn mirror_sync_failed(lang: Lang, at: &str) -> String { +pub fn mirror_sync_failed(lang: Lang) -> (&'static str, &'static str) { match lang { - Lang::En => format!("last sync {at} failed"), - Lang::Tr => format!("son eşitleme {at} başarısız oldu"), + Lang::En => ("last sync ", " failed"), + Lang::Tr => ("son eşitleme ", " başarısız oldu"), } } diff --git a/crates/forge-web/src/i18n/community.rs b/crates/forge-web/src/i18n/community.rs index 14135a3..207cc14 100644 --- a/crates/forge-web/src/i18n/community.rs +++ b/crates/forge-web/src/i18n/community.rs @@ -406,22 +406,27 @@ pub fn page_too_large(lang: Lang, max: usize) -> String { } } -/// `2 files · updated 3 days ago` / `2 dosya · 3 gün önce güncellendi`. -/// `updated 3 days ago` / `3 gün önce güncellendi`. -pub fn updated_on(lang: Lang, updated: &str) -> String { +/// Words before a relative update time: `updated ` in English. Turkish puts the time first. +pub fn updated_before(lang: Lang) -> &'static str { match lang { - Lang::En => format!("updated {updated}"), - Lang::Tr => format!("{updated} güncellendi"), + Lang::En => "updated ", + Lang::Tr => "", } } -pub fn files_updated(lang: Lang, count: u64, updated: &str) -> String { +/// Words after a relative update time: ` güncellendi` in Turkish. English puts the time last. +pub fn updated_after(lang: Lang) -> &'static str { match lang { - Lang::En => format!( - "{count} {} · updated {updated}", - if count == 1 { "file" } else { "files" } - ), - Lang::Tr => format!("{count} dosya · {updated} güncellendi"), + Lang::En => "", + Lang::Tr => " güncellendi", + } +} + +/// `2 files` / `1 file` / `2 dosya`. +pub fn files_count(lang: Lang, count: u64) -> String { + match lang { + Lang::En => format!("{count} {}", if count == 1 { "file" } else { "files" }), + Lang::Tr => format!("{count} dosya"), } } @@ -573,7 +578,7 @@ mod tests { assert_eq!(comments_count(Lang::En, 3), "3 comments"); assert_eq!(comments_count(Lang::Tr, 3), "3 yorum"); assert_eq!(page_number(Lang::Tr, 2), "Sayfa 2"); - assert_eq!(files_updated(Lang::En, 2, "now"), "2 files · updated now"); - assert_eq!(files_updated(Lang::En, 1, "now"), "1 file · updated now"); + assert_eq!(files_count(Lang::En, 2), "2 files"); + assert_eq!(files_count(Lang::En, 1), "1 file"); } } diff --git a/crates/forge-web/src/i18n/integrations.rs b/crates/forge-web/src/i18n/integrations.rs index 8b21e25..cb437a2 100644 --- a/crates/forge-web/src/i18n/integrations.rs +++ b/crates/forge-web/src/i18n/integrations.rs @@ -17,6 +17,7 @@ pub enum K { ClearSecret, CreateWebhook, CurrentUrl, + Cancel, DeleteConfirm, DeleteIntro, DeleteMirror, @@ -54,7 +55,6 @@ pub enum K { ManualOnly, Mirrors, MirrorsIntro, - Never, NoDeliveries, NoMirrors, NoWebhooks, @@ -164,7 +164,6 @@ pub const ALL: &[K] = &[ K::ManualOnly, K::Mirrors, K::MirrorsIntro, - K::Never, K::NoDeliveries, K::NoMirrors, K::NoWebhooks, @@ -268,8 +267,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (CreateWebhook, Tr) => "Web kancası oluştur", (CurrentUrl, En) => "Current URL:", (CurrentUrl, Tr) => "Mevcut URL:", - (DeleteConfirm, En) => "I understand this cannot be undone", - (DeleteConfirm, Tr) => "Bunun geri alınamayacağını anlıyorum", + (Cancel, En) => "Cancel", + (Cancel, Tr) => "Vazgeç", + (DeleteConfirm, En) => "Delete it? This cannot be undone.", + (DeleteConfirm, Tr) => "Silinsin mi? Bu işlem geri alınamaz.", (DeleteIntro, En) => { "Deleting removes the webhook and its delivery history. Events stop being sent to its URL at once." } @@ -339,10 +340,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { "Bu depo arşivlenmiş. Web kancaları salt okunurdur: değiştirilemez, test edilemez ya da yeniden teslim edilemez." } (HookNoticeConfirm, En) => { - "Tick the confirmation box to delete the webhook. Nothing was deleted." + "The delete was not confirmed. Nothing was deleted." } (HookNoticeConfirm, Tr) => { - "Web kancasını silmek için onay kutusunu işaretleyin. Hiçbir şey silinmedi." + "Silme onaylanmadı. Hiçbir şey silinmedi." } (HookNoticeCreated, En) => "Webhook created. A ping was queued.", (HookNoticeCreated, Tr) => "Web kancası oluşturuldu. Bir ping sıraya alındı.", @@ -368,8 +369,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (MirrorsIntro, Tr) => { "Çekme yansısı bu depoyu uzak bir depoyla eşit tutar: dallar ve etiketler aralıkla ya da istendiğinde çekilir, göndermeler reddedilir. Gönderme yansısı her göndermeden sonra dalları ve etiketleri uzak depoya gönderir. Çekme istekleri ve sorunlar yerel kalır." } - (Never, En) => "never", - (Never, Tr) => "hiç", (NoDeliveries, En) => "No deliveries yet.", (NoDeliveries, Tr) => "Henüz teslimat yok.", (NoMirrors, En) => "No mirrors yet.", @@ -381,10 +380,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (NoResponse, En) => "no response", (NoResponse, Tr) => "yanıt yok", (NoticeConfirm, En) => { - "Tick the confirmation box to delete the mirror. Nothing was deleted." + "The delete was not confirmed. Nothing was deleted." } (NoticeConfirm, Tr) => { - "Yansıyı silmek için onay kutusunu işaretleyin. Hiçbir şey silinmedi." + "Silme onaylanmadı. Hiçbir şey silinmedi." } (NoticeCreated, En) => { "Push mirror created. It will be pushed after the next push or on its interval." diff --git a/crates/forge-web/src/i18n/issues.rs b/crates/forge-web/src/i18n/issues.rs index 117e567..7644d0e 100644 --- a/crates/forge-web/src/i18n/issues.rs +++ b/crates/forge-web/src/i18n/issues.rs @@ -151,6 +151,7 @@ pub enum K { SortUpdated, NewIssue, NoIssuesMatch, + NoIssuesYet, SearchTitles, IssuesByState, LabelsAndMilestones, @@ -460,6 +461,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::NewIssue, Lang::Tr) => "Yeni sorun", (K::NoIssuesMatch, Lang::En) => "No issues match these filters.", (K::NoIssuesMatch, Lang::Tr) => "Bu filtrelerle eşleşen sorun yok.", + (K::NoIssuesYet, Lang::En) => "No issues yet.", + (K::NoIssuesYet, Lang::Tr) => "Henüz sorun yok.", (K::SearchTitles, Lang::En) => "Search titles", (K::SearchTitles, Lang::Tr) => "Başlıklarda ara", (K::IssuesByState, Lang::En) => "Issues by state", @@ -1032,6 +1035,7 @@ mod tests { K::SortUpdated, K::NewIssue, K::NoIssuesMatch, + K::NoIssuesYet, K::SearchTitles, K::IssuesByState, K::LabelsAndMilestones, diff --git a/crates/forge-web/src/i18n/link.rs b/crates/forge-web/src/i18n/link.rs index 9ac8491..d8580d1 100644 --- a/crates/forge-web/src/i18n/link.rs +++ b/crates/forge-web/src/i18n/link.rs @@ -7,6 +7,14 @@ use super::Lang; pub enum K { Restarting, BackSubmit, + /// The tick after a settings form saved. + Saved, + /// The tick after another form succeeded. + Done, + /// The note under a comment draft put back into its field. + DraftRestored, + /// The button that drops a restored draft. + DraftDiscard, } /// The phrase for `key`. @@ -17,6 +25,14 @@ pub fn t(lang: Lang, key: K) -> &'static str { (Restarting, Lang::Tr) => "Sunucu yeniden başlıyor\u{2026} sayfanız korunuyor", (BackSubmit, Lang::En) => "Server is back, submit again", (BackSubmit, Lang::Tr) => "Sunucu geri geldi, tekrar gönderin", + (Saved, Lang::En) => "Saved", + (Saved, Lang::Tr) => "Kaydedildi", + (Done, Lang::En) => "Done", + (Done, Lang::Tr) => "Tamam", + (DraftRestored, Lang::En) => "Draft restored", + (DraftRestored, Lang::Tr) => "Taslak geri yüklendi", + (DraftDiscard, Lang::En) => "Discard", + (DraftDiscard, Lang::Tr) => "Vazgeç", } } @@ -27,7 +43,7 @@ mod tests { #[test] fn every_string_has_no_em_dash() { for lang in [Lang::En, Lang::Tr] { - for key in [K::Restarting, K::BackSubmit] { + for key in [K::Restarting, K::BackSubmit, K::Saved, K::Done, K::DraftRestored, K::DraftDiscard] { assert!(!t(lang, key).contains('\u{2014}')); } } diff --git a/crates/forge-web/src/i18n/migrate.rs b/crates/forge-web/src/i18n/migrate.rs index 7b39084..3b790f7 100644 --- a/crates/forge-web/src/i18n/migrate.rs +++ b/crates/forge-web/src/i18n/migrate.rs @@ -325,11 +325,11 @@ pub fn t(lang: Lang, key: K) -> &'static str { } } -/// "Expires in N days" style line for the export list. -pub fn expires_on(lang: Lang, date: &str) -> String { +/// The label before an export's expiry time, which follows as a relative time. +pub fn expires_label(lang: Lang) -> &'static str { match lang { - Lang::En => format!("Expires {date}"), - Lang::Tr => format!("Son geçerlilik {date}"), + Lang::En => "Expires", + Lang::Tr => "Son geçerlilik", } } diff --git a/crates/forge-web/src/i18n/orgs.rs b/crates/forge-web/src/i18n/orgs.rs index ecd92d0..18c89c3 100644 --- a/crates/forge-web/src/i18n/orgs.rs +++ b/crates/forge-web/src/i18n/orgs.rs @@ -120,6 +120,7 @@ pub enum K { TabStars, FilterRepos, NoReposMatch, + ClearSearch, // Dashboard and landing. Dashboard, Home, @@ -367,6 +368,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (FilterRepos, Tr) => "Depo ara", (NoReposMatch, En) => "No repositories match.", (NoReposMatch, Tr) => "Aramayla eşleşen depo yok.", + (ClearSearch, En) => "Clear search", + (ClearSearch, Tr) => "Aramayı temizle", (Dashboard, En) => "Dashboard", (Dashboard, Tr) => "Pano", (Home, En) => "Home", @@ -607,6 +610,7 @@ mod tests { K::TabStars, K::FilterRepos, K::NoReposMatch, + K::ClearSearch, K::Dashboard, K::Home, K::LandingTagline, diff --git a/crates/forge-web/src/i18n/packages.rs b/crates/forge-web/src/i18n/packages.rs index f26f11e..75961de 100644 --- a/crates/forge-web/src/i18n/packages.rs +++ b/crates/forge-web/src/i18n/packages.rs @@ -41,6 +41,7 @@ pub enum K { DeleteTagMessage, DeleteTagConfirm, NoTags, + NoVersions, PackageTagCount, PackageTagCountOne, } @@ -83,6 +84,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (DeleteTagConfirm, Tr) => "Evet, sil", (NoTags, En) => "No tags yet. Push an image to see it here.", (NoTags, Tr) => "Henüz etiket yok. Burada görmek için bir imaj gönderin.", + (NoVersions, En) => "No versions published yet.", + (NoVersions, Tr) => "Henüz sürüm yayımlanmadı.", (PackageTagCount, En) => "tags", (PackageTagCount, Tr) => "etiket", (PackageTagCountOne, En) => "tag", diff --git a/crates/forge-web/src/i18n/push.rs b/crates/forge-web/src/i18n/push.rs index 4258d77..18b4fe3 100644 --- a/crates/forge-web/src/i18n/push.rs +++ b/crates/forge-web/src/i18n/push.rs @@ -97,19 +97,19 @@ pub fn test_sent(lang: Lang, devices: usize) -> String { } } -/// "Added 2026-10-02" and the matching delivery line. -pub fn added_on(lang: Lang, date: &str) -> String { +/// The label before a device's added time: "Added 3 days ago" with the time after it. +pub fn added_label(lang: Lang) -> &'static str { match lang { - Lang::En => format!("Added {date}"), - Lang::Tr => format!("Eklendi {date}"), + Lang::En => "Added", + Lang::Tr => "Eklendi", } } -/// "Last delivered 2026-10-02". -pub fn last_delivered(lang: Lang, date: &str) -> String { +/// The label before a device's last delivery: "Last delivered 5 minutes ago". +pub fn last_delivered_label(lang: Lang) -> &'static str { match lang { - Lang::En => format!("Last delivered {date}"), - Lang::Tr => format!("Son teslim {date}"), + Lang::En => "Last delivered", + Lang::Tr => "Son teslim", } } diff --git a/crates/forge-web/src/i18n/releases_ci.rs b/crates/forge-web/src/i18n/releases_ci.rs index 8eb17e9..03942b1 100644 --- a/crates/forge-web/src/i18n/releases_ci.rs +++ b/crates/forge-web/src/i18n/releases_ci.rs @@ -128,7 +128,6 @@ pub enum K { Assets, AllReleases, SourceCode, - Confirm, DeleteRelease, BackToRelease, UploadAsset, @@ -347,8 +346,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (RelAssetInvalid, Tr) => { "Yüklenen dosya okunamadı. Hiçbir şey değiştirilmedi; yeniden deneyin." } - (RelConfirm, En) => "Tick the confirmation box to delete the release. Nothing was deleted.", - (RelConfirm, Tr) => "Sürümü silmek için onay kutusunu işaretleyin. Hiçbir şey silinmedi.", + (RelConfirm, En) => "The delete was not confirmed. Nothing was deleted.", + (RelConfirm, Tr) => "Silme onaylanmadı. Hiçbir şey silinmedi.", (RelInvalid, En) => { "Enter a title of up to 200 characters and release notes of up to 65536 characters. Nothing was changed." } @@ -423,8 +422,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (AllReleases, Tr) => "Tüm sürümler", (SourceCode, En) => "Source code", (SourceCode, Tr) => "Kaynak kodu", - (Confirm, En) => "Confirm", - (Confirm, Tr) => "Onayla", (DeleteRelease, En) => "Delete release", (DeleteRelease, Tr) => "Sürümü sil", (BackToRelease, En) => "Back to the release", @@ -656,7 +653,6 @@ mod tests { K::Assets, K::AllReleases, K::SourceCode, - K::Confirm, K::DeleteRelease, K::BackToRelease, K::UploadAsset, diff --git a/crates/forge-web/src/i18n/repo_admin.rs b/crates/forge-web/src/i18n/repo_admin.rs index 7ace125..0db144b 100644 --- a/crates/forge-web/src/i18n/repo_admin.rs +++ b/crates/forge-web/src/i18n/repo_admin.rs @@ -17,9 +17,11 @@ pub enum K { ApprovalsRange, ArchiveHeading, ArchiveHelp, + ArchiveConfirm, ArchiveRepo, ArchivedHelp, ArchivedSecrets, + Cancel, BadForm, BlockWhileChanges, BranchMissing, @@ -31,7 +33,7 @@ pub enum K { BuiltinRowText, CancelRule, CancelTransfer, - ChangeVisibility, + MakePrivate, CollabAdded, CollabRemoved, Collaborators, @@ -58,7 +60,8 @@ pub enum K { ForcePushDesc, General, GeneralSaved, - IUnderstand, + MakePublic, + MakePublicConfirm, InvalidRole, LastUpdated, Mirrors, @@ -140,7 +143,7 @@ pub enum K { ValueTooLarge, VisibilityChanged, VisibilityHeading, - VisibilityHelp, + MakePrivateConfirm, Webhooks, } @@ -186,6 +189,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (ArchiveHelp, Tr) => { "Arşivleme depoyu salt okunur yapar: gönderimler reddedilir; sorunlar, etiketler ve kilometre taşları değiştirilemez. Arşivden istediğiniz zaman çıkarabilirsiniz." } + (ArchiveConfirm, En) => "Archive this repository? You can unarchive it at any time.", + (ArchiveConfirm, Tr) => "Depo arşivlensin mi? İstediğiniz zaman arşivden çıkarabilirsiniz.", + (Cancel, En) => "Cancel", + (Cancel, Tr) => "Vazgeç", (ArchiveRepo, En) => "Archive repository", (ArchiveRepo, Tr) => "Depoyu arşivle", (ArchivedHelp, En) => { @@ -226,8 +233,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (CancelRule, Tr) => "Vazgeç", (CancelTransfer, En) => "Cancel transfer", (CancelTransfer, Tr) => "Devri iptal et", - (ChangeVisibility, En) => "Change visibility", - (ChangeVisibility, Tr) => "Görünürlüğü değiştir", + (MakePrivate, En) => "Make private", + (MakePrivate, Tr) => "Özel yap", (CollabAdded, En) => "Collaborator added.", (CollabAdded, Tr) => "Ortak çalışan eklendi.", (CollabRemoved, En) => "Collaborator removed.", @@ -300,8 +307,14 @@ pub fn t(lang: Lang, key: K) -> &'static str { (General, Tr) => "Genel", (GeneralSaved, En) => "General settings saved.", (GeneralSaved, Tr) => "Genel ayarlar kaydedildi.", - (IUnderstand, En) => "I understand", - (IUnderstand, Tr) => "Anlıyorum", + (MakePublic, En) => "Make public", + (MakePublic, Tr) => "Herkese açık yap", + (MakePublicConfirm, En) => { + "Make it public? Anyone will be able to read its code, issues and pull requests. It takes effect at once." + } + (MakePublicConfirm, Tr) => { + "Herkese açık yapılsın mı? Kodunu, sorunlarını ve çekme isteklerini herkes okuyabilir. Hemen geçerli olur." + } (InvalidRole, En) => "Choose a valid role.", (InvalidRole, Tr) => "Geçerli bir rol seçin.", (LastUpdated, En) => "Last updated", @@ -487,10 +500,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (UnarchiveRepo, En) => "Unarchive repository", (UnarchiveRepo, Tr) => "Depoyu arşivden çıkar", (UnderstandNeeded, En) => { - "To change the visibility, tick I understand. Nothing was changed." + "The change was not confirmed. Nothing was changed." } (UnderstandNeeded, Tr) => { - "Görünürlüğü değiştirmek için \"Anlıyorum\" kutusunu işaretleyin. Hiçbir şey değiştirilmedi." + "Değişiklik onaylanmadı. Hiçbir şey değiştirilmedi." } (UnknownUser, En) => "No user has that username.", (UnknownUser, Tr) => "Bu kullanıcı adına sahip bir kullanıcı yok.", @@ -504,11 +517,11 @@ pub fn t(lang: Lang, key: K) -> &'static str { (VisibilityChanged, Tr) => "Görünürlük değiştirildi.", (VisibilityHeading, En) => "Visibility", (VisibilityHeading, Tr) => "Görünürlük", - (VisibilityHelp, En) => { - "Tick I understand to change the visibility. The change takes effect at once." + (MakePrivateConfirm, En) => { + "Make it private? Only its owner, collaborators and instance admins will see it; others get a 404. It takes effect at once." } - (VisibilityHelp, Tr) => { - "Görünürlüğü değiştirmek için \"Anlıyorum\" kutusunu işaretleyin. Değişiklik hemen geçerli olur." + (MakePrivateConfirm, Tr) => { + "Özel yapılsın mı? Yalnızca sahibi, ortak çalışanları ve sunucu yöneticileri görebilir; diğerleri 404 hatası alır. Hemen geçerli olur." } (Webhooks, En) => "Webhooks", (Webhooks, Tr) => "Web kancaları", @@ -601,8 +614,7 @@ pub fn transfer_summary( to_is_org: bool, to_name: &str, started_by: &str, - expires_on: &str, -) -> String { +) -> (String, &'static str) { match lang { Lang::En => { let target = if to_is_org { @@ -610,8 +622,9 @@ pub fn transfer_summary( } else { to_name.to_owned() }; - format!( - "Pending transfer to {target}, started by {started_by}. It expires on {expires_on} unless accepted." + ( + format!("Pending transfer to {target}, started by {started_by}. It expires "), + " unless accepted.", ) } Lang::Tr => { @@ -620,8 +633,11 @@ pub fn transfer_summary( } else { format!("{to_name} kullanıcısı") }; - format!( - "{target} için bekleyen devir, {started_by} tarafından başlatıldı. Kabul edilmezse {expires_on} tarihinde sona erer." + ( + format!( + "{target} için bekleyen devir, {started_by} tarafından başlatıldı. Kabul edilmezse " + ), + " sona erer.", ) } } @@ -671,9 +687,11 @@ mod tests { K::ApprovalsRange, K::ArchiveHeading, K::ArchiveHelp, + K::ArchiveConfirm, K::ArchiveRepo, K::ArchivedHelp, K::ArchivedSecrets, + K::Cancel, K::BadForm, K::BlockWhileChanges, K::BranchMissing, @@ -685,7 +703,7 @@ mod tests { K::BuiltinRowText, K::CancelRule, K::CancelTransfer, - K::ChangeVisibility, + K::MakePrivate, K::CollabAdded, K::CollabRemoved, K::Collaborators, @@ -712,7 +730,8 @@ mod tests { K::ForcePushDesc, K::General, K::GeneralSaved, - K::IUnderstand, + K::MakePublic, + K::MakePublicConfirm, K::InvalidRole, K::LastUpdated, K::Mirrors, @@ -794,7 +813,7 @@ mod tests { K::ValueTooLarge, K::VisibilityChanged, K::VisibilityHeading, - K::VisibilityHelp, + K::MakePrivateConfirm, K::Webhooks, ]; diff --git a/crates/forge-web/src/package_ops.rs b/crates/forge-web/src/package_ops.rs index 6932b41..874916c 100644 --- a/crates/forge-web/src/package_ops.rs +++ b/crates/forge-web/src/package_ops.rs @@ -4,6 +4,7 @@ //! `api::packages` and the pages translate these results. Bytes go to the blob store under //! `packages/`, and each change is announced on the owner's live signal. +use forge_core::authz::{Action, authorize}; use forge_core::cargo; use forge_core::model::User; use forge_core::packages::{KIND_CARGO, KIND_OCI, NewPackageVersion, Package}; @@ -49,8 +50,32 @@ pub async fn owner_named(state: &AppState, name: &str) -> Result, P Ok(state.store.user_by_username(name).await?) } -/// True when `actor` may read `package`. Public packages are readable by anyone. A private one -/// is readable by the instance admin, the owner and the owner's org members. +/// True when `actor` may read the repo a package is linked to. A link to a missing repo counts +/// as unreadable, so a dangling link never exposes the package. +async fn linked_repo_readable( + state: &AppState, + actor: Option<&User>, + repo_id: &str, +) -> Result { + let Some(repo) = state.store.repo_by_id(repo_id).await? else { + return Ok(false); + }; + let (role, org_role) = match actor { + Some(user) => ( + state.store.collaborator_role(&repo.id, &user.id).await?, + state + .store + .org_repo_role(&repo.owner_id, &user.id, &repo.id) + .await?, + ), + None => (None, None), + }; + Ok(authorize(actor, &repo, role, org_role, Action::Read).is_ok()) +} + +/// True when `actor` may read `package`. A public package is readable by anyone, unless it is +/// linked to a repo the actor may not read. A private one is readable by the instance admin, the +/// owner and the owner's org members. pub async fn may_read( state: &AppState, actor: Option<&User>, @@ -58,7 +83,10 @@ pub async fn may_read( package: &Package, ) -> Result { if !package.private { - return Ok(true); + return match &package.repo_id { + Some(repo_id) => linked_repo_readable(state, actor, repo_id).await, + None => Ok(true), + }; } let Some(actor) = actor else { return Ok(false); diff --git a/crates/forge-web/src/pages/admin_backups.rs b/crates/forge-web/src/pages/admin_backups.rs index 9102d99..54e1aea 100644 --- a/crates/forge-web/src/pages/admin_backups.rs +++ b/crates/forge-web/src/pages/admin_backups.rs @@ -5,7 +5,6 @@ //! A button press is audited and redirects back here with a notice. use forge_core::store::backup_runs::{BackupRun, RunKind}; -use forge_core::tz::format_in_tz; use forge_core::{AuditAction, Error, Store, User}; use serde::Deserialize; use topcoat::Result; @@ -25,7 +24,7 @@ use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; use crate::pages::issues_list::stamp_unix; use crate::state::AppState; -use crate::views::{enc, shell}; +use crate::views::{empty_state, enc, rel_time, shell}; /// Runs shown on the page. const RUN_LIMIT: u32 = 20; @@ -109,7 +108,7 @@ fn duration_text(run: &BackupRun) -> String { } } -fn run_row(run: &BackupRun, tz: &str, lang: Lang) -> RunRow { +fn run_row(run: &BackupRun, lang: Lang) -> RunRow { let (status, detail) = match (run.finished_at.is_some(), run.ok) { (false, _) => (g::t(lang, K::StatusInProgress).to_owned(), String::new()), (true, Some(true)) => (g::t(lang, K::StatusOk).to_owned(), String::new()), @@ -121,7 +120,7 @@ fn run_row(run: &BackupRun, tz: &str, lang: Lang) -> RunRow { RunRow { kind: g::kind_name(lang, run.kind).to_owned(), trigger: g::trigger_name(lang, run.trigger).to_owned(), - started: format_in_tz(stamp_unix(&run.started_at), tz), + started: run.started_at.clone(), duration: duration_text(run), size: run.bytes.map(human_bytes).unwrap_or_default(), status, @@ -166,7 +165,7 @@ async fn backups_view(

    (g::running_line(lang, kind))

    }
    -
    +
    @@ -179,7 +178,9 @@ async fn backups_view(

    (g::t(lang, K::RecentRuns))

    if rows.is_empty() { -

    (g::t(lang, K::NoRunsYet))

    + empty_state(title: g::t(lang, K::NoRunsYet), hint: Some(g::t(lang, K::BackupsEmptyHint))) { + (g::t(lang, K::RunBackupNow)) + } } else {
    @@ -198,7 +199,7 @@ async fn backups_view( - +
    (row.kind.as_str()) (row.trigger.as_str())(row.started.as_str())rel_time(lang: lang, stamp: row.started.as_str()) (row.duration.as_str()) (row.size.as_str()) @@ -251,8 +252,7 @@ async fn backups_page(cx: &Cx) -> Result { let state = app_context::(cx); let lang = i18n::lang(cx, Some(&viewer.0)); let runs = state.store.recent_runs(RUN_LIMIT).await?; - let tz = viewer.0.timezone.as_str(); - let rows: Vec = runs.iter().map(|run| run_row(run, tz, lang)).collect(); + let rows: Vec = runs.iter().map(|run| run_row(run, lang)).collect(); let running = state.jobs.running(); let settings = settings_view(lang, &state.config.backup); let csrf = viewer.1.csrf_token.clone(); diff --git a/crates/forge-web/src/pages/admin_health.rs b/crates/forge-web/src/pages/admin_health.rs index 9e5e182..4dbabf6 100644 --- a/crates/forge-web/src/pages/admin_health.rs +++ b/crates/forge-web/src/pages/admin_health.rs @@ -12,7 +12,6 @@ use forge_core::mail::MailState; use forge_core::store::backup_runs::RunKind; use forge_core::store::replication::DB_SUBJECT; use forge_core::time::stamp_to_unix; -use forge_core::tz::format_in_tz; use tokio::process::Command; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -205,7 +204,7 @@ fn uptime_secs() -> Option { Some((system - start_ticks / 100.0).max(0.0) as u64) } -async fn gather(state: &AppState, lang: Lang, tz: &str) -> Result { +async fn gather(state: &AppState, lang: Lang) -> Result { let live = state.live(); let now = now_unix(); let data_dir = live.data_dir.clone(); @@ -321,7 +320,6 @@ async fn gather(state: &AppState, lang: Lang, tz: &str) -> Result { }; services.push(match backup { Some(run) => { - let at_unix = stamp_to_unix(&run.started_at).unwrap_or(0); let (value, dot) = match run.ok { Some(true) => (at(lang, A::Ok), Dot::Ok), Some(false) => (at(lang, A::Failed), Dot::Bad), @@ -331,7 +329,7 @@ async fn gather(state: &AppState, lang: Lang, tz: &str) -> Result { label: at(lang, A::LastBackup), dot, value: value.to_owned(), - detail: format_in_tz(at_unix, tz), + detail: String::new(), stamp: Some(run.started_at.clone()), } } @@ -426,39 +424,35 @@ async fn gather(state: &AppState, lang: Lang, tz: &str) -> Result { struct AlertRow { title: String, body: String, - /// The raised time as the server formats it, and its stamp for the live relative time. - date: String, + /// The raised time, as a live relative time. stamp: String, } /// The alerts active now, worded for the viewer. -async fn alert_rows(state: &AppState, lang: Lang, tz: &str) -> Result> { - let now = now_unix(); +async fn alert_rows(state: &AppState, lang: Lang) -> Result> { Ok(state .store .active_alerts() .await? .into_iter() .map(|alert| { - let raised = stamp_to_unix(&alert.raised_at).unwrap_or(now); AlertRow { title: alert_text::title(lang, &alert.kind, &alert.subject, false), body: alert_text::body(lang, &alert.kind, &alert.subject, &alert.detail, false), - date: format_in_tz(raised, tz), stamp: alert.raised_at.clone(), } }) .collect()) } -/// The alert's raised time: "since · ", worded per language. +/// The alert's raised time as a live relative time, worded per language. #[component] -async fn since_line(lang: Lang, date: &str, stamp: &str) -> Result { +async fn since_line(lang: Lang, stamp: &str) -> Result { Ok(view! { if matches!(lang, Lang::Tr) { - (date) " · " rel_time(lang: lang, stamp: stamp) " tarihinden beri" + rel_time(lang: lang, stamp: stamp) " başladı" } else { - "since " (date) " · " rel_time(lang: lang, stamp: stamp) + "raised " rel_time(lang: lang, stamp: stamp) } }) } @@ -496,7 +490,7 @@ async fn health_view(lang: Lang, health: Health, alerts: Vec) -> Resul for a in alerts.into_iter() {
  • (a.title.as_str()) - since_line(lang: lang, date: a.date.as_str(), stamp: a.stamp.as_str()) + since_line(lang: lang, stamp: a.stamp.as_str()) if !a.body.is_empty() {
    (a.body.as_str())
    } @@ -565,8 +559,8 @@ async fn health_page(cx: &Cx) -> Result { let viewer = admin_only(cx).await?; let lang = i18n::lang(cx, Some(&viewer.0)); let state = app_context::(cx); - let health = gather(state, lang, &viewer.0.timezone).await?; - let alerts = alert_rows(state, lang, &viewer.0.timezone).await?; + let health = gather(state, lang).await?; + let alerts = alert_rows(state, lang).await?; let title = at(lang, A::Health); Ok(view! { shell(title: title, viewer: Some(&viewer), health_view(lang: lang, health: health, alerts: alerts)) @@ -583,7 +577,7 @@ async fn health_fingerprint(state: &AppState) -> Result { .store .mail_state_counts(&forge_core::time::now_stamp()) .await?; - let alerts: Vec<(String, String)> = alert_rows(state, Lang::En, "UTC") + let alerts: Vec<(String, String)> = alert_rows(state, Lang::En) .await? .into_iter() .map(|alert| (alert.title, alert.body)) diff --git a/crates/forge-web/src/pages/admin_mail.rs b/crates/forge-web/src/pages/admin_mail.rs index 46e079f..33119cf 100644 --- a/crates/forge-web/src/pages/admin_mail.rs +++ b/crates/forge-web/src/pages/admin_mail.rs @@ -12,7 +12,6 @@ use forge_core::mail::{ MailKind, MailSettings, MailSettingsUpdate, MailState, OutboxEntry, Security, }; use forge_core::time::now_stamp; -use forge_core::tz::format_in_tz; use forge_core::{AuditAction, Error}; use futures_util::{Stream, stream}; use serde::Deserialize; @@ -33,9 +32,8 @@ use crate::i18n::{self, Key, Lang}; use crate::mail::{enqueue, live, templates}; use crate::pages::admin_users::admin_only; use crate::pages::ci_runs::{changed_event, events_response}; -use crate::pages::issues_list::stamp_unix; use crate::state::AppState; -use crate::views::{enc, shell}; +use crate::views::{empty_state, enc, rel_time, shell}; /// Rows shown in the queue at most. const LIST_LIMIT: u32 = 100; @@ -65,7 +63,7 @@ struct QueueRow { attempts: u32, error: String, created: String, - sent: String, + sent: Option, failed: bool, } @@ -126,7 +124,7 @@ fn tab_class(on: bool) -> &'static str { } } -fn row_view(entry: &OutboxEntry, now: &str, tz: &str, lang: Lang) -> QueueRow { +fn row_view(entry: &OutboxEntry, now: &str, lang: Lang) -> QueueRow { let state = entry.state_at(now); QueueRow { id: entry.id.clone(), @@ -137,12 +135,8 @@ fn row_view(entry: &OutboxEntry, now: &str, tz: &str, lang: Lang) -> QueueRow { state_class: state_class(state), attempts: entry.attempts, error: entry.last_error.clone().unwrap_or_default(), - created: format_in_tz(stamp_unix(&entry.created_at), tz), - sent: entry - .sent_at - .as_deref() - .map(|sent| format_in_tz(stamp_unix(sent), tz)) - .unwrap_or_default(), + created: entry.created_at.clone(), + sent: entry.sent_at.clone(), failed: state == MailState::Failed, } } @@ -150,7 +144,6 @@ fn row_view(entry: &OutboxEntry, now: &str, tz: &str, lang: Lang) -> QueueRow { /// The queue tab's data. `filter` of `None` lists every state. async fn queue_data( state: &AppState, - tz: &str, lang: Lang, filter: Option, ) -> forge_core::Result { @@ -176,7 +169,7 @@ async fn queue_data( .list_mail(filter, &now, LIST_LIMIT) .await? .iter() - .map(|entry| row_view(entry, &now, tz, lang)) + .map(|entry| row_view(entry, &now, lang)) .collect(); Ok(QueueData { chips, @@ -187,14 +180,13 @@ async fn queue_data( async fn page_data( state: &AppState, - tz: &str, lang: Lang, tab: Tab, filter: Option, ) -> forge_core::Result { let settings: MailSettings = state.store.mail_settings().await?; let queue = match tab { - Tab::Queue => Some(queue_data(state, tz, lang, filter).await?), + Tab::Queue => Some(queue_data(state, lang, filter).await?), Tab::Settings => None, }; Ok(PageData { @@ -296,7 +288,11 @@ async fn mail_view(
    if queue.rows.is_empty() { -

    (g::t(lang, K::MailNothingMatches))

    + if queue.filter_param.is_empty() { + empty_state(title: g::t(lang, K::MailQueueEmpty)) + } else { + empty_state(title: g::t(lang, K::MailNothingMatches)) + } } else {
    @@ -316,13 +312,13 @@ async fn mail_view( for row in queue.rows.into_iter() { - + - + - +
    (row.created.as_str())rel_time(lang: lang, stamp: row.created.as_str()) (row.to.as_str()) (row.kind) (row.subject.as_str()) (row.state) (row.attempts)(row.sent.as_str())if let Some(sent) = row.sent.as_deref() { rel_time(lang: lang, stamp: sent) } (row.error.as_str()) if row.failed { @@ -369,7 +365,7 @@ async fn mail_page(cx: &Cx) -> Result { Tab::Settings }; let filter = query.state.as_deref().and_then(MailState::parse); - let data = page_data(state, viewer.0.timezone.as_str(), lang, tab, filter).await?; + let data = page_data(state, lang, tab, filter).await?; let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::Mail); Ok(view! { diff --git a/crates/forge-web/src/pages/admin_replication.rs b/crates/forge-web/src/pages/admin_replication.rs index 45919d9..1d7a192 100644 --- a/crates/forge-web/src/pages/admin_replication.rs +++ b/crates/forge-web/src/pages/admin_replication.rs @@ -10,7 +10,6 @@ use std::time::Duration; use forge_core::store::replication::{DB_SUBJECT, ReplicationStatus}; use forge_core::time::stamp_ago; -use forge_core::tz::format_in_tz; use forge_core::{AuditAction, Error}; use serde::Deserialize; use topcoat::Result; @@ -24,12 +23,11 @@ use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; -use crate::i18n::{self, Key, Lang}; +use crate::i18n::{self, Lang}; use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; -use crate::pages::issues_list::stamp_unix; use crate::state::AppState; -use crate::views::{enc, shell}; +use crate::views::{empty_state, enc, rel_time_or_never, shell}; #[query_params(error = bad_request)] pub(crate) struct NoticeQuery { @@ -95,7 +93,8 @@ struct RepoRow { dot: &'static str, tone: &'static str, health: &'static str, - last_ok: String, + /// The last good copy's stamp, shown as a live relative time. + last_ok: Option, error: String, } @@ -105,23 +104,16 @@ struct PageData { target: String, db_dot: &'static str, db_health: &'static str, - db_last_ok: String, - db_last_attempt: String, + db_last_ok: Option, + db_last_attempt: Option, db_error: String, interval: String, healthcheck: &'static str, repos: Vec, } -fn ok_text(stamp: Option<&str>, tz: &str, lang: Lang) -> String { - match stamp { - Some(stamp) => format_in_tz(stamp_unix(stamp), tz), - None => i18n::t(lang, Key::Never).to_owned(), - } -} - /// Builds the page data from the config, the status rows and the repo list. -async fn page_data(state: &AppState, tz: &str, lang: Lang) -> forge_core::Result { +async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result { let config = &state.config.replication; let db_cutoff = stamp_ago(Duration::from_secs(config.db_snapshot_minutes * 60 * 2)); let repo_cutoff = stamp_ago(Duration::from_secs(config.reconcile_minutes * 60 * 2)); @@ -149,7 +141,7 @@ async fn page_data(state: &AppState, tz: &str, lang: Lang) -> forge_core::Result dot: h.dot(), tone: h.tone(), health: h.label(lang), - last_ok: ok_text(status.and_then(|s| s.last_ok_at.as_deref()), tz, lang), + last_ok: status.and_then(|s| s.last_ok_at.clone()), error: status .and_then(|s| s.last_error.clone()) .unwrap_or_default(), @@ -164,7 +156,7 @@ async fn page_data(state: &AppState, tz: &str, lang: Lang) -> forge_core::Result dot: h.dot(), tone: h.tone(), health: h.label(lang), - last_ok: ok_text(status.last_ok_at.as_deref(), tz, lang), + last_ok: status.last_ok_at.clone(), error: status.last_error.clone().unwrap_or_default(), }); } @@ -175,8 +167,8 @@ async fn page_data(state: &AppState, tz: &str, lang: Lang) -> forge_core::Result target: config.target.clone(), db_dot: health(db, &db_cutoff).dot(), db_health: health(db, &db_cutoff).label(lang), - db_last_ok: ok_text(db.and_then(|s| s.last_ok_at.as_deref()), tz, lang), - db_last_attempt: ok_text(db.and_then(|s| s.last_attempt_at.as_deref()), tz, lang), + db_last_ok: db.and_then(|s| s.last_ok_at.clone()), + db_last_attempt: db.and_then(|s| s.last_attempt_at.clone()), db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(), interval: g::interval_line(lang, config.db_snapshot_minutes, config.reconcile_minutes), healthcheck: if config.healthcheck_url.is_empty() { @@ -214,8 +206,8 @@ async fn replication_view(
    (g::t(lang, K::Interval))
    (data.interval.as_str())
    (g::t(lang, K::Healthcheck))
    (data.healthcheck)
    (g::t(lang, K::Database))
    (data.db_health)
    -
    (g::t(lang, K::LastDbSnapshotShipped))
    (data.db_last_ok.as_str())
    -
    (g::t(lang, K::LastDbAttempt))
    (data.db_last_attempt.as_str())
    +
    (g::t(lang, K::LastDbSnapshotShipped))
    rel_time_or_never(lang: lang, stamp: data.db_last_ok.as_deref())
    +
    (g::t(lang, K::LastDbAttempt))
    rel_time_or_never(lang: lang, stamp: data.db_last_attempt.as_deref())
    if !data.db_error.is_empty() {

    (g::t(lang, K::DatabaseErrorPrefix))(data.db_error.as_str())

    @@ -233,7 +225,9 @@ async fn replication_view(

    (g::t(lang, K::Repos))

    if data.repos.is_empty() { -

    (g::t(lang, K::NoReposYet))

    + empty_state(title: g::t(lang, K::NoReposYet), hint: Some(g::t(lang, K::ReposEmptyHint))) { +

    (g::t(lang, K::ReplicationConfigHint))

    + } } else {
      for row in data.repos.into_iter() { @@ -243,7 +237,7 @@ async fn replication_view( (row.name.as_str()) -

      (g::t(lang, K::LastSuccess))": "(row.last_ok.as_str())

      +

      (g::t(lang, K::LastSuccess))": " rel_time_or_never(lang: lang, stamp: row.last_ok.as_deref())

      if !row.error.is_empty() {

      (row.error.as_str())

      } @@ -261,14 +255,14 @@ async fn replication_view( /// What the replication page shows, as one string. The health labels are read at each wake, so a /// wake also refreshes a copy that has gone stale since the last change. async fn page_fingerprint(state: &AppState) -> Result { - let data = page_data(state, "UTC", Lang::En).await?; + let data = page_data(state, Lang::En).await?; let rows: Vec<_> = data .repos .iter() .map(|row| (&row.name, row.health, &row.last_ok, &row.error)) .collect(); Ok(format!( - "{}|{}|{}|{}|{}|{}|{:?}", + "{}|{}|{:?}|{:?}|{}|{}|{:?}", data.enabled, data.db_health, data.db_last_ok, @@ -302,7 +296,7 @@ async fn replication_page(cx: &Cx) -> Result { let query = query_params::(cx)?; let lang = i18n::lang(cx, Some(&viewer.0)); let state = app_context::(cx); - let data = page_data(state, viewer.0.timezone.as_str(), lang).await?; + let data = page_data(state, lang).await?; let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::Replication); Ok(view! { diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index 334f9a4..5f483b5 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -30,7 +30,7 @@ use crate::pages::admin_users::admin_only; use crate::pages::ci_runs::events_response; use crate::pages::repo_mirrors::stamp_in_tz; use crate::state::AppState; -use crate::views::{enc, now_unix, relative_time, shell}; +use crate::views::{empty_state, enc, now_unix, relative_time, shell}; path_param!(runner_id); @@ -327,7 +327,9 @@ async fn runners_view(

      (g::t(lang, K::Runners))

      if rows.is_empty() { -

      (g::t(lang, K::NoRunnersYet))

      + empty_state(title: g::t(lang, K::NoRunnersYet), hint: Some(g::t(lang, K::RunnersEmptyHint))) { +
      "forge runner register --url  --token  --name  --labels linux,x86_64"
      + } } else {
        for row in rows.iter() { @@ -1688,8 +1690,8 @@ mod tests { "token in the box and the command" ); let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await; + // The empty list shows the register command with a placeholder, never the token. assert!(!list.contains(&token), "the list never shows the token"); - assert!(!list.contains("forge runner register")); // Only the hash is stored, so the list and the database hold no plain token. assert!(store.list_runners().await.expect("list").is_empty()); diff --git a/crates/forge-web/src/pages/admin_user_detail.rs b/crates/forge-web/src/pages/admin_user_detail.rs index 5027d51..4ea4de8 100644 --- a/crates/forge-web/src/pages/admin_user_detail.rs +++ b/crates/forge-web/src/pages/admin_user_detail.rs @@ -5,7 +5,6 @@ use forge_core::names::normalize_name; use forge_core::store::suspension::{AccountFacts, Suspension}; use forge_core::store::user_delete::GHOST_USERNAME; -use forge_core::tz::format_in_tz; use forge_core::{AuditAction, Store, User}; use serde::Deserialize; use topcoat::Result; @@ -23,10 +22,9 @@ use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; -use crate::pages::issues_list::stamp_unix; use crate::pages::passkeys::s; use crate::state::AppState; -use crate::views::{alert, avatar_url, enc, rel_time_or_never, shell, user_facing_message}; +use crate::views::{alert, avatar_url, enc, rel_time, rel_time_or_never, shell, user_facing_message}; #[query_params(error = bad_request)] pub(crate) struct DoneQuery { @@ -113,7 +111,6 @@ fn done_text(lang: Lang, done: &str) -> Option<&'static str> { async fn detail_body( lang: Lang, csrf: &str, - tz: &str, viewer_id: &str, detail: Detail, notice: Notice, @@ -127,7 +124,6 @@ async fn detail_body( } = detail; let base = format!("/admin/users/{}", enc(&target.id)); let own = target.id == viewer_id; - let created = format_in_tz(stamp_unix(&target.created_at), tz); let last_login = facts.last_login.clone(); let repos = facts.repo_count.to_string(); let suspended = suspension.is_some(); @@ -181,7 +177,7 @@ async fn detail_body( if !email.is_empty() { (email.as_str()) " · " } - (at(lang, A::Joined)) " " (created.as_str()) " · " (at(lang, A::LastLogin)) " " rel_time_or_never(lang: lang, stamp: last_login.as_deref()) + (at(lang, A::Joined)) " " rel_time(lang: lang, stamp: target.created_at.as_str()) " · " (at(lang, A::LastLogin)) " " rel_time_or_never(lang: lang, stamp: last_login.as_deref())

        @@ -384,7 +380,7 @@ async fn detail_page(cx: &Cx) -> Result { let csrf = viewer.1.csrf_token.clone(); let title = detail.target.username.clone(); Ok(view! { - shell(title: title.as_str(), viewer: Some(&viewer), detail_body(lang: lang, csrf: csrf.as_str(), tz: viewer.0.timezone.as_str(), viewer_id: viewer.0.id.as_str(), detail: detail, notice: notice)) + shell(title: title.as_str(), viewer: Some(&viewer), detail_body(lang: lang, csrf: csrf.as_str(), viewer_id: viewer.0.id.as_str(), detail: detail, notice: notice)) }) } @@ -546,7 +542,7 @@ async fn respond(cx: &Cx, form: ActionForm, action: Action) -> Result let csrf = viewer.1.csrf_token.clone(); let title = detail.target.username.clone(); Ok(view! { - shell(title: title.as_str(), viewer: Some(&viewer), detail_body(lang: lang, csrf: csrf.as_str(), tz: viewer.0.timezone.as_str(), viewer_id: viewer.0.id.as_str(), detail: detail, notice: notice)) + shell(title: title.as_str(), viewer: Some(&viewer), detail_body(lang: lang, csrf: csrf.as_str(), viewer_id: viewer.0.id.as_str(), detail: detail, notice: notice)) }) } diff --git a/crates/forge-web/src/pages/admin_users.rs b/crates/forge-web/src/pages/admin_users.rs index 4492963..5f74c15 100644 --- a/crates/forge-web/src/pages/admin_users.rs +++ b/crates/forge-web/src/pages/admin_users.rs @@ -2,7 +2,6 @@ use forge_core::names::{normalize_name, validate_username}; use forge_core::store::user_delete::{DeletionReport, GHOST_USERNAME}; -use forge_core::tz::format_in_tz; use forge_core::{AuditAction, Session, Store, User}; use serde::Deserialize; use topcoat::Result; @@ -18,9 +17,8 @@ use crate::auth::{check_csrf, current_user, hash_password_async}; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; use crate::live::{Topic, stream_changes}; -use crate::pages::issues_list::stamp_unix; use crate::state::AppState; -use crate::views::{alert, enc, shell, user_facing_message}; +use crate::views::{alert, enc, rel_time, shell, user_facing_message}; const MIN_PASSWORD_CHARS: usize = 12; const MAX_PASSWORD_BYTES: usize = 1024; @@ -58,7 +56,6 @@ async fn users_view( lang: Lang, csrf: &str, viewer_id: &str, - tz: &str, users: Vec, error: Option, ) -> Result { @@ -85,7 +82,7 @@ async fn users_view(
    (user.email.clone().unwrap_or_default()) (if user.is_org() { g::t(lang, K::RoleOrganization) } else if user.is_admin { g::t(lang, K::RoleAdmin) } else { g::t(lang, K::RoleUser) })(format_in_tz(stamp_unix(&user.created_at), tz))rel_time(lang: lang, stamp: user.created_at.as_str()) if user.id != viewer_id && !is_ghost(&user) { (i18n::t(lang, Key::Delete)) @@ -168,7 +165,7 @@ async fn users_page(cx: &Cx) -> Result { let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::Users); Ok(view! { - shell(title: title, viewer: Some(&viewer), users_view(lang: lang, csrf: csrf.as_str(), viewer_id: viewer.0.id.as_str(), tz: viewer.0.timezone.as_str(), users: users, error: None)) + shell(title: title, viewer: Some(&viewer), users_view(lang: lang, csrf: csrf.as_str(), viewer_id: viewer.0.id.as_str(), users: users, error: None)) }) } @@ -205,7 +202,7 @@ async fn users_create(cx: &Cx, Form(form): Form) -> Result RowView { +fn row_view(entry: &AuditEntry, lang: Lang) -> RowView { let actor = match (entry.actor_name.as_str(), entry.actor_id.is_some()) { ("", _) => g::t(lang, K::Anonymous).to_owned(), (name, _) => name.to_owned(), @@ -55,7 +54,7 @@ fn row_view(entry: &AuditEntry, tz: &str, lang: Lang) -> RowView { format!("{}: {name}", entry.target_kind) }; RowView { - when: format_in_tz(stamp_unix(&entry.at), tz), + when: entry.at.clone(), actor, action: entry.action.as_str().to_owned(), target, @@ -94,7 +93,7 @@ async fn fetch_page( async fn audit_table(lang: Lang, rows: Vec, show_actor: bool) -> Result { Ok(view! { if rows.is_empty() { -

    (g::t(lang, K::NoEntries))

    + empty_state(title: g::t(lang, K::NoEntries)) } else {
    @@ -113,7 +112,7 @@ async fn audit_table(lang: Lang, rows: Vec, show_actor: bool) -> Result for row in rows.into_iter() { - + if show_actor { } @@ -233,10 +232,9 @@ async fn admin_audit_page(cx: &Cx) -> Result { fetch_page(store, &filter, query.before.as_deref()).await? }; - let tz = viewer.0.timezone.as_str(); let rows: Vec = entries .iter() - .map(|entry| row_view(entry, tz, lang)) + .map(|entry| row_view(entry, lang)) .collect(); let older_href = next.map(|cursor| { list_href( @@ -311,10 +309,9 @@ async fn own_log_page(cx: &Cx) -> Result { }; let (entries, next) = fetch_page(store, &filter, query.before.as_deref()).await?; - let tz = viewer.0.timezone.as_str(); let rows: Vec = entries .iter() - .map(|entry| row_view(entry, tz, lang)) + .map(|entry| row_view(entry, lang)) .collect(); let older_href = next.map(|cursor| list_href("/settings/security/log", &[("before", cursor.as_str())])); @@ -479,7 +476,7 @@ mod tests { fn anonymous_actor_and_target_fallbacks() { let mut entry = AuditEntry::new(AuditAction::LoginFailed); entry.target_name = "mallory".into(); - let row = row_view(&entry, "UTC", Lang::En); + let row = row_view(&entry, Lang::En); assert_eq!(row.actor, "anonymous"); assert_eq!(row.target, "mallory"); assert_eq!(row.details, ""); diff --git a/crates/forge-web/src/pages/authoring.rs b/crates/forge-web/src/pages/authoring.rs index 1cd83f8..07182a1 100644 --- a/crates/forge-web/src/pages/authoring.rs +++ b/crates/forge-web/src/pages/authoring.rs @@ -278,7 +278,9 @@ async fn download(cx: &Cx) -> Result { ); h.insert( HeaderName::from_static("cache-control"), - HeaderValue::from_static("private, max-age=3600"), + // No max-age: a repo made private must stop serving its attachments at once, so + // browsers revalidate on every use instead of reusing a cached copy. + HeaderValue::from_static("private, no-cache"), ); Ok(res) } diff --git a/crates/forge-web/src/pages/branches.rs b/crates/forge-web/src/pages/branches.rs index 2d095b1..2c8e1be 100644 --- a/crates/forge-web/src/pages/branches.rs +++ b/crates/forge-web/src/pages/branches.rs @@ -29,7 +29,7 @@ use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::pages::tree::{LastCommit, last_commit_view}; use crate::post_update::after_ref_update; use crate::state::AppState; -use crate::views::{alert, iso_time, now_unix, relative_time, repo_href, shell}; +use crate::views::{alert, empty_state, iso_time, now_unix, relative_time, repo_href, shell}; path_param!(owner); path_param!(repo); @@ -317,7 +317,7 @@ async fn branches_page(cx: &Cx) -> Result { default_branch: default_branch, options: options) } if empty { -

    (g::t(lang, K::NothingHere))

    + empty_state(title: g::t(lang, K::NothingHere)) } else { branch_table(rows: rows, lang: lang, csrf: csrf.clone(), delete_action: delete_action, can_delete: can_write) } diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index c801faa..4b44a24 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -11,8 +11,8 @@ use std::sync::Arc; use std::time::Duration; use bytes::Bytes; -use forge_core::Store; use forge_core::ci::{CiArtifact, CiJob, CiRun}; +use forge_core::{Store, User}; use futures_util::{Stream, TryStreamExt}; use http::header::{CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE}; use http_body::Frame; @@ -38,7 +38,7 @@ use crate::pages::ci_runs::{ state_text, }; use crate::pages::repo::repo_head; -use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; +use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable}; use crate::state::AppState; use crate::views::{enc, human_size, shell}; @@ -161,13 +161,15 @@ async fn log_tail(path: &Path) -> Result { /// Follows a log: yields what the file holds, then sends new bytes each time the job changes (its /// log grew or its state did). The stream ends when the job is terminal and a read after seeing -/// that returns nothing, so every byte the runner wrote is sent. A job that is gone, or a read -/// error, ends the stream. +/// that returns nothing, so every byte the runner wrote is sent. A job that is gone, a read +/// error, or a repo the viewer can no longer read ends the stream. pub(crate) fn follow_log( store: Store, live: Arc, job_id: String, path: PathBuf, + viewer: Option, + repo_id: String, ) -> impl Stream> + Send + 'static { struct Follow { store: Store, @@ -177,6 +179,8 @@ pub(crate) fn follow_log( file: Option, /// Subscribed before the first read, so a change between the read and the wait is seen. wake: watch::Receiver, + viewer: Option, + repo_id: String, } let wake = live.subscribe_job(&job_id); futures_util::stream::unfold( @@ -187,9 +191,14 @@ pub(crate) fn follow_log( path, file: None, wake, + viewer, + repo_id, }, |mut follow| async move { loop { + if !still_readable(&follow.store, follow.viewer.as_ref(), &follow.repo_id).await { + return None; + } // Checked before the read, so a read that finds nothing after this is the end. let terminal = match follow.store.job_by_id(&follow.job_id).await { Ok(Some(job)) => job.state.is_terminal(), @@ -524,6 +533,8 @@ async fn job_events(cx: &Cx) -> Result { primed: false, pending_fingerprint: None, pending_log: None, + viewer: ctx.viewer.as_ref().map(|(user, _)| user.clone()), + repo_id: ctx.repo.id.clone(), }; events_response(cx, job_stream(follow)) } @@ -555,11 +566,19 @@ struct JobFollow { pending_fingerprint: Option, /// The text and the offset past it. pending_log: Option<(String, u64)>, + /// The viewer the stream opened for, and the repo, so each send is checked for read access. + viewer: Option, + repo_id: String, } fn job_stream(follow: JobFollow) -> impl Stream> + Send + 'static { futures_util::stream::unfold(follow, |mut f| async move { loop { + // Checked before anything is sent, so a repo made private or a removed collaborator ends + // the stream on the next wake, not when it reopens. + if !still_readable(&f.store, f.viewer.as_ref(), &f.repo_id).await { + return None; + } if let Some(fingerprint) = f.pending_fingerprint.take() { return Some((changed_event(fingerprint), f)); } @@ -643,6 +662,8 @@ async fn job_log(cx: &Cx) -> Result { Arc::clone(&state.ci_live), job.id.clone(), path, + ctx.viewer.as_ref().map(|(user, _)| user.clone()), + ctx.repo.id.clone(), ) .map_ok(Frame::data); let mut res = Response::new(Body::new(StreamBody::new(chunks))); diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index 6f788a3..f075f67 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -40,9 +40,9 @@ use crate::i18n::{ }; use crate::pages::refs::load_refs; use crate::pages::repo::repo_head; -use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; +use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable}; use crate::state::AppState; -use crate::views::{alert, enc, human_size, now_unix, relative_time, shell, short_oid}; +use crate::views::{alert, empty_state, enc, human_size, now_unix, rel_time, relative_time, shell, short_oid}; path_param!(owner); path_param!(repo); @@ -321,11 +321,9 @@ fn trigger_text(lang: Lang, trigger: &str) -> String { } } -/// The next scheduled run as `2026-10-21 03:00 UTC`. +/// The next scheduled run as an RFC 3339 stamp, shown as a live relative time. fn next_run_text(at: i64) -> Option { - let when = time::OffsetDateTime::from_unix_timestamp(at).ok()?; - let format = time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]"); - Some(format!("{} UTC", when.format(&format).ok()?)) + forge_core::time::stamp_from_unix(at) } /// One run in the list. `bar` is its duration bar on the page's shared scale. @@ -1662,13 +1660,10 @@ async fn runs_body( if let Some(next) = next_scheduled.as_ref() { -

    (g::t(lang, K::NextScheduledRun)) ": "

    +

    (g::t(lang, K::NextScheduledRun)) ": " rel_time(lang: lang, stamp: next.as_str())

    } if rows.is_empty() { -
    -

    (g::t(lang, K::NoRunsYet))

    -

    (g::t(lang, K::NoRunsHint))

    -
    + empty_state(title: g::t(lang, K::NoRunsYet), hint: Some(g::t(lang, K::NoRunsHint))) } else {

    (scale.as_str())

      @@ -2070,10 +2065,20 @@ async fn run_events(cx: &Cx) -> Result { let wake = state.ci_live.subscribe_run(&run.id); let store = state.store.clone(); let run_id = run.id.clone(); + let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone()); + let repo_id = ctx.repo.id.clone(); let events = changed_stream(wake, false, move || { let store = store.clone(); let run_id = run_id.clone(); - async move { run_status(&store, &run_id).await } + let viewer = viewer.clone(); + let repo_id = repo_id.clone(); + async move { + // A repo the viewer can no longer read ends the stream before the status is sent. + if !still_readable(&store, viewer.as_ref(), &repo_id).await { + return Ok(None); + } + run_status(&store, &run_id).await + } }); events_response(cx, events) } diff --git a/crates/forge-web/src/pages/ci_tests.rs b/crates/forge-web/src/pages/ci_tests.rs index 839ae23..6ada390 100644 --- a/crates/forge-web/src/pages/ci_tests.rs +++ b/crates/forge-web/src/pages/ci_tests.rs @@ -848,6 +848,8 @@ async fn log_txt_and_log_follower() { Arc::clone(&live), job.id.clone(), path.clone(), + fx.store.user_by_id(&fx.tahinli).await.expect("viewer"), + run.repo_id.clone(), )); let (tx, mut chunks) = tokio::sync::mpsc::unbounded_channel(); tokio::spawn(async move { diff --git a/crates/forge-web/src/pages/code_search.rs b/crates/forge-web/src/pages/code_search.rs index 1687787..0a9ddeb 100644 --- a/crates/forge-web/src/pages/code_search.rs +++ b/crates/forge-web/src/pages/code_search.rs @@ -20,7 +20,7 @@ use crate::pages::commits::blocking; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; use crate::state::AppState; -use crate::views::{repo_href, shell}; +use crate::views::{empty_state, repo_href, shell}; path_param!(owner); path_param!(repo); @@ -260,7 +260,7 @@ async fn search_page(cx: &Cx) -> Result { } } else if searched { -

      (g::t(lang, K::NoMatches))

      + empty_state(title: g::t(lang, K::NoMatches)) } } ) diff --git a/crates/forge-web/src/pages/commits.rs b/crates/forge-web/src/pages/commits.rs index bdb7e17..94519ac 100644 --- a/crates/forge-web/src/pages/commits.rs +++ b/crates/forge-web/src/pages/commits.rs @@ -24,7 +24,7 @@ use crate::render::emoji::emojify; use crate::signatures::{self, SigBadge}; use crate::state::AppState; use crate::views::commit_status::{StatusLang, StatusSummary, commit_status}; -use crate::views::shell; +use crate::views::{empty_state, shell}; path_param!(owner); path_param!(repo); @@ -286,7 +286,11 @@ async fn commits_page(cx: &Cx) -> Result {

      (g::t(lang, K::FilteredTo)) (filter_text.as_str()) " · " (g::t(lang, K::ClearFilter))

      } if empty { -

      (g::t(lang, K::NoCommits))

      + empty_state(title: g::t(lang, K::NoCommits), + if has_filter { + (g::t(lang, K::ClearFilter)) + } + ) } else {
        for row in rows.iter() { diff --git a/crates/forge-web/src/pages/compare.rs b/crates/forge-web/src/pages/compare.rs index be22814..2edc588 100644 --- a/crates/forge-web/src/pages/compare.rs +++ b/crates/forge-web/src/pages/compare.rs @@ -37,7 +37,7 @@ use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::state::AppState; use crate::templates; use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section}; -use crate::views::{alert, repo_href, shell, user_facing_message}; +use crate::views::{alert, empty_state, repo_href, shell, user_facing_message}; use crate::webhooks::emit::{Sender, emit_pull}; path_param!(owner); @@ -337,7 +337,7 @@ async fn compare_view(

        (g::t(lang, K::Unrelated))

        } if nothing { -

        (g::t(lang, K::NothingToCompare))

        + empty_state(title: g::t(lang, K::NothingToCompare)) } if has_commits {

        (commits_label.as_str())

        diff --git a/crates/forge-web/src/pages/dashboard.rs b/crates/forge-web/src/pages/dashboard.rs index 649d03b..02fa8ad 100644 --- a/crates/forge-web/src/pages/dashboard.rs +++ b/crates/forge-web/src/pages/dashboard.rs @@ -25,7 +25,7 @@ use crate::pages::issue_parts::stamp_unix; use crate::pages::repo_settings::{notice_banner_for, take_notice}; use crate::state::AppState; use crate::views::heatmap::{self, Calendar, DayDetail, contribution_calendar}; -use crate::views::{SIDE_REPOS, display_name, now_unix, relative_time, shell}; +use crate::views::{SIDE_REPOS, display_name, empty_state, now_unix, relative_time, shell}; /// How far back the calendar reads contributions: 53 weeks plus the days of the current week. const CALENDAR_DAYS: u64 = 371; @@ -303,7 +303,9 @@ async fn dashboard(dash: Dashboard, lang: Lang) -> Result { (g::t(lang, K::NewRepository)) if empty { -

        (g::t(lang, K::NoReposYet))

        + empty_state(title: g::t(lang, K::NoReposYet), + (g::t(lang, K::NewRepository)) + (crate::i18n::migrate::t(lang, crate::i18n::migrate::K::ImportTitle))) } else {
    (row.when.as_str())rel_time(lang: lang, stamp: row.when.as_str())(row.actor.as_str())
    @@ -337,7 +339,7 @@ async fn dashboard(dash: Dashboard, lang: Lang) -> Result {

    (m::t(lang, MK::NeedsAttention))

    if attention_empty { -

    (m::t(lang, MK::NothingNeedsYou))

    + empty_state(title: m::t(lang, MK::NothingNeedsYou)) } else {
      for item in dash.attention.into_iter() { diff --git a/crates/forge-web/src/pages/discussions.rs b/crates/forge-web/src/pages/discussions.rs index f126daf..14367c2 100644 --- a/crates/forge-web/src/pages/discussions.rs +++ b/crates/forge-web/src/pages/discussions.rs @@ -27,7 +27,7 @@ use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; use crate::render::markdown::mentioned_usernames; use crate::state::AppState; -use crate::views::{alert, csrf_field, now_unix, repo_href, shell, user_link}; +use crate::views::{alert, csrf_field, empty_state, now_unix, repo_href, shell, user_link}; path_param!(owner); path_param!(repo); @@ -317,7 +317,11 @@ async fn discussions_list_page(cx: &Cx) -> Result { } if rows.is_empty() { -

      (empty_text)

      + empty_state(title: empty_text, + if can_start { + (new_label) + } + ) } else {
        for row in rows.iter() { diff --git a/crates/forge-web/src/pages/explore.rs b/crates/forge-web/src/pages/explore.rs index f9f7996..2c0f285 100644 --- a/crates/forge-web/src/pages/explore.rs +++ b/crates/forge-web/src/pages/explore.rs @@ -18,7 +18,7 @@ use crate::state::AppState; use crate::views::repo_list::{ PageLink, RepoRow, SortLink, pager, pager_links, repo_rows, sort_chips, }; -use crate::views::{enc, now_unix, shell}; +use crate::views::{empty_state, enc, now_unix, shell}; const PER_PAGE: u64 = 30; /// Longest search text kept, in characters. @@ -194,8 +194,10 @@ async fn explore_body( live: String, ) -> Result { let empty = rows.is_empty(); + let has_search = !q.is_empty(); let has_orgs = !orgs.is_empty(); let (links, prev, next) = nav; + let clear_href = explore_href("", sort, 1); Ok(view! {

        (g::t(lang, K::Explore))

        @@ -219,7 +221,10 @@ async fn explore_body( sort_chips(links: sort_links, lang: lang)

        (g::repo_count(lang, total))

        if empty { -

        (g::t(lang, K::NoPublicReposMatch))

        + empty_state(title: g::t(lang, K::NoPublicReposMatch), + if has_search { + (g::t(lang, K::ClearSearch)) + }) } else { repo_rows(rows: rows, lang: lang) } diff --git a/crates/forge-web/src/pages/import.rs b/crates/forge-web/src/pages/import.rs index 8863685..f586e6e 100644 --- a/crates/forge-web/src/pages/import.rs +++ b/crates/forge-web/src/pages/import.rs @@ -5,7 +5,6 @@ use std::collections::HashMap; use forge_core::store::imports::{ImportJob, ImportState}; -use forge_core::time::stamp_to_unix; use forge_core::{AuditAction, Repo, User, Visibility}; use forge_git::repo::{init_bare, repo_path}; use futures_util::stream; @@ -30,8 +29,9 @@ use crate::importer::{ }; use crate::pages::ci_runs::{changed_event, events_response}; use crate::pages::new_repo::{owner_choices, repo_owner}; +use crate::pages::repo_ctx::still_readable; use crate::state::AppState; -use crate::views::{alert, csrf_field, now_unix, relative_time, shell, user_facing_message}; +use crate::views::{alert, csrf_field, empty_state, rel_time, shell, user_facing_message}; path_param!(job_id); @@ -682,7 +682,7 @@ async fn bulk_select( if empty { -

        (g::t(lang, K::BulkNone))

        + empty_state(title: g::t(lang, K::BulkNone)) } else {
        if empty { -

        (g::t(lang, K::NoJobs))

        + empty_state(title: g::t(lang, K::NoJobs), + (g::t(lang, K::ImportTitle))) } else {
        job_rows(lang: lang, jobs: jobs) @@ -1195,10 +1202,7 @@ async fn job_page(cx: &Cx) -> Result { let lang = i18n::lang(cx, Some(&viewer.0)); let state = app_context::(cx); let job = owned_job(cx, &viewer.0).await?; - let repo = match &job.repo_id { - Some(id) => state.store.repo_by_id(id).await?, - None => None, - }; + let repo = job_repo(state, Some(&viewer.0), &job).await?; let log = state.store.list_import_events(&job.id, 200).await?; let csrf = viewer.1.csrf_token.clone(); let title = job.source_ref.clone(); diff --git a/crates/forge-web/src/pages/issues_list.rs b/crates/forge-web/src/pages/issues_list.rs index 9188473..ddf5ca0 100644 --- a/crates/forge-web/src/pages/issues_list.rs +++ b/crates/forge-web/src/pages/issues_list.rs @@ -26,8 +26,8 @@ use crate::pages::repo_ctx::{RepoHead, load_repo}; use crate::state::AppState; use crate::templates::{self, Template}; use crate::views::{ - alert, avatar_url, csrf_field, enc, iso_time, now_unix, relative_time, repo_href, shell, - user_facing_message, user_link, + alert, avatar_url, csrf_field, empty_state, enc, iso_time, now_unix, relative_time, repo_href, + shell, user_facing_message, user_link, }; use crate::webhooks::emit::{Sender, emit_issue}; @@ -484,7 +484,11 @@ async fn issues_list_page(cx: &Cx) -> Result { let labels_page_href = repo_href(&owner_name, &repo_name, "labels", ""); let milestones_href = repo_href(&owner_name, &repo_name, "milestones", ""); let title = g::issues_title(lang, &format!("{owner_name}/{repo_name}")); - let empty_text = g::t(lang, K::NoIssuesMatch); + let empty_text = if has_filters { + g::t(lang, K::NoIssuesMatch) + } else { + g::t(lang, K::NoIssuesYet) + }; let state_word = sel.state; let live_href = list_live_url(&owner_name, &repo_name); @@ -543,7 +547,17 @@ async fn issues_list_page(cx: &Cx) -> Result {
        } if rows.is_empty() { -

        (empty_text)

        + if has_filters { + empty_state(title: empty_text, + (g::t(lang, K::ClearFilters)) + ) + } else { + empty_state(title: empty_text, + if can_create { + (g::t(lang, K::NewIssue)) + } + ) + } } else {
          for row in rows.iter() { @@ -1020,7 +1034,7 @@ mod tests { } let empty = send(&fx.router, "GET", &base(), true, None, &[]).await; assert_eq!(empty.status, 200, "empty list"); - assert!(empty.text().contains("No issues match these filters.")); + assert!(empty.text().contains("No issues yet.")); assert_eq!(rows(&empty.text()), 0); let tr = send( &fx.router, @@ -1033,7 +1047,7 @@ mod tests { .await .text(); assert!(tr.contains(">Yeni sorun"), "{tr}"); - assert!(tr.contains("Bu filtrelerle eşleşen sorun yok."), "{tr}"); + assert!(tr.contains("Henüz sorun yok."), "{tr}"); // [refusals] an empty-title draft keeps its body and creates nothing; bad CSRF is 403. let draft = send( diff --git a/crates/forge-web/src/pages/labels_page.rs b/crates/forge-web/src/pages/labels_page.rs index ca6912d..a8c630a 100644 --- a/crates/forge-web/src/pages/labels_page.rs +++ b/crates/forge-web/src/pages/labels_page.rs @@ -21,7 +21,7 @@ use crate::pages::issues_live::list_live_url; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; use crate::state::AppState; -use crate::views::{enc, shell}; +use crate::views::{empty_state, enc, shell}; path_param!(owner); path_param!(repo); @@ -88,15 +88,16 @@ async fn labels_body(

          (g::t(lang, K::Labels))

          if empty { -

          (g::t(lang, K::NoLabelsYet))

          - if can_triage && !archived { -
          - -
          - -
          - - } + empty_state(title: g::t(lang, K::NoLabelsYet), + if can_triage && !archived { +
          + +
          + +
          + + } + ) }
            for row in rows.iter() { diff --git a/crates/forge-web/src/pages/merge_queue.rs b/crates/forge-web/src/pages/merge_queue.rs index 08aa832..4d08270 100644 --- a/crates/forge-web/src/pages/merge_queue.rs +++ b/crates/forge-web/src/pages/merge_queue.rs @@ -35,7 +35,7 @@ use crate::pages::pulls_merge::ERR_NOT_OPEN; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::state::AppState; -use crate::views::{repo_href, shell}; +use crate::views::{rel_time, repo_href, shell}; path_param!(owner); path_param!(repo); @@ -191,21 +191,13 @@ struct QueueRow { state: &'static str, state_class: &'static str, by: String, - queued: String, + queued_at: String, run_href: Option, run_label: String, reason: String, remove: bool, } -/// `2026-10-21T19:11:22.700Z` as `2026-10-21 19:11` (UTC), for the queue table. -fn stamp_minute(stamp: &str) -> String { - match stamp.get(..16) { - Some(minute) => minute.replace('T', " "), - None => stamp.to_owned(), - } -} - async fn queue_rows( state: &AppState, ctx: &RepoCtx, @@ -282,7 +274,7 @@ async fn queue_rows( state: state_label(lang, entry.state), state_class: state_class(entry.state), by, - queued: stamp_minute(&entry.enqueued_at), + queued_at: entry.enqueued_at.clone(), run_href, run_label, reason: entry @@ -403,7 +395,7 @@ async fn queue_body(
    - + - + if can_delete {
    (row.branch.as_str()) (row.state) (row.by.as_str())(row.queued.as_str())rel_time(lang: lang, stamp: row.queued_at.as_str()) if let Some(href) = row.run_href.as_ref() { (row.run_label.as_str()) diff --git a/crates/forge-web/src/pages/milestones_page.rs b/crates/forge-web/src/pages/milestones_page.rs index d1a07e0..58d78b2 100644 --- a/crates/forge-web/src/pages/milestones_page.rs +++ b/crates/forge-web/src/pages/milestones_page.rs @@ -25,7 +25,7 @@ use crate::pages::repo::repo_head; use crate::pages::repo_ctx::load_repo; use crate::render::markdown::render_markdown; use crate::state::AppState; -use crate::views::{enc, shell}; +use crate::views::{empty_state, enc, shell}; path_param!(owner); path_param!(repo); @@ -258,6 +258,11 @@ async fn milestones_body( let can_triage = frame.can_triage; let row_csrf = csrf.clone(); let header = frame.head.clone(); + let empty_text = if closed { + g::t(lang, K::NoClosedMilestones) + } else { + g::t(lang, K::NoOpenMilestones) + }; Ok(view! { repo_head(head: header) issue_subnav(lang: lang, title: title.clone(), active: "milestones".to_owned()) @@ -267,7 +272,7 @@ async fn milestones_body( state_tabs(lang: lang, title: title.clone(), closed: closed)
    if empty { -

    (if closed { g::t(lang, K::NoClosedMilestones) } else { g::t(lang, K::NoOpenMilestones) })

    + empty_state(title: empty_text) }
      for row in rows.into_iter() { diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 01b1630..e6da8d0 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -79,6 +79,7 @@ pub mod org_settings; pub mod org_teams; pub mod packages; pub mod packages_oci; +pub mod palette; pub mod passkeys; #[cfg(test)] mod passkeys_tests; diff --git a/crates/forge-web/src/pages/notifications.rs b/crates/forge-web/src/pages/notifications.rs index fc70228..d84beca 100644 --- a/crates/forge-web/src/pages/notifications.rs +++ b/crates/forge-web/src/pages/notifications.rs @@ -35,7 +35,7 @@ use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::pages::repo_transfer::transfer_list_for; use crate::pages::star::return_path; use crate::state::AppState; -use crate::views::{csrf_field, display_name, iso_time, now_unix, relative_time, repo_href, shell}; +use crate::views::{csrf_field, display_name, empty_state, iso_time, now_unix, relative_time, repo_href, shell}; /// Rows per inbox page. const PAGE_SIZE: u32 = 50; @@ -972,6 +972,11 @@ async fn inbox_list( live: String, ) -> Result { let empty = groups.is_empty(); + let empty_text = if all { + g::t(lang, K::NoNotificationsYet) + } else { + g::t(lang, K::NoUnreadNotifications) + }; let unread_class = if all { "" } else { "active" }; let all_class = if all { "active" } else { "" }; let unread_text = format!("{} ({unread_count})", g::t(lang, K::Unread)); @@ -992,13 +997,10 @@ async fn inbox_list( (crate::i18n::authoring::t(lang, crate::i18n::authoring::K::ReviewRequestsTab)) if empty { -

      - if all { - (g::t(lang, K::NoNotificationsYet)) - } else { - (g::t(lang, K::NoUnreadNotifications)) - } -

      + empty_state(title: empty_text, + if !all { + (g::t(lang, K::ViewAllNotifications)) + }) } for group in groups.into_iter() {
      diff --git a/crates/forge-web/src/pages/org_teams.rs b/crates/forge-web/src/pages/org_teams.rs index d6092a1..e8e8798 100644 --- a/crates/forge-web/src/pages/org_teams.rs +++ b/crates/forge-web/src/pages/org_teams.rs @@ -24,7 +24,7 @@ use crate::pages::org_ctx::{ }; use crate::pages::passkeys; use crate::state::AppState; -use crate::views::{avatar_url, display_name, repo_href, shell}; +use crate::views::{avatar_url, display_name, empty_state, repo_href, shell}; path_param!(org); path_param!(team); @@ -199,7 +199,10 @@ async fn teams_body(

      (g::t(lang, K::Teams))

      (g::t(lang, K::TeamsIntro))

      if rows.is_empty() { -

      (g::t(lang, K::NoTeamsYet))

      + empty_state(title: g::t(lang, K::NoTeamsYet), + if owner { + (g::t(lang, K::NewTeam)) + }) } else {
        for row in rows.iter() { @@ -217,7 +220,7 @@ async fn teams_body( }
      if owner { -
      +

      (g::t(lang, K::NewTeam))

      @@ -347,7 +350,10 @@ async fn team_body(

      (g::t(lang, K::Members))

      if data.members.is_empty() { -

      (g::t(lang, K::NoTeamMembers))

      + empty_state(title: g::t(lang, K::NoTeamMembers), + if owner { + (g::t(lang, K::AddMember)) + }) } else {
        for member in data.members.iter() { @@ -375,7 +381,7 @@ async fn team_body(
      } if owner { - + @@ -385,7 +391,10 @@ async fn team_body(

      (g::t(lang, K::Repositories))

      if data.repos.is_empty() { -

      (g::t(lang, K::NoTeamRepos))

      + empty_state(title: g::t(lang, K::NoTeamRepos), + if owner && has_choices { + (g::t(lang, K::LinkRepository)) + }) } else {
        for repo in data.repos.iter() { @@ -410,7 +419,7 @@ async fn team_body(
      } if owner && has_choices { - +
    (tag.as_str()) (short.as_str()) (size.as_str())(created.as_str())rel_time(lang: lang, stamp: created.as_str())
    @@ -187,7 +187,7 @@ pub async fn oci_package_view(page: OciPage) -> Result {
    } else { -

    (pk::t(lang, K::NoTags))

    + empty_state(title: pk::t(lang, K::NoTags)) } diff --git a/crates/forge-web/src/pages/palette.rs b/crates/forge-web/src/pages/palette.rs new file mode 100644 index 0000000..b9f9b49 --- /dev/null +++ b/crates/forge-web/src/pages/palette.rs @@ -0,0 +1,74 @@ +//! The command palette's destinations: `GET /-/palette` lists what the signed-in viewer can jump to, +//! their repos, the orgs they belong to and the fixed pages (the sidebar's links, the settings pages +//! and, for admins, the admin pages). The palette itself, its filtering and keys live in +//! `assets/nav.js`. + +use http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; +use serde_json::{Value, json}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::response::Response; +use topcoat::router::{Body, HeaderValue, StatusCode, route}; + +use crate::auth::current_user; +use crate::i18n::community::{self as cm, K as CK}; +use crate::i18n::orgs::{self as o, K as OK}; +use crate::i18n::{self, Key, t}; +use crate::state::AppState; +use crate::views::{admin_items, repo_href, settings_items, user_href}; + +/// Repos listed at most. The palette filters in the browser, so a longer list would only cost time. +pub const MAX_REPOS: u64 = 500; + +/// One destination: its label, its path and what it is (`repo`, `org` or `page`). +fn destination(label: &str, href: &str, kind: &str) -> Value { + json!({ "label": label, "href": href, "kind": kind }) +} + +/// `{"items": [{"label", "href", "kind"}, ...]}` for the signed-in viewer. Anonymous visitors get +/// 401, as the other signed-in-only JSON routes do. +#[route(GET "/-/palette")] +async fn palette(cx: &Cx) -> Result { + let Some((user, _)) = current_user(cx).await? else { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(res); + }; + let state = app_context::(cx); + let lang = i18n::lang(cx, Some(&user)); + + let mut items = Vec::new(); + for repo in state.store.list_viewer_repos(&user, MAX_REPOS).await? { + let label = format!("{}/{}", repo.owner_name, repo.name); + let href = repo_href(&repo.owner_name, &repo.name, "", ""); + items.push(destination(&label, &href, "repo")); + } + for (org, _) in state.store.orgs_for_user(&user.id).await? { + items.push(destination(&org.username, &user_href(&org.username), "org")); + } + + items.push(destination(o::t(lang, OK::Dashboard), "/", "page")); + items.push(destination(t(lang, Key::Explore), "/explore", "page")); + items.push(destination(t(lang, Key::Notifications), "/notifications", "page")); + items.push(destination(cm::t(lang, CK::Snippets), "/snippets", "page")); + items.push(destination(t(lang, Key::NewRepository), "/new", "page")); + for item in settings_items(lang) { + items.push(destination(item.label, &item.href, "page")); + } + if user.is_admin { + for item in admin_items(lang) { + items.push(destination(item.label, &item.href, "page")); + } + } + + let body = json!({ "items": items }); + let mut response = Response::new(Body::from(body.to_string().into_bytes())); + let headers = response.headers_mut(); + headers.insert( + CONTENT_TYPE, + HeaderValue::from_static("application/json; charset=utf-8"), + ); + headers.insert(CACHE_CONTROL, HeaderValue::from_static("private, no-cache")); + headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); + Ok(response) +} diff --git a/crates/forge-web/src/pages/profile.rs b/crates/forge-web/src/pages/profile.rs index b45d96d..026019e 100644 --- a/crates/forge-web/src/pages/profile.rs +++ b/crates/forge-web/src/pages/profile.rs @@ -32,7 +32,7 @@ use crate::state::AppState; use crate::views::repo_list::{ PageLink, RepoRow, SortLink, pager, pager_links, repo_rows, sort_chips, }; -use crate::views::{avatar_url, enc, now_unix, repo_href, shell}; +use crate::views::{avatar_url, empty_state, enc, now_unix, repo_href, shell}; path_param!(username); @@ -539,7 +539,7 @@ async fn profile_card( } } else { -

    (g::t(lang, K::NoVisibleRepos))

    + empty_state(title: g::t(lang, K::NoVisibleRepos)) } if let Some(summary) = org { @@ -547,7 +547,7 @@ async fn profile_card(

    (g::t(lang, K::Members))

    (g::members_and_teams(lang, summary.members.len(), summary.teams))

    if summary.members.is_empty() { -

    (g::t(lang, K::NoMembers))

    + empty_state(title: g::t(lang, K::NoMembers)) } else {