diff --git a/crates/forge-core/migrations/0073_sage_ink_default.sql b/crates/forge-core/migrations/0073_sage_ink_default.sql new file mode 100644 index 0000000..2d71e3d --- /dev/null +++ b/crates/forge-core/migrations/0073_sage_ink_default.sql @@ -0,0 +1,21 @@ +-- Sage on Ink becomes the look of a new account. An account that never chose its colours moves +-- with the default; one that chose keeps its choice. The Fern and Graphite bases are gone, so an +-- account that chose one moves to Ink. SQLite cannot change a column's default in place, so each +-- column is replaced. +ALTER TABLE users RENAME COLUMN accent TO accent_old; +ALTER TABLE users RENAME COLUMN accent_dark TO accent_dark_old; +ALTER TABLE users RENAME COLUMN base_light TO base_light_old; +ALTER TABLE users RENAME COLUMN base_dark TO base_dark_old; +ALTER TABLE users ADD COLUMN accent TEXT NOT NULL DEFAULT 'sage'; +ALTER TABLE users ADD COLUMN accent_dark TEXT NOT NULL DEFAULT 'sage'; +ALTER TABLE users ADD COLUMN base_light TEXT NOT NULL DEFAULT 'ink'; +ALTER TABLE users ADD COLUMN base_dark TEXT NOT NULL DEFAULT 'ink'; +UPDATE users SET accent = accent_old, accent_dark = accent_dark_old, + base_light = CASE WHEN base_light_old IN ('fern', 'graphite') THEN 'ink' ELSE base_light_old END, + base_dark = CASE WHEN base_dark_old IN ('fern', 'graphite') THEN 'ink' ELSE base_dark_old END +WHERE NOT (accent_old = 'ember' AND accent_dark_old = 'ember' + AND base_light_old = 'anvil' AND base_dark_old = 'anvil'); +ALTER TABLE users DROP COLUMN accent_old; +ALTER TABLE users DROP COLUMN accent_dark_old; +ALTER TABLE users DROP COLUMN base_light_old; +ALTER TABLE users DROP COLUMN base_dark_old; diff --git a/crates/forge-core/src/model.rs b/crates/forge-core/src/model.rs index 644034d..ec5d771 100644 --- a/crates/forge-core/src/model.rs +++ b/crates/forge-core/src/model.rs @@ -48,13 +48,13 @@ pub struct User { /// Language code, e.g. "en"; "auto" uses the instance default. pub language: String, /// Accent colour for the light theme: the id of a palette in forge-web's `accent_palette.rs`. - /// "ember" is the default. + /// "sage" is the default. pub accent: String, - /// Accent colour for the dark theme, chosen separately from `accent`. "ember" is the default. + /// Accent colour for the dark theme, chosen separately from `accent`. "sage" is the default. pub accent_dark: String, - /// Base (neutral background, surface and text) set for the light theme. "anvil" is the default. + /// Base (neutral background, surface and text) set for the light theme. "ink" is the default. pub base_light: String, - /// Base set for the dark theme. "anvil" is the default. + /// Base set for the dark theme. "ink" is the default. pub base_dark: String, /// Which side the main shell sidebar sits on: "left" (the default) or "right". pub sidebar_side: String, diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index dba7b03..c4a5751 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -118,6 +118,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ ), (71, include_str!("../../migrations/0071_ci_job_steps.sql")), (72, include_str!("../../migrations/0072_ember_anvil_default.sql")), + (73, include_str!("../../migrations/0073_sage_ink_default.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/ui_prefs.rs b/crates/forge-core/src/store/ui_prefs.rs index c8e3cf4..00e5057 100644 --- a/crates/forge-core/src/store/ui_prefs.rs +++ b/crates/forge-core/src/store/ui_prefs.rs @@ -15,11 +15,11 @@ pub const AUTO: &str = "auto"; /// The accent colour a new user gets. It must match the default palette in forge-web's /// `accent_palette.rs`, which a test there checks. -pub const DEFAULT_ACCENT: &str = "ember"; +pub const DEFAULT_ACCENT: &str = "sage"; /// The base colour set a new user gets, for both themes. It must match the default base in /// forge-web's `accent_palette.rs`, which a test there checks. -pub const DEFAULT_BASE: &str = "anvil"; +pub const DEFAULT_BASE: &str = "ink"; /// The sidebar sides, in the order the settings page lists them. pub const SIDEBAR_SIDES: &[&str] = &["left", "right"]; @@ -263,7 +263,7 @@ mod tests { assert_eq!(user.base_light, DEFAULT_BASE, "case colours default"); assert_eq!(user.base_dark, DEFAULT_BASE, "case colours default"); store - .set_colours(&user.id, "ocean", "rose", "graphite", "ink") + .set_colours(&user.id, "ocean", "rose", "heather", "ink") .await .unwrap(); let stored = store.user_by_id(&user.id).await.unwrap().unwrap(); @@ -274,12 +274,12 @@ mod tests { stored.base_light.as_str(), stored.base_dark.as_str() ), - ("ocean", "rose", "graphite", "ink"), + ("ocean", "rose", "heather", "ink"), "case colours persisted" ); assert!( store - .set_colours(&user.id, "ocean", "Rose", "graphite", "ink") + .set_colours(&user.id, "ocean", "Rose", "heather", "ink") .await .is_err(), "case colours casing" @@ -293,7 +293,7 @@ mod tests { ); assert!( store - .set_colours(&user.id, "ocean", "rose", "graphite", "") + .set_colours(&user.id, "ocean", "rose", "heather", "") .await .is_err(), "case colours empty" @@ -306,7 +306,7 @@ mod tests { still.base_light.as_str(), still.base_dark.as_str() ), - ("ocean", "rose", "graphite", "ink"), + ("ocean", "rose", "heather", "ink"), "case colours unchanged" ); diff --git a/crates/forge-e2e/tests/e2e/ui_prefs_e2e.rs b/crates/forge-e2e/tests/e2e/ui_prefs_e2e.rs index 53b84d2..3e45b03 100644 --- a/crates/forge-e2e/tests/e2e/ui_prefs_e2e.rs +++ b/crates/forge-e2e/tests/e2e/ui_prefs_e2e.rs @@ -230,7 +230,7 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() { let session = login(&env.http, "tahinli", PW).await; let page = env.http.get("/settings/appearance", Some(&session)).await; - let defaults = ["ember", "ember", "anvil", "anvil"].map(str::to_owned); + let defaults = ["sage", "sage", "ink", "ink"].map(str::to_owned); assert_eq!(checked_colours(&page.body), defaults.clone().map(Some)); assert_eq!(html_colours(&page.body), defaults.map(Some)); let csrf = input_value(&page.body, "csrf"); @@ -267,14 +267,14 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() { ("csrf", &csrf), ("theme", "light"), ("language", "en"), - ("base_dark", "graphite"), + ("base_dark", "heather"), ], Some(&session), ) .await; assert_eq!(saved.status, 303, "save: {}", saved.body); let page = env.http.get("/settings/appearance", Some(&session)).await; - let chosen = ["ocean", "plum", "ink", "graphite"].map(str::to_owned); + let chosen = ["ocean", "plum", "ink", "heather"].map(str::to_owned); assert_eq!(checked_colours(&page.body), chosen.clone().map(Some)); assert_eq!(html_colours(&page.body), chosen.map(Some)); @@ -300,7 +300,7 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() { assert_ne!(res.status, 303, "bad {field} {bad:?} must not save"); } let page = env.http.get("/settings/appearance", Some(&session)).await; - let chosen = ["ocean", "plum", "ink", "graphite"].map(str::to_owned); + let chosen = ["ocean", "plum", "ink", "heather"].map(str::to_owned); assert_eq!(checked_colours(&page.body), chosen.clone().map(Some)); assert_eq!(html_colours(&page.body), chosen.map(Some)); @@ -315,7 +315,7 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() { ("language", "tr"), ("accent_light", "hue-200"), ("accent_dark", "rose"), - ("base_light", "graphite"), + ("base_light", "heather"), ("base_dark", "dusk"), ], Some(&session), @@ -324,9 +324,9 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() { assert_eq!(saved.status, 303, "save: {}", saved.body); let page = env.http.get("/settings/appearance", Some(&session)).await; // The Custom radio carries the hue at the default vividness; the stored id stays `hue-200`. - let checked = ["hue-200-v50", "rose", "graphite", "dusk"].map(str::to_owned); + let checked = ["hue-200-v50", "rose", "heather", "dusk"].map(str::to_owned); assert_eq!(checked_colours(&page.body), checked.map(Some)); - let chosen = ["hue-200", "rose", "graphite", "dusk"].map(str::to_owned); + let chosen = ["hue-200", "rose", "heather", "dusk"].map(str::to_owned); assert_eq!(html_colours(&page.body), chosen.map(Some)); // The newest accents and backgrounds save and show the same way. @@ -341,14 +341,14 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() { ("accent_light", "sage"), ("accent_dark", "ocean"), ("base_light", "ink"), - ("base_dark", "graphite"), + ("base_dark", "heather"), ], Some(&session), ) .await; assert_eq!(saved.status, 303, "save: {}", saved.body); let page = env.http.get("/settings/appearance", Some(&session)).await; - let chosen = ["sage", "ocean", "ink", "graphite"].map(str::to_owned); + let chosen = ["sage", "ocean", "ink", "heather"].map(str::to_owned); assert_eq!(checked_colours(&page.body), chosen.clone().map(Some)); assert_eq!(html_colours(&page.body), chosen.map(Some)); } @@ -370,7 +370,7 @@ async fn a_save_without_colour_fields_keeps_the_stored_colours() { ("language", "en"), ("accent_light", "rose"), ("accent_dark", "ocean"), - ("base_light", "fern"), + ("base_light", "blush"), ("base_dark", "dusk"), ], Some(&session), @@ -378,7 +378,7 @@ async fn a_save_without_colour_fields_keeps_the_stored_colours() { .await; assert_eq!(saved.status, 303, "save: {}", saved.body); let before = env.http.get("/settings/appearance", Some(&session)).await; - let stored = ["rose", "ocean", "fern", "dusk"].map(str::to_owned); + let stored = ["rose", "ocean", "blush", "dusk"].map(str::to_owned); assert_eq!(html_colours(&before.body), stored.clone().map(Some)); let saved = env diff --git a/crates/forge-web-base/src/accent.rs b/crates/forge-web-base/src/accent.rs index b2475c8..f2ca432 100644 --- a/crates/forge-web-base/src/accent.rs +++ b/crates/forge-web-base/src/accent.rs @@ -310,11 +310,11 @@ mod tests { fn the_presets_are_offered_in_picker_order_and_removed_ids_are_not() { assert_eq!( ids().collect::>(), - ["ember", "sage", "ocean", "plum", "rose"] + ["sage", "ember", "ocean", "plum", "rose"] ); assert_eq!( base_ids().collect::>(), - ["anvil", "fern", "graphite", "dusk", "ink"] + ["ink", "anvil", "dusk", "heather", "blush"] ); for id in [ "ochre", @@ -327,7 +327,7 @@ mod tests { ] { assert!(!is_offered(id), "{id}"); } - for id in ["stone", "mist", "Fern", "dune", "slate-blue", "spark"] { + for id in ["stone", "mist", "fern", "graphite", "dune", "slate-blue", "spark"] { assert!(!is_offered_base(id), "{id}"); } } @@ -345,7 +345,8 @@ mod tests { assert_eq!(resolve_base("ink").id, "ink"); assert_eq!(resolve_base("removed-base").id, BASE_DEFAULT); assert_eq!(base_id("mist"), BASE_DEFAULT); - assert_eq!(base_id("graphite"), "graphite"); + assert_eq!(base_id("heather"), "heather"); + assert_eq!(base_id("graphite"), BASE_DEFAULT); } #[test] @@ -383,7 +384,7 @@ mod tests { assert_eq!(preset_accent_hue("plum"), Some(300)); assert_eq!(preset_accent_hue("fern"), None); assert_eq!(preset_accent_hue("hue-5"), None); - assert!(preset_base_hue("fern").is_some()); + assert!(preset_base_hue("blush").is_some()); assert!(preset_base_hue("dusk").is_some()); assert_eq!(preset_base_hue("sage"), None); } @@ -397,10 +398,10 @@ mod tests { accent_tokens(215, 50, false).accent ); assert_eq!(swatch("hue-215", true), accent_tokens(215, 50, true).accent); - // A removed id falls back to the default, Ember. - assert_eq!(swatch("terracotta", false), swatch("ember", false)); - let (bg, text) = base_swatch("fern", false); - assert_eq!((bg.as_str(), text.as_str()), ("#F6F8F5", "#1E2420")); + // A removed id falls back to the default. + assert_eq!(swatch("terracotta", false), swatch(DEFAULT, false)); + let (bg, text) = base_swatch("blush", false); + assert_eq!((bg.as_str(), text.as_str()), ("#F5EBEC", "#2B191C")); let (bg, text) = base_swatch("hue-215", true); assert_eq!(bg, base_tokens(215, 30, true).bg); assert_eq!(text, base_tokens(215, 30, true).text); @@ -408,10 +409,10 @@ mod tests { #[test] fn the_custom_stylesheet_is_linked_only_when_a_hue_is_chosen() { - assert_eq!(custom_css_href("sage", "plum", "fern", "ink"), None); + assert_eq!(custom_css_href("sage", "plum", "blush", "ink"), None); assert_eq!( - custom_css_href("hue-215", "plum", "fern", "hue-7").as_deref(), - Some("/theme/custom.css?al=hue-215&ad=plum&bl=fern&bd=hue-7") + custom_css_href("hue-215", "plum", "blush", "hue-7").as_deref(), + Some("/theme/custom.css?al=hue-215&ad=plum&bl=blush&bd=hue-7") ); assert_eq!( custom_css_href("sage", "sage", "ink", "hue-0").as_deref(), diff --git a/crates/forge-web-base/src/accent_palette.rs b/crates/forge-web-base/src/accent_palette.rs index 073175f..84217eb 100644 --- a/crates/forge-web-base/src/accent_palette.rs +++ b/crates/forge-web-base/src/accent_palette.rs @@ -27,7 +27,7 @@ pub struct Palette { } /// The palette used when none is stored, and for anonymous visitors. It must be `PALETTES[0]`. -pub const DEFAULT: &str = "ember"; +pub const DEFAULT: &str = "sage"; /// One token: the custom property it becomes and the field of `Tokens` that holds its value. pub struct TokenVar { @@ -83,34 +83,6 @@ pub const TOKEN_VARS: &[TokenVar] = &[ /// here: style/_heatmap.scss mixes them from `--accent`/`--accent-ink` and the base's surface, /// so they follow every accent and base. pub const PALETTES: &[Palette] = &[ - // Ember: iron at working heat, a soft red-orange; copper in light. - Palette { - id: "ember", - light: Tokens { - accent: "#B44D1A", - accent_ink: "#8F3A12", - accent_soft: "#F8E9DF", - accent_text: "#FFFFFF", - focus: "#8F3A12", - public_bg: "#F9E4D6", - public_text: "#8F3A12", - note: "#8F3A12", - hunk_bg: "#FBF0E8", - hunk_text: "#883611", - }, - dark: Tokens { - accent: "#E8894A", - accent_ink: "#FFB27A", - accent_soft: "#3A2518", - accent_text: "#1A0E06", - focus: "#FFB27A", - public_bg: "#3A2416", - public_text: "#FFC69A", - note: "#FFB27A", - hunk_bg: "#24180F", - hunk_text: "#F0A066", - }, - }, // Sage: the original forge colour. Palette { id: "sage", @@ -141,6 +113,34 @@ pub const PALETTES: &[Palette] = &[ hunk_text: "#B3C385", }, }, + // Ember: iron at working heat, a soft red-orange; copper in light. + Palette { + id: "ember", + light: Tokens { + accent: "#B44D1A", + accent_ink: "#8F3A12", + accent_soft: "#F8E9DF", + accent_text: "#FFFFFF", + focus: "#8F3A12", + public_bg: "#F9E4D6", + public_text: "#8F3A12", + note: "#8F3A12", + hunk_bg: "#FBF0E8", + hunk_text: "#883611", + }, + dark: Tokens { + accent: "#E8894A", + accent_ink: "#FFB27A", + accent_soft: "#3A2518", + accent_text: "#1A0E06", + focus: "#FFB27A", + public_bg: "#3A2416", + public_text: "#FFC69A", + note: "#FFB27A", + hunk_bg: "#24180F", + hunk_text: "#F0A066", + }, + }, // Blue, clear and cool. Palette { id: "ocean", @@ -253,7 +253,7 @@ pub struct Base { } /// The base used when none is stored, and for anonymous visitors. It must be `BASES[0]`. -pub const BASE_DEFAULT: &str = "anvil"; +pub const BASE_DEFAULT: &str = "ink"; /// One base token: the custom property it becomes and the field of `BaseTokens` that holds its /// value. @@ -314,9 +314,42 @@ pub const BASE_TOKEN_VARS: &[BaseTokenVar] = &[ }, ]; -/// Every base on offer, in the order the picker lists them. `fern` is the original forge -/// neutral set. +/// Every base on offer, in the order the picker lists them: the default first, then each in the +/// column of the accent of its hue (Anvil under Ember, Dusk under Ocean, Heather under Plum, Blush +/// under Rose). Ink's faint olive tint sits with Sage. pub const BASES: &[Base] = &[ + // Ink: crisp white in light, near-black in dark. + Base { + id: "ink", + light: BaseTokens { + bg: "#FCFCFB", + surface: "#FFFFFF", + surface_2: "#F2F2F0", + text: "#111111", + text_2: "#333333", + muted: "#5F5F5C", + border: "#E3E3E0", + border_strong: "#C9C9C5", + code_bg: "#F2F2F0", + private_bg: "#F2F2F0", + private_text: "#333333", + ln_text: "#5F5F5C", + }, + dark: BaseTokens { + bg: "#000000", + surface: "#0B0B0B", + surface_2: "#141414", + text: "#F2F2F0", + text_2: "#CFCFCC", + muted: "#9C9C98", + border: "#242424", + border_strong: "#353535", + code_bg: "#141414", + private_bg: "#141414", + private_text: "#CFCFCC", + ln_text: "#9C9C98", + }, + }, // Anvil: warm soot and cooled steel in dark, ash in light. Base { id: "anvil", @@ -349,71 +382,6 @@ pub const BASES: &[Base] = &[ ln_text: "#AAA69D", }, }, - // Fern: the original forge neutrals, green-tinted in light and slate in dark. - Base { - id: "fern", - light: BaseTokens { - bg: "#F6F8F5", - surface: "#FFFFFF", - surface_2: "#EEF2EC", - text: "#1E2420", - text_2: "#3A433D", - muted: "#667068", - border: "#DDE3DB", - border_strong: "#C5CFC3", - code_bg: "#EEF2EC", - private_bg: "#EEF2EC", - private_text: "#3A433D", - ln_text: "#646D65", - }, - // Dark is cool slate: a green-tinted near-black looked swampy. - dark: BaseTokens { - bg: "#131618", - surface: "#191D20", - surface_2: "#20252A", - text: "#E3E8EA", - text_2: "#C3CACD", - muted: "#96A0A5", - border: "#283035", - border_strong: "#384146", - code_bg: "#1C2125", - private_bg: "#20252A", - private_text: "#C3CACD", - ln_text: "#8A959A", - }, - }, - // Graphite: a cool neutral grey, flatter than the warmer neutrals. - Base { - id: "graphite", - light: BaseTokens { - bg: "#E9EAEC", - surface: "#F9FAFB", - surface_2: "#DCDEE2", - text: "#17191C", - text_2: "#33373D", - muted: "#5C626B", - border: "#CFD3D9", - border_strong: "#B5BBC3", - code_bg: "#DCDEE2", - private_bg: "#DCDEE2", - private_text: "#33373D", - ln_text: "#545A63", - }, - dark: BaseTokens { - bg: "#1A1B1E", - surface: "#222428", - surface_2: "#2B2D32", - text: "#E6E8EB", - text_2: "#C8CCD2", - muted: "#9499A2", - border: "#33363C", - border_strong: "#44484F", - code_bg: "#2B2D32", - private_bg: "#2B2D32", - private_text: "#C8CCD2", - ln_text: "#9499A2", - }, - }, // Dusk: cool blue-grey, a deeper blue-tinted neutral. Base { id: "dusk", @@ -446,36 +414,68 @@ pub const BASES: &[Base] = &[ ln_text: "#8F9BB0", }, }, - // Ink: crisp white in light, near-black in dark. + // Heather: violet-grey, Dusk turned to the hue of Plum. Base { - id: "ink", + id: "heather", light: BaseTokens { - bg: "#FCFCFB", - surface: "#FFFFFF", - surface_2: "#F2F2F0", - text: "#111111", - text_2: "#333333", - muted: "#5F5F5C", - border: "#E3E3E0", - border_strong: "#C9C9C5", - code_bg: "#F2F2F0", - private_bg: "#F2F2F0", - private_text: "#333333", - ln_text: "#5F5F5C", + bg: "#EEECF4", + surface: "#FAF9FD", + surface_2: "#E4E0EC", + text: "#211B2B", + text_2: "#40384F", + muted: "#665E77", + border: "#D6D1E1", + border_strong: "#BDB6CB", + code_bg: "#E4E0EC", + private_bg: "#E4E0EC", + private_text: "#40384F", + ln_text: "#605870", }, dark: BaseTokens { - bg: "#000000", - surface: "#0B0B0B", - surface_2: "#141414", - text: "#F2F2F0", - text_2: "#CFCFCC", - muted: "#9C9C98", - border: "#242424", - border_strong: "#353535", - code_bg: "#141414", - private_bg: "#141414", - private_text: "#CFCFCC", - ln_text: "#9C9C98", + bg: "#110E18", + surface: "#1B1625", + surface_2: "#251F30", + text: "#E8E4F0", + text_2: "#CAC5D7", + muted: "#9D96AD", + border: "#2F293B", + border_strong: "#3F384E", + code_bg: "#251F30", + private_bg: "#251F30", + private_text: "#CAC5D7", + ln_text: "#9D96AD", + }, + }, + // Blush: rose-grey, Dusk turned to the hue of Rose. + Base { + id: "blush", + light: BaseTokens { + bg: "#F5EBEC", + surface: "#FDF9F9", + surface_2: "#EDDEE0", + text: "#2B191C", + text_2: "#4F3438", + muted: "#77595E", + border: "#E2CED1", + border_strong: "#CCB2B6", + code_bg: "#EDDEE0", + private_bg: "#EDDEE0", + private_text: "#4F3438", + ln_text: "#715358", + }, + dark: BaseTokens { + bg: "#180C0E", + surface: "#251316", + surface_2: "#301C20", + text: "#F0E2E4", + text_2: "#D8C2C5", + muted: "#AE9296", + border: "#3C2529", + border_strong: "#4E3438", + code_bg: "#301C20", + private_bg: "#301C20", + private_text: "#D8C2C5", + ln_text: "#AE9296", }, }, ]; diff --git a/crates/forge-web-base/src/i18n/accents.rs b/crates/forge-web-base/src/i18n/accents.rs index f7ce67f..d8b3d67 100644 --- a/crates/forge-web-base/src/i18n/accents.rs +++ b/crates/forge-web-base/src/i18n/accents.rs @@ -39,6 +39,10 @@ pub fn base_name(lang: Lang, id: &str) -> &'static str { ("dusk", Lang::Tr) => "Alacakaranlık", ("graphite", Lang::En) => "Graphite", ("graphite", Lang::Tr) => "Grafit", + ("heather", Lang::En) => "Heather", + ("heather", Lang::Tr) => "Funda", + ("blush", Lang::En) => "Blush", + ("blush", Lang::Tr) => "Allık", ("anvil", Lang::En) => "Anvil", ("anvil", Lang::Tr) => "Örs", _ => "", diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index dae35aa..d6c5650 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -1230,7 +1230,10 @@ dest.search = q ? '?' + q : ''; // Enter in a live field on its own results page runs the search now and leaves the reader typing. var typing = document.activeElement; - if (typing && typing.form === form && typing.hasAttribute('data-live-search') && url.pathname === location.pathname) { + // A filter or option ticked in a form that searches live refreshes in place too. + var liveForm = !!form.querySelector('[data-live-search]'); + if (typing && typing.form === form && url.pathname === location.pathname && + (typing.hasAttribute('data-live-search') || (liveForm && typing.hasAttribute('data-autosubmit')))) { clearTimeout(searchTimer); searchTimer = null; if (dest.pathname + dest.search === shown) { pending.delete(form); return; } @@ -2292,6 +2295,8 @@ // through the same feed. All text is set with textContent, never as HTML. var logQuery = ''; // the search text survives a live swap of the page var LOG_MAX_MARKS = 2000; + var logExact = false; // the Exact and Aa options survive a live swap too + var logCase = false; function ansiState() { return { fg: null, bg: null, b: false, d: false, i: false, u: false, v: false }; } @@ -2504,36 +2509,126 @@ if (bar) { bar.classList.toggle('has-hits', !!text && !none); } } - // Highlights every match of `q` (case-insensitive) in the log and selects the one at `keep`. + // Slips a typed word may have, as views/find.rs counts them: none under four letters, one up to seven, two after. + function logSlips(len) { return len <= 3 ? 0 : (len <= 7 ? 1 : 2); } + + // Edits (insert, delete, change, swap two neighbours) between two words given as character arrays. + function logDistance(a, b) { + if (Math.abs(a.length - b.length) > 2) { return 99; } + var n = a.length, m = b.length, d = [], i, j; + for (i = 0; i <= n; i++) { d.push([i]); } + for (j = 1; j <= m; j++) { d[0][j] = j; } + for (i = 1; i <= n; i++) { + for (j = 1; j <= m; j++) { + var best = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { best = Math.min(best, d[i - 2][j - 2] + 1); } + d[i][j] = best; + } + } + return d[n][m]; + } + + // True when a typed word is close to a word of the line, or to the start of it as long as the word. + function logNear(word, token) { + var slips = logSlips(word.length); + if (!slips) { return false; } + if (logDistance(word, token) <= slips) { return true; } + return token.length > word.length && logDistance(word, token.slice(0, word.length)) <= slips; + } + + // Every place `part` occurs in `hay`, as [start, end) spans. + function logOccur(hay, part, out) { + var from = 0, at; + while (part && (at = hay.indexOf(part, from)) >= 0) { + out.push([at, at + part.length]); + from = at + part.length; + } + return out; + } + + // The spans of one line that match the search, or [] when it does not. Mirrors views/find.rs: the + // whole search as one piece; unless Exact, every typed word as typed (Aa) or, by default, every word + // in the line or close to one of its words (the near word is the span). + function logSpans(text, q, exact, cas) { + var hay = cas ? text : text.toLowerCase(); + var needle = cas ? q : q.toLowerCase(); + if (hay.indexOf(needle) >= 0) { return logOccur(hay, needle, []); } + if (exact) { return []; } + var words = needle.match(/[\p{L}\p{N}]+/gu) || []; + if (!words.length) { return []; } + // Word by word, each typed word must start one of the line's words (or, without Aa, be near + // one), so a short word such as "1" does not match every line with a 1 in it. + var spans = [], w, tokens, i, m, re, found, typed; + tokens = []; + re = /[\p{L}\p{N}]+/gu; + while ((m = re.exec(hay))) { tokens.push([m.index, m.index + m[0].length, m[0], Array.from(m[0])]); } + for (w = 0; w < words.length; w++) { + typed = Array.from(words[w]); + found = false; + for (i = 0; i < tokens.length; i++) { + if (tokens[i][2].indexOf(words[w]) === 0) { + spans.push([tokens[i][0], tokens[i][0] + words[w].length]); found = true; + } else if (!cas && logNear(typed, tokens[i][3])) { + spans.push([tokens[i][0], tokens[i][1]]); found = true; + } + } + if (!found) { return []; } + } + return spans; + } + + // Sorts spans and joins the ones that overlap, so one place is one mark. + function logMerge(spans) { + var sorted = spans.slice().sort(function (x, y) { return x[0] - y[0] || x[1] - y[1]; }); + var out = []; + for (var i = 0; i < sorted.length; i++) { + var last = out[out.length - 1]; + if (last && sorted[i][0] < last[1]) { last[1] = Math.max(last[1], sorted[i][1]); } + else { out.push([sorted[i][0], sorted[i][1]]); } + } + return out; + } + + // Wraps each span of a line's text in a mark, across the line's text nodes. + function logMark(el, spans) { + var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + var nodes = []; + while (walker.nextNode()) { nodes.push(walker.currentNode); } + var base = 0; + for (var k = 0; k < nodes.length; k++) { + var node = nodes[k]; + var end = base + node.data.length; + var cuts = []; + for (var s = 0; s < spans.length; s++) { + var a = Math.max(spans[s][0], base), b = Math.min(spans[s][1], end); + if (a < b) { cuts.push([a - base, b - base]); } + } + for (var c = cuts.length - 1; c >= 0; c--) { + var mid = node.splitText(cuts[c][0]); + mid.splitText(cuts[c][1] - cuts[c][0]); + var mark = document.createElement('mark'); + mark.className = 'lm'; + mid.parentNode.replaceChild(mark, mid); + mark.appendChild(mid); + } + base = end; + } + } + + // Highlights every match of `q` in the log and selects the one at `keep`. function logFind(pre, q, keep) { logClear(pre); logCount('', false); + q = Array.from(q.trim()).slice(0, 100).join(''); if (!q) { return; } - var needle = q.toLowerCase(); var total = 0; var texts = pre.querySelectorAll('.lt'); for (var t = 0; t < texts.length && total < LOG_MAX_MARKS; t++) { - var walker = document.createTreeWalker(texts[t], NodeFilter.SHOW_TEXT); - var nodes = []; - while (walker.nextNode()) { nodes.push(walker.currentNode); } - for (var k = 0; k < nodes.length && total < LOG_MAX_MARKS; k++) { - var node = nodes[k]; - var lower = node.data.toLowerCase(); - var at = [], from = 0, idx; - while ((idx = lower.indexOf(needle, from)) >= 0 && total + at.length < LOG_MAX_MARKS) { - at.push(idx); - from = idx + needle.length; - } - for (var m = at.length - 1; m >= 0; m--) { - var mid = node.splitText(at[m]); - mid.splitText(needle.length); - var mark = document.createElement('mark'); - mark.className = 'lm'; - mid.parentNode.replaceChild(mark, mid); - mark.appendChild(mid); - } - total += at.length; - } + var spans = logSpans(texts[t].textContent, q, logExact, logCase); + if (!spans.length) { continue; } + spans = logMerge(spans).slice(0, LOG_MAX_MARKS - total); + total += spans.length; + logMark(texts[t], spans); } var marks = pre.querySelectorAll('mark.lm'); if (!marks.length) { @@ -2572,6 +2667,10 @@ var pre = document.querySelector('[data-live-log]'); if (!pre || pre.getAttribute('data-ci')) { return; } logInit(pre); + var ex = document.querySelector('[data-log-exact]'); + if (ex) { ex.checked = logExact; } + var cs = document.querySelector('[data-log-case]'); + if (cs) { cs.checked = logCase; } var input = document.querySelector('[data-log-q]'); if (input && logQuery) { input.value = logQuery; logFind(pre, logQuery, -1); } if (location.hash && /^#L\d+$/.test(location.hash)) { logSelect(location.hash.slice(1), true); } @@ -2586,6 +2685,18 @@ logFind(pre, logQuery, -1); }); + // Exact and Aa re-run the search at once. + document.addEventListener('change', function (e) { + var box = e.target; + if (!box || !box.hasAttribute) { return; } + if (box.hasAttribute('data-log-exact')) { logExact = box.checked; } + else if (box.hasAttribute('data-log-case')) { logCase = box.checked; } + else { return; } + var pre = document.querySelector('[data-live-log]'); + if (!pre || !pre._ci) { return; } + logFind(pre, logQuery, -1); + }); + document.addEventListener('keydown', function (e) { var input = e.target; if (!input || !input.hasAttribute || !input.hasAttribute('data-log-q')) { return; } diff --git a/crates/forge-web/src/exporter.rs b/crates/forge-web/src/exporter.rs index 1eaf76b..cb37089 100644 --- a/crates/forge-web/src/exporter.rs +++ b/crates/forge-web/src/exporter.rs @@ -406,6 +406,21 @@ pub async fn sweep_expired(state: &AppState) { } } +/// Deletes one export by hand, its archive and its row. A missing archive is not an error. +pub async fn delete_one(state: &AppState, export: &DataExport) -> forge_core::Result<()> { + match tokio::fs::remove_file(archive_path(state, &export.id)).await { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => { + tracing::warn!(error = %e, "export: could not remove an archive"); + return Err(e.into()); + } + } + state.store.delete_export(&export.id).await?; + bump(&export.user_id); + Ok(()) +} + /// Fails exports a restart cut short and removes expired ones. pub async fn on_boot(state: &AppState) { if let Err(e) = state.store.fail_interrupted_exports().await { diff --git a/crates/forge-web/src/pages/admin_replication.rs b/crates/forge-web/src/pages/admin_replication.rs index 20da536..7b544e6 100644 --- a/crates/forge-web/src/pages/admin_replication.rs +++ b/crates/forge-web/src/pages/admin_replication.rs @@ -27,14 +27,30 @@ use crate::i18n::{self, Lang}; use crate::live::{Topic, stream_changes}; use crate::pages::admin_users::admin_only; use crate::state::AppState; +use crate::pages::issues_list::list_href; +use crate::pages::passkeys::s; +use crate::views::find::{Finder, finder_field}; use crate::views::parts::{SubPart, head, post_act}; +use crate::views::repo_list::{PageLink, pager, pager_links}; use crate::views::{enc, rel_time_or_never, shell}; #[query_params(error = bad_request)] pub(crate) struct NoticeQuery { notice: Option, + q: Option, + exact: Option, + case: Option, + /// The health to list: "ok", "lagging", "error", "never", or anything else for all. + health: Option, + page: Option, } +/// Repos per page of the list. +const REPO_ROWS: usize = 10; + +/// The health filter's values, in the order the menu lists them. +const HEALTH_KEYS: [&str; 4] = ["error", "lagging", "never", "ok"]; + /// How a subject reads on the page. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Health { @@ -64,6 +80,21 @@ impl Health { } } + fn key(self) -> &'static str { + match self { + Health::Ok => "ok", + Health::Lagging => "lagging", + Health::Error => "error", + Health::Never => "never", + } + } + + fn from_key(key: &str) -> Option { + [Health::Ok, Health::Lagging, Health::Error, Health::Never] + .into_iter() + .find(|h| h.key() == key) + } + fn label(self, lang: Lang) -> &'static str { match self { Health::Ok => g::t(lang, K::HealthOk), @@ -91,6 +122,7 @@ fn health(status: Option<&ReplicationStatus>, cutoff: &str) -> Health { /// One line of the repos table, already formatted. struct RepoRow { name: String, + kind: Health, dot: &'static str, tone: &'static str, health: &'static str, @@ -99,6 +131,20 @@ struct RepoRow { error: String, } +impl RepoRow { + fn copy(&self) -> RepoRow { + RepoRow { + name: self.name.clone(), + kind: self.kind, + dot: self.dot, + tone: self.tone, + health: self.health, + last_ok: self.last_ok.clone(), + error: self.error.clone(), + } + } +} + /// Everything the page shows, already formatted. struct PageData { enabled: bool, @@ -139,6 +185,7 @@ async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result let h = health(status, &repo_cutoff); repos.push(RepoRow { name, + kind: h, dot: h.dot(), tone: h.tone(), health: h.label(lang), @@ -154,6 +201,7 @@ async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result let h = health(Some(status), &repo_cutoff); repos.push(RepoRow { name: g::deleted_repo_name(lang, &status.subject), + kind: h, dot: h.dot(), tone: h.tone(), health: h.label(lang), @@ -187,7 +235,20 @@ async fn replication_view( csrf: String, data: PageData, notice: Option, + list: RepoList, ) -> Result { + let RepoList { + finder, + health, + rows, + page, + pages, + nav: (links, prev, next), + } = list; + let has_repos = !data.repos.is_empty(); + let all_label = s(lang, "All", "Tümü"); + let health_label = s(lang, "Health", "Durum"); + let placeholder = s(lang, "Search repositories", "Depolarda ara"); let sub = vec![SubPart::text(g::t(lang, K::ReplicationIntro))]; Ok(view! { head(title: g::t(lang, K::Replication), sub: sub, @@ -239,12 +300,29 @@ async fn replication_view( }

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

- if data.repos.is_empty() { + if !has_repos {

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

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

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

} else { - for row in data.repos.into_iter() { + + if rows.is_empty() { +

(s(lang, "No repository matches.", "Eşleşen depo yok."))

+ } + for row in rows.into_iter() {
(row.name.as_str()) (row.health) " · " (g::t(lang, K::LastSuccess)) ": " rel_time_or_never(lang: lang, stamp: row.last_ok.as_deref()) @@ -255,6 +333,7 @@ async fn replication_view( } }
+ pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang) }) } @@ -297,17 +376,73 @@ async fn replication_events(cx: &Cx) -> Result { .await } +/// One page of the repo list, after the search and the health filter. +struct RepoList { + finder: Finder, + health: Option, + rows: Vec, + page: u64, + pages: u64, + nav: (Vec, Option, Option), +} + +/// Takes the repos that match the query out of `data`, a page of them. +fn repo_list(data: &mut PageData, query: &NoticeQuery) -> RepoList { + let finder = Finder::new( + query.q.as_deref(), + query.exact.as_deref(), + query.case.as_deref(), + ); + let health = query.health.as_deref().and_then(Health::from_key); + let matching: Vec = data + .repos + .iter() + .filter(|row| health.is_none_or(|h| row.kind == h)) + .filter(|row| finder.matches_any(&[row.name.as_str(), row.error.as_str()])) + .map(RepoRow::copy) + .collect(); + let pages = (matching.len() as u64).div_ceil(REPO_ROWS as u64).max(1); + let page = query + .page + .as_deref() + .and_then(|p| p.parse::().ok()) + .unwrap_or(1) + .clamp(1, pages); + let rows = matching + .into_iter() + .skip((page - 1) as usize * REPO_ROWS) + .take(REPO_ROWS) + .collect(); + let health_key = health.map_or("", Health::key); + let nav = pager_links(page, pages, |n| { + let number = n.to_string(); + let mut params = finder.params(); + params.push(("health", health_key)); + params.push(("page", number.as_str())); + list_href("/admin/replication", ¶ms) + }); + RepoList { + finder, + health, + rows, + page, + pages, + nav, + } +} + #[page("/admin/replication")] async fn replication_page(cx: &Cx) -> Result { let viewer = admin_only(cx).await?; let query = query_params::(cx)?; let lang = i18n::lang(cx, Some(&viewer.0)); let state = app_context::(cx); - let data = page_data(state, lang).await?; + let mut data = page_data(state, lang).await?; + let list = repo_list(&mut data, query); let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::Replication); Ok(view! { - shell(title: title, viewer: Some(&viewer), replication_view(lang: lang, csrf: csrf, data: data, notice: query.notice.clone())) + shell(title: title, viewer: Some(&viewer), replication_view(lang: lang, csrf: csrf, data: data, notice: query.notice.clone(), list: list)) }) } diff --git a/crates/forge-web/src/pages/admin_server.rs b/crates/forge-web/src/pages/admin_server.rs index 0dbae94..00186b9 100644 --- a/crates/forge-web/src/pages/admin_server.rs +++ b/crates/forge-web/src/pages/admin_server.rs @@ -38,6 +38,7 @@ use crate::pages::ci_runs::{changed_event, events_response}; use crate::pages::passkeys::s; use crate::self_update; use crate::state::AppState; +use crate::views::find::{Finder, finder_field}; use crate::views::parts::{RailItem, SubPart, confirm_act, head, rail}; use crate::views::{enc, shell}; @@ -48,6 +49,10 @@ pub(crate) struct ServerQuery { cat: Option, /// The search text: when set, the page lists the matching settings from every category instead. q: Option, + /// Set when the search asks for the text as typed, as one piece. + exact: Option, + /// Set when the search keeps upper and lower case apart. + case: Option, /// The older name for `cat`, still read so an old link opens the same category. tab: Option, /// The boot id of the server that was asked to restart. @@ -329,19 +334,15 @@ async fn rows_for(state: &AppState, lang: Lang, page: &SrvPage) -> forge_core::R .collect()) } -/// The settings from every category whose key, label or help holds `needle` (already lowercase). -async fn search_hits(state: &AppState, lang: Lang, needle: &str) -> forge_core::Result> { +/// The settings from every category whose key, label or help matches the search. +async fn search_hits(state: &AppState, lang: Lang, finder: &Finder) -> forge_core::Result> { let overrides = state.store.server_overrides().await?; Ok(state .settings .views(&overrides) .iter() .map(|view| row(lang, view)) - .filter(|hit| { - hit.key.contains(needle) - || hit.label.to_lowercase().contains(needle) - || hit.help.to_lowercase().contains(needle) - }) + .filter(|hit| finder.matches_any(&[hit.key, hit.label, hit.help])) .collect()) } @@ -419,7 +420,7 @@ async fn server_view( csrf: String, page: &'static SrvPage, rows: Vec, - q: String, + finder: Finder, search: Option>, notice: Option, restart: Restart, @@ -472,10 +473,8 @@ async fn server_view( }
rail(label: g::t(lang, K::ServerSettings), items: items, - )
@@ -528,17 +527,20 @@ async fn server_page(cx: &Cx) -> Result { .or(query.tab.as_deref()) .and_then(page_by_slug) .unwrap_or(&PAGES[0]); - let q = query.q.clone().unwrap_or_default(); - let needle = q.trim().to_lowercase(); - let (rows, search) = if needle.is_empty() { + let finder = Finder::new( + query.q.as_deref(), + query.exact.as_deref(), + query.case.as_deref(), + ); + let (rows, search) = if finder.is_empty() { (rows_for(state, lang, page).await?, None) } else { - (Vec::new(), Some(search_hits(state, lang, &needle).await?)) + (Vec::new(), Some(search_hits(state, lang, &finder).await?)) }; let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::ServerSettings); Ok(view! { - shell(title: title, viewer: Some(&viewer), server_view(lang: lang, csrf: csrf, page: page, rows: rows, q: q, search: search, notice: query.notice.clone(), restart: restart_state(query.restarting.as_deref()))) + shell(title: title, viewer: Some(&viewer), server_view(lang: lang, csrf: csrf, page: page, rows: rows, finder: finder, search: search, notice: query.notice.clone(), restart: restart_state(query.restarting.as_deref()))) }) } diff --git a/crates/forge-web/src/pages/admin_users.rs b/crates/forge-web/src/pages/admin_users.rs index 4a89883..04cd9ea 100644 --- a/crates/forge-web/src/pages/admin_users.rs +++ b/crates/forge-web/src/pages/admin_users.rs @@ -23,15 +23,15 @@ use crate::live::{Topic, stream_changes}; use crate::pages::passkeys::s; use crate::state::AppState; use crate::views::parts::{head, reveal}; +use crate::pages::issues_list::list_href; +use crate::views::find::{Finder, finder_field}; use crate::views::repo_list::{pager, pager_links}; use crate::views::{alert, enc, rel_time, shell, user_facing_message}; const MIN_PASSWORD_CHARS: usize = 12; const MAX_PASSWORD_BYTES: usize = 1024; /// Accounts per page of the list. -const PER_PAGE: u64 = 50; -/// The longest search the list takes. -const MAX_QUERY_CHARS: usize = 100; +const PER_PAGE: u64 = 12; #[derive(Deserialize)] struct CreateUserForm { @@ -59,6 +59,8 @@ struct DeleteForm { #[query_params(error = bad_request)] struct UsersQuery { q: Option, + exact: Option, + case: Option, kind: Option, page: Option, } @@ -98,16 +100,13 @@ impl Kind { } } -/// The search text, kind and page the query asks for, with the defaults filled in. -fn listing_args(query: &UsersQuery) -> (String, Kind, u64) { - let q: String = query - .q - .as_deref() - .unwrap_or("") - .trim() - .chars() - .take(MAX_QUERY_CHARS) - .collect(); +/// The search, kind and page the query asks for, with the defaults filled in. +fn listing_args(query: &UsersQuery) -> (Finder, Kind, u64) { + let finder = Finder::new( + query.q.as_deref(), + query.exact.as_deref(), + query.case.as_deref(), + ); let kind = Kind::parse(query.kind.as_deref()); let page = query .page @@ -115,31 +114,21 @@ fn listing_args(query: &UsersQuery) -> (String, Kind, u64) { .and_then(|p| p.parse::().ok()) .unwrap_or(1) .max(1); - (q, kind, page) + (finder, kind, page) } /// `/admin/users` with the search, the kind and the page. An empty search is left out. -fn users_href(q: &str, kind: Kind, page: u64) -> String { - let mut href = String::from("/admin/users?"); - if !q.is_empty() { - href.push_str("q="); - href.push_str(&enc(q)); - href.push('&'); - } - href.push_str(&format!("kind={}&page={page}", kind.key())); - href +fn users_href(finder: &Finder, kind: Kind, page: u64) -> String { + let number = page.to_string(); + let mut params = finder.params(); + params.push(("kind", kind.key())); + params.push(("page", number.as_str())); + list_href("/admin/users", ¶ms) } -/// Whether the account's name or email holds the lowercase search text. An empty search holds all. -fn matches_search(user: &User, needle: &str) -> bool { - needle.is_empty() - || user.username.to_lowercase().contains(needle) - || user - .email - .as_deref() - .unwrap_or("") - .to_lowercase() - .contains(needle) +/// Whether the account's name or email matches the search. An empty search matches all. +fn matches_search(user: &User, finder: &Finder) -> bool { + finder.matches_any(&[user.username.as_str(), user.email.as_deref().unwrap_or("")]) } /// The ghost account is reserved and never shown as a deletable user. @@ -182,15 +171,14 @@ async fn users_view( lang: Lang, csrf: &str, users: Vec, - q: String, + finder: Finder, kind: Kind, page: u64, error: Option, ) -> Result { - let needle = q.to_lowercase(); let matching: Vec = users .into_iter() - .filter(|user| matches_search(user, &needle)) + .filter(|user| matches_search(user, &finder)) .collect(); let all_count = matching.len(); let org_count = matching.iter().filter(|user| user.is_org()).count(); @@ -205,10 +193,15 @@ async fn users_view( .take(PER_PAGE as usize) .map(|user| UserRow::new(lang, user)) .collect(); - let (links, prev, next) = pager_links(page, pages, |n| users_href(&q, kind, n)); + let (links, prev, next) = pager_links(page, pages, |n| users_href(&finder, kind, n)); let empty = rows.is_empty(); let open = error.is_some(); - let search_label = s(lang, "Search users and organizations", "Kullanıcı ve kuruluşlarda ara"); + // The field says what the current tab lists. + let search_label = match kind { + Kind::All => s(lang, "Search users and organizations", "Kullanıcı ve kuruluşlarda ara"), + Kind::People => s(lang, "Search users", "Kullanıcılarda ara"), + Kind::Organizations => s(lang, "Search organizations", "Kuruluşlarda ara"), + }; let filter_label = s(lang, "Filter", "Filtre"); let all_label = format!("{} {}", s(lang, "All", "Tümü"), all_count); let people_label = format!( @@ -217,9 +210,9 @@ async fn users_view( all_count - org_count ); let orgs_label = format!("{} {}", og::t(lang, OG::Organizations), org_count); - let all_href = users_href(&q, Kind::All, 1); - let people_href = users_href(&q, Kind::People, 1); - let orgs_href = users_href(&q, Kind::Organizations, 1); + let all_href = users_href(&finder, Kind::All, 1); + let people_href = users_href(&finder, Kind::People, 1); + let orgs_href = users_href(&finder, Kind::Organizations, 1); Ok(view! { head(title: g::t(lang, K::Users), reveal(label: g::t(lang, K::CreateUser), id: Some("create-user"), open: open, @@ -256,10 +249,8 @@ async fn users_view(
-
@@ -330,12 +321,12 @@ async fn users_events(cx: &Cx) -> Result { async fn users_page(cx: &Cx) -> Result { let viewer = admin_only(cx).await?; let lang = i18n::lang(cx, Some(&viewer.0)); - let (q, kind, page) = listing_args(query_params::(cx)?); + let (finder, kind, page) = listing_args(query_params::(cx)?); let users = app_context::(cx).store.list_users().await?; let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::Users); Ok(view! { - shell(title: title, viewer: Some(&viewer), users_view(lang: lang, csrf: csrf.as_str(), users: users, q: q, kind: kind, page: page, error: None)) + shell(title: title, viewer: Some(&viewer), users_view(lang: lang, csrf: csrf.as_str(), users: users, finder: finder, kind: kind, page: page, error: None)) }) } @@ -372,7 +363,7 @@ async fn users_create(cx: &Cx, Form(form): Form) -> Result, + /// An exact actor username. No form sends it any more (the search covers actors); old links + /// still filter by it. actor: Option, + q: Option, + exact: Option, + case: Option, /// Old cursor links. Still accepted so old bookmarks load, and ignored. #[allow(dead_code)] before: Option, @@ -44,23 +51,81 @@ pub(crate) struct AuditQuery { page: Option, } -/// One table row, already formatted for display. A row can stand for several entries in a row. +/// One entry, already formatted for display. struct RowView { when: String, actor: String, - /// The action as words: "Ui prefs changed". + /// The action as words: "Display preferences changed". name: String, /// The raw action, for the hover title. action: String, /// "kind: name", or the name alone, or empty when the entry has no target name. target: String, ip: String, - /// The details when short enough to show in the row. Empty when they are long. - details_inline: String, - /// The details when too long for the row, for the line's hover title. Empty otherwise. - details_title: String, - /// How many entries this row stands for. - count: usize, + /// The details as words, whole. + details: String, +} + +impl RowView { + /// Every word a search reads. + fn text(&self) -> String { + [ + self.name.as_str(), + self.action.as_str(), + self.actor.as_str(), + self.target.as_str(), + self.ip.as_str(), + self.details.as_str(), + ] + .join(" \u{1f} ") + } + + /// The details as shown in a row: cut when long. + fn details_short(&self) -> String { + if self.details.chars().count() <= DETAILS_INLINE_CHARS { + self.details.clone() + } else { + let cut: String = self.details.chars().take(DETAILS_INLINE_CHARS).collect(); + format!("{cut}\u{2026}") + } + } +} + +/// A run of entries of one action by one actor, newest first. A run of one is a plain row. +struct Group { + /// The key the run folds on. + key: (String, Option, String), + rows: Vec, +} + +impl Group { + fn first(&self) -> &RowView { + &self.rows[0] + } + + /// The target when every entry has the same one. + fn shared_target(&self) -> Option<&str> { + let first = self.first().target.as_str(); + self.rows + .iter() + .all(|row| row.target == first) + .then_some(first) + } + + /// The IP when every entry came from the same one. + fn shared_ip(&self) -> Option<&str> { + let first = self.first().ip.as_str(); + self.rows.iter().all(|row| row.ip == first).then_some(first) + } + + /// The details when every entry has the same. + fn shared_details(&self) -> Option<&str> { + let first = self.first().details.as_str(); + self.rows + .iter() + .all(|row| row.details == first) + .then_some(first) + } } /// "ci_secret_set" as "CI secret set": words, with the short names in capitals. @@ -164,11 +229,6 @@ fn row_view(entry: &AuditEntry, lang: Lang) -> RowView { } else { details_words(lang, &entry.data) }; - let (details_inline, details_title) = if details.chars().count() < DETAILS_INLINE_CHARS { - (details.clone(), String::new()) - } else { - (String::new(), details.clone()) - }; RowView { when: entry.at.clone(), actor, @@ -176,32 +236,33 @@ fn row_view(entry: &AuditEntry, lang: Lang) -> RowView { action: entry.action.as_str().to_owned(), target, ip: entry.ip.clone(), - details_inline, - details_title, - count: 1, + details, } } -/// Rows for `entries` (newest first), with consecutive entries of the same action, actor and -/// target folded into one row. The row keeps the newest entry's time, IP and details. -fn fold_rows(entries: &[AuditEntry], lang: Lang) -> Vec { - let mut rows: Vec<(&AuditEntry, RowView)> = Vec::new(); +/// Groups for `entries` (newest first) that match the search: consecutive entries of the same +/// action by the same actor fold into one group, whatever their targets. +fn fold_groups(entries: &[AuditEntry], lang: Lang, finder: &Finder) -> Vec { + let mut groups: Vec = Vec::new(); for entry in entries { - if let Some((last, row)) = rows.last_mut() { - let same = last.action == entry.action - && last.actor_id == entry.actor_id - && last.actor_name == entry.actor_name - && last.target_kind == entry.target_kind - && last.target_id == entry.target_id - && last.target_name == entry.target_name; - if same { - row.count += 1; - continue; - } + let row = row_view(entry, lang); + if !finder.matches(&row.text()) { + continue; + } + let key = ( + entry.action.as_str().to_owned(), + entry.actor_id.clone(), + entry.actor_name.clone(), + ); + match groups.last_mut() { + Some(group) if group.key == key => group.rows.push(row), + _ => groups.push(Group { + key, + rows: vec![row], + }), } - rows.push((entry, row_view(entry, lang))); } - rows.into_iter().map(|(_, row)| row).collect() + groups } /// The page the query asks for, 1-based. Anything unreadable is page 1. @@ -214,23 +275,21 @@ fn requested_page(query: &AuditQuery) -> u64 { .max(1) } -/// One page of `size` entries, and the page that was asked for, clamped to the pages there are, -/// with the page count. -async fn fetch_page( - store: &Store, - filter: &AuditFilter, - page: u64, - size: usize, -) -> forge_core::Result<(Vec, u64, u64)> { - let total = store.count_audit(filter).await?; - let pages = total.div_ceil(size as u64).max(1); +/// The groups of one page, the page clamped to the pages there are, and the page count. +fn page_of(mut groups: Vec, page: u64) -> (Vec, u64, u64) { + let pages = (groups.len() as u64).div_ceil(PAGE_ROWS as u64).max(1); let page = page.clamp(1, pages); - let offset = ((page - 1) * size as u64) as u32; - let entries = store.list_audit_page(filter, offset, size as u32).await?; - Ok((entries, page, pages)) + let start = (page - 1) as usize * PAGE_ROWS; + let shown: Vec = groups.drain(..).skip(start).take(PAGE_ROWS).collect(); + (shown, page, pages) +} + +/// The newest entries the filter selects, as many as a search reads. +async fn fetch_entries(store: &Store, filter: &AuditFilter) -> forge_core::Result> { + store.list_audit_page(filter, 0, SEARCH_CAP).await } -/// The numbered pager's entries and links for `page` of `pages`, under `href`'s params. +/// The numbered pager's entries and links for `page` of `pages`, under `base` with `params`. fn nav_for( page: u64, pages: u64, @@ -245,48 +304,181 @@ fn nav_for( }) } +/// The search and the action filter, in one GET form to `action`. #[component] -async fn audit_table(lang: Lang, rows: Vec, show_actor: bool) -> Result { +async fn log_tools( + lang: Lang, + form_action: &str, + finder: Finder, + action: String, + actor: String, +) -> Result { + let placeholder = s(lang, "Search the log", "Günlükte ara"); Ok(view! { - if rows.is_empty() { +
+
+ finder_field(lang: lang, finder: finder, placeholder: placeholder, id: Some("log-q")) + + if !actor.is_empty() { + + } +
+
+ }) +} + +/// The facts of one entry after its name: time, then whatever `show` asks for. +#[component] +async fn entry_facts( + lang: Lang, + row: RowView, + show_actor: bool, + show_target: bool, + show_ip: bool, + show_details: bool, +) -> Result { + let details = row.details_short(); + Ok(view! { + rel_time(lang: lang, stamp: row.when.as_str()) + if show_actor { + " · " (row.actor.as_str()) + } + if show_target && !row.target.is_empty() { + " · " (row.target.as_str()) + } + if show_ip && !row.ip.is_empty() { + " · IP " (row.ip.as_str()) + } + if show_details && !details.is_empty() { + " · " (details.as_str()) + } + }) +} + +#[component] +async fn audit_table(lang: Lang, groups: Vec, show_actor: bool) -> Result { + Ok(view! { + if groups.is_empty() {

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

} else { - for row in rows.into_iter() { - let count = row.count.to_string(); -
- (row.name.as_str()) - if row.count > 1 { - "×" (count.as_str()) - } - - rel_time(lang: lang, stamp: row.when.as_str()) - if show_actor { - " · " (row.actor.as_str()) - } - if !row.target.is_empty() { - " · " (row.target.as_str()) - } - if !row.ip.is_empty() { - " · IP " (row.ip.as_str()) - } - if !row.details_inline.is_empty() { - " · " (row.details_inline.as_str()) - } - -
+ for group in groups.into_iter() { + if group.rows.len() == 1 { + single_row(lang: lang, group: group, show_actor: show_actor) + } else { + group_row(lang: lang, group: group, show_actor: show_actor) + } } } }) } +/// One entry on its own line. +#[component] +async fn single_row(lang: Lang, mut group: Group, show_actor: bool) -> Result { + let row = group.rows.remove(0); + let title = row.details.clone(); + let name = row.name.clone(); + let action = row.action.clone(); + Ok(view! { +
+ (name.as_str()) + entry_facts(lang: lang, row: row, show_actor: show_actor, show_target: true, show_ip: true, show_details: true) +
+ }) +} + +/// A run of entries: one row with the count and what they share, which opens to list each one +/// with what differs. +#[component] +async fn group_row(lang: Lang, mut group: Group, show_actor: bool) -> Result { + let count = group.rows.len().to_string(); + let target = group.shared_target().map(str::to_owned); + let ip = group.shared_ip().map(str::to_owned).filter(|ip| !ip.is_empty()); + let details = group + .shared_details() + .map(str::to_owned) + .filter(|d| !d.is_empty()); + let mut seen: Vec = group.rows.iter().map(|row| row.target.clone()).collect(); + seen.sort_unstable(); + seen.dedup(); + let target_text = match target.as_deref() { + Some(target) => target.to_owned(), + None => format!("{} {}", seen.len(), s(lang, "targets", "hedef")), + }; + let show_target = target.is_none(); + let show_ip = ip.is_none(); + let show_details = details.is_none(); + let ip = ip.unwrap_or_default(); + let details = details.unwrap_or_default(); + let name = group.first().name.clone(); + let action = group.first().action.clone(); + let when = group.first().when.clone(); + let actor = group.first().actor.clone(); + let rows = std::mem::take(&mut group.rows); + Ok(view! { +
+ + (name.as_str()) + "×" (count.as_str()) + + rel_time(lang: lang, stamp: when.as_str()) + if show_actor { + " · " (actor.as_str()) + } + if !target_text.is_empty() { + " · " (target_text.as_str()) + } + if !ip.is_empty() { + " · IP " (ip.as_str()) + } + if !details.is_empty() { + " · " (details.as_str()) + } + + +
+ for row in rows.into_iter() { + item_line(lang: lang, row: row, show_target: show_target, show_ip: show_ip, show_details: show_details) + } +
+
+ }) +} + +/// One entry inside an opened run: its time and what the run's row does not already say. +#[component] +async fn item_line( + lang: Lang, + row: RowView, + show_target: bool, + show_ip: bool, + show_details: bool, +) -> Result { + let title = row.details.clone(); + Ok(view! { +
+ entry_facts(lang: lang, row: row, show_actor: false, show_target: show_target, show_ip: show_ip, show_details: show_details) +
+ }) +} + #[component] async fn admin_audit_view( lang: Lang, live: String, + finder: Finder, action: String, actor: String, notice: Option, - rows: Vec, + groups: Vec, page: u64, pages: u64, nav: (Vec, Option, Option), @@ -296,28 +488,11 @@ async fn admin_audit_view( Ok(view! { head(title: g::t(lang, K::AuditLog), sub: sub)
-
-
- - -
-
+ log_tools(lang: lang, form_action: "/admin/audit", finder: finder, action: action, actor: actor) if let Some(message) = notice {

(message.as_str())

} - audit_table(lang: lang, rows: rows, show_actor: true) + audit_table(lang: lang, groups: groups, show_actor: true) pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang)
}) @@ -327,7 +502,9 @@ async fn admin_audit_view( async fn own_log_view( lang: Lang, items: Vec, - rows: Vec, + finder: Finder, + action: String, + groups: Vec, page: u64, pages: u64, nav: (Vec, Option, Option), @@ -339,25 +516,41 @@ async fn own_log_view(
rail(label: i18n::t(lang, i18n::Key::Security), items: items)
-
-

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

-

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

- audit_table(lang: lang, rows: rows, show_actor: false) -
+ log_tools(lang: lang, form_action: "/settings/security/log", finder: finder, action: action, actor: String::new()) + audit_table(lang: lang, groups: groups, show_actor: false) pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang)
}) } +/// The search, action and actor a query asks for, trimmed. +fn query_parts(query: &AuditQuery) -> (Finder, String, String) { + let finder = Finder::new( + query.q.as_deref(), + query.exact.as_deref(), + query.case.as_deref(), + ); + let action = query.action.clone().unwrap_or_default().trim().to_owned(); + let actor = query.actor.clone().unwrap_or_default().trim().to_owned(); + (finder, action, actor) +} + +/// The link params that keep the search and filters. +fn keep_params<'a>(finder: &'a Finder, action: &'a str, actor: &'a str) -> Vec<(&'a str, &'a str)> { + let mut params = finder.params(); + params.push(("action", action)); + params.push(("actor", actor)); + params +} + #[page("/admin/audit")] async fn admin_audit_page(cx: &Cx) -> Result { let viewer = admin_only(cx).await?; let lang = i18n::lang(cx, Some(&viewer.0)); let query = query_params::(cx)?; let store = &app_context::(cx).store; - let action = query.action.clone().unwrap_or_default().trim().to_owned(); - let actor = query.actor.clone().unwrap_or_default().trim().to_owned(); + let (finder, action, actor) = query_parts(query); let mut filter = AuditFilter::default(); let mut notice: Option = None; @@ -374,30 +567,26 @@ async fn admin_audit_page(cx: &Cx) -> Result { } } // An unknown action or actor matches nothing, so the notice explains the empty table. - let (entries, page, pages) = if notice.is_some() { - (Vec::new(), 1, 1) + let entries = if notice.is_some() { + Vec::new() } else { - fetch_page(store, &filter, requested_page(&query), ADMIN_PAGE_SIZE).await? + fetch_entries(store, &filter).await? }; - - let rows = fold_rows(&entries, lang); - let nav = nav_for( - page, - pages, - "/admin/audit", - &[("action", action.as_str()), ("actor", actor.as_str())], - ); + let groups = fold_groups(&entries, lang, &finder); + let (groups, page, pages) = page_of(groups, requested_page(query)); + let params = keep_params(&finder, &action, &actor); + let nav = nav_for(page, pages, "/admin/audit", ¶ms); let live = list_href( "/admin/audit/events", &[("action", action.as_str()), ("actor", actor.as_str())], ); let title = g::t(lang, K::AuditLog); Ok(view! { - shell(title: title, viewer: Some(&viewer), admin_audit_view(lang: lang, live: live, action: action, actor: actor, notice: notice, rows: rows, page: page, pages: pages, nav: nav)) + shell(title: title, viewer: Some(&viewer), admin_audit_view(lang: lang, live: live, finder: finder.clone(), action: action.clone(), actor: actor.clone(), notice: notice, groups: groups, page: page, pages: pages, nav: nav)) }) } -/// The first page of entries the filter selects, as one string: the stream sends when it changes. +/// The newest entries the filter selects, as one string: the stream sends when it changes. /// An unknown action or actor selects nothing, as on the page. async fn first_page_fingerprint(store: &Store, action: &str, actor: &str) -> Result { let mut filter = AuditFilter::default(); @@ -413,7 +602,7 @@ async fn first_page_fingerprint(store: &Store, action: &str, actor: &str) -> Res None => return Ok(String::new()), } } - let (entries, _, _) = fetch_page(store, &filter, 1, ADMIN_PAGE_SIZE).await?; + let entries = store.list_audit_page(&filter, 0, PAGE_ROWS as u32).await?; Ok(entries .iter() .map(|entry| entry.id.as_str()) @@ -444,19 +633,24 @@ async fn own_log_page(cx: &Cx) -> Result { let lang = i18n::lang(cx, Some(&viewer.0)); let query = query_params::(cx)?; let store = &app_context::(cx).store; - let filter = AuditFilter { + let (finder, action, _) = query_parts(query); + let mut filter = AuditFilter { involving_user: Some(viewer.0.id.clone()), ..Default::default() }; - let (entries, page, pages) = - fetch_page(store, &filter, requested_page(&query), OWN_PAGE_SIZE).await?; - - let rows = fold_rows(&entries, lang); - let nav = nav_for(page, pages, "/settings/security/log", &[]); + // An unknown action is ignored here: the menu only offers known ones. + if let Some(known) = AuditAction::parse(&action) { + filter.action = Some(known); + } + let entries = fetch_entries(store, &filter).await?; + let groups = fold_groups(&entries, lang, &finder); + let (groups, page, pages) = page_of(groups, requested_page(query)); + let params = keep_params(&finder, &action, ""); + let nav = nav_for(page, pages, "/settings/security/log", ¶ms); let items = security_rail_for(app_context::(cx), lang, &viewer, "log").await?; let title = g::t(lang, K::SecurityLogTitle); Ok(view! { - shell(title: title, viewer: Some(&viewer), own_log_view(lang: lang, items: items, rows: rows, page: page, pages: pages, nav: nav)) + shell(title: title, viewer: Some(&viewer), own_log_view(lang: lang, items: items, finder: finder.clone(), action: action.clone(), groups: groups, page: page, pages: pages, nav: nav)) }) } @@ -604,7 +798,8 @@ mod tests { ) .await; assert_eq!(status, 200); - assert_eq!(body.matches("login_success").count(), 1); + // One row of the viewer's own sign-in (the action filter lists it once more). + assert_eq!(body.matches("title=\"login_success\"").count(), 1); assert!(body.contains("password_reset_by_admin")); // The own log needs a session. @@ -618,6 +813,6 @@ mod tests { let row = row_view(&entry, Lang::En); assert_eq!(row.actor, "anonymous"); assert_eq!(row.target, "mallory"); - assert_eq!(row.details_inline, ""); + assert_eq!(row.details, ""); } } diff --git a/crates/forge-web/src/pages/avatars.rs b/crates/forge-web/src/pages/avatars.rs index 0d2529d..33b0e0e 100644 --- a/crates/forge-web/src/pages/avatars.rs +++ b/crates/forge-web/src/pages/avatars.rs @@ -24,6 +24,9 @@ const PALETTE: [&str; 8] = [ const CACHE_IMMUTABLE: &str = "public, max-age=31536000, immutable"; /// Without a matching `?v=`, the browser revalidates: the ETag gives a cheap 304. const CACHE_REVALIDATE: &str = "no-cache"; +/// The generated letter avatar is the same for a username until a photo is set, which changes the +/// link: a page shows it from cache at once and checks it in the background. +const CACHE_DEFAULT: &str = "public, max-age=3600, stale-while-revalidate=604800"; const CSP: &str = "default-src 'none'"; #[query_params(error = bad_request)] @@ -31,9 +34,10 @@ struct AvatarQuery { v: Option, } -/// The generated default avatar: the first letter of the username on a palette color. -pub fn default_svg(username: &str, user_id: &str) -> String { - let digest = Sha256::digest(user_id.as_bytes()); +/// The generated default avatar: the first letter of the username on a palette color picked by +/// the username, so a page can draw it inline without asking the server. +pub fn default_svg(username: &str) -> String { + let digest = Sha256::digest(username.as_bytes()); let color = PALETTE[usize::from(digest[0]) % PALETTE.len()]; let letter = username .chars() @@ -45,6 +49,22 @@ pub fn default_svg(username: &str, user_id: &str) -> String { ) } +/// The generated default avatar as a `data:` URL, for an `` of an account known to have no +/// photo: the page shows it at once, with no request. +pub fn default_data_url(username: &str) -> String { + let svg = default_svg(username); + let mut out = String::with_capacity(svg.len() + 40); + out.push_str("data:image/svg+xml,"); + for byte in svg.bytes() { + if byte.is_ascii_alphanumeric() || b" -_.~/=:;,'()".contains(&byte) { + out.push(char::from(byte)); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} + fn xml_escape(text: &str) -> String { let mut out = String::with_capacity(text.len()); for c in text.chars() { @@ -97,10 +117,10 @@ async fn avatar(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec)> { (png, "image/png", hash, cache) } None => { - let svg = default_svg(&user.username, &user.id).into_bytes(); + let svg = default_svg(&user.username).into_bytes(); let digest = Sha256::digest(&svg); let tag: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect(); - (svg, "image/svg+xml", tag, CACHE_REVALIDATE) + (svg, "image/svg+xml", tag, CACHE_DEFAULT) } }; @@ -130,9 +150,12 @@ mod tests { #[test] fn default_svg_escapes_the_letter_and_is_stable() { - let svg = super::default_svg("<", "user-1"); + let svg = super::default_svg("<"); assert!(svg.contains("><"), "{svg}"); - assert_eq!(svg, super::default_svg("<", "user-1")); + assert_eq!(svg, super::default_svg("<")); + let url = super::default_data_url("<"); + assert!(url.starts_with("data:image/svg+xml,%3Csvg"), "{url}"); + assert!(!url.contains('<') && !url.contains('#') && !url.contains('"'), "{url}"); assert!(super::PALETTE.iter().any(|c| svg.contains(c))); } diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index 2134e2b..a337f66 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -479,6 +479,8 @@ async fn job_body( (g::t(lang, K::Log))
+ + diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index e347577..fdfefe8 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -2623,6 +2623,8 @@ async fn run_log( if let Some(log) = run.log.as_ref() {
+ + diff --git a/crates/forge-web/src/pages/explore.rs b/crates/forge-web/src/pages/explore.rs index 011c2b3..e695ed7 100644 --- a/crates/forge-web/src/pages/explore.rs +++ b/crates/forge-web/src/pages/explore.rs @@ -1,8 +1,10 @@ //! Page: public repo listing at `/explore`. Only public repos are listed, even for their owners -//! (private repos never appear here). A search box filters by name or description, three sort -//! orders are offered, and 30 repos are shown per page. `explore` is a reserved username, so this +//! (private repos never appear here). A live search reads names and descriptions, forgiving typos +//! unless Exact or Aa is on; three sort orders are offered, and 12 repos are shown per page, so a +//! page fits the window. `explore` is a reserved username, so this //! route cannot collide with a profile. +use forge_core::{Repo, User}; use forge_core::store::RepoSort; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -19,11 +21,13 @@ use crate::views::parts::{SubPart, head}; use crate::views::repo_list::{ PageLink, RepoRow, SortLink, pager, pager_links, repo_rows, sort_chips, }; -use crate::views::{enc, now_unix, shell}; +use crate::pages::issues_list::list_href; +use crate::views::find::{Finder, finder_field}; +use crate::views::{now_unix, shell}; -const PER_PAGE: u64 = 30; -/// Longest search text kept, in characters. -const MAX_QUERY_CHARS: usize = 100; +const PER_PAGE: u64 = 12; +/// The most public repos a search reads. +const SEARCH_CAP: u64 = 5000; /// Sort keys in the order their links are shown, with the text key of each link. The first one is /// the default. @@ -36,20 +40,61 @@ const SORTS: [(&str, K); 3] = [ #[query_params(error = bad_request)] struct ExploreQuery { q: Option, + exact: Option, + case: Option, sort: Option, page: Option, + tab: Option, +} + +/// The Organizations tab's key in the query. +const ORGS_TAB: &str = "organizations"; + +/// True when the query asks for the Organizations tab. +fn orgs_tab(query: &ExploreQuery) -> bool { + query.tab.as_deref() == Some(ORGS_TAB) +} + +/// `/explore?tab=organizations` with the given search and page. +fn orgs_href(finder: &Finder, page: u64) -> String { + let number = page.to_string(); + let mut params = finder.params(); + params.push(("tab", ORGS_TAB)); + params.push(("page", number.as_str())); + list_href("/explore", ¶ms) +} + +/// The organizations the search matches, by name, and how many there are: one page. +async fn org_listing(state: &AppState, finder: &Finder, page: u64) -> Result<(Vec, u64)> { + let mut all: Vec = state + .store + .list_orgs() + .await? + .into_iter() + .filter(|org| { + finder.matches_any(&[ + org.username.as_str(), + org.display_name.as_deref().unwrap_or(""), + ]) + }) + .collect(); + all.sort_by_key(|org| org.username.to_lowercase()); + let total = all.len() as u64; + let shown = all + .into_iter() + .skip(((page.max(1) - 1) * PER_PAGE) as usize) + .take(PER_PAGE as usize) + .collect(); + Ok((shown, total)) } /// `/explore` with the given search, sort key and page. An empty search is left out. -fn explore_href(q: &str, sort: &str, page: u64) -> String { - let mut href = String::from("/explore?"); - if !q.is_empty() { - href.push_str("q="); - href.push_str(&enc(q)); - href.push('&'); - } - href.push_str(&format!("sort={sort}&page={page}")); - href +fn explore_href(finder: &Finder, sort: &str, page: u64) -> String { + let number = page.to_string(); + let mut params = finder.params(); + params.push(("sort", sort)); + params.push(("page", number.as_str())); + list_href("/explore", ¶ms) } /// Maps the `sort` query value to a key from `SORTS`; anything unknown means the default. @@ -61,16 +106,13 @@ fn sort_key(raw: Option<&str>) -> &'static str { .unwrap_or(SORTS[0].0) } -/// The search text, sort key and page the query asks for, with the defaults filled in. -fn listing_args(query: &ExploreQuery) -> (String, &'static str, u64) { - let q: String = query - .q - .as_deref() - .unwrap_or("") - .trim() - .chars() - .take(MAX_QUERY_CHARS) - .collect(); +/// The search, sort key and page the query asks for, with the defaults filled in. +fn listing_args(query: &ExploreQuery) -> (Finder, &'static str, u64) { + let finder = Finder::new( + query.q.as_deref(), + query.exact.as_deref(), + query.case.as_deref(), + ); let sort = sort_key(query.sort.as_deref()); let page = query .page @@ -78,28 +120,63 @@ fn listing_args(query: &ExploreQuery) -> (String, &'static str, u64) { .and_then(|p| p.parse::().ok()) .unwrap_or(1) .max(1); - (q, sort, page) + (finder, sort, page) +} + +/// The public repos the search matches, in the sort's order, and how many there are: one page. +async fn listing( + state: &AppState, + finder: &Finder, + sort: &'static str, + page: u64, +) -> Result<(Vec<(Repo, u64, String)>, u64)> { + let sort_kind = match sort { + "stars" => RepoSort::MostStars, + "name" => RepoSort::Name, + _ => RepoSort::RecentlyUpdated, + }; + let (all, _) = state + .store + .list_public_repos(None, sort_kind, 1, SEARCH_CAP) + .await?; + let matching: Vec<_> = all + .into_iter() + .filter(|(repo, _, _)| { + let full = format!("{}/{}", repo.owner_name, repo.name); + finder.matches_any(&[full.as_str(), repo.description.as_str()]) + }) + .collect(); + let total = matching.len() as u64; + let shown = matching + .into_iter() + .skip(((page.max(1) - 1) * PER_PAGE) as usize) + .take(PER_PAGE as usize) + .collect(); + Ok((shown, total)) } #[page("/explore")] async fn explore_page(cx: &Cx) -> Result { let query = query_params::(cx)?; - let (q, sort, page) = listing_args(query); - let live = explore_href(&q, sort, page).replacen("/explore?", "/explore/events?", 1); + let (finder, sort, page) = listing_args(query); + let live = explore_href(&finder, sort, page).replacen("/explore?", "/explore/events?", 1); let viewer = current_user(cx).await?; let lang = i18n::lang(cx, viewer.as_ref().map(|(u, _)| u)); let state = app_context::(cx); - - let sort_kind = match sort { - "stars" => RepoSort::MostStars, - "name" => RepoSort::Name, - _ => RepoSort::RecentlyUpdated, - }; - let search = (!q.is_empty()).then_some(q.as_str()); - let (listed, total) = state + let on_orgs = orgs_tab(query); + let (listed, repo_total) = listing(state, &finder, sort, page).await?; + let (org_page, org_total) = org_listing(state, &finder, page).await?; + let total = if on_orgs { org_total } else { repo_total }; + let (_, repos_all) = state .store - .list_public_repos(search, sort_kind, page, PER_PAGE) + .list_public_repos(None, RepoSort::RecentlyUpdated, 1, 1) .await?; + let orgs_all = state.store.list_orgs().await?.len() as u64; + let live = if on_orgs { + orgs_href(&finder, page).replacen("/explore?", "/explore/events?", 1) + } else { + live + }; let now = now_unix(); let tz = viewer.as_ref().map_or("UTC", |(u, _)| u.timezone.as_str()); @@ -107,30 +184,38 @@ async fn explore_page(cx: &Cx) -> Result { .into_iter() .map(|listed| RepoRow::new(lang, tz, now, listed)) .collect(); - let orgs: Vec = state - .store - .list_orgs() - .await? - .into_iter() - .map(|org| org.username) - .collect(); + let mut orgs: Vec<(String, String)> = Vec::new(); + for org in org_page { + let hash = state.store.avatar_hash(&org.id).await?; + let avatar = crate::views::avatar_url(&org.username, hash.as_deref()); + orgs.push((org.username, avatar)); + } let pages = total.div_ceil(PER_PAGE).max(1); let page = page.min(pages); let sort_links: Vec = SORTS .iter() .map(|(key, label)| SortLink { label: g::t(lang, *label), - href: explore_href(&q, key, 1), + href: explore_href(&finder, key, 1), current: *key == sort, }) .collect(); - let nav = pager_links(page, pages, |n| explore_href(&q, sort, n)); + let nav = if on_orgs { + pager_links(page, pages, |n| orgs_href(&finder, n)) + } else { + pager_links(page, pages, |n| explore_href(&finder, sort, n)) + }; + let tabs = vec![ + (g::t(lang, K::Repositories), explore_href(&Finder::default(), sort, 1), repos_all, !on_orgs), + (g::t(lang, K::Organizations), orgs_href(&Finder::default(), 1), orgs_all, on_orgs), + ]; let title = g::t(lang, K::Explore); Ok(view! { cx => shell(title: title, viewer: viewer.as_ref(), - explore_body(q: q, sort: sort, sort_links: sort_links, rows: rows, - total: total, page: page, pages: pages, nav: nav, orgs: orgs, lang: lang, live: live)) + explore_body(finder: finder, sort: sort, sort_links: sort_links, rows: rows, + total: total, page: page, pages: pages, nav: nav, orgs: orgs, lang: lang, live: live, + on_orgs: on_orgs, tabs: tabs)) }) } @@ -140,12 +225,13 @@ async fn explore_page(cx: &Cx) -> Result { #[route(GET "/explore/events")] async fn explore_events(cx: &Cx) -> Result { let query = query_params::(cx)?; - let (q, sort, page) = listing_args(query); + let (finder, sort, page) = listing_args(query); + let on_orgs = orgs_tab(query); let state = app_context::(cx).clone(); stream_changes(cx, &state.live.clone(), &[Topic::Explore], move || { let state = state.clone(); - let q = q.clone(); - async move { explore_fingerprint(&state, &q, sort, page).await } + let finder = finder.clone(); + async move { explore_fingerprint(&state, &finder, sort, page, on_orgs).await } }) .await } @@ -153,20 +239,18 @@ async fn explore_events(cx: &Cx) -> Result { /// The state the explore listing shows: its total, each row with its stars, and the org names. async fn explore_fingerprint( state: &AppState, - q: &str, + finder: &Finder, sort: &'static str, page: u64, + on_orgs: bool, ) -> Result { - let sort_kind = match sort { - "stars" => RepoSort::MostStars, - "name" => RepoSort::Name, - _ => RepoSort::RecentlyUpdated, - }; - let search = (!q.is_empty()).then_some(q); - let (listed, total) = state - .store - .list_public_repos(search, sort_kind, page, PER_PAGE) - .await?; + if on_orgs { + let (orgs, total) = org_listing(state, finder, page).await?; + let mut lines = vec![total.to_string()]; + lines.extend(orgs.into_iter().map(|org| format!("org {}", org.username))); + return Ok(lines.join("\n")); + } + let (listed, total) = listing(state, finder, sort, page).await?; let mut lines = vec![total.to_string()]; for (repo, stars, activity) in listed { lines.push(format!( @@ -174,15 +258,12 @@ async fn explore_fingerprint( repo.owner_name, repo.name, repo.description, repo.visibility, repo.default_branch )); } - for org in state.store.list_orgs().await? { - lines.push(format!("org {}", org.username)); - } Ok(lines.join("\n")) } #[component] async fn explore_body( - q: String, + finder: Finder, sort: &'static str, sort_links: Vec, rows: Vec, @@ -190,47 +271,79 @@ async fn explore_body( page: u64, pages: u64, nav: (Vec, Option, Option), - orgs: Vec, + orgs: Vec<(String, String)>, lang: Lang, live: String, + on_orgs: bool, + tabs: Vec<(&'static str, String, u64, bool)>, ) -> Result { - let empty = rows.is_empty(); - let has_search = !q.is_empty(); - let has_orgs = !orgs.is_empty(); + let empty = if on_orgs { orgs.is_empty() } else { rows.is_empty() }; + let has_search = !finder.is_empty(); let (links, prev, next) = nav; - let clear_href = explore_href("", sort, 1); + let clear_href = if on_orgs { + orgs_href(&Finder::default(), 1) + } else { + explore_href(&Finder::default(), sort, 1) + }; + let placeholder = if on_orgs { + crate::pages::passkeys::s(lang, "Search organizations", "Kuruluşlarda ara") + } else { + g::t(lang, K::SearchPublicRepos) + }; + let count_text = match (lang, total) { + (Lang::Tr, n) => format!("{n} kuruluş"), + (_, 1) => "1 organization".to_owned(), + (_, n) => format!("{n} organizations"), + }; + let empty_text = if on_orgs { + crate::pages::passkeys::s(lang, "No organization matches.", "Eşleşen kuruluş yok.") + } else { + g::t(lang, K::NoPublicReposMatch) + }; Ok(view! { head(title: g::t(lang, K::Explore), sub: vec![SubPart::text(g::t(lang, K::PublicReposIntro))]) +
- (g::repo_count(lang, total)) - - sort_chips(links: sort_links, lang: lang) + if !on_orgs { + sort_chips(links: sort_links, lang: lang) + }
if empty { -

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

+

(empty_text)

if has_search { } + } else if on_orgs { + for (name, avatar) in orgs.into_iter() { + + + (name) + + } } else { repo_rows(rows: rows, lang: lang) } pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang) - if has_orgs { -
-

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

- for org in orgs.iter() { - (org.as_str()) - } -
- }
}) } diff --git a/crates/forge-web/src/pages/import.rs b/crates/forge-web/src/pages/import.rs index 1694dec..5f1d730 100644 --- a/crates/forge-web/src/pages/import.rs +++ b/crates/forge-web/src/pages/import.rs @@ -180,12 +180,15 @@ async fn source_tabs(lang: Lang, base: &str, active: Source) -> Result - (g::t(lang, K::SrcGit)) - (g::t(lang, K::SrcGitHub)) - (g::t(lang, K::SrcGitLab)) - (g::t(lang, K::SrcForgejo)) - +
+ (crate::pages::passkeys::s(lang, "Source", "Kaynak")) + +
}) } @@ -278,6 +281,7 @@ impl Draft { #[component] async fn import_form( lang: Lang, + username: String, csrf: &str, draft: Draft, error: Option, @@ -317,24 +321,16 @@ async fn import_form( let opts = draft.opts; Ok(view! { head(title: g::t(lang, K::ImportTitle), sub: vec![SubPart::text(g::t(lang, K::ImportIntro))]) + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) newrepo_tabs(lang: lang, active: "import") - source_tabs(lang: lang, base: "/new/import", active: source)
- if !is_git { -
-

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

-

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

- -
- }
if let Some(message) = error { alert(message: message.as_str()) } csrf_field(token: csrf) + source_tabs(lang: lang, base: "/new/import", active: source) if has_instance {
@@ -379,6 +375,15 @@ async fn import_form( visibility_pick(lang: lang, private: private) + if !is_git { +
+

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

+

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

+ +
+ }
}) } @@ -390,6 +395,7 @@ const RECENT_IMPORTS: usize = 5; #[component] async fn import_home( lang: Lang, + username: String, csrf: String, draft: Draft, owners: Vec, @@ -397,7 +403,7 @@ async fn import_home( more: bool, ) -> Result { Ok(view! { - import_form(lang: lang, csrf: csrf.as_str(), draft: draft, error: None, owners: owners) + import_form(lang: lang, username: username, csrf: csrf.as_str(), draft: draft, error: None, owners: owners) recent_imports(lang: lang, jobs: jobs, more: more) }) } @@ -406,13 +412,14 @@ async fn import_home( #[component] async fn import_error_body( lang: Lang, + username: String, csrf: String, draft: Draft, error: String, owners: Vec, ) -> Result { Ok(view! { - import_form(lang: lang, csrf: csrf.as_str(), draft: draft, error: Some(error), owners: owners) + import_form(lang: lang, username: username, csrf: csrf.as_str(), draft: draft, error: Some(error), owners: owners) }) } @@ -431,7 +438,7 @@ async fn import_page(cx: &Cx) -> Result { jobs.truncate(RECENT_IMPORTS); Ok(view! { cx => shell(title: g::t(lang, K::ImportTitle), viewer: Some(&viewer), - import_home(lang: lang, csrf: csrf, draft: Draft::fresh(source), owners: owners, jobs: jobs, more: more)) + import_home(lang: lang, username: viewer.0.username.clone(), csrf: csrf, draft: Draft::fresh(source), owners: owners, jobs: jobs, more: more)) }) } @@ -448,7 +455,7 @@ async fn import_submit(cx: &Cx, Form(form): Form) -> Result shell(title: g::t(lang, K::ImportTitle), viewer: Some(&viewer), - import_error_body(lang: lang, csrf: csrf, draft: draft, error: message, owners: owners)) + import_error_body(lang: lang, username: viewer.0.username.clone(), csrf: csrf, draft: draft, error: message, owners: owners)) }) } } @@ -593,6 +600,7 @@ async fn begin( #[component] async fn bulk_form( lang: Lang, + username: String, csrf: &str, source: Source, instance: &str, @@ -611,8 +619,8 @@ async fn bulk_form( let owner_required = source != Source::Forgejo; Ok(view! { head(title: g::t(lang, K::BulkTitle), sub: vec![SubPart::text(g::t(lang, K::BulkIntro))]) + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) newrepo_tabs(lang: lang, active: "import") - source_tabs(lang: lang, base: "/new/import/bulk", active: source)
if let Some(message) = error { @@ -620,6 +628,7 @@ async fn bulk_form( } csrf_field(token: csrf) + source_tabs(lang: lang, base: "/new/import/bulk", active: source) if has_instance {
@@ -655,6 +664,7 @@ struct Listed { #[component] async fn bulk_select( lang: Lang, + username: String, csrf: &str, form: BulkFormEcho, repos: Vec, @@ -671,6 +681,7 @@ async fn bulk_select( }; Ok(view! { head(title: g::t(lang, K::BulkSelectHeading)) + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) newrepo_tabs(lang: lang, active: "import")
@@ -753,7 +764,7 @@ async fn bulk_page(cx: &Cx) -> Result { let csrf = viewer.1.csrf_token.clone(); Ok(view! { cx => shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer), - bulk_form(lang: lang, csrf: csrf.as_str(), source: source, instance: default_instance(source), owners: owners, error: query.error.clone().filter(|e| e.len() < 300))) + bulk_form(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), source: source, instance: default_instance(source), owners: owners, error: query.error.clone().filter(|e| e.len() < 300))) }) } @@ -852,7 +863,7 @@ async fn bulk_submit(cx: &Cx, Form(form): Form) -> Result { }; Ok(view! { cx => shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer), - bulk_stage(lang: lang, csrf: csrf.as_str(), source: source, instance: instance.as_str(), owners: owners, error: error, picker: picker)) + bulk_stage(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), source: source, instance: instance.as_str(), owners: owners, error: error, picker: picker)) }) } @@ -860,6 +871,7 @@ async fn bulk_submit(cx: &Cx, Form(form): Form) -> Result { #[component] async fn bulk_stage( lang: Lang, + username: String, csrf: &str, source: Source, instance: &str, @@ -869,9 +881,9 @@ async fn bulk_stage( ) -> Result { Ok(view! { if let Some((echo, repos)) = picker { - bulk_select(lang: lang, csrf: csrf, form: echo, repos: repos, owners: owners) + bulk_select(lang: lang, username: username, csrf: csrf, form: echo, repos: repos, owners: owners) } else { - bulk_form(lang: lang, csrf: csrf, source: source, instance: instance, owners: owners, error: error) + bulk_form(lang: lang, username: username, csrf: csrf, source: source, instance: instance, owners: owners, error: error) } }) } @@ -1075,6 +1087,7 @@ async fn recent_imports( #[component] async fn jobs_list( lang: Lang, + username: String, jobs: Vec<(ImportJob, Option)>, skipped: Option, ) -> Result { @@ -1082,6 +1095,8 @@ async fn jobs_list( let retry = jobs.iter().any(|(job, _)| job.state == ImportState::Failed); Ok(view! { head(title: g::t(lang, K::JobsTitle), live: Some("/import/events")) + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) + newrepo_tabs(lang: lang, active: "import")
if retry {
@@ -1155,13 +1170,14 @@ async fn jobs_page(cx: &Cx) -> Result { .filter(|s| !s.is_empty() && s.len() < 2000) .map(|s| g::bulk_skipped(lang, &s)); Ok(view! { cx => - shell(title: g::t(lang, K::JobsTitle), viewer: Some(&viewer), jobs_list(lang: lang, jobs: rows, skipped: skipped)) + shell(title: g::t(lang, K::JobsTitle), viewer: Some(&viewer), jobs_list(lang: lang, username: viewer.0.username.clone(), jobs: rows, skipped: skipped)) }) } #[component] async fn job_view( lang: Lang, + username: String, csrf: &str, job: ImportJob, repo: Option, @@ -1194,6 +1210,8 @@ async fn job_view( }]; Ok(view! { head(title: job.source_ref.as_str(), sub: sub, live: live.as_deref()) + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) + newrepo_tabs(lang: lang, active: "import")
if !stage.is_empty() { @@ -1271,7 +1289,7 @@ async fn job_page(cx: &Cx) -> Result { let title = job.source_ref.clone(); Ok(view! { cx => shell(title: title.as_str(), viewer: Some(&viewer), - job_view(lang: lang, csrf: csrf.as_str(), job: job, repo: repo, log: log)) + job_view(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), job: job, repo: repo, log: log)) }) } @@ -1409,11 +1427,13 @@ fn source_label(raw: &str) -> &'static str { } #[component] -async fn retry_list(lang: Lang, csrf: &str, rows: Vec<(ImportJob, Repo)>) -> Result { +async fn retry_list(lang: Lang, username: String, csrf: &str, rows: Vec<(ImportJob, Repo)>) -> Result { let count = rows.len(); let empty = rows.is_empty(); Ok(view! { head(title: g::t(lang, K::RetryFailedTitle)) + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) + newrepo_tabs(lang: lang, active: "import")
csrf_field(token: csrf) @@ -1461,7 +1481,7 @@ async fn retry_page(cx: &Cx) -> Result { let csrf = viewer.1.csrf_token.clone(); Ok(view! { cx => shell(title: g::t(lang, K::RetryFailedTitle), viewer: Some(&viewer), - retry_list(lang: lang, csrf: csrf.as_str(), rows: rows)) + retry_list(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), rows: rows)) }) } diff --git a/crates/forge-web/src/pages/issue_parts.rs b/crates/forge-web/src/pages/issue_parts.rs index 4a902f7..2c95df4 100644 --- a/crates/forge-web/src/pages/issue_parts.rs +++ b/crates/forge-web/src/pages/issue_parts.rs @@ -28,7 +28,7 @@ use crate::state::AppState; use crate::views::review_thread::{ThreadCtx, review_thread_in}; use crate::views::user_facing_message; use crate::views::{ - alert, avatar_url, display_name, iso_time, now_unix, relative_time, repo_href, short_oid, + alert, avatar_url, avatar_url_unknown, display_name, iso_time, now_unix, relative_time, repo_href, short_oid, user_href, user_link, }; use crate::views::parts::{confirm_act, reveal}; @@ -990,7 +990,7 @@ async fn review_entries( anchor: format!("review-{}", review.id), author: display_name(lang, &review.author_name), login: review.author_name.clone(), - avatar: avatar_url(&review.author_name, None), + avatar: avatar_url_unknown(&review.author_name), when: When::new(lang, &stamp, tz, now), verb, dismissed, diff --git a/crates/forge-web/src/pages/issues_list.rs b/crates/forge-web/src/pages/issues_list.rs index 05fa64a..77fedf4 100644 --- a/crates/forge-web/src/pages/issues_list.rs +++ b/crates/forge-web/src/pages/issues_list.rs @@ -28,7 +28,7 @@ use crate::state::AppState; use crate::templates::{self, Template}; use crate::views::parts::{RailItem, SubPart, rail}; use crate::views::{ - alert, avatar_url, csrf_field, enc, iso_time, now_unix, relative_time, repo_href, + alert, avatar_url_unknown, csrf_field, enc, iso_time, now_unix, relative_time, repo_href, shell, user_facing_message, user_link, }; use crate::webhooks::emit::{Sender, emit_issue}; @@ -349,7 +349,7 @@ fn row_view(row: RowCtx<'_>, item: &IssueListItem) -> RowView { .iter() .map(|name| AssigneeView { name: name.clone(), - avatar: avatar_url(name, None), + avatar: avatar_url_unknown(name), }) .collect(), has_comments: comments > 0, diff --git a/crates/forge-web/src/pages/needs_you.rs b/crates/forge-web/src/pages/needs_you.rs index 9c4173b..a11e1e9 100644 --- a/crates/forge-web/src/pages/needs_you.rs +++ b/crates/forge-web/src/pages/needs_you.rs @@ -410,6 +410,7 @@ async fn needs_you(cx: &Cx) -> Result { let empty = full.is_none() && sections.is_empty(); let back = full.as_ref().map(|_| ni::t(lang, K::BackToNeedsYou)); let heading = ni::t(lang, K::NeedsYou); + let unread = state.store.unread_count(&user.id).await?; let sub = vec![SubPart::text(s(lang, "Waiting on you", "Senden beklenenler"))]; Ok(view! { shell(title: heading, viewer: Some(&viewer), @@ -418,16 +419,19 @@ async fn needs_you(cx: &Cx) -> Result { (back) } ) -
- if empty { -

(ni::t(lang, K::AllClear))

- } - for section in sections.into_iter() { - need_section(lang: lang, section: section) - } - if let Some(section) = full { - need_section(lang: lang, section: section) - } +
+ crate::pages::notifications::inbox_rail(lang: lang, current: "needs", unread_count: unread) +
+ if empty { +

(ni::t(lang, K::AllClear))

+ } + for section in sections.into_iter() { + need_section(lang: lang, section: section) + } + if let Some(section) = full { + need_section(lang: lang, section: section) + } +
) }) diff --git a/crates/forge-web/src/pages/new_repo.rs b/crates/forge-web/src/pages/new_repo.rs index d674844..6435e81 100644 --- a/crates/forge-web/src/pages/new_repo.rs +++ b/crates/forge-web/src/pages/new_repo.rs @@ -209,6 +209,7 @@ impl Draft { #[component] async fn new_repo_form( lang: Lang, + username: String, csrf: &str, draft: Draft, error: Option, @@ -235,6 +236,7 @@ async fn new_repo_form( let draft_mirror_interval = draft.mirror_interval; Ok(view! { head(title: i18n::t(lang, Key::NewRepository)) + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) crate::pages::import::newrepo_tabs(lang: lang, active: "create")
@@ -339,7 +341,7 @@ async fn new_repo_page(cx: &Cx) -> Result { } let csrf = viewer.1.csrf_token.clone(); Ok(view! { cx => - shell(title: i18n::t(lang, Key::NewRepository), viewer: Some(&viewer), new_repo_form(lang: lang, csrf: csrf.as_str(), draft: draft, error: None, owners: owners)) + shell(title: i18n::t(lang, Key::NewRepository), viewer: Some(&viewer), new_repo_form(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), draft: draft, error: None, owners: owners)) }) } @@ -355,7 +357,7 @@ async fn new_repo_submit(cx: &Cx, Form(form): Form) -> Result - shell(title: i18n::t(lang, Key::NewRepository), viewer: Some(&viewer), new_repo_form(lang: lang, csrf: csrf.as_str(), draft: draft, error: Some(message), owners: owners)) + shell(title: i18n::t(lang, Key::NewRepository), viewer: Some(&viewer), new_repo_form(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), draft: draft, error: Some(message), owners: owners)) }) } } diff --git a/crates/forge-web/src/pages/notifications.rs b/crates/forge-web/src/pages/notifications.rs index 149760e..96d24d8 100644 --- a/crates/forge-web/src/pages/notifications.rs +++ b/crates/forge-web/src/pages/notifications.rs @@ -1099,6 +1099,43 @@ fn back(cx: &Cx) -> String { return_path(cx).unwrap_or_else(|| "/notifications".to_owned()) } +/// The inbox rail's places, the same on Notifications, Needs you and Review requests, so each +/// reaches the others: Unread with its count, All, Needs you, Review requests. `current` is the +/// key of the page showing it. +pub(crate) fn inbox_items(lang: Lang, current: &str, unread_count: u64) -> Vec { + let item = |key: &str, name: &str, val: String, href: &str| RailItem { + name: name.to_owned(), + val, + href: href.to_owned(), + current: key == current, + }; + vec![ + item("unread", g::t(lang, K::Unread), unread_count.to_string(), "/notifications"), + item("all", g::t(lang, K::AllTab), String::new(), "/notifications?all=1"), + item( + "needs", + crate::i18n::needs::t(lang, crate::i18n::needs::K::NeedsYou), + String::new(), + "/needs-you", + ), + item( + "reviews", + crate::i18n::authoring::t(lang, crate::i18n::authoring::K::ReviewRequestsTab), + String::new(), + "/review-requests", + ), + ] +} + +/// The inbox rail as Needs you and Review requests show it, beside their sheet. +#[component] +pub(crate) async fn inbox_rail(lang: Lang, current: &str, unread_count: u64) -> Result { + let items = inbox_items(lang, current, unread_count); + Ok(view! { + rail(label: g::t(lang, K::NotificationFilter), items: items) + }) +} + /// The inbox page: the head with Mark all read, the filter rail (Unread, All, Reviews), then one /// sheet holding the transfers, the repo groups and the older-rows link. #[component] @@ -1118,29 +1155,10 @@ async fn inbox_list( } else { g::t(lang, K::NoUnreadNotifications) }; - let filters = vec![ - RailItem { - name: g::t(lang, K::Unread).to_owned(), - val: unread_count.to_string(), - href: "/notifications".to_owned(), - current: !all, - }, - RailItem { - name: g::t(lang, K::AllTab).to_owned(), - val: String::new(), - href: "/notifications?all=1".to_owned(), - current: all, - }, - RailItem { - name: crate::i18n::authoring::t(lang, crate::i18n::authoring::K::ReviewRequestsTab) - .to_owned(), - val: String::new(), - href: "/review-requests".to_owned(), - current: false, - }, - ]; + let filters = inbox_items(lang, if all { "all" } else { "unread" }, unread_count); Ok(view! { head(title: i18n::t(lang, Key::Notifications), + sub: vec![crate::views::parts::SubPart::text(crate::pages::passkeys::s(lang, "What happened where you take part", "Katıldığın yerlerde olanlar"))], if !empty { diff --git a/crates/forge-web/src/pages/org_new.rs b/crates/forge-web/src/pages/org_new.rs index 6ae7d3b..12481f7 100644 --- a/crates/forge-web/src/pages/org_new.rs +++ b/crates/forge-web/src/pages/org_new.rs @@ -48,9 +48,11 @@ async fn new_org_form( description: String, error: Option, lang: Lang, + username: String, ) -> Result { Ok(view! { head(title: g::t(lang, K::NewOrganization), sub: vec![SubPart::text(g::t(lang, K::NewOrgIntro))]) + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "organizations".to_owned())
if let Some(message) = error { alert(message: message.as_str()) @@ -82,7 +84,7 @@ async fn new_org_page(cx: &Cx) -> Result { let csrf = viewer.1.csrf_token.clone(); Ok(view! { cx => shell(title: title, viewer: Some(&viewer), - new_org_form(csrf: csrf, name: String::new(), description: String::new(), error: None, lang: lang)) + new_org_form(csrf: csrf, name: String::new(), description: String::new(), error: None, lang: lang, username: viewer.0.username.clone())) }) } @@ -103,7 +105,7 @@ async fn new_org_submit(cx: &Cx, Form(form): Form) -> Result shell(title: title, viewer: Some(&viewer), - new_org_form(csrf: csrf, name: name, description: description, error: Some(message), lang: lang)) + new_org_form(csrf: csrf, name: name, description: description, error: Some(message), lang: lang, username: viewer.0.username.clone())) }) } } diff --git a/crates/forge-web/src/pages/profile.rs b/crates/forge-web/src/pages/profile.rs index 0fb9df6..ea4bc88 100644 --- a/crates/forge-web/src/pages/profile.rs +++ b/crates/forge-web/src/pages/profile.rs @@ -35,6 +35,7 @@ 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; use crate::state::AppState; +use crate::views::find::{Finder, finder_field}; use crate::views::heatmap::{Calendar, DayDetail, contribution_calendar}; use crate::views::parts::{SubPart, head}; use crate::views::repo_list::{ @@ -59,13 +60,17 @@ struct PinsMenu { const POPULAR_COUNT: usize = 6; /// Members an organization's overview lists; a longer list links to the members page. const ORG_MEMBERS_SHOWN: usize = 12; -/// Longest name filter kept, in characters. -const MAX_QUERY_CHARS: usize = 100; +/// Repos the name filter reads at once. The filter runs in Rust, so it covers every repo in scope. +const SEARCH_CAP: u64 = 5000; #[query_params(error = bad_request)] struct ProfileQuery { tab: Option, q: Option, + /// Set when the filter asks for the text as typed, as one piece. + exact: Option, + /// Set when the filter keeps upper and lower case apart. + case: Option, sort: Option, page: Option, /// A calendar day whose contributions to list under the calendar on the overview. @@ -124,14 +129,11 @@ async fn profile_page(cx: &Cx) -> Result { } else { tab }; - let q: String = query - .q - .as_deref() - .unwrap_or("") - .trim() - .chars() - .take(MAX_QUERY_CHARS) - .collect(); + let finder = Finder::new( + query.q.as_deref(), + query.exact.as_deref(), + query.case.as_deref(), + ); let page = page_number(query.page.as_deref()); let sort = sort_key(query.sort.as_deref()); @@ -263,14 +265,35 @@ async fn profile_page(cx: &Cx) -> Result { "name" => RepoSort::Name, _ => RepoSort::RecentlyUpdated, }; - let search = (!q.is_empty()).then_some(q.as_str()); - let (listed, total) = state - .store - .list_visible_repos(scope, actor, search, sort_kind, page, PER_PAGE) - .await?; + let (listed, total) = if finder.is_empty() { + state + .store + .list_visible_repos(scope, actor, None, sort_kind, page, PER_PAGE) + .await? + } else { + // The search reads each repo's name and description, so it runs here over every + // repo in scope, then takes the one page asked for. + let (all, _) = state + .store + .list_visible_repos(scope, actor, None, sort_kind, 1, SEARCH_CAP) + .await?; + let matching: Vec<_> = all + .into_iter() + .filter(|(repo, _, _)| { + finder.matches_any(&[repo.name.as_str(), repo.description.as_str()]) + }) + .collect(); + let total = matching.len() as u64; + let shown = matching + .into_iter() + .skip(((page - 1) * PER_PAGE) as usize) + .take(PER_PAGE as usize) + .collect(); + (shown, total) + }; let tz = actor.map_or("UTC", |u| u.timezone.as_str()); let now = now_unix(); - let empty = match (tab, q.is_empty()) { + let empty = match (tab, finder.is_empty()) { (_, false) => g::t(lang, K::NoReposMatch), ("stars", true) => g::t(lang, K::NoVisibleStarred), _ => g::t(lang, K::NoVisibleRepos), @@ -290,13 +313,13 @@ async fn profile_page(cx: &Cx) -> Result { page, pages, pager: pager_links(page, pages, |n| { - profile_href(&user.username, tab, &q, sort, n) + profile_href(&user.username, tab, &finder, sort, n) }), sort_links: SORTS .iter() .map(|(key, label)| SortLink { label: g::t(lang, *label), - href: profile_href(&user.username, tab, &q, key, 1), + href: profile_href(&user.username, tab, &finder, key, 1), current: *key == sort, }) .collect(), @@ -339,7 +362,7 @@ async fn profile_page(cx: &Cx) -> Result { shell(title: title.as_str(), viewer: viewer.as_ref(), notice_banner_for(lang: lang, title: notice) 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, + org: org, lang: lang, tab: tab.to_owned(), finder: finder, sort: sort, repo_total: repo_total, star_total: star_total, cards: cards, from_pins: from_pins, pins_menu_data: pins_menu_data, pins_error: pins_error, edit_profile: own, listing: listing, packages_on: packages_on, package_rows: package_rows, @@ -505,11 +528,15 @@ fn page_number(raw: Option<&str>) -> u64 { /// The profile URL for a tab, with the name filter, a sort other than the default and the page /// when they are set. -fn profile_href(name: &str, tab: &str, q: &str, sort: &str, page: u64) -> String { +fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) -> String { let mut href = format!("/{}?tab={tab}", enc(name)); - if !q.is_empty() { - href.push_str("&q="); - href.push_str(&enc(q)); + if !finder.is_empty() { + for (key, value) in finder.params() { + href.push('&'); + href.push_str(key); + href.push('='); + href.push_str(&enc(value)); + } } if sort != SORTS[0].0 { href.push_str("&sort="); @@ -568,7 +595,7 @@ async fn profile_card( org: Option, lang: Lang, tab: String, - q: String, + finder: Finder, sort: &'static str, repo_total: u64, star_total: u64, @@ -745,12 +772,10 @@ async fn profile_card(
(count_text.as_str()) - + - - + finder_field(lang: lang, finder: finder, placeholder: filter_label, id: Some("profile-q")) sort_chips(links: sort_links, lang: lang)
@@ -836,6 +861,42 @@ async fn profile_card( }) } +/// The viewer's own profile tabs on a page that makes something of theirs (a repository, a +/// snippet, an organization): the same tabs and counts as their profile, with `current` marked. +#[component] +pub async fn own_profile_tabs(lang: Lang, username: String, current: String) -> Result { + let items = crate::views::profile_items(lang, &username, false, true, false); + let mut counts = Vec::new(); + if let Some(state) = topcoat::context::try_app_context::(__cx) + && let Some(user) = state.store.user_by_username(&username).await? + { + let actor = Some(&user); + let repos = state + .store + .count_visible_repos(RepoScope::OwnedBy(&user.id), actor) + .await?; + let stars = state + .store + .count_visible_repos(RepoScope::StarredBy(&user.id), actor) + .await?; + let snippets = state + .store + .list_owner_snippets(&user.id, Some(user.id.as_str())) + .await? + .len(); + let packages = packages::package_rows(state, actor, &user).await?.len(); + counts = vec![ + ("repositories", repos.to_string()), + ("snippets", snippets.to_string()), + ("stars", stars.to_string()), + ("packages", packages.to_string()), + ]; + } + Ok(view! { + profile_tabs(username: username, items: items, current: current, counts: counts) + }) +} + /// The profile tab bar: one link per item, the current tab marked, and a count after the label of /// each tab that has one in `counts`, by the item's key. A person's, an organization's and an /// organization's member pages all render it. diff --git a/crates/forge-web/src/pages/pulls_list.rs b/crates/forge-web/src/pages/pulls_list.rs index 2a0bfd9..25e9d8a 100644 --- a/crates/forge-web/src/pages/pulls_list.rs +++ b/crates/forge-web/src/pages/pulls_list.rs @@ -25,7 +25,7 @@ use crate::state::AppState; use crate::pages::passkeys::s; use crate::views::parts::{RailItem, SubPart, rail}; use crate::views::{ - avatar_url, iso_time, now_unix, relative_time, repo_href, shell, user_link, + avatar_url_unknown, iso_time, now_unix, relative_time, repo_href, shell, user_link, }; path_param!(owner); @@ -136,7 +136,7 @@ fn row_view( .iter() .map(|name| AssigneeView { name: name.clone(), - avatar: avatar_url(name, None), + avatar: avatar_url_unknown(name), }) .collect(), has_comments: comments > 0, diff --git a/crates/forge-web/src/pages/register.rs b/crates/forge-web/src/pages/register.rs index a325577..f7d92ff 100644 --- a/crates/forge-web/src/pages/register.rs +++ b/crates/forge-web/src/pages/register.rs @@ -23,6 +23,7 @@ use crate::auth::{ use crate::client_ip::client_ip; use crate::i18n::{self, Key, Lang, password_too_long, password_too_short, t}; use crate::mail::account; +use crate::pages::settings_security::mail_can_send; use crate::state::AppState; use crate::throttle; use crate::views::parts::{SubPart, head}; @@ -425,6 +426,9 @@ async fn verify_submit(cx: &Cx, Form(form): Form) -> Result) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let state = app_context::(cx); + if !mail_can_send(state).await { + return Ok(see_other("/settings/security?saved=verify_wait")); + } if let Some(address) = viewer.0.email.clone() && !state.store.email_is_verified(&viewer.0.id).await? && !account::send_verify(state, &viewer.0, &address).await? diff --git a/crates/forge-web/src/pages/review_requests.rs b/crates/forge-web/src/pages/review_requests.rs index 906dffd..b5c0b38 100644 --- a/crates/forge-web/src/pages/review_requests.rs +++ b/crates/forge-web/src/pages/review_requests.rs @@ -286,6 +286,7 @@ async fn review_requests(cx: &Cx) -> Result { } let heading = ga::t(lang, AK::ReviewRequests); let empty = rows.is_empty(); + let unread = state.store.unread_count(&user.id).await?; let sub = vec![SubPart::text(s( lang, "Pull requests waiting for your review", @@ -294,19 +295,22 @@ async fn review_requests(cx: &Cx) -> Result { Ok(view! { shell(title: heading, viewer: Some(&viewer), head(title: heading, sub: sub, live: Some("/review-requests/events")) -
-
- if empty { -

(ga::t(lang, AK::NoReviewRequests))

- } - for row in rows.iter() { - - (row.2.as_str()) - (row.0.as_str()) - (row.3.as_str()) - rel_time(lang: lang, stamp: row.4.as_str()) - - } +
+ crate::pages::notifications::inbox_rail(lang: lang, current: "reviews", unread_count: unread) +
+
+ if empty { +

(ga::t(lang, AK::NoReviewRequests))

+ } + for row in rows.iter() { + + (row.2.as_str()) + (row.0.as_str()) + (row.3.as_str()) + rel_time(lang: lang, stamp: row.4.as_str()) + + } +
) diff --git a/crates/forge-web/src/pages/settings_appearance.rs b/crates/forge-web/src/pages/settings_appearance.rs index b874851..0e605dc 100644 --- a/crates/forge-web/src/pages/settings_appearance.rs +++ b/crates/forge-web/src/pages/settings_appearance.rs @@ -723,15 +723,15 @@ mod tests { "accent: empty" ); assert!( - base_choice(Lang::En, Some("ink"), "fern").is_ok(), + base_choice(Lang::En, Some("ink"), "blush").is_ok(), "base: offered" ); assert!( - base_choice(Lang::En, Some("neon"), "fern").is_err(), + base_choice(Lang::En, Some("neon"), "blush").is_err(), "base: unknown" ); assert!( - base_choice(Lang::En, Some(""), "fern").is_err(), + base_choice(Lang::En, Some(""), "blush").is_err(), "base: empty" ); @@ -746,14 +746,14 @@ mod tests { "accent upper case {id}" ); } - for id in ["fern", "graphite", "dusk", "ink", "anvil", "hue-120"] { + for id in ["blush", "heather", "dusk", "ink", "anvil", "hue-120"] { assert_eq!( - base_choice(Lang::Tr, Some(id), "fern").unwrap(), + base_choice(Lang::Tr, Some(id), "blush").unwrap(), id, "base {id}" ); assert!( - base_choice(Lang::Tr, Some(&id.to_uppercase()), "fern").is_err(), + base_choice(Lang::Tr, Some(&id.to_uppercase()), "blush").is_err(), "base upper case {id}" ); } @@ -777,7 +777,8 @@ mod tests { for id in [ "dune", "lilac", - "blush", + "fern", + "graphite", "pine", "slate-blue", "spark", @@ -785,7 +786,7 @@ mod tests { "hue-07", ] { assert!( - base_choice(Lang::En, Some(id), "fern").is_err(), + base_choice(Lang::En, Some(id), "blush").is_err(), "base refused {id}" ); } @@ -810,7 +811,7 @@ mod tests { accent_err.to_string().contains("accent colour"), "{accent_err}" ); - let base_err = base_choice(Lang::En, Some("neon"), "fern").unwrap_err(); + let base_err = base_choice(Lang::En, Some("neon"), "blush").unwrap_err(); assert!(base_err.to_string().contains("background"), "{base_err}"); } diff --git a/crates/forge-web/src/pages/settings_export.rs b/crates/forge-web/src/pages/settings_export.rs index 10e1942..cbf1151 100644 --- a/crates/forge-web/src/pages/settings_export.rs +++ b/crates/forge-web/src/pages/settings_export.rs @@ -26,7 +26,7 @@ use crate::i18n::migrate::{self as g, K}; use crate::i18n::{self, Lang}; use crate::pages::ci_runs::{changed_event, events_response}; use crate::state::AppState; -use crate::views::parts::{SubPart, head}; +use crate::views::parts::{SubPart, confirm_act, head}; use crate::views::{alert, csrf_field, human_size, rel_time, shell}; path_param!(export_id); @@ -61,6 +61,10 @@ async fn export_view(lang: Lang, csrf: &str, exports: Vec) -> Result ) }); let empty = exports.is_empty(); + let deletes: Vec = exports + .iter() + .map(|e| format!("/settings/export/{}/delete", e.id)) + .collect(); let ttl_note = g::export_ttl_note(lang, exporter::EXPORT_TTL_DAYS); Ok(view! { head(title: g::t(lang, K::ExportTitle), sub: vec![SubPart::text(g::t(lang, K::ExportIntro))], @@ -80,13 +84,14 @@ async fn export_view(lang: Lang, csrf: &str, exports: Vec) -> Result if empty {

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

} - for export in exports.iter() { + for (export, delete) in exports.iter().zip(deletes.iter()) {
(g::t(lang, K::ExportRequested)) " " rel_time(lang: lang, stamp: export.created_at.as_str()) if export.state == ExportState::Ready { - (g::t(lang, K::ExportReady)) + (g::t(lang, K::ExportReady)) " · " (g::t(lang, K::ExportSize)) ": " (human_size(lang, u64::try_from(export.size).unwrap_or(0))) + " · " (g::expires_label(lang)) " " rel_time(lang: lang, stamp: export.expires_at.as_str()) } if export.state == ExportState::Building { (g::t(lang, K::ExportBuilding)) @@ -95,16 +100,13 @@ async fn export_view(lang: Lang, csrf: &str, exports: Vec) -> Result (g::t(lang, K::ExportFailed)) } -
- if export.state == ExportState::Ready { -

- (g::t(lang, K::ExportSize)) ": " (human_size(lang, u64::try_from(export.size).unwrap_or(0))) - " · " (g::expires_label(lang)) " " rel_time(lang: lang, stamp: export.expires_at.as_str()) -

-
+ if export.state == ExportState::Ready { (g::t(lang, K::ExportDownload)) -
- } + } + if export.state != ExportState::Building { + confirm_act(lang: lang, label: crate::pages::passkeys::s(lang, "Delete", "Sil"), action: delete.as_str(), csrf: csrf, note: Some(crate::pages::passkeys::s(lang, "The archive is deleted from the server.", "Arşiv sunucudan silinir.").to_owned())) + } +
if export.state == ExportState::Building { } @@ -140,6 +142,20 @@ async fn export_request(cx: &Cx, Form(form): Form) -> Result Err(see_other("/settings/export").into()) } +/// Deletes one archive by hand. Only its owner, and not while it is still building. +#[route(POST "/settings/export/{export_id}/delete")] +async fn export_delete(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param::(cx).to_owned(); + let state = app_context::(cx); + let export = match state.store.data_export(&id).await? { + Some(e) if e.user_id == viewer.0.id && e.state != ExportState::Building => e, + _ => return Err(not_found().into()), + }; + exporter::delete_one(state, &export).await?; + Err(see_other("/settings/export").into()) +} + /// The `changed` stream of the export page. It sends when the exports differ from what the page /// shows, then on each change, and ends once nothing is building. #[route(GET "/settings/export/events")] diff --git a/crates/forge-web/src/pages/settings_profile.rs b/crates/forge-web/src/pages/settings_profile.rs index 94041a8..82e3eb7 100644 --- a/crates/forge-web/src/pages/settings_profile.rs +++ b/crates/forge-web/src/pages/settings_profile.rs @@ -994,7 +994,7 @@ pub(crate) mod tests { ); let (_, _, body) = send(&fx.router, "GET", "/explore", true, None).await; assert!( - body.contains(r#"src="/avatars/tahinli?v=default""#), + body.contains(r#"src="data:image/svg+xml,"#), "remove: nav default {body}" ); // With no photo there is nothing to remove, so the menu leaves that item out. diff --git a/crates/forge-web/src/pages/settings_security.rs b/crates/forge-web/src/pages/settings_security.rs index 408fcfe..a035f84 100644 --- a/crates/forge-web/src/pages/settings_security.rs +++ b/crates/forge-web/src/pages/settings_security.rs @@ -29,7 +29,7 @@ use crate::pages::passkeys::{PasskeyPanel, build_panel, passkeys_panel, s}; use crate::pages::settings_sessions::session_label; use crate::state::AppState; use crate::throttle::{self, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT}; -use crate::views::parts::{RailItem, SubPart, confirm_act, head, post_act, rail, reveal}; +use crate::views::parts::{RailItem, SubPart, confirm_act, head, post_act, rail}; use crate::views::{added_status, alert, rel_time, shell, user_facing_message}; /// Shortest and longest new passwords, in characters. @@ -82,6 +82,8 @@ struct CodeForm { #[serde(default)] csrf: String, #[serde(default)] + current_password: String, + #[serde(default)] code: String, } @@ -171,6 +173,8 @@ struct SecurityPage { email_status: String, /// When the latest verification mail went out, shown after the state as a live time. email_sent: Option, + /// Whether this server can send mail at all. The resend link shows only when it can. + mail_ready: bool, notice: Option<&'static str>, password_error: Option, email_error: Option, @@ -296,6 +300,7 @@ async fn security_body(page: SecurityPage, csrf: &str) -> Result { stored_email, email_status, email_sent, + mail_ready, notice, password_error, email_error, @@ -323,7 +328,7 @@ async fn security_body(page: SecurityPage, csrf: &str) -> Result { let password_open = password_error.is_some(); let email_open = email_error.is_some(); let email_set = !email.is_empty(); - let show_resend = email_set && !email_verified; + let show_resend = email_set && !email_verified && mail_ready; let regenerate_error = two_factor_error .clone() .filter(|_| two_factor_panel == TwoFactorPanel::Regenerate); @@ -444,46 +449,54 @@ async fn security_body(page: SecurityPage, csrf: &str) -> Result { if let Some(device) = two_factor {

(t(lang, Key::PillOn)) " · " (device.name.as_str())

added_status(lang: lang, added: device.added.as_deref(), used: device.used.as_deref())

-

(device.codes_line.as_str())

+
+ (t(lang, Key::RecoveryCodes)) + (device.codes_line.as_str()) +
if device.codes_low {

(t(lang, Key::CodesRunningLow))

} -
- reveal(label: t(lang, Key::RegenerateCodes), open: regenerate_open, +
+ (s(lang, "Regenerate…", "Yeniden oluştur…")) +
if let Some(message) = regenerate_error { alert(message: message.as_str()) }

(t(lang, Key::RegenerateCodesHint))

+
+ + +
- ) -
- (t(lang, Key::TurnOffTwoFactorButton)) -
- if let Some(message) = disable_error { - alert(message: message.as_str()) - } -
- -
- - -
-
- - -
- -
-
-
-
+
+ +
+ (t(lang, Key::TurnOffTwoFactorButton)) +
+ if let Some(message) = disable_error { + alert(message: message.as_str()) + } +
+ +
+ + +
+
+ + +
+ +
+
+
} else if pending_set {

(t(lang, Key::SetupInProgress))

} else { @@ -617,6 +630,22 @@ fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> { } } +/// Whether this server can send mail now. The log transport always can. SMTP can only when the +/// stored settings are enabled and name a host and a sender. +pub(crate) async fn mail_can_send(state: &AppState) -> bool { + if state.config.mail.transport == forge_core::config::MailTransport::Log { + return true; + } + match state.store.mail_settings().await { + Ok(settings) => { + settings.enabled + && !settings.host.trim().is_empty() + && !settings.from_addr.trim().is_empty() + } + Err(_) => false, + } +} + /// Builds the page data from the stored state and the message set for this render. async fn build_page( state: &AppState, @@ -692,6 +721,7 @@ async fn build_page( stored_email, email_status, email_sent, + mail_ready: mail_can_send(state).await, email: shown .email_draft .unwrap_or_else(|| viewer.0.email.clone().unwrap_or_default()), @@ -1103,6 +1133,11 @@ async fn two_factor_recovery(cx: &Cx, Form(form): Form) -> Result +
for (number, label, checked) in tabs.into_iter() { @@ -474,6 +475,9 @@ async fn snippet_body( confirm_act(lang: lang, label: g::t(lang, K::Delete), action: delete_action.as_str(), csrf: token.as_str()) } ) + if is_owner { + crate::pages::profile::own_profile_tabs(lang: lang, username: owner.to_owned(), current: "snippets".to_owned()) + }
if !description.is_empty() { @@ -510,6 +514,7 @@ async fn revisions_body( title: &str, revisions: Vec, live: Option, + owner_tabs: Option, ) -> Result { let back = format!("/snippets/{snippet_id}"); let heading = g::revisions_of(lang, title); @@ -517,6 +522,9 @@ async fn revisions_body( head(title: heading.as_str(), (g::t(lang, K::BackToSnippet)) ) + if let Some(owner) = owner_tabs { + crate::pages::profile::own_profile_tabs(lang: lang, username: owner, current: "snippets".to_owned()) + }
if revisions.is_empty() {

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

@@ -547,9 +555,11 @@ async fn snippet_form_page( let title = draft.title.clone(); let description = draft.description.clone(); let visibility = draft.visibility.clone(); + let tab_user = viewer.0.username.clone(); Ok(view! { shell(title: heading, viewer: Some(viewer), head(title: heading) + crate::pages::profile::own_profile_tabs(lang: lang, username: tab_user, current: "snippets".to_owned())
snippet_form(lang: lang, csrf: csrf.as_str(), action: action, title: title.as_str(), description: description.as_str(), @@ -779,7 +789,8 @@ async fn snippet_revisions(cx: &Cx) -> Result { Ok(view! { shell(title: snippet.title.as_str(), viewer: viewer.as_ref(), revisions_body(lang: lang, snippet_id: snippet.id.as_str(), title: snippet.title.as_str(), - revisions: rows, live: Some(item_live_url(snippet.id.as_str()))) + revisions: rows, live: Some(item_live_url(snippet.id.as_str())), + owner_tabs: viewer.as_ref().filter(|(user, _)| user.id == snippet.owner_id).map(|(user, _)| user.username.clone())) ) }) } diff --git a/crates/forge-web/src/views/find.rs b/crates/forge-web/src/views/find.rs new file mode 100644 index 0000000..15ec068 --- /dev/null +++ b/crates/forge-web/src/views/find.rs @@ -0,0 +1,212 @@ +//! Search in a list: one field, live as you type, with two options beside it. By default a search +//! forgives typos and case: every word typed must be in the text, or close to one of its words +//! (one slip in words of four to seven letters, two in longer ones), or the start of one. "Exact" asks for the typed +//! text as it is, as one piece; "Match case" keeps upper and lower case apart and looks for each +//! word as typed. + +use topcoat::Result; +use topcoat::view::{View, component, view}; + +use crate::i18n::Lang; +use crate::pages::passkeys::s; + +/// The longest search kept, in characters. +pub const MAX_QUERY_CHARS: usize = 100; + +/// A search as typed, with its options. +#[derive(Clone, Debug, Default)] +pub struct Finder { + /// The search as typed, trimmed. + pub q: String, + pub exact: bool, + pub case: bool, + /// The search folded for matching: lower case unless Match case is on. + needle: String, + words: Vec>, +} + +impl Finder { + /// A search from the query's `q`, `exact` and `case` values. An option is on when its value is + /// present and not empty. + pub fn new(q: Option<&str>, exact: Option<&str>, case: Option<&str>) -> Finder { + let q: String = q + .unwrap_or("") + .trim() + .chars() + .take(MAX_QUERY_CHARS) + .collect(); + let exact = exact.is_some_and(|v| !v.is_empty()); + let case = case.is_some_and(|v| !v.is_empty()); + let needle = if case { q.clone() } else { q.to_lowercase() }; + let words = needle + .split(|c: char| !c.is_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(|w| w.chars().collect()) + .collect(); + Finder { + q, + exact, + case, + needle, + words, + } + } + + /// True when nothing was typed: everything matches. + pub fn is_empty(&self) -> bool { + self.needle.is_empty() + } + + /// True when `text` matches the search. + pub fn matches(&self, text: &str) -> bool { + if self.is_empty() { + return true; + } + let hay = if self.case { + text.to_owned() + } else { + text.to_lowercase() + }; + if hay.contains(&self.needle) { + return true; + } + if self.exact { + return false; + } + // Word by word, each typed word must start one of the text's words, so a short word such + // as "1" does not match every text with a 1 somewhere in it. Match case asks for the words + // as typed, so a slip of case is not forgiven as a typo. + let tokens: Vec> = hay + .split(|c: char| !c.is_alphanumeric()) + .filter(|t| !t.is_empty()) + .map(|t| t.chars().collect()) + .collect(); + !self.words.is_empty() + && self.words.iter().all(|word| { + tokens + .iter() + .any(|token| token.starts_with(word) || (!self.case && near(word, token))) + }) + } + + /// True when any of `fields` matches, read as one text. + pub fn matches_any(&self, fields: &[&str]) -> bool { + self.is_empty() || self.matches(&fields.join(" \u{1f} ")) + } + + /// The query pairs that keep this search in a link: `q`, and each option that is on. + pub fn params(&self) -> Vec<(&'static str, &str)> { + let mut out = vec![("q", self.q.as_str())]; + if self.exact { + out.push(("exact", "1")); + } + if self.case { + out.push(("case", "1")); + } + out + } +} + +/// How many slips a typed word of `len` letters may have. +fn slips_for(len: usize) -> usize { + match len { + 0..=3 => 0, + 4..=7 => 1, + _ => 2, + } +} + +/// True when the typed `word` is close to `token`, or to the start of it as long as the word. +fn near(word: &[char], token: &[char]) -> bool { + let slips = slips_for(word.len()); + if slips == 0 { + return false; + } + if distance(word, token) <= slips { + return true; + } + token.len() > word.len() && distance(word, &token[..word.len()]) <= slips +} + +/// Edits (insert, delete, change, swap two neighbours) between two words. +fn distance(a: &[char], b: &[char]) -> usize { + if a.len().abs_diff(b.len()) > 2 { + return usize::MAX; + } + let (n, m) = (a.len(), b.len()); + let mut d = vec![vec![0usize; m + 1]; n + 1]; + for (i, row) in d.iter_mut().enumerate() { + row[0] = i; + } + for j in 0..=m { + d[0][j] = j; + } + for i in 1..=n { + for j in 1..=m { + let cost = usize::from(a[i - 1] != b[j - 1]); + let mut best = (d[i - 1][j] + 1) + .min(d[i][j - 1] + 1) + .min(d[i - 1][j - 1] + cost); + if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] { + best = best.min(d[i - 2][j - 2] + 1); + } + d[i][j] = best; + } + } + d[n][m] +} + +/// The search field of a list, with its two options beside it, for inside a GET form. The field +/// searches as you type; an option applies the moment it is ticked. +#[component] +pub async fn finder_field( + lang: Lang, + finder: Finder, + placeholder: &str, + #[default] id: Option<&str>, +) -> Result { + let id = id.unwrap_or("find-q"); + Ok(view! { +
+ + + + +
+ }) +} + +#[cfg(test)] +mod tests { + use super::Finder; + + fn find(q: &str, exact: bool, case: bool) -> Finder { + Finder::new(Some(q), exact.then_some("1"), case.then_some("1")) + } + + #[test] + fn forgives_typos_and_case_unless_asked() { + let text = "Repository created · Hezarfen/hezarfen_landing"; + assert!(find("", false, false).matches(text)); + assert!(find("reposotory", false, false).matches(text)); + assert!(find("landnig hezarfen", false, false).matches(text)); + assert!(find("crea", false, false).matches(text)); + assert!(!find("deleted", false, false).matches(text)); + assert!(!find("reposotory", true, false).matches(text)); + assert!(find("repository CREATED", true, false).matches(text)); + assert!(!find("repository", false, true).matches(text)); + assert!(find("Repository", false, true).matches(text)); + assert!(!find("bulk 1", false, false).matches("tahinli/bulk-21")); + assert!(find("bulk 1", false, false).matches("tahinli/bulk-12")); + } +} diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index dfb8c2a..6e5bccb 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -4,6 +4,7 @@ pub mod commit_line; pub mod commit_status; pub mod diff; +pub mod find; pub mod heatmap; pub mod parts; pub mod repo_list; @@ -1218,9 +1219,19 @@ pub fn display_name(lang: Lang, username: &str) -> String { } /// URL of a user's avatar. `hash` is the avatar's content hash (`?v=` makes the response -/// immutable); `None` gives the generated default, which is cached for a short time only. +/// immutable); `None` means the account has no photo, and gives its letter avatar inline, so the +/// page shows it with no request. pub fn avatar_url(username: &str, hash: Option<&str>) -> String { - format!("/avatars/{}?v={}", enc(username), hash.unwrap_or("default")) + match hash { + Some(hash) => format!("/avatars/{}?v={hash}", enc(username)), + None => crate::pages::avatars::default_data_url(username), + } +} + +/// URL of a user's avatar when the page does not know whether the account has a photo: the server +/// answers with the photo or the letter avatar. +pub fn avatar_url_unknown(username: &str) -> String { + format!("/avatars/{}?v=default", enc(username)) } /// Public profile URL of a user: `/{username}`. @@ -2026,10 +2037,10 @@ mod shell_tests { // An anonymous page renders the default colours. let tag = html_tag(&html); - assert!(tag.contains("data-accent-light=\"ember\""), "{tag}"); - assert!(tag.contains("data-accent-dark=\"ember\""), "{tag}"); - assert!(tag.contains("data-base-light=\"anvil\""), "{tag}"); - assert!(tag.contains("data-base-dark=\"anvil\""), "{tag}"); + assert!(tag.contains("data-accent-light=\"sage\""), "{tag}"); + assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}"); + assert!(tag.contains("data-base-light=\"ink\""), "{tag}"); + assert!(tag.contains("data-base-dark=\"ink\""), "{tag}"); } /// The `` start tag of a page. @@ -2101,10 +2112,10 @@ mod shell_tests { ["removed-palette", "removed-palette", "x", "x"], ) .await; - assert!(removed.contains("data-accent-light=\"ember\""), "{removed}"); - assert!(removed.contains("data-accent-dark=\"ember\""), "{removed}"); - assert!(removed.contains("data-base-light=\"anvil\""), "{removed}"); - assert!(removed.contains("data-base-dark=\"anvil\""), "{removed}"); + assert!(removed.contains("data-accent-light=\"sage\""), "{removed}"); + assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}"); + assert!(removed.contains("data-base-light=\"ink\""), "{removed}"); + assert!(removed.contains("data-base-dark=\"ink\""), "{removed}"); // A removed preset (`ochre`, `mist`) falls back too, and a hue passes through as itself. let retired = html_tag_for_colours( &router, @@ -2114,10 +2125,10 @@ mod shell_tests { ["ochre", "terracotta", "mist", "stone"], ) .await; - assert!(retired.contains("data-accent-light=\"ember\""), "{retired}"); - assert!(retired.contains("data-accent-dark=\"ember\""), "{retired}"); - assert!(retired.contains("data-base-light=\"anvil\""), "{retired}"); - assert!(retired.contains("data-base-dark=\"anvil\""), "{retired}"); + assert!(retired.contains("data-accent-light=\"sage\""), "{retired}"); + assert!(retired.contains("data-accent-dark=\"sage\""), "{retired}"); + assert!(retired.contains("data-base-light=\"ink\""), "{retired}"); + assert!(retired.contains("data-base-dark=\"ink\""), "{retired}"); let hued = html_tag_for_colours( &router, &store, diff --git a/crates/forge-web/src/views/repo_list.rs b/crates/forge-web/src/views/repo_list.rs index 7874f4e..9414460 100644 --- a/crates/forge-web/src/views/repo_list.rs +++ b/crates/forge-web/src/views/repo_list.rs @@ -101,23 +101,36 @@ pub struct PageLink { current: bool, } -/// The pages to show for `page` of `pages`: the first, the last and the neighbours of the -/// current page, with `None` for a gap. A gap of a single page shows that page instead. +/// How many page slots the numbered pager shows once there are more pages than that. +const PAGE_SLOTS: u64 = 7; + +/// The pages to show for `page` of `pages`, with `None` for a gap. Past seven pages there are +/// always seven slots (the first, the last, the current one's neighbours and the gaps), so moving +/// between pages never moves Next or the numbers. fn page_numbers(page: u64, pages: u64) -> Vec> { - let mut out = Vec::new(); - let mut last = 0; - for n in 1..=pages { - let near = n == 1 || n == pages || n.abs_diff(page) <= 1; - let fills_gap = (n == 2 && page == 4) || (n + 1 == pages && page + 3 == pages); - if near || fills_gap { - if n > last + 1 { - out.push(None); - } - out.push(Some(n)); - last = n; - } + if pages <= PAGE_SLOTS { + return (1..=pages).map(Some).collect(); + } + let page = page.clamp(1, pages); + if page <= 4 { + let mut out: Vec> = (1..=5).map(Some).collect(); + out.extend([None, Some(pages)]); + out + } else if page + 3 >= pages { + let mut out = vec![Some(1), None]; + out.extend((pages - 4..=pages).map(Some)); + out + } else { + vec![ + Some(1), + None, + Some(page - 1), + Some(page), + Some(page + 1), + None, + Some(pages), + ] } - out } /// The numbered pager with Previous and Next, from `pager_links`. Nothing is shown for a single @@ -138,6 +151,8 @@ pub async fn pager( } @@ -200,10 +217,14 @@ mod tests { fn pages_are_compact_with_gaps() { assert_eq!(shown(1, 1), "1"); assert_eq!(shown(1, 3), "1 2 3"); + assert_eq!(shown(1, 7), "1 2 3 4 5 6 7"); assert_eq!(shown(5, 12), "1 ... 4 5 6 ... 12"); - assert_eq!(shown(1, 12), "1 2 ... 12"); - assert_eq!(shown(12, 12), "1 ... 11 12"); + assert_eq!(shown(1, 12), "1 2 3 4 5 ... 12"); + assert_eq!(shown(12, 12), "1 ... 8 9 10 11 12"); assert_eq!(shown(4, 12), "1 2 3 4 5 ... 12"); assert_eq!(shown(9, 12), "1 ... 8 9 10 11 12"); + for page in 1..=54 { + assert_eq!(page_numbers(page, 54).len(), 7, "page {page}"); + } } } diff --git a/crates/forge-web/src/views/review_thread.rs b/crates/forge-web/src/views/review_thread.rs index 6fcf884..701e2c6 100644 --- a/crates/forge-web/src/views/review_thread.rs +++ b/crates/forge-web/src/views/review_thread.rs @@ -16,7 +16,7 @@ use crate::i18n::pulls_review::{self as g, K}; use crate::pages::issue_parts::When; use crate::render::markdown::{LinkContext, render_markdown}; use crate::views::parts::{confirm_act, post_act, reveal}; -use crate::views::{avatar_url, display_name, now_unix, user_href, user_link}; +use crate::views::{avatar_url_unknown, display_name, now_unix, user_href, user_link}; /// What the Apply control of a suggestion shows. A root without a state shows the diff only. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -149,7 +149,7 @@ fn comment_row( let edited = ctx.edits.get(&comment.id).is_some_and(|count| *count > 0); let parts = body_parts(&comment, ctx, state); CommentRow { - avatar: avatar_url(&comment.author_name, None), + avatar: avatar_url_unknown(&comment.author_name), author: display_name(lang, &comment.author_name), login: comment.author_name.clone(), when: When::new(lang, &comment.created_at, &ctx.tz, now), diff --git a/docs/ui-language.md b/docs/ui-language.md index 4df5ad0..dbb904e 100644 --- a/docs/ui-language.md +++ b/docs/ui-language.md @@ -67,10 +67,15 @@ no `margin-left:auto`, no `justify-content:space-between`, no second column at t - **Button**: `