ui_kit: lit sphere thumbnail and look-chain widget (#6281) (#6284)

* claim: #6281

* ui_kit: lit sphere thumbnail, cached and bounded

* ui_kit: look-chain widget (four steps, one active, empty steps dashed)

* ui_kit: add both to the gallery and the UI kit notes
This commit is contained in:
Nathan Dane authored and GitHub committed 2026-10-27 11:52:55 +00:00
1 parent 44a0be8d94
commit 192ef78ff3
7 files changed
+447

No files matched your search

+69
View File
@@ -29,6 +29,36 @@ macro_rules! element {
// One entry per element/variant: names, rendering and geometry expectations stay together.
const ELEMENTS: &[Element] = &[
element!("sphere_thumbnail", |ui, _| {
ui.horizontal(|ui| {
for kind in [FinishKind::Matte, FinishKind::Satin, FinishKind::Gloss, FinishKind::Metal, FinishKind::Glass] {
sphere_thumbnail(
ui,
&format!("gallery:sphere:{kind:?}"),
Sphere { color: Tokens::get().render_accent, kind, opacity: None },
Tokens::get().space_24 * 2.0,
);
}
});
}),
element!("look_chain", "gallery:chain", Some("gallery:chain:body"), |ui, _| {
let t = Tokens::get();
look_chain(
ui,
"gallery:chain",
["Face", "Body", "Component", "Material"],
[
None,
Some(Sphere { color: t.render_accent, kind: FinishKind::Satin, opacity: None }),
None,
Some(Sphere { color: t.control_border, kind: FinishKind::Metal, opacity: None }),
],
LookStep::Body,
);
}),
element!("look_chain_empty", |ui, _| {
look_chain(ui, "gallery:empty-chain", ["Face", "Body", "Component", "Material"], [None; 4], LookStep::Face);
}),
element!("settings_form", |ui, state| {
settings_form(ui, Tokens::get().form_label_width, |ui| {
row(ui, "Sample", |ui| {
@@ -1400,10 +1430,12 @@ fn gallery_covers_every_inline_element() {
"disclosure.rs",
"fields.rs",
"layout.rs",
"look_chain.rs",
"menu.rs",
"metrics.rs",
"radial.rs",
"reports.rs",
"sphere.rs",
"status.rs",
"table.rs",
] {
@@ -1956,3 +1988,40 @@ fn file_view_application_evidence_in_both_themes_and_widths() {
std::fs::remove_file(path).unwrap();
std::fs::remove_dir(fixture_dir).unwrap();
}
/// CPU-rendered review board using the actual gallery widgets, without a window.
#[test]
fn material_widgets_board_in_both_themes() {
use super::checks::tests::{raster, textures_update};
use std::collections::HashMap;
let previous = crate::theme::is_dark();
for dark in [false, true] {
crate::theme::set_dark(dark);
let ctx = crate::fonts::test_context();
let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 240.0));
let mut textures = HashMap::new();
let mut image = None;
for _ in 0..3 {
let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(bounds), ..Default::default() }, |ui| {
ui.set_width(320.0);
ui.painter().rect_filled(bounds, 0.0, Tokens::get().panel);
scope(ui, |ui| {
for name in ["sphere_thumbnail", "look_chain", "look_chain_empty"] {
example(ui, ELEMENTS.iter().find(|e| e.name == name).unwrap());
ui.add_space(Tokens::get().space_12);
}
});
});
textures_update(&mut textures, &output.textures_delta);
output.textures_delta.clear();
image = Some(raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures));
}
let image = image.unwrap();
assert!(image.pixels().any(|p| p.0[3] != 0));
if let Some(dir) = std::env::var_os("SOLIDCRAFT_MATERIAL_WIDGET_EVIDENCE") {
std::fs::create_dir_all(&dir).unwrap();
image.save(std::path::Path::new(&dir).join(if dark { "material-widgets-dark.png" } else { "material-widgets-light.png" })).unwrap();
}
}
crate::theme::set_dark(previous);
}
+89
View File
@@ -0,0 +1,89 @@
//! Appearance inheritance selector. The caller owns selection and commands.
use super::{Sphere, sphere::paint_sphere};
use crate::{scenario, theme::Tokens};
use egui::{Rect, Sense, Stroke, Ui, pos2, vec2};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LookStep {
Face,
Body,
Component,
Material,
}
impl LookStep {
pub const ALL: [Self; 4] = [Self::Face, Self::Body, Self::Component, Self::Material];
fn name(self) -> &'static str {
match self {
Self::Face => "face",
Self::Body => "body",
Self::Component => "component",
Self::Material => "material",
}
}
}
/// Labels are caller supplied for translation. `None` is an empty inheritance slot.
/// An enum active value guarantees exactly one active step, including empty steps.
/// Publishes `{id}:{face|body|component|material}` hit targets and the `{id}` allocation.
pub fn look_chain(ui: &mut Ui, id: &str, labels: [&str; 4], looks: [Option<Sphere>; 4], active: LookStep) -> Option<LookStep> {
let t = Tokens::get();
let width = ui.available_width().clamp(1.0, t.form_card_width * 2.0);
let side = t.space_24.min(width / 4.0);
let ring_width = t.space_2.min(side / 8.0);
let height = side + t.space_8 + t.font_small + t.space_4;
let (rect, _) = ui.allocate_exact_size(vec2(width, height), Sense::hover());
let mut clicked = None;
for (index, ((step, label), look)) in LookStep::ALL.into_iter().zip(labels).zip(looks).enumerate() {
let cell_width = width / 4.0;
let cell = Rect::from_min_size(rect.min + vec2(index as f32 * cell_width, 0.0), vec2(cell_width, height));
let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(cell));
let center = pos2(cell.center().x, cell.top() + side / 2.0 + ring_width);
let radius = (side / 2.0 - ring_width * 2.0).max(0.0);
if index < 3 {
ui.painter()
.line_segment([center + vec2(side / 2.0, 0.0), center + vec2(cell_width - side / 2.0, 0.0)], Stroke::new(1.0, t.control_border));
}
let key = format!("{id}:{}", step.name());
let response = ui.interact(cell, ui.make_persistent_id(&key), Sense::click());
response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, ui.is_enabled(), active == step, label));
if response.clicked() {
clicked = Some(step);
}
if let Some(look) = look {
paint_sphere(ui, Rect::from_center_size(center, vec2(radius * 2.0, radius * 2.0)), look);
} else {
// Evenly spaced analytic dashes, independent of any icon asset.
for dash in 0..12 {
let start = dash as f32 * std::f32::consts::TAU / 12.0;
let points = (0..=4)
.map(|n| {
let a = start + n as f32 * std::f32::consts::TAU / 96.0;
center + vec2(a.cos(), a.sin()) * radius
})
.collect();
painter.add(egui::Shape::line(points, Stroke::new(1.0, t.form_dim)));
}
let arm = radius * 0.4;
painter.line_segment([center - vec2(arm, 0.0), center + vec2(arm, 0.0)], Stroke::new(1.0, t.form_dim));
painter.line_segment([center - vec2(0.0, arm), center + vec2(0.0, arm)], Stroke::new(1.0, t.form_dim));
}
if step == active {
painter.circle_stroke(center, radius + ring_width, Stroke::new(ring_width, t.render_accent));
}
let font = egui::FontId::proportional(t.font_small);
let label_width = ui.painter().layout_no_wrap(label.to_owned(), font.clone(), t.form_ink).size().x;
let label_left = (cell.center().x - label_width / 2.0).max(cell.left());
let label_rect = Rect::from_min_max(pos2(label_left, cell.top() + side + t.space_4), cell.max);
super::text::paint_text(ui, label_rect, label, font, t.form_ink, false);
scenario::publish_rect(&key, cell);
scenario::publish_handle(&key, cell.center());
}
scenario::publish_rect(id, rect);
clicked
}
#[cfg(test)]
#[path = "look_chain_tests.rs"]
mod tests;
@@ -0,0 +1,65 @@
use super::*;
use crate::ui_kit::{
FinishKind,
test_support::{frame, pointer},
};
#[test]
fn chain_has_one_active_ring_and_empty_slots_and_returns_each_click() {
let ctx = crate::fonts::test_context();
let t = Tokens::get();
let sphere = Sphere { color: t.render_accent, kind: FinishKind::Satin, opacity: None };
for active in LookStep::ALL {
for filled in [false, true] {
let looks = if filled { [Some(sphere); 4] } else { [None; 4] };
let clicked = std::cell::Cell::new(None);
let mut draw = |ui: &mut Ui| {
clicked.set(look_chain(ui, "chain", ["Face", "Body", "Component", "Material"], looks, active));
};
frame(&ctx, vec![], &mut draw);
assert_eq!(clicked.get(), None);
for step in LookStep::ALL {
let key = format!("chain:{}", step.name());
let pos = scenario::handle_at(&key).unwrap();
assert!(scenario::rect_of("chain").unwrap().contains(pos));
frame(&ctx, pointer(pos, true), &mut draw);
frame(&ctx, pointer(pos, false), &mut draw);
assert_eq!(clicked.get(), Some(step));
}
let output = ctx.run_ui(Default::default(), |ui| {
look_chain(ui, "paint", ["Face", "Body", "Component", "Material"], looks, active);
});
let rings: Vec<_> = output
.shapes
.iter()
.filter_map(|s| match &s.shape {
egui::Shape::Circle(c) if c.stroke.color == t.render_accent => Some(c),
_ => None,
})
.collect();
assert_eq!(rings.len(), 1);
let active_rect = scenario::rect_of(&format!("paint:{}", active.name())).unwrap();
assert_eq!(rings[0].center.x, active_rect.center().x);
let meshes = output.shapes.iter().filter(|s| matches!(s.shape, egui::Shape::Mesh(_))).count();
let dashes = output.shapes.iter().filter(|s| matches!(s.shape, egui::Shape::Path(_))).count();
assert_eq!(meshes, if filled { 4 } else { 0 });
assert_eq!(dashes, if filled { 0 } else { 48 });
}
}
}
#[test]
fn disabled_chain_does_not_return_clicks() {
let ctx = crate::fonts::test_context();
let mut clicked = None;
let mut draw = |ui: &mut Ui| {
ui.add_enabled_ui(false, |ui| {
clicked = look_chain(ui, "disabled", ["Face", "Body", "Component", "Material"], [None; 4], LookStep::Body);
});
};
frame(&ctx, vec![], &mut draw);
let pos = scenario::handle_at("disabled:face").unwrap();
frame(&ctx, pointer(pos, true), &mut draw);
frame(&ctx, pointer(pos, false), &mut draw);
assert_eq!(clicked, None);
}
+4
View File
@@ -14,6 +14,7 @@ mod fields;
mod file_view;
mod history;
mod layout;
mod look_chain;
mod menu;
mod metrics;
pub(crate) mod panel;
@@ -26,6 +27,7 @@ mod radial;
mod reports;
mod search;
mod shortcuts;
mod sphere;
mod status;
mod table;
mod text;
@@ -46,6 +48,7 @@ pub(crate) use fields::*;
pub(crate) use file_view::{FileView, RecentRow, RecoveryMessage, SampleCard};
pub(crate) use history::*;
pub(crate) use layout::*;
pub use look_chain::{LookStep, look_chain};
pub(crate) use menu::{Menu, MenuItem, rename_menu, workspace_menu};
pub(crate) use metrics::{ContentWidth, header_height, row_height, table_row_height};
pub(crate) use panel::{ComputeStatus, FeatureOptions, Panel, Part, WindowPage, panel_header_hover};
@@ -60,6 +63,7 @@ pub(crate) use radial::{RADIAL_RADIUS, radial_menu};
pub(crate) use reports::*;
pub(crate) use search::{CommandSearch, SearchBadge, SearchFieldGeometry};
pub(crate) use shortcuts::*;
pub use sphere::{FinishKind, Sphere, sphere_thumbnail};
pub(crate) use status::*;
pub(crate) use table::*;
pub(crate) use value_focus::*;
+144
View File
@@ -0,0 +1,144 @@
//! Small deterministic material previews; no textures, jobs or graphics device.
use crate::{scenario, theme::Tokens};
use egui::{Color32, Mesh, Rect, Response, Sense, Ui, pos2, vec2};
use std::{collections::VecDeque, sync::Arc};
const CACHE_ENTRIES: usize = 64;
const MAX_SIDE: u16 = 96;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FinishKind {
Matte,
Satin,
Gloss,
Metal,
Glass,
}
/// Colour is document data. All surrounding chrome and checker colours come from Tokens.
#[derive(Clone, Copy, Debug)]
pub struct Sphere {
pub color: Color32,
pub kind: FinishKind,
pub opacity: Option<f32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Key {
color: Color32,
kind: FinishKind,
opacity: u8,
side: u16,
}
impl Sphere {
fn key(self, side: f32) -> Key {
let opacity = self.opacity.filter(|v| v.is_finite()).unwrap_or(if self.kind == FinishKind::Glass { 0.35 } else { 1.0 });
Key {
color: self.color,
kind: self.kind,
opacity: (opacity.clamp(0.0, 1.0) * 255.0).round() as u8,
side: if side.is_finite() { side.round().clamp(1.0, f32::from(MAX_SIDE)) as u16 } else { 1 },
}
}
}
#[derive(Clone, Default)]
struct SphereCache {
entries: VecDeque<(Key, Arc<Mesh>)>,
palette: Option<(Color32, Color32)>,
}
impl SphereCache {
fn mesh(&mut self, key: Key, t: &Tokens) -> Arc<Mesh> {
let palette = (t.on_accent, t.tab_on_fill_dark);
if self.palette != Some(palette) {
self.entries.clear();
self.palette = Some(palette);
}
if let Some((_, mesh)) = self.entries.iter().find(|(stored, _)| *stored == key) {
return mesh.clone();
}
let mesh = Arc::new(shade(key, t));
if self.entries.len() >= CACHE_ENTRIES {
self.entries.pop_front();
}
self.entries.push_back((key, mesh.clone()));
mesh
}
}
fn shade(key: Key, t: &Tokens) -> Mesh {
// Fixed topology bounds both work and memory independently of input size.
const RINGS: u32 = 12;
const SECTORS: u32 = 48;
let mut mesh = Mesh::default();
let radius = f32::from(key.side) * 0.5;
for ring in 0..=RINGS {
let r = ring as f32 / RINGS as f32;
for sector in 0..=SECTORS {
let angle = std::f32::consts::TAU * sector as f32 / SECTORS as f32;
let (x, y) = (r * angle.cos(), r * angle.sin());
let z = (1.0 - r * r).max(0.0).sqrt();
let light = (-0.4 * x - 0.5 * y + 0.76 * z).max(0.0);
let specular = (-0.25 * x - 0.35 * y + 0.902 * z).max(0.0);
let (diffuse, shine) = match key.kind {
FinishKind::Matte => (0.3 + 0.7 * light, 0.04 * specular.powi(8)),
FinishKind::Satin => (0.25 + 0.75 * light, 0.25 * specular.powi(16)),
FinishKind::Gloss => (0.2 + 0.8 * light, 0.85 * specular.powi(64)),
FinishKind::Metal => (0.15 + 0.65 * light, 0.8 * specular.powi(24)),
FinishKind::Glass => (0.5 + 0.5 * light, (0.85 * specular.powi(64) + 0.4 * (1.0 - z).powi(3)).min(1.0)),
};
let shaded = key.color.lerp_to_gamma(t.tab_on_fill_dark, 1.0 - diffuse);
let highlight = if key.kind == FinishKind::Metal { key.color.lerp_to_gamma(t.on_accent, 0.65) } else { t.on_accent };
let color = shaded.lerp_to_gamma(highlight, shine).gamma_multiply(f32::from(key.opacity) / 255.0);
mesh.colored_vertex(pos2(radius + x * radius, radius + y * radius), color);
if ring < RINGS && sector < SECTORS {
let a = ring * (SECTORS + 1) + sector;
let b = a + SECTORS + 1;
mesh.add_triangle(a, b, b + 1);
mesh.add_triangle(a, b + 1, a + 1);
}
}
}
mesh
}
pub(super) fn paint_sphere(ui: &Ui, rect: Rect, sphere: Sphere) {
if !ui.is_rect_visible(rect) {
return;
}
let t = Tokens::get();
let key = sphere.key(rect.width());
let mesh = ui.ctx().data_mut(|data| data.get_temp_mut_or_default::<SphereCache>(egui::Id::new("ui_kit:spheres")).mesh(key, &t));
if sphere.kind == FinishKind::Glass {
// A bounded four-by-four checker remains visible through the sphere.
for y in 0..4 {
for x in 0..4 {
let cell = Rect::from_min_size(rect.min + vec2(x as f32, y as f32) * rect.size() / 4.0, rect.size() / 4.0);
ui.painter().rect_filled(cell, 0.0, if (x + y) % 2 == 0 { t.control_fill } else { t.control_border });
}
}
}
let mut mesh = (*mesh).clone();
let scale = rect.width() / f32::from(key.side);
for vertex in &mut mesh.vertices {
vertex.pos = rect.min + vertex.pos.to_vec2() * scale;
}
ui.painter().add(egui::Shape::mesh(mesh));
}
/// Clamps size to 1–96 logical points. Cache: 64 FIFO entries per egui context.
/// The caller owns commands and may attach interaction to the returned response.
pub fn sphere_thumbnail(ui: &mut Ui, id: &str, sphere: Sphere, size: f32) -> Response {
let side = f32::from(sphere.key(size).side);
let (rect, response) = ui.allocate_exact_size(vec2(side, side), Sense::hover());
paint_sphere(ui, rect, sphere);
scenario::publish_rect(id, rect);
scenario::publish_handle(id, rect.center());
response
}
#[cfg(test)]
#[path = "sphere_tests.rs"]
mod tests;
+46
View File
@@ -0,0 +1,46 @@
use super::*;
#[test]
fn cache_bounds_a_thousand_distinct_inputs_and_evicts_oldest() {
let t = Tokens::light();
let mut cache = SphereCache::default();
let first = Sphere { color: t.render_accent, kind: FinishKind::Satin, opacity: None }.key(32.0);
let initial = cache.mesh(first, &t);
assert!(Arc::ptr_eq(&initial, &cache.mesh(first, &t)), "hits reuse shading");
for index in 0..1000_u16 {
let key = Sphere { color: Color32::from_rgb(index as u8, (index / 256) as u8, 100), kind: FinishKind::Gloss, opacity: Some(0.8) }
.key(f32::from(index));
let mesh = cache.mesh(key, &t);
assert!(cache.entries.len() <= CACHE_ENTRIES);
assert!(key.side <= MAX_SIDE);
assert!(mesh.vertices.len() <= 13 * 49);
assert!(mesh.vertices.iter().all(|v| v.pos.is_finite() && v.pos.x <= f32::from(MAX_SIDE) && v.pos.y <= f32::from(MAX_SIDE)));
}
assert_eq!(cache.entries.len(), CACHE_ENTRIES);
assert!(!cache.entries.iter().any(|(key, _)| *key == first));
assert!(!Arc::ptr_eq(&initial, &cache.mesh(first, &t)));
let mut changed_palette = Tokens::dark();
changed_palette.on_accent = t.render_accent;
cache.mesh(first, &changed_palette);
assert_eq!(cache.entries.len(), 1, "theme changes discard shaded colours");
}
#[test]
fn sphere_inputs_are_finite_bounded_and_finishes_differ() {
let t = Tokens::light();
let sphere = Sphere { color: t.render_accent, kind: FinishKind::Glass, opacity: Some(f32::NAN) };
for size in [f32::NAN, f32::INFINITY, -2.0, 0.0, f32::MAX] {
let key = sphere.key(size);
assert!((1..=MAX_SIDE).contains(&key.side));
assert_eq!(key.opacity, 89);
}
let mut previous = None;
for kind in [FinishKind::Matte, FinishKind::Satin, FinishKind::Gloss, FinishKind::Metal, FinishKind::Glass] {
let mesh = shade(Sphere { kind, opacity: Some(1.0), ..sphere }.key(32.0), &t);
let colors: Vec<_> = mesh.vertices.iter().map(|v| v.color).collect();
if let Some(previous) = previous {
assert_ne!(colors, previous);
}
previous = Some(colors);
}
}
+30
View File
@@ -558,3 +558,33 @@ shared renderer snapshots that palette into the icon look and cache identity;
callers continue to request semantic icon IDs and surface-specific monochrome ink.
See [the shipped-theme colour audit](theme-colour-audit.md) for the schema,
workspace assignments, accessibility rules and intentionally monochrome themes.
## Material previews and look chains
`sphere_thumbnail(ui, id, Sphere { color, kind, opacity }, size)` paints a lit
sphere using a fixed CPU mesh and the egui painter, without a texture or GPU.
`FinishKind` covers Matte, Satin, Gloss, Metal and Glass. Colour is document data;
highlights, shadows, checker and UI chrome use `Tokens`. Glass shows a four-by-four
checker and defaults to 35% opacity; other finishes default to opaque. Explicit
opacity is clamped to 0–1; non-finite opacity uses the finish default. Sizes are
rounded and bounded to 1–96 logical points (non-finite sizes become 1).
A shared per-egui-context FIFO cache retains at most 64 meshes, keyed by RGBA,
finish, byte opacity and bounded size. Hits reuse shading without changing eviction
order. Every mesh has 637 vertices and 1,152 triangles, independently of input.
Theme highlight/shadow changes clear the cache. No file assets are added.
`look_chain(ui, id, labels, looks, active)` draws Face → Body → Component → Material
as four connected steps. Pass translated labels, `[Option<Sphere>; 4]` and one
`LookStep`; empty slots use a dashed circle and plus, while filled slots reuse the
sphere cache. Exactly one step has a `Tokens::render_accent` ring. It returns
`Option<LookStep>` on activation; callers own commands and selection. Disabled
controls do not activate. Handles/rects are `{id}:face`, `:body`, `:component`,
`:material`; `{id}` is the full allocation. Long labels clip within their step.
These are content widgets; their enclosing surface still belongs to `Container`.
Gallery entries show all five sphere finishes, a mixed filled/empty look chain
with Body active, and an empty chain with Face active in both themes.
For CPU-rendered review images, run
`SOLIDCRAFT_MATERIAL_WIDGET_EVIDENCE=/tmp/material-widgets cargo test -p solidcraft-ui-egui ui_kit::gallery::material_widgets_board_in_both_themes`.