forge
Explore
Log in

Don't you dare go Hollow

Per-theme background and accent colours, instant-save appearance page

Browse files at this commit

9261c0f58e1fceb0d2d51094b1bb0684a41e41e6Ahmet Kaan GümüşParent: 894eaf4
  • feat
    • per-theme background and accent colours, instant-save appearance page
Show full message
✨ feat: per-theme background and accent colours, instant-save appearance page

- Light and dark themes each get their own accent and background set
  (fern, stone, sand, mist, ink); migration 0042 keeps existing looks.
- Appearance page saves every change immediately, with live preview; no Save button.
- Fix soft-nav restoring the first radio of a group (accent jumped back to Sage).

19 changed files +1225 -318

crates/forge-core/migrations/0042_colours.sqladded+12 -0
@@ -0,0 +1,12 @@
1+-- Colour choices per user: the accent and base palettes for the light and the dark theme. The
2+-- ids are those of forge-web's accent_palette.rs, which decides what exists, so there is no
3+-- CHECK list here. Applied by store/migrate.rs.
4+--
5+-- `accent` now means the light-theme accent. The dark accent starts as a copy of it, so an
6+-- existing user sees the same colours in both themes until they choose otherwise.
7+
8+ALTER TABLE users ADD COLUMN accent_dark TEXT NOT NULL DEFAULT 'sage';
9+ALTER TABLE users ADD COLUMN base_light TEXT NOT NULL DEFAULT 'fern';
10+ALTER TABLE users ADD COLUMN base_dark TEXT NOT NULL DEFAULT 'fern';
11+
12+UPDATE users SET accent_dark = accent;
crates/forge-core/src/authz.rsmodified+3 -0
@@ -129,6 +129,9 @@ mod tests {
129129 theme: "auto".into(),
130130 language: "auto".into(),
131131 accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
132+ accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
133+ base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
134+ base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
132135 kind: AccountKind::User,
133136 email_notifications: true,
134137 }
crates/forge-core/src/model.rsmodified+14 -1
@@ -47,8 +47,15 @@ pub struct User {
4747 pub theme: String,
4848 /// Language code, e.g. "en"; "auto" uses the instance default.
4949 pub language: String,
50- /// Accent colour: the id of a palette in forge-web's `accent_palette.rs`. "sage" is the default.
50+ /// Accent colour for the light theme: the id of a palette in forge-web's `accent_palette.rs`.
51+ /// "sage" is the default.
5152 pub accent: String,
53+ /// Accent colour for the dark theme, chosen separately from `accent`. "sage" is the default.
54+ pub accent_dark: String,
55+ /// Base (neutral background, surface and text) set for the light theme. "fern" is the default.
56+ pub base_light: String,
57+ /// Base set for the dark theme. "fern" is the default.
58+ pub base_dark: String,
5259 /// `User` for a person, `Org` for an organization.
5360 pub kind: AccountKind,
5461 /// Whether notifications are also sent by email (needs a verified email and instance mail).
@@ -130,6 +137,9 @@ impl std::fmt::Debug for User {
130137 .field("theme", &self.theme)
131138 .field("language", &self.language)
132139 .field("accent", &self.accent)
140+ .field("accent_dark", &self.accent_dark)
141+ .field("base_light", &self.base_light)
142+ .field("base_dark", &self.base_dark)
133143 .field("kind", &self.kind)
134144 .finish()
135145 }
@@ -219,6 +229,9 @@ mod tests {
219229 theme: "auto".into(),
220230 language: "auto".into(),
221231 accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
232+ accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
233+ base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
234+ base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
222235 kind: AccountKind::User,
223236 email_notifications: true,
224237 };
crates/forge-core/src/store/account_tokens.rsmodified+4 -1
@@ -100,7 +100,7 @@ impl Store {
100100 &conn,
101101 "SELECT id, username, email, password_hash, is_admin, created_at, about, timezone, \
102102 (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \
103- theme, language, kind, email_notifications, display_name, accent FROM users WHERE LOWER(email) = LOWER(?1) \
103+ theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark FROM users WHERE LOWER(email) = LOWER(?1) \
104104 AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1",
105105 (email.to_owned(),),
106106 map_user,
@@ -304,6 +304,9 @@ impl Store {
304304 theme: "light".into(),
305305 language: "auto".into(),
306306 accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
307+ accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
308+ base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
309+ base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
307310 kind: AccountKind::User,
308311 email_notifications: true,
309312 };
crates/forge-core/src/store/migrate.rsmodified+1 -0
@@ -60,6 +60,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
6060 (39, include_str!("../../migrations/0039_totp_device.sql")),
6161 (40, include_str!("../../migrations/0040_mail_queue.sql")),
6262 (41, include_str!("../../migrations/0041_accent.sql")),
63+ (42, include_str!("../../migrations/0042_colours.sql")),
6364 ];
6465
6566 /// The highest migration version this binary knows about.
crates/forge-core/src/store/mod.rsmodified+11 -2
@@ -110,7 +110,7 @@ struct Inner {
110110
111111 const USER_COLS: &str = "id, username, email, password_hash, is_admin, created_at, about, timezone, \
112112 (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \
113- theme, language, kind, email_notifications, display_name, accent";
113+ theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark";
114114 const SESSION_COLS: &str = "id, user_id, csrf_token, created_at, expires_at, last_seen, user_agent";
115115 const SSH_KEY_COLS: &str =
116116 "id, user_id, title, algorithm, key_blob, fingerprint, created_at, last_used_at";
@@ -201,6 +201,9 @@ impl Store {
201201 theme: "light".into(),
202202 language: "auto".into(),
203203 accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
204+ accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
205+ base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
206+ base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
204207 kind: AccountKind::User,
205208 email_notifications: true,
206209 };
@@ -245,6 +248,9 @@ impl Store {
245248 theme: "light".into(),
246249 language: "auto".into(),
247250 accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
251+ accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
252+ base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
253+ base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
248254 kind: AccountKind::User,
249255 email_notifications: true,
250256 };
@@ -1039,6 +1045,9 @@ fn map_user(row: &Row) -> Result<User> {
10391045 email_notifications: col_bool(row, 12)?,
10401046 display_name: col_opt_text(row, 13)?,
10411047 accent: col_text(row, 14)?,
1048+ accent_dark: col_text(row, 15)?,
1049+ base_light: col_text(row, 16)?,
1050+ base_dark: col_text(row, 17)?,
10421051 })
10431052 }
10441053
@@ -2169,7 +2178,7 @@ impl Store {
21692178 WHERE collaborators.repo_id = ?1 ORDER BY users.username_folded"
21702179 ),
21712180 (repo_id.to_string(),),
2172- |row| Ok((map_user(row)?, parse_role(&col_text(row, 15)?)?)),
2181+ |row| Ok((map_user(row)?, parse_role(&col_text(row, 18)?)?)),
21732182 )
21742183 .await
21752184 }
crates/forge-core/src/store/orgs.rsmodified+2 -2
@@ -277,7 +277,7 @@ impl Store {
277277 ORDER BY (org_role = 'owner') DESC, username_folded"
278278 ),
279279 (org_id.to_string(),),
280- |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 15)?)?)),
280+ |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 18)?)?)),
281281 )
282282 .await
283283 }
@@ -397,7 +397,7 @@ impl Store {
397397 (SELECT org_id FROM org_members WHERE user_id = ?1) ORDER BY username_folded"
398398 ),
399399 (user_id.to_string(),),
400- |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 15)?)?)),
400+ |row| Ok((map_user(row)?, OrgMemberRole::parse(&col_text(row, 18)?)?)),
401401 )
402402 .await
403403 }
crates/forge-core/src/store/ui_prefs.rsmodified+131 -6
@@ -1,7 +1,8 @@
1-//! Per-user UI preferences: the colour theme, the language and the accent colour. All are stored
2-//! as text in `users` (migrations 0030 and 0041). The web layer decides which values it offers;
3-//! the store only checks that a value is well formed, so a new language or accent needs no store
4-//! change.
1+//! Per-user UI preferences: the colour theme, the language and the colour choices. The colours
2+//! are an accent and a base (neutral background, surface and text) for each of the light and the
3+//! dark theme. All are stored as text in `users` (migrations 0030, 0041 and 0042). The web layer
4+//! decides which values it offers; the store only checks that a value is well formed, so a new
5+//! language, accent or base needs no store change.
56
67 use super::{Store, db_err};
78 use crate::error::{Error, Result};
@@ -16,6 +17,10 @@ pub const AUTO: &str = "auto";
1617 /// `accent_palette.rs`, which a test there checks.
1718 pub const DEFAULT_ACCENT: &str = "sage";
1819
20+/// The base colour set a new user gets, for both themes. It must match the default base in
21+/// forge-web's `accent_palette.rs`, which a test there checks.
22+pub const DEFAULT_BASE: &str = "fern";
23+
1924 /// Longest accepted language code, in bytes.
2025 const MAX_LANGUAGE_LEN: usize = 16;
2126
@@ -70,7 +75,8 @@ impl Store {
7075 Ok(())
7176 }
7277
73- /// Sets the user's accent colour id. A malformed id is rejected and nothing is written.
78+ /// Sets the user's accent colour id for both themes. A malformed id is rejected and nothing is
79+ /// written.
7480 pub async fn set_accent(&self, user_id: &str, accent: &str) -> Result<()> {
7581 if !valid_accent(accent) {
7682 return Err(Error::Invalid(format!("accent {accent:?}")));
@@ -78,7 +84,7 @@ impl Store {
7884 let conn = self.inner.conn.lock().await;
7985 let n = conn
8086 .execute(
81- "UPDATE users SET accent = ?2 WHERE id = ?1",
87+ "UPDATE users SET accent = ?2, accent_dark = ?2 WHERE id = ?1",
8288 (user_id.to_string(), accent.to_string()),
8389 )
8490 .await
@@ -89,6 +95,47 @@ impl Store {
8995 Ok(())
9096 }
9197
98+ /// Sets the four colour choices: the accent and the base for the light theme, then the accent
99+ /// and the base for the dark theme. If any id is malformed, nothing is written.
100+ pub async fn set_colours(
101+ &self,
102+ user_id: &str,
103+ accent_light: &str,
104+ accent_dark: &str,
105+ base_light: &str,
106+ base_dark: &str,
107+ ) -> Result<()> {
108+ for accent in [accent_light, accent_dark] {
109+ if !valid_accent(accent) {
110+ return Err(Error::Invalid(format!("accent {accent:?}")));
111+ }
112+ }
113+ for base in [base_light, base_dark] {
114+ if !valid_accent(base) {
115+ return Err(Error::Invalid(format!("base {base:?}")));
116+ }
117+ }
118+ let conn = self.inner.conn.lock().await;
119+ let n = conn
120+ .execute(
121+ "UPDATE users SET accent = ?2, accent_dark = ?3, base_light = ?4, base_dark = ?5 \
122+ WHERE id = ?1",
123+ (
124+ user_id.to_string(),
125+ accent_light.to_string(),
126+ accent_dark.to_string(),
127+ base_light.to_string(),
128+ base_dark.to_string(),
129+ ),
130+ )
131+ .await
132+ .map_err(db_err)?;
133+ if n == 0 {
134+ return Err(Error::NotFound);
135+ }
136+ Ok(())
137+ }
138+
92139 /// Turns the email copy of notifications on or off for one user (migration 0035).
93140 pub async fn set_email_notifications(&self, user_id: &str, on: bool) -> Result<()> {
94141 let conn = self.inner.conn.lock().await;
@@ -159,6 +206,84 @@ mod tests {
159206 );
160207 }
161208
209+ #[tokio::test]
210+ async fn colours_persist_and_bad_values_change_nothing() {
211+ let dir = tempfile::tempdir().unwrap();
212+ let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
213+ let user = store
214+ .create_user("tahinli", None, "hash", false)
215+ .await
216+ .unwrap();
217+ assert_eq!(user.accent_dark, DEFAULT_ACCENT);
218+ assert_eq!(user.base_light, DEFAULT_BASE);
219+ assert_eq!(user.base_dark, DEFAULT_BASE);
220+
221+ store
222+ .set_colours(&user.id, "ocean", "rose", "stone", "ink")
223+ .await
224+ .unwrap();
225+ let stored = store.user_by_id(&user.id).await.unwrap().unwrap();
226+ assert_eq!(
227+ (
228+ stored.accent.as_str(),
229+ stored.accent_dark.as_str(),
230+ stored.base_light.as_str(),
231+ stored.base_dark.as_str()
232+ ),
233+ ("ocean", "rose", "stone", "ink")
234+ );
235+
236+ assert!(
237+ store
238+ .set_colours(&user.id, "ocean", "Rose", "stone", "ink")
239+ .await
240+ .is_err()
241+ );
242+ assert!(
243+ store
244+ .set_colours(&user.id, "ocean", "rose", "../x", "ink")
245+ .await
246+ .is_err()
247+ );
248+ assert!(
249+ store
250+ .set_colours(&user.id, "ocean", "rose", "stone", "")
251+ .await
252+ .is_err()
253+ );
254+ let still = store.user_by_id(&user.id).await.unwrap().unwrap();
255+ assert_eq!(
256+ (
257+ still.accent.as_str(),
258+ still.accent_dark.as_str(),
259+ still.base_light.as_str(),
260+ still.base_dark.as_str()
261+ ),
262+ ("ocean", "rose", "stone", "ink")
263+ );
264+ }
265+
266+ #[tokio::test]
267+ async fn set_accent_sets_both_accents_and_keeps_bases() {
268+ let dir = tempfile::tempdir().unwrap();
269+ let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
270+ let user = store
271+ .create_user("tahinli", None, "hash", false)
272+ .await
273+ .unwrap();
274+ store
275+ .set_colours(&user.id, "sage", "sage", "mist", "ink")
276+ .await
277+ .unwrap();
278+
279+ store.set_accent(&user.id, "ocean").await.unwrap();
280+ let stored = store.user_by_id(&user.id).await.unwrap().unwrap();
281+ assert_eq!(stored.accent, "ocean");
282+ assert_eq!(stored.accent_dark, "ocean");
283+ assert_eq!(stored.base_light, "mist");
284+ assert_eq!(stored.base_dark, "ink");
285+ }
286+
162287 #[tokio::test]
163288 async fn prefs_persist_and_bad_values_change_nothing() {
164289 let dir = tempfile::tempdir().unwrap();
crates/forge-core/src/store/user_delete.rsmodified+3 -0
@@ -167,6 +167,9 @@ impl Store {
167167 theme: "light".into(),
168168 language: "auto".into(),
169169 accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
170+ accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
171+ base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
172+ base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
170173 kind: AccountKind::User,
171174 email_notifications: true,
172175 };
crates/forge-web/assets/nav.jsmodified+39 -2
@@ -13,6 +13,7 @@
1313 var liveDirty = false; // a live change came while a navigation was on the wire
1414 var inFlight = 0; // requests on the wire, drives aria-busy
1515 var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored
16+ var queued = new WeakSet(); // forms that changed while pending: submitted again once it completes
1617 var shown = location.pathname + location.search;
1718 var GET_INIT = { headers: { accept: 'text/html' } };
1819
@@ -46,9 +47,11 @@
4647 }
4748
4849 // Field preservation: a dirty or focused field keeps its value, and the caret offsets come along.
50+ // Radios and checkboxes share a name, so their value is part of the key to tell them apart.
4951 function fieldKey(el) {
5052 var form = el.form ? (el.form.getAttribute('action') || '') : '';
51- return form + '|' + (el.name || '') + '|' + (el.type || '') + '|' + el.tagName;
53+ var value = el.type === 'radio' || el.type === 'checkbox' ? el.value : '';
54+ return form + '|' + (el.name || '') + '|' + (el.type || '') + '|' + el.tagName + '|' + value;
5255 }
5356
5457 function savable(el) {
@@ -127,7 +130,7 @@
127130
128131 function adopt(doc, keepFields, dd) {
129132 document.title = doc.title;
130- ['lang', 'data-theme', 'data-accent', 'data-ui'].forEach(function (name) {
133+ ['lang', 'data-theme', 'data-accent-light', 'data-accent-dark', 'data-base-light', 'data-base-dark', 'data-ui'].forEach(function (name) {
131134 if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); }
132135 else { root.removeAttribute(name); }
133136 });
@@ -245,9 +248,24 @@
245248 userBusy -= 1;
246249 if (liveDirty) { refreshLive(); }
247250 }
251+ if (o.form && queued.has(o.form)) { queued.delete(o.form); resend(o.form); }
248252 });
249253 }
250254
255+ // The form to send a queued change on: the form itself, or after a swap the one with the same action.
256+ function resend(form) {
257+ var target = form;
258+ if (!form.isConnected) {
259+ target = null;
260+ var action = form.getAttribute('action') || '';
261+ for (var i = 0; i < document.forms.length; i++) {
262+ if ((document.forms[i].getAttribute('action') || '') === action) { target = document.forms[i]; break; }
263+ }
264+ }
265+ if (!target) { return; }
266+ if (target.requestSubmit) { target.requestSubmit(); } else { target.submit(); }
267+ }
268+
251269 function saveScroll() {
252270 try { history.replaceState({ y: window.scrollY }, '', location.href); } catch (err) { }
253271 }
@@ -399,9 +417,28 @@
399417 document.addEventListener('change', function (e) {
400418 var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null;
401419 if (!c || !c.form) { return; }
420+ // A request is already on the wire for this form: the change waits for it, and is sent when it completes.
421+ if (pending.has(c.form)) { queued.add(c.form); return; }
402422 if (c.form.requestSubmit) { c.form.requestSubmit(); } else { c.form.submit(); }
403423 });
404424
425+ // Appearance page: a colour or theme choice shows on <html> at once, before the form's request returns.
426+ // The attributes match what the shell renders: theme `auto` has no data-theme, `dark` is dark, else light.
427+ var PREVIEW_ATTR = { accent_light: 'data-accent-light', accent_dark: 'data-accent-dark', base_light: 'data-base-light', base_dark: 'data-base-dark' };
428+
429+ document.addEventListener('change', function (e) {
430+ var el = e.target;
431+ if (!el || !el.form || !el.form.hasAttribute('data-appearance')) { return; }
432+ if (el.name === 'theme') {
433+ if (el.value === 'auto') { root.removeAttribute('data-theme'); }
434+ else { root.setAttribute('data-theme', el.value === 'dark' ? 'dark' : 'light'); }
435+ return;
436+ }
437+ if (el.type === 'radio' && Object.prototype.hasOwnProperty.call(PREVIEW_ATTR, el.name)) {
438+ root.setAttribute(PREVIEW_ATTR[el.name], el.value);
439+ }
440+ }, false);
441+
405442 // A filtered view asked for in place: the URL is replaced (no history entry per change), fields
406443 // and caret come through the swap, and the scroll stays put.
407444 // Live unread count. The bell is re-rendered by every swap, so it is looked up on each update. One
crates/forge-web/build.rsmodified+118 -42
@@ -2,8 +2,8 @@
22 //! asset also gets a content hash (FORGE_MAIN_CSS_V, FORGE_NAV_JS_V) that the page links use as
33 //! their cache-busting query, so an unchanged file keeps its URL and a changed one gets a new one.
44 //!
5-//! The accent colours come from `src/accent_palette.rs`, the same data the app reads. This script
6-//! turns it into `_accents.scss` in OUT_DIR, which main.scss imports.
5+//! The accent colours and the neutral bases come from `src/accent_palette.rs`, the same data the
6+//! app reads. This script turns it into `_accents.scss` in OUT_DIR, which main.scss imports.
77
88 use std::{env, fs, path::PathBuf};
99
@@ -14,77 +14,153 @@ use sha2::{Digest, Sha256};
1414 #[allow(dead_code)]
1515 mod accent_palette;
1616
17-use accent_palette::{DEFAULT, PALETTES, Palette, TOKEN_VARS, Tokens};
17+use accent_palette::{
18+ BASE_DEFAULT, BASE_TOKEN_VARS, BASES, Base, BaseTokens, DEFAULT, PALETTES, Palette, TOKEN_VARS,
19+ Tokens,
20+};
1821
1922 /// First 12 hex characters of the SHA-256 of `bytes`.
2023 fn content_version(bytes: &[u8]) -> String {
2124 encode(Sha256::digest(bytes))[..12].to_string()
2225 }
2326
24-/// One `--token: value;` line per token, indented for a rule body.
25-fn declarations(tokens: &Tokens) -> String {
27+/// The `(name, value)` declarations of one accent palette's tokens in one theme.
28+fn accent_decls(tokens: &Tokens) -> Vec<(&'static str, &'static str)> {
2629 TOKEN_VARS
2730 .iter()
28- .map(|token| format!(" {}: {};\n", token.name, (token.value)(tokens)))
31+ .map(|token| (token.name, (token.value)(tokens)))
2932 .collect()
3033 }
3134
32-/// Appends `selector { … }` with the palette's tokens for one theme. `indent` is 0 or 2.
33-fn rule(css: &mut String, indent: &str, selector: &str, tokens: &Tokens) {
35+/// The `(name, value)` declarations of one base's neutral tokens in one theme.
36+fn base_decls(tokens: &BaseTokens) -> Vec<(&'static str, &'static str)> {
37+ BASE_TOKEN_VARS
38+ .iter()
39+ .map(|token| (token.name, (token.value)(tokens)))
40+ .collect()
41+}
42+
43+/// Appends `selector { … }` with one `--token: value;` line per declaration. `indent` is 0 or 2.
44+fn rule(css: &mut String, indent: &str, selector: &str, decls: &[(&str, &str)]) {
3445 css.push_str(&format!("{indent}{selector} {{\n"));
35- for line in declarations(tokens).lines() {
36- css.push_str(&format!("{indent}{line}\n"));
46+ for (name, value) in decls {
47+ css.push_str(&format!("{indent} {name}: {value};\n"));
3748 }
3849 css.push_str(&format!("{indent}}}\n"));
3950 }
4051
41-/// The rules for one palette. The default palette sits on bare `:root`, as it always has. Every
42-/// other palette is scoped to `[data-accent]`, which is more specific, so it wins over the
43-/// default in all three theme states: light, dark by `data-theme`, and dark by the OS.
44-fn palette_rules(css: &mut String, palette: &Palette) {
45- let base = if palette.id == DEFAULT {
46- ":root".to_string()
47- } else {
48- format!(":root[data-accent=\"{}\"]", palette.id)
49- };
50- let os_dark = format!("{base}:not([data-theme=\"light\"])");
51- let forced_dark = format!("{base}[data-theme=\"dark\"]");
52- rule(css, "", &base, &palette.light);
52+/// The rules for one choice: its light tokens on `light`, and its dark tokens on `dark` in both
53+/// dark states, by the OS and by `data-theme`. Dark selectors carry one more attribute than the
54+/// light one, so the dark rules win in dark mode whatever the light choice is.
55+fn choice_rules(
56+ css: &mut String,
57+ light: &str,
58+ dark: &str,
59+ light_decls: &[(&str, &str)],
60+ dark_decls: &[(&str, &str)],
61+) {
62+ let os_dark = format!("{dark}:not([data-theme=\"light\"])");
63+ let forced_dark = format!("{dark}[data-theme=\"dark\"]");
64+ rule(css, "", light, light_decls);
5365 css.push_str("@media (prefers-color-scheme: dark) {\n");
54- rule(css, " ", &os_dark, &palette.dark);
66+ rule(css, " ", &os_dark, dark_decls);
5567 css.push_str("}\n");
56- rule(css, "", &forced_dark, &palette.dark);
68+ rule(css, "", &forced_dark, dark_decls);
69+}
70+
71+/// The bare fallbacks for pages without the choice attributes: the default accent and base, on
72+/// plain `:root`.
73+fn fallback_rules(css: &mut String) {
74+ let accent = PALETTES
75+ .iter()
76+ .find(|p| p.id == DEFAULT)
77+ .expect("the default accent is one of the palettes");
78+ choice_rules(
79+ css,
80+ ":root",
81+ ":root",
82+ &accent_decls(&accent.light),
83+ &accent_decls(&accent.dark),
84+ );
85+ let base = BASES
86+ .iter()
87+ .find(|b| b.id == BASE_DEFAULT)
88+ .expect("the default base is one of the bases");
89+ choice_rules(
90+ css,
91+ ":root",
92+ ":root",
93+ &base_decls(&base.light),
94+ &base_decls(&base.dark),
95+ );
5796 }
5897
59-/// The swatch chip for one palette in the settings picker: its accent, light or dark.
60-fn swatch_rules(css: &mut String, palette: &Palette) {
61- let swatch = format!(".accent-swatch[data-accent-swatch=\"{}\"]", palette.id);
62- css.push_str(&format!(
63- "{swatch} {{ background: {}; }}\n",
64- palette.light.accent
65- ));
66- css.push_str(&format!(
67- "@media (prefers-color-scheme: dark) {{\n :root:not([data-theme=\"light\"]) {swatch} {{ background: {}; }}\n}}\n",
68- palette.dark.accent
69- ));
70- css.push_str(&format!(
71- ":root[data-theme=\"dark\"] {swatch} {{ background: {}; }}\n",
72- palette.dark.accent
73- ));
98+/// The rules for one accent palette: its light tokens are keyed on `data-accent-light`, its dark
99+/// tokens on `data-accent-dark`.
100+fn palette_rules(css: &mut String, palette: &Palette) {
101+ choice_rules(
102+ css,
103+ &format!(":root[data-accent-light=\"{}\"]", palette.id),
104+ &format!(":root[data-accent-dark=\"{}\"]", palette.id),
105+ &accent_decls(&palette.light),
106+ &accent_decls(&palette.dark),
107+ );
108+}
109+
110+/// The rules for one base: its light tokens are keyed on `data-base-light`, its dark tokens on
111+/// `data-base-dark`.
112+fn base_rules(css: &mut String, base: &Base) {
113+ choice_rules(
114+ css,
115+ &format!(":root[data-base-light=\"{}\"]", base.id),
116+ &format!(":root[data-base-dark=\"{}\"]", base.id),
117+ &base_decls(&base.light),
118+ &base_decls(&base.dark),
119+ );
74120 }
75121
76-/// The whole generated stylesheet: the palettes, then the swatch chips.
122+/// The swatch chips for the settings picker. They show fixed colours, so they do not depend on
123+/// the current theme: an accent chip is the accent itself, a base chip is its background and text
124+/// split diagonally.
125+fn swatch_rules(css: &mut String) {
126+ for palette in PALETTES {
127+ css.push_str(&format!(
128+ ".accent-swatch[data-accent-light-swatch=\"{}\"] {{ background: {}; }}\n",
129+ palette.id, palette.light.accent
130+ ));
131+ css.push_str(&format!(
132+ ".accent-swatch[data-accent-dark-swatch=\"{}\"] {{ background: {}; }}\n",
133+ palette.id, palette.dark.accent
134+ ));
135+ }
136+ for base in BASES {
137+ css.push_str(&format!(
138+ ".base-swatch[data-base-light-swatch=\"{}\"] {{ background: linear-gradient(135deg, {} 0 50%, {} 50% 100%); }}\n",
139+ base.id, base.light.bg, base.light.text
140+ ));
141+ css.push_str(&format!(
142+ ".base-swatch[data-base-dark-swatch=\"{}\"] {{ background: linear-gradient(135deg, {} 0 50%, {} 50% 100%); }}\n",
143+ base.id, base.dark.bg, base.dark.text
144+ ));
145+ }
146+}
147+
148+/// The whole generated stylesheet: the bare fallbacks, the accent and base rules, then the swatch
149+/// chips.
77150 fn accents_scss() -> String {
78151 let mut css = String::from(
79152 "/* Generated by crates/forge-web/build.rs from src/accent_palette.rs. Edit that file. */\n",
80153 );
81154 assert_eq!(PALETTES[0].id, DEFAULT, "the default palette comes first");
155+ assert_eq!(BASES[0].id, BASE_DEFAULT, "the default base comes first");
156+ fallback_rules(&mut css);
82157 for palette in PALETTES {
83158 palette_rules(&mut css, palette);
84159 }
85- for palette in PALETTES {
86- swatch_rules(&mut css, palette);
160+ for base in BASES {
161+ base_rules(&mut css, base);
87162 }
163+ swatch_rules(&mut css);
88164 css
89165 }
90166
crates/forge-web/src/accent.rsmodified+118 -37
@@ -1,8 +1,8 @@
1-//! Accent colour: which palette a viewer sees. The colours live in `accent_palette.rs`, which
2-//! `build.rs` also turns into the stylesheet. This module only resolves stored ids and checks
3-//! which ids forge offers.
1+//! Accent colour and base: which palette and which neutral set a viewer sees. The values live in
2+//! `accent_palette.rs`, which `build.rs` also turns into the stylesheet. This module only resolves
3+//! stored ids and checks which ids forge offers.
44
5-use crate::accent_palette::{DEFAULT, PALETTES, Palette};
5+use crate::accent_palette::{BASE_DEFAULT, BASES, Base, DEFAULT, PALETTES, Palette};
66
77 /// The palette for a stored id. An unknown or removed id falls back to the default.
88 pub fn resolve(stored: &str) -> &'static Palette {
@@ -22,6 +22,24 @@ pub fn ids() -> impl Iterator<Item = &'static str> {
2222 PALETTES.iter().map(|p| p.id)
2323 }
2424
25+/// The base for a stored id. An unknown or removed id falls back to the default.
26+pub fn resolve_base(stored: &str) -> &'static Base {
27+ BASES
28+ .iter()
29+ .find(|b| b.id == stored)
30+ .unwrap_or_else(default_base)
31+}
32+
33+/// True when forge offers this base id.
34+pub fn is_offered_base(id: &str) -> bool {
35+ BASES.iter().any(|b| b.id == id)
36+}
37+
38+/// Every offered base id, in the order the picker lists them.
39+pub fn base_ids() -> impl Iterator<Item = &'static str> {
40+ BASES.iter().map(|b| b.id)
41+}
42+
2543 fn default_palette() -> &'static Palette {
2644 PALETTES
2745 .iter()
@@ -29,18 +47,19 @@ fn default_palette() -> &'static Palette {
2947 .expect("the default accent is one of the palettes")
3048 }
3149
50+fn default_base() -> &'static Base {
51+ BASES
52+ .iter()
53+ .find(|b| b.id == BASE_DEFAULT)
54+ .expect("the default base is one of the bases")
55+}
56+
3257 #[cfg(test)]
3358 mod tests {
3459 use std::collections::HashSet;
3560
3661 use super::*;
37- use crate::accent_palette::{TOKEN_VARS, Tokens};
38-
39- /// The neutral backgrounds of style/main.scss, in each theme.
40- const LIGHT_BG: &str = "#F6F8F5";
41- const LIGHT_SURFACE: &str = "#FFFFFF";
42- const DARK_BG: &str = "#121613";
43- const DARK_SURFACE: &str = "#191E1A";
62+ use crate::accent_palette::{BASE_TOKEN_VARS, TOKEN_VARS, Tokens};
4463
4564 /// WCAG relative luminance of a `#RRGGBB` colour.
4665 fn luminance(hex: &str) -> f64 {
@@ -82,6 +101,21 @@ mod tests {
82101 }
83102 }
84103
104+ #[test]
105+ fn base_ids_are_slugs_unique_and_the_default_comes_first() {
106+ assert_eq!(BASES[0].id, BASE_DEFAULT);
107+ assert_eq!(BASE_DEFAULT, forge_core::store::ui_prefs::DEFAULT_BASE);
108+ let mut seen = HashSet::new();
109+ for b in BASES {
110+ assert!(
111+ forge_core::store::ui_prefs::valid_accent(b.id),
112+ "{} is not a slug",
113+ b.id
114+ );
115+ assert!(seen.insert(b.id), "{} is listed twice", b.id);
116+ }
117+ }
118+
85119 #[test]
86120 fn every_token_is_a_hex_colour() {
87121 for p in PALETTES {
@@ -91,6 +125,13 @@ mod tests {
91125 }
92126 }
93127 }
128+ for b in BASES {
129+ for token in BASE_TOKEN_VARS {
130+ for t in [&b.light, &b.dark] {
131+ assert!(is_hex_colour((token.value)(t)), "{} {}", b.id, token.name);
132+ }
133+ }
134+ }
94135 }
95136
96137 #[test]
@@ -103,38 +144,78 @@ mod tests {
103144 }
104145
105146 #[test]
106- fn every_palette_meets_the_contrast_targets() {
147+ fn unknown_and_removed_base_ids_fall_back_to_the_default() {
148+ assert_eq!(resolve_base("ink").id, "ink");
149+ assert_eq!(resolve_base("removed-base").id, BASE_DEFAULT);
150+ assert_eq!(resolve_base("").id, BASE_DEFAULT);
151+ assert!(is_offered_base("mist"));
152+ assert!(!is_offered_base("removed-base"));
153+ }
154+
155+ #[test]
156+ fn every_accent_keeps_its_own_text_readable() {
107157 for p in PALETTES {
108- let themes = [
109- ("light", &p.light, LIGHT_BG, LIGHT_SURFACE),
110- ("dark", &p.dark, DARK_BG, DARK_SURFACE),
111- ];
112- for (theme, t, bg, surface) in themes {
113- let check = |what: &str, ratio: f64, min: f64| {
114- assert!(ratio >= min, "{} {theme} {what}: {ratio:.2} < {min}", p.id);
115- };
116- check(
117- "accent_text on accent",
118- contrast(t.accent_text, t.accent),
119- 4.5,
120- );
121- check("accent_ink on bg", contrast(t.accent_ink, bg), 4.5);
122- check(
123- "accent_ink on surface",
124- contrast(t.accent_ink, surface),
125- 4.5,
126- );
127- check(
128- "accent_ink on accent_soft",
129- contrast(t.accent_ink, t.accent_soft),
130- 4.5,
131- );
158+ let check = |what: &str, ratio: f64, min: f64| {
159+ assert!(ratio >= min, "{} {what}: {ratio:.2} < {min}", p.id);
160+ };
161+ check(
162+ "accent_text on accent (light)",
163+ contrast(p.light.accent_text, p.light.accent),
164+ 4.5,
165+ );
166+ check(
167+ "accent_text on accent (dark)",
168+ contrast(p.dark.accent_text, p.dark.accent),
169+ 4.5,
170+ );
171+ for t in [&p.light, &p.dark] {
132172 check(
133173 "public_text on public_bg",
134174 contrast(t.public_text, t.public_bg),
135175 4.5,
136176 );
137- check("focus on bg", contrast(t.focus, bg), 3.0);
177+ }
178+ }
179+ }
180+
181+ #[test]
182+ fn every_base_with_every_accent_meets_the_contrast_targets() {
183+ for base in BASES {
184+ for p in PALETTES {
185+ let themes = [
186+ ("light", &base.light, &p.light),
187+ ("dark", &base.dark, &p.dark),
188+ ];
189+ for (theme, b, t) in themes {
190+ let who = format!("{} with {} ({theme})", base.id, p.id);
191+ let check = |what: &str, ratio: f64, min: f64| {
192+ assert!(ratio >= min, "{who} {what}: {ratio:.2} < {min}");
193+ };
194+ check("text on bg", contrast(b.text, b.bg), 7.0);
195+ check("text on surface", contrast(b.text, b.surface), 7.0);
196+ check("text_2 on bg", contrast(b.text_2, b.bg), 4.5);
197+ check("text_2 on surface", contrast(b.text_2, b.surface), 4.5);
198+ check("muted on bg", contrast(b.muted, b.bg), 4.5);
199+ check("muted on surface", contrast(b.muted, b.surface), 4.5);
200+ check("ln_text on code_bg", contrast(b.ln_text, b.code_bg), 4.5);
201+ check(
202+ "private_text on private_bg",
203+ contrast(b.private_text, b.private_bg),
204+ 4.5,
205+ );
206+ check("accent_ink on bg", contrast(t.accent_ink, b.bg), 4.5);
207+ check(
208+ "accent_ink on surface",
209+ contrast(t.accent_ink, b.surface),
210+ 4.5,
211+ );
212+ check(
213+ "accent_ink on accent_soft",
214+ contrast(t.accent_ink, t.accent_soft),
215+ 4.5,
216+ );
217+ check("focus on bg", contrast(t.focus, b.bg), 3.0);
218+ }
138219 }
139220 }
140221 }
crates/forge-web/src/accent_palette.rsmodified+252 -0
@@ -336,3 +336,255 @@ pub const PALETTES: &[Palette] = &[
336336 },
337337 },
338338 ];
339+
340+/// The neutral colour tokens one base sets in one theme. The values are CSS colours;
341+/// `BASE_TOKEN_VARS` names the custom property each field becomes.
342+pub struct BaseTokens {
343+ pub bg: &'static str,
344+ pub surface: &'static str,
345+ pub surface_2: &'static str,
346+ pub text: &'static str,
347+ pub text_2: &'static str,
348+ pub muted: &'static str,
349+ pub border: &'static str,
350+ pub border_strong: &'static str,
351+ pub code_bg: &'static str,
352+ pub private_bg: &'static str,
353+ pub private_text: &'static str,
354+ pub ln_text: &'static str,
355+}
356+
357+/// One base: the neutral backgrounds, surfaces and text. Its id is the stored value and the
358+/// attribute value, and the tokens are used in light and dark themes.
359+pub struct Base {
360+ pub id: &'static str,
361+ pub light: BaseTokens,
362+ pub dark: BaseTokens,
363+}
364+
365+/// The base used when none is stored, and for anonymous visitors. It must be `BASES[0]`.
366+pub const BASE_DEFAULT: &str = "fern";
367+
368+/// One base token: the custom property it becomes and the field of `BaseTokens` that holds its
369+/// value.
370+pub struct BaseTokenVar {
371+ pub name: &'static str,
372+ pub value: fn(&BaseTokens) -> &'static str,
373+}
374+
375+/// Every neutral token a base sets. The stylesheet keeps no copy of these.
376+pub const BASE_TOKEN_VARS: &[BaseTokenVar] = &[
377+ BaseTokenVar {
378+ name: "--bg",
379+ value: |t| t.bg,
380+ },
381+ BaseTokenVar {
382+ name: "--surface",
383+ value: |t| t.surface,
384+ },
385+ BaseTokenVar {
386+ name: "--surface-2",
387+ value: |t| t.surface_2,
388+ },
389+ BaseTokenVar {
390+ name: "--text",
391+ value: |t| t.text,
392+ },
393+ BaseTokenVar {
394+ name: "--text-2",
395+ value: |t| t.text_2,
396+ },
397+ BaseTokenVar {
398+ name: "--muted",
399+ value: |t| t.muted,
400+ },
401+ BaseTokenVar {
402+ name: "--border",
403+ value: |t| t.border,
404+ },
405+ BaseTokenVar {
406+ name: "--border-strong",
407+ value: |t| t.border_strong,
408+ },
409+ BaseTokenVar {
410+ name: "--code-bg",
411+ value: |t| t.code_bg,
412+ },
413+ BaseTokenVar {
414+ name: "--private-bg",
415+ value: |t| t.private_bg,
416+ },
417+ BaseTokenVar {
418+ name: "--private-text",
419+ value: |t| t.private_text,
420+ },
421+ BaseTokenVar {
422+ name: "--ln-text",
423+ value: |t| t.ln_text,
424+ },
425+];
426+
427+/// Every base on offer, in the order the picker lists them. `fern` is the original forge
428+/// neutral set.
429+pub const BASES: &[Base] = &[
430+ // Fern: the original forge neutrals, green-tinted.
431+ Base {
432+ id: "fern",
433+ light: BaseTokens {
434+ bg: "#F6F8F5",
435+ surface: "#FFFFFF",
436+ surface_2: "#EEF2EC",
437+ text: "#1E2420",
438+ text_2: "#3A433D",
439+ muted: "#69736B",
440+ border: "#DDE3DB",
441+ border_strong: "#C5CFC3",
442+ code_bg: "#EEF2EC",
443+ private_bg: "#EEF2EC",
444+ private_text: "#3A433D",
445+ ln_text: "#646D65",
446+ },
447+ dark: BaseTokens {
448+ bg: "#121613",
449+ surface: "#191E1A",
450+ surface_2: "#1F261F",
451+ text: "#E3E8E2",
452+ text_2: "#C4CCC3",
453+ muted: "#97A198",
454+ border: "#2A322C",
455+ border_strong: "#3A443C",
456+ code_bg: "#1F261F",
457+ private_bg: "#1F261F",
458+ private_text: "#C4CCC3",
459+ ln_text: "#97A198",
460+ },
461+ },
462+ // Stone: pure neutral grey.
463+ Base {
464+ id: "stone",
465+ light: BaseTokens {
466+ bg: "#F5F5F4",
467+ surface: "#FFFFFF",
468+ surface_2: "#EDEDEB",
469+ text: "#1C1C1B",
470+ text_2: "#3D3D3B",
471+ muted: "#6B6B68",
472+ border: "#DEDEDB",
473+ border_strong: "#C6C6C2",
474+ code_bg: "#EDEDEB",
475+ private_bg: "#EDEDEB",
476+ private_text: "#3D3D3B",
477+ ln_text: "#6B6B68",
478+ },
479+ dark: BaseTokens {
480+ bg: "#131313",
481+ surface: "#1A1A1A",
482+ surface_2: "#212121",
483+ text: "#E6E6E4",
484+ text_2: "#C7C7C4",
485+ muted: "#9A9A96",
486+ border: "#2C2C2B",
487+ border_strong: "#3C3C3A",
488+ code_bg: "#212121",
489+ private_bg: "#212121",
490+ private_text: "#C7C7C4",
491+ ln_text: "#9A9A96",
492+ },
493+ },
494+ // Sand: warm paper and warm ink.
495+ Base {
496+ id: "sand",
497+ light: BaseTokens {
498+ bg: "#F8F5EF",
499+ surface: "#FFFDF9",
500+ surface_2: "#F0EBE1",
501+ text: "#2A2620",
502+ text_2: "#4A443B",
503+ muted: "#716A5E",
504+ border: "#E2DBCF",
505+ border_strong: "#CBC2B3",
506+ code_bg: "#F0EBE1",
507+ private_bg: "#F0EBE1",
508+ private_text: "#4A443B",
509+ ln_text: "#6B6457",
510+ },
511+ dark: BaseTokens {
512+ bg: "#171511",
513+ surface: "#1E1B16",
514+ surface_2: "#26221C",
515+ text: "#E9E4DA",
516+ text_2: "#CBC5B9",
517+ muted: "#A29B8D",
518+ border: "#342F27",
519+ border_strong: "#463F35",
520+ code_bg: "#26221C",
521+ private_bg: "#26221C",
522+ private_text: "#CBC5B9",
523+ ln_text: "#A29B8D",
524+ },
525+ },
526+ // Mist: cool blue-grey.
527+ Base {
528+ id: "mist",
529+ light: BaseTokens {
530+ bg: "#F3F6F9",
531+ surface: "#FFFFFF",
532+ surface_2: "#E9EEF3",
533+ text: "#1B2430",
534+ text_2: "#384352",
535+ muted: "#66717F",
536+ border: "#D9E0E8",
537+ border_strong: "#C2CCD8",
538+ code_bg: "#E9EEF3",
539+ private_bg: "#E9EEF3",
540+ private_text: "#384352",
541+ ln_text: "#5E6977",
542+ },
543+ dark: BaseTokens {
544+ bg: "#11161C",
545+ surface: "#182029",
546+ surface_2: "#1E2834",
547+ text: "#E2E8EF",
548+ text_2: "#C3CCD7",
549+ muted: "#949FAD",
550+ border: "#28323E",
551+ border_strong: "#37424F",
552+ code_bg: "#1E2834",
553+ private_bg: "#1E2834",
554+ private_text: "#C3CCD7",
555+ ln_text: "#949FAD",
556+ },
557+ },
558+ // Ink: crisp white in light, near-black in dark.
559+ Base {
560+ id: "ink",
561+ light: BaseTokens {
562+ bg: "#FCFCFB",
563+ surface: "#FFFFFF",
564+ surface_2: "#F2F2F0",
565+ text: "#111111",
566+ text_2: "#333333",
567+ muted: "#5F5F5C",
568+ border: "#E3E3E0",
569+ border_strong: "#C9C9C5",
570+ code_bg: "#F2F2F0",
571+ private_bg: "#F2F2F0",
572+ private_text: "#333333",
573+ ln_text: "#5F5F5C",
574+ },
575+ dark: BaseTokens {
576+ bg: "#000000",
577+ surface: "#0B0B0B",
578+ surface_2: "#141414",
579+ text: "#F2F2F0",
580+ text_2: "#CFCFCC",
581+ muted: "#9C9C98",
582+ border: "#242424",
583+ border_strong: "#353535",
584+ code_bg: "#141414",
585+ private_bg: "#141414",
586+ private_text: "#CFCFCC",
587+ ln_text: "#9C9C98",
588+ },
589+ },
590+];
crates/forge-web/src/i18n/accents.rsmodified+29 -2
@@ -1,5 +1,5 @@
1-//! Names of the accent colours on the appearance page, keyed by palette id. Adding a palette
2-//! without a name here fails `every_palette_has_a_name`.
1+//! Names of the accent colours and the backgrounds on the appearance page, keyed by id. Adding a
2+//! palette or a base without a name here fails `every_palette_has_a_name` or `every_base_has_a_name`.
33
44 use super::Lang;
55
@@ -23,6 +23,24 @@ pub fn accent_name(lang: Lang, id: &str) -> &'static str {
2323 }
2424 }
2525
26+/// The display name of a base (the neutral background set). An id with no name returns an empty
27+/// string, which the test rules out for every offered base.
28+pub fn base_name(lang: Lang, id: &str) -> &'static str {
29+ match (id, lang) {
30+ ("fern", Lang::En) => "Fern",
31+ ("fern", Lang::Tr) => "Eğrelti",
32+ ("stone", Lang::En) => "Stone",
33+ ("stone", Lang::Tr) => "Taş",
34+ ("sand", Lang::En) => "Sand",
35+ ("sand", Lang::Tr) => "Kum",
36+ ("mist", Lang::En) => "Mist",
37+ ("mist", Lang::Tr) => "Sis",
38+ ("ink", Lang::En) => "Ink",
39+ ("ink", Lang::Tr) => "Mürekkep",
40+ _ => "",
41+ }
42+}
43+
2644 #[cfg(test)]
2745 mod tests {
2846 use super::*;
@@ -36,4 +54,13 @@ mod tests {
3654 }
3755 }
3856 }
57+
58+ #[test]
59+ fn every_base_has_a_name() {
60+ for id in accent::base_ids() {
61+ for lang in [Lang::En, Lang::Tr] {
62+ assert!(!base_name(lang, id).is_empty(), "{id} has no name");
63+ }
64+ }
65+ }
3966 }
crates/forge-web/src/i18n/misc.rsmodified+16 -12
@@ -14,7 +14,6 @@ pub enum K {
1414 Appearance,
1515 ThemeLabel,
1616 LanguageLabel,
17- ThemeAndLanguage,
1817 MatchSystemHelp,
1918 MatchSystem,
2019 Light,
@@ -24,12 +23,14 @@ pub enum K {
2423 SwitchToLight,
2524 SwitchToDark,
2625 SwitchToMatchSystem,
27- AppearanceSaved,
2826 ChooseTheme,
2927 ChooseLanguage,
3028 AccentLabel,
31- AccentHelp,
3229 ChooseAccent,
30+ LightColours,
31+ DarkColours,
32+ BackgroundLabel,
33+ ChooseBase,
3334 // Notifications: row kinds.
3435 KindOpenIssue,
3536 KindClosedIssue,
@@ -156,7 +157,6 @@ const ALL: &[K] = &[
156157 K::Appearance,
157158 K::ThemeLabel,
158159 K::LanguageLabel,
159- K::ThemeAndLanguage,
160160 K::MatchSystemHelp,
161161 K::MatchSystem,
162162 K::Light,
@@ -165,12 +165,14 @@ const ALL: &[K] = &[
165165 K::SwitchToLight,
166166 K::SwitchToDark,
167167 K::SwitchToMatchSystem,
168- K::AppearanceSaved,
169168 K::ChooseTheme,
170169 K::ChooseLanguage,
171170 K::AccentLabel,
172- K::AccentHelp,
173171 K::ChooseAccent,
172+ K::LightColours,
173+ K::DarkColours,
174+ K::BackgroundLabel,
175+ K::ChooseBase,
174176 K::KindOpenIssue,
175177 K::KindClosedIssue,
176178 K::KindOpenPull,
@@ -289,8 +291,6 @@ pub fn t(lang: Lang, key: K) -> &'static str {
289291 (ThemeLabel, Tr) => "Tema",
290292 (LanguageLabel, En) => "Language",
291293 (LanguageLabel, Tr) => "Dil",
292- (ThemeAndLanguage, En) => "Theme and language",
293- (ThemeAndLanguage, Tr) => "Tema ve dil",
294294 (MatchSystemHelp, En) => {
295295 "Match the system follows your operating system's light or dark setting."
296296 }
@@ -311,18 +311,22 @@ pub fn t(lang: Lang, key: K) -> &'static str {
311311 (SwitchToDark, Tr) => "Koyu temaya geç",
312312 (SwitchToMatchSystem, En) => "Switch to match the system",
313313 (SwitchToMatchSystem, Tr) => "Sistem ile eşleştir moduna geç",
314- (AppearanceSaved, En) => "Appearance saved.",
315- (AppearanceSaved, Tr) => "Görünüm kaydedildi.",
316314 (ChooseTheme, En) => "Choose a theme from the list.",
317315 (ChooseTheme, Tr) => "Listeden bir tema seçin.",
318316 (ChooseLanguage, En) => "Choose a language from the list.",
319317 (ChooseLanguage, Tr) => "Listeden bir dil seçin.",
320318 (AccentLabel, En) => "Accent colour",
321319 (AccentLabel, Tr) => "Vurgu rengi",
322- (AccentHelp, En) => "Used for buttons, links and the activity heatmap.",
323- (AccentHelp, Tr) => "Düğmeler, bağlantılar ve etkinlik ısı haritası için kullanılır.",
324320 (ChooseAccent, En) => "Choose an accent colour from the list.",
325321 (ChooseAccent, Tr) => "Listeden bir vurgu rengi seçin.",
322+ (LightColours, En) => "Light theme",
323+ (LightColours, Tr) => "Açık tema",
324+ (DarkColours, En) => "Dark theme",
325+ (DarkColours, Tr) => "Koyu tema",
326+ (BackgroundLabel, En) => "Background",
327+ (BackgroundLabel, Tr) => "Arka plan",
328+ (ChooseBase, En) => "Choose a background from the list.",
329+ (ChooseBase, Tr) => "Listeden bir arka plan seçin.",
326330 (KindOpenIssue, En) => "Open issue",
327331 (KindOpenIssue, Tr) => "Açık sorun",
328332 (KindClosedIssue, En) => "Closed issue",
crates/forge-web/src/pages/settings_appearance.rsmodified+223 -89
@@ -1,6 +1,7 @@
1-//! Page: appearance (`/settings/appearance`). The colour theme, the accent colour and the language,
2-//! all stored per user. Anonymous visitors set the theme from the footer instead (see `pages/theme_cookie.rs`).
3-//! Every POST checks the CSRF token first.
1+//! Page: appearance (`/settings/appearance`). The colour theme, the language, and for each of the
2+//! light and dark themes a background and an accent colour, all stored per user. Every change
3+//! saves at once, so the form has no Save button. Anonymous visitors set the theme from the footer
4+//! instead (see `pages/theme_cookie.rs`). Every POST checks the CSRF token first.
45
56 use forge_core::AuditAction;
67 use forge_core::store::ui_prefs::THEMES;
@@ -10,15 +11,15 @@ use topcoat::Result;
1011 use topcoat::context::{Cx, app_context};
1112 use topcoat::router::content::Form;
1213 use topcoat::router::error::{SeeOther, see_other};
13-use topcoat::router::{page, query_params, route};
14+use topcoat::router::{page, route};
1415 use topcoat::view::{View, component, view};
1516
1617 use crate::accent;
1718 use crate::audit::{self, Actor, Target};
1819 use crate::auth::{require_csrf, require_user};
19-use crate::i18n::accents::accent_name;
20+use crate::i18n::accents::{accent_name, base_name};
2021 use crate::i18n::misc::{self as g, K};
21-use crate::i18n::{self, Key, Lang};
22+use crate::i18n::{self, Lang};
2223 use crate::state::AppState;
2324 use crate::views::shell;
2425
@@ -29,11 +30,6 @@ pub const LANGUAGE_CODES: &[&str] = &["auto", "en", "tr"];
2930 /// Theme codes, in display order.
3031 const THEME_CODES: &[&str] = &["auto", "light", "dark"];
3132
32-#[query_params(error = bad_request)]
33-struct AppearanceQuery {
34- saved: Option<String>,
35-}
36-
3733 /// Reads a field that is present as a string, even an empty one. The plain `Option<String>`
3834 /// reading would turn an empty value into `None`, which is the same as a missing field.
3935 fn present_string<'de, D: Deserializer<'de>>(
@@ -48,12 +44,19 @@ struct AppearanceForm {
4844 csrf: String,
4945 #[serde(default)]
5046 theme: String,
51- /// Optional so a form loaded before the accent picker existed still saves. When absent,
52- /// the stored accent is kept. A present but empty value stays `Some("")` and is rejected.
53- #[serde(default, deserialize_with = "present_string")]
54- accent: Option<String>,
5547 #[serde(default)]
5648 language: String,
49+ /// The four colour fields are optional so a form loaded before a field existed still saves.
50+ /// When a field is absent, its stored value is kept. A present but empty or unknown value
51+ /// stays `Some("")` or an unknown id, and is rejected.
52+ #[serde(default, deserialize_with = "present_string")]
53+ accent_light: Option<String>,
54+ #[serde(default, deserialize_with = "present_string")]
55+ accent_dark: Option<String>,
56+ #[serde(default, deserialize_with = "present_string")]
57+ base_light: Option<String>,
58+ #[serde(default, deserialize_with = "present_string")]
59+ base_dark: Option<String>,
5760 }
5861
5962 struct Choice {
@@ -62,13 +65,24 @@ struct Choice {
6265 selected: bool,
6366 }
6467
68+/// The colour choices of one theme: its background and its accent colour. `dark` picks the
69+/// field names and the swatch attributes that belong to the dark theme.
70+struct ColourGroup {
71+ dark: bool,
72+ heading: &'static str,
73+ background: &'static str,
74+ accent: &'static str,
75+ bases: Vec<Choice>,
76+ accents: Vec<Choice>,
77+}
78+
6579 struct AppearancePage {
6680 lang: Lang,
6781 csrf: String,
6882 theme: Vec<Choice>,
69- accents: Vec<Choice>,
7083 language: Vec<Choice>,
71- notice: Option<&'static str>,
84+ light: ColourGroup,
85+ dark: ColourGroup,
7286 }
7387
7488 /// The label of a language code. The two native names stay as they are in every language.
@@ -109,105 +123,177 @@ fn choices(
109123 .collect()
110124 }
111125
126+/// One theme's colour choices, with the stored (resolved) background and accent selected.
127+fn colour_group(lang: Lang, dark: bool, base: &str, accent_id: &str) -> ColourGroup {
128+ let base_codes: Vec<&'static str> = accent::base_ids().collect();
129+ let accent_codes: Vec<&'static str> = accent::ids().collect();
130+ ColourGroup {
131+ dark,
132+ heading: g::t(
133+ lang,
134+ if dark {
135+ K::DarkColours
136+ } else {
137+ K::LightColours
138+ },
139+ ),
140+ background: g::t(lang, K::BackgroundLabel),
141+ accent: g::t(lang, K::AccentLabel),
142+ bases: choices(&base_codes, base, |id| base_name(lang, id)),
143+ accents: choices(&accent_codes, accent_id, |id| accent_name(lang, id)),
144+ }
145+}
146+
147+#[component]
148+async fn colour_group_fields(group: ColourGroup) -> Result<impl View> {
149+ let ColourGroup {
150+ dark,
151+ heading,
152+ background,
153+ accent,
154+ bases,
155+ accents,
156+ } = group;
157+ let base_field = if dark { "base_dark" } else { "base_light" };
158+ let accent_field = if dark { "accent_dark" } else { "accent_light" };
159+ Ok(view! {
160+ <fieldset class="card colour-group">
161+ <legend>(heading)</legend>
162+ <fieldset class="colour-picker">
163+ <legend>(background)</legend>
164+ <div class="colour-choices">
165+ for choice in bases.into_iter() {
166+ <label class="colour-choice">
167+ <input type="radio" name=(base_field) value=(choice.value) checked=(choice.selected) data-autosubmit="true">
168+ if dark {
169+ <span class="base-swatch" data-base-dark-swatch=(choice.value) aria-hidden="true"></span>
170+ } else {
171+ <span class="base-swatch" data-base-light-swatch=(choice.value) aria-hidden="true"></span>
172+ }
173+ <span>(choice.label)</span>
174+ </label>
175+ }
176+ </div>
177+ </fieldset>
178+ <fieldset class="colour-picker">
179+ <legend>(accent)</legend>
180+ <div class="colour-choices">
181+ for choice in accents.into_iter() {
182+ <label class="colour-choice">
183+ <input type="radio" name=(accent_field) value=(choice.value) checked=(choice.selected) data-autosubmit="true">
184+ if dark {
185+ <span class="accent-swatch" data-accent-dark-swatch=(choice.value) aria-hidden="true"></span>
186+ } else {
187+ <span class="accent-swatch" data-accent-light-swatch=(choice.value) aria-hidden="true"></span>
188+ }
189+ <span>(choice.label)</span>
190+ </label>
191+ }
192+ </div>
193+ </fieldset>
194+ </fieldset>
195+ })
196+}
197+
112198 #[component]
113199 async fn appearance_body(page: AppearancePage) -> Result<impl View> {
114200 let AppearancePage {
115201 lang,
116202 csrf,
117203 theme,
118- accents,
119204 language,
120- notice,
205+ light,
206+ dark,
121207 } = page;
122208 Ok(view! {
123209 <div class="settings-layout">
124210 <section class="page-head">
125211 <h1>(g::t(lang, K::Appearance))</h1>
126212 </section>
127- if let Some(message) = notice {
128- <section class="card notice" role="status">
129- <p>(message)</p>
130- </section>
131- }
132- <section class="card">
133- <h2>(g::t(lang, K::ThemeAndLanguage))</h2>
134- <form method="post" action="/settings/appearance" class="stack">
135- <input type="hidden" name="csrf" value=(csrf.as_str())>
213+ <form method="post" action="/settings/appearance" class="appearance" data-appearance="true">
214+ <input type="hidden" name="csrf" value=(csrf.as_str())>
215+ <div class="appearance-top">
136216 <label>
137217 <span>(g::t(lang, K::ThemeLabel))</span>
138- <select name="theme">
218+ <select name="theme" data-autosubmit="true">
139219 for choice in theme.into_iter() {
140220 <option value=(choice.value) selected=(choice.selected)>(choice.label)</option>
141221 }
142222 </select>
143223 <small class="muted">(g::t(lang, K::MatchSystemHelp))</small>
144224 </label>
145- <fieldset class="accent-picker">
146- <legend>(g::t(lang, K::AccentLabel))</legend>
147- <div class="accent-choices">
148- for choice in accents.into_iter() {
149- <label class="accent-choice">
150- <input type="radio" name="accent" value=(choice.value) checked=(choice.selected)>
151- <span class="accent-swatch" data-accent-swatch=(choice.value) aria-hidden="true"></span>
152- <span>(choice.label)</span>
153- </label>
154- }
155- </div>
156- <small class="muted">(g::t(lang, K::AccentHelp))</small>
157- </fieldset>
158225 <label>
159226 <span>(g::t(lang, K::LanguageLabel))</span>
160- <select name="language">
227+ <select name="language" data-autosubmit="true">
161228 for choice in language.into_iter() {
162229 <option value=(choice.value) selected=(choice.selected)>(choice.label)</option>
163230 }
164231 </select>
165232 </label>
166- <button type="submit" class="primary">(i18n::t(lang, Key::Save))</button>
167- </form>
168- </section>
233+ </div>
234+ <div class="appearance-columns">
235+ colour_group_fields(group: light)
236+ colour_group_fields(group: dark)
237+ </div>
238+ </form>
169239 </div>
170240 })
171241 }
172242
173-/// Rejects a theme, accent or language that is not offered. Nothing is saved for any of them.
174-fn check_choice(
175- lang: Lang,
176- theme: &str,
177- accent_id: &str,
178- language: &str,
179-) -> forge_core::Result<()> {
243+/// Rejects a theme or a language that is not offered. Nothing is saved for either of them.
244+fn check_choice(lang: Lang, theme: &str, language: &str) -> forge_core::Result<()> {
180245 if !THEMES.contains(&theme) {
181246 return Err(CoreError::Invalid(g::t(lang, K::ChooseTheme).into()));
182247 }
183- if !accent::is_offered(accent_id) {
184- return Err(CoreError::Invalid(g::t(lang, K::ChooseAccent).into()));
185- }
186248 if !LANGUAGE_CODES.contains(&language) {
187249 return Err(CoreError::Invalid(g::t(lang, K::ChooseLanguage).into()));
188250 }
189251 Ok(())
190252 }
191253
192-fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> {
193- match saved {
194- Some("1") => Some(g::t(lang, K::AppearanceSaved)),
195- _ => None,
254+/// The accent a save stores for one theme. An absent field keeps the stored id. A present one
255+/// must be an offered accent, so an empty or unknown value is rejected.
256+fn accent_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {
257+ match posted {
258+ None => Ok(stored.to_owned()),
259+ Some(id) if accent::is_offered(id) => Ok(id.to_owned()),
260+ Some(_) => Err(CoreError::Invalid(g::t(lang, K::ChooseAccent).into())),
196261 }
197262 }
198263
199-/// Builds the page for a viewer. The theme, accent and language are the stored values.
200-fn page_for(viewer: &(User, Session), lang: Lang, notice: Option<&'static str>) -> AppearancePage {
201- let accent_codes: Vec<&'static str> = accent::ids().collect();
264+/// The background a save stores for one theme. An absent field keeps the stored id. A present
265+/// one must be an offered base, so an empty or unknown value is rejected.
266+fn base_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {
267+ match posted {
268+ None => Ok(stored.to_owned()),
269+ Some(id) if accent::is_offered_base(id) => Ok(id.to_owned()),
270+ Some(_) => Err(CoreError::Invalid(g::t(lang, K::ChooseBase).into())),
271+ }
272+}
273+
274+/// Builds the page for a viewer. Each choice shows the stored value, or the default when the
275+/// stored id is no longer offered, which is what the page renders on `<html>` too.
276+fn page_for(viewer: &(User, Session), lang: Lang) -> AppearancePage {
277+ let user = &viewer.0;
202278 AppearancePage {
203279 lang,
204280 csrf: viewer.1.csrf_token.clone(),
205- theme: choices(THEME_CODES, &viewer.0.theme, |code| theme_label(lang, code)),
206- accents: choices(&accent_codes, &viewer.0.accent, |id| accent_name(lang, id)),
207- language: choices(LANGUAGE_CODES, &viewer.0.language, |code| {
281+ theme: choices(THEME_CODES, &user.theme, |code| theme_label(lang, code)),
282+ language: choices(LANGUAGE_CODES, &user.language, |code| {
208283 language_label(lang, code)
209284 }),
210- notice,
285+ light: colour_group(
286+ lang,
287+ false,
288+ accent::resolve_base(&user.base_light).id,
289+ accent::resolve(&user.accent).id,
290+ ),
291+ dark: colour_group(
292+ lang,
293+ true,
294+ accent::resolve_base(&user.base_dark).id,
295+ accent::resolve(&user.accent_dark).id,
296+ ),
211297 }
212298 }
213299
@@ -215,8 +301,7 @@ fn page_for(viewer: &(User, Session), lang: Lang, notice: Option<&'static str>)
215301 async fn appearance_page(cx: &Cx) -> Result<impl View> {
216302 let viewer = require_user(cx).await?;
217303 let lang = i18n::lang(cx, Some(&viewer.0));
218- let saved = query_params::<AppearanceQuery>(cx)?.saved.clone();
219- let page = page_for(&viewer, lang, notice_for(lang, saved.as_deref()));
304+ let page = page_for(&viewer, lang);
220305 Ok(view! {
221306 shell(title: g::t(lang, K::Appearance), viewer: Some(&viewer), appearance_body(page: page))
222307 })
@@ -227,29 +312,46 @@ async fn appearance_save(cx: &Cx, Form(form): Form<AppearanceForm>) -> Result<Se
227312 let viewer = require_csrf(cx, &form.csrf).await?;
228313 let lang = i18n::lang(cx, Some(&viewer.0));
229314 let store: &Store = &app_context::<AppState>(cx).store;
315+ let user = &viewer.0;
230316
231- let accent = form.accent.as_deref().unwrap_or(&viewer.0.accent);
232- check_choice(lang, &form.theme, accent, &form.language)?;
317+ check_choice(lang, &form.theme, &form.language)?;
318+ let accent_light = accent_choice(lang, form.accent_light.as_deref(), &user.accent)?;
319+ let accent_dark = accent_choice(lang, form.accent_dark.as_deref(), &user.accent_dark)?;
320+ let base_light = base_choice(lang, form.base_light.as_deref(), &user.base_light)?;
321+ let base_dark = base_choice(lang, form.base_dark.as_deref(), &user.base_dark)?;
233322 store
234- .set_ui_prefs(&viewer.0.id, &form.theme, &form.language)
323+ .set_ui_prefs(&user.id, &form.theme, &form.language)
324+ .await?;
325+ store
326+ .set_colours(
327+ &user.id,
328+ &accent_light,
329+ &accent_dark,
330+ &base_light,
331+ &base_dark,
332+ )
235333 .await?;
236- if form.accent.is_some() {
237- store.set_accent(&viewer.0.id, accent).await?;
238- }
239334 audit::record(
240335 store,
241336 Some(cx),
242- Actor::User(&viewer.0),
337+ Actor::User(user),
243338 AuditAction::UiPrefsChanged,
244339 Target {
245340 kind: "user",
246- id: &viewer.0.id,
247- name: &viewer.0.username,
341+ id: &user.id,
342+ name: &user.username,
248343 },
249- serde_json::json!({ "theme": form.theme, "accent": accent, "language": form.language }),
344+ serde_json::json!({
345+ "theme": form.theme,
346+ "language": form.language,
347+ "accent_light": accent_light,
348+ "accent_dark": accent_dark,
349+ "base_light": base_light,
350+ "base_dark": base_dark,
351+ }),
250352 )
251353 .await;
252- Ok(see_other("/settings/appearance?saved=1"))
354+ Ok(see_other("/settings/appearance"))
253355 }
254356
255357 #[cfg(test)]
@@ -258,14 +360,35 @@ mod tests {
258360
259361 #[test]
260362 fn only_offered_choices_pass() {
261- assert!(check_choice(Lang::En, "dark", "ocean", "tr").is_ok());
262- assert!(check_choice(Lang::Tr, "auto", "sage", "auto").is_ok());
263- assert!(check_choice(Lang::En, "neon", "sage", "en").is_err());
264- assert!(check_choice(Lang::En, "light", "neon", "en").is_err());
265- assert!(check_choice(Lang::En, "light", "Ocean", "en").is_err());
266- assert!(check_choice(Lang::En, "light", "", "en").is_err());
267- assert!(check_choice(Lang::En, "light", "sage", "de").is_err());
268- assert!(check_choice(Lang::Tr, "light", "sage", "").is_err());
363+ assert!(check_choice(Lang::En, "dark", "tr").is_ok());
364+ assert!(check_choice(Lang::Tr, "auto", "auto").is_ok());
365+ assert!(check_choice(Lang::En, "neon", "en").is_err());
366+ assert!(check_choice(Lang::En, "light", "de").is_err());
367+ assert!(check_choice(Lang::Tr, "light", "").is_err());
368+ assert!(accent_choice(Lang::En, Some("ocean"), "sage").is_ok());
369+ assert!(accent_choice(Lang::En, Some("neon"), "sage").is_err());
370+ assert!(accent_choice(Lang::En, Some("Ocean"), "sage").is_err());
371+ assert!(accent_choice(Lang::En, Some(""), "sage").is_err());
372+ assert!(base_choice(Lang::En, Some("ink"), "fern").is_ok());
373+ assert!(base_choice(Lang::En, Some("neon"), "fern").is_err());
374+ assert!(base_choice(Lang::En, Some(""), "fern").is_err());
375+ }
376+
377+ #[test]
378+ fn an_absent_colour_keeps_the_stored_value() {
379+ assert_eq!(accent_choice(Lang::En, None, "plum").unwrap(), "plum");
380+ assert_eq!(base_choice(Lang::En, None, "mist").unwrap(), "mist");
381+ }
382+
383+ #[test]
384+ fn a_rejected_colour_says_what_to_choose() {
385+ let accent_err = accent_choice(Lang::En, Some("neon"), "sage").unwrap_err();
386+ assert!(
387+ accent_err.to_string().contains("accent colour"),
388+ "{accent_err}"
389+ );
390+ let base_err = base_choice(Lang::En, Some("neon"), "fern").unwrap_err();
391+ assert!(base_err.to_string().contains("background"), "{base_err}");
269392 }
270393
271394 #[test]
@@ -280,7 +403,7 @@ mod tests {
280403 }
281404
282405 #[test]
283- fn the_stored_accent_is_selected() {
406+ fn the_stored_accent_and_base_are_selected() {
284407 let codes: Vec<&'static str> = accent::ids().collect();
285408 let options = choices(&codes, "plum", |id| accent_name(Lang::En, id));
286409 let selected: Vec<&str> = options
@@ -290,12 +413,23 @@ mod tests {
290413 .collect();
291414 assert_eq!(selected, ["plum"]);
292415 assert_eq!(options[0].value, crate::accent_palette::DEFAULT);
416+
417+ let group = colour_group(Lang::En, true, "ink", "plum");
418+ let bases: Vec<&str> = group
419+ .bases
420+ .iter()
421+ .filter(|c| c.selected)
422+ .map(|c| c.value)
423+ .collect();
424+ assert_eq!(bases, ["ink"]);
425+ assert_eq!(group.bases[0].value, crate::accent_palette::BASE_DEFAULT);
293426 }
294427
295428 #[test]
296429 fn labels_follow_the_page_language() {
297430 assert_eq!(theme_label(Lang::En, "dark"), "Dark");
298431 assert_eq!(theme_label(Lang::Tr, "dark"), "Koyu");
432+ assert_eq!(base_name(Lang::Tr, "ink"), "M\u{fc}rekkep");
299433 }
300434
301435 #[test]
crates/forge-web/src/views/mod.rsmodified+51 -22
@@ -161,12 +161,28 @@ pub async fn shell(
161161 let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned());
162162 let lang = i18n::lang(__cx, viewer.map(|(user, _)| user));
163163 let theme_attr = crate::theme::data_theme(__cx, viewer.map(|(user, _)| user));
164- // Always set, sage included, so a page never keeps the accent of the one before it.
165- let stored_accent = match viewer {
166- Some((user, _)) => user.accent.as_str(),
167- None => crate::accent_palette::DEFAULT,
168- };
169- let accent_id = crate::accent::resolve(stored_accent).id;
164+ // Always set, defaults included, so a page never keeps the colours of the one before it.
165+ // Each of the four choices is resolved on its own, so an id that is no longer offered falls
166+ // back to its default.
167+ let (stored_accent_light, stored_accent_dark, stored_base_light, stored_base_dark) =
168+ match viewer {
169+ Some((user, _)) => (
170+ user.accent.as_str(),
171+ user.accent_dark.as_str(),
172+ user.base_light.as_str(),
173+ user.base_dark.as_str(),
174+ ),
175+ None => (
176+ crate::accent_palette::DEFAULT,
177+ crate::accent_palette::DEFAULT,
178+ crate::accent_palette::BASE_DEFAULT,
179+ crate::accent_palette::BASE_DEFAULT,
180+ ),
181+ };
182+ let accent_light_id = crate::accent::resolve(stored_accent_light).id;
183+ let accent_dark_id = crate::accent::resolve(stored_accent_dark).id;
184+ let base_light_id = crate::accent::resolve_base(stored_base_light).id;
185+ let base_dark_id = crate::accent::resolve_base(stored_base_dark).id;
170186 // The stored preference, "auto" included, drives the button: its icon, its label and the
171187 // value it posts (the next preference in the cycle auto, light, dark).
172188 let theme_pref = crate::theme::preference(__cx, viewer.map(|(user, _)| user));
@@ -196,7 +212,7 @@ pub async fn shell(
196212 let unread_aside = unread_badge.clone();
197213 Ok(view! {
198214 <!DOCTYPE html>
199- <html lang=(lang.code()) data-theme=(theme_attr) data-accent=(accent_id)>
215+ <html lang=(lang.code()) data-theme=(theme_attr) data-accent-light=(accent_light_id) data-accent-dark=(accent_dark_id) data-base-light=(base_light_id) data-base-dark=(base_dark_id)>
200216 <head>
201217 <meta charset="utf-8">
202218 <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -962,8 +978,9 @@ mod shell_tests {
962978 &page[at..at + len + 1]
963979 }
964980
965- /// The `<html>` tag of `/settings/sessions` for a signed-in user whose stored accent is `accent`.
966- async fn html_tag_for_accent(accent: &str) -> String {
981+ /// The `<html>` tag of `/settings/sessions` for a signed-in user whose stored colours are the
982+ /// four ids given, in the order light accent, dark accent, light base, dark base.
983+ async fn html_tag_for_colours(colours: [&str; 4]) -> String {
967984 use crate::auth::SESSION_COOKIE;
968985 let dir = tempfile::tempdir().expect("tempdir");
969986 let state = crate::test_support::test_state(dir.path()).await;
@@ -973,12 +990,16 @@ mod shell_tests {
973990 .create_user("tahinli", None, "x", false)
974991 .await
975992 .expect("user");
976- store.set_accent(&user.id, accent).await.expect("accent");
977- crate::test_support::create_session(&store, &user.id, "accent-token", "accent-csrf").await;
993+ let [accent_light, accent_dark, base_light, base_dark] = colours;
994+ store
995+ .set_colours(&user.id, accent_light, accent_dark, base_light, base_dark)
996+ .await
997+ .expect("colours");
998+ crate::test_support::create_session(&store, &user.id, "colour-token", "colour-csrf").await;
978999 let req = Request::builder()
9791000 .method("GET")
9801001 .uri("/settings/sessions")
981- .header("cookie", format!("__Host-{SESSION_COOKIE}=accent-token"))
1002+ .header("cookie", format!("__Host-{SESSION_COOKIE}=colour-token"))
9821003 .body(Body::empty())
9831004 .unwrap();
9841005 let res = router.handle(req).await;
@@ -988,18 +1009,23 @@ mod shell_tests {
9881009 }
9891010
9901011 #[tokio::test]
991- async fn the_html_tag_carries_the_viewers_accent() {
992- let ocean = html_tag_for_accent("ocean").await;
993- assert!(ocean.contains("data-accent=\"ocean\""), "{ocean}");
994- let sage = html_tag_for_accent("sage").await;
995- assert!(sage.contains("data-accent=\"sage\""), "{sage}");
996- // A stored id that is no longer offered falls back to the default, never to nothing.
997- let removed = html_tag_for_accent("removed-palette").await;
998- assert!(removed.contains("data-accent=\"sage\""), "{removed}");
1012+ async fn the_html_tag_carries_the_viewers_colours() {
1013+ let tag = html_tag_for_colours(["ocean", "plum", "ink", "mist"]).await;
1014+ assert!(tag.contains("data-accent-light=\"ocean\""), "{tag}");
1015+ assert!(tag.contains("data-accent-dark=\"plum\""), "{tag}");
1016+ assert!(tag.contains("data-base-light=\"ink\""), "{tag}");
1017+ assert!(tag.contains("data-base-dark=\"mist\""), "{tag}");
1018+ assert!(!tag.contains("data-accent="), "{tag}");
1019+ // Stored ids that are no longer offered fall back to the defaults, never to nothing.
1020+ let removed = html_tag_for_colours(["removed-palette", "removed-palette", "x", "x"]).await;
1021+ assert!(removed.contains("data-accent-light=\"sage\""), "{removed}");
1022+ assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}");
1023+ assert!(removed.contains("data-base-light=\"fern\""), "{removed}");
1024+ assert!(removed.contains("data-base-dark=\"fern\""), "{removed}");
9991025 }
10001026
10011027 #[tokio::test]
1002- async fn anonymous_pages_render_the_default_accent() {
1028+ async fn anonymous_pages_render_the_default_colours() {
10031029 let dir = tempfile::tempdir().expect("tempdir");
10041030 let state = crate::test_support::test_state(dir.path()).await;
10051031 let router = crate::test_support::app_router(state);
@@ -1012,6 +1038,9 @@ mod shell_tests {
10121038 let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
10131039 let html = String::from_utf8_lossy(&bytes);
10141040 let tag = html_tag(&html);
1015- assert!(tag.contains("data-accent=\"sage\""), "{tag}");
1041+ assert!(tag.contains("data-accent-light=\"sage\""), "{tag}");
1042+ assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}");
1043+ assert!(tag.contains("data-base-light=\"fern\""), "{tag}");
1044+ assert!(tag.contains("data-base-dark=\"fern\""), "{tag}");
10161045 }
10171046 }
crates/forge-web/tests/ui_prefs_e2e.rsmodified+127 -49
@@ -110,10 +110,31 @@ fn html_theme(body: &str) -> Option<String> {
110110 doc.root_element().attr("data-theme").map(str::to_owned)
111111 }
112112
113-/// The `data-accent` attribute of `<html>`.
114-fn html_accent(body: &str) -> Option<String> {
113+/// The value of attribute `name` on `<html>`, if the page sets it.
114+fn html_attr(body: &str, name: &str) -> Option<String> {
115115 let doc = scraper::Html::parse_document(body);
116- doc.root_element().attr("data-accent").map(str::to_owned)
116+ doc.root_element().attr(name).map(str::to_owned)
117+}
118+
119+/// The four colour attributes of `<html>`, in the order light accent, dark accent, light base,
120+/// dark base.
121+fn html_colours(body: &str) -> [Option<String>; 4] {
122+ [
123+ html_attr(body, "data-accent-light"),
124+ html_attr(body, "data-accent-dark"),
125+ html_attr(body, "data-base-light"),
126+ html_attr(body, "data-base-dark"),
127+ ]
128+}
129+
130+/// The checked radio of each colour group, in the same order as `html_colours`.
131+fn checked_colours(body: &str) -> [Option<String>; 4] {
132+ [
133+ checked_radio(body, "accent_light"),
134+ checked_radio(body, "accent_dark"),
135+ checked_radio(body, "base_light"),
136+ checked_radio(body, "base_dark"),
137+ ]
117138 }
118139
119140 /// 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() {
246267 .http
247268 .post_form(
248269 "/settings/appearance",
249- &[
250- ("csrf", &csrf),
251- ("theme", "dark"),
252- ("accent", "sage"),
253- ("language", "tr"),
254- ],
270+ &[("csrf", &csrf), ("theme", "dark"), ("language", "tr")],
255271 Some(&session),
256272 )
257273 .await;
258274 assert_eq!(saved.status, 303, "save: {}", saved.body);
259275 assert_eq!(
260276 saved.header(reqwest::header::LOCATION).as_deref(),
261- Some("/settings/appearance?saved=1")
277+ Some("/settings/appearance"),
278+ "a save redirects back with no saved notice"
262279 );
263280
264- let page = env
265- .http
266- .get("/settings/appearance?saved=1", Some(&session))
267- .await;
281+ let page = env.http.get("/settings/appearance", Some(&session)).await;
268282 assert_eq!(
269283 selected_option(&page.body, "theme").as_deref(),
270284 Some("dark")
@@ -273,29 +287,48 @@ async fn appearance_setting_persists_and_renders_the_html_attribute() {
273287 selected_option(&page.body, "language").as_deref(),
274288 Some("tr")
275289 );
290+ assert_eq!(html_theme(&page.body).as_deref(), Some("dark"));
291+}
276292
277- let home = env.http.get("/settings/appearance", Some(&session)).await;
278- assert_eq!(html_theme(&home.body).as_deref(), Some("dark"));
279-
293+#[tokio::test]
294+async fn the_form_has_no_save_button_and_every_field_autosubmits() {
295+ let env = start().await;
296+ let session = login(&env.http, "tahinli").await;
280297 let page = env.http.get("/settings/appearance", Some(&session)).await;
281- assert_eq!(
282- selected_option(&page.body, "theme").as_deref(),
283- Some("dark")
284- );
285- assert_eq!(
286- selected_option(&page.body, "language").as_deref(),
287- Some("tr")
288- );
298+ let doc = scraper::Html::parse_document(&page.body);
299+
300+ let form = scraper::Selector::parse("form[data-appearance]").expect("selector");
301+ assert_eq!(doc.select(&form).count(), 1, "one appearance form");
302+ let buttons = scraper::Selector::parse("form[data-appearance] button").expect("selector");
303+ assert_eq!(doc.select(&buttons).count(), 0, "no Save button");
304+ let submits =
305+ scraper::Selector::parse("form[data-appearance] input[type=\"submit\"]").expect("selector");
306+ assert_eq!(doc.select(&submits).count(), 0, "no submit input");
307+
308+ let fields =
309+ scraper::Selector::parse("form[data-appearance] input, form[data-appearance] select")
310+ .expect("selector");
311+ for field in doc.select(&fields) {
312+ if field.value().attr("type") == Some("hidden") {
313+ continue;
314+ }
315+ assert!(
316+ field.value().attr("data-autosubmit").is_some(),
317+ "{:?} does not autosubmit",
318+ field.value().attr("name")
319+ );
320+ }
289321 }
290322
291323 #[tokio::test]
292-async fn accent_setting_persists_and_renders_the_html_attribute() {
324+async fn light_and_dark_colours_save_independently_and_render_on_html() {
293325 let env = start().await;
294326 let session = login(&env.http, "tahinli").await;
295327
296328 let page = env.http.get("/settings/appearance", Some(&session)).await;
297- assert_eq!(checked_radio(&page.body, "accent").as_deref(), Some("sage"));
298- assert_eq!(html_accent(&page.body).as_deref(), Some("sage"));
329+ let defaults = ["sage", "sage", "fern", "fern"].map(str::to_owned);
330+ assert_eq!(checked_colours(&page.body), defaults.clone().map(Some));
331+ assert_eq!(html_colours(&page.body), defaults.map(Some));
299332 let csrf = input_value(&page.body, "csrf");
300333
301334 let saved = env
@@ -305,8 +338,11 @@ async fn accent_setting_persists_and_renders_the_html_attribute() {
305338 &[
306339 ("csrf", &csrf),
307340 ("theme", "light"),
308- ("accent", "ocean"),
309341 ("language", "en"),
342+ ("accent_light", "ocean"),
343+ ("accent_dark", "plum"),
344+ ("base_light", "ink"),
345+ ("base_dark", "mist"),
310346 ],
311347 Some(&session),
312348 )
@@ -314,43 +350,85 @@ async fn accent_setting_persists_and_renders_the_html_attribute() {
314350 assert_eq!(saved.status, 303, "save: {}", saved.body);
315351
316352 let page = env.http.get("/settings/appearance", Some(&session)).await;
317- assert_eq!(
318- checked_radio(&page.body, "accent").as_deref(),
319- Some("ocean")
320- );
321- assert_eq!(html_accent(&page.body).as_deref(), Some("ocean"));
353+ let chosen = ["ocean", "plum", "ink", "mist"].map(str::to_owned);
354+ assert_eq!(checked_colours(&page.body), chosen.clone().map(Some));
355+ assert_eq!(html_colours(&page.body), chosen.map(Some));
356+
357+ // A single field changes on its own; the other three keep their values.
358+ let saved = env
359+ .http
360+ .post_form(
361+ "/settings/appearance",
362+ &[
363+ ("csrf", &csrf),
364+ ("theme", "light"),
365+ ("language", "en"),
366+ ("base_dark", "sand"),
367+ ],
368+ Some(&session),
369+ )
370+ .await;
371+ assert_eq!(saved.status, 303, "save: {}", saved.body);
372+ let page = env.http.get("/settings/appearance", Some(&session)).await;
373+ let chosen = ["ocean", "plum", "ink", "sand"].map(str::to_owned);
374+ assert_eq!(checked_colours(&page.body), chosen.clone().map(Some));
375+ assert_eq!(html_colours(&page.body), chosen.map(Some));
322376
323377 // Malformed or unknown ids change nothing.
324- for accent in ["Ocean", "../x", "neon", ""] {
378+ for (field, bad) in [
379+ ("accent_light", "Ocean"),
380+ ("accent_dark", "../x"),
381+ ("accent_dark", "neon"),
382+ ("accent_light", ""),
383+ ("base_light", "neon"),
384+ ("base_dark", ""),
385+ ] {
325386 let form = [
326387 ("csrf", csrf.as_str()),
327388 ("theme", "light"),
328389 ("language", "en"),
329- ("accent", accent),
390+ (field, bad),
330391 ];
331392 let res = env
332393 .http
333394 .post_form("/settings/appearance", &form, Some(&session))
334395 .await;
335- assert_ne!(res.status, 303, "bad accent {accent:?} must not save");
396+ assert_ne!(res.status, 303, "bad {field} {bad:?} must not save");
336397 }
337398 let page = env.http.get("/settings/appearance", Some(&session)).await;
338- assert_eq!(
339- checked_radio(&page.body, "accent").as_deref(),
340- Some("ocean")
341- );
342- assert_eq!(html_accent(&page.body).as_deref(), Some("ocean"));
399+ let chosen = ["ocean", "plum", "ink", "sand"].map(str::to_owned);
400+ assert_eq!(checked_colours(&page.body), chosen.clone().map(Some));
401+ assert_eq!(html_colours(&page.body), chosen.map(Some));
343402 }
344403
345404 #[tokio::test]
346-async fn appearance_save_without_accent_keeps_the_stored_accent() {
405+async fn a_save_without_colour_fields_keeps_the_stored_colours() {
347406 let env = start().await;
348407 let session = login(&env.http, "tahinli").await;
349408
350409 let page = env.http.get("/settings/appearance", Some(&session)).await;
351410 let csrf = input_value(&page.body, "csrf");
352- let before = checked_radio(&page.body, "accent");
353- assert!(before.is_some(), "an accent is always selected");
411+ let saved = env
412+ .http
413+ .post_form(
414+ "/settings/appearance",
415+ &[
416+ ("csrf", &csrf),
417+ ("theme", "light"),
418+ ("language", "en"),
419+ ("accent_light", "rose"),
420+ ("accent_dark", "slate"),
421+ ("base_light", "sand"),
422+ ("base_dark", "stone"),
423+ ],
424+ Some(&session),
425+ )
426+ .await;
427+ assert_eq!(saved.status, 303, "save: {}", saved.body);
428+ let before = env.http.get("/settings/appearance", Some(&session)).await;
429+ let stored = ["rose", "slate", "sand", "stone"].map(str::to_owned);
430+ assert_eq!(html_colours(&before.body), stored.clone().map(Some));
431+
354432 let saved = env
355433 .http
356434 .post_form(
@@ -359,15 +437,15 @@ async fn appearance_save_without_accent_keeps_the_stored_accent() {
359437 Some(&session),
360438 )
361439 .await;
362- assert_eq!(saved.status, 303, "save without accent: {}", saved.body);
440+ assert_eq!(saved.status, 303, "save without colours: {}", saved.body);
363441
364442 let page = env.http.get("/settings/appearance", Some(&session)).await;
365443 assert_eq!(
366444 selected_option(&page.body, "theme").as_deref(),
367445 Some("dark")
368446 );
369- assert_eq!(checked_radio(&page.body, "accent"), before);
370- assert_eq!(html_accent(&page.body), before);
447+ assert_eq!(checked_colours(&page.body), stored.clone().map(Some));
448+ assert_eq!(html_colours(&page.body), stored.map(Some));
371449 }
372450
373451 #[tokio::test]
@@ -505,7 +583,7 @@ async fn signed_in_toggle_saves_the_preference_and_returns_to_back() {
505583 &[
506584 ("csrf", &csrf),
507585 ("theme", "auto"),
508- ("accent", "sage"),
586+ ("accent_light", "sage"),
509587 ("language", "tr"),
510588 ],
511589 Some(&session),
style/main.scssmodified+71 -51
@@ -60,19 +60,13 @@
6060 }
6161
6262 // Accent tokens (light and dark) are generated into _accents.scss from src/accent_palette.rs.
63-// They are imported here so they keep their place in the cascade; the neutral tokens follow.
63+// They are imported here so they keep their place in the cascade; the other tokens follow.
6464 @import "accents";
6565
66-// The neutral dark values are repeated in the two dark blocks below and must stay identical.
66+// The neutral tokens (--bg, --surface, --text and so on) are not here: they come from the
67+// generated _accents.scss, one block per base in src/accent_palette.rs. Only the tokens that are
68+// the same for every base stay below.
6769 :root {
68- --bg: #F6F8F5;
69- --surface: #FFFFFF;
70- --surface-2: #EEF2EC;
71- --text: #1E2420;
72- --text-2: #3A433D;
73- --muted: #69736B;
74- --border: #DDE3DB;
75- --border-strong: #C5CFC3;
7670 --ok: #1D7A62;
7771 --warn: #9A6200;
7872 --bad: #B0413A;
@@ -81,16 +75,12 @@
8175 --danger-bg: #F8E1DE;
8276 --alert-bg: #F8E1DE;
8377 --alert-text: #7D2B25;
84- --code-bg: #EEF2EC;
85- --private-bg: #EEF2EC;
86- --private-text: #3A433D;
8778 --add-bg: #DCF2EA;
8879 --add-text: #174D3F;
8980 --add-mark: #1D7A62;
9081 --del-bg: #F8E1DE;
9182 --del-text: #7D2B25;
9283 --del-mark: #B0413A;
93- --ln-text: #69736B;
9484 --row-target: #FFF4C2;
9585 --tip: #1D7A62;
9686 --important: #6A4BB0;
@@ -102,20 +92,12 @@
10292 --topbar-h: 52px;
10393 --sidebar-w: 232px;
10494 color-scheme: light;
105- // Native checkboxes, radios and progress bars pick up the sage accent in every browser.
95+ // Native checkboxes, radios and progress bars pick up the chosen accent in every browser.
10696 accent-color: var(--accent);
10797 }
10898
10999 @media (prefers-color-scheme: dark) {
110100 :root:not([data-theme="light"]) {
111- --bg: #121613;
112- --surface: #191E1A;
113- --surface-2: #1F261F;
114- --text: #E3E8E2;
115- --text-2: #C4CCC3;
116- --muted: #97A198;
117- --border: #2A322C;
118- --border-strong: #3A443C;
119101 --ok: #7CCBAE;
120102 --warn: #E6B765;
121103 --bad: #F09A90;
@@ -124,16 +106,12 @@
124106 --danger-bg: #3A1E1C;
125107 --alert-bg: #3A1E1C;
126108 --alert-text: #F2B8B0;
127- --code-bg: #1F261F;
128- --private-bg: #1F261F;
129- --private-text: #C4CCC3;
130109 --add-bg: #143029;
131110 --add-text: #A6E3CF;
132111 --add-mark: #7CCBAE;
133112 --del-bg: #3A1E1C;
134113 --del-text: #F2B8B0;
135114 --del-mark: #F09A90;
136- --ln-text: #97A198;
137115 --row-target: #3A3510;
138116 --tip: #7CCBAE;
139117 --important: #C4A7FF;
@@ -148,14 +126,6 @@
148126 }
149127
150128 :root[data-theme="dark"] {
151- --bg: #121613;
152- --surface: #191E1A;
153- --surface-2: #1F261F;
154- --text: #E3E8E2;
155- --text-2: #C4CCC3;
156- --muted: #97A198;
157- --border: #2A322C;
158- --border-strong: #3A443C;
159129 --ok: #7CCBAE;
160130 --warn: #E6B765;
161131 --bad: #F09A90;
@@ -164,16 +134,12 @@
164134 --danger-bg: #3A1E1C;
165135 --alert-bg: #3A1E1C;
166136 --alert-text: #F2B8B0;
167- --code-bg: #1F261F;
168- --private-bg: #1F261F;
169- --private-text: #C4CCC3;
170137 --add-bg: #143029;
171138 --add-text: #A6E3CF;
172139 --add-mark: #7CCBAE;
173140 --del-bg: #3A1E1C;
174141 --del-text: #F2B8B0;
175142 --del-mark: #F09A90;
176- --ln-text: #97A198;
177143 --row-target: #3A3510;
178144 --tip: #7CCBAE;
179145 --important: #C4A7FF;
@@ -1857,12 +1823,55 @@ code {
18571823 max-width: 24rem;
18581824 }
18591825
1860-// Accent picker (appearance settings). Each choice is a native radio, so the keyboard and screen
1826+// Colour pickers (appearance settings). Each choice is a native radio, so the keyboard and screen
18611827 // readers work as usual; the swatch beside it shows the colour. The swatch colours come from the
1862-// generated _accents.scss, so nothing here names a colour.
1863-.accent-picker {
1828+// generated _accents.scss, so nothing here names a colour. The two themes sit side by side, and
1829+// stack on narrow screens, so the whole page fits a laptop window without a long scroll.
1830+.appearance {
18641831 display: grid;
1865- gap: 8px;
1832+ gap: 16px;
1833+ min-width: 0;
1834+}
1835+
1836+.appearance-top {
1837+ display: flex;
1838+ flex-wrap: wrap;
1839+ gap: 16px 24px;
1840+
1841+ label {
1842+ display: grid;
1843+ gap: 4px;
1844+ min-width: 0;
1845+ }
1846+}
1847+
1848+.appearance-columns {
1849+ display: grid;
1850+ grid-template-columns: repeat(2, minmax(0, 1fr));
1851+ gap: 16px;
1852+ min-width: 0;
1853+
1854+ @media (max-width: 720px) {
1855+ grid-template-columns: minmax(0, 1fr);
1856+ }
1857+}
1858+
1859+.colour-group {
1860+ display: grid;
1861+ gap: 14px;
1862+ min-width: 0;
1863+ margin: 0;
1864+
1865+ legend {
1866+ padding: 0;
1867+ margin-bottom: 4px;
1868+ font-weight: 600;
1869+ }
1870+}
1871+
1872+.colour-picker {
1873+ display: grid;
1874+ gap: 6px;
18661875 min-width: 0;
18671876 margin: 0;
18681877 padding: 0;
@@ -1870,18 +1879,19 @@ code {
18701879
18711880 legend {
18721881 padding: 0;
1873- margin-bottom: 6px;
1874- font-weight: 600;
1882+ margin-bottom: 2px;
1883+ font-size: 0.875rem;
1884+ color: var(--muted);
18751885 }
18761886 }
18771887
1878-.accent-choices {
1888+.colour-choices {
18791889 display: flex;
18801890 flex-wrap: wrap;
1881- gap: 10px 18px;
1891+ gap: 8px 14px;
18821892 }
18831893
1884-.accent-choice {
1894+.colour-choice {
18851895 display: inline-flex;
18861896 align-items: center;
18871897 gap: 8px;
@@ -1896,17 +1906,20 @@ code {
18961906 opacity: 0;
18971907 }
18981908
1899- input:focus-visible + .accent-swatch {
1909+ input:focus-visible + .accent-swatch,
1910+ input:focus-visible + .base-swatch {
19001911 outline: 2px solid var(--focus);
19011912 outline-offset: 3px;
19021913 }
19031914
1904- input:checked + .accent-swatch {
1915+ input:checked + .accent-swatch,
1916+ input:checked + .base-swatch {
19051917 box-shadow: 0 0 0 2px var(--surface), 0 0 0 4px var(--focus);
19061918 }
19071919 }
19081920
1909-.accent-swatch {
1921+.accent-swatch,
1922+.base-swatch {
19101923 display: inline-block;
19111924 flex: none;
19121925 width: 28px;
@@ -1915,6 +1928,13 @@ code {
19151928 border: 1px solid var(--border-strong);
19161929 }
19171930
1931+// A background swatch is split light and dark, so a pale one needs its own outline to show on a
1932+// pale page.
1933+.base-swatch {
1934+ outline: 1px solid var(--border-strong);
1935+ outline-offset: 1px;
1936+}
1937+
19181938 // branch protection
19191939 // Settings page: rules table with a Remove form per row, then the add/update form.
19201940 .branch-rules {