From c812504a9bcc48c0950d1f69f878aeaff146e97f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 31 Oct 2026 08:52:38 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20the=20sidebar=20and=20dashb?= =?UTF-8?q?oard=20are=20gone:=20/=20opens=20your=20profile,=20which=20hold?= =?UTF-8?q?s=20the=20contribution=20calendar=20and=20tabs=20for=20Reposito?= =?UTF-8?q?ries=20(with=20New=20repository),=20Snippets,=20Stars,=20Packag?= =?UTF-8?q?es=20and=20Organizations=20(with=20New=20organization),=20and?= =?UTF-8?q?=20a=20sidebar=20stays=20only=20on=20section=20pages;=20the=20p?= =?UTF-8?q?rofile=20corner=20is=20a=20floating=20panel,=20bottom=20left=20?= =?UTF-8?q?by=20default,=20that=20can=20be=20dragged=20anywhere=20and=20re?= =?UTF-8?q?set=20with=20a=20double=20click;=20organizations=20get=20a=20re?= =?UTF-8?q?al=20profile=20with=20New=20repository,=20Members,=20Teams=20an?= =?UTF-8?q?d=20Settings,=20and=20their=20settings=20take=20a=20display=20n?= =?UTF-8?q?ame=20and=20an=20avatar;=20failed=20bulk=20imports=20can=20be?= =?UTF-8?q?=20retried=20from=20a=20checklist=20with=20a=20token;=20a=20sig?= =?UTF-8?q?ned-in=20user's=20tree=20width,=20panel=20position,=20diff=20vi?= =?UTF-8?q?ew=20and=20banner=20dismissal=20are=20stored=20in=20the=20datab?= =?UTF-8?q?ase=20(migration=200069);=20=F0=9F=90=9B=20fix:=20a=20form=20th?= =?UTF-8?q?e=20server=20refuses=20keeps=20its=20address,=20so=20a=20live?= =?UTF-8?q?=20refresh=20no=20longer=20lands=20on=20a=20405=20page=20after?= =?UTF-8?q?=20a=20wrong=20repo=20transfer;=20the=20Recent=20imports=20card?= =?UTF-8?q?=20matches=20the=20import=20form's=20width=20and=20no=20longer?= =?UTF-8?q?=20touches=20it;=20deleting=20a=20repo=20returns=20to=20the=20o?= =?UTF-8?q?wner's=20Repositories=20tab=20with=20its=20notice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../forge-core/migrations/0069_user_prefs.sql | 11 + crates/forge-core/src/store/migrate.rs | 1 + crates/forge-core/src/store/mod.rs | 1 + crates/forge-core/src/store/snippets.rs | 53 ++- crates/forge-core/src/store/user_delete.rs | 1 + crates/forge-core/src/store/user_prefs.rs | 55 +++ crates/forge-web/assets/nav.js | 207 +++++++-- crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/i18n/migrate.rs | 15 + crates/forge-web/src/i18n/misc.rs | 40 -- crates/forge-web/src/i18n/orgs.rs | 44 +- crates/forge-web/src/importer/mod.rs | 1 + crates/forge-web/src/importer/tests.rs | 61 ++- crates/forge-web/src/live.rs | 2 +- crates/forge-web/src/pages/banner.rs | 33 +- crates/forge-web/src/pages/commit.rs | 3 +- crates/forge-web/src/pages/compare.rs | 3 +- crates/forge-web/src/pages/dashboard.rs | 401 ------------------ crates/forge-web/src/pages/home.rs | 47 ++ crates/forge-web/src/pages/import.rs | 204 ++++++++- crates/forge-web/src/pages/mod.rs | 4 +- crates/forge-web/src/pages/new_repo.rs | 20 +- crates/forge-web/src/pages/notifications.rs | 10 +- crates/forge-web/src/pages/org_ctx.rs | 2 + crates/forge-web/src/pages/org_settings.rs | 236 +++++++++-- crates/forge-web/src/pages/palette.rs | 6 +- crates/forge-web/src/pages/profile.rs | 245 ++++++++++- .../forge-web/src/pages/profile_calendar.rs | 92 ++++ crates/forge-web/src/pages/pull_files.rs | 2 +- crates/forge-web/src/pages/repo.rs | 2 +- crates/forge-web/src/pages/repo_settings.rs | 13 +- .../forge-web/src/pages/settings_profile.rs | 14 +- crates/forge-web/src/pages/setup.rs | 8 +- crates/forge-web/src/pages/shell_events.rs | 18 +- crates/forge-web/src/pages/snippets.rs | 57 ++- crates/forge-web/src/pages/user_prefs.rs | 158 +++++++ crates/forge-web/src/post_update.rs | 4 +- crates/forge-web/src/test_support.rs | 3 +- crates/forge-web/src/views/diff.rs | 66 ++- crates/forge-web/src/views/heatmap.rs | 18 +- crates/forge-web/src/views/mod.rs | 274 ++++-------- crates/forge-web/src/views/repo_list.rs | 9 +- crates/forge-web/tests/e2e/browse_e2e.rs | 14 +- crates/forge-web/tests/e2e/orgs_ui_e2e.rs | 7 +- .../forge-web/tests/e2e/repo_settings_e2e.rs | 20 +- style/_dashboard.scss | 273 ------------ style/_heatmap.scss | 2 +- style/_import.scss | 6 + style/_shell.scss | 277 +++++------- style/main.scss | 21 +- 50 files changed, 1708 insertions(+), 1357 deletions(-) create mode 100644 crates/forge-core/migrations/0069_user_prefs.sql create mode 100644 crates/forge-core/src/store/user_prefs.rs delete mode 100644 crates/forge-web/src/pages/dashboard.rs create mode 100644 crates/forge-web/src/pages/home.rs create mode 100644 crates/forge-web/src/pages/profile_calendar.rs create mode 100644 crates/forge-web/src/pages/user_prefs.rs delete mode 100644 style/_dashboard.scss diff --git a/crates/forge-core/migrations/0069_user_prefs.sql b/crates/forge-core/migrations/0069_user_prefs.sql new file mode 100644 index 0000000..5e03e25 --- /dev/null +++ b/crates/forge-core/migrations/0069_user_prefs.sql @@ -0,0 +1,11 @@ +-- Account preferences that do not fit a column of `users`: the tree width, the profile corner's +-- position and similar. One row per user and key; the web layer decides the keys and values, and +-- a value of "" never reaches here (it deletes the row). Applied by store/migrate.rs. + +CREATE TABLE user_prefs ( + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + key TEXT NOT NULL, + value TEXT NOT NULL, + updated_at TEXT NOT NULL, + PRIMARY KEY (user_id, key) +); diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index c849a62..cb0f194 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -108,6 +108,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (66, include_str!("../../migrations/0066_session_ip.sql")), (67, include_str!("../../migrations/0067_coauthored_commits.sql")), (68, include_str!("../../migrations/0068_ci_jobs_runner.sql")), + (69, include_str!("../../migrations/0069_user_prefs.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 9ff3304..9498999 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -48,6 +48,7 @@ pub mod suspension; pub mod transfers; pub mod ui_prefs; pub mod user_delete; +pub mod user_prefs; pub mod web_push; pub mod webhooks; pub mod wiki; diff --git a/crates/forge-core/src/store/snippets.rs b/crates/forge-core/src/store/snippets.rs index b001e1a..0f46b89 100644 --- a/crates/forge-core/src/store/snippets.rs +++ b/crates/forge-core/src/store/snippets.rs @@ -202,6 +202,20 @@ fn map_snippet(row: &turso::Row) -> Result { }) } +/// One row of the summary queries: id, owner name, title, visibility, update stamp, file count. +fn summary_row(row: &turso::Row) -> Result { + let visibility = col_text(row, 3)?; + Ok(SnippetSummary { + id: col_text(row, 0)?, + owner_name: col_text(row, 1)?, + title: col_text(row, 2)?, + visibility: SnippetVisibility::parse(&visibility) + .ok_or_else(|| Error::Database(format!("unknown snippet visibility {visibility}")))?, + updated_at: col_text(row, 4)?, + file_count: u64::try_from(col_int(row, 5)?).unwrap_or(0), + }) +} + fn map_file(row: &turso::Row) -> Result { Ok(SnippetFile { name: col_text(row, 0)?, @@ -411,19 +425,32 @@ impl Store { WHERE s.visibility = 'public' OR s.owner_id = ?1 \ ORDER BY s.updated_at DESC, s.id DESC LIMIT ?2", (viewer_id.unwrap_or("").to_string(), LIST_LIMIT), - |row| { - let visibility = col_text(row, 3)?; - Ok(SnippetSummary { - id: col_text(row, 0)?, - owner_name: col_text(row, 1)?, - title: col_text(row, 2)?, - visibility: SnippetVisibility::parse(&visibility).ok_or_else(|| { - Error::Database(format!("unknown snippet visibility {visibility}")) - })?, - updated_at: col_text(row, 4)?, - file_count: u64::try_from(col_int(row, 5)?).unwrap_or(0), - }) - }, + summary_row, + ) + .await + } + + /// The snippets `owner_id` owns that the viewer can list: their public ones, and all of them + /// when the viewer is the owner. Unlisted ones are left out, as on `list_snippets`. Newest first. + pub async fn list_owner_snippets( + &self, + owner_id: &str, + viewer_id: Option<&str>, + ) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT s.id, u.username, s.title, s.visibility, s.updated_at, \ + (SELECT COUNT(*) FROM snippet_files f WHERE f.snippet_id = s.id) \ + FROM snippets s JOIN users u ON u.id = s.owner_id \ + WHERE s.owner_id = ?1 AND (s.visibility = 'public' OR s.owner_id = ?2) \ + ORDER BY s.updated_at DESC, s.id DESC LIMIT ?3", + ( + owner_id.to_string(), + viewer_id.unwrap_or("").to_string(), + LIST_LIMIT, + ), + summary_row, ) .await } diff --git a/crates/forge-core/src/store/user_delete.rs b/crates/forge-core/src/store/user_delete.rs index 85a8548..b214cf8 100644 --- a/crates/forge-core/src/store/user_delete.rs +++ b/crates/forge-core/src/store/user_delete.rs @@ -138,6 +138,7 @@ const REMOVED: &[(&str, &str, &str)] = &[ ), ("admin notifications", "admin_notifications", "user_id"), ("reactions", "reactions", "user_id"), + ("preferences", "user_prefs", "user_id"), ("review requests", "review_requests", "reviewer_id"), ]; diff --git a/crates/forge-core/src/store/user_prefs.rs b/crates/forge-core/src/store/user_prefs.rs new file mode 100644 index 0000000..b0b7b03 --- /dev/null +++ b/crates/forge-core/src/store/user_prefs.rs @@ -0,0 +1,55 @@ +//! Account preferences that are not columns of `users`: one text value per user and key, in +//! `user_prefs` (migration 0069). The web layer decides which keys exist and what each value may +//! be; this store only keeps the rows. Rows go with the user (ON DELETE CASCADE). + +use std::collections::HashMap; + +use super::{Store, col_text, db_err, fetch_all}; +use crate::error::Result; +use crate::time::now_stamp; + +impl Store { + /// All of a user's preferences as `key -> value`. + pub async fn user_prefs(&self, user_id: &str) -> Result> { + let conn = self.read_conn().await; + let rows = fetch_all( + &conn, + "SELECT key, value FROM user_prefs WHERE user_id = ?1", + (user_id.to_string(),), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await?; + Ok(rows.into_iter().collect()) + } + + /// Stores `value` under `key` for the user, replacing an earlier value. + pub async fn set_user_pref(&self, user_id: &str, key: &str, value: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO user_prefs (user_id, key, value, updated_at) VALUES (?1, ?2, ?3, ?4) \ + ON CONFLICT (user_id, key) DO UPDATE SET \ + value = excluded.value, updated_at = excluded.updated_at", + ( + user_id.to_string(), + key.to_string(), + value.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Removes one preference. A key the user never set is not an error. + pub async fn delete_user_pref(&self, user_id: &str, key: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM user_prefs WHERE user_id = ?1 AND key = ?2", + (user_id.to_string(), key.to_string()), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 8565827..dac1a43 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -17,6 +17,7 @@ var inFlight = 0; // requests on the wire, drives aria-busy var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored var queued = new WeakSet(); // forms that changed while pending: submitted again once it completes + var heldForm = false; // a rejected form is on screen; see load() var shown = location.pathname + location.search; var GET_INIT = { headers: { accept: 'text/html' } }; @@ -427,6 +428,12 @@ } var dest = new URL(res.url.href); dest.hash = o.dest.hash; + // A form the server refused comes back as a page under the POST's URL, which may have no GET. + // The address stays on the page the form was sent from, and live refreshes wait, because one + // would replace the error with a fresh page. The next navigation ends the wait. + var refused = o.post && !res.redirected; + if (refused) { dest = new URL(location.href); } + if (o.how !== 'live') { heldForm = refused; } // A live refresh that lands on another path (a revoked session sent to the login page) is a // 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; @@ -564,8 +571,8 @@ // Every page holds one stream to /-/shell/events (`/-/alive` for a page from before a deploy, and for // an anonymous visitor the same alive events). Its error means the server, or the proxy in front of - // it, is down; its open means it is back. Signed-in viewers also get `unread` (the inbox count), - // `activity` (the live strip and ring) and `side` (the sidebar's repo list) on the same connection. + // it, is down; its open means it is back. Signed-in viewers also get `unread` (the inbox count) and + // `activity` (the live strip and ring) on the same connection. // A `theme` event carries the signed-in user's appearance as `name=value` pairs joined by `;` // (the `` attributes). An empty value removes the attribute. Only data-* names are applied. function applyAppearance(data) { @@ -613,9 +620,7 @@ // The inbox count changed (see `unreadChanged` above). unread: unreadChanged, // The viewer's activity changed: the strip, ring and chips are fetched again. - activity: function () { refreshActivity(); }, - // The sidebar's repo list changed (the sidebar is re-rendered with the page). - side: sideChanged + activity: function () { refreshActivity(); } }); document.addEventListener('visibilitychange', function () { wake(false); }); document.addEventListener('resume', function () { wake(true); }); @@ -643,11 +648,11 @@ } // Dropdown menus: the
that float over the page (avatar menu, branch selector, clone - // popover, phone menu, profile corner). Inline disclosures are not listed: a click outside leaves them open. + // popover, section menu, profile corner). Inline disclosures are not listed: a click outside leaves them open. var DROPDOWN = 'details.menu, details.ref-select, details.clone, details.nav-toggle, details.corner, details.strip-runs'; - // Closes every open dropdown that does not contain `from` (pass null to close them all). The corner - // sits inside the phone menu, so a click in the corner keeps the phone menu open too. + // Closes every open dropdown that does not contain `from` (pass null to close them all). A click + // inside the floating corner keeps its own menu open. function closeDropdowns(from) { document.querySelectorAll(DROPDOWN).forEach(function (d) { if (d.open && !(from && d.contains(from))) { d.open = false; } @@ -706,6 +711,138 @@ closeDropdowns(e.target && e.target.nodeType === 1 ? e.target : null); }, false); + // The profile corner can be dragged anywhere on the window. A press records its start; it becomes a + // drag after CORNER_SLOP px of movement, and then the panel follows the pointer, clamped to the + // window. The released position is kept as fractions of the free space, so it holds at any size. + var CORNER_SLOP = 5; + var cornerPress = null; // { el, id, x, y, left, top, dragging } from a press to its release + var cornerSwallow = false; // the click that ends a drag must not open the menu or the bell + + function parseCorner(text) { + var parts = String(text || '').split(','); + if (parts.length !== 2) { return null; } + var x = parseFloat(parts[0]), y = parseFloat(parts[1]); + if (!isFinite(x) || !isFinite(y)) { return null; } + return [Math.min(1, Math.max(0, x)), Math.min(1, Math.max(0, y))]; + } + // [x, y] fractions of the stored position, or null for the default corner. Kept current by drags and resets. + var cornerSaved = parseCorner(document.body.dataset.cornerPos); + + // Registered before the bell's click listener below, so it runs first and stops the click that + // follows a drag once. + window.addEventListener('click', function (e) { + if (!cornerSwallow) { return; } + cornerSwallow = false; + e.preventDefault(); + e.stopImmediatePropagation(); + }, true); + + function cornerEl() { return document.querySelector('.corner-float'); } + + // The menu opens down when the panel is in the top half of the window, and anchors to the right + // edge when the panel is in the right half. The default corner (no attribute) opens up, as before. + function cornerDirection(el, left, top, w, h) { + if (top + h / 2 < window.innerHeight / 2) { el.setAttribute('data-open', 'down'); } else { el.removeAttribute('data-open'); } + if (left + w / 2 > window.innerWidth / 2) { el.setAttribute('data-side', 'right'); } else { el.removeAttribute('data-side'); } + } + + // Places the panel at (left, top) in px, clamped so the whole panel stays in the window. + function cornerPlace(el, left, top) { + var w = el.offsetWidth, h = el.offsetHeight; + left = Math.max(0, Math.min(left, window.innerWidth - w)); + top = Math.max(0, Math.min(top, window.innerHeight - h)); + el.style.left = left + 'px'; + el.style.top = top + 'px'; + el.style.right = 'auto'; + el.style.bottom = 'auto'; + cornerDirection(el, left, top, w, h); + } + + // Puts the panel where the stored position says, or in the default corner. It does nothing while a + // drag runs, so a re-render or a resize does not pull the panel from under the pointer. + function cornerApply() { + var el = cornerEl(); + if (!el || (cornerPress && cornerPress.dragging)) { return; } + if (cornerSaved) { + cornerPlace(el, cornerSaved[0] * (window.innerWidth - el.offsetWidth), cornerSaved[1] * (window.innerHeight - el.offsetHeight)); + return; + } + el.style.left = ''; + el.style.top = ''; + el.style.right = ''; + el.style.bottom = ''; + var r = el.getBoundingClientRect(); + cornerDirection(el, r.left, r.top, el.offsetWidth, el.offsetHeight); + } + + // Saves one account preference through /-/prefs, signed in only (the CSRF token comes from the + // panel). Saves go one after another, and `read` gives the value at the moment of sending, so the + // last one sent holds the newest value. A failure is ignored: the next load shows what the server has. + var prefsChain = Promise.resolve(); + function prefSave(key, read) { + prefsChain = prefsChain.then(function () { + var el = document.querySelector('.corner-float[data-prefs-csrf]'); + var body = new URLSearchParams({ csrf: el ? el.getAttribute('data-prefs-csrf') : '', key: key, value: read() }); + return fetch('/-/prefs', { method: 'POST', credentials: 'same-origin', body: body }); + }).catch(function () { }); + } + + document.addEventListener('pointerdown', function (e) { + cornerSwallow = false; + var el = e.target && e.target.closest ? e.target.closest('.corner-float') : null; + if (!el || e.button !== 0) { cornerPress = null; return; } + var r = el.getBoundingClientRect(); + cornerPress = { el: el, id: e.pointerId, x: e.clientX, y: e.clientY, left: r.left, top: r.top, dragging: false }; + }); + + document.addEventListener('pointermove', function (e) { + var p = cornerPress; + if (!p || e.pointerId !== p.id) { return; } + if (!p.dragging) { + if (Math.hypot(e.clientX - p.x, e.clientY - p.y) < CORNER_SLOP) { return; } + p.dragging = true; + try { p.el.setPointerCapture(p.id); } catch (err) { } + p.el.classList.add('dragging'); + } + cornerPlace(p.el, p.left + e.clientX - p.x, p.top + e.clientY - p.y); + }); + + function cornerEnd(e) { + var p = cornerPress; + if (!p || e.pointerId !== p.id) { return; } + cornerPress = null; + if (!p.dragging) { return; } + p.el.classList.remove('dragging'); + if (e.type === 'pointercancel') { cornerApply(); return; } + cornerSwallow = true; + // A swap that replaced the panel during the drag leaves the new one to the stored position. + if (!p.el.isConnected) { cornerApply(); return; } + var room = { x: window.innerWidth - p.el.offsetWidth, y: window.innerHeight - p.el.offsetHeight }; + var x = room.x > 0 ? Math.round(10000 * (parseFloat(p.el.style.left) || 0) / room.x) / 10000 : 0; + var y = room.y > 0 ? Math.round(10000 * (parseFloat(p.el.style.top) || 0) / room.y) / 10000 : 0; + x = Math.min(1, Math.max(0, x)); + y = Math.min(1, Math.max(0, y)); + cornerSaved = [x, y]; + prefSave('corner_pos', function () { return x + ',' + y; }); + } + document.addEventListener('pointerup', cornerEnd); + document.addEventListener('pointercancel', cornerEnd); + + // A double click on the panel, not on a link or a button, returns it to the default corner. + document.addEventListener('dblclick', function (e) { + var target = e.target; + if (!target || !target.closest || target.closest('a, button, input, select, textarea, summary, label, [role="button"]')) { return; } + var el = target.closest('.corner-float'); + if (!el) { return; } + cornerSaved = null; + prefSave('corner_pos', function () { return ''; }); + cornerApply(); + }); + + document.addEventListener('forge:swapped', cornerApply); + window.addEventListener('resize', cornerApply); + cornerApply(); + // The bell beside the profile corner opens a popover of the newest notifications instead of going // to the inbox. A plain click toggles it; with a modifier or a middle click the link's own // behaviour stays. The Popover API light-dismisses it and Escape closes it. Its list is fetched @@ -718,12 +855,20 @@ // Under the bell, opening upward: the popover's bottom sits 6px above the bell's top, and its left // edge follows the bell but stays inside the viewport. + // When the panel sits in the top half (data-open="down" on it), the popover opens below the bell. function placePeek(bell, pop) { if (!bell) { return; } var r = bell.getBoundingClientRect(); var left = Math.max(8, Math.min(r.left, window.innerWidth - pop.offsetWidth - 8)); pop.style.left = left + 'px'; - pop.style.bottom = (window.innerHeight - r.top + 6) + 'px'; + var corner = bell.closest('.corner-float'); + if (corner && corner.getAttribute('data-open') === 'down') { + pop.style.top = (r.bottom + 6) + 'px'; + pop.style.bottom = 'auto'; + } else { + pop.style.top = 'auto'; + pop.style.bottom = (window.innerHeight - r.top + 6) + 'px'; + } } // Fills the popover's list with the server's fragment. A reader who closed it meanwhile, or a newer @@ -793,7 +938,7 @@ } }, true); - // A page swap replaces the sidebar; an open popover goes with the page it was opened on. + // A page swap re-renders the page and its corner; an open popover goes with the page it was opened on. document.addEventListener('forge:swapped', function () { document.querySelectorAll('.bell-pop').forEach(function (pop) { try { pop.hidePopover(); } catch (err) { } @@ -803,17 +948,33 @@ // Repo home resize: a drag on the separator between the file tree and the README sets the tree's // width, the --tree-w property of the .repo-home grid. The width is kept in localStorage and applied // to each repo home on load and after every swap. The README takes the rest of the row. - var TREE_KEY = 'forge-tree-w'; + var TREE_KEY = 'forge-tree-w'; // signed-out visitors keep the width in localStorage + // Signed in, the width is the account's tree_width preference. The variable starts from the page's + // data-tree-w and follows every change, so a swap never reads back an older value. + var signedIn = document.body.dataset.signedIn === 'true'; + var treeAccount = parseFloat(document.body.dataset.treeW) || 0; + var treeTimer = null; var TREE_MIN = 220; // px, the narrowest the tree goes var README_MIN = 360; // px, room the drag always leaves for the README var TREE_STEP = 16; // px per arrow key; Shift moves 64px var treeDrag = null; // { grid, id, x, w, moved } while a pointer drag runs function treeLoad() { + if (signedIn) { return treeAccount; } try { return parseFloat(localStorage.getItem(TREE_KEY)) || 0; } catch (err) { return 0; } } function treeStore(px) { + if (signedIn) { + treeAccount = px ? Math.round(px) : 0; + // One save once the changes settle, not one per step of a drag or a key repeat. + clearTimeout(treeTimer); + treeTimer = setTimeout(function () { + treeTimer = null; + prefSave('tree_width', function () { return treeAccount ? String(treeAccount) : ''; }); + }, 300); + return; + } try { if (px) { localStorage.setItem(TREE_KEY, String(Math.round(px))); } else { localStorage.removeItem(TREE_KEY); } } catch (err) { } @@ -1812,8 +1973,8 @@ // Live unread count. The profile corner (data-unread-stream) is re-rendered by every swap, so it is // looked up on each update. The count arrives as an `unread` event of the shell stream (see // `/-/shell/events`, opened with the alive handlers above), which the server pushes on each change; - // nothing polls. Each `unread` event also refreshes the activity (below). The count shows twice: as - // a dot on the menu toggle (has-dot), and next to Notifications in the sidebar and the phone menu. + // nothing polls. Each `unread` event also refreshes the activity (below). The count shows on the + // bell of the floating profile corner. // Shows the count in one link the way the server renders it: a span with the number, or no span at zero. function setCount(el, cls, n) { @@ -1831,12 +1992,9 @@ } function setUnread(n) { - // The menu toggle carries a dot while anything is unread. - var toggles = document.querySelectorAll('details.nav-toggle > summary'); - for (var t = 0; t < toggles.length; t++) { toggles[t].classList.toggle('has-dot', n > 0); } - // The sidebar's Notifications link (the sidebar and the phone menu hold one each), `.count` as the server renders it. - var links = document.querySelectorAll('nav.side-links a[href="/notifications"]'); - for (var i = 0; i < links.length; i++) { setCount(links[i], 'count', n); } + // The bell of the profile corner, `.bell-count` as the server renders it. + var bells = document.querySelectorAll('.corner-bell'); + for (var i = 0; i < bells.length; i++) { setCount(bells[i], 'bell-count', n); } } // An `unread` event: the count, then the activity is fetched again. @@ -2574,15 +2732,6 @@ return es; } - // A `side` event of the shell stream: the sidebar's repo list changed. The page is re-rendered with - // it, as a `changed` event of a data-live stream would, but at most once a second (a code view or a - // live-now page re-renders at once). - function sideChanged() { - if (document.querySelector('[data-live-code], [data-live-now]')) { refreshLive(true); return; } - if (liveTimer) { return; } - liveTimer = setTimeout(function () { liveTimer = null; refreshLive(true); }, 1000); - } - // Closes the streams the page no longer names and opens the ones it newly names. function syncLive() { var want = liveWanted(); @@ -2642,6 +2791,8 @@ // A one-time secret (a token, recovery codes) is on screen only in the response that made it: a // re-render would take it away. The page is refreshed at the next navigation instead. if (document.querySelector('[data-once]')) { return; } + // A rejected form is on screen: a re-render would replace its error. See load(). + if (heldForm) { return; } if (userBusy > 0 || liveBusy || selecting()) { liveDirty = true; if (force) { liveForced = true; } return; } liveDirty = false; liveForced = false; diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 884f771..755cf04 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -172,6 +172,7 @@ pub async fn serve( .layer(crate::pages::settings_live::AccountWriteLayer) .cookies() .layer(crate::pages::settings_profile::avatar_body_limit()) + .layer(crate::pages::settings_profile::org_avatar_body_limit()) .layer(crate::pages::repo_ctx::RepoMovedLayer) .layer(crate::pages::pull_live::PullWriteLayer) .layer(crate::pages::discussion_live::DiscussionWriteLayer) diff --git a/crates/forge-web/src/i18n/migrate.rs b/crates/forge-web/src/i18n/migrate.rs index 242379f..aa6a192 100644 --- a/crates/forge-web/src/i18n/migrate.rs +++ b/crates/forge-web/src/i18n/migrate.rs @@ -67,6 +67,10 @@ pub enum K { JobProgress, JobNoLog, JobStarted, + RetryFailedTitle, + RetrySelected, + RetryNone, + RetryTokenHelp, StageGit, StageLabels, StageMilestones, @@ -155,6 +159,10 @@ const ALL: &[K] = &[ K::JobProgress, K::JobNoLog, K::JobStarted, + K::RetryFailedTitle, + K::RetrySelected, + K::RetryNone, + K::RetryTokenHelp, K::StageGit, K::StageLabels, K::StageMilestones, @@ -278,6 +286,13 @@ fn pair(key: K) -> (&'static str, &'static str) { K::JobProgress => ("Progress", "İlerleme"), K::JobNoLog => ("Nothing yet.", "Henüz bir şey yok."), K::JobStarted => ("Started", "Başladı"), + K::RetryFailedTitle => ("Retry failed imports", "Başarısız içe aktarmaları yeniden dene"), + K::RetrySelected => ("Retry selected", "Seçilenleri yeniden dene"), + K::RetryNone => ("No failed imports", "Başarısız içe aktarma yok"), + K::RetryTokenHelp => ( + "Used for every import you select, then discarded. Retry imports from another account or provider separately with their own token. What was already imported is skipped.", + "Seçtiğiniz her içe aktarma için kullanılır, sonra silinir. Başka bir hesap veya sağlayıcıdan gelen içe aktarmaları kendi belirteçleriyle ayrı olarak yeniden deneyin. Daha önce içe aktarılanlar atlanır.", + ), K::StageGit => ("Git data", "Git verisi"), K::StageLabels => ("Labels", "Etiketler"), K::StageMilestones => ("Milestones", "Kilometre taşları"), diff --git a/crates/forge-web/src/i18n/misc.rs b/crates/forge-web/src/i18n/misc.rs index 1aa1c52..4e0a18d 100644 --- a/crates/forge-web/src/i18n/misc.rs +++ b/crates/forge-web/src/i18n/misc.rs @@ -158,12 +158,6 @@ pub enum K { WedLabel, FriLabel, NoContributionsDay, - // Dashboard greeting and "Needs your attention" column. - GoodMorning, - GoodAfternoon, - GoodEvening, - NeedsAttention, - NothingNeedsYou, ViewAllNotifications, // Shell chrome (`views::mod`): breadcrumb landmark, theme picker, ref selector. BreadcrumbNav, @@ -323,11 +317,6 @@ const ALL: &[K] = &[ K::WedLabel, K::FriLabel, K::NoContributionsDay, - K::GoodMorning, - K::GoodAfternoon, - K::GoodEvening, - K::NeedsAttention, - K::NothingNeedsYou, K::ViewAllNotifications, K::BreadcrumbNav, K::ApplyTheme, @@ -644,16 +633,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (FriLabel, Tr) => "Cum", (NoContributionsDay, En) => "No contributions on this day.", (NoContributionsDay, Tr) => "Bu günde katkı yok.", - (GoodMorning, En) => "Good morning", - (GoodMorning, Tr) => "Günaydın", - (GoodAfternoon, En) => "Good afternoon", - (GoodAfternoon, Tr) => "İyi günler", - (GoodEvening, En) => "Good evening", - (GoodEvening, Tr) => "İyi akşamlar", - (NeedsAttention, En) => "Needs your attention", - (NeedsAttention, Tr) => "Dikkatinizi bekleyenler", - (NothingNeedsYou, En) => "Nothing needs you right now.", - (NothingNeedsYou, Tr) => "Şu an dikkatinizi bekleyen bir şey yok.", (ViewAllNotifications, En) => "View all notifications", (ViewAllNotifications, Tr) => "Tüm bildirimleri gör", (BreadcrumbNav, En) => "Path", @@ -994,25 +973,6 @@ pub fn git_init_failed(lang: Lang, error: impl Display) -> String { /// Upper-cases the first character. Turkish verbs here start with a plain letter, so the /// default mapping is right. -/// "Good morning, Ahmet" for an hour before noon, "Good afternoon" before 18:00 and "Good -/// evening" otherwise. `hour` is 0-23 in UTC. -pub fn greeting(lang: Lang, hour: u8, name: &str) -> String { - let phrase = match hour { - 0..12 => K::GoodMorning, - 12..18 => K::GoodAfternoon, - _ => K::GoodEvening, - }; - format!("{}, {name}", t(lang, phrase)) -} - -/// `1 repository` / `3 repositories`, and `3 depo` in Turkish. -pub fn repositories_count(lang: Lang, n: u64) -> String { - match lang { - Lang::En => format!("{n} repositor{}", if n == 1 { "y" } else { "ies" }), - Lang::Tr => format!("{n} depo"), - } -} - fn capitalize(text: &str) -> String { let mut chars = text.chars(); match chars.next() { diff --git a/crates/forge-web/src/i18n/orgs.rs b/crates/forge-web/src/i18n/orgs.rs index 18c89c3..0a9cd1f 100644 --- a/crates/forge-web/src/i18n/orgs.rs +++ b/crates/forge-web/src/i18n/orgs.rs @@ -1,5 +1,5 @@ //! Strings for the organization pages (`/org/...`), org creation, and the org-related parts of the -//! profile, explore and dashboard pages. +//! profile, explore and landing pages. use super::Lang; @@ -33,6 +33,8 @@ pub enum K { NoticeHasRepos, NoticeConfirmName, NoticeDescriptionLength, + NoticeInvalidDisplayName, + NoticeAvatarInvalid, // Shared labels. Save, Remove, @@ -49,6 +51,7 @@ pub enum K { // Organization settings. Settings, Description, + DisplayNameLabel, DefaultRoleLabel, DefaultRoleHelp, MembersCanCreate, @@ -107,6 +110,7 @@ pub enum K { // Profile. LocalTime, NoMembers, + NoOrganizations, NoVisibleRepos, NoVisibleStarred, Pinned, @@ -117,19 +121,16 @@ pub enum K { PinsTooMany, NoPinnableRepos, TabOverview, + Overview, TabStars, FilterRepos, NoReposMatch, ClearSearch, - // Dashboard and landing. - Dashboard, + // Landing. Home, LandingTagline, LogIn, SetUpForge, - YourRepositories, - RecentRepositories, - NoReposYet, } pub fn t(lang: Lang, key: K) -> &'static str { @@ -190,6 +191,14 @@ pub fn t(lang: Lang, key: K) -> &'static str { (NoticeConfirmName, Tr) => "Kuruluşu silmek için adını tam olarak yazın.", (NoticeDescriptionLength, En) => "The description is longer than 2000 characters.", (NoticeDescriptionLength, Tr) => "Açıklama 2000 karakterden uzun.", + (NoticeInvalidDisplayName, En) => "That display name can't be used.", + (NoticeInvalidDisplayName, Tr) => "Bu görünen ad kullanılamıyor.", + (NoticeAvatarInvalid, En) => { + "That image can't be used. Try a PNG, JPEG, WebP or GIF up to 5 MiB." + } + (NoticeAvatarInvalid, Tr) => { + "Bu görsel kullanılamıyor. PNG, JPEG, WebP ya da GIF, en fazla 5 MiB deneyin." + } (Save, En) => "Save", (Save, Tr) => "Kaydet", (Remove, En) => "Remove", @@ -220,6 +229,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (Settings, Tr) => "Ayarlar", (Description, En) => "Description", (Description, Tr) => "Açıklama", + (DisplayNameLabel, En) => "Display name", + (DisplayNameLabel, Tr) => "Görünen ad", (DefaultRoleLabel, En) => "Default role on the organization's repositories", (DefaultRoleLabel, Tr) => "Kuruluş depolarında varsayılan rol", (DefaultRoleHelp, En) => { @@ -342,6 +353,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (LocalTime, Tr) => "Yerel saat: ", (NoMembers, En) => "No members.", (NoMembers, Tr) => "Üye yok.", + (NoOrganizations, En) => "You are not in any organization yet.", + (NoOrganizations, Tr) => "Henüz hiçbir kuruluşta değilsiniz.", (NoVisibleRepos, En) => "No visible repositories.", (NoVisibleRepos, Tr) => "Görünür depo yok.", (NoVisibleStarred, En) => "No visible starred repositories.", @@ -362,6 +375,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (NoPinnableRepos, Tr) => "Henüz sabitlenecek depo yok.", (TabOverview, En) => "Overview", (TabOverview, Tr) => "Genel bakış", + (Overview, En) => "Overview", + (Overview, Tr) => "Genel bakış", (TabStars, En) => "Stars", (TabStars, Tr) => "Yıldızlar", (FilterRepos, En) => "Find a repository", @@ -370,8 +385,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (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", (Home, Tr) => "Ana sayfa", (LandingTagline, En) => "Self-hosted git repositories with a small, fast web interface.", @@ -382,12 +395,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (LogIn, Tr) => "Giriş yap", (SetUpForge, En) => "Set up forge", (SetUpForge, Tr) => "forge'u kur", - (YourRepositories, En) => "Your repositories", - (YourRepositories, Tr) => "Depolarınız", - (RecentRepositories, En) => "Recent repositories", - (RecentRepositories, Tr) => "Son depolar", - (NoReposYet, En) => "You have no repositories yet.", - (NoReposYet, Tr) => "Henüz deponuz yok.", } } @@ -531,6 +538,8 @@ mod tests { K::NoticeHasRepos, K::NoticeConfirmName, K::NoticeDescriptionLength, + K::NoticeInvalidDisplayName, + K::NoticeAvatarInvalid, K::Save, K::Remove, K::Username, @@ -544,6 +553,7 @@ mod tests { K::CreateOrg, K::Settings, K::Description, + K::DisplayNameLabel, K::DefaultRoleLabel, K::DefaultRoleHelp, K::MembersCanCreate, @@ -597,6 +607,7 @@ mod tests { K::NoPublicReposMatch, K::LocalTime, K::NoMembers, + K::NoOrganizations, K::NoVisibleRepos, K::NoVisibleStarred, K::Pinned, @@ -607,18 +618,15 @@ mod tests { K::PinsTooMany, K::NoPinnableRepos, K::TabOverview, + K::Overview, K::TabStars, K::FilterRepos, K::NoReposMatch, K::ClearSearch, - K::Dashboard, K::Home, K::LandingTagline, K::LogIn, K::SetUpForge, - K::YourRepositories, - K::RecentRepositories, - K::NoReposYet, ]; #[test] diff --git a/crates/forge-web/src/importer/mod.rs b/crates/forge-web/src/importer/mod.rs index eca1f9d..9c7adac 100644 --- a/crates/forge-web/src/importer/mod.rs +++ b/crates/forge-web/src/importer/mod.rs @@ -359,6 +359,7 @@ async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) { } async fn fail(state: &AppState, rep: &Reporter, message: &str) { + tracing::warn!(job = %rep.job_id, %message, "import failed"); rep.log("error", message).await; if let Err(e) = state .store diff --git a/crates/forge-web/src/importer/tests.rs b/crates/forge-web/src/importer/tests.rs index 210b1a5..0cf43db 100644 --- a/crates/forge-web/src/importer/tests.rs +++ b/crates/forge-web/src/importer/tests.rs @@ -8,6 +8,8 @@ use std::sync::Mutex; use forge_core::issues::IssueFilter; use forge_core::store::imports::{ImportJob, ImportState}; use forge_core::{IssueState, Visibility}; +use topcoat::router::request::Request; +use topcoat::router::{Body, to_bytes}; use super::api::{ ApiError, ApiResult, AssetStream, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone, @@ -16,8 +18,9 @@ use super::api::{ use super::{ ImportOptions, JobSpec, Source, Transport, asset_name, origin_note, run_job, with_note, }; +use crate::auth::SESSION_COOKIE; use crate::state::AppState; -use crate::test_support::test_state; +use crate::test_support::{app_router, create_session, test_state}; const TOKEN: &str = "ghp_supersecret_token_value"; @@ -495,6 +498,62 @@ async fn the_token_is_never_written_to_the_database() { ); } +#[tokio::test] +async fn retry_submit_leaves_another_users_failed_job_alone() { + let fx = fixture().await; + let other = fx + .state + .store + .create_user("mallory", None, "unused", false) + .await + .unwrap(); + let job = new_job(&fx, Source::GitHub).await; + fx.state + .store + .set_import_state(&job.id, ImportState::Failed, Some("rate limit")) + .await + .unwrap(); + create_session(&fx.state.store, &other.id, "retry-other-session", "retry-csrf").await; + + let router = app_router(fx.state.clone()); + let cookie = format!("__Host-{SESSION_COOKIE}=retry-other-session"); + + // The static /import/retry is not taken for /import/{job_id}: mallory sees her own empty list. + let page = router + .handle( + Request::builder() + .method("GET") + .uri("/import/retry") + .header("cookie", cookie.as_str()) + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(page.status().as_u16(), 200); + let bytes = to_bytes(page.into_body(), usize::MAX).await.unwrap(); + assert!(String::from_utf8_lossy(&bytes).contains("No failed imports")); + + // The form names the owner's job, and mallory is signed in: the page redirects, nothing starts. + let form = format!("csrf=retry-csrf&token=&sel_0={}", job.id); + let res = router + .handle( + Request::builder() + .method("POST") + .uri("/import/retry") + .header("cookie", cookie.as_str()) + .header("content-type", "application/x-www-form-urlencoded") + .body(Body::from(form)) + .unwrap(), + ) + .await; + assert_eq!(res.status().as_u16(), 303); + let _ = to_bytes(res.into_body(), usize::MAX).await.unwrap(); + + let after = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); + assert_eq!(after.state, ImportState::Failed); + assert_eq!(after.error.as_deref(), Some("rate limit")); +} + #[test] fn the_origin_note_escapes_the_mention_and_cleans_the_name() { let note = origin_note( diff --git a/crates/forge-web/src/live.rs b/crates/forge-web/src/live.rs index db8eec4..0c42ee7 100644 --- a/crates/forge-web/src/live.rs +++ b/crates/forge-web/src/live.rs @@ -59,7 +59,7 @@ pub enum Topic { /// home page shows its newest version). The header's counts follow [`Topic::RepoIssues`] and /// [`Topic::PullList`] as well. Repo(String), - /// A user's repo listing, pins, contribution calendar and the signed-in sidebar's repo list. + /// A user's repo listing, pins and contribution calendar. /// Keyed by user id (an organization is a user too). User(String), /// A user's inbox: a notification was added, read or marked read. Keyed by user id. diff --git a/crates/forge-web/src/pages/banner.rs b/crates/forge-web/src/pages/banner.rs index 1a5103a..27d053e 100644 --- a/crates/forge-web/src/pages/banner.rs +++ b/crates/forge-web/src/pages/banner.rs @@ -1,26 +1,32 @@ //! The site announcement banner. The admin sets it in the server settings (`banner.*`, live), and //! the shell shows it under the header on every page. A visitor dismisses it with -//! `POST /-/banner/dismiss`, which stores the hash of the message in the `forge_banner` cookie, so a -//! changed message shows again. +//! `POST /-/banner/dismiss`, which stores the hash of the message so a changed message shows again: +//! in the `forge_banner` cookie for a signed-out visitor, and as the `banner_dismissed` account +//! preference for a signed-in user. +use std::collections::HashMap; use std::time::Duration; use forge_core::config::BannerConfig; use forge_core::token::hash_token; use serde::Deserialize; use topcoat::Result; -use topcoat::context::{Cx, try_app_context}; +use topcoat::context::{Cx, app_context, try_app_context}; use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, see_other}; use topcoat::router::route; +use crate::auth::current_user; use crate::pages::theme_cookie::safe_back; use crate::state::AppState; /// Name of the dismissal cookie. pub const BANNER_COOKIE: &str = "forge_banner"; +/// Account preference key holding the dismissed hash of a signed-in user. +pub const BANNER_PREF: &str = "banner_dismissed"; + const BANNER_COOKIE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60); /// What the shell draws. @@ -39,7 +45,7 @@ pub fn banner_hash(message: &str, level: &str) -> String { } /// The banner to show at `now`, or `None` when it is off, expired or dismissed (`dismissed` is the -/// cookie value). +/// stored hash). pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Option { if !config.active_at(now) { return None; @@ -57,15 +63,19 @@ pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Opt }) } -/// The banner for this request, read from the live settings and the cookie. -pub fn current(cx: &Cx) -> Option { +/// The banner for this request, read from the live settings. `prefs` is a signed-in viewer's +/// account preferences; without them the dismissal comes from the cookie. +pub fn current(cx: &Cx, prefs: Option<&HashMap>) -> Option { let state = try_app_context::(cx)?; let live = state.live(); if live.banner.message.trim().is_empty() { return None; } - let cookie = cookies(cx).get(BANNER_COOKIE).map(|c| c.value().to_owned()); - view_for(&live.banner, crate::views::now_unix(), cookie.as_deref()) + let dismissed = match prefs { + Some(prefs) => prefs.get(BANNER_PREF).cloned(), + None => cookies(cx).get(BANNER_COOKIE).map(|c| c.value().to_owned()), + }; + view_for(&live.banner, crate::views::now_unix(), dismissed.as_deref()) } #[derive(Deserialize)] @@ -79,7 +89,12 @@ struct DismissForm { #[route(POST "/-/banner/dismiss")] async fn dismiss(cx: &Cx, Form(form): Form) -> Result { let hash_ok = form.hash.len() == 16 && form.hash.bytes().all(|b| b.is_ascii_hexdigit()); - if hash_ok { + if hash_ok && let Some((user, _)) = current_user(cx).await? { + app_context::(cx) + .store + .set_user_pref(&user.id, BANNER_PREF, &form.hash) + .await?; + } else if hash_ok { let max_age = time::Duration::seconds(i64::try_from(BANNER_COOKIE_TTL.as_secs()).unwrap_or(i64::MAX)); cookies(cx).add( diff --git a/crates/forge-web/src/pages/commit.rs b/crates/forge-web/src/pages/commit.rs index 7fe8a57..670764c 100644 --- a/crates/forge-web/src/pages/commit.rs +++ b/crates/forge-web/src/pages/commit.rs @@ -134,7 +134,8 @@ async fn commit_page(cx: &Cx) -> Result { ctx.repo.owner_name, ctx.repo.name, info.oid ), )), - ); + ) + .await?; let diff = history::commit_diff_ws(&state.git, &ctx.path, &info.oid, LIMITS, opts.ignore_ws).await?; diff --git a/crates/forge-web/src/pages/compare.rs b/crates/forge-web/src/pages/compare.rs index 1b3ecb3..516cd11 100644 --- a/crates/forge-web/src/pages/compare.rs +++ b/crates/forge-web/src/pages/compare.rs @@ -269,7 +269,8 @@ async fn compare_view( format!("{compare_path}.patch"), format!("{compare_path}.diff"), )), - ); + ) + .await?; // The page may be a failed POST re-shown; the toolbar still links to the comparison itself. opts.path = compare_path; let diff = if show_diff { diff --git a/crates/forge-web/src/pages/dashboard.rs b/crates/forge-web/src/pages/dashboard.rs deleted file mode 100644 index cfd8758..0000000 --- a/crates/forge-web/src/pages/dashboard.rs +++ /dev/null @@ -1,401 +0,0 @@ -//! Page: home. Landing page for visitors; repo dashboard for signed-in users. -//! -//! The dashboard is a greeting, the contribution calendar, then two columns: the user's -//! repositories and the unread inbox rows that need them. - -use std::time::Duration; - -use forge_core::store::RepoSort; -use forge_core::store::repo_listing::RepoScope; -use forge_core::time::stamp_from_unix; -use forge_core::{Notification, Repo, Visibility}; -use jiff::{Timestamp, civil}; -use topcoat::Result; -use topcoat::context::{Cx, app_context}; -use topcoat::router::content::sse::Event; -use topcoat::router::response::Response; -use topcoat::router::{Body, StatusCode, page, query_params, route}; -use topcoat::view::{View, component, view}; - -use crate::auth::{current_user, percent_encode}; -use crate::i18n::misc::{self as m, K as MK}; -use crate::i18n::orgs::{self as g, K}; -use crate::i18n::{self, Lang}; -use crate::live::{Topic, named_changes, stream_changes}; -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, 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; - -/// The `since` stamp for the calendar. One extra day covers the viewer's local day, which can -/// start before the UTC day that `CALENDAR_DAYS` reaches back to. -fn calendar_since() -> String { - forge_core::time::stamp_ago(Duration::from_secs((CALENDAR_DAYS + 1) * 86_400)) -} - -/// The `day` query: a calendar day whose contributions to list under the calendar. -#[query_params(error = bad_request)] -struct DayQuery { - day: Option, -} - -/// Unread inbox rows in the "Needs your attention" column. -const ATTENTION_ROWS: u32 = 5; - -/// What the signed-in dashboard shows, loaded once per page view. -struct Dashboard { - name: String, - hour: u8, - repos: Vec, - calendar: Calendar, - selected: Option, - attention: Vec, -} - -/// One unread inbox row, with its strings ready for the view. -struct AttentionRow { - href: String, - reference: String, - title: String, - kind: &'static str, - /// The item's update stamp, for the `
- +