diff --git a/crates/forge-core/migrations/0042_colours.sql b/crates/forge-core/migrations/0042_colours.sql new file mode 100644 index 0000000..f1927bc --- /dev/null +++ b/crates/forge-core/migrations/0042_colours.sql @@ -0,0 +1,12 @@ +-- Colour choices per user: the accent and base palettes for the light and the dark theme. The +-- ids are those of forge-web's accent_palette.rs, which decides what exists, so there is no +-- CHECK list here. Applied by store/migrate.rs. +-- +-- `accent` now means the light-theme accent. The dark accent starts as a copy of it, so an +-- existing user sees the same colours in both themes until they choose otherwise. + +ALTER TABLE users ADD COLUMN accent_dark TEXT NOT NULL DEFAULT 'sage'; +ALTER TABLE users ADD COLUMN base_light TEXT NOT NULL DEFAULT 'fern'; +ALTER TABLE users ADD COLUMN base_dark TEXT NOT NULL DEFAULT 'fern'; + +UPDATE users SET accent_dark = accent; diff --git a/crates/forge-core/src/authz.rs b/crates/forge-core/src/authz.rs index b164377..6a7fb92 100644 --- a/crates/forge-core/src/authz.rs +++ b/crates/forge-core/src/authz.rs @@ -129,6 +129,9 @@ mod tests { theme: "auto".into(), language: "auto".into(), accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), + base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), kind: AccountKind::User, email_notifications: true, } diff --git a/crates/forge-core/src/model.rs b/crates/forge-core/src/model.rs index b96bf4b..74c5ca4 100644 --- a/crates/forge-core/src/model.rs +++ b/crates/forge-core/src/model.rs @@ -47,8 +47,15 @@ pub struct User { pub theme: String, /// Language code, e.g. "en"; "auto" uses the instance default. pub language: String, - /// Accent colour: the id of a palette in forge-web's `accent_palette.rs`. "sage" is the default. + /// Accent colour for the light theme: the id of a palette in forge-web's `accent_palette.rs`. + /// "sage" is the default. pub accent: String, + /// 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. "fern" is the default. + pub base_light: String, + /// Base set for the dark theme. "fern" is the default. + pub base_dark: String, /// `User` for a person, `Org` for an organization. pub kind: AccountKind, /// Whether notifications are also sent by email (needs a verified email and instance mail). @@ -130,6 +137,9 @@ impl std::fmt::Debug for User { .field("theme", &self.theme) .field("language", &self.language) .field("accent", &self.accent) + .field("accent_dark", &self.accent_dark) + .field("base_light", &self.base_light) + .field("base_dark", &self.base_dark) .field("kind", &self.kind) .finish() } @@ -219,6 +229,9 @@ mod tests { theme: "auto".into(), language: "auto".into(), accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), + base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), kind: AccountKind::User, email_notifications: true, }; diff --git a/crates/forge-core/src/store/account_tokens.rs b/crates/forge-core/src/store/account_tokens.rs index 2c8947b..6fc734b 100644 --- a/crates/forge-core/src/store/account_tokens.rs +++ b/crates/forge-core/src/store/account_tokens.rs @@ -100,7 +100,7 @@ impl Store { &conn, "SELECT id, username, email, password_hash, is_admin, created_at, about, timezone, \ (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ - theme, language, kind, email_notifications, display_name, accent FROM users WHERE LOWER(email) = LOWER(?1) \ + theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark FROM users WHERE LOWER(email) = LOWER(?1) \ AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1", (email.to_owned(),), map_user, @@ -304,6 +304,9 @@ impl Store { theme: "light".into(), language: "auto".into(), accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), + base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), kind: AccountKind::User, email_notifications: true, }; diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index ea0fbf5..7c5c09f 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -60,6 +60,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (39, include_str!("../../migrations/0039_totp_device.sql")), (40, include_str!("../../migrations/0040_mail_queue.sql")), (41, include_str!("../../migrations/0041_accent.sql")), + (42, include_str!("../../migrations/0042_colours.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index cd352a9..e3f9ed2 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -110,7 +110,7 @@ struct Inner { const USER_COLS: &str = "id, username, email, password_hash, is_admin, created_at, about, timezone, \ (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ - theme, language, kind, email_notifications, display_name, accent"; + theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark"; const SESSION_COLS: &str = "id, user_id, csrf_token, created_at, expires_at, last_seen, user_agent"; const SSH_KEY_COLS: &str = "id, user_id, title, algorithm, key_blob, fingerprint, created_at, last_used_at"; @@ -201,6 +201,9 @@ impl Store { theme: "light".into(), language: "auto".into(), accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), + base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), kind: AccountKind::User, email_notifications: true, }; @@ -245,6 +248,9 @@ impl Store { theme: "light".into(), language: "auto".into(), accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), + base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), kind: AccountKind::User, email_notifications: true, }; @@ -1039,6 +1045,9 @@ fn map_user(row: &Row) -> Result { email_notifications: col_bool(row, 12)?, display_name: col_opt_text(row, 13)?, accent: col_text(row, 14)?, + accent_dark: col_text(row, 15)?, + base_light: col_text(row, 16)?, + base_dark: col_text(row, 17)?, }) } @@ -2169,7 +2178,7 @@ impl Store { WHERE collaborators.repo_id = ?1 ORDER BY users.username_folded" ), (repo_id.to_string(),), - |row| Ok((map_user(row)?, parse_role(&col_text(row, 15)?)?)), + |row| Ok((map_user(row)?, parse_role(&col_text(row, 18)?)?)), ) .await } diff --git a/crates/forge-core/src/store/orgs.rs b/crates/forge-core/src/store/orgs.rs index 6d68af2..2541eac 100644 --- a/crates/forge-core/src/store/orgs.rs +++ b/crates/forge-core/src/store/orgs.rs @@ -277,7 +277,7 @@ impl Store { ORDER BY (org_role = 'owner') DESC, username_folded" ), (org_id.to_string(),), - |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 15)?)?)), + |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 18)?)?)), ) .await } @@ -397,7 +397,7 @@ impl Store { (SELECT org_id FROM org_members WHERE user_id = ?1) ORDER BY username_folded" ), (user_id.to_string(),), - |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 15)?)?)), + |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 18)?)?)), ) .await } diff --git a/crates/forge-core/src/store/ui_prefs.rs b/crates/forge-core/src/store/ui_prefs.rs index e8ad2e5..41bc938 100644 --- a/crates/forge-core/src/store/ui_prefs.rs +++ b/crates/forge-core/src/store/ui_prefs.rs @@ -1,7 +1,8 @@ -//! Per-user UI preferences: the colour theme, the language and the accent colour. All are stored -//! as text in `users` (migrations 0030 and 0041). The web layer decides which values it offers; -//! the store only checks that a value is well formed, so a new language or accent needs no store -//! change. +//! Per-user UI preferences: the colour theme, the language and the colour choices. The colours +//! are an accent and a base (neutral background, surface and text) for each of the light and the +//! dark theme. All are stored as text in `users` (migrations 0030, 0041 and 0042). The web layer +//! decides which values it offers; the store only checks that a value is well formed, so a new +//! language, accent or base needs no store change. use super::{Store, db_err}; use crate::error::{Error, Result}; @@ -16,6 +17,10 @@ pub const AUTO: &str = "auto"; /// `accent_palette.rs`, which a test there checks. 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 = "fern"; + /// Longest accepted language code, in bytes. const MAX_LANGUAGE_LEN: usize = 16; @@ -70,7 +75,8 @@ impl Store { Ok(()) } - /// Sets the user's accent colour id. A malformed id is rejected and nothing is written. + /// Sets the user's accent colour id for both themes. A malformed id is rejected and nothing is + /// written. pub async fn set_accent(&self, user_id: &str, accent: &str) -> Result<()> { if !valid_accent(accent) { return Err(Error::Invalid(format!("accent {accent:?}"))); @@ -78,7 +84,7 @@ impl Store { let conn = self.inner.conn.lock().await; let n = conn .execute( - "UPDATE users SET accent = ?2 WHERE id = ?1", + "UPDATE users SET accent = ?2, accent_dark = ?2 WHERE id = ?1", (user_id.to_string(), accent.to_string()), ) .await @@ -89,6 +95,47 @@ impl Store { Ok(()) } + /// Sets the four colour choices: the accent and the base for the light theme, then the accent + /// and the base for the dark theme. If any id is malformed, nothing is written. + pub async fn set_colours( + &self, + user_id: &str, + accent_light: &str, + accent_dark: &str, + base_light: &str, + base_dark: &str, + ) -> Result<()> { + for accent in [accent_light, accent_dark] { + if !valid_accent(accent) { + return Err(Error::Invalid(format!("accent {accent:?}"))); + } + } + for base in [base_light, base_dark] { + if !valid_accent(base) { + return Err(Error::Invalid(format!("base {base:?}"))); + } + } + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "UPDATE users SET accent = ?2, accent_dark = ?3, base_light = ?4, base_dark = ?5 \ + WHERE id = ?1", + ( + user_id.to_string(), + accent_light.to_string(), + accent_dark.to_string(), + base_light.to_string(), + base_dark.to_string(), + ), + ) + .await + .map_err(db_err)?; + if n == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + /// Turns the email copy of notifications on or off for one user (migration 0035). pub async fn set_email_notifications(&self, user_id: &str, on: bool) -> Result<()> { let conn = self.inner.conn.lock().await; @@ -159,6 +206,84 @@ mod tests { ); } + #[tokio::test] + async fn colours_persist_and_bad_values_change_nothing() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let user = store + .create_user("tahinli", None, "hash", false) + .await + .unwrap(); + assert_eq!(user.accent_dark, DEFAULT_ACCENT); + assert_eq!(user.base_light, DEFAULT_BASE); + assert_eq!(user.base_dark, DEFAULT_BASE); + + store + .set_colours(&user.id, "ocean", "rose", "stone", "ink") + .await + .unwrap(); + let stored = store.user_by_id(&user.id).await.unwrap().unwrap(); + assert_eq!( + ( + stored.accent.as_str(), + stored.accent_dark.as_str(), + stored.base_light.as_str(), + stored.base_dark.as_str() + ), + ("ocean", "rose", "stone", "ink") + ); + + assert!( + store + .set_colours(&user.id, "ocean", "Rose", "stone", "ink") + .await + .is_err() + ); + assert!( + store + .set_colours(&user.id, "ocean", "rose", "../x", "ink") + .await + .is_err() + ); + assert!( + store + .set_colours(&user.id, "ocean", "rose", "stone", "") + .await + .is_err() + ); + let still = store.user_by_id(&user.id).await.unwrap().unwrap(); + assert_eq!( + ( + still.accent.as_str(), + still.accent_dark.as_str(), + still.base_light.as_str(), + still.base_dark.as_str() + ), + ("ocean", "rose", "stone", "ink") + ); + } + + #[tokio::test] + async fn set_accent_sets_both_accents_and_keeps_bases() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let user = store + .create_user("tahinli", None, "hash", false) + .await + .unwrap(); + store + .set_colours(&user.id, "sage", "sage", "mist", "ink") + .await + .unwrap(); + + store.set_accent(&user.id, "ocean").await.unwrap(); + let stored = store.user_by_id(&user.id).await.unwrap().unwrap(); + assert_eq!(stored.accent, "ocean"); + assert_eq!(stored.accent_dark, "ocean"); + assert_eq!(stored.base_light, "mist"); + assert_eq!(stored.base_dark, "ink"); + } + #[tokio::test] async fn prefs_persist_and_bad_values_change_nothing() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/forge-core/src/store/user_delete.rs b/crates/forge-core/src/store/user_delete.rs index 9a4bffe..cb88640 100644 --- a/crates/forge-core/src/store/user_delete.rs +++ b/crates/forge-core/src/store/user_delete.rs @@ -167,6 +167,9 @@ impl Store { theme: "light".into(), language: "auto".into(), accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), + base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), + base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), kind: AccountKind::User, email_notifications: true, }; diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index e871c97..be0fb05 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -13,6 +13,7 @@ var liveDirty = false; // a live change came while a navigation was on the wire var inFlight = 0; // requests on the wire, drives aria-busy var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored + var queued = new WeakSet(); // forms that changed while pending: submitted again once it completes var shown = location.pathname + location.search; var GET_INIT = { headers: { accept: 'text/html' } }; @@ -46,9 +47,11 @@ } // Field preservation: a dirty or focused field keeps its value, and the caret offsets come along. + // Radios and checkboxes share a name, so their value is part of the key to tell them apart. function fieldKey(el) { var form = el.form ? (el.form.getAttribute('action') || '') : ''; - return form + '|' + (el.name || '') + '|' + (el.type || '') + '|' + el.tagName; + var value = el.type === 'radio' || el.type === 'checkbox' ? el.value : ''; + return form + '|' + (el.name || '') + '|' + (el.type || '') + '|' + el.tagName + '|' + value; } function savable(el) { @@ -127,7 +130,7 @@ function adopt(doc, keepFields, dd) { document.title = doc.title; - ['lang', 'data-theme', 'data-accent', 'data-ui'].forEach(function (name) { + ['lang', 'data-theme', 'data-accent-light', 'data-accent-dark', 'data-base-light', 'data-base-dark', 'data-ui'].forEach(function (name) { if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); } else { root.removeAttribute(name); } }); @@ -245,9 +248,24 @@ userBusy -= 1; if (liveDirty) { refreshLive(); } } + if (o.form && queued.has(o.form)) { queued.delete(o.form); resend(o.form); } }); } + // The form to send a queued change on: the form itself, or after a swap the one with the same action. + function resend(form) { + var target = form; + if (!form.isConnected) { + target = null; + var action = form.getAttribute('action') || ''; + for (var i = 0; i < document.forms.length; i++) { + if ((document.forms[i].getAttribute('action') || '') === action) { target = document.forms[i]; break; } + } + } + if (!target) { return; } + if (target.requestSubmit) { target.requestSubmit(); } else { target.submit(); } + } + function saveScroll() { try { history.replaceState({ y: window.scrollY }, '', location.href); } catch (err) { } } @@ -399,9 +417,28 @@ document.addEventListener('change', function (e) { var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null; if (!c || !c.form) { return; } + // A request is already on the wire for this form: the change waits for it, and is sent when it completes. + if (pending.has(c.form)) { queued.add(c.form); return; } if (c.form.requestSubmit) { c.form.requestSubmit(); } else { c.form.submit(); } }); + // Appearance page: a colour or theme choice shows on at once, before the form's request returns. + // The attributes match what the shell renders: theme `auto` has no data-theme, `dark` is dark, else light. + var PREVIEW_ATTR = { accent_light: 'data-accent-light', accent_dark: 'data-accent-dark', base_light: 'data-base-light', base_dark: 'data-base-dark' }; + + document.addEventListener('change', function (e) { + var el = e.target; + if (!el || !el.form || !el.form.hasAttribute('data-appearance')) { return; } + if (el.name === 'theme') { + if (el.value === 'auto') { root.removeAttribute('data-theme'); } + else { root.setAttribute('data-theme', el.value === 'dark' ? 'dark' : 'light'); } + return; + } + if (el.type === 'radio' && Object.prototype.hasOwnProperty.call(PREVIEW_ATTR, el.name)) { + root.setAttribute(PREVIEW_ATTR[el.name], el.value); + } + }, false); + // A filtered view asked for in place: the URL is replaced (no history entry per change), fields // and caret come through the swap, and the scroll stays put. // Live unread count. The bell is re-rendered by every swap, so it is looked up on each update. One diff --git a/crates/forge-web/build.rs b/crates/forge-web/build.rs index 771c318..e1424fa 100644 --- a/crates/forge-web/build.rs +++ b/crates/forge-web/build.rs @@ -2,8 +2,8 @@ //! asset also gets a content hash (FORGE_MAIN_CSS_V, FORGE_NAV_JS_V) that the page links use as //! their cache-busting query, so an unchanged file keeps its URL and a changed one gets a new one. //! -//! The accent colours come from `src/accent_palette.rs`, the same data the app reads. This script -//! turns it into `_accents.scss` in OUT_DIR, which main.scss imports. +//! The accent colours and the neutral bases come from `src/accent_palette.rs`, the same data the +//! app reads. This script turns it into `_accents.scss` in OUT_DIR, which main.scss imports. use std::{env, fs, path::PathBuf}; @@ -14,77 +14,153 @@ use sha2::{Digest, Sha256}; #[allow(dead_code)] mod accent_palette; -use accent_palette::{DEFAULT, PALETTES, Palette, TOKEN_VARS, Tokens}; +use accent_palette::{ + BASE_DEFAULT, BASE_TOKEN_VARS, BASES, Base, BaseTokens, DEFAULT, PALETTES, Palette, TOKEN_VARS, + Tokens, +}; /// First 12 hex characters of the SHA-256 of `bytes`. fn content_version(bytes: &[u8]) -> String { encode(Sha256::digest(bytes))[..12].to_string() } -/// One `--token: value;` line per token, indented for a rule body. -fn declarations(tokens: &Tokens) -> String { +/// The `(name, value)` declarations of one accent palette's tokens in one theme. +fn accent_decls(tokens: &Tokens) -> Vec<(&'static str, &'static str)> { TOKEN_VARS .iter() - .map(|token| format!(" {}: {};\n", token.name, (token.value)(tokens))) + .map(|token| (token.name, (token.value)(tokens))) .collect() } -/// Appends `selector { … }` with the palette's tokens for one theme. `indent` is 0 or 2. -fn rule(css: &mut String, indent: &str, selector: &str, tokens: &Tokens) { +/// The `(name, value)` declarations of one base's neutral tokens in one theme. +fn base_decls(tokens: &BaseTokens) -> Vec<(&'static str, &'static str)> { + BASE_TOKEN_VARS + .iter() + .map(|token| (token.name, (token.value)(tokens))) + .collect() +} + +/// Appends `selector { … }` with one `--token: value;` line per declaration. `indent` is 0 or 2. +fn rule(css: &mut String, indent: &str, selector: &str, decls: &[(&str, &str)]) { css.push_str(&format!("{indent}{selector} {{\n")); - for line in declarations(tokens).lines() { - css.push_str(&format!("{indent}{line}\n")); + for (name, value) in decls { + css.push_str(&format!("{indent} {name}: {value};\n")); } css.push_str(&format!("{indent}}}\n")); } -/// The rules for one palette. The default palette sits on bare `:root`, as it always has. Every -/// other palette is scoped to `[data-accent]`, which is more specific, so it wins over the -/// default in all three theme states: light, dark by `data-theme`, and dark by the OS. -fn palette_rules(css: &mut String, palette: &Palette) { - let base = if palette.id == DEFAULT { - ":root".to_string() - } else { - format!(":root[data-accent=\"{}\"]", palette.id) - }; - let os_dark = format!("{base}:not([data-theme=\"light\"])"); - let forced_dark = format!("{base}[data-theme=\"dark\"]"); - rule(css, "", &base, &palette.light); +/// The rules for one choice: its light tokens on `light`, and its dark tokens on `dark` in both +/// dark states, by the OS and by `data-theme`. Dark selectors carry one more attribute than the +/// light one, so the dark rules win in dark mode whatever the light choice is. +fn choice_rules( + css: &mut String, + light: &str, + dark: &str, + light_decls: &[(&str, &str)], + dark_decls: &[(&str, &str)], +) { + let os_dark = format!("{dark}:not([data-theme=\"light\"])"); + let forced_dark = format!("{dark}[data-theme=\"dark\"]"); + rule(css, "", light, light_decls); css.push_str("@media (prefers-color-scheme: dark) {\n"); - rule(css, " ", &os_dark, &palette.dark); + rule(css, " ", &os_dark, dark_decls); css.push_str("}\n"); - rule(css, "", &forced_dark, &palette.dark); + rule(css, "", &forced_dark, dark_decls); +} + +/// The bare fallbacks for pages without the choice attributes: the default accent and base, on +/// plain `:root`. +fn fallback_rules(css: &mut String) { + let accent = PALETTES + .iter() + .find(|p| p.id == DEFAULT) + .expect("the default accent is one of the palettes"); + choice_rules( + css, + ":root", + ":root", + &accent_decls(&accent.light), + &accent_decls(&accent.dark), + ); + let base = BASES + .iter() + .find(|b| b.id == BASE_DEFAULT) + .expect("the default base is one of the bases"); + choice_rules( + css, + ":root", + ":root", + &base_decls(&base.light), + &base_decls(&base.dark), + ); } -/// The swatch chip for one palette in the settings picker: its accent, light or dark. -fn swatch_rules(css: &mut String, palette: &Palette) { - let swatch = format!(".accent-swatch[data-accent-swatch=\"{}\"]", palette.id); - css.push_str(&format!( - "{swatch} {{ background: {}; }}\n", - palette.light.accent - )); - css.push_str(&format!( - "@media (prefers-color-scheme: dark) {{\n :root:not([data-theme=\"light\"]) {swatch} {{ background: {}; }}\n}}\n", - palette.dark.accent - )); - css.push_str(&format!( - ":root[data-theme=\"dark\"] {swatch} {{ background: {}; }}\n", - palette.dark.accent - )); +/// The rules for one accent palette: its light tokens are keyed on `data-accent-light`, its dark +/// tokens on `data-accent-dark`. +fn palette_rules(css: &mut String, palette: &Palette) { + choice_rules( + css, + &format!(":root[data-accent-light=\"{}\"]", palette.id), + &format!(":root[data-accent-dark=\"{}\"]", palette.id), + &accent_decls(&palette.light), + &accent_decls(&palette.dark), + ); +} + +/// The rules for one base: its light tokens are keyed on `data-base-light`, its dark tokens on +/// `data-base-dark`. +fn base_rules(css: &mut String, base: &Base) { + choice_rules( + css, + &format!(":root[data-base-light=\"{}\"]", base.id), + &format!(":root[data-base-dark=\"{}\"]", base.id), + &base_decls(&base.light), + &base_decls(&base.dark), + ); } -/// The whole generated stylesheet: the palettes, then the swatch chips. +/// The swatch chips for the settings picker. They show fixed colours, so they do not depend on +/// the current theme: an accent chip is the accent itself, a base chip is its background and text +/// split diagonally. +fn swatch_rules(css: &mut String) { + for palette in PALETTES { + css.push_str(&format!( + ".accent-swatch[data-accent-light-swatch=\"{}\"] {{ background: {}; }}\n", + palette.id, palette.light.accent + )); + css.push_str(&format!( + ".accent-swatch[data-accent-dark-swatch=\"{}\"] {{ background: {}; }}\n", + palette.id, palette.dark.accent + )); + } + for base in BASES { + css.push_str(&format!( + ".base-swatch[data-base-light-swatch=\"{}\"] {{ background: linear-gradient(135deg, {} 0 50%, {} 50% 100%); }}\n", + base.id, base.light.bg, base.light.text + )); + css.push_str(&format!( + ".base-swatch[data-base-dark-swatch=\"{}\"] {{ background: linear-gradient(135deg, {} 0 50%, {} 50% 100%); }}\n", + base.id, base.dark.bg, base.dark.text + )); + } +} + +/// The whole generated stylesheet: the bare fallbacks, the accent and base rules, then the swatch +/// chips. fn accents_scss() -> String { let mut css = String::from( "/* Generated by crates/forge-web/build.rs from src/accent_palette.rs. Edit that file. */\n", ); assert_eq!(PALETTES[0].id, DEFAULT, "the default palette comes first"); + assert_eq!(BASES[0].id, BASE_DEFAULT, "the default base comes first"); + fallback_rules(&mut css); for palette in PALETTES { palette_rules(&mut css, palette); } - for palette in PALETTES { - swatch_rules(&mut css, palette); + for base in BASES { + base_rules(&mut css, base); } + swatch_rules(&mut css); css } diff --git a/crates/forge-web/src/accent.rs b/crates/forge-web/src/accent.rs index eb351be..b318a12 100644 --- a/crates/forge-web/src/accent.rs +++ b/crates/forge-web/src/accent.rs @@ -1,8 +1,8 @@ -//! Accent colour: which palette a viewer sees. The colours live in `accent_palette.rs`, which -//! `build.rs` also turns into the stylesheet. This module only resolves stored ids and checks -//! which ids forge offers. +//! Accent colour and base: which palette and which neutral set a viewer sees. The values live in +//! `accent_palette.rs`, which `build.rs` also turns into the stylesheet. This module only resolves +//! stored ids and checks which ids forge offers. -use crate::accent_palette::{DEFAULT, PALETTES, Palette}; +use crate::accent_palette::{BASE_DEFAULT, BASES, Base, DEFAULT, PALETTES, Palette}; /// The palette for a stored id. An unknown or removed id falls back to the default. pub fn resolve(stored: &str) -> &'static Palette { @@ -22,6 +22,24 @@ pub fn ids() -> impl Iterator { PALETTES.iter().map(|p| p.id) } +/// The base for a stored id. An unknown or removed id falls back to the default. +pub fn resolve_base(stored: &str) -> &'static Base { + BASES + .iter() + .find(|b| b.id == stored) + .unwrap_or_else(default_base) +} + +/// True when forge offers this base id. +pub fn is_offered_base(id: &str) -> bool { + BASES.iter().any(|b| b.id == id) +} + +/// Every offered base id, in the order the picker lists them. +pub fn base_ids() -> impl Iterator { + BASES.iter().map(|b| b.id) +} + fn default_palette() -> &'static Palette { PALETTES .iter() @@ -29,18 +47,19 @@ fn default_palette() -> &'static Palette { .expect("the default accent is one of the palettes") } +fn default_base() -> &'static Base { + BASES + .iter() + .find(|b| b.id == BASE_DEFAULT) + .expect("the default base is one of the bases") +} + #[cfg(test)] mod tests { use std::collections::HashSet; use super::*; - use crate::accent_palette::{TOKEN_VARS, Tokens}; - - /// The neutral backgrounds of style/main.scss, in each theme. - const LIGHT_BG: &str = "#F6F8F5"; - const LIGHT_SURFACE: &str = "#FFFFFF"; - const DARK_BG: &str = "#121613"; - const DARK_SURFACE: &str = "#191E1A"; + use crate::accent_palette::{BASE_TOKEN_VARS, TOKEN_VARS, Tokens}; /// WCAG relative luminance of a `#RRGGBB` colour. fn luminance(hex: &str) -> f64 { @@ -82,6 +101,21 @@ mod tests { } } + #[test] + fn base_ids_are_slugs_unique_and_the_default_comes_first() { + assert_eq!(BASES[0].id, BASE_DEFAULT); + assert_eq!(BASE_DEFAULT, forge_core::store::ui_prefs::DEFAULT_BASE); + let mut seen = HashSet::new(); + for b in BASES { + assert!( + forge_core::store::ui_prefs::valid_accent(b.id), + "{} is not a slug", + b.id + ); + assert!(seen.insert(b.id), "{} is listed twice", b.id); + } + } + #[test] fn every_token_is_a_hex_colour() { for p in PALETTES { @@ -91,6 +125,13 @@ mod tests { } } } + for b in BASES { + for token in BASE_TOKEN_VARS { + for t in [&b.light, &b.dark] { + assert!(is_hex_colour((token.value)(t)), "{} {}", b.id, token.name); + } + } + } } #[test] @@ -103,38 +144,78 @@ mod tests { } #[test] - fn every_palette_meets_the_contrast_targets() { + fn unknown_and_removed_base_ids_fall_back_to_the_default() { + assert_eq!(resolve_base("ink").id, "ink"); + assert_eq!(resolve_base("removed-base").id, BASE_DEFAULT); + assert_eq!(resolve_base("").id, BASE_DEFAULT); + assert!(is_offered_base("mist")); + assert!(!is_offered_base("removed-base")); + } + + #[test] + fn every_accent_keeps_its_own_text_readable() { for p in PALETTES { - let themes = [ - ("light", &p.light, LIGHT_BG, LIGHT_SURFACE), - ("dark", &p.dark, DARK_BG, DARK_SURFACE), - ]; - for (theme, t, bg, surface) in themes { - let check = |what: &str, ratio: f64, min: f64| { - assert!(ratio >= min, "{} {theme} {what}: {ratio:.2} < {min}", p.id); - }; - check( - "accent_text on accent", - contrast(t.accent_text, t.accent), - 4.5, - ); - check("accent_ink on bg", contrast(t.accent_ink, bg), 4.5); - check( - "accent_ink on surface", - contrast(t.accent_ink, surface), - 4.5, - ); - check( - "accent_ink on accent_soft", - contrast(t.accent_ink, t.accent_soft), - 4.5, - ); + let check = |what: &str, ratio: f64, min: f64| { + assert!(ratio >= min, "{} {what}: {ratio:.2} < {min}", p.id); + }; + check( + "accent_text on accent (light)", + contrast(p.light.accent_text, p.light.accent), + 4.5, + ); + check( + "accent_text on accent (dark)", + contrast(p.dark.accent_text, p.dark.accent), + 4.5, + ); + for t in [&p.light, &p.dark] { check( "public_text on public_bg", contrast(t.public_text, t.public_bg), 4.5, ); - check("focus on bg", contrast(t.focus, bg), 3.0); + } + } + } + + #[test] + fn every_base_with_every_accent_meets_the_contrast_targets() { + for base in BASES { + for p in PALETTES { + let themes = [ + ("light", &base.light, &p.light), + ("dark", &base.dark, &p.dark), + ]; + for (theme, b, t) in themes { + let who = format!("{} with {} ({theme})", base.id, p.id); + let check = |what: &str, ratio: f64, min: f64| { + assert!(ratio >= min, "{who} {what}: {ratio:.2} < {min}"); + }; + check("text on bg", contrast(b.text, b.bg), 7.0); + check("text on surface", contrast(b.text, b.surface), 7.0); + check("text_2 on bg", contrast(b.text_2, b.bg), 4.5); + check("text_2 on surface", contrast(b.text_2, b.surface), 4.5); + check("muted on bg", contrast(b.muted, b.bg), 4.5); + check("muted on surface", contrast(b.muted, b.surface), 4.5); + check("ln_text on code_bg", contrast(b.ln_text, b.code_bg), 4.5); + check( + "private_text on private_bg", + contrast(b.private_text, b.private_bg), + 4.5, + ); + check("accent_ink on bg", contrast(t.accent_ink, b.bg), 4.5); + check( + "accent_ink on surface", + contrast(t.accent_ink, b.surface), + 4.5, + ); + check( + "accent_ink on accent_soft", + contrast(t.accent_ink, t.accent_soft), + 4.5, + ); + check("focus on bg", contrast(t.focus, b.bg), 3.0); + } } } } diff --git a/crates/forge-web/src/accent_palette.rs b/crates/forge-web/src/accent_palette.rs index 924ad57..3b42136 100644 --- a/crates/forge-web/src/accent_palette.rs +++ b/crates/forge-web/src/accent_palette.rs @@ -336,3 +336,255 @@ pub const PALETTES: &[Palette] = &[ }, }, ]; + +/// The neutral colour tokens one base sets in one theme. The values are CSS colours; +/// `BASE_TOKEN_VARS` names the custom property each field becomes. +pub struct BaseTokens { + pub bg: &'static str, + pub surface: &'static str, + pub surface_2: &'static str, + pub text: &'static str, + pub text_2: &'static str, + pub muted: &'static str, + pub border: &'static str, + pub border_strong: &'static str, + pub code_bg: &'static str, + pub private_bg: &'static str, + pub private_text: &'static str, + pub ln_text: &'static str, +} + +/// One base: the neutral backgrounds, surfaces and text. Its id is the stored value and the +/// attribute value, and the tokens are used in light and dark themes. +pub struct Base { + pub id: &'static str, + pub light: BaseTokens, + pub dark: BaseTokens, +} + +/// The base used when none is stored, and for anonymous visitors. It must be `BASES[0]`. +pub const BASE_DEFAULT: &str = "fern"; + +/// One base token: the custom property it becomes and the field of `BaseTokens` that holds its +/// value. +pub struct BaseTokenVar { + pub name: &'static str, + pub value: fn(&BaseTokens) -> &'static str, +} + +/// Every neutral token a base sets. The stylesheet keeps no copy of these. +pub const BASE_TOKEN_VARS: &[BaseTokenVar] = &[ + BaseTokenVar { + name: "--bg", + value: |t| t.bg, + }, + BaseTokenVar { + name: "--surface", + value: |t| t.surface, + }, + BaseTokenVar { + name: "--surface-2", + value: |t| t.surface_2, + }, + BaseTokenVar { + name: "--text", + value: |t| t.text, + }, + BaseTokenVar { + name: "--text-2", + value: |t| t.text_2, + }, + BaseTokenVar { + name: "--muted", + value: |t| t.muted, + }, + BaseTokenVar { + name: "--border", + value: |t| t.border, + }, + BaseTokenVar { + name: "--border-strong", + value: |t| t.border_strong, + }, + BaseTokenVar { + name: "--code-bg", + value: |t| t.code_bg, + }, + BaseTokenVar { + name: "--private-bg", + value: |t| t.private_bg, + }, + BaseTokenVar { + name: "--private-text", + value: |t| t.private_text, + }, + BaseTokenVar { + name: "--ln-text", + value: |t| t.ln_text, + }, +]; + +/// Every base on offer, in the order the picker lists them. `fern` is the original forge +/// neutral set. +pub const BASES: &[Base] = &[ + // Fern: the original forge neutrals, green-tinted. + Base { + id: "fern", + light: BaseTokens { + bg: "#F6F8F5", + surface: "#FFFFFF", + surface_2: "#EEF2EC", + text: "#1E2420", + text_2: "#3A433D", + muted: "#69736B", + border: "#DDE3DB", + border_strong: "#C5CFC3", + code_bg: "#EEF2EC", + private_bg: "#EEF2EC", + private_text: "#3A433D", + ln_text: "#646D65", + }, + dark: BaseTokens { + bg: "#121613", + surface: "#191E1A", + surface_2: "#1F261F", + text: "#E3E8E2", + text_2: "#C4CCC3", + muted: "#97A198", + border: "#2A322C", + border_strong: "#3A443C", + code_bg: "#1F261F", + private_bg: "#1F261F", + private_text: "#C4CCC3", + ln_text: "#97A198", + }, + }, + // Stone: pure neutral grey. + Base { + id: "stone", + light: BaseTokens { + bg: "#F5F5F4", + surface: "#FFFFFF", + surface_2: "#EDEDEB", + text: "#1C1C1B", + text_2: "#3D3D3B", + muted: "#6B6B68", + border: "#DEDEDB", + border_strong: "#C6C6C2", + code_bg: "#EDEDEB", + private_bg: "#EDEDEB", + private_text: "#3D3D3B", + ln_text: "#6B6B68", + }, + dark: BaseTokens { + bg: "#131313", + surface: "#1A1A1A", + surface_2: "#212121", + text: "#E6E6E4", + text_2: "#C7C7C4", + muted: "#9A9A96", + border: "#2C2C2B", + border_strong: "#3C3C3A", + code_bg: "#212121", + private_bg: "#212121", + private_text: "#C7C7C4", + ln_text: "#9A9A96", + }, + }, + // Sand: warm paper and warm ink. + Base { + id: "sand", + light: BaseTokens { + bg: "#F8F5EF", + surface: "#FFFDF9", + surface_2: "#F0EBE1", + text: "#2A2620", + text_2: "#4A443B", + muted: "#716A5E", + border: "#E2DBCF", + border_strong: "#CBC2B3", + code_bg: "#F0EBE1", + private_bg: "#F0EBE1", + private_text: "#4A443B", + ln_text: "#6B6457", + }, + dark: BaseTokens { + bg: "#171511", + surface: "#1E1B16", + surface_2: "#26221C", + text: "#E9E4DA", + text_2: "#CBC5B9", + muted: "#A29B8D", + border: "#342F27", + border_strong: "#463F35", + code_bg: "#26221C", + private_bg: "#26221C", + private_text: "#CBC5B9", + ln_text: "#A29B8D", + }, + }, + // Mist: cool blue-grey. + Base { + id: "mist", + light: BaseTokens { + bg: "#F3F6F9", + surface: "#FFFFFF", + surface_2: "#E9EEF3", + text: "#1B2430", + text_2: "#384352", + muted: "#66717F", + border: "#D9E0E8", + border_strong: "#C2CCD8", + code_bg: "#E9EEF3", + private_bg: "#E9EEF3", + private_text: "#384352", + ln_text: "#5E6977", + }, + dark: BaseTokens { + bg: "#11161C", + surface: "#182029", + surface_2: "#1E2834", + text: "#E2E8EF", + text_2: "#C3CCD7", + muted: "#949FAD", + border: "#28323E", + border_strong: "#37424F", + code_bg: "#1E2834", + private_bg: "#1E2834", + private_text: "#C3CCD7", + ln_text: "#949FAD", + }, + }, + // 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", + }, + }, +]; diff --git a/crates/forge-web/src/i18n/accents.rs b/crates/forge-web/src/i18n/accents.rs index edb0ace..24f81c9 100644 --- a/crates/forge-web/src/i18n/accents.rs +++ b/crates/forge-web/src/i18n/accents.rs @@ -1,5 +1,5 @@ -//! Names of the accent colours on the appearance page, keyed by palette id. Adding a palette -//! without a name here fails `every_palette_has_a_name`. +//! Names of the accent colours and the backgrounds on the appearance page, keyed by id. Adding a +//! palette or a base without a name here fails `every_palette_has_a_name` or `every_base_has_a_name`. use super::Lang; @@ -23,6 +23,24 @@ pub fn accent_name(lang: Lang, id: &str) -> &'static str { } } +/// The display name of a base (the neutral background set). An id with no name returns an empty +/// string, which the test rules out for every offered base. +pub fn base_name(lang: Lang, id: &str) -> &'static str { + match (id, lang) { + ("fern", Lang::En) => "Fern", + ("fern", Lang::Tr) => "Eğrelti", + ("stone", Lang::En) => "Stone", + ("stone", Lang::Tr) => "Taş", + ("sand", Lang::En) => "Sand", + ("sand", Lang::Tr) => "Kum", + ("mist", Lang::En) => "Mist", + ("mist", Lang::Tr) => "Sis", + ("ink", Lang::En) => "Ink", + ("ink", Lang::Tr) => "Mürekkep", + _ => "", + } +} + #[cfg(test)] mod tests { use super::*; @@ -36,4 +54,13 @@ mod tests { } } } + + #[test] + fn every_base_has_a_name() { + for id in accent::base_ids() { + for lang in [Lang::En, Lang::Tr] { + assert!(!base_name(lang, id).is_empty(), "{id} has no name"); + } + } + } } diff --git a/crates/forge-web/src/i18n/misc.rs b/crates/forge-web/src/i18n/misc.rs index c3e38a7..4ce0e24 100644 --- a/crates/forge-web/src/i18n/misc.rs +++ b/crates/forge-web/src/i18n/misc.rs @@ -14,7 +14,6 @@ pub enum K { Appearance, ThemeLabel, LanguageLabel, - ThemeAndLanguage, MatchSystemHelp, MatchSystem, Light, @@ -24,12 +23,14 @@ pub enum K { SwitchToLight, SwitchToDark, SwitchToMatchSystem, - AppearanceSaved, ChooseTheme, ChooseLanguage, AccentLabel, - AccentHelp, ChooseAccent, + LightColours, + DarkColours, + BackgroundLabel, + ChooseBase, // Notifications: row kinds. KindOpenIssue, KindClosedIssue, @@ -156,7 +157,6 @@ const ALL: &[K] = &[ K::Appearance, K::ThemeLabel, K::LanguageLabel, - K::ThemeAndLanguage, K::MatchSystemHelp, K::MatchSystem, K::Light, @@ -165,12 +165,14 @@ const ALL: &[K] = &[ K::SwitchToLight, K::SwitchToDark, K::SwitchToMatchSystem, - K::AppearanceSaved, K::ChooseTheme, K::ChooseLanguage, K::AccentLabel, - K::AccentHelp, K::ChooseAccent, + K::LightColours, + K::DarkColours, + K::BackgroundLabel, + K::ChooseBase, K::KindOpenIssue, K::KindClosedIssue, K::KindOpenPull, @@ -289,8 +291,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (ThemeLabel, Tr) => "Tema", (LanguageLabel, En) => "Language", (LanguageLabel, Tr) => "Dil", - (ThemeAndLanguage, En) => "Theme and language", - (ThemeAndLanguage, Tr) => "Tema ve dil", (MatchSystemHelp, En) => { "Match the system follows your operating system's light or dark setting." } @@ -311,18 +311,22 @@ pub fn t(lang: Lang, key: K) -> &'static str { (SwitchToDark, Tr) => "Koyu temaya geç", (SwitchToMatchSystem, En) => "Switch to match the system", (SwitchToMatchSystem, Tr) => "Sistem ile eşleştir moduna geç", - (AppearanceSaved, En) => "Appearance saved.", - (AppearanceSaved, Tr) => "Görünüm kaydedildi.", (ChooseTheme, En) => "Choose a theme from the list.", (ChooseTheme, Tr) => "Listeden bir tema seçin.", (ChooseLanguage, En) => "Choose a language from the list.", (ChooseLanguage, Tr) => "Listeden bir dil seçin.", (AccentLabel, En) => "Accent colour", (AccentLabel, Tr) => "Vurgu rengi", - (AccentHelp, En) => "Used for buttons, links and the activity heatmap.", - (AccentHelp, Tr) => "Düğmeler, bağlantılar ve etkinlik ısı haritası için kullanılır.", (ChooseAccent, En) => "Choose an accent colour from the list.", (ChooseAccent, Tr) => "Listeden bir vurgu rengi seçin.", + (LightColours, En) => "Light theme", + (LightColours, Tr) => "Açık tema", + (DarkColours, En) => "Dark theme", + (DarkColours, Tr) => "Koyu tema", + (BackgroundLabel, En) => "Background", + (BackgroundLabel, Tr) => "Arka plan", + (ChooseBase, En) => "Choose a background from the list.", + (ChooseBase, Tr) => "Listeden bir arka plan seçin.", (KindOpenIssue, En) => "Open issue", (KindOpenIssue, Tr) => "Açık sorun", (KindClosedIssue, En) => "Closed issue", diff --git a/crates/forge-web/src/pages/settings_appearance.rs b/crates/forge-web/src/pages/settings_appearance.rs index 8b4a2a1..5a2323f 100644 --- a/crates/forge-web/src/pages/settings_appearance.rs +++ b/crates/forge-web/src/pages/settings_appearance.rs @@ -1,6 +1,7 @@ -//! Page: appearance (`/settings/appearance`). The colour theme, the accent colour and the language, -//! all stored per user. Anonymous visitors set the theme from the footer instead (see `pages/theme_cookie.rs`). -//! Every POST checks the CSRF token first. +//! Page: appearance (`/settings/appearance`). The colour theme, the language, and for each of the +//! light and dark themes a background and an accent colour, all stored per user. Every change +//! saves at once, so the form has no Save button. Anonymous visitors set the theme from the footer +//! instead (see `pages/theme_cookie.rs`). Every POST checks the CSRF token first. use forge_core::AuditAction; use forge_core::store::ui_prefs::THEMES; @@ -10,15 +11,15 @@ use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, see_other}; -use topcoat::router::{page, query_params, route}; +use topcoat::router::{page, route}; use topcoat::view::{View, component, view}; use crate::accent; use crate::audit::{self, Actor, Target}; use crate::auth::{require_csrf, require_user}; -use crate::i18n::accents::accent_name; +use crate::i18n::accents::{accent_name, base_name}; use crate::i18n::misc::{self as g, K}; -use crate::i18n::{self, Key, Lang}; +use crate::i18n::{self, Lang}; use crate::state::AppState; use crate::views::shell; @@ -29,11 +30,6 @@ pub const LANGUAGE_CODES: &[&str] = &["auto", "en", "tr"]; /// Theme codes, in display order. const THEME_CODES: &[&str] = &["auto", "light", "dark"]; -#[query_params(error = bad_request)] -struct AppearanceQuery { - saved: Option, -} - /// Reads a field that is present as a string, even an empty one. The plain `Option` /// reading would turn an empty value into `None`, which is the same as a missing field. fn present_string<'de, D: Deserializer<'de>>( @@ -48,12 +44,19 @@ struct AppearanceForm { csrf: String, #[serde(default)] theme: String, - /// Optional so a form loaded before the accent picker existed still saves. When absent, - /// the stored accent is kept. A present but empty value stays `Some("")` and is rejected. - #[serde(default, deserialize_with = "present_string")] - accent: Option, #[serde(default)] language: String, + /// The four colour fields are optional so a form loaded before a field existed still saves. + /// When a field is absent, its stored value is kept. A present but empty or unknown value + /// stays `Some("")` or an unknown id, and is rejected. + #[serde(default, deserialize_with = "present_string")] + accent_light: Option, + #[serde(default, deserialize_with = "present_string")] + accent_dark: Option, + #[serde(default, deserialize_with = "present_string")] + base_light: Option, + #[serde(default, deserialize_with = "present_string")] + base_dark: Option, } struct Choice { @@ -62,13 +65,24 @@ struct Choice { selected: bool, } +/// The colour choices of one theme: its background and its accent colour. `dark` picks the +/// field names and the swatch attributes that belong to the dark theme. +struct ColourGroup { + dark: bool, + heading: &'static str, + background: &'static str, + accent: &'static str, + bases: Vec, + accents: Vec, +} + struct AppearancePage { lang: Lang, csrf: String, theme: Vec, - accents: Vec, language: Vec, - notice: Option<&'static str>, + light: ColourGroup, + dark: ColourGroup, } /// The label of a language code. The two native names stay as they are in every language. @@ -109,105 +123,177 @@ fn choices( .collect() } +/// One theme's colour choices, with the stored (resolved) background and accent selected. +fn colour_group(lang: Lang, dark: bool, base: &str, accent_id: &str) -> ColourGroup { + let base_codes: Vec<&'static str> = accent::base_ids().collect(); + let accent_codes: Vec<&'static str> = accent::ids().collect(); + ColourGroup { + dark, + heading: g::t( + lang, + if dark { + K::DarkColours + } else { + K::LightColours + }, + ), + background: g::t(lang, K::BackgroundLabel), + accent: g::t(lang, K::AccentLabel), + bases: choices(&base_codes, base, |id| base_name(lang, id)), + accents: choices(&accent_codes, accent_id, |id| accent_name(lang, id)), + } +} + +#[component] +async fn colour_group_fields(group: ColourGroup) -> Result { + let ColourGroup { + dark, + heading, + background, + accent, + bases, + accents, + } = group; + let base_field = if dark { "base_dark" } else { "base_light" }; + let accent_field = if dark { "accent_dark" } else { "accent_light" }; + Ok(view! { +
+ (heading) +
+ (background) +
+ for choice in bases.into_iter() { + + } +
+
+
+ (accent) +
+ for choice in accents.into_iter() { + + } +
+
+
+ }) +} + #[component] async fn appearance_body(page: AppearancePage) -> Result { let AppearancePage { lang, csrf, theme, - accents, language, - notice, + light, + dark, } = page; Ok(view! {

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

- if let Some(message) = notice { -
-

(message)

-
- } -
-

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

-
- + + +
-
- (g::t(lang, K::AccentLabel)) -
- for choice in accents.into_iter() { - - } -
- (g::t(lang, K::AccentHelp)) -
- - -
+
+
+ colour_group_fields(group: light) + colour_group_fields(group: dark) +
+ }) } -/// Rejects a theme, accent or language that is not offered. Nothing is saved for any of them. -fn check_choice( - lang: Lang, - theme: &str, - accent_id: &str, - language: &str, -) -> forge_core::Result<()> { +/// Rejects a theme or a language that is not offered. Nothing is saved for either of them. +fn check_choice(lang: Lang, theme: &str, language: &str) -> forge_core::Result<()> { if !THEMES.contains(&theme) { return Err(CoreError::Invalid(g::t(lang, K::ChooseTheme).into())); } - if !accent::is_offered(accent_id) { - return Err(CoreError::Invalid(g::t(lang, K::ChooseAccent).into())); - } if !LANGUAGE_CODES.contains(&language) { return Err(CoreError::Invalid(g::t(lang, K::ChooseLanguage).into())); } Ok(()) } -fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> { - match saved { - Some("1") => Some(g::t(lang, K::AppearanceSaved)), - _ => None, +/// The accent a save stores for one theme. An absent field keeps the stored id. A present one +/// must be an offered accent, so an empty or unknown value is rejected. +fn accent_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result { + match posted { + None => Ok(stored.to_owned()), + Some(id) if accent::is_offered(id) => Ok(id.to_owned()), + Some(_) => Err(CoreError::Invalid(g::t(lang, K::ChooseAccent).into())), } } -/// Builds the page for a viewer. The theme, accent and language are the stored values. -fn page_for(viewer: &(User, Session), lang: Lang, notice: Option<&'static str>) -> AppearancePage { - let accent_codes: Vec<&'static str> = accent::ids().collect(); +/// The background a save stores for one theme. An absent field keeps the stored id. A present +/// one must be an offered base, so an empty or unknown value is rejected. +fn base_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result { + match posted { + None => Ok(stored.to_owned()), + Some(id) if accent::is_offered_base(id) => Ok(id.to_owned()), + Some(_) => Err(CoreError::Invalid(g::t(lang, K::ChooseBase).into())), + } +} + +/// Builds the page for a viewer. Each choice shows the stored value, or the default when the +/// stored id is no longer offered, which is what the page renders on `` too. +fn page_for(viewer: &(User, Session), lang: Lang) -> AppearancePage { + let user = &viewer.0; AppearancePage { lang, csrf: viewer.1.csrf_token.clone(), - theme: choices(THEME_CODES, &viewer.0.theme, |code| theme_label(lang, code)), - accents: choices(&accent_codes, &viewer.0.accent, |id| accent_name(lang, id)), - language: choices(LANGUAGE_CODES, &viewer.0.language, |code| { + theme: choices(THEME_CODES, &user.theme, |code| theme_label(lang, code)), + language: choices(LANGUAGE_CODES, &user.language, |code| { language_label(lang, code) }), - notice, + light: colour_group( + lang, + false, + accent::resolve_base(&user.base_light).id, + accent::resolve(&user.accent).id, + ), + dark: colour_group( + lang, + true, + accent::resolve_base(&user.base_dark).id, + accent::resolve(&user.accent_dark).id, + ), } } @@ -215,8 +301,7 @@ fn page_for(viewer: &(User, Session), lang: Lang, notice: Option<&'static str>) async fn appearance_page(cx: &Cx) -> Result { let viewer = require_user(cx).await?; let lang = i18n::lang(cx, Some(&viewer.0)); - let saved = query_params::(cx)?.saved.clone(); - let page = page_for(&viewer, lang, notice_for(lang, saved.as_deref())); + let page = page_for(&viewer, lang); Ok(view! { shell(title: g::t(lang, K::Appearance), viewer: Some(&viewer), appearance_body(page: page)) }) @@ -227,29 +312,46 @@ async fn appearance_save(cx: &Cx, Form(form): Form) -> Result(cx).store; + let user = &viewer.0; - let accent = form.accent.as_deref().unwrap_or(&viewer.0.accent); - check_choice(lang, &form.theme, accent, &form.language)?; + check_choice(lang, &form.theme, &form.language)?; + let accent_light = accent_choice(lang, form.accent_light.as_deref(), &user.accent)?; + let accent_dark = accent_choice(lang, form.accent_dark.as_deref(), &user.accent_dark)?; + let base_light = base_choice(lang, form.base_light.as_deref(), &user.base_light)?; + let base_dark = base_choice(lang, form.base_dark.as_deref(), &user.base_dark)?; store - .set_ui_prefs(&viewer.0.id, &form.theme, &form.language) + .set_ui_prefs(&user.id, &form.theme, &form.language) + .await?; + store + .set_colours( + &user.id, + &accent_light, + &accent_dark, + &base_light, + &base_dark, + ) .await?; - if form.accent.is_some() { - store.set_accent(&viewer.0.id, accent).await?; - } audit::record( store, Some(cx), - Actor::User(&viewer.0), + Actor::User(user), AuditAction::UiPrefsChanged, Target { kind: "user", - id: &viewer.0.id, - name: &viewer.0.username, + id: &user.id, + name: &user.username, }, - serde_json::json!({ "theme": form.theme, "accent": accent, "language": form.language }), + serde_json::json!({ + "theme": form.theme, + "language": form.language, + "accent_light": accent_light, + "accent_dark": accent_dark, + "base_light": base_light, + "base_dark": base_dark, + }), ) .await; - Ok(see_other("/settings/appearance?saved=1")) + Ok(see_other("/settings/appearance")) } #[cfg(test)] @@ -258,14 +360,35 @@ mod tests { #[test] fn only_offered_choices_pass() { - assert!(check_choice(Lang::En, "dark", "ocean", "tr").is_ok()); - assert!(check_choice(Lang::Tr, "auto", "sage", "auto").is_ok()); - assert!(check_choice(Lang::En, "neon", "sage", "en").is_err()); - assert!(check_choice(Lang::En, "light", "neon", "en").is_err()); - assert!(check_choice(Lang::En, "light", "Ocean", "en").is_err()); - assert!(check_choice(Lang::En, "light", "", "en").is_err()); - assert!(check_choice(Lang::En, "light", "sage", "de").is_err()); - assert!(check_choice(Lang::Tr, "light", "sage", "").is_err()); + assert!(check_choice(Lang::En, "dark", "tr").is_ok()); + assert!(check_choice(Lang::Tr, "auto", "auto").is_ok()); + assert!(check_choice(Lang::En, "neon", "en").is_err()); + assert!(check_choice(Lang::En, "light", "de").is_err()); + assert!(check_choice(Lang::Tr, "light", "").is_err()); + assert!(accent_choice(Lang::En, Some("ocean"), "sage").is_ok()); + assert!(accent_choice(Lang::En, Some("neon"), "sage").is_err()); + assert!(accent_choice(Lang::En, Some("Ocean"), "sage").is_err()); + assert!(accent_choice(Lang::En, Some(""), "sage").is_err()); + assert!(base_choice(Lang::En, Some("ink"), "fern").is_ok()); + assert!(base_choice(Lang::En, Some("neon"), "fern").is_err()); + assert!(base_choice(Lang::En, Some(""), "fern").is_err()); + } + + #[test] + fn an_absent_colour_keeps_the_stored_value() { + assert_eq!(accent_choice(Lang::En, None, "plum").unwrap(), "plum"); + assert_eq!(base_choice(Lang::En, None, "mist").unwrap(), "mist"); + } + + #[test] + fn a_rejected_colour_says_what_to_choose() { + let accent_err = accent_choice(Lang::En, Some("neon"), "sage").unwrap_err(); + assert!( + accent_err.to_string().contains("accent colour"), + "{accent_err}" + ); + let base_err = base_choice(Lang::En, Some("neon"), "fern").unwrap_err(); + assert!(base_err.to_string().contains("background"), "{base_err}"); } #[test] @@ -280,7 +403,7 @@ mod tests { } #[test] - fn the_stored_accent_is_selected() { + fn the_stored_accent_and_base_are_selected() { let codes: Vec<&'static str> = accent::ids().collect(); let options = choices(&codes, "plum", |id| accent_name(Lang::En, id)); let selected: Vec<&str> = options @@ -290,12 +413,23 @@ mod tests { .collect(); assert_eq!(selected, ["plum"]); assert_eq!(options[0].value, crate::accent_palette::DEFAULT); + + let group = colour_group(Lang::En, true, "ink", "plum"); + let bases: Vec<&str> = group + .bases + .iter() + .filter(|c| c.selected) + .map(|c| c.value) + .collect(); + assert_eq!(bases, ["ink"]); + assert_eq!(group.bases[0].value, crate::accent_palette::BASE_DEFAULT); } #[test] fn labels_follow_the_page_language() { assert_eq!(theme_label(Lang::En, "dark"), "Dark"); assert_eq!(theme_label(Lang::Tr, "dark"), "Koyu"); + assert_eq!(base_name(Lang::Tr, "ink"), "M\u{fc}rekkep"); } #[test] diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index 4813787..43fb48e 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -161,12 +161,28 @@ pub async fn shell( let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned()); let lang = i18n::lang(__cx, viewer.map(|(user, _)| user)); let theme_attr = crate::theme::data_theme(__cx, viewer.map(|(user, _)| user)); - // Always set, sage included, so a page never keeps the accent of the one before it. - let stored_accent = match viewer { - Some((user, _)) => user.accent.as_str(), - None => crate::accent_palette::DEFAULT, - }; - let accent_id = crate::accent::resolve(stored_accent).id; + // Always set, defaults included, so a page never keeps the colours of the one before it. + // Each of the four choices is resolved on its own, so an id that is no longer offered falls + // back to its default. + let (stored_accent_light, stored_accent_dark, stored_base_light, stored_base_dark) = + match viewer { + Some((user, _)) => ( + user.accent.as_str(), + user.accent_dark.as_str(), + user.base_light.as_str(), + user.base_dark.as_str(), + ), + None => ( + crate::accent_palette::DEFAULT, + crate::accent_palette::DEFAULT, + crate::accent_palette::BASE_DEFAULT, + crate::accent_palette::BASE_DEFAULT, + ), + }; + let accent_light_id = crate::accent::resolve(stored_accent_light).id; + let accent_dark_id = crate::accent::resolve(stored_accent_dark).id; + let base_light_id = crate::accent::resolve_base(stored_base_light).id; + let base_dark_id = crate::accent::resolve_base(stored_base_dark).id; // The stored preference, "auto" included, drives the button: its icon, its label and the // value it posts (the next preference in the cycle auto, light, dark). let theme_pref = crate::theme::preference(__cx, viewer.map(|(user, _)| user)); @@ -196,7 +212,7 @@ pub async fn shell( let unread_aside = unread_badge.clone(); Ok(view! { - + @@ -962,8 +978,9 @@ mod shell_tests { &page[at..at + len + 1] } - /// The `` tag of `/settings/sessions` for a signed-in user whose stored accent is `accent`. - async fn html_tag_for_accent(accent: &str) -> String { + /// The `` tag of `/settings/sessions` for a signed-in user whose stored colours are the + /// four ids given, in the order light accent, dark accent, light base, dark base. + async fn html_tag_for_colours(colours: [&str; 4]) -> String { use crate::auth::SESSION_COOKIE; let dir = tempfile::tempdir().expect("tempdir"); let state = crate::test_support::test_state(dir.path()).await; @@ -973,12 +990,16 @@ mod shell_tests { .create_user("tahinli", None, "x", false) .await .expect("user"); - store.set_accent(&user.id, accent).await.expect("accent"); - crate::test_support::create_session(&store, &user.id, "accent-token", "accent-csrf").await; + let [accent_light, accent_dark, base_light, base_dark] = colours; + store + .set_colours(&user.id, accent_light, accent_dark, base_light, base_dark) + .await + .expect("colours"); + crate::test_support::create_session(&store, &user.id, "colour-token", "colour-csrf").await; let req = Request::builder() .method("GET") .uri("/settings/sessions") - .header("cookie", format!("__Host-{SESSION_COOKIE}=accent-token")) + .header("cookie", format!("__Host-{SESSION_COOKIE}=colour-token")) .body(Body::empty()) .unwrap(); let res = router.handle(req).await; @@ -988,18 +1009,23 @@ mod shell_tests { } #[tokio::test] - async fn the_html_tag_carries_the_viewers_accent() { - let ocean = html_tag_for_accent("ocean").await; - assert!(ocean.contains("data-accent=\"ocean\""), "{ocean}"); - let sage = html_tag_for_accent("sage").await; - assert!(sage.contains("data-accent=\"sage\""), "{sage}"); - // A stored id that is no longer offered falls back to the default, never to nothing. - let removed = html_tag_for_accent("removed-palette").await; - assert!(removed.contains("data-accent=\"sage\""), "{removed}"); + async fn the_html_tag_carries_the_viewers_colours() { + let tag = html_tag_for_colours(["ocean", "plum", "ink", "mist"]).await; + assert!(tag.contains("data-accent-light=\"ocean\""), "{tag}"); + assert!(tag.contains("data-accent-dark=\"plum\""), "{tag}"); + assert!(tag.contains("data-base-light=\"ink\""), "{tag}"); + assert!(tag.contains("data-base-dark=\"mist\""), "{tag}"); + assert!(!tag.contains("data-accent="), "{tag}"); + // Stored ids that are no longer offered fall back to the defaults, never to nothing. + let removed = html_tag_for_colours(["removed-palette", "removed-palette", "x", "x"]).await; + assert!(removed.contains("data-accent-light=\"sage\""), "{removed}"); + assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}"); + assert!(removed.contains("data-base-light=\"fern\""), "{removed}"); + assert!(removed.contains("data-base-dark=\"fern\""), "{removed}"); } #[tokio::test] - async fn anonymous_pages_render_the_default_accent() { + async fn anonymous_pages_render_the_default_colours() { let dir = tempfile::tempdir().expect("tempdir"); let state = crate::test_support::test_state(dir.path()).await; let router = crate::test_support::app_router(state); @@ -1012,6 +1038,9 @@ mod shell_tests { let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); let html = String::from_utf8_lossy(&bytes); let tag = html_tag(&html); - assert!(tag.contains("data-accent=\"sage\""), "{tag}"); + assert!(tag.contains("data-accent-light=\"sage\""), "{tag}"); + assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}"); + assert!(tag.contains("data-base-light=\"fern\""), "{tag}"); + assert!(tag.contains("data-base-dark=\"fern\""), "{tag}"); } } diff --git a/crates/forge-web/tests/ui_prefs_e2e.rs b/crates/forge-web/tests/ui_prefs_e2e.rs index ff22014..781bb5b 100644 --- a/crates/forge-web/tests/ui_prefs_e2e.rs +++ b/crates/forge-web/tests/ui_prefs_e2e.rs @@ -110,10 +110,31 @@ fn html_theme(body: &str) -> Option { doc.root_element().attr("data-theme").map(str::to_owned) } -/// The `data-accent` attribute of ``. -fn html_accent(body: &str) -> Option { +/// The value of attribute `name` on ``, if the page sets it. +fn html_attr(body: &str, name: &str) -> Option { let doc = scraper::Html::parse_document(body); - doc.root_element().attr("data-accent").map(str::to_owned) + doc.root_element().attr(name).map(str::to_owned) +} + +/// The four colour attributes of ``, in the order light accent, dark accent, light base, +/// dark base. +fn html_colours(body: &str) -> [Option; 4] { + [ + html_attr(body, "data-accent-light"), + html_attr(body, "data-accent-dark"), + html_attr(body, "data-base-light"), + html_attr(body, "data-base-dark"), + ] +} + +/// The checked radio of each colour group, in the same order as `html_colours`. +fn checked_colours(body: &str) -> [Option; 4] { + [ + checked_radio(body, "accent_light"), + checked_radio(body, "accent_dark"), + checked_radio(body, "base_light"), + checked_radio(body, "base_dark"), + ] } /// The value of the checked radio button in the group `name` on a page. @@ -246,25 +267,18 @@ async fn appearance_setting_persists_and_renders_the_html_attribute() { .http .post_form( "/settings/appearance", - &[ - ("csrf", &csrf), - ("theme", "dark"), - ("accent", "sage"), - ("language", "tr"), - ], + &[("csrf", &csrf), ("theme", "dark"), ("language", "tr")], Some(&session), ) .await; assert_eq!(saved.status, 303, "save: {}", saved.body); assert_eq!( saved.header(reqwest::header::LOCATION).as_deref(), - Some("/settings/appearance?saved=1") + Some("/settings/appearance"), + "a save redirects back with no saved notice" ); - let page = env - .http - .get("/settings/appearance?saved=1", Some(&session)) - .await; + let page = env.http.get("/settings/appearance", Some(&session)).await; assert_eq!( selected_option(&page.body, "theme").as_deref(), Some("dark") @@ -273,29 +287,48 @@ async fn appearance_setting_persists_and_renders_the_html_attribute() { selected_option(&page.body, "language").as_deref(), Some("tr") ); + assert_eq!(html_theme(&page.body).as_deref(), Some("dark")); +} - let home = env.http.get("/settings/appearance", Some(&session)).await; - assert_eq!(html_theme(&home.body).as_deref(), Some("dark")); - +#[tokio::test] +async fn the_form_has_no_save_button_and_every_field_autosubmits() { + let env = start().await; + let session = login(&env.http, "tahinli").await; let page = env.http.get("/settings/appearance", Some(&session)).await; - assert_eq!( - selected_option(&page.body, "theme").as_deref(), - Some("dark") - ); - assert_eq!( - selected_option(&page.body, "language").as_deref(), - Some("tr") - ); + let doc = scraper::Html::parse_document(&page.body); + + let form = scraper::Selector::parse("form[data-appearance]").expect("selector"); + assert_eq!(doc.select(&form).count(), 1, "one appearance form"); + let buttons = scraper::Selector::parse("form[data-appearance] button").expect("selector"); + assert_eq!(doc.select(&buttons).count(), 0, "no Save button"); + let submits = + scraper::Selector::parse("form[data-appearance] input[type=\"submit\"]").expect("selector"); + assert_eq!(doc.select(&submits).count(), 0, "no submit input"); + + let fields = + scraper::Selector::parse("form[data-appearance] input, form[data-appearance] select") + .expect("selector"); + for field in doc.select(&fields) { + if field.value().attr("type") == Some("hidden") { + continue; + } + assert!( + field.value().attr("data-autosubmit").is_some(), + "{:?} does not autosubmit", + field.value().attr("name") + ); + } } #[tokio::test] -async fn accent_setting_persists_and_renders_the_html_attribute() { +async fn light_and_dark_colours_save_independently_and_render_on_html() { let env = start().await; let session = login(&env.http, "tahinli").await; let page = env.http.get("/settings/appearance", Some(&session)).await; - assert_eq!(checked_radio(&page.body, "accent").as_deref(), Some("sage")); - assert_eq!(html_accent(&page.body).as_deref(), Some("sage")); + let defaults = ["sage", "sage", "fern", "fern"].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"); let saved = env @@ -305,8 +338,11 @@ async fn accent_setting_persists_and_renders_the_html_attribute() { &[ ("csrf", &csrf), ("theme", "light"), - ("accent", "ocean"), ("language", "en"), + ("accent_light", "ocean"), + ("accent_dark", "plum"), + ("base_light", "ink"), + ("base_dark", "mist"), ], Some(&session), ) @@ -314,43 +350,85 @@ async fn accent_setting_persists_and_renders_the_html_attribute() { assert_eq!(saved.status, 303, "save: {}", saved.body); let page = env.http.get("/settings/appearance", Some(&session)).await; - assert_eq!( - checked_radio(&page.body, "accent").as_deref(), - Some("ocean") - ); - assert_eq!(html_accent(&page.body).as_deref(), Some("ocean")); + let chosen = ["ocean", "plum", "ink", "mist"].map(str::to_owned); + assert_eq!(checked_colours(&page.body), chosen.clone().map(Some)); + assert_eq!(html_colours(&page.body), chosen.map(Some)); + + // A single field changes on its own; the other three keep their values. + let saved = env + .http + .post_form( + "/settings/appearance", + &[ + ("csrf", &csrf), + ("theme", "light"), + ("language", "en"), + ("base_dark", "sand"), + ], + 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", "sand"].map(str::to_owned); + assert_eq!(checked_colours(&page.body), chosen.clone().map(Some)); + assert_eq!(html_colours(&page.body), chosen.map(Some)); // Malformed or unknown ids change nothing. - for accent in ["Ocean", "../x", "neon", ""] { + for (field, bad) in [ + ("accent_light", "Ocean"), + ("accent_dark", "../x"), + ("accent_dark", "neon"), + ("accent_light", ""), + ("base_light", "neon"), + ("base_dark", ""), + ] { let form = [ ("csrf", csrf.as_str()), ("theme", "light"), ("language", "en"), - ("accent", accent), + (field, bad), ]; let res = env .http .post_form("/settings/appearance", &form, Some(&session)) .await; - assert_ne!(res.status, 303, "bad accent {accent:?} must not save"); + assert_ne!(res.status, 303, "bad {field} {bad:?} must not save"); } let page = env.http.get("/settings/appearance", Some(&session)).await; - assert_eq!( - checked_radio(&page.body, "accent").as_deref(), - Some("ocean") - ); - assert_eq!(html_accent(&page.body).as_deref(), Some("ocean")); + let chosen = ["ocean", "plum", "ink", "sand"].map(str::to_owned); + assert_eq!(checked_colours(&page.body), chosen.clone().map(Some)); + assert_eq!(html_colours(&page.body), chosen.map(Some)); } #[tokio::test] -async fn appearance_save_without_accent_keeps_the_stored_accent() { +async fn a_save_without_colour_fields_keeps_the_stored_colours() { let env = start().await; let session = login(&env.http, "tahinli").await; let page = env.http.get("/settings/appearance", Some(&session)).await; let csrf = input_value(&page.body, "csrf"); - let before = checked_radio(&page.body, "accent"); - assert!(before.is_some(), "an accent is always selected"); + let saved = env + .http + .post_form( + "/settings/appearance", + &[ + ("csrf", &csrf), + ("theme", "light"), + ("language", "en"), + ("accent_light", "rose"), + ("accent_dark", "slate"), + ("base_light", "sand"), + ("base_dark", "stone"), + ], + Some(&session), + ) + .await; + assert_eq!(saved.status, 303, "save: {}", saved.body); + let before = env.http.get("/settings/appearance", Some(&session)).await; + let stored = ["rose", "slate", "sand", "stone"].map(str::to_owned); + assert_eq!(html_colours(&before.body), stored.clone().map(Some)); + let saved = env .http .post_form( @@ -359,15 +437,15 @@ async fn appearance_save_without_accent_keeps_the_stored_accent() { Some(&session), ) .await; - assert_eq!(saved.status, 303, "save without accent: {}", saved.body); + assert_eq!(saved.status, 303, "save without colours: {}", saved.body); let page = env.http.get("/settings/appearance", Some(&session)).await; assert_eq!( selected_option(&page.body, "theme").as_deref(), Some("dark") ); - assert_eq!(checked_radio(&page.body, "accent"), before); - assert_eq!(html_accent(&page.body), before); + assert_eq!(checked_colours(&page.body), stored.clone().map(Some)); + assert_eq!(html_colours(&page.body), stored.map(Some)); } #[tokio::test] @@ -505,7 +583,7 @@ async fn signed_in_toggle_saves_the_preference_and_returns_to_back() { &[ ("csrf", &csrf), ("theme", "auto"), - ("accent", "sage"), + ("accent_light", "sage"), ("language", "tr"), ], Some(&session), diff --git a/style/main.scss b/style/main.scss index f3c8c69..50708aa 100644 --- a/style/main.scss +++ b/style/main.scss @@ -60,19 +60,13 @@ } // Accent tokens (light and dark) are generated into _accents.scss from src/accent_palette.rs. -// They are imported here so they keep their place in the cascade; the neutral tokens follow. +// They are imported here so they keep their place in the cascade; the other tokens follow. @import "accents"; -// The neutral dark values are repeated in the two dark blocks below and must stay identical. +// The neutral tokens (--bg, --surface, --text and so on) are not here: they come from the +// generated _accents.scss, one block per base in src/accent_palette.rs. Only the tokens that are +// the same for every base stay below. :root { - --bg: #F6F8F5; - --surface: #FFFFFF; - --surface-2: #EEF2EC; - --text: #1E2420; - --text-2: #3A433D; - --muted: #69736B; - --border: #DDE3DB; - --border-strong: #C5CFC3; --ok: #1D7A62; --warn: #9A6200; --bad: #B0413A; @@ -81,16 +75,12 @@ --danger-bg: #F8E1DE; --alert-bg: #F8E1DE; --alert-text: #7D2B25; - --code-bg: #EEF2EC; - --private-bg: #EEF2EC; - --private-text: #3A433D; --add-bg: #DCF2EA; --add-text: #174D3F; --add-mark: #1D7A62; --del-bg: #F8E1DE; --del-text: #7D2B25; --del-mark: #B0413A; - --ln-text: #69736B; --row-target: #FFF4C2; --tip: #1D7A62; --important: #6A4BB0; @@ -102,20 +92,12 @@ --topbar-h: 52px; --sidebar-w: 232px; color-scheme: light; - // Native checkboxes, radios and progress bars pick up the sage accent in every browser. + // Native checkboxes, radios and progress bars pick up the chosen accent in every browser. accent-color: var(--accent); } @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { - --bg: #121613; - --surface: #191E1A; - --surface-2: #1F261F; - --text: #E3E8E2; - --text-2: #C4CCC3; - --muted: #97A198; - --border: #2A322C; - --border-strong: #3A443C; --ok: #7CCBAE; --warn: #E6B765; --bad: #F09A90; @@ -124,16 +106,12 @@ --danger-bg: #3A1E1C; --alert-bg: #3A1E1C; --alert-text: #F2B8B0; - --code-bg: #1F261F; - --private-bg: #1F261F; - --private-text: #C4CCC3; --add-bg: #143029; --add-text: #A6E3CF; --add-mark: #7CCBAE; --del-bg: #3A1E1C; --del-text: #F2B8B0; --del-mark: #F09A90; - --ln-text: #97A198; --row-target: #3A3510; --tip: #7CCBAE; --important: #C4A7FF; @@ -148,14 +126,6 @@ } :root[data-theme="dark"] { - --bg: #121613; - --surface: #191E1A; - --surface-2: #1F261F; - --text: #E3E8E2; - --text-2: #C4CCC3; - --muted: #97A198; - --border: #2A322C; - --border-strong: #3A443C; --ok: #7CCBAE; --warn: #E6B765; --bad: #F09A90; @@ -164,16 +134,12 @@ --danger-bg: #3A1E1C; --alert-bg: #3A1E1C; --alert-text: #F2B8B0; - --code-bg: #1F261F; - --private-bg: #1F261F; - --private-text: #C4CCC3; --add-bg: #143029; --add-text: #A6E3CF; --add-mark: #7CCBAE; --del-bg: #3A1E1C; --del-text: #F2B8B0; --del-mark: #F09A90; - --ln-text: #97A198; --row-target: #3A3510; --tip: #7CCBAE; --important: #C4A7FF; @@ -1857,12 +1823,55 @@ code { max-width: 24rem; } -// Accent picker (appearance settings). Each choice is a native radio, so the keyboard and screen +// Colour pickers (appearance settings). Each choice is a native radio, so the keyboard and screen // readers work as usual; the swatch beside it shows the colour. The swatch colours come from the -// generated _accents.scss, so nothing here names a colour. -.accent-picker { +// generated _accents.scss, so nothing here names a colour. The two themes sit side by side, and +// stack on narrow screens, so the whole page fits a laptop window without a long scroll. +.appearance { display: grid; - gap: 8px; + gap: 16px; + min-width: 0; +} + +.appearance-top { + display: flex; + flex-wrap: wrap; + gap: 16px 24px; + + label { + display: grid; + gap: 4px; + min-width: 0; + } +} + +.appearance-columns { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; + min-width: 0; + + @media (max-width: 720px) { + grid-template-columns: minmax(0, 1fr); + } +} + +.colour-group { + display: grid; + gap: 14px; + min-width: 0; + margin: 0; + + legend { + padding: 0; + margin-bottom: 4px; + font-weight: 600; + } +} + +.colour-picker { + display: grid; + gap: 6px; min-width: 0; margin: 0; padding: 0; @@ -1870,18 +1879,19 @@ code { legend { padding: 0; - margin-bottom: 6px; - font-weight: 600; + margin-bottom: 2px; + font-size: 0.875rem; + color: var(--muted); } } -.accent-choices { +.colour-choices { display: flex; flex-wrap: wrap; - gap: 10px 18px; + gap: 8px 14px; } -.accent-choice { +.colour-choice { display: inline-flex; align-items: center; gap: 8px; @@ -1896,17 +1906,20 @@ code { opacity: 0; } - input:focus-visible + .accent-swatch { + input:focus-visible + .accent-swatch, + input:focus-visible + .base-swatch { outline: 2px solid var(--focus); outline-offset: 3px; } - input:checked + .accent-swatch { + input:checked + .accent-swatch, + input:checked + .base-swatch { box-shadow: 0 0 0 2px var(--surface), 0 0 0 4px var(--focus); } } -.accent-swatch { +.accent-swatch, +.base-swatch { display: inline-block; flex: none; width: 28px; @@ -1915,6 +1928,13 @@ code { border: 1px solid var(--border-strong); } +// A background swatch is split light and dark, so a pale one needs its own outline to show on a +// pale page. +.base-swatch { + outline: 1px solid var(--border-strong); + outline-offset: 1px; +} + // branch protection // Settings page: rules table with a Remove form per row, then the add/update form. .branch-rules {