Nacre/src/ui/widgets.rs
astar76 8049f6aa33 S016: R1-21 controls hold still under the pointer
segmented keys its animation state on its widget id instead of its screen
position (the recording showed wrong checks while scrolling); Interface size
uses a new settled_slider that shows a value label while dragged and sets the
value on release; filter_chip keeps one width; zoom resets at 100 %.
Selftest press/drag/release and scroll; smoke scripts sliders(-visible).txt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 07:41:24 -06:00

1131 lines
55 KiB
Rust

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Small building blocks used across the interface, drawn from the theme tokens (docs/DESIGN.md "UI system").
//! Every control answers hover (a state layer), press (a squeeze), keyboard focus (a ring) and disabled.
use egui::{Align2, Color32, CornerRadius, Id, Rect, Response, RichText, Sense, Shape, Stroke, StrokeKind, Ui, Vec2, pos2, vec2};
use super::icons;
use crate::theme::{self, Palette, Weight};
/// How a control looks while the pointer and keyboard work on it, each 0..1 and animated.
pub struct Interaction {
pub hover: f32,
pub press: f32,
pub focus: bool,
pub enabled: bool,
}
pub fn interaction(ui: &Ui, response: &Response) -> Interaction {
let ctx = ui.ctx();
let enabled = response.enabled();
let hover = theme::effect(ctx, response.id.with("hover"), enabled && response.hovered());
let press = theme::spring(ctx, response.id.with("press"), if enabled && response.is_pointer_button_down_on() { 1.0 } else { 0.0 }, theme::FAST);
Interaction { hover, press, focus: response.has_focus(), enabled }
}
impl Interaction {
/// The state layer: the content colour over the container.
pub fn layer(&self, container: Color32, content: Color32) -> Color32 {
theme::layer(container, content, self.amount())
}
/// State layer opacity.
pub fn amount(&self) -> f32 {
theme::HOVER * self.hover + theme::PRESS * self.press.clamp(0.0, 1.0)
}
}
pub fn focus_ring(ui: &Ui, rect: Rect, radius: f32, p: &Palette) {
ui.painter().rect_stroke(rect.expand(2.0), theme::corner_radius(radius + 2.0), Stroke::new(2.0, p.secondary), StrokeKind::Outside);
}
fn disabled(c: Color32, enabled: bool, amount: f32) -> Color32 {
if enabled { c } else { c.gamma_multiply(amount) }
}
/// Is `text` a Material Symbols code point (`icons::*`)?
fn is_icon(text: &str) -> bool {
text.chars().next().is_some_and(|c| ('\u{e000}'..='\u{f8ff}').contains(&c)) && text.chars().count() == 1
}
/// Draws an icon from `icons` (or any short text glyph) centred on `center`.
pub fn icon(ui: &Ui, center: egui::Pos2, glyph: &str, size: f32, filled: bool, color: Color32) {
let font = if is_icon(glyph) { theme::icon_font(size, filled) } else { theme::font(size * 0.8, Weight::Regular) };
ui.painter().text(center, Align2::CENTER_CENTER, glyph, font, color);
}
/// A round icon button with a tooltip. `glyph` is one of `icons::*`.
pub fn icon_button(ui: &mut Ui, glyph: &str, tooltip: &str) -> Response {
icon_control(ui, glyph, tooltip, false)
}
/// Like `icon_button` but shows as selected (tonal fill, filled icon) when `on`.
pub fn icon_toggle(ui: &mut Ui, glyph: &str, tooltip: &str, on: bool) -> Response {
icon_control(ui, glyph, tooltip, on)
}
fn icon_control(ui: &mut Ui, glyph: &str, tooltip: &str, on: bool) -> Response {
let p = theme::palette(ui.ctx());
let size = theme::CONTROL_SMALL;
let (rect, response) = ui.allocate_exact_size(Vec2::splat(size), Sense::click());
if ui.is_rect_visible(rect) {
let s = interaction(ui, &response);
let selected = theme::effect(ui.ctx(), response.id.with("on"), on);
let content = theme::layer(p.on_surface_variant, p.on_secondary_container, selected);
// Press squashes the circle towards a squircle.
let radius = theme::corner_radius(size / 2.0 * (1.0 - 0.45 * s.press.clamp(0.0, 1.2)));
if selected > 0.0 {
ui.painter().rect_filled(rect, radius, p.secondary_container.gamma_multiply(selected));
}
let state = s.amount();
if state > 0.0 {
ui.painter().rect_filled(rect, radius, content.gamma_multiply(state));
}
icon(ui, rect.center(), glyph, theme::ICON, on, disabled(content, s.enabled, theme::DISABLED_CONTENT));
if s.focus {
focus_ring(ui, rect, size / 2.0, &p);
}
}
response.on_hover_text(tooltip)
}
/// An on/off switch (M3): the handle travels, grows and shows a check when on, with a halo on hover.
/// Returns true when it changed.
pub fn switch(ui: &mut Ui, on: &mut bool) -> bool {
let p = theme::palette(ui.ctx());
let (rect, mut response) = ui.allocate_exact_size(vec2(52.0, 32.0), Sense::click());
if response.clicked() {
*on = !*on;
response.mark_changed();
}
if ui.is_rect_visible(rect) {
let s = interaction(ui, &response);
let ctx = ui.ctx();
let t = theme::effect(ctx, response.id.with("on"), *on);
let travel = theme::spring(ctx, response.id.with("x"), if *on { 1.0 } else { 0.0 }, theme::FAST);
let track = theme::layer(p.surface_container_highest, p.primary, t);
let outline = theme::layer(p.outline, p.primary, t);
let painter = ui.painter();
painter.rect(rect, CornerRadius::same(16), disabled(track, s.enabled, theme::DISABLED_CONTAINER), Stroke::new(2.0, disabled(outline, s.enabled, theme::DISABLED_CONTAINER)), StrokeKind::Inside);
let x = egui::lerp((rect.left() + 16.0)..=(rect.right() - 16.0), travel);
let center = pos2(x, rect.center().y);
let halo = theme::layer(p.on_surface, p.primary, t);
if s.amount() > 0.0 {
painter.circle_filled(center, 20.0, halo.gamma_multiply(s.amount()));
}
let handle = 8.0 + 4.0 * t + 2.0 * s.press.clamp(0.0, 1.2);
let fill = theme::layer(p.outline, p.on_primary, t);
let fill = if s.hover > 0.0 { theme::layer(fill, theme::layer(p.on_surface_variant, p.primary_container, t), s.hover) } else { fill };
painter.circle_filled(center, handle, disabled(fill, s.enabled, theme::DISABLED_CONTENT));
if t > 0.01 {
icon(ui, center, icons::CHECK, 16.0 * t, false, p.on_primary_container.gamma_multiply(t));
}
if s.focus {
focus_ring(ui, rect, 16.0, &p);
}
}
response.changed()
}
/// A row of connected buttons choosing one of `options` (M3 segmented buttons): the selected one gets a tonal fill
/// and a check mark. Returns true when it changed.
pub fn segmented<T: Copy + PartialEq>(ui: &mut Ui, value: &mut T, options: &[(T, &str)]) -> bool {
let p = theme::palette(ui.ctx());
let font = theme::font(theme::BODY, Weight::Medium);
let check = 18.0 + theme::GAP_XS;
let widest = options.iter().map(|(_, label)| ui.painter().layout_no_wrap((*label).to_owned(), font.clone(), p.on_surface).size().x).fold(0.0, f32::max);
let segment = vec2((widest + check + 2.0 * theme::GAP_M).max(64.0), theme::CONTROL);
let total = vec2(segment.x * options.len() as f32, segment.y);
// Keyed on the widget's own id, not its place: a position key changes while the page scrolls, so the segments
// would pick up another control's animation state.
let (rect, response) = ui.allocate_exact_size(total, Sense::hover());
let id = response.id;
let mut changed = false;
let last = options.len().saturating_sub(1);
for (i, (option, label)) in options.iter().enumerate() {
let r = Rect::from_min_size(pos2(rect.left() + segment.x * i as f32, rect.top()), segment);
let response = ui.interact(r, id.with(i), Sense::click());
let selected = *value == *option;
if response.clicked() && !selected {
*value = *option;
changed = true;
}
if !ui.is_rect_visible(r) {
continue;
}
let s = interaction(ui, &response);
let t = theme::effect(ui.ctx(), response.id.with("on"), *value == *option);
let full = (segment.y / 2.0) as u8;
let corners = CornerRadius { nw: if i == 0 { full } else { 0 }, sw: if i == 0 { full } else { 0 }, ne: if i == last { full } else { 0 }, se: if i == last { full } else { 0 } };
let container = theme::layer(p.surface, p.secondary_container, t);
let content = theme::layer(p.on_surface, p.on_secondary_container, t);
let fill = s.layer(container, content);
if t > 0.0 || s.hover + s.press > 0.0 {
ui.painter().rect_filled(r, corners, fill);
}
let galley = ui.painter().layout_no_wrap((*label).to_owned(), font.clone(), content);
// The check slides in from nothing, pushing the label right by its width.
let shift = check * t;
let x = r.center().x - (galley.size().x + shift) / 2.0;
if t > 0.01 {
icon(ui, pos2(x + 9.0 * t, r.center().y), icons::CHECK, 18.0 * t, false, content);
}
ui.painter().galley(pos2(x + shift, r.center().y - galley.size().y / 2.0), galley, disabled(content, s.enabled, theme::DISABLED_CONTENT));
if i > 0 {
ui.painter().vline(r.left(), r.y_range(), Stroke::new(1.0, p.outline));
}
if s.focus {
focus_ring(ui, r, segment.y / 2.0, &p);
}
}
ui.painter().rect_stroke(rect, CornerRadius::same((segment.y / 2.0) as u8), Stroke::new(1.0, p.outline), StrokeKind::Inside);
changed
}
/// Button emphasis, highest first.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ButtonKind {
Filled,
Tonal,
Outlined,
Text,
}
/// A pill button with an optional leading icon. Press morphs the pill to a rounded rectangle.
pub fn button(ui: &mut Ui, kind: ButtonKind, icon_glyph: Option<&str>, label: &str) -> Response {
let p = theme::palette(ui.ctx());
let font = theme::font(theme::BODY, Weight::Medium);
let galley = ui.painter().layout_no_wrap(label.to_owned(), font, Color32::PLACEHOLDER);
let pad = if kind == ButtonKind::Text { theme::GAP_M } else { theme::GAP_XL };
let lead = if icon_glyph.is_some() { 18.0 + theme::GAP_S } else { 0.0 };
let left = if icon_glyph.is_some() { theme::GAP_L } else { pad };
let size = vec2(left + lead + galley.size().x + pad, theme::CONTROL);
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
if ui.is_rect_visible(rect) {
let s = interaction(ui, &response);
let (container, content) = match kind {
ButtonKind::Filled => (p.primary, p.on_primary),
ButtonKind::Tonal => (p.secondary_container, p.on_secondary_container),
ButtonKind::Outlined | ButtonKind::Text => (Color32::TRANSPARENT, p.primary),
};
let content = if s.enabled { content } else { p.on_surface.gamma_multiply(theme::DISABLED_CONTENT) };
let radius = egui::lerp((rect.height() / 2.0)..=theme::radius(ui.ctx(), theme::S), s.press.clamp(0.0, 1.0));
let r = theme::corner_radius(radius);
let fill = if !s.enabled {
if container == Color32::TRANSPARENT { Color32::TRANSPARENT } else { p.on_surface.gamma_multiply(theme::DISABLED_CONTAINER) }
} else if container == Color32::TRANSPARENT {
content.gamma_multiply(s.amount())
} else {
s.layer(container, content)
};
ui.painter().rect_filled(rect, r, fill);
if kind == ButtonKind::Outlined {
let line = if s.enabled { p.outline_variant } else { p.on_surface.gamma_multiply(theme::DISABLED_CONTAINER) };
ui.painter().rect_stroke(rect, r, Stroke::new(1.0, line), StrokeKind::Inside);
}
let mut x = rect.left() + left;
if let Some(glyph) = icon_glyph {
icon(ui, pos2(x + 9.0, rect.center().y), glyph, 18.0, false, content);
x += lead;
}
ui.painter().galley_with_override_text_color(pos2(x, rect.center().y - galley.size().y / 2.0), galley, content);
if s.focus {
focus_ring(ui, rect, rect.height() / 2.0, &p);
}
}
response
}
/// The rows of a card: each row after the first draws a hairline above itself.
fn first_row_id(ui: &Ui) -> Id {
ui.id().with("first-row")
}
/// Rows whose title or description contains this text (lower case) are highlighted and counted.
fn highlight_id() -> Id {
Id::new("row-highlight")
}
/// Highlight rows matching `query` from now on (empty: none). `highlighted` counts the matches since.
pub fn highlight_rows(ctx: &egui::Context, query: &str) {
ctx.data_mut(|d| {
d.insert_temp(highlight_id(), query.to_lowercase());
d.insert_temp(highlight_id().with("count"), 0usize);
});
}
pub fn highlighted(ctx: &egui::Context) -> usize {
ctx.data(|d| d.get_temp(highlight_id().with("count"))).unwrap_or(0)
}
/// What a row shows besides its control.
#[derive(Clone, Copy, Default)]
struct RowText<'a> {
title: &'a str,
description: &'a str,
/// Leading icon.
lead: Option<&'a str>,
/// What the engine can't do for this setting, under the description.
note: Option<&'a str>,
/// The control always goes under the text (chips and lists that wrap).
below: bool,
}
/// Text needs at least this much room beside a control; with less the control goes under the text.
const ROW_TEXT_MIN: f32 = 220.0;
/// A setting: title and description on the left, the control on the right.
pub fn row<R>(ui: &mut Ui, title: &str, description: &str, control: impl FnOnce(&mut Ui) -> R) -> R {
row_frame(ui, RowText { title, description, ..Default::default() }, None, control).0
}
/// A row with a leading icon.
pub fn icon_row<R>(ui: &mut Ui, glyph: &str, title: &str, description: &str, control: impl FnOnce(&mut Ui) -> R) -> R {
row_frame(ui, RowText { title, description, lead: Some(glyph), ..Default::default() }, None, control).0
}
/// A row whose control sits under the text, full width: wrapping chips, lists, wide fields.
pub fn wide_row<R>(ui: &mut Ui, title: &str, description: &str, control: impl FnOnce(&mut Ui) -> R) -> R {
row_frame(ui, RowText { title, description, below: true, ..Default::default() }, None, control).0
}
/// A setting the engine only partly supports: `limit` says what doesn't work, under the description.
pub fn limited_row<R>(ui: &mut Ui, title: &str, description: &str, limit: &str, control: impl FnOnce(&mut Ui) -> R) -> R {
row_frame(ui, RowText { title, description, note: Some(limit), ..Default::default() }, None, control).0
}
/// A setting the engine can't do at all: kept in its place with the reason and a "Not available" label.
pub fn unavailable_row(ui: &mut Ui, title: &str, reason: &str) {
let p = theme::palette(ui.ctx());
row_frame(ui, RowText { title, description: reason, ..Default::default() }, None, |ui| {
let font = theme::font(theme::SMALL, Weight::Medium);
let galley = ui.painter().layout_no_wrap("Not available".to_owned(), font, p.on_surface_variant);
let (rect, _) = ui.allocate_exact_size(vec2(theme::GAP_M + 16.0 + theme::GAP_XS + galley.size().x + theme::GAP_M, theme::CONTROL_SMALL - 4.0), Sense::hover());
let r = theme::corner_radius(theme::radius(ui.ctx(), theme::S));
ui.painter().rect_stroke(rect, r, Stroke::new(1.0, p.outline_variant), StrokeKind::Inside);
icon(ui, pos2(rect.left() + theme::GAP_M + 8.0, rect.center().y), icons::BLOCK, 16.0, false, p.on_surface_variant);
ui.painter().galley(pos2(rect.left() + theme::GAP_M + 16.0 + theme::GAP_XS, rect.center().y - galley.size().y / 2.0), galley, p.on_surface_variant);
});
}
fn row_frame<R>(ui: &mut Ui, text: RowText, click: Option<Id>, control: impl FnOnce(&mut Ui) -> R) -> (R, Option<Response>) {
let p = theme::palette(ui.ctx());
let first = ui.data_mut(|d| d.remove_temp::<bool>(first_row_id(ui))).unwrap_or(false);
let query: String = ui.data(|d| d.get_temp(highlight_id())).unwrap_or_default();
let matched = !query.is_empty() && (text.title.to_lowercase().contains(&query) || text.description.to_lowercase().contains(&query));
if matched {
ui.data_mut(|d| *d.get_temp_mut_or(highlight_id().with("count"), 0usize) += 1);
}
let background = ui.painter().add(Shape::Noop);
// The control's width from the last frame decides whether it fits beside the text.
let width_id = ui.id().with(("row-control", text.title));
let known: Option<Vec2> = ui.data(|d| d.get_temp(width_id));
let lead = if text.lead.is_some() { theme::ICON + theme::GAP_L } else { 0.0 };
let inner_width = ui.available_width() - 2.0 * theme::GAP_L - lead;
let control_width = known.map_or(0.0, |k| k.x);
let control_height = known.map_or(0.0, |k| k.y);
let stacked = text.below || control_width > inner_width - ROW_TEXT_MIN;
let mut result = None;
let mut measured = Vec2::ZERO;
// Runs in one of two places below.
let mut control = Some(control);
let lines = 20.0 + if text.description.is_empty() { 0.0 } else { 16.0 } + if text.note.is_some() { 16.0 } else { 0.0 };
let inner = egui::Frame::NONE.inner_margin(egui::Margin::symmetric(theme::GAP_L as i8, theme::GAP_M as i8)).show(ui, |ui| {
ui.set_min_height(theme::ROW - 2.0 * theme::GAP_M);
ui.set_min_width(ui.available_width());
ui.horizontal(|ui| {
if lead > 0.0 {
ui.add_space(lead - ui.spacing().item_spacing.x);
}
ui.vertical(|ui| {
let width = if stacked { ui.available_width() } else { (ui.available_width() - control_width - theme::GAP_L).max(ROW_TEXT_MIN) };
ui.set_max_width(width);
if !stacked {
ui.add_space(((theme::ROW - 2.0 * theme::GAP_M).max(control_height) - lines).max(0.0) / 2.0);
}
ui.label(RichText::new(text.title).font(theme::font(theme::BODY, Weight::Regular)).color(p.on_surface));
if !text.description.is_empty() {
ui.label(RichText::new(text.description).font(theme::font(theme::SMALL, Weight::Regular)).color(p.on_surface_variant));
}
if let Some(note) = text.note {
let mut job = egui::text::LayoutJob::default();
let format = |color| egui::TextFormat { font_id: theme::font(theme::SMALL, Weight::Regular), color, ..Default::default() };
job.append(&format!("{} ", icons::INFO), 0.0, format(p.tertiary));
job.append(note, 0.0, format(p.on_surface_variant));
ui.label(job);
}
if stacked {
ui.add_space(theme::GAP_S);
result = control.take().map(|c| ui.horizontal_wrapped(|ui| c(ui)).inner);
}
});
if !stacked {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let right = ui.max_rect().right();
result = control.take().map(|c| c(ui));
measured = vec2(right - ui.min_rect().left(), ui.min_rect().height());
});
}
});
});
// Remember the control's natural width (measured beside the text); redo the frame unseen when the control
// turns out not to fit, so it moves under the text without a flicker.
if !stacked && known.is_none_or(|k| (k - measured).length() > 1.0) {
ui.data_mut(|d| d.insert_temp(width_id, measured));
if known.is_none() || measured.x > inner_width - ROW_TEXT_MIN {
ui.ctx().request_discard("row control moves under its text");
}
}
let rect = inner.response.rect;
if !first {
ui.painter().hline(rect.x_range().shrink(theme::GAP_L), rect.top(), Stroke::new(1.0, p.outline_variant));
}
if let Some(glyph) = text.lead {
let y = if stacked { rect.top() + theme::GAP_M + 10.0 } else { rect.center().y };
icon(ui, pos2(rect.left() + theme::GAP_L + theme::ICON / 2.0, y), glyph, theme::ICON, false, p.on_surface_variant);
}
let highlight = if matched { theme::layer(p.surface_container, p.secondary_container, 0.7) } else { Color32::TRANSPARENT };
let radius = theme::corner_radius(theme::radius(ui.ctx(), theme::M));
let response = click.map(|id| {
let response = ui.interact(rect, id, Sense::click());
let s = interaction(ui, &response);
let fill = if matched { s.layer(highlight, p.on_surface) } else { p.on_surface.gamma_multiply(s.amount()) };
ui.painter().set(background, Shape::rect_filled(rect.shrink2(vec2(theme::GAP_XS, 2.0)), radius, fill));
if s.focus {
focus_ring(ui, rect.shrink(2.0), theme::radius(ui.ctx(), theme::M), &p);
}
response
});
if response.is_none() && matched {
ui.painter().set(background, Shape::rect_filled(rect.shrink2(vec2(theme::GAP_XS, 2.0)), radius, highlight));
}
(result.expect("control ran"), response)
}
/// A switch row. Returns true when it changed.
pub fn switch_row(ui: &mut Ui, title: &str, description: &str, on: &mut bool) -> bool {
row(ui, title, description, |ui| switch(ui, on))
}
/// A row that opens something: the whole row is the button, with a chevron at the end.
pub fn link_row(ui: &mut Ui, title: &str, description: &str) -> bool {
link(ui, RowText { title, description, ..Default::default() })
}
/// `link_row` with a leading icon.
pub fn icon_link_row(ui: &mut Ui, glyph: &str, title: &str, description: &str) -> bool {
link(ui, RowText { title, description, lead: Some(glyph), ..Default::default() })
}
fn link(ui: &mut Ui, text: RowText) -> bool {
let p = theme::palette(ui.ctx());
let id = ui.id().with("link-row").with(text.title);
let (_, response) = row_frame(ui, text, Some(id), |ui| {
let (rect, _) = ui.allocate_exact_size(Vec2::splat(24.0), Sense::hover());
icon(ui, rect.center(), icons::CHEVRON_RIGHT, theme::ICON, false, p.on_surface_variant);
});
response.is_some_and(|r| r.clicked())
}
/// A group title above a card, in the accent colour, lined up with the rows' text.
pub fn section(ui: &mut Ui, title: &str) {
let p = theme::palette(ui.ctx());
ui.add_space(theme::GAP_XL);
ui.horizontal(|ui| {
ui.add_space(theme::GAP_L);
ui.label(RichText::new(title).font(theme::font(theme::BODY, Weight::Medium)).color(p.primary));
});
ui.add_space(theme::GAP_XS);
}
/// A card that groups rows: a large rounded surface a step above the page.
pub fn card<R>(ui: &mut Ui, contents: impl FnOnce(&mut Ui) -> R) -> R {
let p = theme::palette(ui.ctx());
let radius = theme::corner_radius(theme::radius(ui.ctx(), theme::L));
egui::Frame::NONE
.fill(p.surface_container)
.corner_radius(radius)
.inner_margin(egui::Margin::symmetric(0, theme::GAP_XS as i8))
.show(ui, |ui| {
ui.data_mut(|d| d.insert_temp(first_row_id(ui), true));
let r = contents(ui);
ui.data_mut(|d| d.remove_temp::<bool>(first_row_id(ui)));
r
})
.inner
}
/// Centered page column of at most `width` points, scrolling.
pub fn page_column<R>(ui: &mut Ui, id: &str, width: f32, contents: impl FnOnce(&mut Ui) -> R) -> R {
egui::ScrollArea::vertical().id_salt(id).auto_shrink([false, false]).show(ui, |ui| {
// Margins are small integers in egui, so center with spacing instead.
let avail = ui.available_width();
let w = (avail - 32.0).min(width).max(200.0);
let pad = ((avail - w) / 2.0).max(0.0);
ui.horizontal_top(|ui| {
ui.add_space(pad);
ui.vertical(|ui| {
ui.set_width(w);
ui.add_space(16.0);
let r = contents(ui);
ui.add_space(32.0);
r
})
.inner
})
.inner
})
.inner
}
/// A text field with a hint; returns its response.
pub fn text_field(ui: &mut Ui, text: &mut String, hint: &str, width: f32) -> Response {
ui.add(egui::TextEdit::singleline(text).hint_text(hint).desired_width(width).margin(vec2(theme::GAP_M, theme::GAP_S)))
}
/// A number with − and + buttons either side; the number itself can be dragged or typed. Returns true when it
/// changed.
pub fn number(ui: &mut Ui, value: &mut u32, range: std::ops::RangeInclusive<u32>, suffix: &str) -> bool {
let before = *value;
let (lo, hi) = (*range.start(), *range.end());
// Steps that reach the far end in about 30 presses.
let step = match hi - lo {
0..=60 => 1,
61..=300 => 5,
301..=900 => 15,
_ => 30,
};
ui.scope(|ui| {
ui.spacing_mut().item_spacing.x = theme::GAP_XS;
// Laid out right to left inside rows, so the + comes first.
let rtl = ui.layout().prefer_right_to_left();
let plus = |ui: &mut Ui, value: &mut u32| {
if ui.add_enabled_ui(*value < hi, |ui| icon_button(ui, icons::ADD, "More")).inner.clicked() {
*value = (*value + step - *value % step).min(hi);
}
};
if rtl {
plus(ui, value);
} else {
minus(ui, value, lo, step);
}
// One width for every stepper, so the buttons line up from row to row.
ui.add_sized(vec2(112.0, theme::CONTROL_SMALL), egui::DragValue::new(value).range(range.clone()).suffix(suffix));
if rtl {
minus(ui, value, lo, step);
} else {
plus(ui, value);
}
});
*value != before
}
fn minus(ui: &mut Ui, value: &mut u32, lo: u32, step: u32) {
if ui.add_enabled_ui(*value > lo, |ui| icon_button(ui, icons::REMOVE, "Less")).inner.clicked() {
let down = if *value % step == 0 { step } else { *value % step };
*value = value.saturating_sub(down).max(lo);
}
}
/// A filter chip: icon (optional) and label in an outlined pill; the selected one is filled.
pub fn chip(ui: &mut Ui, glyph: Option<&str>, label: &str, selected: bool) -> Response {
let p = theme::palette(ui.ctx());
let font = theme::font(theme::BODY, Weight::Medium);
let galley = ui.painter().layout_no_wrap(label.to_owned(), font, p.on_surface);
let lead = if glyph.is_some() { 18.0 + theme::GAP_S } else { 0.0 };
let size = vec2(theme::GAP_M + lead + galley.size().x + if glyph.is_some() { theme::GAP_L } else { theme::GAP_M }, theme::CONTROL_SMALL + 4.0);
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
if !ui.is_rect_visible(rect) {
return response;
}
let s = interaction(ui, &response);
let on = theme::effect(ui.ctx(), response.id.with("on"), selected);
let radius = theme::radius(ui.ctx(), theme::S);
let container = theme::layer(p.surface_container_high, p.secondary_container, on);
let content = theme::layer(p.on_surface_variant, p.on_secondary_container, on);
let content = disabled(content, s.enabled, theme::DISABLED_CONTENT);
ui.painter().rect_filled(rect, theme::corner_radius(radius), s.layer(container, content));
if on < 0.99 {
ui.painter().rect_stroke(rect, theme::corner_radius(radius), Stroke::new(1.0, p.outline_variant.gamma_multiply(1.0 - on)), StrokeKind::Inside);
}
if let Some(glyph) = glyph {
icon(ui, pos2(rect.left() + theme::GAP_M + 9.0, rect.center().y), glyph, 18.0, on > 0.5, content);
}
ui.painter().galley(pos2(rect.left() + theme::GAP_M + lead, rect.center().y - galley.size().y / 2.0), galley, content);
if s.focus {
focus_ring(ui, rect, radius, &p);
}
response
}
/// A chip that is on or off: on, it is filled and a check slides in before the label. It keeps one width either
/// way, so picking it doesn't move the chips after it (or wrap them onto another line).
pub fn filter_chip(ui: &mut Ui, label: &str, selected: bool) -> Response {
let p = theme::palette(ui.ctx());
let font = theme::font(theme::BODY, Weight::Medium);
let galley = ui.painter().layout_no_wrap(label.to_owned(), font, p.on_surface);
let lead = 18.0 + theme::GAP_S;
let size = vec2(theme::GAP_M + lead + galley.size().x + theme::GAP_L, theme::CONTROL_SMALL + 4.0);
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
if !ui.is_rect_visible(rect) {
return response;
}
let s = interaction(ui, &response);
let on = theme::effect(ui.ctx(), response.id.with("on"), selected);
let radius = theme::radius(ui.ctx(), theme::S);
let container = theme::layer(p.surface_container_high, p.secondary_container, on);
let content = theme::layer(p.on_surface_variant, p.on_secondary_container, on);
let content = disabled(content, s.enabled, theme::DISABLED_CONTENT);
ui.painter().rect_filled(rect, theme::corner_radius(radius), s.layer(container, content));
if on < 0.99 {
ui.painter().rect_stroke(rect, theme::corner_radius(radius), Stroke::new(1.0, p.outline_variant.gamma_multiply(1.0 - on)), StrokeKind::Inside);
}
// Off, the label sits in the middle; the check pushes it to its place at the end.
let x = rect.center().x - (galley.size().x + lead * on) / 2.0;
if on > 0.01 {
icon(ui, pos2(x + 9.0 * on, rect.center().y), icons::CHECK, 18.0 * on, false, content);
}
ui.painter().galley(pos2(x + lead * on, rect.center().y - galley.size().y / 2.0), galley, content);
if s.focus {
focus_ring(ui, rect, radius, &p);
}
response
}
/// One of `options` as a wrapping row of chips, the chosen one with a check. For lists too long for a segmented
/// button. Returns true when it changed.
pub fn choice_chips<T: Clone + PartialEq>(ui: &mut Ui, value: &mut T, options: &[(T, &str)]) -> bool {
let mut changed = false;
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(theme::GAP_S, theme::GAP_S);
for (option, label) in options {
let selected = *value == *option;
if filter_chip(ui, label, selected).clicked() && !selected {
*value = option.clone();
changed = true;
}
}
});
changed
}
/// Any of `options` (keys in `chosen`) as toggling chips. Returns true when it changed.
pub fn toggle_chips(ui: &mut Ui, chosen: &mut Vec<String>, options: &[(&str, &str)]) -> bool {
let mut changed = false;
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(theme::GAP_S, theme::GAP_S);
for (key, label) in options {
let on = chosen.iter().any(|k| k == key);
if filter_chip(ui, label, on).clicked() {
if on {
chosen.retain(|k| k != key);
} else {
chosen.push((*key).to_owned());
}
changed = true;
}
}
});
changed
}
/// An input chip: a label with a × that removes it. Returns true when the × was clicked.
pub fn input_chip(ui: &mut Ui, label: &str, remove_tooltip: &str) -> bool {
let p = theme::palette(ui.ctx());
let font = theme::font(theme::BODY, Weight::Regular);
let galley = ui.painter().layout_no_wrap(label.to_owned(), font, p.on_surface_variant);
let size = vec2(theme::GAP_M + galley.size().x + theme::GAP_XS + 24.0 + theme::GAP_XS, theme::CONTROL_SMALL);
let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
let radius = theme::corner_radius(theme::radius(ui.ctx(), theme::S));
ui.painter().rect_stroke(rect, radius, Stroke::new(1.0, p.outline_variant), StrokeKind::Inside);
ui.painter().galley(pos2(rect.left() + theme::GAP_M, rect.center().y - galley.size().y / 2.0), galley, p.on_surface_variant);
let x = Rect::from_center_size(pos2(rect.right() - theme::GAP_XS - 12.0, rect.center().y), Vec2::splat(24.0));
let response = ui.interact(x, ui.id().with(("input-chip", label)), Sense::click());
let s = interaction(ui, &response);
if s.amount() > 0.0 {
ui.painter().circle_filled(x.center(), 12.0, p.on_surface.gamma_multiply(s.amount()));
}
icon(ui, x.center(), icons::CLOSE, 16.0, false, p.on_surface_variant);
if s.focus {
focus_ring(ui, x, 12.0, &p);
}
response.on_hover_text(remove_tooltip).clicked()
}
/// An M3 Expressive slider: a thick track, the active part in the accent, a bar for a handle with a gap round
/// it. Drag or click to set; arrow keys step by a twentieth. Sets the value live, for settings that only repaint
/// (colours, dim, blur). Returns true when the value changed.
pub fn slider(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive<f32>, width: f32, tooltip: &str) -> bool {
track(ui, value, range, width, &|_| tooltip.to_owned(), false)
}
/// A slider for settings that re-lay out the page (interface size): while dragging, only the handle and a value
/// label above it move, and the value is set on release, so the page doesn't move under the pointer. A click or
/// an arrow key sets it at once. `label` formats a value for the label and the tooltip.
pub fn settled_slider(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive<f32>, width: f32, label: &dyn Fn(f32) -> String) -> bool {
track(ui, value, range, width, label, true)
}
/// Where a settled slider stands: `pending` is the dragged fraction (kept while `dragging`). Returns the fraction
/// to draw, what to keep as pending, and whether to set the value now.
fn settle(committed: f32, pending: Option<f32>, pointer: Option<f32>, dragging: bool) -> (f32, Option<f32>, bool) {
let fraction = pointer.or(pending).unwrap_or(committed);
if dragging { (fraction, Some(fraction), false) } else { (fraction, None, fraction != committed) }
}
fn track(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive<f32>, width: f32, label: &dyn Fn(f32) -> String, settled: bool) -> bool {
let p = theme::palette(ui.ctx());
let (rect, response) = ui.allocate_exact_size(vec2(width, theme::CONTROL), Sense::click_and_drag());
let (lo, hi) = (*range.start(), *range.end());
let committed = ((*value - lo) / (hi - lo)).clamp(0.0, 1.0);
let track = rect.shrink2(vec2(2.0, 0.0));
let mut pointer = None;
if (response.dragged() || response.clicked())
&& let Some(at) = response.interact_pointer_pos()
{
pointer = Some(((at.x - track.left()) / track.width()).clamp(0.0, 1.0));
}
let pending_id = response.id.with("pending");
let (mut fraction, pending, mut changed) = if settled {
// Only while this drag lasts: a value left from a drag the slider wasn't drawn for to the end is dropped.
let pending = if response.dragged() || response.drag_stopped() { ui.data(|d| d.get_temp::<f32>(pending_id)) } else { None };
settle(committed, pending, pointer, response.dragged())
} else {
let fraction = pointer.unwrap_or(committed);
(fraction, None, fraction != committed)
};
ui.data_mut(|d| match pending {
Some(f) => drop(d.insert_temp(pending_id, f)),
None => drop(d.remove_temp::<f32>(pending_id)),
});
if response.has_focus() && pending.is_none() {
let step = ui.input(|i| i.key_pressed(egui::Key::ArrowRight) as i32 - i.key_pressed(egui::Key::ArrowLeft) as i32);
if step != 0 {
fraction = (fraction + step as f32 * 0.05).clamp(0.0, 1.0);
changed = fraction != committed;
}
}
if changed {
*value = lo + fraction * (hi - lo);
}
let s = interaction(ui, &response);
let enabled = s.enabled;
let dim = |c: Color32, k: f32| if enabled { c } else { p.on_surface.gamma_multiply(k) };
let x = track.left() + fraction * track.width();
let thickness = 16.0;
let gap = 6.0;
let handle_width = 4.0 - 2.0 * s.press.clamp(0.0, 1.0);
let r = theme::corner_radius(thickness / 2.0);
let y = track.center().y;
let active = Rect::from_min_max(pos2(track.left(), y - thickness / 2.0), pos2((x - gap).max(track.left()), y + thickness / 2.0));
let rest = Rect::from_min_max(pos2((x + gap).min(track.right()), y - thickness / 2.0), pos2(track.right(), y + thickness / 2.0));
if active.width() > 0.5 {
ui.painter().rect_filled(active, r, dim(p.primary, theme::DISABLED_CONTENT));
}
if rest.width() > 0.5 {
ui.painter().rect_filled(rest, r, dim(p.secondary_container, theme::DISABLED_CONTAINER));
}
let handle = Rect::from_center_size(pos2(x, y), vec2(handle_width, 36.0));
if s.amount() > 0.0 {
ui.painter().rect_filled(handle.expand(4.0), theme::corner_radius(6.0), p.primary.gamma_multiply(s.amount()));
}
ui.painter().rect_filled(handle, theme::corner_radius(2.0), dim(p.primary, theme::DISABLED_CONTENT));
if s.focus {
focus_ring(ui, handle.expand(4.0), 6.0, &p);
}
let shown = lo + fraction * (hi - lo);
if pending.is_some() {
// The M3 value label: a pill above the handle, over everything so the row doesn't clip it.
let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, response.id));
let galley = painter.layout_no_wrap(label(shown), theme::font(theme::SMALL, Weight::Medium), p.inverse_on_surface);
let pill = Rect::from_center_size(pos2(x, handle.top() - theme::GAP_XS - 14.0), vec2(galley.size().x + 2.0 * theme::GAP_M, 28.0));
painter.rect_filled(pill, CornerRadius::same(14), p.inverse_surface);
painter.galley(pill.center() - galley.size() / 2.0, galley, p.inverse_on_surface);
} else {
response.on_hover_text(label(shown));
}
changed
}
/// Icon for a toolbar button key.
pub fn glyph(key: &str) -> &'static str {
match key {
"back" => icons::ARROW_BACK,
"forward" => icons::ARROW_FORWARD,
"reload" => icons::REFRESH,
"home" => icons::HOME,
"incognito" => icons::DOMINO_MASK,
"passwords" => icons::KEY,
"history" => icons::HISTORY,
"downloads" => icons::DOWNLOAD,
"bookmarks" => icons::STAR,
"qr" => icons::QR_CODE_2,
"devtools" => icons::CODE,
"adblock" => icons::SHIELD,
"media" => icons::MUSIC_NOTE,
"vpn" => icons::VPN_LOCK,
"apps" => icons::APPS,
"screenshot" => icons::SCREENSHOT_MONITOR,
"pip" => icons::PICTURE_IN_PICTURE_ALT,
"zoom" => icons::ZOOM_IN,
"share" => icons::SHARE,
"reader" => icons::CHROME_READER_MODE,
"settings" => icons::SETTINGS,
_ => icons::CIRCLE,
}
}
#[cfg(test)]
mod tests {
use super::*;
use egui::{Event, Key, Modifiers, PointerButton, RawInput};
/// Runs one frame of `body` at `time` with `events`, returning the rect the body drew in.
fn frame(ctx: &egui::Context, time: f64, events: Vec<Event>, body: &mut dyn FnMut(&mut Ui)) -> Rect {
let mut rect = Rect::NOTHING;
let input = RawInput { time: Some(time), events, screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() };
let _ = ctx.run_ui(input, |ui| rect = ui.horizontal(|ui| body(ui)).response.rect);
rect
}
fn click_at(pos: egui::Pos2) -> Vec<Vec<Event>> {
let button = |pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
vec![vec![Event::PointerMoved(pos)], vec![button(true)], vec![button(false)], vec![]]
}
#[test]
fn switch_toggles_by_pointer_and_keyboard() {
let ctx = egui::Context::default();
let mut on = false;
let mut changes = 0;
let mut draw = |ui: &mut Ui| {
if switch(ui, &mut on) {
changes += 1;
}
};
let rect = frame(&ctx, 0.0, vec![], &mut draw);
for (i, events) in click_at(rect.center()).into_iter().enumerate() {
frame(&ctx, 0.02 * (i + 1) as f64, events, &mut draw);
}
drop(draw);
assert!(on, "a click turns it on");
assert_eq!(changes, 1);
let key = |key, pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE };
let mut draw = |ui: &mut Ui| {
switch(ui, &mut on);
};
// Move the pointer away, then Tab to focus the switch and Space to toggle it.
for (i, events) in [vec![Event::PointerGone], vec![key(Key::Tab, true), key(Key::Tab, false)], vec![key(Key::Space, true), key(Key::Space, false)], vec![]].into_iter().enumerate() {
frame(&ctx, 1.0 + 0.02 * i as f64, events, &mut draw);
}
drop(draw);
assert!(!on, "Space on the focused switch turns it off");
}
#[test]
fn segmented_picks_the_clicked_option() {
let ctx = egui::Context::default();
let mut value = 0;
let mut draw = |ui: &mut Ui| {
segmented(ui, &mut value, &[(0, "Few"), (1, "Some"), (2, "Lots")]);
};
let rect = frame(&ctx, 0.0, vec![], &mut draw);
let third = egui::pos2(rect.left() + rect.width() * 5.0 / 6.0, rect.center().y);
for (i, events) in click_at(third).into_iter().enumerate() {
frame(&ctx, 0.02 * (i + 1) as f64, events, &mut draw);
}
drop(draw);
assert_eq!(value, 2);
}
/// The stepper's + moves to the next step (15 min steps to 30 in 0..=1440), − back down, and both stop at the range.
#[test]
fn number_steps_and_clamps() {
let ctx = egui::Context::default();
let mut value = 15;
let mut draw = |ui: &mut Ui| {
number(ui, &mut value, 0..=1440, " min");
};
let rect = frame(&ctx, 0.0, vec![], &mut draw);
let plus = egui::pos2(rect.right() - theme::CONTROL_SMALL / 2.0, rect.center().y);
let minus = egui::pos2(rect.left() + theme::CONTROL_SMALL / 2.0, rect.center().y);
let mut t = 0.0;
let mut click = |pos, draw: &mut dyn FnMut(&mut Ui)| {
for events in click_at(pos) {
t += 0.02;
frame(&ctx, t, events, draw);
}
};
click(plus, &mut draw);
click(minus, &mut draw);
click(minus, &mut draw);
click(minus, &mut draw);
drop(draw);
assert_eq!(value, 0, "15 → 30 → 0 → stays at 0");
}
/// A settled slider keeps the value while it is dragged and sets it on release; a live one follows the pointer.
#[test]
fn settled_slider_sets_on_release() {
assert_eq!(settle(0.2, None, Some(0.6), true), (0.6, Some(0.6), false), "dragging previews only");
assert_eq!(settle(0.2, Some(0.6), None, true), (0.6, Some(0.6), false), "the pending value stays while held");
assert_eq!(settle(0.2, Some(0.6), None, false), (0.6, None, true), "release sets it");
assert_eq!(settle(0.2, None, Some(0.9), false), (0.9, None, true), "a click sets it at once");
assert_eq!(settle(0.2, None, None, false), (0.2, None, false), "nothing happens");
let ctx = egui::Context::default();
let mut value = 1.0;
let mut seen = Vec::new();
let mut draw = |ui: &mut Ui| {
settled_slider(ui, &mut value, 0.0..=2.0, 200.0, &|v| format!("{v:.2}"));
seen.push(value);
};
let rect = frame(&ctx, 0.0, vec![], &mut draw);
let at = |f: f32| egui::pos2(rect.left() + 2.0 + f * (rect.width() - 4.0), rect.center().y);
let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
let steps = [vec![Event::PointerMoved(at(0.5))], vec![button(at(0.5), true)], vec![Event::PointerMoved(at(0.6))], vec![Event::PointerMoved(at(0.75))], vec![]];
for (i, events) in steps.into_iter().enumerate() {
frame(&ctx, 0.02 * (i + 1) as f64, events, &mut draw);
}
frame(&ctx, 0.2, vec![button(at(0.75), false)], &mut draw);
frame(&ctx, 0.22, vec![], &mut draw);
drop(draw);
let held = &seen[..seen.len() - 2];
assert!(held.iter().all(|v| *v == 1.0), "unchanged while dragging: {seen:?}");
assert!((value - 1.5).abs() < 0.02, "set on release, got {value}");
}
/// Picking a filter chip doesn't change its width, so the chips after it stay put.
#[test]
fn filter_chip_keeps_its_width() {
let ctx = egui::Context::default();
let width = |selected| {
let mut w = 0.0;
frame(&ctx, 0.0, vec![], &mut |ui: &mut Ui| w = filter_chip(ui, "Vibrant", selected).rect.width());
w
};
assert_eq!(width(false), width(true));
}
/// Hover fades in with the effect spring and a press squeezes, both settling back once the pointer leaves.
#[test]
fn hover_and_press_animate_and_settle() {
let ctx = egui::Context::default();
let id = std::cell::Cell::new(Id::NULL);
let mut draw = |ui: &mut Ui| id.set(button(ui, ButtonKind::Tonal, None, "Save").id);
let rect = frame(&ctx, 0.0, vec![], &mut draw);
let id = id.get();
let hover = |ctx: &egui::Context| theme::spring_value(ctx, id.with("hover")).unwrap_or(0.0);
frame(&ctx, 0.016, vec![Event::PointerMoved(rect.center())], &mut draw);
frame(&ctx, 0.032, vec![], &mut draw);
let early = hover(&ctx);
for i in 3..40 {
frame(&ctx, 0.016 * i as f64, vec![], &mut draw);
}
assert!(early > 0.0 && early < 1.0, "hover eases in, got {early}");
assert_eq!(hover(&ctx), 1.0);
for i in 40..90 {
frame(&ctx, 0.016 * i as f64, if i == 40 { vec![Event::PointerGone] } else { vec![] }, &mut draw);
}
assert_eq!(hover(&ctx), 0.0);
}
}
/// A page title (Headline) with an optional line under it and the page's actions beside it, or under it when the
/// page is narrow. Lines up with the rows' text.
pub fn page_header(ui: &mut Ui, title: &str, subtitle: &str, actions: impl FnOnce(&mut Ui)) {
let p = theme::palette(ui.ctx());
let wide = ui.available_width() >= 640.0;
let mut actions = Some(actions);
let title = |ui: &mut Ui| ui.label(RichText::new(title).font(theme::font(theme::HEADLINE, Weight::Medium)).color(p.on_surface));
ui.add_space(theme::GAP_S);
if wide {
ui.horizontal(|ui| {
ui.set_min_height(theme::CONTROL);
ui.add_space(theme::GAP_L - ui.spacing().item_spacing.x);
title(ui);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = theme::GAP_S;
if let Some(actions) = actions.take() {
actions(ui);
}
});
});
} else {
ui.horizontal(|ui| {
ui.add_space(theme::GAP_L - ui.spacing().item_spacing.x);
title(ui);
});
}
if !subtitle.is_empty() {
ui.horizontal(|ui| {
ui.add_space(theme::GAP_L - ui.spacing().item_spacing.x);
ui.add(egui::Label::new(RichText::new(subtitle).font(theme::font(theme::BODY, Weight::Regular)).color(p.on_surface_variant)).truncate());
});
}
if !wide {
ui.add_space(theme::GAP_S);
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(theme::GAP_S, theme::GAP_S);
ui.add_space(theme::GAP_S);
if let Some(actions) = actions.take() {
actions(ui);
}
});
}
ui.add_space(theme::GAP_M);
}
/// A search pill: icon, field, and a clear button once something is typed. Escape clears it. Returns true when
/// the text changed.
pub fn search_pill(ui: &mut Ui, id: &str, text: &mut String, hint: &str) -> bool {
let p = theme::palette(ui.ctx());
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), theme::CONTROL), Sense::hover());
let id = Id::new(("search-pill", id));
let focused = ui.memory(|m| m.has_focus(id));
let ring = theme::effect(ui.ctx(), id.with("ring"), focused);
let radius = theme::corner_radius(theme::FULL);
ui.painter().rect_filled(rect, radius, p.surface_container_high);
if ring > 0.0 {
ui.painter().rect_stroke(rect, radius, Stroke::new(2.0, p.primary.gamma_multiply(ring)), StrokeKind::Inside);
}
icon(ui, pos2(rect.left() + theme::GAP_L + theme::ICON / 2.0, rect.center().y), icons::SEARCH, theme::ICON, false, p.on_surface_variant);
let before = text.clone();
let clear = !text.is_empty();
let field = Rect::from_min_max(pos2(rect.left() + theme::GAP_L + theme::ICON + theme::GAP_M, rect.top()), pos2(rect.right() - if clear { 40.0 } else { theme::GAP_L }, rect.bottom()));
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(field).layout(egui::Layout::left_to_right(egui::Align::Center)));
let edit = egui::TextEdit::singleline(text).id(id).frame(egui::Frame::NONE).hint_text(hint).font(theme::font(theme::BODY, Weight::Regular)).desired_width(field.width());
let response = child.add(edit);
if response.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) {
text.clear();
}
if clear {
let mut x = ui.new_child(egui::UiBuilder::new().max_rect(Rect::from_center_size(pos2(rect.right() - 24.0, rect.center().y), Vec2::splat(theme::CONTROL_SMALL))));
if icon_button(&mut x, icons::CLOSE, "Clear search").clicked() {
text.clear();
}
}
*text != before
}
/// What a page shows when there is nothing to list: a round icon, what will appear and how, and optionally the
/// button that gets something there. Returns true when that button was clicked.
pub fn empty_state(ui: &mut Ui, glyph: &str, title: &str, body: &str, action: Option<(&str, &str)>) -> bool {
let p = theme::palette(ui.ctx());
let mut clicked = false;
ui.add_space(theme::GAP_XL * 2.0);
ui.vertical_centered(|ui| {
let (rect, _) = ui.allocate_exact_size(Vec2::splat(72.0), Sense::hover());
ui.painter().circle_filled(rect.center(), 36.0, p.secondary_container);
icon(ui, rect.center(), glyph, theme::ICON_LARGE, false, p.on_secondary_container);
ui.add_space(theme::GAP_L);
ui.label(RichText::new(title).font(theme::font(theme::TITLE, Weight::Medium)).color(p.on_surface));
ui.add_space(theme::GAP_XS);
ui.scope(|ui| {
ui.set_max_width(360.0);
ui.label(RichText::new(body).font(theme::font(theme::BODY, Weight::Regular)).color(p.on_surface_variant));
});
if let Some((glyph, label)) = action {
ui.add_space(theme::GAP_L);
clicked = button(ui, ButtonKind::Tonal, Some(glyph), label).clicked();
}
});
clicked
}
/// A page that is still loading or failed to load: a message in the page's own style, with a retry when there is one.
pub fn status_state(ui: &mut Ui, glyph: &str, title: &str, body: &str, error: bool) {
let p = theme::palette(ui.ctx());
ui.add_space(theme::GAP_XL * 2.0);
ui.vertical_centered(|ui| {
let (rect, _) = ui.allocate_exact_size(Vec2::splat(72.0), Sense::hover());
let (fill, content) = if error { (p.error_container, p.on_error_container) } else { (p.surface_container_high, p.on_surface_variant) };
ui.painter().circle_filled(rect.center(), 36.0, fill);
icon(ui, rect.center(), glyph, theme::ICON_LARGE, false, content);
ui.add_space(theme::GAP_L);
ui.label(RichText::new(title).font(theme::font(theme::TITLE, Weight::Medium)).color(p.on_surface));
ui.add_space(theme::GAP_XS);
ui.scope(|ui| {
ui.set_max_width(360.0);
ui.label(RichText::new(body).font(theme::font(theme::BODY, Weight::Regular)).color(p.on_surface_variant));
});
});
}
/// One entry of a list inside a card: a round icon (or `None`), a title and a detail line cut with an ellipsis, and
/// whatever `trailing` adds at the right end (icon buttons). The whole row answers hover and press and the returned
/// response is its click. `id` must be unique on the page.
pub fn list_item(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, glyph: Option<&str>, title: &str, detail: &str, trailing: impl FnOnce(&mut Ui)) -> Response {
let p = theme::palette(ui.ctx());
let first = ui.data_mut(|d| d.remove_temp::<bool>(first_row_id(ui))).unwrap_or(false);
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), theme::ROW), Sense::hover());
let response = ui.interact(rect, ui.id().with(("list-item", id)), Sense::click());
let s = interaction(ui, &response);
let hit = rect.shrink2(vec2(theme::GAP_XS, 2.0));
let radius = theme::radius(ui.ctx(), theme::M);
ui.painter().rect_filled(hit, theme::corner_radius(radius), p.on_surface.gamma_multiply(s.amount()));
if !first {
ui.painter().hline(rect.x_range().shrink(theme::GAP_L), rect.top(), Stroke::new(1.0, p.outline_variant));
}
if s.focus {
focus_ring(ui, hit, radius, &p);
}
let mut end = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(vec2(theme::GAP_S, 0.0))).layout(egui::Layout::right_to_left(egui::Align::Center)));
end.spacing_mut().item_spacing.x = theme::GAP_XS;
trailing(&mut end);
let right = end.min_rect().left().min(rect.right() - theme::GAP_S) - theme::GAP_S;
let mut left = rect.left() + theme::GAP_L;
if let Some(glyph) = glyph {
let c = pos2(left + theme::CONTROL / 2.0, rect.center().y);
ui.painter().circle_filled(c, theme::CONTROL / 2.0, p.surface_container_highest);
icon(ui, c, glyph, theme::ICON, false, p.on_surface_variant);
left += theme::CONTROL + theme::GAP_M;
}
let width = (right - left).max(40.0);
let title_galley = super::menus::one_line(ui, title, theme::font(theme::BODY, Weight::Medium), p.on_surface, width);
let detail_galley = (!detail.is_empty()).then(|| super::menus::one_line(ui, detail, theme::font(theme::SMALL, Weight::Regular), p.on_surface_variant, width));
let height = title_galley.size().y + detail_galley.as_ref().map_or(0.0, |g| g.size().y + 2.0);
let mut y = rect.center().y - height / 2.0;
let title_height = title_galley.size().y;
ui.painter().galley(pos2(left, y), title_galley, p.on_surface);
y += title_height + 2.0;
if let Some(g) = detail_galley {
ui.painter().galley(pos2(left, y), g, p.on_surface_variant);
}
response
}
/// A "more" button that opens a menu of `menus::menu_item`s. Close it with `ui.close()` after a choice.
pub fn more_menu(ui: &mut Ui, contents: impl FnOnce(&mut Ui)) {
let p = theme::palette(ui.ctx());
let r = icon_button(ui, icons::MORE_VERT, "More");
egui::Popup::menu(&r).align(egui::RectAlign::BOTTOM_END).gap(theme::GAP_XS).frame(super::menus::surface(&p, ui.ctx())).show(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
ui.set_min_width(220.0);
contents(ui);
});
}
/// A text field for secrets: dots instead of letters.
pub fn password_field(ui: &mut Ui, text: &mut String, hint: &str, width: f32) -> Response {
ui.add(egui::TextEdit::singleline(text).password(true).hint_text(hint).desired_width(width).margin(vec2(theme::GAP_M, theme::GAP_S)))
}
/// Password strength as four segments (`level` 0..=4, from `vault::strength`) and its word.
pub fn strength_meter(ui: &mut Ui, level: u8, label: &str) {
let p = theme::palette(ui.ctx());
let color = match level {
0..=1 => p.error,
2 => p.warning,
_ => p.success,
};
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = theme::GAP_XS;
for i in 0..4u8 {
let (rect, _) = ui.allocate_exact_size(vec2(36.0, 6.0), Sense::hover());
let on = theme::effect(ui.ctx(), ui.id().with(("strength", i)), i < level);
ui.painter().rect_filled(rect, theme::corner_radius(theme::FULL), theme::layer(p.surface_container_highest, color, on));
}
ui.add_space(theme::GAP_S);
ui.label(RichText::new(label).font(theme::font(theme::SMALL, Weight::Medium)).color(p.on_surface_variant));
});
}