From 1512ebbfc3168802ec6e7df88f3a74b0f6587f1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 1 Nov 2026 16:21:06 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20search=20forgives=20typos?= =?UTF-8?q?=20and=20reaches=20everywhere:=20letters=20missing,=20extra,=20?= =?UTF-8?q?wrong=20or=20swapped=20still=20match,=20accents=20do=20not=20ma?= =?UTF-8?q?tter,=20and=20words=20match=20in=20any=20order,=20so=20secuirty?= =?UTF-8?q?,=20pasword=20and=20forge=20webhoks=20land=20where=20they=20sho?= =?UTF-8?q?uld;=20it=20finds=20what=20is=20on=20a=20settings=20page,=20eve?= =?UTF-8?q?ry=20organization=20tab=20and=20team,=20every=20admin=20page=20?= =?UTF-8?q?and=20each=20server=20setting,=20landing=20in=20that=20field,?= =?UTF-8?q?=20and=20the=20pages=20of=20the=20current=20repo=20or=20any=20r?= =?UTF-8?q?epo=20named=20in=20the=20query;=20a=20row=20says=20which=20word?= =?UTF-8?q?=20matched;=20=E2=99=BB=EF=B8=8F=20refactor:=20pins=20are=20cho?= =?UTF-8?q?sen=20from=20a=20menu=20on=20the=20profile=20and=20the=20separa?= =?UTF-8?q?te=20pins=20page=20is=20gone;=20=F0=9F=92=84=20style:=20pages?= =?UTF-8?q?=20hold=20up=20on=20wide=20windows=20with=20real=20data:=20one-?= =?UTF-8?q?pane=20pages=20fill=20the=20window=20and=20a=20list=20keeps=20i?= =?UTF-8?q?ts=20form=20beside=20it,=20org=20Members=20and=20Teams=20are=20?= =?UTF-8?q?a=20list=20with=20a=20form=20with=20no=20repeated=20heading,=20?= =?UTF-8?q?invites,=20mail,=20import=20and=20the=20runner=20page=20lose=20?= =?UTF-8?q?their=20gaps,=20mail's=20test=20button=20sits=20by=20Save,=20pr?= =?UTF-8?q?ofile=20and=20org=20tabs=20no=20longer=20hug=20their=20underlin?= =?UTF-8?q?e,=20the=20branch=20picker=20drops=20its=20key=20hints=20and=20?= =?UTF-8?q?accent,=20and=20explore=20lists=20organizations=20on=20one=20ro?= =?UTF-8?q?w;=20=F0=9F=90=9B=20fix:=20the=20on=20state=20of=20a=20toggle?= =?UTF-8?q?=20shows=20its=20knob=20again,=20and=20the=20newest=20commit=20?= =?UTF-8?q?in=20the=20history=20bars=20is=20no=20longer=20green=20unless?= =?UTF-8?q?=20a=20run=20says=20so?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-web/assets/nav.js | 200 ++++++++-- crates/forge-web/src/pages/admin_mail.rs | 6 +- crates/forge-web/src/pages/admin_runners.rs | 2 +- crates/forge-web/src/pages/admin_server.rs | 4 +- crates/forge-web/src/pages/invites.rs | 4 +- crates/forge-web/src/pages/org_members.rs | 5 +- crates/forge-web/src/pages/org_teams.rs | 12 +- crates/forge-web/src/pages/palette.rs | 420 ++++++++++++++++++-- crates/forge-web/src/pages/profile.rs | 56 ++- crates/forge-web/src/pages/profile_pins.rs | 266 ++++--------- crates/forge-web/src/views/mod.rs | 36 +- style/_canvas_repo.scss | 10 +- style/_fit_forms.scss | 3 +- style/_lang_admin.scss | 13 +- style/_palette.scss | 7 + style/_system.scss | 216 +++++++++- style/main.scss | 45 +-- 17 files changed, 943 insertions(+), 362 deletions(-) diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 104d341..128bae0 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -310,6 +310,9 @@ var el = document.getElementById(id); if (!el) { return false; } el.scrollIntoView(); + // A palette shortcut to a server setting lands in its field. + var field = el.matches('.srv-field') ? el.querySelector('input:not([type="hidden"]), select, textarea') : null; + if (field) { field.focus({ preventScroll: true }); } return true; } @@ -766,7 +769,7 @@ // Dropdown menus: the
that float over the page (avatar menu, branch selector, clone // 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, details.dock-expand'; + var DROPDOWN = 'details.menu, details.pins-menu, details.ref-select, details.clone, details.nav-toggle, details.corner, details.strip-runs, details.dock-expand'; // 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. @@ -4025,6 +4028,7 @@ 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 PALETTE_SPLIT = /[\s\/._\-·]+/; // the same characters, to split a text into words // files: the current repo's file items, once its finder list is loaded (filesSrc names the finder // it came from); filesBusy names the source being fetched. // acts: the actions this page offers, read from its live elements at each open. busy: a state change @@ -4079,42 +4083,180 @@ return out; } - // 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); + // Text for matching: lowercase, without accents, and with the dotless i, so "guvenlik" finds "Güvenlik". + function paletteFold(text) { + return text.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/ı/g, 'i'); + } + + // A text ready to match against: folded, split into words, and with its separators removed. + function paletteParts(text) { + var s = paletteFold(text); + var words = s.split(PALETTE_SPLIT).filter(Boolean); + return { text: text, s: s, words: words, whole: words.join('') }; + } + + // An item's label and other words, folded once. + function paletteMeta(item) { + if (!item.meta) { + item.meta = { label: paletteParts(item.label), terms: (item.terms || []).map(paletteParts) }; + } + return item.meta; + } + + // The fewest single-letter typos (a missing, extra or wrong letter, or two letters swapped) between + // the token and the start of the word, or more than max when there are too many. + function paletteTypos(t, w, max) { + if (w.length < t.length - max) { return max + 1; } + var size = Math.min(w.length, t.length + max) + 1; + var before = null, prev = [], row = [], i, j; + for (j = 0; j < size; j++) { prev[j] = j; } + for (i = 1; i <= t.length; i++) { + row = [i]; + var low = i; + for (j = 1; j < size; j++) { + var cost = t.charAt(i - 1) === w.charAt(j - 1) ? 0 : 1; + var v = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + cost); + if (before && j > 1 && t.charAt(i - 1) === w.charAt(j - 2) && t.charAt(i - 2) === w.charAt(j - 1)) { + v = Math.min(v, before[j - 2] + 1); + } + row[j] = v; + if (v < low) { low = v; } + } + if (low > max) { return max + 1; } + before = prev; + prev = row; + } + var best = max + 1; + for (j = Math.max(0, t.length - max); j < size; j++) { if (row[j] < best) { best = row[j]; } } + return best; + } + + // How well one token matches a text: 4 exact, 3 prefix, 2.6 a whole word, 2 a word's start, + // 1.8 inside a word, then 1.5 or 1.4 for one or two typos. A long token may have more typos, + // and one under four letters has none, or "ssh" would match half the list. + function paletteField(t, x) { + if (x.s === t) { return 4; } + var at = x.s.indexOf(t); + if (at === 0) { return 3; } + if (x.words.indexOf(t) >= 0) { return 2.6; } + var mid = at >= 0 ? 1.8 : 0; 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); + if (PALETTE_WORD.test(x.s.charAt(at - 1))) { return 2; } + at = x.s.indexOf(t, at + 1); + } + if (mid) { return mid; } + var max = t.length < 4 ? 0 : t.length < 8 ? 1 : 2; + if (!max) { return 0; } + var best = max + 1, first = false; + for (var i = 0; i < x.words.length; i++) { + var d = paletteTypos(t, x.words[i], max); + if (d < best) { best = d; first = i === 0; } + } + if (x.words.length > 1 && t.length >= 6) { best = Math.min(best, paletteTypos(t, x.whole, max)); } + return best <= max ? 1.6 - best / 10 + (first ? 0.05 : 0) : 0; + } + + // The letters of the token in order, close together, so "gk" finds "GPG Keys" and a long label + // does not match by holding every letter somewhere. + function paletteInOrder(t, s) { + var ti = 0, from = -1; + for (var i = 0; i < s.length && ti < t.length; i++) { + if (s.charAt(i) === t.charAt(ti)) { + if (!ti) { from = i; } + ti++; + if (ti === t.length) { return i - from < t.length * 3; } + } + } + return false; + } + + // How well one token matches an item: its label first, then its other words at four fifths of the + // score. Sets item.why to the other word that matched, so the row can say why it is listed. + function paletteToken(t, item) { + var m = paletteMeta(item); + var best = paletteField(t, m.label), why = ''; + m.terms.forEach(function (term) { + var v = paletteField(t, term) * 0.8; + if (v > best) { best = v; why = /[._]/.test(term.text) || m.label.s.indexOf(term.s) >= 0 ? '' : term.text; } + }); + if (!best && paletteInOrder(t, m.label.s)) { best = 1; } + if (why) { item.why = why; } + return best; + } + + // How well a query matches an item, 0 for no match. Each word of the query must match, in any order, + // so "forge hooks" and "mail host" work. The whole query as a phrase counts too, and a shorter label + // wins within a tier: the bonus stays under 0.5. An empty query matches all. + function paletteScore(q, item) { + item.why = ''; + if (!q) { return 1; } + var fq = paletteFold(q).trim(); + var m = paletteMeta(item); + var bonus = 1 / (m.label.s.length + 2); + var tokens = fq.split(/\s+/); + var sum = 0; + for (var i = 0; i < tokens.length; i++) { + var v = paletteToken(tokens[i], item); + if (!v) { + if (tokens.length < 2 || m.label.s.indexOf(fq) < 0) { return 0; } + sum = 0; + break; + } + sum += v; } - var qi = 0; - for (var i = 0; i < s.length && qi < q.length; i++) { - if (s.charAt(i) === q.charAt(qi)) { qi++; } + var best = sum / tokens.length; + if (tokens.length > 1) { best = Math.max(best, paletteField(fq, m.label)); } + return best + bonus; + } + + // The pages of a repo the query is about: the current repo's always, and with two or more words, + // those of up to four repos one word names, so "forge hooks" works from any page. + function paletteRepoPages(q, current) { + var pages = (pal.data && pal.data.pages) || []; + var out = [], seen = {}; + function add(label, base, admin) { + pages.forEach(function (p) { + var href = base + '/' + p.path; + if ((p.admin && !admin) || seen[href]) { return; } + seen[href] = true; + out.push({ label: label + ' · ' + p.label, href: href, kind: 'repo', terms: p.terms }); + }); } - return qi === q.length ? 1 + bonus : 0; + if (current) { add(current.name, current.href, current.admin); } + var tokens = paletteFold(q).split(/\s+/).filter(Boolean); + if (tokens.length < 2 || !pal.data) { return out; } + var found = 0; + pal.data.items.forEach(function (item) { + if (item.kind !== 'repo' || found >= 4) { return; } + var named = tokens.some(function (t) { return paletteField(t, paletteMeta(item).label) >= 1.4; }); + if (named) { found++; add(item.label, item.href, item.admin); } + }); + return out; } - // The destinations to filter: the current repo's tabs first, then the fetched list. - function paletteItems() { - var items = []; + // The destinations to filter: the current repo's tabs first, its other pages, then the fetched list. + // The query picks which other repos' pages are worth building. + function paletteItems(q) { + var items = [], current = null; 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) { + var admin = false; 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' }); + if (a.pathname === '/' + repo + '/settings') { admin = true; } }); + current = { name: repo, href: '/' + repo, admin: admin }; } } + var known = {}; + items.forEach(function (i) { known[i.href] = true; }); + items = items.concat(paletteRepoPages(q, current).filter(function (i) { return !known[i.href]; })); if (pal.data) { items = items.concat(pal.data.items); } return pal.acts.concat(items); } @@ -4150,6 +4292,7 @@ // The text a completed item leaves in the input: a tab's label is its repo, and a repo gets a "/". function paletteCompletion(item) { var label = item.label; + if (item.kind !== 'repo' && item.kind !== 'org') { return label; } var at = label.indexOf(' \u00b7 '); if (at >= 0) { label = label.slice(0, at); } return label + (item.kind === 'repo' ? '/' : ''); @@ -4176,14 +4319,19 @@ var typed = pal.prefill && !idle && q.indexOf(pal.prefill.toLowerCase()) === 0 ? q.slice(pal.prefill.length) : ''; // With a "/" the query is a path: an item matches when its label starts with it. var pathMode = q.indexOf('/') >= 0; + // After the opening path, text with no "/" of its own searches by name, as it would with no path. + var words = typed && typed.indexOf('/') < 0 ? typed : (typed || idle ? '' : q.replace(/\//g, ' ').trim()); var scored = []; - paletteItems().concat(paletteFiles(q)).forEach(function (item, idx) { + paletteItems(pathMode ? words : q).concat(paletteFiles(q)).forEach(function (item, idx) { if (!Object.prototype.hasOwnProperty.call(pal.str.heads, item.kind)) { return; } - var s = pathMode ? (item.label.toLowerCase().indexOf(q) === 0 ? 3 : 0) : paletteScore(q, item.label); + var s; + if (!pathMode) { s = paletteScore(q, item); } + else if (item.label.toLowerCase().indexOf(q) === 0) { s = item.label.length === q.length ? 3.5 : 3; item.why = ''; } + else { s = words && item.kind !== 'file' && item.kind !== 'action' ? paletteScore(words, item) : 0; } // Above a path match (3), which would otherwise fill the list and cut the actions off. Text typed // after the opening path searches the page's actions by name. if (item.kind === 'action' && idle) { s = 4; } - else if (item.kind === 'action' && typed) { var m = paletteScore(typed, item.label); s = m ? m + 3 : 0; } + else if (item.kind === 'action' && typed) { var m = paletteScore(typed, item); s = m ? m + 3 : 0; } 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; }); @@ -4221,6 +4369,12 @@ li.setAttribute('aria-selected', 'false'); li.setAttribute('data-n', String(n)); li.textContent = item.label; + if (item.why) { + var why = document.createElement('span'); + why.className = 'palette-why'; + why.textContent = item.why; + li.appendChild(why); + } pal.list.appendChild(li); }); }); @@ -4248,7 +4402,7 @@ 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.data = { at: Date.now(), items: Array.isArray(json.items) ? json.items : [], pages: Array.isArray(json.repoPages) ? json.repoPages : [] }; pal.request = null; if (pal.dlg.open) { renderPalette(); } }).catch(function () { diff --git a/crates/forge-web/src/pages/admin_mail.rs b/crates/forge-web/src/pages/admin_mail.rs index 04cd8e5..99d74bf 100644 --- a/crates/forge-web/src/pages/admin_mail.rs +++ b/crates/forge-web/src/pages/admin_mail.rs @@ -268,13 +268,11 @@ async fn mail_view(
+
-
+ -
- -
diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index 7fb9855..d83f69a 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -1656,7 +1656,7 @@ async fn runner_detail_view( // A runner that has reported nothing has no figures to show, only the note below. let has_host = !metrics.empty || runner.reported.cpus.is_some(); Ok(view! { -
+

(runner.name.as_str())

diff --git a/crates/forge-web/src/pages/admin_server.rs b/crates/forge-web/src/pages/admin_server.rs index efe3a62..2ad2f76 100644 --- a/crates/forge-web/src/pages/admin_server.rs +++ b/crates/forge-web/src/pages/admin_server.rs @@ -109,7 +109,7 @@ struct Row { fixed: bool, } -fn tab_label(lang: Lang, group: Group) -> &'static str { +pub(crate) fn tab_label(lang: Lang, group: Group) -> &'static str { g::t( lang, match group { @@ -263,7 +263,7 @@ async fn server_view(
for r in rows.iter() { -
+
(r.label) (r.kind_label) diff --git a/crates/forge-web/src/pages/invites.rs b/crates/forge-web/src/pages/invites.rs index 385f4bc..f635bf8 100644 --- a/crates/forge-web/src/pages/invites.rs +++ b/crates/forge-web/src/pages/invites.rs @@ -37,14 +37,14 @@ async fn invite_body( Ok(view! {

(t(lang, Key::InvitesTitle))

-

(t(lang, Key::InvitesSub))

+

(t(lang, Key::InvitesSub))

if let Some(message) = notice {

(message)

} -
+
if let Some(message) = error { alert(message: message.as_str()) } diff --git a/crates/forge-web/src/pages/org_members.rs b/crates/forge-web/src/pages/org_members.rs index e24fe0e..434f4ce 100644 --- a/crates/forge-web/src/pages/org_members.rs +++ b/crates/forge-web/src/pages/org_members.rs @@ -90,8 +90,8 @@ async fn members_body( org_head(name: name.clone(), description: description) org_tabs(lang: lang, name: name, current: "members".to_owned(), repo_count: repo_count, package_count: package_count) org_notice(notice: notice) +
-

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

@@ -163,11 +163,12 @@ async fn members_body(

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

- +
} + }) } diff --git a/crates/forge-web/src/pages/org_teams.rs b/crates/forge-web/src/pages/org_teams.rs index b23d590..f7dedb8 100644 --- a/crates/forge-web/src/pages/org_teams.rs +++ b/crates/forge-web/src/pages/org_teams.rs @@ -201,14 +201,10 @@ async fn teams_body( org_head(name: name.clone(), description: description) org_tabs(lang: lang, name: name, current: "teams".to_owned(), repo_count: repo_count, package_count: package_count) org_notice(notice: notice) +
-

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

-

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

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

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

if owner {
@@ -256,6 +253,7 @@ async fn teams_body(
} +
}) } @@ -317,6 +315,7 @@ async fn team_body( org_head(name: data.org_name.clone(), description: data.org_description.clone()) org_tabs(lang: lang, name: data.org_name.clone(), current: "teams".to_owned(), repo_count: data.repo_count, package_count: data.package_count) org_notice(notice: notice) +

(data.team_name.as_str())

if has_description { @@ -439,6 +438,7 @@ async fn team_body( }
+
}) } diff --git a/crates/forge-web/src/pages/palette.rs b/crates/forge-web/src/pages/palette.rs index fa640a6..cdc0fe6 100644 --- a/crates/forge-web/src/pages/palette.rs +++ b/crates/forge-web/src/pages/palette.rs @@ -1,15 +1,21 @@ //! The command palette's destinations: `GET /-/palette` lists what the signed-in viewer can jump to. -//! Their repos, the orgs they belong to with that org's members, teams and (for owners) settings, -//! and the pages the navigation links to: their own profile's tabs, the fixed site pages and the -//! settings and admin pages. Those pages come from the same lists the navigation is built from -//! (`views::profile_items`, `views::global_items`, `views::settings_items`, `views::admin_items`), -//! so a page the sidebar or a tab bar links to is found here too. Each href is listed once, the -//! first time it appears. The palette itself, its filtering and keys live in `assets/nav.js`. The -//! actions of the page it is opened on are not listed here: a control marked `data-palette-action` -//! is rendered only for a viewer who may use it, and the palette reads those controls from the page. +//! Their repos, the orgs they belong to with each org's tabs, teams and (for owners) settings, and the +//! pages the navigation links to: their own profile's tabs, the fixed site pages and the settings and +//! admin pages. For an admin it also lists every tab and every field of the server settings. Those +//! pages come from the same lists the navigation is built from (`views::profile_items`, +//! `views::global_items`, `views::settings_items`, `views::admin_items`), so a page the sidebar or a +//! tab bar links to is found here too. Each href is listed once, the first time it appears. +//! +//! An item may carry `terms`: what is on that page and other words for it, in both languages, so +//! "password" finds Security. `repoPages` lists the pages of a repo as paths: `assets/nav.js` applies +//! them to the current repo, and to a repo named in the query. The palette itself, its typo-tolerant +//! matching and keys live in `assets/nav.js`. The actions of the page it is opened on are not listed +//! here: a control marked `data-palette-action` is rendered only for a viewer who may use it, and the +//! palette reads those controls from the page. use std::collections::HashSet; +use forge_core::server_settings::{FIELDS, Group}; use forge_core::store::orgs::OrgMemberRole; use http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; use serde_json::{Value, json}; @@ -19,9 +25,13 @@ use topcoat::router::response::Response; use topcoat::router::{Body, HeaderValue, StatusCode, route}; use crate::auth::current_user; -use crate::i18n; +use crate::i18n::code::{self, K as CK}; use crate::i18n::orgs::{self as g, K}; +use crate::i18n::repo_admin::{self as ra, K as RK}; +use crate::i18n::{self, Lang}; +use crate::pages::admin_server::tab_label; use crate::pages::org_new::may_create_org; +use crate::pages::passkeys::s; use crate::state::AppState; use crate::views::{ admin_items, enc, global_items, profile_items, repo_href, settings_items, user_href, @@ -30,20 +40,271 @@ use crate::views::{ /// 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 }) +/// What each settings page holds and other words for it, in both languages. +const SETTINGS_TERMS: &[(&str, &[&str])] = &[ + ( + "/settings/profile", + &[ + "Display name", + "Görünen ad", + "Username", + "Kullanıcı adı", + "About", + "Bio", + "Hakkında", + "Time zone", + "Saat dilimi", + "Avatar", + "Picture", + "Photo", + "Fotoğraf", + "Resim", + ], + ), + ("/settings/keys", &["SSH", "Public key", "Açık anahtar"]), + ( + "/settings/gpg", + &[ + "GPG", + "Signing key", + "Signature", + "İmza", + "Verified commits", + ], + ), + ( + "/settings/tokens", + &["API", "PAT", "Personal access token", "Erişim belirteci"], + ), + ( + "/settings/sessions", + &["Devices", "Cihazlar", "Sign out", "Logged in", "Oturumlar"], + ), + ( + "/settings/security", + &[ + "Password", + "Parola", + "Şifre", + "Email", + "E-posta", + "Mail", + "Two-factor", + "2FA", + "TOTP", + "İki adımlı", + "Passkey", + "Geçiş anahtarı", + "Recovery codes", + "Kurtarma kodları", + "Delete account", + "Hesabı sil", + "Security log", + ], + ), + ( + "/settings/notifications", + &[ + "Email notifications", + "Bildirim", + "Push", + "Browser notifications", + "Tarayıcı bildirimi", + ], + ), + ( + "/settings/appearance", + &[ + "Theme", + "Tema", + "Dark mode", + "Light mode", + "Koyu", + "Açık", + "Accent", + "Vurgu rengi", + "Colour", + "Color", + "Renk", + "Background", + "Arka plan", + "Language", + "Dil", + "Sidebar", + "Sound", + "Ses", + "Tones", + ], + ), + ( + "/settings/export", + &[ + "Download my data", + "Verilerimi indir", + "Archive", + "Dışa aktar", + ], + ), +]; + +/// What each admin page holds and other words for it, in both languages. +const ADMIN_TERMS: &[(&str, &[&str])] = &[ + ( + "/admin/users", + &["Accounts", "Hesaplar", "Suspend", "Askıya al"], + ), + ( + "/admin/health", + &[ + "Status", + "Durum", + "Disk", + "Monitoring", + "Alerts", + "Uyarılar", + ], + ), + ("/admin/invites", &["Invite someone", "Davet et"]), + ("/admin/audit", &["Log", "Günlük", "History", "Geçmiş"]), + ( + "/admin/runners", + &["CI", "Actions", "Agents", "Workers", "Çalıştırıcılar"], + ), + ( + "/admin/mail", + &["SMTP", "Email", "E-posta", "Sender", "Gönderen"], + ), + ( + "/admin/server", + &["Configuration", "Config", "Yapılandırma", "Ayarlar"], + ), + ("/admin/backups", &["Restore", "Geri yükle", "S3", "R2"]), + ( + "/admin/replication", + &["Standby", "Failover", "Yedek sunucu"], + ), +]; + +/// One destination: its label, its path, what it is (`repo`, `org` or `page`) and its other words. +fn destination(label: &str, href: &str, kind: &str, terms: &[&str]) -> Value { + let mut item = json!({ "label": label, "href": href, "kind": kind }); + if !terms.is_empty() { + item["terms"] = json!(terms); + } + item } /// Adds a destination unless its href is already listed. fn push(items: &mut Vec, seen: &mut HashSet, label: &str, href: &str, kind: &str) { + push_terms(items, seen, label, href, kind, &[]); +} + +/// Adds a destination with its other words unless its href is already listed. +fn push_terms( + items: &mut Vec, + seen: &mut HashSet, + label: &str, + href: &str, + kind: &str, + terms: &[&str], +) { if seen.insert(href.to_owned()) { - items.push(destination(label, href, kind)); + items.push(destination(label, href, kind, terms)); } } -/// `{"items": [{"label", "href", "kind"}, ...]}` for the signed-in viewer. Anonymous visitors get -/// 401, as the other signed-in-only JSON routes do. +/// The other words listed for an href. +fn terms_for(table: &'static [(&str, &[&str])], href: &str) -> &'static [&'static str] { + table + .iter() + .find(|(path, _)| *path == href) + .map_or(&[], |(_, terms)| terms) +} + +/// One page of a repo, relative to the repo's path. `admin` pages are offered only to people who +/// may manage the repo. +fn repo_page(label: &str, path: &str, admin: bool, terms: &[&str]) -> Value { + json!({ "label": label, "path": path, "admin": admin, "terms": terms }) +} + +/// The pages every repo has, and its settings pages. +fn repo_pages(lang: Lang) -> Vec { + let code = |key| code::t(lang, key); + let admin = |key| ra::t(lang, key); + let settings = format!("{} \u{b7} {}", code(CK::TabSettings), admin(RK::General)); + vec![ + repo_page(code(CK::TabIssues), "issues", false, &["Bugs", "Tickets"]), + repo_page( + code(CK::TabPulls), + "pulls", + false, + &["PR", "Merge requests"], + ), + repo_page( + code(CK::TabCi), + "ci", + false, + &["Actions", "Runs", "Workflows", "Pipelines", "Builds"], + ), + repo_page(code(CK::BranchesTitle), "branches", false, &[]), + repo_page(code(CK::TagsTitle), "tags", false, &[]), + repo_page(code(CK::TabReleases), "releases", false, &[]), + repo_page( + &settings, + "settings", + true, + &[ + "Visibility", + "Görünürlük", + "Archive", + "Arşiv", + "Description", + "Açıklama", + ], + ), + repo_page( + admin(RK::BranchProtection), + "settings?section=branches", + true, + &["Rules", "Kurallar"], + ), + repo_page( + admin(RK::Collaborators), + "settings/collaborators", + true, + &["Access", "Erişim", "Members"], + ), + repo_page( + admin(RK::RenameTransferNav), + "settings/rename", + true, + &["Rename", "Transfer"], + ), + repo_page(admin(RK::Webhooks), "settings/hooks", true, &["Hooks"]), + repo_page( + admin(RK::Mirrors), + "settings/mirrors", + true, + &["Sync", "Mirror"], + ), + repo_page( + admin(RK::Secrets), + "settings/secrets", + true, + &["Variables", "Env"], + ), + repo_page(code(CK::TabWiki), "settings/wiki", true, &[]), + repo_page( + admin(RK::DangerZone), + "settings?section=danger", + true, + &["Delete repository", "Depoyu sil"], + ), + ] +} + +/// `{"items": [{"label", "href", "kind", "terms"?, "admin"?}, ...], "repoPages": [...]}` 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 { @@ -53,42 +314,50 @@ async fn palette(cx: &Cx) -> Result { }; let state = app_context::(cx); let lang = i18n::lang(cx, Some(&user)); + let orgs = state.store.orgs_for_user(&user.id).await?; let mut items = Vec::new(); let mut seen = HashSet::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, "", ""); - push(&mut items, &mut seen, &label, &href, "repo"); + // Enough to offer the settings pages. A collaborator with Admin gets them on the repo itself, + // where the page's own Settings tab says so. + let admin = user.is_admin + || repo.owner_id == user.id + || orgs + .iter() + .any(|(org, role)| org.id == repo.owner_id && *role == OrgMemberRole::Owner); + if seen.insert(href.clone()) { + let mut item = destination(&label, &href, "repo", &[]); + item["admin"] = json!(admin); + items.push(item); + } } - for (org, role) in state.store.orgs_for_user(&user.id).await? { + for (org, role) in &orgs { let name = &org.username; let base = format!("/org/{}", enc(name)); push(&mut items, &mut seen, name, &user_href(name), "org"); - let members = format!("{name} \u{b7} {}", g::t(lang, K::Members)); - push( - &mut items, - &mut seen, - &members, - &format!("{base}/members"), - "page", - ); - let teams = format!("{name} \u{b7} {}", g::t(lang, K::Teams)); - push( - &mut items, - &mut seen, - &teams, - &format!("{base}/teams"), - "page", - ); - if role == OrgMemberRole::Owner { + for tab in profile_items(lang, name, true, false, true) { + if tab.key != "overview" { + let label = format!("{name} \u{b7} {}", tab.label); + push(&mut items, &mut seen, &label, &tab.href, "page"); + } + } + for team in state.store.teams_for_org(&org.id).await? { + let label = format!("{name} \u{b7} {}", team.name); + let href = format!("{base}/teams/{}", team.id); + push(&mut items, &mut seen, &label, &href, "page"); + } + if *role == OrgMemberRole::Owner { let settings = format!("{name} \u{b7} {}", g::t(lang, K::Settings)); - push( + push_terms( &mut items, &mut seen, &settings, &format!("{base}/settings"), "page", + &["Avatar", "Delete organization", "Organizasyonu sil"], ); } } @@ -99,16 +368,52 @@ async fn palette(cx: &Cx) -> Result { for item in global_items(lang, may_create_org(state, &user)) { push(&mut items, &mut seen, item.label, &item.href, "page"); } + let settings_area = g::t(lang, K::Settings); for item in settings_items(lang) { - push(&mut items, &mut seen, item.label, &item.href, "page"); + let label = format!("{settings_area} \u{b7} {}", item.label); + let terms = terms_for(SETTINGS_TERMS, &item.href); + push_terms(&mut items, &mut seen, &label, &item.href, "page", terms); } if user.is_admin { + let admin_area = crate::i18n::admin::t(lang, crate::i18n::admin::K::AdminArea); for item in admin_items(lang) { - push(&mut items, &mut seen, item.label, &item.href, "page"); + let label = format!("{admin_area} \u{b7} {}", item.label); + let terms = terms_for(ADMIN_TERMS, &item.href); + push_terms(&mut items, &mut seen, &label, &item.href, "page", terms); + } + let queue = format!( + "{admin_area} \u{b7} {}", + s(lang, "Mail queue", "E-posta kuyruğu") + ); + push( + &mut items, + &mut seen, + &queue, + "/admin/mail?tab=queue", + "page", + ); + let server = crate::i18n::admin::t(lang, crate::i18n::admin::K::ServerSettings); + for group in Group::ALL { + let label = format!("{server} \u{b7} {}", tab_label(lang, group)); + let href = format!("/admin/server?tab={}", group.slug()); + push(&mut items, &mut seen, &label, &href, "page"); + } + for field in FIELDS { + let name = match (lang, crate::i18n::server_settings::field_tr(field.key)) { + (Lang::Tr, Some((tr, _))) => tr, + _ => field.label, + }; + let label = format!( + "{server} \u{b7} {} \u{b7} {name}", + tab_label(lang, field.group) + ); + let href = format!("/admin/server?tab={}#srv-{}", field.group.slug(), field.key); + let terms = [field.key, field.label]; + push_terms(&mut items, &mut seen, &label, &href, "page", &terms); } } - let body = json!({ "items": items }); + let body = json!({ "items": items, "repoPages": repo_pages(lang) }); let mut response = Response::new(Body::from(body.to_string().into_bytes())); let headers = response.headers_mut(); headers.insert( @@ -129,6 +434,45 @@ mod tests { use crate::i18n::Lang; use crate::views::profile_items; + /// Every admin page and setting is offered to an admin, and none of them to anyone else. + #[tokio::test] + async fn admin_destinations_reach_admins_only() { + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + let store = state.store.clone(); + let router = crate::test_support::app_router(state); + let admin = store + .create_user("boss", None, "not-a-real-hash", true) + .await + .unwrap(); + let plain = store + .create_user("plain", None, "not-a-real-hash", false) + .await + .unwrap(); + crate::test_support::create_session(&store, &admin.id, "boss-token", "boss-csrf").await; + crate::test_support::create_session(&store, &plain.id, "plain-token", "plain-csrf").await; + for (token, is_admin) in [("boss-token", true), ("plain-token", false)] { + let request = Request::builder() + .method("GET") + .uri("/-/palette") + .header("cookie", format!("__Host-{SESSION_COOKIE}={token}")) + .body(Body::empty()) + .unwrap(); + let res = router.handle(request).await; + let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + let hrefs: Vec<&str> = body["items"] + .as_array() + .unwrap() + .iter() + .map(|item| item["href"].as_str().unwrap()) + .collect(); + assert!(hrefs.contains(&"/settings/security")); + assert_eq!(hrefs.contains(&"/admin/mail"), is_admin); + assert_eq!(hrefs.iter().any(|href| href.contains("#srv-")), is_admin); + } + } + /// Every tab of the viewer's own profile is in the palette, so a tab is found by its name. #[tokio::test] async fn palette_lists_every_profile_tab() { diff --git a/crates/forge-web/src/pages/profile.rs b/crates/forge-web/src/pages/profile.rs index a1befac..a349937 100644 --- a/crates/forge-web/src/pages/profile.rs +++ b/crates/forge-web/src/pages/profile.rs @@ -30,6 +30,7 @@ use crate::live::{Topic, stream_changes}; use crate::pages::org_new::may_create_org; use crate::pages::packages::{self as packages, PackageRow}; use crate::pages::profile_calendar::{calendar_since, load_calendar}; +use crate::pages::profile_pins::{PinOption, pin_options, pins_menu}; use crate::pages::repo_settings::{notice_banner_for, take_notice}; use crate::pages::snippets::{ListRow, list_row, snippet_rows}; use crate::render::markdown::render_markdown; @@ -46,6 +47,13 @@ path_param!(username); /// Repos per page on the repositories and stars tabs. const PER_PAGE: u64 = 30; +/// What the pin menu needs: shown to whoever may edit the pins, on the overview. +struct PinsMenu { + action: String, + csrf: String, + options: Vec, +} + /// Repos the overview shows when the owner has no visible pins. const POPULAR_COUNT: usize = 6; /// Members an organization's overview lists; a longer list links to the members page. @@ -61,6 +69,8 @@ struct ProfileQuery { page: Option, /// A calendar day whose contributions to list under the calendar on the overview. day: Option, + /// `too_many` after a save with more pins than the limit. + pins: Option, } /// Sort keys of the repo tabs in the order their chips are shown, with the label of each. The @@ -178,13 +188,23 @@ async fn profile_page(cx: &Cx) -> Result { Some(u) => u.id == user.id, None => false, }; - let pins_edit_href = can_edit_pins.then(|| { - if user.is_org() { - format!("/org/{}/settings/pins", user.username) - } else { - "/settings/pins".to_owned() + let mut pins_menu_data = None; + if can_edit_pins && tab == "overview" { + let options = pin_options(&state.store, &user.id).await?; + if let (false, Some((_, session))) = (options.is_empty(), viewer.as_ref()) { + let action = if user.is_org() { + format!("/org/{}/settings/pins", user.username) + } else { + "/settings/pins".to_owned() + }; + pins_menu_data = Some(PinsMenu { + action, + csrf: session.csrf_token.clone(), + options, + }); } - }); + } + let pins_error = can_edit_pins && query.pins.as_deref() == Some("too_many"); // The contribution calendar on the overview, for a person only. Its counts and day links use // public repos alone, so anyone may see it. @@ -320,7 +340,7 @@ async fn profile_page(cx: &Cx) -> Result { profile_card(user: user, avatar: avatar, about_html: about_html, local_time: local_time, org: org, lang: lang, tab: tab.to_owned(), q: q, sort: sort, repo_total: repo_total, star_total: star_total, cards: cards, from_pins: from_pins, - pins_edit_href: pins_edit_href, edit_profile: own, listing: listing, + pins_menu_data: pins_menu_data, pins_error: pins_error, edit_profile: own, listing: listing, packages_on: packages_on, package_rows: package_rows, org_member: org_member, org_owner: org_owner, org_can_create: org_can_create, heat: heat, snippets: snippets, orgs: orgs, org_create_allowed: org_create_allowed, @@ -557,7 +577,8 @@ async fn profile_card( star_total: u64, cards: Vec, from_pins: bool, - pins_edit_href: Option, + pins_menu_data: Option, + pins_error: bool, edit_profile: bool, listing: Listing, packages_on: bool, @@ -677,10 +698,13 @@ async fn profile_card(

(pinned_heading)

- if let Some(href) = pins_edit_href { - (g::t(lang, K::CustomizePins)) + if let Some(menu) = pins_menu_data { + pins_menu(lang: lang, action: menu.action, csrf: menu.csrf, options: menu.options) }
+ if pins_error { + + } if has_cards {
    for card in cards.into_iter() { @@ -1156,8 +1180,8 @@ mod tests { // Settings keeps a sidebar of its own pages, and its back link goes to the profile. let (_, settings) = get(&site.router, "/org/forge-org/settings", Some(&owner_cookie)).await; assert!( - settings.contains("href=\"/org/forge-org/settings/pins\""), - "org settings: sidebar lists Customize pins" + !settings.contains("/org/forge-org/settings/pins"), + "org settings: pins live on the profile" ); assert!( !settings.contains("href=\"/org/forge-org/members\""), @@ -1182,8 +1206,8 @@ mod tests { let (_, owner) = get(&site.router, "/acme", Some(&owner_cookie)).await; assert!(owner.contains("acme/lib"), "org pins: owner sees pin"); assert!( - owner.contains("href=\"/org/acme/settings/pins\""), - "org pins: owner edit link" + owner.contains("action=\"/org/acme/settings/pins\""), + "org pins: owner edits them on the profile" ); let (_, anon) = get(&site.router, "/acme", None).await; assert!(anon.contains("acme/lib"), "org pins: anonymous sees pin"); @@ -1251,8 +1275,8 @@ mod tests { "pins: owner customize link" ); assert!( - owner.contains("href=\"/settings/pins\""), - "pins: owner settings link" + owner.contains("action=\"/settings/pins\""), + "pins: owner edits them on the profile" ); // Fallback: with no visible pin, the overview shows popular repos instead. diff --git a/crates/forge-web/src/pages/profile_pins.rs b/crates/forge-web/src/pages/profile_pins.rs index 826fdcf..ce1a5e4 100644 --- a/crates/forge-web/src/pages/profile_pins.rs +++ b/crates/forge-web/src/pages/profile_pins.rs @@ -1,38 +1,48 @@ -//! Pages: where a profile's owner picks the repos pinned on it, at most six. `/settings/pins` is for -//! the signed-in user. `/org/{org}/settings/pins` is for an organization, and only its owners may -//! use it. Both show a form of checkboxes, one per repo the owner has, and redirect to the profile -//! after a save. +//! Picking the repos pinned on a profile, at most six. The menu sits on the profile itself and +//! posts to `/settings/pins` for the signed-in user, or to `/org/{org}/settings/pins` for an +//! organization, whose owners alone may use it. Both redirect to the profile after a save. use forge_core::store::profile_pins::MAX_PROFILE_PINS; -use forge_core::{Repo, Session, Store, User}; +use forge_core::{Repo, Store, User}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::RawForm; -use topcoat::router::error::see_other; -use topcoat::router::response::Response; -use topcoat::router::{page, path_param, route}; +use topcoat::router::error::{SeeOther, see_other}; +use topcoat::router::{path_param, route}; use topcoat::view::{View, component, view}; use crate::auth::{require_csrf, require_user}; +use crate::i18n::Lang; use crate::i18n::orgs::{self as g, K}; -use crate::i18n::{self, Lang}; -use crate::live::{Topic, stream_changes}; use crate::pages::issue_meta::{form_all, form_field, form_pairs}; use crate::pages::org_ctx::{load_org, require_form_csrf, require_owner}; use crate::state::AppState; -use crate::views::{empty_state, shell}; path_param!(org); /// A repo the owner may pin, and whether it is pinned now. -struct PinOption { +pub(crate) struct PinOption { repo: Repo, checked: bool, } -/// The repo ids pinned, in order. -fn ids(repos: Vec) -> Vec { - repos.into_iter().map(|repo| repo.id).collect() +/// Each repo `owner_id` may pin, with the pinned ones ticked. +pub(crate) async fn pin_options(store: &Store, owner_id: &str) -> Result> { + let chosen: Vec = store + .profile_pins(owner_id) + .await? + .into_iter() + .map(|repo| repo.id) + .collect(); + Ok(store + .list_repos_by_owner(owner_id) + .await? + .into_iter() + .map(|repo| { + let checked = chosen.contains(&repo.id); + PinOption { repo, checked } + }) + .collect()) } /// The repo ids a form chose: blanks and repeats are dropped, the order is kept. @@ -46,204 +56,89 @@ fn selection(raw: Vec) -> Vec { out } -/// The pin form for `owner`, with the `chosen` repos ticked. `error` is shown above the form. -/// The values are owned so the returned view borrows nothing from the caller. -async fn pins_form( - cx: &Cx, - viewer: (User, Session), - owner: User, - action: String, - chosen: Vec, - error: Option<&'static str>, -) -> Result { - let state = app_context::(cx); - let lang = i18n::lang(cx, Some(&viewer.0)); - let options: Vec = state - .store - .list_repos_by_owner(&owner.id) - .await? - .into_iter() - .map(|repo| { - let checked = chosen.contains(&repo.id); - PinOption { repo, checked } - }) - .collect(); - let csrf = viewer.1.csrf_token.clone(); - let title = g::t(lang, K::CustomizePins); - let error = error.map(str::to_owned); - // The form follows the owner's topic: a pin or a repo of the owner changed elsewhere re-renders it. - let live = format!("{action}/events"); - Ok(view! { cx => - shell(title: title, viewer: Some(&viewer), - pins_body(lang: lang, action: action, live: live, csrf: csrf, options: options, error: error)) - }) -} - +/// The menu on the profile that picks the pins. It saves through the server, and the profile shows +/// the result after the redirect. #[component] -async fn pins_body( +pub(crate) async fn pins_menu( lang: Lang, action: String, - live: String, csrf: String, options: Vec, - error: Option, ) -> Result { - let has_options = !options.is_empty(); - let intro = g::t(lang, K::PinsIntro); - let empty = g::t(lang, K::NoPinnableRepos); - let save = g::t(lang, K::SavePins); Ok(view! { -
    -

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

    -

    (intro)

    - if let Some(message) = error { - - } - if has_options { -
    - -
      - for option in options.into_iter() { -
    • - -
    • - } -
    -
    - -
    - - } else { - empty_state(title: empty, - (g::t(lang, K::NewRepository))) - } -
    +
    + (g::t(lang, K::CustomizePins)) +
    + +

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

    +
      + for option in options.into_iter() { +
    • + +
    • + } +
    + + +
    }) } -/// Stores the chosen pins for `owner` and redirects to `back`. More than the limit re-shows the -/// form with the error and changes nothing. +/// Stores the chosen pins for `owner` and redirects to `back`. More than the limit changes nothing, +/// and the profile says why. async fn save_pins( - cx: &Cx, - viewer: (User, Session), + state: &AppState, owner: User, - action: String, chosen: Vec, back: String, -) -> Result { +) -> Result { if chosen.len() > MAX_PROFILE_PINS { - let lang = i18n::lang(cx, Some(&viewer.0)); - let error = g::t(lang, K::PinsTooMany); - return pins_form(cx, viewer, owner, action, chosen, Some(error)).await; + return Err(see_other(format!("{back}?pins=too_many")).into()); } - let state = app_context::(cx); state.store.set_profile_pins(&owner.id, &chosen).await?; state.live.bump(&crate::live::Topic::User(owner.id.clone())); Err(see_other(back).into()) } -/// What the pin form shows: the owner's pinned repos in order, then each repo the owner may pin. -async fn pins_fingerprint(store: &Store, owner_id: &str) -> Result { - let mut lines = Vec::new(); - for repo in store.profile_pins(owner_id).await? { - lines.push(format!("pin {}", repo.id)); - } - for repo in store.list_repos_by_owner(owner_id).await? { - lines.push(format!( - "repo {} {}/{}", - repo.id, repo.owner_name, repo.name - )); - } - Ok(lines.join("\n")) -} - -/// The pin form's change stream for the signed-in user. Its own page only, as the form. -#[route(GET "/settings/pins/events")] -async fn pins_events(cx: &Cx) -> Result { - let viewer = require_user(cx).await?; - let state = app_context::(cx); - let owner_id = viewer.0.id.clone(); - let store = state.store.clone(); - stream_changes( - cx, - &state.live, - &[Topic::User(owner_id.clone())], - move || { - let store = store.clone(); - let owner_id = owner_id.clone(); - async move { pins_fingerprint(&store, &owner_id).await } - }, - ) - .await -} - -/// Gets the pin form for the signed-in user's own profile. -#[page("/settings/pins")] -async fn pins_page(cx: &Cx) -> Result { +/// Pins are picked on the profile; an old link lands there. +#[route(GET "/settings/pins")] +async fn pins_page(cx: &Cx) -> Result { let viewer = require_user(cx).await?; - let store = &app_context::(cx).store; - let chosen = ids(store.profile_pins(&viewer.0.id).await?); - let owner = viewer.0.clone(); - pins_form(cx, viewer, owner, "/settings/pins".to_owned(), chosen, None).await + Err(see_other(format!("/{}", viewer.0.username)).into()) } /// Saves the signed-in user's pins, then back to the profile. -#[page(POST "/settings/pins")] -async fn pins_save(cx: &Cx, RawForm(raw): RawForm) -> Result { +#[route(POST "/settings/pins")] +async fn pins_save(cx: &Cx, RawForm(raw): RawForm) -> Result { let pairs = form_pairs(&raw[..]); let viewer = require_csrf(cx, &form_field(&pairs, "csrf")).await?; let chosen = selection(form_all(&pairs, "repo")); let back = format!("/{}", viewer.0.username); let owner = viewer.0.clone(); - save_pins(cx, viewer, owner, "/settings/pins".to_owned(), chosen, back).await -} - -/// The pin form's change stream for an organization. Owners only, as the form. -#[route(GET "/org/{org}/settings/pins/events")] -async fn org_pins_events(cx: &Cx) -> Result { - let ctx = load_org(cx, path_param::(cx)).await?; - require_owner(&ctx)?; - let state = app_context::(cx); - let owner_id = ctx.org.id.clone(); - let store = state.store.clone(); - stream_changes( - cx, - &state.live, - &[Topic::User(owner_id.clone())], - move || { - let store = store.clone(); - let owner_id = owner_id.clone(); - async move { pins_fingerprint(&store, &owner_id).await } - }, - ) - .await + save_pins(app_context::(cx), owner, chosen, back).await } -/// Gets the pin form for an organization. Owners only. -#[page("/org/{org}/settings/pins")] -async fn org_pins_page(cx: &Cx) -> Result { +/// Pins are picked on the profile; an old link lands there. Owners only, as the form was. +#[route(GET "/org/{org}/settings/pins")] +async fn org_pins_page(cx: &Cx) -> Result { let ctx = load_org(cx, path_param::(cx)).await?; require_owner(&ctx)?; - let store = &app_context::(cx).store; - let chosen = ids(store.profile_pins(&ctx.org.id).await?); - let action = ctx.href("/settings/pins"); - pins_form(cx, ctx.viewer, ctx.org, action, chosen, None).await + Err(see_other(format!("/{}", ctx.org.username)).into()) } /// Saves an organization's pins, then back to the org profile. Owners only. -#[page(POST "/org/{org}/settings/pins")] -async fn org_pins_save(cx: &Cx, RawForm(raw): RawForm) -> Result { +#[route(POST "/org/{org}/settings/pins")] +async fn org_pins_save(cx: &Cx, RawForm(raw): RawForm) -> Result { let ctx = load_org(cx, path_param::(cx)).await?; let pairs = form_pairs(&raw[..]); require_form_csrf(&ctx, &form_field(&pairs, "csrf"))?; require_owner(&ctx)?; let chosen = selection(form_all(&pairs, "repo")); - let action = ctx.href("/settings/pins"); let back = format!("/{}", ctx.org.username); - save_pins(cx, ctx.viewer, ctx.org, action, chosen, back).await + save_pins(app_context::(cx), ctx.org, chosen, back).await } #[cfg(test)] @@ -379,7 +274,7 @@ mod tests { .collect() } - /// The owner saves pins and the form reflects them. The bad submissions that follow + /// The owner saves pins and the profile reflects them. The bad submissions that follow /// (too many pins, a wrong CSRF token, a foreign repo, another user) must leave the saved /// pins alone. The scenarios run in order on one seed, and each reads the state before it. #[tokio::test] @@ -417,16 +312,18 @@ mod tests { "save: stored pins" ); - // The form ticks the pinned repos. - let form = send(&s.site, "GET", "/settings/pins", Some(&cookie), &[]).await; - assert_eq!(form.status, 200, "form: status"); - assert!( - form.body.contains("checked"), - "form: pinned repos are ticked" + // The profile's menu ticks the pinned repos, and the old page leads there. + let profile = send(&s.site, "GET", "/tahinli", Some(&cookie), &[]).await; + assert!(profile.body.contains("pins-menu"), "menu on the profile"); + assert!(profile.body.contains("checked"), "pinned repos are ticked"); + let old = send(&s.site, "GET", "/settings/pins", Some(&cookie), &[]).await; + assert_eq!( + old.location.as_deref(), + Some("/tahinli"), + "old page redirects" ); - assert!(form.body.contains("tahinli/open-repo"), "form: lists repos"); - // Seven pins is one too many: the form is shown again and the saved pins stay. + // Seven pins is one too many: the saved pins stay. let repos = s.site.store.list_repos_by_owner(&s.tahinli).await.unwrap(); assert!(repos.len() >= 7, "seed has enough repos"); let ids: Vec = repos.iter().map(|r| r.id.clone()).collect(); @@ -434,13 +331,14 @@ mod tests { fields.extend(ids.iter().map(|id| ("repo", id.as_str()))); let six = send(&s.site, "POST", "/settings/pins", Some(&cookie), &fields).await; assert_eq!( - six.status, 200, - "six limit: form shown again, not redirected" + six.location.as_deref(), + Some("/tahinli?pins=too_many"), + "six limit: the profile says why" ); + let told = send(&s.site, "GET", "/tahinli?pins=too_many", Some(&cookie), &[]).await; assert!( - six.body.contains("at most six"), - "six limit: friendly error: {}", - six.body + told.body.contains("at most six"), + "six limit: friendly error" ); assert_eq!( pinned_names(&s.site.store, &s.tahinli).await, diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index 761854c..946f982 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -916,23 +916,15 @@ pub fn admin_items(lang: Lang) -> Vec { ] } -/// The organization's settings sidebar: General and Customize pins. Its profile, repositories, +/// The organization's settings sidebar. Its profile, repositories, /// members and teams are reached from the profile tab bar, so they are not listed here. fn org_items(lang: Lang, org: &str) -> Vec { - vec![ - NavItem { - key: "settings", - href: format!("/org/{org}/settings"), - label: o::t(lang, OK::General), - icon: "appearance", - }, - NavItem { - key: "pins", - href: format!("/org/{org}/settings/pins"), - label: o::t(lang, OK::CustomizePins), - icon: "pins", - }, - ] + vec![NavItem { + key: "settings", + href: format!("/org/{org}/settings"), + label: o::t(lang, OK::General), + icon: "appearance", + }] } /// The profile tab bar in its order, for a person's or an organization's profile: overview, @@ -1064,12 +1056,6 @@ pub fn settings_items(lang: Lang) -> Vec { mi::t(lang, MK::Appearance), "appearance", ), - item( - "pins", - "/settings/pins", - o::t(lang, OK::CustomizePins), - "pins", - ), item( "export", "/settings/export", @@ -1089,7 +1075,7 @@ pub fn section_for(lang: Lang, path: &str) -> Option
    { let (title, items) = match first { "admin" => (ad::t(lang, AK::AdminArea).to_owned(), admin_items(lang)), "settings" => (o::t(lang, OK::Settings).to_owned(), settings_items(lang)), - // An organization's settings pages (`/org/{name}/settings` and `settings/pins`) keep a + // An organization's settings pages (`/org/{name}/settings`) keep a // sidebar. Its profile, members and teams pages have none: the tab bar leads to them. `/org/new` // is the create form and keeps the global links. "org" if !second.is_empty() && second != "new" => { @@ -1790,7 +1776,6 @@ pub async fn ref_selector( - "esc"
    ref_group(lang: lang, kind: "branches", heading: g::t(lang, K::BranchesTitle), links: branches, now: now) @@ -1800,9 +1785,8 @@ pub async fn ref_selector(

    diff --git a/style/_canvas_repo.scss b/style/_canvas_repo.scss index 9e29e96..0d901aa 100644 --- a/style/_canvas_repo.scss +++ b/style/_canvas_repo.scss @@ -518,12 +518,16 @@ opacity: 1; } - // The newest commit is the accent, at full strength, whether or not its run goes. - > a.hs-live, - > a:last-child:not(.hs-bad) { + // Accent means a run is going. The newest commit is only brighter: a bar says nothing of a result + // unless a run failed, and a repo with no CI has none. + > a.hs-live { background: var(--accent); opacity: 1; } + + > a:last-child:not(.hs-bad, .hs-live) { + opacity: 1; + } } // Narrow windows: the panes stack and the page grows; the strip, which needs the width, is left out. diff --git a/style/_fit_forms.scss b/style/_fit_forms.scss index 40c9b26..3235197 100644 --- a/style/_fit_forms.scss +++ b/style/_fit_forms.scss @@ -100,7 +100,8 @@ @media (min-width: 1200px) { .import-home > .newrepo-form { display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-columns: repeat(2, minmax(0, 720px)); + justify-content: start; align-items: start; > :not(.newrepo-card) { diff --git a/style/_lang_admin.scss b/style/_lang_admin.scss index 7950d56..05a201a 100644 --- a/style/_lang_admin.scss +++ b/style/_lang_admin.scss @@ -1,6 +1,6 @@ // Settings and admin pages: the pages behind the site section sidebar (`.shell-site`, see views/mod.rs). -// Main takes the window's full width. From 900px its direct children are panes that sit side by side -// across the window, and anything that is not a pane (the head, a notice) spans the row. Forms stop at +// Main takes the window's full width. From 900px its one pane fills it, or a second pane sits beside +// the first at a form's width, and anything that is not a pane (the head, a notice) spans the row. Forms stop at // 720px and stay left aligned. Repo, org and other pages are not affected. // The page's column: main itself, or the `data-live` wrapper that most admin pages put inside it. @@ -14,7 +14,8 @@ $page-column: ".shell-site > .shell-body > main, .shell-site > .shell-body > mai @media (min-width: 900px) { #{$page-column} { display: grid; - grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr)); + grid-template-columns: minmax(0, 1fr); + align-content: start; align-items: start; gap: 16px; @@ -22,6 +23,12 @@ $page-column: ".shell-site > .shell-body > main, .shell-site > .shell-body > mai grid-column: 1 / -1; } } + + // Two panes: the list takes the window, and the form beside it stays a form's width. + .shell-site > .shell-body > main:has(> .card ~ .card), + .shell-site > .shell-body > main > [data-live]:not(.srv-page):not(.health-page):not(.user-page):not(.teams-page):not(.runner-detail):has(> .card ~ .card) { + grid-template-columns: minmax(0, 1fr) minmax(20rem, 24rem); + } } // Settings pages wrap their sections in one `.settings-layout`; it fills main and takes no max width. diff --git a/style/_palette.scss b/style/_palette.scss index eae010c..e86c2af 100644 --- a/style/_palette.scss +++ b/style/_palette.scss @@ -120,6 +120,13 @@ dialog.palette { } } +.palette-why { + float: right; + margin-left: 12px; + color: var(--muted); + font-size: 0.75rem; +} + .palette-note { flex: none; margin: 0; diff --git a/style/_system.scss b/style/_system.scss index f239605..c46b48d 100644 --- a/style/_system.scss +++ b/style/_system.scss @@ -130,7 +130,7 @@ input[type="checkbox"] { background: var(--accent); } - &:checked::before { + &:checked:not(.switch-row *)::before { content: ""; position: absolute; inset: 0; @@ -341,7 +341,6 @@ main .side-picker > legend { &.active, &[aria-current="page"] { color: var(--text); - font-weight: 600; } } @@ -466,12 +465,10 @@ main .side-picker > legend { } } -// Settings and admin pages lay panes side by side, and the head spans that grid, which keeps two -// tracks open. A page with one pane takes both, and so does a filter with the list it filters. +// A filter stays above the list it filters. @media (min-width: 900px) { .shell-site > .shell-body > main, .shell-site > .shell-body > main > [data-live] { - > .card:not(.card ~ .card):not(:has(~ .card)), > .card:has(> .filter-bar), > .card:has(> .filter-bar) ~ .card { grid-column: 1 / -1; @@ -529,13 +526,6 @@ main .side-picker > legend { align-self: start; } -// The page column's rows start under the head and do not share out the window's height. -@media (min-width: 900px) { - .shell-site > .shell-body > main { - align-content: start; - } -} - // A folder with no README: the list is what the page is for, so it takes the width and its last // commit column comes back. @media (min-width: 900px) { @@ -567,7 +557,8 @@ main .side-picker > legend { // Disclosure rows use the same chevron as every other menu, not the browser's triangle. .checks-details > summary, .commit-full-message > summary, -.ci-tl-more > summary { +.ci-tl-more > summary, +.mx-table > summary { display: inline-flex; align-items: center; gap: 4px; @@ -590,7 +581,8 @@ main .side-picker > legend { .checks-details[open] > summary::before, .commit-full-message[open] > summary::before, -.ci-tl-more[open] > summary::before { +.ci-tl-more[open] > summary::before, +.mx-table[open] > summary::before { transform: rotate(180deg); } @@ -651,3 +643,199 @@ main .side-picker > legend { white-space: normal; } } + +.profile-tabs .tab { + display: inline-flex; + align-items: center; + gap: 6px; + height: 36px; +} + +// Organization pages: the name, the tabs on one rule, then the panes a little below it. +.page-head.org-head { + margin-bottom: 0; + border-bottom: 0; +} + +.org-head + .profile-tabs { + margin-bottom: 16px; +} + +.org-split { + display: grid; + grid-template-columns: minmax(0, 1fr); + align-items: start; + gap: 16px; + + > .card { + margin: 0; + } + + > .card > h3 { + margin: 0 0 12px; + color: var(--muted); + font-family: var(--mono); + font-size: 12px; + font-weight: 500; + letter-spacing: 0.08em; + text-transform: uppercase; + } +} + +@media (min-width: 900px) { + .org-split:has(> .card ~ .card) { + grid-template-columns: minmax(0, 1fr) minmax(20rem, 24rem); + } +} + +// Forms that are a grid do not share out their pane's height. +form.stack[action="/admin/mail"], +.import-home > .newrepo-form { + align-content: start; +} + +@media (min-width: 900px) { + form.stack[action="/admin/mail"] { + max-width: 960px; + } + + // The note and the switch in the third column stand on the fields' line. + form.stack[action="/admin/mail"] > p, + form.stack[action="/admin/mail"] > label:has(> input[type="checkbox"]) { + align-self: end; + min-height: var(--control-h); + margin: 0; + display: flex; + align-items: center; + gap: 8px; + } +} + +// Charts: a figure wraps inside its own column and never runs over the next. +.mx-caption { + white-space: normal; + overflow-wrap: anywhere; +} + +.srv-field > label, +.srv-label { + flex-wrap: wrap; +} + +// Profile pins: the menu sits on the section's head. +.pins-menu { + position: relative; + font-family: var(--font); + font-size: 13px; + font-weight: 400; + letter-spacing: 0; + text-transform: none; +} + +.pins-menu > summary { + list-style: none; + cursor: pointer; + + &::-webkit-details-marker { + display: none; + } +} + +.pins-menu > .pop-panel { + position: absolute; + top: 100%; + right: 0; + left: auto; + z-index: 30; + display: grid; + gap: 10px; + width: min(20rem, calc(100vw - 32px)); + margin-top: 6px; + padding: 12px; + max-height: min(60vh, 28rem); + overflow-y: auto; +} + +.pins-menu > .pop-panel > p { + margin: 0; +} + +.pins-menu > .pop-panel > .primary { + justify-content: center; + text-align: center; +} + +.pins-menu .pin-options { + display: grid; + gap: 2px; + margin: 0; + padding: 0; + list-style: none; + + li { + border: 0; + } + + label { + display: flex; + align-items: center; + gap: 8px; + min-height: 32px; + border: 0; + font-weight: 400; + } +} + +// Explore: organizations are one row of links above the list. +.explore-orgs { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px 16px; + padding: 8px 14px; + border-bottom: 1px solid var(--border); + + > h2 { + margin: 0; + color: var(--muted); + font-family: var(--mono); + font-size: 12px; + font-weight: 500; + letter-spacing: 0.08em; + text-transform: uppercase; + } + + > .item-list { + display: flex; + flex-wrap: wrap; + gap: 16px; + margin: 0; + } +} + +.mx-table > summary { + display: inline-flex; + align-items: center; + gap: 4px; + list-style: none; + cursor: pointer; +} + +// A team: its members and repositories are the page; its own settings stand beside them. +@media (min-width: 900px) { + .team-split { + > .card:first-child { + grid-column: 2; + grid-row: 1 / span 2; + } + + > .card:nth-child(n + 2) { + grid-column: 1; + } + } +} + +.org-split > .card > h2 { + margin: 0 0 4px; + font-size: 16px; +} diff --git a/style/main.scss b/style/main.scss index 190c82d..cbca9bc 100644 --- a/style/main.scss +++ b/style/main.scss @@ -1260,23 +1260,19 @@ code { // A