diff --git a/Cargo.lock b/Cargo.lock index 10c2125..6bc6aab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5063,6 +5063,7 @@ dependencies = [ "dioxus-core", "dioxus-native", "dioxus-web", + "js-sys", "keyboard-types", "unit", ] diff --git a/README.md b/README.md index 3e5aed7..04a5f4c 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ unit = { git = "https://github.com/diaryx-org/unit", branch = "main" } | Icons | `Icon`: a path on a 24-unit grid stroked in `currentColor`, the text's or an `Ink` of the theme's; `icon::paths` | | Choices | `Checkbox`, `Switch`, `RadioGroup`, `Segmented`, `Slider`, `Chips` (each with a colour's dot and a count, if it has them; or `single`, a radio group drawn as pills) | | Text | `TextField` (text, search, email, URL, password, number; with an `action` at its end, pressed by Return too), `TextArea`, `CodeField` (a one-time code: a cell for each digit, one field to assistive tech, a whole code pasted or filled in at once) | -| Menus | `MenuButton`, `Select`, `ContextMenu` (the secondary button, or a finger held); items with shortcuts, ticks, icons, separators, submenus, and destructive ones | +| Menus | `MenuButton`, `Select`, `ContextMenu` (the secondary button, or a finger held); items with shortcuts, ticks, icons, separators, submenus, and destructive ones; a `palette`, a few items side by side in one row (Copy, Share, Delete; or Reflow, Pages, Source, ticked where they stand), which keeps a long menu short | | Lists | `Section` (rows under a caption), `Row` (icon, title, subtitle, a note under it, value, a chevron or a tick, a control at the right, set in by a `depth`) | | Navigation | `Tabs`, `ListBox` (arrows, Home, End, typeahead), `Disclosure`, `NavBar` (back, forward, a title to press), `TabBar` (with a button of its own at the end), `Tree` and `TreeRow` | | Collections | `TileGrid` (a folder's icons, a library of photos: tiles of a fixed size or stretched to `fill` the row, with or without `labels`, under `section` headings, some not to be chosen, each with a button of its own) and `Table` (rows under column titles that sort), each choosing as a file browser does into a `Selection` the page keeps: a press alone, ⌘ or Ctrl to add, Shift for a range, the arrows, ⌘A, Space, Return or a double click to open, a letter to jump, a menu on the selection; on a phone a tap opens, or puts in and out while it `toggles` | @@ -39,7 +39,7 @@ unit = { git = "https://github.com/diaryx-org/unit", branch = "main" } | Overlays | `Unit::open_dialog` (alerts, confirmations, a prompt), `Unit::open_actions` (an action sheet), `Modal` and its `Sheet` placement (a sheet along the bottom on a phone held upright, with Cancel and Done and dragged down to close, and a card in the middle of a wider window; `BottomSheet` for a sheet everywhere), `Unit::toast` (until dismissed, or for as long as it `lasts`) | | Gestures | `LongPress` and `use_hold`: a finger held still, timed by the host's sleep (`Unit::set_timer`) | | Layout | `Stack`, `Spacer`, `Card`, `Divider`, `Field` (a form's row), `Heading`, `Text`, `Badge`, `Progress`, `Callout` | -| Theme | `Theme`: a light and a dark `Palette`, a pointer's and a finger's `Metrics`, and a text and a heading font, written as CSS custom properties; `Appearance`, `Density` and `Accent` on the root | +| Theme | `Theme`: a light and a dark `Palette`, a pointer's and a finger's `Metrics` (corners among them), a `Shape` (edges, pills, shadows, how a menu's rows sit), and a text and a heading font, written as CSS custom properties; `Appearance`, `Density` and `Accent` on the root. Three ship: `Theme::default()` (Unit), `Theme::soft()` (Diaryx's: warm, round, faces by fill) and `Theme::sharp()` (square and ruled); the gallery switches between them, and `?theme=soft` opens it in one | Its component list and its theme of tokens take after [Libero](https://github.com/tdymel/libero)'s; how it is built does not. diff --git a/gallery/Cargo.toml b/gallery/Cargo.toml index 943d8da..1c1a743 100644 --- a/gallery/Cargo.toml +++ b/gallery/Cargo.toml @@ -43,3 +43,7 @@ blitz-traits = "=0.3.0-beta.4" accesskit = "0.25" atomic_refcell = "0.1" keyboard-types = "0.8" + +# The page's address on the web, for a theme asked for in it (`?theme=soft`). +[target.'cfg(target_arch = "wasm32")'.dependencies] +js-sys = "0.3" diff --git a/gallery/audit.baseline b/gallery/audit.baseline index 753740a..98aec10 100644 --- a/gallery/audit.baseline +++ b/gallery/audit.baseline @@ -55,12 +55,12 @@ edge-contrast light/touch/390 unit-input.unit-textarea edge-contrast light/touch/390 unit-radio-ring edge-contrast light/touch/390 unit-slider-line edge-contrast light/touch/390 unit-switch-track -focus-ring dark/regular/1200 RadioGroup:Appearance -focus-ring dark/touch/320 RadioGroup:Appearance -focus-ring dark/touch/390 RadioGroup:Appearance -focus-ring light/regular/1200 RadioGroup:Appearance -focus-ring light/touch/320 RadioGroup:Appearance -focus-ring light/touch/390 RadioGroup:Appearance +focus-ring dark/regular/1200 RadioGroup:Theme +focus-ring dark/touch/320 RadioGroup:Theme +focus-ring dark/touch/390 RadioGroup:Theme +focus-ring light/regular/1200 RadioGroup:Theme +focus-ring light/touch/320 RadioGroup:Theme +focus-ring light/touch/390 RadioGroup:Theme keyboard dark/regular/1200 Button:Italic keyboard dark/touch/320 Button:Italic keyboard dark/touch/390 Button:Italic diff --git a/gallery/src/lib.rs b/gallery/src/lib.rs index ad6b0a2..4c8ac6d 100644 --- a/gallery/src/lib.rs +++ b/gallery/src/lib.rs @@ -17,6 +17,8 @@ const DELETE: usize = 12; const OPEN: usize = 20; const RENAME: usize = 21; const TRASH: usize = 22; +const COPY_FILE: usize = 23; +const SHARE_FILE: usize = 24; /// The page, at the appearance and density the page itself chooses. #[allow(non_snake_case)] @@ -24,11 +26,40 @@ pub fn Gallery() -> Element { let (appearance, density) = chosen(); let appearance = use_signal(|| appearance); let density = use_signal(|| density); + let theme = use_signal(chosen_theme); rsx! { - Shown { appearance, density, accent: Accent::System } + Shown { appearance, density, theme, accent: Accent::System } } } +/// Which of unit's themes the page starts in: the environment's +/// UNIT_THEME (unit, soft, sharp), or a web page's `?theme=soft`. +fn chosen_theme() -> usize { + #[cfg(not(target_arch = "wasm32"))] + let asked = std::env::var("UNIT_THEME").unwrap_or_default(); + #[cfg(target_arch = "wasm32")] + let asked = web_query("theme"); + Theme::all() + .iter() + .position(|t| t.name.eq_ignore_ascii_case(&asked)) + .unwrap_or(0) +} + +/// A query parameter of the page's address, on the web. +#[cfg(target_arch = "wasm32")] +fn web_query(name: &str) -> String { + let search = js_sys::eval("location.search") + .ok() + .and_then(|v| v.as_string()) + .unwrap_or_default(); + search + .trim_start_matches('?') + .split('&') + .find_map(|kv| kv.strip_prefix(name)?.strip_prefix('=')) + .unwrap_or_default() + .to_string() +} + /// The appearance and density the environment asks for: a window can start /// dark, or at a finger's density, for a look at each: /// UNIT_APPEARANCE=dark, UNIT_DENSITY=touch. @@ -59,8 +90,9 @@ pub fn GallerySized(width: f64, height: f64) -> Element { let (appearance, density) = chosen(); let appearance = use_signal(|| appearance); let density = use_signal(|| density); + let theme = use_signal(chosen_theme); rsx! { - Shown { appearance, density, accent: Accent::Theme, size: (width, height) } + Shown { appearance, density, theme, accent: Accent::Theme, size: (width, height) } } } @@ -73,11 +105,15 @@ pub fn GalleryAt( density: Density, /// The window's size, as a host would tell unit. size: Option<(f64, f64)>, + /// Which of [`Theme::all`]: unit's own unless given. + #[props(default)] + theme: usize, ) -> Element { let appearance = use_signal(|| appearance); let density = use_signal(|| density); + let theme = use_signal(|| theme); rsx! { - Shown { appearance, density, accent: Accent::Theme, size } + Shown { appearance, density, theme, accent: Accent::Theme, size } } } @@ -85,14 +121,17 @@ pub fn GalleryAt( fn Shown( appearance: Signal, density: Signal, + /// Which of [`Theme::all`]. + theme: Signal, accent: Accent, size: Option<(f64, f64)>, ) -> Element { + let shown = Theme::all().swap_remove(theme().min(Theme::all().len() - 1)); rsx! { - UnitRoot { appearance: appearance(), density: density(), accent, class: "gallery", + UnitRoot { appearance: appearance(), density: density(), accent, theme: shown, class: "gallery", style { {GALLERY_CSS} } Sized { size } - Page { appearance, density } + Page { appearance, density, theme } // The page's own element, outside any component, as a host's // editor is: unit's styles leave its box as the page drew it. div { class: "gallery-own" } @@ -198,7 +237,7 @@ html, body { margin: 0; } "#; #[component] -fn Page(appearance: Signal, density: Signal) -> Element { +fn Page(appearance: Signal, density: Signal, theme: Signal) -> Element { let unit = use_unit(); #[cfg(not(target_arch = "wasm32"))] use_hook(move || { @@ -299,18 +338,21 @@ fn Page(appearance: Signal, density: Signal) -> Element { let shown: Vec = files.iter().map(|f| f.name.clone()).collect(); let tiles: Vec = files.iter().map(File::tile).collect(); let rows: Vec = files.iter().map(File::row).collect(); + // A file's menu, condensed: what is done most in a palette at its + // top, the rest in rows under it. let file_menu = vec![ Entry::header(match chosen().len() { 1 => "1 file".to_string(), n => format!("{n} files"), }), - Item::new(OPEN, "Open").into(), - Item::new(RENAME, "Rename…").into(), + Entry::palette(vec![ + Item::new(OPEN, "Open").icon(paths::ARROW_UP_RIGHT), + Item::new(RENAME, "Rename").icon(paths::PENCIL), + Item::new(COPY_FILE, "Duplicate").icon(paths::COPY), + Item::new(TRASH, "Trash").icon(paths::TRASH).destructive(), + ]), Entry::Separator, - Item::new(TRASH, "Move to Trash") - .icon(paths::TRASH) - .destructive() - .into(), + Item::new(SHARE_FILE, "Share…").icon(paths::SHARE).into(), ]; let on_file = move |id: usize| { let n = chosen.peek().len(); @@ -322,6 +364,8 @@ fn Page(appearance: Signal, density: Signal) -> Element { said.set(match id { OPEN => format!("Open {what}."), RENAME => format!("Rename {what}."), + COPY_FILE => format!("Duplicate {what}."), + SHARE_FILE => format!("Share {what}."), _ => format!("Move {what} to the Trash."), }); }; @@ -365,6 +409,12 @@ fn Page(appearance: Signal, density: Signal) -> Element { Stack { axis: Axis::Horizontal, align: Align::Center, wrap: true, Heading { level: 1, "unit" } Spacer {} + Segmented { + label: "Theme", + options: Theme::all().iter().map(|t| t.name.to_string()).collect::>(), + selected: Some(theme()), + onchange: move |i| theme.clone().set(i), + } Segmented { label: "Appearance", options: vec!["System".into(), "Light".into(), "Dark".into()], diff --git a/gallery/tests/audit.rs b/gallery/tests/audit.rs index 1c16d5a..3260b7a 100644 --- a/gallery/tests/audit.rs +++ b/gallery/tests/audit.rs @@ -169,14 +169,17 @@ struct At { appearance: Appearance, density: Density, size: (f64, f64), + /// Which of `Theme::all()`. + theme: usize, } impl At { - fn of(m: Mode) -> At { + fn of(m: Mode, theme: usize) -> At { At { appearance: m.appearance, density: m.density, size: (m.width as f64, m.height as f64), + theme, } } } @@ -184,7 +187,7 @@ impl At { #[allow(non_snake_case)] fn WholeGallery(at: At) -> Element { rsx! { - GalleryAt { appearance: at.appearance, density: at.density, size: at.size } + GalleryAt { appearance: at.appearance, density: at.density, size: at.size, theme: at.theme } } } @@ -197,6 +200,7 @@ fn LongText(at: At) -> Element { let options: Vec = vec![LONG.into(), WORD.into()]; rsx! { UnitRoot { appearance: at.appearance, density: at.density, + theme: unit::Theme::all().swap_remove(at.theme), Stack { gap: 12.0, Heading { level: 1, "{LONG}" } Heading { level: 1, "{WORD}" } @@ -242,12 +246,15 @@ fn laid_out(vdom: VirtualDom, m: Mode) -> DioxusDocument { doc } -fn gallery(m: Mode) -> DioxusDocument { - laid_out(VirtualDom::new_with_props(WholeGallery, At::of(m)), m) +fn gallery(m: Mode, theme: usize) -> DioxusDocument { + laid_out( + VirtualDom::new_with_props(WholeGallery, At::of(m, theme)), + m, + ) } -fn long_text(m: Mode) -> DioxusDocument { - laid_out(VirtualDom::new_with_props(LongText, At::of(m)), m) +fn long_text(m: Mode, theme: usize) -> DioxusDocument { + laid_out(VirtualDom::new_with_props(LongText, At::of(m, theme)), m) } fn rect(doc: &DioxusDocument, node: NodeId) -> (f64, f64, f64, f64) { @@ -773,16 +780,16 @@ impl Audit { } } -/// Every check in every mode. -fn audit() -> Audit { +/// Every check in every mode, in the `theme`th of `Theme::all()`. +fn audit(theme: usize) -> Audit { let mut a = Audit::default(); for m in MODES { - let mut doc = gallery(m); + let mut doc = gallery(m, theme); a.page(&doc, m, "page"); a.keyboard(&mut doc, m); for (scene, button, scrolled) in SCENES { - let mut doc = gallery(m); + let mut doc = gallery(m, theme); let target = { let inner = doc.inner.borrow(); let all = inner.query_selector_all("button").unwrap(); @@ -811,7 +818,7 @@ fn audit() -> Audit { } } - let doc = long_text(m); + let doc = long_text(m, theme); a.page(&doc, m, "long-text"); } a @@ -862,7 +869,7 @@ fn report(a: &Audit) -> String { /// The list of failures only shrinks. See the top of this file. #[test] fn the_audit_holds() { - let a = audit(); + let a = audit(0); // A file, as corgi shows nothing a passing test prints. std::fs::create_dir_all("../target").unwrap(); std::fs::write(REPORT, report(&a)).unwrap(); @@ -901,6 +908,34 @@ fn the_audit_holds() { ); } +/// Every other theme unit ships fails no cell its own theme passes: a +/// theme may round, recolour and unedge a page, and still never take a +/// check away from it. Its failures, all of them on the baseline, are in +/// `target/audit-.txt`. +#[test] +fn every_theme_fails_only_what_units_own_does() { + let known = listed(Path::new(BASELINE)); + for (i, theme) in unit::Theme::all().iter().enumerate().skip(1) { + let a = audit(i); + let name = theme.name.to_lowercase(); + std::fs::create_dir_all("../target").unwrap(); + std::fs::write(format!("../target/audit-{name}.txt"), report(&a)).unwrap(); + let new: Vec = a + .failed + .iter() + .filter(|(c, _)| !known.contains(*c)) + .map(|(c, why)| format!(" {c} # {why}")) + .collect(); + assert!( + new.is_empty(), + "{} fails {} cells unit's own theme passes:\n{}", + theme.name, + new.len(), + new.join("\n") + ); + } +} + /// A component the gallery does not show is one the audit cannot see. #[test] fn the_gallery_shows_every_component() { diff --git a/gallery/tests/blitz.rs b/gallery/tests/blitz.rs index e7e2226..6dec797 100644 --- a/gallery/tests/blitz.rs +++ b/gallery/tests/blitz.rs @@ -2013,7 +2013,7 @@ fn a_collections_menu_is_about_its_selection() { assert!(selected(&doc, letters)); assert!(!selected(&doc, option_named(&doc, "Notes.md"))); assert!(menu_open(&doc)); - let trash = find(&doc, ".unit-item", "Move to Trash"); + let trash = find(&doc, ".unit-cell", "Trash"); click(&mut doc, trash); assert_eq!(said(&doc), "Move 1 item to the Trash."); // On one of several chosen, it keeps them all. @@ -2021,7 +2021,7 @@ fn a_collections_menu_is_about_its_selection() { click_with(&mut doc, plans, Modifiers::META); right_click(&mut doc, plans); assert_eq!(chosen(&doc), "2 of 7 chosen."); - let open = find(&doc, ".unit-item", "Open"); + let open = find(&doc, ".unit-cell", "Open"); click(&mut doc, open); assert_eq!(said(&doc), "Open 2 items."); // The Menu key opens it too, its first item lit as a key's menu is. @@ -2033,6 +2033,89 @@ fn a_collections_menu_is_about_its_selection() { assert_eq!(said(&doc), "Open 1 item."); } +/// A palette's items stand side by side in one row of the menu, inside +/// it, each an icon over its label, read as a group of menu items; the +/// arrows go along it and Return picks. +#[test] +fn a_palette_lays_its_items_side_by_side_in_the_menu() { + for finger in [false, true] { + let mut doc = page(1200, 800); + if finger { + let touch = find(&doc, ".unit-segment", "Touch"); + tap(&mut doc, touch); + } + let letters = option_named(&doc, "Letters.md"); + right_click(&mut doc, letters); + assert!(menu_open(&doc)); + let cells: Vec = ["Open", "Rename", "Duplicate", "Trash"] + .iter() + .map(|l| find(&doc, ".unit-cell", l)) + .collect(); + let level = doc + .inner + .borrow() + .query_selector(".unit-menu") + .unwrap() + .unwrap(); + let (lx, ly, lw, lh) = rect(&doc, level); + let boxes: Vec<_> = cells.iter().map(|&c| rect(&doc, c)).collect(); + for (i, &(x, y, w, h)) in boxes.iter().enumerate() { + assert!(w > 0.0 && h > 0.0, "cell {i} is drawn"); + assert!( + x >= lx && x + w <= lx + lw + 0.5, + "cell {i} inside the menu" + ); + assert!( + y >= ly && y + h <= ly + lh + 0.5, + "cell {i} inside the menu" + ); + assert_eq!(y, boxes[0].1, "one row"); + if i > 0 { + assert!(x >= boxes[i - 1].0 + boxes[i - 1].2, "side by side"); + } + assert!( + icon_under(&doc, cells[i]).1.starts_with("unit-svg"), + "an icon in cell {i}" + ); + } + assert!(class_of(&doc, cells[3]).contains("danger")); + let nodes = tree(&doc); + assert!( + with_role(&nodes, Role::MenuItem) + .iter() + .any(|n| n.label() == Some("Duplicate")), + "a cell is read as a menu item" + ); + // The pointer picks a cell. + click(&mut doc, cells[2]); + assert_eq!(said(&doc), "Duplicate 1 item."); + assert!(!menu_open(&doc)); + // From the keys: the Menu key lights the palette's first cell, and + // the arrows go along it. + click(&mut doc, letters); + key(&mut doc, Key::Named(NamedKey::ContextMenu)); + assert!(menu_open(&doc)); + // A new opening draws its rows anew. + let cells: Vec = ["Open", "Rename", "Duplicate", "Trash"] + .iter() + .map(|l| find(&doc, ".unit-cell", l)) + .collect(); + assert!( + class_of(&doc, cells[0]).contains("hot"), + "the first cell lit" + ); + key(&mut doc, Key::Named(NamedKey::ArrowRight)); + key(&mut doc, Key::Named(NamedKey::ArrowRight)); + key(&mut doc, Key::Named(NamedKey::ArrowRight)); + assert!( + class_of(&doc, cells[3]).contains("hot"), + "along the palette" + ); + key(&mut doc, Key::Named(NamedKey::Enter)); + assert_eq!(said(&doc), "Move 1 item to the Trash."); + } +} + #[test] fn a_table_sorts_by_its_columns_and_chooses_its_rows() { let mut doc = page(1200, 800); diff --git a/src/icon.rs b/src/icon.rs index 0ee2b02..46271f4 100644 --- a/src/icon.rs +++ b/src/icon.rs @@ -120,6 +120,12 @@ pub mod paths { pub const SEARCH: &str = "M21 21l-4.34-4.34M3 11a8 8 0 1 0 16 0a8 8 0 1 0 -16 0"; /// Lucide's `trash`. pub const TRASH: &str = "M10 11v6M14 11v6M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"; + /// Lucide's `copy`: two sheets, one over the other. + pub const COPY: &str = "M10 8h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H10a2 2 0 0 1-2-2V10a2 2 0 0 1 2-2zM4 16a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2"; + /// Lucide's `pencil`: rename, edit. + pub const PENCIL: &str = "M21.17 6.81a1 1 0 0 0-3.99-3.99L3.84 16.17a2 2 0 0 0-.5.83l-1.32 4.35a.5.5 0 0 0 .62.62l4.35-1.32a2 2 0 0 0 .83-.5zM15 5l4 4"; + /// Lucide's `shield`: kept safe. + pub const SHIELD: &str = "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"; /// Lucide's `share`. pub const SHARE: &str = "M12 2v13M16 6l-4-4-4 4M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"; /// Lucide's `chevron-up`. @@ -196,6 +202,9 @@ pub mod paths { ("SEARCH", SEARCH), ("TRASH", TRASH), ("SHARE", SHARE), + ("COPY", COPY), + ("SHIELD", SHIELD), + ("PENCIL", PENCIL), ("CHEVRON_UP", CHEVRON_UP), ("CHEVRON_UP_DOWN", CHEVRON_UP_DOWN), ("ARROW_UP", ARROW_UP), diff --git a/src/layer.rs b/src/layer.rs index d537197..369bbf1 100644 --- a/src/layer.rs +++ b/src/layer.rs @@ -509,6 +509,7 @@ fn MenuLevel(unit: Unit, depth: usize, level: Option) -> Element { }, l.entries.clone(), l.hot, + l.cell, )), ), None => ("display: none".to_string(), None), @@ -524,7 +525,7 @@ fn MenuLevel(unit: Unit, depth: usize, level: Option) -> Element { m.press(); } }, - for (opening, style, entries, hot) in rows { + for (opening, style, entries, hot, cell) in rows { div { key: "{opening}", class: "unit-menu-rows", style, onscroll: move |_| { let mut l = unit.layer; @@ -533,7 +534,7 @@ fn MenuLevel(unit: Unit, depth: usize, level: Option) -> Element { } }, for (i, entry) in entries.iter().enumerate() { - {entry_view(unit, depth, i, entry, hot == Some(i))} + {entry_view(unit, depth, i, entry, (hot == Some(i)).then_some(cell))} } } } @@ -541,7 +542,13 @@ fn MenuLevel(unit: Unit, depth: usize, level: Option) -> Element { } } -fn entry_view(unit: Unit, depth: usize, i: usize, entry: &Entry, hot: bool) -> Element { +/// Entry `i` of level `depth`; `lit` where it is highlighted, with which +/// of a palette's cells is. +fn entry_view(unit: Unit, depth: usize, i: usize, entry: &Entry, lit: Option) -> Element { + if let Entry::Palette(items) = entry { + return palette_view(unit, depth, i, items, lit); + } + let hot = lit.is_some(); let hover = move |_: PointerEvent| { let mut l = unit.layer; let now = l @@ -623,6 +630,83 @@ fn entry_view(unit: Unit, depth: usize, i: usize, entry: &Entry, hot: bool) -> E span { class: "unit-key", "aria-hidden": "true", "▸" } } }, + Entry::Palette(_) => unreachable!("drawn by palette_view"), + } +} + +/// A palette: its items side by side in one row, each an icon over its +/// label, a group of menu items to assistive tech. +fn palette_view( + unit: Unit, + depth: usize, + i: usize, + items: &[crate::menu::Item], + lit: Option, +) -> Element { + // Words alone, with no icons: a row's height, a segmented choice. + let plain = items.iter().all(|i| i.icon.is_none()); + let cells = items.iter().cloned().enumerate().map(|(cell, item)| { + let hot = lit == Some(cell); + let hover = move |_: PointerEvent| { + let mut l = unit.layer; + let now = l + .peek() + .menu + .as_ref() + .and_then(|(m, _)| m.levels.get(depth).map(|l| (l.hot, l.cell))); + let armed = l.peek().menu.as_ref().is_some_and(|(m, _)| m.armed); + if (now != Some((Some(i), cell)) || !armed) + && let Some((m, _)) = l.write().menu.as_mut() + { + m.hover_at(depth, i, cell); + } + }; + let release = move |e: PointerEvent| { + e.stop_propagation(); + let mut l = unit.layer; + let outcome = l + .write() + .menu + .as_mut() + .map_or(Outcome::Ignored, |(m, _)| m.release_at(depth, i, cell)); + unit.settle(outcome); + }; + let class = format!( + "unit-cell{}{}{}{}", + if hot { " hot" } else { "" }, + if item.checked { " on" } else { "" }, + if item.enabled { "" } else { " off" }, + if item.destructive { " danger" } else { "" }, + ); + let ink = match () { + _ if !item.enabled => Ink::Dim, + _ if hot => Ink::AccentText, + _ if item.destructive => Ink::Danger, + _ if item.checked => Ink::Accent, + _ => Ink::Text, + }; + let role = if item.checkable { + "menuitemcheckbox" + } else { + "menuitem" + }; + rsx! { + div { key: "{cell}", class, role, + "aria-checked": item.checkable.then(|| item.checked.to_string()), + "aria-disabled": (!item.enabled).then_some("true"), + "aria-label": "{item.label}", + onpointermove: hover, onpointerup: release, + if let Some(d) = item.icon { + Icon { d, ink, size: 18.0 } + } + span { class: "unit-cell-label", "aria-hidden": "true", "{item.label}" } + } + } + }); + rsx! { + div { class: if plain { "unit-palette plain" } else { "unit-palette" }, role: "group", + {cells} + } } } diff --git a/src/menu.rs b/src/menu.rs index 679008c..f25db6c 100644 --- a/src/menu.rs +++ b/src/menu.rs @@ -28,6 +28,12 @@ pub struct Sizes { pub margin: f64, /// How far a submenu overlaps its parent, as the system's do. pub overlap: f64, + /// A palette's height: a row of items side by side, each an icon over + /// a short label ([`Entry::Palette`]). A palette of words alone, with no + /// icons, is an item's height. + pub palette: f64, + /// A palette's narrowest cell. + pub cell: f64, } impl Sizes { @@ -39,6 +45,8 @@ impl Sizes { min_width: 160.0, margin: 4.0, overlap: 4.0, + palette: 44.0, + cell: 52.0, }; /// For a finger: rows tall enough to tap. @@ -50,6 +58,8 @@ impl Sizes { min_width: 200.0, margin: 4.0, overlap: 4.0, + palette: 64.0, + cell: 64.0, }; /// For a terminal's cells: an item and a separator a row each, and a @@ -66,6 +76,9 @@ impl Sizes { min_width: 160.0, margin: 0.0, overlap: 9.7, + // A row: the labels side by side, no icons. + palette: 24.0, + cell: 48.0, }; } @@ -89,6 +102,12 @@ pub enum Entry { entries: Vec, enabled: bool, }, + /// Items side by side in one row, each an icon over a short label: the + /// few things done most, at the top of a long menu (Copy, Share, + /// Duplicate, Delete), or a choice of a few, ticked where it stands + /// (Reflow, Pages, Source) instead of a submenu of them. One entry for + /// the arrows up and down; left and right go along it. + Palette(Vec), } /// An item that does something when chosen: its `id` is what the menu's @@ -174,17 +193,26 @@ impl Entry { } } + /// A row of `items` side by side ([`Entry::Palette`]). + pub fn palette(items: Vec) -> Self { + Entry::Palette(items) + } + pub fn enabled(&self) -> bool { match self { Entry::Item(i) => i.enabled, Entry::Separator | Entry::Header(_) => false, Entry::Submenu { enabled, .. } => *enabled, + Entry::Palette(items) => items.iter().any(|i| i.enabled), } } fn height(&self, z: Sizes) -> f64 { match self { Entry::Separator => z.separator, + // Words alone, a choice of a few: a row's height. + Entry::Palette(items) if items.iter().all(|i| i.icon.is_none()) => z.item, + Entry::Palette(_) => z.palette, _ => z.item, } } @@ -202,6 +230,17 @@ impl Entry { Entry::Separator => 0.0, Entry::Header(label) => chars(label) * z.char, Entry::Submenu { label, .. } => chars(label) * z.char + 16.0, + // The cells share the row equally, so each is as wide as the + // widest label in the palette's smaller face, or its narrowest; + // less the gutters a row leaves for a tick and an arrow, which a + // palette has no need of. + Entry::Palette(items) => { + let widest = items + .iter() + .map(|i| (chars(&i.label) * z.char * 0.9 + 14.0).max(z.cell)) + .fold(0.0, f64::max); + widest * items.len() as f64 - GUTTERS + 12.0 + } } } } @@ -218,6 +257,9 @@ pub struct Level { /// the page has for it: it scrolls inside that. `None` where they fit. pub clip: Option, pub hot: Option, + /// Which of a palette's items is highlighted, where [`Level::hot`] is + /// a palette. + pub cell: usize, pub sizes: Sizes, /// Which opening this is, of every level any menu has opened: the box /// its rows scroll in is drawn anew for each (`layer.rs`), so a level @@ -239,6 +281,7 @@ impl Level { width, clip: None, hot: None, + cell: 0, sizes: z, opening: OPENINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed), } @@ -292,6 +335,41 @@ impl Level { } None } + + /// Highlight entry `i`, and where it is a palette, its first item that + /// can be chosen at or after `cell`. Over a row, `cell` is kept: the + /// column the arrows go on down in, into the next palette. + fn light(&mut self, i: Option, cell: usize) { + self.hot = i; + self.cell = cell; + if let Some(Entry::Palette(items)) = i.and_then(|i| self.entries.get(i)) { + let n = items.len(); + self.cell = (0..n) + .map(|k| (cell.min(n.saturating_sub(1)) + k) % n) + .find(|&k| items[k].enabled) + .unwrap_or(0); + } + } + + /// Move along the highlighted palette, `right` or left, past what + /// cannot be chosen: whether there was anywhere to go. + fn along(&mut self, right: bool) -> bool { + let Some(Entry::Palette(items)) = self.hot.and_then(|i| self.entries.get(i)) else { + return false; + }; + let mut k = self.cell; + loop { + k = match (right, k) { + (true, k) if k + 1 < items.len() => k + 1, + (false, k) if k > 0 => k - 1, + _ => return false, + }; + if items[k].enabled { + self.cell = k; + return true; + } + } + } } /// What a key or a press did to the menu. @@ -377,14 +455,25 @@ impl Menu { /// Highlight entry `i` of level `depth`, opening its submenu or closing /// any deeper level. pub fn hover(&mut self, depth: usize, i: usize) { + self.hover_at(depth, i, 0); + } + + /// Highlight item `cell` of the palette at entry `i` of level `depth` + /// ([`Menu::hover`] for any other entry). A cell that cannot be chosen + /// highlights nothing, as such an item does. + pub fn hover_at(&mut self, depth: usize, i: usize, cell: usize) { self.armed = true; if depth >= self.levels.len() { return; } self.levels.truncate(depth + 1); let level = &mut self.levels[depth]; - let enabled = level.entries.get(i).is_some_and(Entry::enabled); + let enabled = match level.entries.get(i) { + Some(Entry::Palette(items)) => items.get(cell).is_some_and(|c| c.enabled), + entry => entry.is_some_and(Entry::enabled), + }; level.hot = enabled.then_some(i); + level.cell = if enabled { cell } else { 0 }; if enabled { self.open_submenu(depth, i); } @@ -425,7 +514,8 @@ impl Menu { /// Highlight the first level's first item that can be chosen. pub fn hot_first(&mut self) { let level = &mut self.levels[0]; - level.hot = level.step(None, true); + let first = level.step(None, true); + level.light(first, 0); } /// The pointer pressed in the menu. @@ -436,21 +526,38 @@ impl Menu { /// The pointer let go over entry `i` of level `depth`. pub fn release(&mut self, depth: usize, i: usize) -> Outcome { + self.release_at(depth, i, 0) + } + + /// The pointer let go over item `cell` of the palette at entry `i` of + /// level `depth` ([`Menu::release`] for any other entry). + pub fn release_at(&mut self, depth: usize, i: usize, cell: usize) -> Outcome { if !self.armed || std::mem::take(&mut self.scrolled) { return Outcome::Handled; } + if let Some(level) = self.levels.get_mut(depth) + && matches!(level.entries.get(i), Some(Entry::Palette(_))) + { + level.cell = cell; + } self.activate(depth, i) } fn activate(&mut self, depth: usize, i: usize) -> Outcome { - match self.levels.get(depth).and_then(|l| l.entries.get(i)) { + let level = self.levels.get(depth); + let cell = level.map_or(0, |l| l.cell); + match level.and_then(|l| l.entries.get(i)) { Some(Entry::Item(item)) if item.enabled => Outcome::Pick(item.id), + Some(Entry::Palette(items)) => match items.get(cell) { + Some(item) if item.enabled => Outcome::Pick(item.id), + _ => Outcome::Handled, + }, Some(Entry::Submenu { enabled: true, .. }) => { self.levels[depth].hot = Some(i); if self.open_submenu(depth, i) { let deeper = depth + 1; let first = self.levels[deeper].step(None, true); - self.levels[deeper].hot = first; + self.levels[deeper].light(first, 0); } Outcome::Handled } @@ -468,17 +575,24 @@ impl Menu { Key::Named(ArrowDown) | Key::Named(ArrowUp) => { let down = *key == Key::Named(ArrowDown); let level = &mut self.levels[depth]; - level.hot = level.step(level.hot, down); + let next = level.step(level.hot, down); + // Down a column of a palette and back up it. + level.light(next, level.cell); Outcome::Handled } Key::Named(ArrowRight) => { - if let Some(i) = self.levels[depth].hot { + if self.levels[depth].along(true) { + return Outcome::Handled; + } + if let Some(i) = self.levels[depth].hot + && !matches!(self.levels[depth].entries.get(i), Some(Entry::Palette(_))) + { self.activate(depth, i); } Outcome::Handled } Key::Named(ArrowLeft) => { - if depth > 0 { + if !self.levels[depth].along(false) && depth > 0 { self.levels.pop(); } Outcome::Handled @@ -495,22 +609,36 @@ impl Menu { Key::Character(c) if mods.is_empty() || mods == Modifiers::SHIFT => { let c = c.to_lowercase(); let level = &mut self.levels[depth]; - let n = level.entries.len(); - let start = level.hot.map_or(0, |h| h + 1); - let found = (0..n).map(|k| (start + k) % n).find(|&k| { - let label = match &level.entries[k] { - Entry::Item(i) if i.enabled => &i.label, + let starts = |label: &str| label.to_lowercase().starts_with(&c); + // Each item that can be chosen, as (entry, cell), after the + // highlighted one and round: a palette's in its order. + let mut stops = Vec::new(); + for (k, entry) in level.entries.iter().enumerate() { + match entry { + Entry::Item(i) if i.enabled && starts(&i.label) => stops.push((k, 0)), Entry::Submenu { label, enabled: true, .. - } => label, - _ => return false, - }; - label.to_lowercase().starts_with(&c) - }); - if found.is_some() { - level.hot = found; + } if starts(label) => stops.push((k, 0)), + Entry::Palette(items) => stops.extend( + items + .iter() + .enumerate() + .filter(|(_, i)| i.enabled && starts(&i.label)) + .map(|(cell, _)| (k, cell)), + ), + _ => {} + } + } + let now = level.hot.map(|h| (h, level.cell)); + let found = stops + .iter() + .find(|&&stop| now.is_none_or(|now| stop > now)) + .or(stops.first()); + if let Some(&(k, cell)) = found { + level.hot = Some(k); + level.cell = cell; } Outcome::Handled } @@ -663,6 +791,95 @@ mod tests { assert_eq!(m.release(0, 1), Outcome::Handled); } + fn palette() -> Vec { + vec![ + Entry::header("Notes.md"), + Entry::palette(vec![ + Item::new(1, "Copy").icon(crate::icon::paths::COPY), + Item::new(2, "Share") + .icon(crate::icon::paths::SHARE) + .enabled(false), + Item::new(3, "Duplicate").icon(crate::icon::paths::COPY), + Item::new(4, "Delete") + .icon(crate::icon::paths::TRASH) + .destructive(), + ]), + Entry::Separator, + Item::new(5, "Rename…").into(), + Entry::palette(vec![ + Item::new(6, "Reflow").checked(true), + Item::new(7, "Pages").checked(false), + ]), + ] + } + + #[test] + fn a_palette_is_one_entry_a_palette_tall_and_as_wide_as_its_cells() { + let z = Sizes::REGULAR; + let l = Level::new(palette(), z); + assert_eq!( + l.height(), + // The second palette is words alone: a row's height. + 2.0 * z.pad + 3.0 * z.item + z.palette + z.separator + ); + assert!(l.width >= 4.0 * z.cell, "{}", l.width); + // Words alone are a row's height. + let plain = Level::new( + vec![Entry::palette(vec![ + Item::new(1, "Reflow"), + Item::new(2, "Pages"), + ])], + z, + ); + assert_eq!(plain.height(), 2.0 * z.pad + z.item); + } + + #[test] + fn the_arrows_go_along_a_palette_and_down_out_of_it() { + let mut m = Menu::open(palette(), (0.0, 0.0), 0.0, PAGE, Sizes::REGULAR); + let none = Modifiers::empty(); + let key = |m: &mut Menu, k: NamedKey| m.key(&Key::Named(k), none); + m.hot_first(); + assert_eq!((m.levels[0].hot, m.levels[0].cell), (Some(1), 0)); + key(&mut m, NamedKey::ArrowRight); + // Past Share, which cannot be chosen. + assert_eq!(m.levels[0].cell, 2); + key(&mut m, NamedKey::ArrowRight); + key(&mut m, NamedKey::ArrowRight); + assert_eq!(m.levels[0].cell, 3, "it stops at the end"); + assert_eq!(key(&mut m, NamedKey::Enter), Outcome::Pick(4)); + key(&mut m, NamedKey::ArrowLeft); + assert_eq!(m.levels[0].cell, 2); + key(&mut m, NamedKey::ArrowDown); + assert_eq!(m.levels[0].hot, Some(3)); + // Down into the next palette, as near the column as it has. + m.levels[0].cell = 0; + key(&mut m, NamedKey::ArrowUp); + assert_eq!(m.levels[0].hot, Some(1)); + m.levels[0].cell = 3; + key(&mut m, NamedKey::ArrowDown); + key(&mut m, NamedKey::ArrowDown); + assert_eq!((m.levels[0].hot, m.levels[0].cell), (Some(4), 1)); + assert_eq!(key(&mut m, NamedKey::Enter), Outcome::Pick(7)); + // A letter finds a palette's item too. + m.key(&Key::Character("d".into()), none); + assert_eq!((m.levels[0].hot, m.levels[0].cell), (Some(1), 2)); + m.key(&Key::Character("d".into()), none); + assert_eq!((m.levels[0].hot, m.levels[0].cell), (Some(1), 3)); + } + + #[test] + fn the_pointer_picks_a_palettes_cell_but_never_one_that_is_off() { + let mut m = Menu::open(palette(), (0.0, 0.0), 0.0, PAGE, Sizes::REGULAR); + m.hover_at(0, 1, 1); + assert_eq!(m.levels[0].hot, None, "Share cannot be chosen"); + assert_eq!(m.release_at(0, 1, 1), Outcome::Handled); + m.hover_at(0, 1, 2); + assert_eq!((m.levels[0].hot, m.levels[0].cell), (Some(1), 2)); + assert_eq!(m.release_at(0, 1, 2), Outcome::Pick(3)); + assert_eq!(m.release_at(0, 4, 0), Outcome::Pick(6)); + } + #[test] fn a_submenu_with_nothing_to_choose_is_disabled() { let s = Entry::submenu( diff --git a/src/style.rs b/src/style.rs index d402204..192ea3b 100644 --- a/src/style.rs +++ b/src/style.rs @@ -1,5 +1,7 @@ -//! Every component's styles. Colours and sizes are the theme's custom -//! properties (`theme.rs`) and nothing else, so a theme restyles them all. +//! Every component's styles. Colours, sizes, corners, edges and shadows are +//! the theme's custom properties (`theme.rs`) and nothing else, so a theme +//! restyles them all. What is still written here in pixels is what a +//! density decides, not a theme: a menu row's height, a checkbox's size. //! //! Written for what Blitz lays out as a browser does: flexbox, absolute //! positions by `left`/`top`/`right`/`bottom`, attribute selectors, `:hover` @@ -15,7 +17,7 @@ pub const CSS: &str = r#" under the root lays out by the box model it chose. */ .unit-root [class*="unit-"], .unit-root [class*="unit-"] *, .unit-root [class*="unit-"]::before, .unit-root [class*="unit-"]::after { box-sizing: border-box; } -.unit-focused, [data-unit-focused] { outline: 2px solid var(--unit-focus); outline-offset: 1px; } +.unit-focused, [data-unit-focused] { outline: var(--unit-focus-ring) solid var(--unit-focus); outline-offset: 1px; } /* The overlay */ .unit-layer { position: fixed; left: 0; top: 0; right: 0; bottom: 0; z-index: 100; @@ -27,10 +29,10 @@ pub const CSS: &str = r#" /* Menus: rows and separators the heights menu::Sizes says */ .unit-menu { position: absolute; padding: 5px 0; font-size: 13px; background: var(--unit-surface); color: var(--unit-text); - border: 1px solid var(--unit-border); border-radius: 8px; - box-shadow: 0 8px 24px var(--unit-shadow); } -.unit-item { display: flex; height: 24px; line-height: 24px; margin: 0 5px; padding: 0 8px 0 0; - border-radius: 4px; } + border: var(--unit-float-edge) solid var(--unit-border); border-radius: var(--unit-radius-large); + box-shadow: var(--unit-float-shadow); } +.unit-item { display: flex; height: 24px; line-height: 24px; margin: 0 var(--unit-menu-inset); padding: 0 8px 0 0; + border-radius: var(--unit-radius-small); } .unit-item.hot { background: var(--unit-accent); color: var(--unit-accent-text); } .unit-item.off { color: var(--unit-dim); } .unit-item.danger { color: var(--unit-danger); } @@ -43,8 +45,31 @@ pub const CSS: &str = r#" .unit-sep { height: 9px; padding: 4px 10px; } .unit-item.unit-header { color: var(--unit-dim); font-size: 0.85em; font-weight: 600; } .unit-rule { height: 1px; background: var(--unit-separator); } -.unit-root[data-density="touch"] .unit-menu { padding: 6px 0; font-size: 17px; border-radius: 12px; } -.unit-root[data-density="touch"] .unit-item { height: 44px; line-height: 44px; border-radius: 8px; } +/* A palette: items side by side, each an icon over a short label, the + height menu::Sizes says. A ticked one wears the selection's colour. */ +.unit-palette { display: flex; height: 44px; margin: 0 var(--unit-menu-inset); gap: 2px; } +.unit-cell { display: flex; flex: 1 1 0; min-width: 0; flex-direction: column; align-items: center; + justify-content: center; gap: 3px; font-size: 11px; line-height: 1.2; + border-radius: var(--unit-radius-small); } +.unit-cell.on { background: var(--unit-selection); color: var(--unit-text); } +.unit-cell.off { color: var(--unit-dim); } +.unit-cell.danger { color: var(--unit-danger); } +.unit-cell.hot { background: var(--unit-accent); color: var(--unit-accent-text); } +.unit-cell.danger.hot { background: var(--unit-danger); } +.unit-cell-label { display: block; max-width: 100%; padding: 0 3px; white-space: nowrap; + overflow: hidden; text-overflow: ellipsis; } +.unit-root[data-density="touch"] .unit-palette { height: 64px; } +/* Words alone: an item's height, its cells a segmented choice. */ +.unit-palette.plain { height: 24px; } +.unit-palette.plain .unit-cell { font-size: inherit; line-height: 1; } +.unit-root[data-density="touch"] .unit-palette.plain { height: 44px; } +.unit-root[data-density="touch"] .unit-cell { gap: 5px; font-size: 13px; } +.unit-root[data-density="cell"] .unit-palette { height: 24px; margin: 0; gap: 0; } +.unit-root[data-density="cell"] .unit-palette.plain { height: 24px; } +.unit-root[data-density="cell"] .unit-cell { flex-direction: row; font-size: inherit; line-height: 24px; } +.unit-root[data-density="cell"] .unit-cell .unit-svg { display: none; } +.unit-root[data-density="touch"] .unit-menu { padding: 6px 0; font-size: 17px; } +.unit-root[data-density="touch"] .unit-item { height: 44px; line-height: 44px; } .unit-root[data-density="touch"] .unit-tick { width: 28px; } .unit-root[data-density="touch"] .unit-sep { height: 13px; padding: 6px 12px; } .unit-root[data-density="cell"] { line-height: 24px; } @@ -65,9 +90,9 @@ pub const CSS: &str = r#" .unit-modal { overscroll-behavior: contain; touch-action: pan-x pan-y; } .unit-dialog { width: 380px; max-width: 100%; padding: 16px 18px 14px; white-space: normal; background: var(--unit-surface); color: var(--unit-text); - border: 1px solid var(--unit-border); border-radius: var(--unit-radius-large); - box-shadow: 0 12px 40px var(--unit-shadow); } -.unit-dialog-title { font-family: var(--unit-heading-font); font-weight: 700; margin-bottom: 6px; } + border: var(--unit-float-edge) solid var(--unit-border); border-radius: var(--unit-radius-large); + box-shadow: var(--unit-float-shadow); } +.unit-dialog-title { font-family: var(--unit-heading-font); font-weight: var(--unit-heading-weight); margin-bottom: 6px; } .unit-dialog-message { margin-bottom: 10px; } .unit-dialog .unit-input { margin: 4px 0 14px; } .unit-dialog-buttons { display: flex; gap: 8px; justify-content: flex-end; margin-top: 12px; } @@ -91,7 +116,8 @@ pub const CSS: &str = r#" white-space: normal; pointer-events: auto; } .unit-actions-group { display: flex; flex-direction: column; overflow: hidden; background: var(--unit-surface); border-radius: var(--unit-radius-large); - border: 1px solid var(--unit-border); } + border: var(--unit-float-edge) solid var(--unit-border); + box-shadow: var(--unit-float-shadow); } .unit-actions-head { padding: 12px 16px; text-align: center; color: var(--unit-dim); font-size: 0.85em; border-bottom: 1px solid var(--unit-separator); } .unit-actions-title { font-weight: 700; } @@ -104,7 +130,8 @@ pub const CSS: &str = r#" .unit-action.off { color: var(--unit-dim); } .unit-action:hover, .unit-actions-cancel:hover { background: var(--unit-control-hover); } .unit-actions-cancel { font-weight: 700; background: var(--unit-surface); - border: 1px solid var(--unit-border); border-radius: var(--unit-radius-large); } + border: var(--unit-float-edge) solid var(--unit-border); border-radius: var(--unit-radius-large); + box-shadow: var(--unit-float-shadow); } .unit-action.hot, .unit-actions-cancel.hot { background: var(--unit-accent); color: var(--unit-accent-text); } .unit-action.danger.hot { background: var(--unit-danger); color: var(--unit-accent-text); } .unit-root[data-density="cell"] .unit-actions-place { justify-content: flex-start; padding: 72px 20px 24px; } @@ -120,20 +147,21 @@ pub const CSS: &str = r#" .unit-toast { display: flex; align-items: center; gap: 8px; padding: 6px 6px 6px 14px; max-width: 90%; white-space: normal; background: var(--unit-surface); color: var(--unit-text); - border: 1px solid var(--unit-border); border-radius: var(--unit-radius-large); - box-shadow: 0 6px 20px var(--unit-shadow); } + border: var(--unit-float-edge) solid var(--unit-border); border-radius: var(--unit-radius-large); + box-shadow: var(--unit-float-shadow); } .unit-toast-message { flex: 1; } -.unit-toast.unit-success { border-color: var(--unit-success); } -.unit-toast.unit-warning { border-color: var(--unit-warning); } -.unit-toast.unit-danger { border-color: var(--unit-danger); } +/* A toast's tone is its edge, drawn whether or not the theme draws edges. */ +.unit-toast.unit-success { border: 1px solid var(--unit-success); } +.unit-toast.unit-warning { border: 1px solid var(--unit-warning); } +.unit-toast.unit-danger { border: 1px solid var(--unit-danger); } /* Buttons */ .unit-button { display: inline-flex; align-items: center; justify-content: center; gap: 6px; height: var(--unit-control-height); padding: 0 12px; margin: 0; font-family: inherit; font-size: inherit; line-height: 1; white-space: nowrap; color: var(--unit-text); background: var(--unit-control); - border: 1px solid var(--unit-border); border-radius: var(--unit-radius); - box-shadow: 0 1px 2px var(--unit-shadow-soft); } + border: var(--unit-edge) solid var(--unit-border); border-radius: var(--unit-radius); + box-shadow: var(--unit-control-shadow); } /* Hover, on what is not disabled: `:where()` adds nothing to a selector's weight, so a face below still wins over the hover above it. */ .unit-button:hover:where(:not([disabled])) { background: var(--unit-control-hover); } @@ -172,46 +200,45 @@ pub const CSS: &str = r#" min-height: var(--unit-control-height); } .unit-check-box { display: flex; align-items: center; justify-content: center; flex: none; width: 16px; height: 16px; font-size: 12px; line-height: 1; - color: var(--unit-accent-text); background: var(--unit-control); - border: 1px solid var(--unit-border); border-radius: 4px; - box-shadow: 0 1px 2px var(--unit-shadow-soft); } + color: var(--unit-accent-text); background: var(--unit-field); + border: var(--unit-field-edge) solid var(--unit-border); border-radius: var(--unit-radius-small); + box-shadow: var(--unit-control-shadow); } .unit-check.on .unit-check-box { background: var(--unit-accent); border-color: var(--unit-accent); } .unit-check.off, .unit-switch.off, .unit-slider.off { color: var(--unit-dim); } .unit-switch-label { flex: 1; min-width: 0; overflow-wrap: anywhere; } .unit-switch-track { display: flex; flex: none; width: 32px; height: 18px; padding: 2px; - background: var(--unit-border); border-radius: 9px; } + background: var(--unit-border); border-radius: var(--unit-pill); } .unit-switch.on .unit-switch-track { justify-content: flex-end; background: var(--unit-accent); } -.unit-switch-knob { width: 14px; height: 14px; border-radius: 7px; background: #ffffff; - box-shadow: 0 1px 2px var(--unit-shadow); } +.unit-switch-knob { width: 14px; height: 14px; border-radius: var(--unit-pill); background: #ffffff; + box-shadow: var(--unit-raised-shadow); } .unit-radios { display: flex; flex-direction: column; gap: 4px; } .unit-radios.unit-row { flex-direction: row; gap: 14px; } .unit-radio { display: flex; align-items: center; gap: 8px; min-height: var(--unit-control-height); } .unit-radio-ring { display: flex; align-items: center; justify-content: center; flex: none; width: 16px; height: 16px; border-radius: 8px; - background: var(--unit-control); border: 1px solid var(--unit-border); - box-shadow: 0 1px 2px var(--unit-shadow-soft); } + background: var(--unit-field); border: var(--unit-field-edge) solid var(--unit-border); + box-shadow: var(--unit-control-shadow); } .unit-radio.on .unit-radio-ring { background: var(--unit-accent); border-color: var(--unit-accent); } .unit-radio-dot { width: 6px; height: 6px; border-radius: 3px; background: transparent; } .unit-radio.on .unit-radio-dot { background: var(--unit-accent-text); } .unit-root[data-density="touch"] .unit-check-box, .unit-root[data-density="touch"] .unit-radio-ring { width: 24px; height: 24px; border-radius: 12px; } -.unit-root[data-density="touch"] .unit-check-box { border-radius: 6px; font-size: 16px; } +.unit-root[data-density="touch"] .unit-check-box { border-radius: var(--unit-radius-small); font-size: 16px; } .unit-root[data-density="touch"] .unit-radio-dot { width: 10px; height: 10px; border-radius: 5px; } -.unit-root[data-density="touch"] .unit-switch-track { width: 51px; height: 31px; border-radius: 16px; } -.unit-root[data-density="touch"] .unit-switch-knob { width: 27px; height: 27px; border-radius: 14px; } +.unit-root[data-density="touch"] .unit-switch-track { width: 51px; height: 31px; } +.unit-root[data-density="touch"] .unit-switch-knob { width: 27px; height: 27px; } .unit-segmented { display: inline-flex; align-self: flex-start; max-width: 100%; height: var(--unit-control-height); padding: 0 2px; gap: 2px; background: var(--unit-track); border-radius: var(--unit-radius); } /* A segment is the groove's whole height, which a press lands in; its face is drawn 2px in from the groove's edge. */ .unit-segment { display: flex; min-width: 0; padding: 2px 0; } -.unit-segment-face { display: block; flex: 1; min-width: 0; padding: 0 10px; border-radius: 4px; +.unit-segment-face { display: block; flex: 1; min-width: 0; padding: 0 10px; border-radius: var(--unit-radius-small); line-height: calc(var(--unit-control-height) - 4px); text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .unit-segment:hover .unit-segment-face { background: var(--unit-control-hover); } .unit-segment.on .unit-segment-face { background: var(--unit-raised); - box-shadow: 0 1px 3px var(--unit-shadow); } -.unit-root[data-density="touch"] .unit-segment-face { border-radius: 8px; } + box-shadow: var(--unit-raised-shadow); } /* Swatches: colour circles, the chosen one ringed off from its neighbours */ .unit-swatches { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; @@ -234,12 +261,12 @@ pub const CSS: &str = r#" height: var(--unit-control-height); padding: 2px; background: var(--unit-track); border-radius: var(--unit-radius); } .unit-step { display: flex; align-items: center; justify-content: center; width: 32px; - align-self: stretch; border-radius: 4px; } + align-self: stretch; border-radius: var(--unit-radius-small); } .unit-step:hover { background: var(--unit-control-hover); } .unit-step.off { color: var(--unit-dim); opacity: 0.5; } .unit-stepper-rule { width: 1px; align-self: stretch; margin: 6px 0; background: var(--unit-border); } .unit-root[data-density="touch"] .unit-stepper { height: 32px; } -.unit-root[data-density="touch"] .unit-step { width: 46px; border-radius: 8px; } +.unit-root[data-density="touch"] .unit-step { width: 46px; } /* Slider: the thumb's and the stops' room inside its own box */ .unit-scrollbar:hover .unit-scrollbar-thumb { opacity: 0.85 !important; } @@ -252,7 +279,7 @@ pub const CSS: &str = r#" border-radius: 2px; background: var(--unit-accent); } .unit-slider-thumb { position: absolute; top: 50%; width: 16px; height: 16px; margin: -8px 0 0 -8px; border-radius: 8px; background: #ffffff; - border: 1px solid var(--unit-separator); box-shadow: 0 1px 3px var(--unit-shadow); } + border: 1px solid var(--unit-separator); box-shadow: var(--unit-raised-shadow); } .unit-root[data-density="touch"] .unit-slider-thumb { width: 28px; height: 28px; margin: -14px 0 0 -14px; border-radius: 14px; } .unit-slider-stops { position: absolute; left: 8px; right: 8px; top: 0; bottom: 0; display: flex; } @@ -263,8 +290,8 @@ pub const CSS: &str = r#" .unit-field-label { font-weight: 500; } .unit-input { display: block; width: 100%; height: var(--unit-control-height); padding: 0 8px; margin: 0; font-family: inherit; font-size: inherit; color: var(--unit-text); - background: var(--unit-control); border: 1px solid var(--unit-border); - border-radius: var(--unit-radius); box-shadow: 0 1px 2px var(--unit-shadow-soft); } + background: var(--unit-field); border: var(--unit-field-edge) solid var(--unit-border); + border-radius: var(--unit-radius); box-shadow: var(--unit-control-shadow); } .unit-textarea { height: auto; padding: 6px 8px; } /* A one-time code: a cell for each digit, the field over them unseen, so a @@ -275,9 +302,9 @@ pub const CSS: &str = r#" .unit-code-cells { display: flex; gap: 8px; min-width: 0; } .unit-code-cell { display: flex; align-items: center; justify-content: center; flex: 0 1 auto; min-width: 0; width: 36px; height: 44px; font-size: 1.4em; font-weight: 500; - color: var(--unit-text); background: var(--unit-control); - border: 1px solid var(--unit-border); border-radius: var(--unit-radius); - box-shadow: 0 1px 2px var(--unit-shadow-soft); } + color: var(--unit-text); background: var(--unit-field); + border: var(--unit-field-edge) solid var(--unit-border); border-radius: var(--unit-radius); + box-shadow: var(--unit-control-shadow); } .unit-code-cell.on { border-color: var(--unit-accent); outline: 2px solid var(--unit-focus); outline-offset: 0; } .unit-code-cell .unit-caret { height: 1.1em; } .unit-code.invalid .unit-code-cell { border-color: var(--unit-danger); } @@ -287,18 +314,18 @@ pub const CSS: &str = r#" padding: 0; margin: 0; border: none; font-size: 16px; opacity: 0; background: transparent; } .unit-root[data-density="touch"] .unit-code-cell { width: 42px; height: 52px; font-size: 1.5em; } -.unit-heading { margin: 0 0 6px; font-family: var(--unit-heading-font); font-weight: 700; } +.unit-heading { margin: 0 0 6px; font-family: var(--unit-heading-font); font-weight: var(--unit-heading-weight); } .unit-text { margin: 0 0 6px; } .unit-text.dim, .unit-note { color: var(--unit-dim); } .unit-note { font-size: 0.92em; margin-top: 4px; } /* Choosing among: chips, tabs, a list, a disclosure */ .unit-chips { display: flex; align-self: stretch; flex-wrap: wrap; gap: 6px; } -.unit-chip { padding: 3px 10px; margin: 0; font-family: inherit; font-size: inherit; +.unit-chip { min-height: var(--unit-control-height); padding: 3px 10px; margin: 0; font-family: inherit; font-size: inherit; color: var(--unit-text); background: var(--unit-control); - border: 1px solid var(--unit-border); border-radius: 999px; white-space: nowrap; + border: var(--unit-edge) solid var(--unit-border); border-radius: var(--unit-pill); white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; - box-shadow: 0 1px 2px var(--unit-shadow-soft); } + box-shadow: var(--unit-control-shadow); } .unit-chip:hover { background: var(--unit-control-hover); } .unit-chip.on { background: var(--unit-accent); color: var(--unit-accent-text); border-color: var(--unit-accent); } @@ -308,7 +335,7 @@ pub const CSS: &str = r#" .unit-root[data-density="touch"] .unit-chip { padding: 0 14px; min-height: var(--unit-control-height); } .unit-chip.unit-marked { display: inline-flex; align-items: center; gap: 6px; } .unit-chip-dot { width: 8px; height: 8px; border-radius: 4px; flex: none; } -.unit-chip-badge { font-size: 0.8em; padding: 0 6px; border-radius: 8px; +.unit-chip-badge { font-size: 0.8em; padding: 0 6px; border-radius: var(--unit-pill); background: var(--unit-control-hover); color: var(--unit-dim); } .unit-chip.on .unit-chip-badge { background: transparent; color: inherit; } .unit-tablist { display: flex; gap: 4px; border-bottom: 1px solid var(--unit-separator); } @@ -321,10 +348,10 @@ pub const CSS: &str = r#" .unit-tab.on { color: var(--unit-text); font-weight: 500; border-bottom-color: var(--unit-accent); } .unit-tabpanel { padding-top: 12px; } .unit-listbox { display: flex; flex-direction: column; padding: 4px; overflow: auto; - background: var(--unit-control); border: 1px solid var(--unit-border); + background: var(--unit-control); border: var(--unit-edge) solid var(--unit-border); border-radius: var(--unit-radius); } .unit-option { display: flex; align-items: center; min-height: var(--unit-control-height); - padding: 0 8px; border-radius: 4px; } + padding: 0 8px; border-radius: var(--unit-radius-small); } .unit-option:hover { background: var(--unit-control-hover); } .unit-option.on { background: var(--unit-accent); color: var(--unit-accent-text); } .unit-disclosure-title { display: flex; align-items: center; gap: 6px; width: 100%; @@ -339,8 +366,8 @@ pub const CSS: &str = r#" .unit-section-title { padding: 0 14px; font-size: 0.85em; color: var(--unit-dim); } .unit-section-footer { padding: 0 14px; font-size: 0.85em; color: var(--unit-dim); } .unit-section-body { display: flex; flex-direction: column; overflow: hidden; - background: var(--unit-surface); border: 1px solid var(--unit-separator); - border-radius: var(--unit-radius-large); } + background: var(--unit-surface); border: var(--unit-surface-edge) solid var(--unit-separator); + border-radius: var(--unit-radius-large); box-shadow: var(--unit-surface-shadow); } .unit-section-body > * { border-top: 1px solid var(--unit-separator); } .unit-section-body > *:first-child { border-top: none; } .unit-section-body > *:not(.unit-row):not(.unit-row-pair):not(.unit-segmented) { padding: 6px 14px; } @@ -387,7 +414,7 @@ pub const CSS: &str = r#" .unit-navbar-side { display: flex; align-items: center; flex: 1 0 0; } .unit-navbar-end { justify-content: flex-end; } .unit-navbar-title { flex: 0 1 auto; min-width: 0; text-align: center; font-family: var(--unit-heading-font); - font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + font-weight: var(--unit-heading-weight); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .unit-button.unit-navbar-title { display: flex; } .unit-navbar-title > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; } /* Back's word is a column that asks for its width and needs none, so the @@ -425,8 +452,8 @@ pub const CSS: &str = r#" .unit-modal-place.unit-sheet-place { justify-content: flex-end; padding: 0; } .unit-modal { max-width: 100%; max-height: 100%; overflow: auto; padding: 14px 16px; background: var(--unit-surface); color: var(--unit-text); - border: 1px solid var(--unit-border); border-radius: var(--unit-radius-large); - box-shadow: 0 12px 40px var(--unit-shadow); } + border: var(--unit-float-edge) solid var(--unit-border); border-radius: var(--unit-radius-large); + box-shadow: var(--unit-float-shadow); } .unit-modal.unit-sheet { width: 100%; border-bottom-left-radius: 0; border-bottom-right-radius: 0; padding-bottom: 28px; } .unit-modal-head { display: flex; align-items: center; justify-content: space-between; @@ -434,7 +461,7 @@ pub const CSS: &str = r#" .unit-modal-head .unit-dialog-title { margin: 0; } .unit-sheet .unit-modal-head, .unit-sheet-grabber { touch-action: none; } .unit-sheet-grabber { display: flex; justify-content: center; padding: 0 0 8px; margin-top: -6px; } -.unit-sheet-grabber-bar { width: 36px; height: 5px; border-radius: 3px; background: var(--unit-track); } +.unit-sheet-grabber-bar { width: 36px; height: 5px; border-radius: var(--unit-pill); background: var(--unit-track); } .unit-modal-head.unit-phone-bar .unit-dialog-title { flex: 1; text-align: center; } .unit-modal-side { display: flex; flex: 1 1 0; } .unit-modal-side.unit-modal-end { justify-content: flex-end; } @@ -446,8 +473,8 @@ pub const CSS: &str = r#" .unit-spacer { flex: 1; } .unit-card { display: flex; flex-direction: column; gap: var(--unit-gap); padding: 14px 16px; background: var(--unit-surface); - border: 1px solid var(--unit-separator); border-radius: var(--unit-radius-large); - box-shadow: 0 1px 3px var(--unit-shadow-soft); } + border: var(--unit-surface-edge) solid var(--unit-separator); border-radius: var(--unit-radius-large); + box-shadow: var(--unit-surface-shadow); } .unit-card-title { margin: 0 0 2px; font-family: var(--unit-heading-font); font-size: 1.08em; font-weight: 600; } .unit-divider { height: 1px; background: var(--unit-separator); margin: 4px 0; } .unit-form-row { display: flex; align-items: flex-start; gap: var(--unit-gap); } @@ -456,11 +483,13 @@ pub const CSS: &str = r#" .unit-root[data-density="touch"] .unit-form-row { flex-direction: column; align-items: stretch; gap: 4px; } .unit-root[data-density="touch"] .unit-form-label { width: auto; text-align: left; } .unit-badge { display: inline-block; padding: 1px 7px; font-size: 0.85em; font-weight: 500; - border-radius: 999px; background: var(--unit-track); border: 1px solid var(--unit-track); } -.unit-badge.unit-success { background: var(--unit-success); border-color: var(--unit-success); color: #ffffff; } -.unit-badge.unit-warning { background: var(--unit-warning); border-color: var(--unit-warning); color: #ffffff; } -.unit-badge.unit-danger { background: var(--unit-danger); border-color: var(--unit-danger); color: #ffffff; } -.unit-progress { height: 6px; overflow: hidden; border-radius: 3px; background: var(--unit-track); } + border-radius: var(--unit-pill); background: var(--unit-track); border: 1px solid var(--unit-track); } +/* A badge's tone is a fill under the accent's text: white, or dark where a + theme's dark tones are light. */ +.unit-badge.unit-success { background: var(--unit-success); border-color: var(--unit-success); color: var(--unit-accent-text); } +.unit-badge.unit-warning { background: var(--unit-warning); border-color: var(--unit-warning); color: var(--unit-accent-text); } +.unit-badge.unit-danger { background: var(--unit-danger); border-color: var(--unit-danger); color: var(--unit-accent-text); } +.unit-progress { height: 6px; overflow: hidden; border-radius: var(--unit-pill); background: var(--unit-track); } .unit-progress-fill { height: 100%; background: var(--unit-accent); } .unit-callout { display: flex; align-items: flex-start; gap: 8px; padding: 10px 12px; border-radius: var(--unit-radius); @@ -484,7 +513,7 @@ pub const CSS: &str = r#" .unit-tilegrid.fill .unit-tile { min-width: 0; } .unit-tilegrid.fill .unit-tile-face { width: 100%; } .unit-tile-action { position: absolute; right: 4px; top: 4px; - background: var(--unit-surface); box-shadow: 0 1px 3px var(--unit-shadow); } + background: var(--unit-surface); box-shadow: var(--unit-raised-shadow); } .unit-tile-face { display: flex; align-items: center; justify-content: center; position: relative; overflow: hidden; border-radius: var(--unit-radius); background: var(--unit-track); border: 2px solid transparent; } @@ -495,14 +524,15 @@ pub const CSS: &str = r#" outline-offset: 1px; } .unit-tile-text { display: flex; flex-direction: column; align-items: center; padding-top: 6px; min-width: 0; } .unit-tile-label { display: block; max-width: 100%; height: 18px; line-height: 18px; padding: 0 5px; - border-radius: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + border-radius: var(--unit-radius-small); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .unit-tile-detail { display: block; max-width: 100%; height: 16px; line-height: 16px; font-size: 11px; color: var(--unit-dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .unit-tile.on .unit-tile-label { background: var(--unit-selection); color: var(--unit-text); } .unit-root[data-density="touch"] .unit-tile-label { height: 22px; line-height: 22px; } .unit-root[data-density="touch"] .unit-tile-detail { height: 20px; line-height: 20px; font-size: 14px; } .unit-table { display: flex; flex-direction: column; overflow: hidden; border-radius: var(--unit-radius); - border: 1px solid var(--unit-separator); background: var(--unit-surface); } + border: var(--unit-surface-edge) solid var(--unit-separator); background: var(--unit-surface); + box-shadow: var(--unit-surface-shadow); } .unit-thead { display: flex; align-items: center; border-bottom: 1px solid var(--unit-separator); min-height: var(--unit-control-height); } .unit-th { display: flex; align-items: center; padding: 0 8px; font-size: 0.92em; font-weight: 600; @@ -582,6 +612,10 @@ mod tests { r.item ))); assert!(CSS.contains(&format!(".unit-sep {{ height: {}px", r.separator))); + assert!(CSS.contains(&format!( + ".unit-palette {{ display: flex; height: {}px", + r.palette + ))); assert!(CSS.contains(&format!( ".unit-menu {{ position: absolute; padding: {}px 0", r.pad @@ -589,11 +623,13 @@ mod tests { let t = Sizes::TOUCH; assert!(CSS.contains(&format!(".unit-item {{ height: {}px", t.item))); assert!(CSS.contains(&format!(".unit-sep {{ height: {}px", t.separator))); + assert!(CSS.contains(&format!(".unit-palette {{ height: {}px", t.palette))); assert!(CSS.contains(&format!(".unit-menu {{ padding: {}px 0", t.pad))); let c = Sizes::CELL; let cell = |rule: &str| format!(".unit-root[data-density=\"cell\"] {rule}"); assert!(CSS.contains(&cell(&format!(".unit-item {{ height: {}px", c.item)))); assert!(CSS.contains(&cell(&format!(".unit-sep {{ height: {}px", c.separator)))); + assert!(CSS.contains(&cell(&format!(".unit-palette {{ height: {}px", c.palette)))); // The cell density's pad is its padding and its 1px border. assert!(CSS.contains(&cell(&format!( ".unit-menu {{ padding: {}px 0", diff --git a/src/theme.rs b/src/theme.rs index c4624b6..64bbc73 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -1,12 +1,19 @@ -//! The theme: every colour, radius and size a component uses is a CSS custom -//! property, and a [`Theme`] is the values of those properties — a palette -//! for the light appearance, one for the dark, and the sizes. [`Theme::css`] +//! The theme: every colour, radius, edge, shadow and size a component uses +//! is a CSS custom property, and a [`Theme`] is the values of those +//! properties — a palette for the light appearance, one for the dark, the +//! sizes of each density, and a [`Shape`]: how thick an edge is, how round a +//! pill, how deep a shadow. [`Theme::css`] //! writes them out, under the root's `data-appearance` and `data-density`, //! so a page forces an appearance or a touch density with an attribute and //! nothing is written twice by hand. //! //! The names follow one scheme, `--unit-`, and the component styles //! (`style.rs`) use nothing else, so a host restyles everything from here. +//! +//! unit ships three: [`Theme::default`], its own; [`Theme::soft`], rounder +//! and quieter, its faces drawn by fill rather than edge, on Diaryx's warm +//! neutrals; and [`Theme::sharp`], square, ruled and flat. [`Theme::all`] +//! lists them by name, for a page that offers a choice. use std::fmt::Write; @@ -21,6 +28,10 @@ pub struct Palette { pub control: &'static str, /// A control's face under the pointer. pub control_hover: &'static str, + /// The face of what is typed in or ticked: a field, a code's cells, a + /// checkbox, a radio's ring. A control's own face unless a theme sets + /// buttons apart by fill and fields by an edge on a lighter face. + pub field: &'static str, /// A groove a control sits in: a segmented control's, a switch's when /// off, a slider's rail, a progress bar's. pub track: &'static str, @@ -58,6 +69,7 @@ impl Palette { surface: "#ffffff", control: "#ffffff", control_hover: "#f2f2f4", + field: "#ffffff", track: "#e6e6ea", raised: "#ffffff", text: "#1d1d1f", @@ -81,6 +93,7 @@ impl Palette { surface: "#2a2a2c", control: "#3a3a3c", control_hover: "#444446", + field: "#3a3a3c", track: "#3a3a3c", raised: "#636366", text: "#ececee", @@ -99,6 +112,110 @@ impl Palette { shadow_soft: "rgba(0, 0, 0, 0.3)", }; + /// [`Theme::soft`]'s light: Diaryx's warm paper and ink, its blue. + pub const SOFT_LIGHT: Palette = Palette { + bg: "#f4f3ef", + surface: "#fcfcfb", + control: "#e9e8e3", + control_hover: "#e0dfd9", + field: "#fcfcfb", + track: "#e4e3dd", + raised: "#fcfcfb", + text: "#1a1a19", + dim: "#63615b", + // A field's and a checkbox's edge: 3:1 on the paper, as WCAG asks + // of what shows where a control is. Rules are the separator's. + border: "#8e8b84", + separator: "#e6e4de", + accent: "#2163c0", + accent_text: "#ffffff", + danger: "#c2301c", + success: "#2a7444", + warning: "#94600f", + focus: "#2163c0", + scrim: "rgba(26, 26, 25, 0.22)", + selection: "#d3e3f7", + shadow: "rgba(40, 36, 28, 0.16)", + shadow_soft: "rgba(40, 36, 28, 0.06)", + }; + + /// [`Theme::soft`]'s dark: warm greys, never black, and a light blue + /// with dark text on it, which reads both as a fill and as a link on + /// the dark ground (no one blue does both with white text). + pub const SOFT_DARK: Palette = Palette { + bg: "#161615", + surface: "#211f1e", + control: "#2e2c2a", + control_hover: "#383633", + field: "#1b1a19", + track: "#2e2c2a", + raised: "#4a4744", + text: "#efeee9", + dim: "#a19f97", + border: "#76736c", + separator: "#2f2d2b", + accent: "#6fa6ee", + accent_text: "#0c1a2e", + danger: "#f0604a", + success: "#4cc475", + warning: "#e7a83e", + focus: "#6fa6ee", + scrim: "rgba(0, 0, 0, 0.5)", + selection: "#28456b", + shadow: "rgba(0, 0, 0, 0.55)", + shadow_soft: "rgba(0, 0, 0, 0.25)", + }; + + /// [`Theme::sharp`]'s light: white, black ink, and rules in between. + pub const SHARP_LIGHT: Palette = Palette { + bg: "#ffffff", + surface: "#ffffff", + control: "#ffffff", + control_hover: "#f0f0f0", + field: "#ffffff", + track: "#e8e8e8", + raised: "#ffffff", + text: "#111111", + dim: "#5f5f5f", + border: "#111111", + separator: "#d0d0d0", + accent: "#111111", + accent_text: "#ffffff", + danger: "#c4161c", + success: "#1d7a35", + warning: "#9a5b00", + focus: "#0050d0", + scrim: "rgba(255, 255, 255, 0.6)", + selection: "#dddddd", + shadow: "rgba(0, 0, 0, 0)", + shadow_soft: "rgba(0, 0, 0, 0)", + }; + + /// [`Theme::sharp`]'s dark: the light turned over. + pub const SHARP_DARK: Palette = Palette { + bg: "#0a0a0a", + surface: "#0a0a0a", + control: "#0a0a0a", + control_hover: "#1e1e1e", + field: "#0a0a0a", + track: "#262626", + raised: "#0a0a0a", + text: "#f2f2f2", + dim: "#a3a3a3", + border: "#f2f2f2", + separator: "#3a3a3a", + accent: "#f2f2f2", + accent_text: "#0a0a0a", + danger: "#ff5a52", + success: "#3ccf6a", + warning: "#ffb340", + focus: "#6ea2ff", + scrim: "rgba(0, 0, 0, 0.6)", + selection: "#3a3a3a", + shadow: "rgba(0, 0, 0, 0)", + shadow_soft: "rgba(0, 0, 0, 0)", + }; + /// This palette with the system's accent, focus ring and selection. pub(crate) fn with(mut self, system: SystemColours) -> Palette { self.accent = system.accent; @@ -107,12 +224,13 @@ impl Palette { self } - fn entries(&self) -> [(&'static str, &'static str); 20] { + fn entries(&self) -> [(&'static str, &'static str); 21] { [ ("bg", self.bg), ("surface", self.surface), ("control", self.control), ("control-hover", self.control_hover), + ("field", self.field), ("track", self.track), ("raised", self.raised), ("text", self.text), @@ -163,9 +281,14 @@ pub struct Metrics { pub font_size: f64, /// The gap between controls in a row or a stack. pub gap: f64, - /// A control's corners, and a raised surface's. + /// A control's corners. pub radius: f64, + /// A raised surface's corners: a card, a group of rows, a menu, a + /// dialog. pub radius_large: f64, + /// The corners of what sits inside a control or a surface: a menu's + /// highlighted row, a segment's face, a checkbox. + pub radius_small: f64, } impl Metrics { @@ -176,6 +299,7 @@ impl Metrics { gap: 8.0, radius: 6.0, radius_large: 10.0, + radius_small: 4.0, }; /// For a finger: 44-point targets, as Apple's guidelines ask. @@ -185,6 +309,7 @@ impl Metrics { gap: 12.0, radius: 10.0, radius_large: 14.0, + radius_small: 8.0, }; /// For a terminal's cells ([`Density::Cell`]): a control a row high, @@ -196,19 +321,147 @@ impl Metrics { gap: 10.0, radius: 0.0, radius_large: 0.0, + radius_small: 0.0, }; - fn entries(&self) -> [(&'static str, f64); 5] { + /// These sizes with other corners: what a theme of another shape + /// changes and nothing else, as [`Theme::soft`] and [`Theme::sharp`] do. + pub const fn rounded(mut self, radius: f64, large: f64, small: f64) -> Metrics { + self.radius = radius; + self.radius_large = large; + self.radius_small = small; + self + } + + fn entries(&self) -> [(&'static str, f64); 6] { [ ("control-height", self.control), ("font-size", self.font_size), ("gap", self.gap), ("radius", self.radius), ("radius-large", self.radius_large), + ("radius-small", self.radius_small), ] } } +/// What a theme's pieces are shaped like, at every density: the edges they +/// are drawn with, how round a pill is, how far what floats stands off the +/// page, and how a menu's rows sit in it. The corners are [`Metrics`]', +/// since they grow with a finger's sizes. +#[derive(Clone, Debug, PartialEq)] +pub struct Shape { + /// A control's edge, in pixels: a button's, a chip's, a list's. 0 + /// draws a face by its fill alone. + pub edge: f64, + /// The edge of what is typed in or ticked: a field, a code's cells, a + /// checkbox, a radio's ring. Its edge is what shows where it is, so a + /// theme keeps it where it draws buttons by fill alone. + pub field_edge: f64, + /// A raised surface's edge: a card's, a group of rows', a table's. + pub surface_edge: f64, + /// The edge of what floats over the page: a menu, a dialog, a toast. + pub float_edge: f64, + /// The corners of a pill, in pixels: a chip, a badge, a switch, a + /// radio's ring. Half its height or more is round. + pub pill: f64, + /// The shadow under a control, as CSS; `none` for none. It may name the + /// palette's shadows: `var(--unit-shadow-soft)`. + pub control_shadow: &'static str, + /// The shadow under a card and a group of rows. + pub surface_shadow: &'static str, + /// The shadow under a menu, a dialog, a toast: what floats. + pub float_shadow: &'static str, + /// The shadow under the chosen segment and a switch's knob: what stands + /// up from a groove. + pub raised_shadow: &'static str, + /// How far a menu's rows stand in from its sides, so a highlighted row + /// is a rounded bar within it (5) or the menu's whole width (0). + pub menu_inset: f64, + /// The focus ring's width. + pub focus_ring: f64, + /// The weight of a heading, a card's title and a dialog's. + pub heading_weight: u16, +} + +impl Shape { + /// unit's own: hairline edges on every control, round pills, and soft + /// shadows under what floats. + pub const DEFAULT: Shape = Shape { + edge: 1.0, + field_edge: 1.0, + surface_edge: 1.0, + float_edge: 1.0, + pill: 999.0, + control_shadow: "0 1px 2px var(--unit-shadow-soft)", + surface_shadow: "0 1px 3px var(--unit-shadow-soft)", + float_shadow: "0 8px 24px var(--unit-shadow)", + raised_shadow: "0 1px 3px var(--unit-shadow)", + menu_inset: 5.0, + focus_ring: 2.0, + heading_weight: 700, + }; + + /// [`Theme::soft`]'s: buttons and chips drawn by fill, not edge, but + /// fields and checkboxes still edged; surfaces lifted by + /// a shadow rather than ruled; a wide, soft shadow under what floats. + pub const SOFT: Shape = Shape { + edge: 0.0, + field_edge: 1.0, + surface_edge: 0.0, + float_edge: 0.0, + pill: 999.0, + control_shadow: "none", + surface_shadow: "0 1px 2px var(--unit-shadow-soft), 0 0 0 1px var(--unit-shadow-soft)", + float_shadow: "0 0 0 1px var(--unit-shadow-soft), 0 12px 32px var(--unit-shadow)", + raised_shadow: "0 1px 2px var(--unit-shadow), 0 0 0 1px var(--unit-shadow-soft)", + menu_inset: 6.0, + focus_ring: 3.0, + heading_weight: 600, + }; + + /// [`Theme::sharp`]'s: square, ruled edges everywhere, and nothing that + /// casts a shadow. + pub const SHARP: Shape = Shape { + edge: 1.0, + field_edge: 1.0, + surface_edge: 1.0, + float_edge: 1.0, + pill: 0.0, + control_shadow: "none", + surface_shadow: "none", + float_shadow: "4px 4px 0 var(--unit-separator)", + raised_shadow: "none", + menu_inset: 0.0, + focus_ring: 2.0, + heading_weight: 800, + }; + + fn entries(&self) -> [(&'static str, String); 12] { + let px = |v: f64| format!("{v}px"); + [ + ("edge", px(self.edge)), + ("field-edge", px(self.field_edge)), + ("surface-edge", px(self.surface_edge)), + ("float-edge", px(self.float_edge)), + ("pill", px(self.pill)), + ("control-shadow", self.control_shadow.to_string()), + ("surface-shadow", self.surface_shadow.to_string()), + ("float-shadow", self.float_shadow.to_string()), + ("raised-shadow", self.raised_shadow.to_string()), + ("menu-inset", px(self.menu_inset)), + ("focus-ring", px(self.focus_ring)), + ("heading-weight", self.heading_weight.to_string()), + ] + } +} + +impl Default for Shape { + fn default() -> Self { + Shape::DEFAULT + } +} + /// Which appearance a page shows. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Appearance { @@ -261,6 +514,8 @@ impl Density { /// Everything a page's components are drawn with. #[derive(Clone, Debug, PartialEq)] pub struct Theme { + /// What a page that offers a choice of themes calls it. + pub name: &'static str, pub light: Palette, pub dark: Palette, pub regular: Metrics, @@ -271,6 +526,8 @@ pub struct Theme { /// The headings' font stack: a heading, a card's and a dialog's title. /// The text's unless a page sets its own, a serif over a sans text. pub heading_font: &'static str, + /// The edges, pills and shadows. + pub shape: Shape, } /// The system's text face, on each platform. @@ -279,6 +536,7 @@ pub const SYSTEM_FONT: &str = "system-ui, -apple-system, \"Segoe UI\", Roboto, s impl Default for Theme { fn default() -> Self { Self { + name: "Unit", light: Palette::LIGHT, dark: Palette::DARK, regular: Metrics::REGULAR, @@ -286,11 +544,57 @@ impl Default for Theme { cell: Metrics::CELL, font: SYSTEM_FONT, heading_font: SYSTEM_FONT, + shape: Shape::DEFAULT, } } } impl Theme { + /// Soft: what Diaryx is drawn in. Diaryx's warm paper and ink and its + /// blue; rounder corners; faces told apart by fill rather than edge; + /// groups of rows and cards lifted by a shadow rather than ruled, and + /// what floats on a wide, soft one. A finger's sizes and a terminal's + /// cells are unit's own, but rounder for a finger. + pub fn soft() -> Theme { + Theme { + name: "Soft", + light: Palette::SOFT_LIGHT, + dark: Palette::SOFT_DARK, + regular: Metrics::REGULAR.rounded(8.0, 12.0, 6.0), + touch: Metrics::TOUCH.rounded(12.0, 18.0, 10.0), + shape: Shape::SOFT, + ..Theme::default() + } + } + + /// Sharp: square corners, every edge ruled in ink, and no shadow but a + /// flat offset under what floats. + pub fn sharp() -> Theme { + Theme { + name: "Sharp", + light: Palette::SHARP_LIGHT, + dark: Palette::SHARP_DARK, + regular: Metrics::REGULAR.rounded(0.0, 0.0, 0.0), + touch: Metrics::TOUCH.rounded(0.0, 0.0, 0.0), + shape: Shape::SHARP, + ..Theme::default() + } + } + + /// Every theme unit ships, its own first: for a page that offers them. + pub fn all() -> Vec { + vec![Theme::default(), Theme::soft(), Theme::sharp()] + } + + /// The sizes of `density`. + pub fn metrics(&self, density: Density) -> &Metrics { + match density { + Density::Regular => &self.regular, + Density::Touch => &self.touch, + Density::Cell => &self.cell, + } + } + /// The custom properties, for the root (`.unit-root`): the light palette /// unless the system or the root asks for the dark, and the regular /// sizes unless the root asks for touch. @@ -309,6 +613,9 @@ impl Theme { s.push_str(".unit-root {\n"); let _ = writeln!(s, " --unit-font: {};", self.font); let _ = writeln!(s, " --unit-heading-font: {};", self.heading_font); + for (name, value) in self.shape.entries() { + let _ = writeln!(s, " --unit-{name}: {value};"); + } palette(&mut s, &self.light); metrics(&mut s, &self.regular); s.push_str("}\n"); @@ -325,6 +632,11 @@ impl Theme { s.push_str("}\n"); s.push_str(".unit-root[data-density=\"cell\"] {\n"); metrics(&mut s, &self.cell); + // Cells draw no curve and no shadow, whatever the theme's shape. + s.push_str(" --unit-pill: 0px;\n"); + for shadow in ["control", "surface", "float", "raised"] { + let _ = writeln!(s, " --unit-{shadow}-shadow: none;"); + } s.push_str("}\n"); s } @@ -362,6 +674,47 @@ mod tests { assert!(css.contains("[data-density=\"touch\"]")); } + /// Every theme unit ships sets every property, and is told apart by + /// its name. + #[test] + fn every_shipped_theme_is_whole_and_named() { + let all = Theme::all(); + let names: Vec<_> = all.iter().map(|t| t.name).collect(); + assert_eq!(names, ["Unit", "Soft", "Sharp"]); + let reference = Theme::default().css(); + let declared = |css: &str| -> Vec { + css.lines() + .filter_map(|l| l.trim().strip_prefix("--unit-")) + .map(|l| l[..l.find(':').unwrap()].to_string()) + .collect() + }; + for theme in &all { + assert_eq!( + declared(&theme.css()), + declared(&reference), + "{}", + theme.name + ); + } + } + + /// A theme's shape reaches the page: Sharp is square and casts no + /// shadow, Soft draws its controls without an edge. + #[test] + fn a_theme_changes_shapes_as_well_as_colours() { + let sharp = Theme::sharp().css(); + assert!(sharp.contains("--unit-pill: 0px;"), "{sharp}"); + assert!(sharp.contains("--unit-radius-large: 0px;"), "{sharp}"); + assert!(sharp.contains("--unit-control-shadow: none;"), "{sharp}"); + let soft = Theme::soft().css(); + assert!(soft.contains("--unit-edge: 0px;"), "{soft}"); + assert!(soft.contains("--unit-radius-large: 12px;"), "{soft}"); + assert!(soft.contains("--unit-accent: #2163c0;"), "{soft}"); + // Cells round nothing, in any theme. + let cell = &soft[soft.find("[data-density=\"cell\"]").unwrap()..]; + assert!(cell.contains("--unit-pill: 0px;") && cell.contains("--unit-float-shadow: none;")); + } + #[test] fn headings_take_their_own_font() { let theme = Theme {