#![forbid(unsafe_code)]
use egui::{
Color32, ComboBox, CornerRadius, DragValue, Margin, Painter, Rect, Response, RichText, Shape,
Slider, Stroke, TextEdit, Ui,
};
use makeover_layout::{
Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State, ThemeVariant, Tone,
};
use std::ops::RangeInclusive;
pub mod host;
pub mod piece;
pub mod table;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Palette {
pub page: Color32,
pub raised: Color32,
pub overlay: Color32,
pub well: Color32,
pub sunken: Color32,
pub bevel_light: Color32,
pub bevel_dark: Color32,
pub elevation: Color32,
pub content: Color32,
pub content_secondary: Color32,
pub content_muted: Color32,
pub action: Color32,
pub content_on_action: Color32,
pub danger: Color32,
pub success: Color32,
pub warning: Color32,
pub info: Color32,
pub border: Color32,
pub info_surface: Color32,
pub success_surface: Color32,
pub warning_surface: Color32,
pub danger_surface: Color32,
pub row_hover: Color32,
pub row_rule: Color32,
pub row_selected: Color32,
}
impl Palette {
#[must_use]
pub const fn two_tone(page: Color32, ink: Color32) -> Self {
Self {
page,
raised: page,
overlay: page,
well: page,
sunken: page,
bevel_light: page,
bevel_dark: ink,
elevation: Color32::TRANSPARENT,
content: ink,
content_secondary: ink,
content_muted: ink,
action: ink,
content_on_action: page,
danger: ink,
success: ink,
warning: ink,
info: ink,
border: ink,
info_surface: page,
success_surface: page,
warning_surface: page,
danger_surface: page,
row_hover: page,
row_rule: ink,
row_selected: page,
}
}
#[must_use]
pub const fn page(mut self, colour: Color32) -> Self {
self.page = colour;
self
}
#[must_use]
pub const fn raised(mut self, colour: Color32) -> Self {
self.raised = colour;
self
}
#[must_use]
pub const fn overlay(mut self, colour: Color32) -> Self {
self.overlay = colour;
self
}
#[must_use]
pub const fn well(mut self, colour: Color32) -> Self {
self.well = colour;
self
}
#[must_use]
pub const fn sunken(mut self, colour: Color32) -> Self {
self.sunken = colour;
self
}
#[must_use]
pub const fn bevel_light(mut self, colour: Color32) -> Self {
self.bevel_light = colour;
self
}
#[must_use]
pub const fn bevel_dark(mut self, colour: Color32) -> Self {
self.bevel_dark = colour;
self
}
#[must_use]
pub const fn elevation(mut self, colour: Color32) -> Self {
self.elevation = colour;
self
}
#[must_use]
pub const fn content(mut self, colour: Color32) -> Self {
self.content = colour;
self
}
#[must_use]
pub const fn content_secondary(mut self, colour: Color32) -> Self {
self.content_secondary = colour;
self
}
#[must_use]
pub const fn content_muted(mut self, colour: Color32) -> Self {
self.content_muted = colour;
self
}
#[must_use]
pub const fn action(mut self, colour: Color32) -> Self {
self.action = colour;
self
}
#[must_use]
pub const fn content_on_action(mut self, colour: Color32) -> Self {
self.content_on_action = colour;
self
}
#[must_use]
pub const fn danger(mut self, colour: Color32) -> Self {
self.danger = colour;
self
}
#[must_use]
pub const fn success(mut self, colour: Color32) -> Self {
self.success = colour;
self
}
#[must_use]
pub const fn warning(mut self, colour: Color32) -> Self {
self.warning = colour;
self
}
#[must_use]
pub const fn info(mut self, colour: Color32) -> Self {
self.info = colour;
self
}
#[must_use]
pub const fn border(mut self, colour: Color32) -> Self {
self.border = colour;
self
}
#[must_use]
pub const fn info_surface(mut self, colour: Color32) -> Self {
self.info_surface = colour;
self
}
#[must_use]
pub const fn success_surface(mut self, colour: Color32) -> Self {
self.success_surface = colour;
self
}
#[must_use]
pub const fn warning_surface(mut self, colour: Color32) -> Self {
self.warning_surface = colour;
self
}
#[must_use]
pub const fn danger_surface(mut self, colour: Color32) -> Self {
self.danger_surface = colour;
self
}
#[must_use]
pub const fn row_hover(mut self, colour: Color32) -> Self {
self.row_hover = colour;
self
}
#[must_use]
pub const fn row_rule(mut self, colour: Color32) -> Self {
self.row_rule = colour;
self
}
#[must_use]
pub const fn row_selected(mut self, colour: Color32) -> Self {
self.row_selected = colour;
self
}
#[cfg(feature = "theme")]
pub fn from_theme(tokens: &makeover::SemanticTokens) -> Result<Self, MissingToken> {
use makeover::Token;
let colour = |token: Token| {
tokens
.rgba(token)
.map(|(r, g, b, a)| Color32::from_rgba_unmultiplied(r, g, b, a))
.ok_or(MissingToken(token))
};
Ok(Self {
page: colour(Token::SurfacePage)?,
raised: colour(Token::SurfaceRaised)?,
overlay: colour(Token::SurfaceOverlay)?,
well: colour(Token::SurfaceWell)?,
sunken: colour(Token::SurfaceSunken)?,
bevel_light: colour(Token::BevelLight)?,
bevel_dark: colour(Token::BevelDark)?,
elevation: colour(Token::Elevation)?,
content: colour(Token::Content)?,
content_secondary: colour(Token::ContentSecondary)?,
content_muted: colour(Token::ContentMuted)?,
action: colour(Token::Action)?,
content_on_action: colour(Token::ContentOnAction)?,
danger: colour(Token::Danger)?,
success: colour(Token::Success)?,
warning: colour(Token::Warning)?,
info: colour(Token::Info)?,
border: colour(Token::Border)?,
info_surface: colour(Token::InfoSurface)?,
success_surface: colour(Token::SuccessSurface)?,
warning_surface: colour(Token::WarningSurface)?,
danger_surface: colour(Token::DangerSurface)?,
row_hover: colour(Token::RowHover)?,
row_rule: colour(Token::RowRule)?,
row_selected: colour(Token::RowSelected)?,
})
}
}
#[cfg(feature = "theme")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MissingToken(pub makeover::Token);
#[cfg(feature = "theme")]
impl std::fmt::Display for MissingToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "the theme resolves no `{}`", self.0.as_str())
}
}
#[cfg(feature = "theme")]
impl std::error::Error for MissingToken {}
impl Palette {
#[must_use]
pub const fn fill(&self, fill: Fill) -> Option<Color32> {
match fill {
Fill::Page => Some(self.page),
Fill::Raised => Some(self.raised),
Fill::Overlay => Some(self.overlay),
Fill::Well => Some(self.well),
Fill::Sunken => Some(self.sunken),
_ => None,
}
}
#[must_use]
pub const fn tone(&self, tone: Tone) -> Color32 {
match tone {
Tone::Neutral => self.content,
Tone::Info => self.info,
Tone::Success => self.success,
Tone::Warning => self.warning,
Tone::Danger => self.danger,
_ => self.content,
}
}
#[must_use]
pub const fn tone_surface(&self, tone: Tone) -> Color32 {
match tone {
Tone::Neutral => self.raised,
Tone::Info => self.info_surface,
Tone::Success => self.success_surface,
Tone::Warning => self.warning_surface,
Tone::Danger => self.danger_surface,
_ => self.raised,
}
}
#[must_use]
pub const fn tone_edge(&self, tone: Tone) -> Color32 {
match tone {
Tone::Neutral => self.border,
other => self.tone(other),
}
}
#[must_use]
pub const fn cast(&self) -> egui::Shadow {
egui::Shadow {
offset: [0, 2],
blur: 24,
spread: 0,
color: self.elevation,
}
}
#[must_use]
pub const fn edge(&self, edge: Edge) -> Color32 {
match edge {
Edge::Light => self.bevel_light,
Edge::Dark => self.bevel_dark,
_ => self.border,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FrameStyle {
pub radius: CornerRadius,
pub margin: Margin,
pub stroke: f32,
}
impl Default for FrameStyle {
fn default() -> Self {
Self {
radius: CornerRadius::ZERO,
margin: Margin::ZERO,
stroke: 1.0,
}
}
}
pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
let (top_left, bottom_right) = bevel.edges();
let r = rect.shrink(stroke / 2.0);
painter.add(Shape::line(
vec![r.left_bottom(), r.left_top(), r.right_top()],
Stroke::new(stroke, palette.edge(top_left)),
));
let shaded = if bevel.draws_bottom() {
vec![r.right_top(), r.right_bottom(), r.left_bottom()]
} else {
vec![r.right_top(), r.right_bottom()]
};
painter.add(Shape::line(
shaded,
Stroke::new(stroke, palette.edge(bottom_right)),
));
}
pub fn frame<R>(
ui: &mut Ui,
depth: Depth,
palette: &Palette,
style: FrameStyle,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> R {
let mut f = egui::Frame::new()
.corner_radius(style.radius)
.inner_margin(style.margin);
if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
f = f.fill(fill);
}
if depth.fill() == Some(Fill::Overlay) {
f = f.shadow(palette.cast());
}
let framed = f.show(ui, add_contents);
if let Some(bevel) = depth.bevel() {
paint_bevel(
ui.painter(),
framed.response.rect,
bevel,
palette,
style.stroke,
);
}
framed.inner
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FieldStyle {
pub frame: FrameStyle,
pub gap: f32,
pub group_gap: f32,
pub required_marker: &'static str,
}
impl Default for FieldStyle {
fn default() -> Self {
Self {
frame: FrameStyle::default(),
gap: 0.0,
group_gap: 0.0,
required_marker: "*",
}
}
}
#[derive(Debug, Default)]
#[non_exhaustive]
pub enum Editing<'a> {
#[default]
Absent,
Text(&'a mut String),
On(&'a mut bool),
Ticked(&'a mut Vec<String>),
Between {
lower: &'a mut String,
upper: &'a mut String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Control {
Typed,
Chosen,
Listed,
Ticked,
Toggled,
Slid,
Themed,
Spanned,
}
fn combo_row(opt: &Choice<'_>) -> String {
let mut text = opt.label.to_owned();
for extra in [opt.detail, opt.unavailable].into_iter().flatten() {
text.push_str(" ");
text.push_str(extra);
}
text
}
const OPTION_DETAIL_INDENT: f32 = 22.0;
const fn control_shape(kind: FieldKind) -> Control {
match kind {
FieldKind::Select => Control::Chosen,
FieldKind::Radio => Control::Listed,
FieldKind::Checklist => Control::Ticked,
FieldKind::Checkbox => Control::Toggled,
FieldKind::Range => Control::Slid,
FieldKind::Interval => Control::Spanned,
FieldKind::Theme => Control::Themed,
_ => Control::Typed,
}
}
fn shape_of(field: &Field<'_>) -> Control {
match control_shape(field.kind) {
Control::Slid if !field.bounded() => Control::Typed,
shape => shape,
}
}
fn extent(field: &Field<'_>) -> Option<RangeInclusive<f64>> {
let min = field.min?.parse::<f64>().ok().filter(|n| n.is_finite())?;
let max = field.max?.parse::<f64>().ok().filter(|n| n.is_finite())?;
Some(min..=max)
}
fn step_value(step: Option<&str>) -> Option<f64> {
step?
.trim()
.parse::<f64>()
.ok()
.filter(|n| n.is_finite() && *n > 0.0)
}
const MAX_DECIMALS: usize = 15;
fn decimals(step: Option<&str>) -> Option<usize> {
let step = step_value(step)?;
let written = format!("{step}");
Some(
written
.split_once('.')
.map_or(0, |(_, fraction)| fraction.len())
.min(MAX_DECIMALS),
)
}
fn written_back(number: f64, step: Option<&str>) -> Option<String> {
if !number.is_finite() {
return None;
}
Some(match decimals(step) {
Some(places) => format!("{number:.places$}"),
None => number.to_string(),
})
}
fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
options
.iter()
.find(|opt| opt.value == value)
.map_or(value, |opt| opt.label)
}
fn chosen_text<'a>(field: &'a Field<'a>, value: &'a str, palette: &Palette) -> (&'a str, Color32) {
match field.placeholder {
Some(ghost) if value.is_empty() => (ghost, palette.content_muted),
_ => (shown_label(field.options, value), palette.content),
}
}
fn option_color(value: &str, option: &str, palette: &Palette) -> Color32 {
if value == option {
palette.content
} else {
palette.content_secondary
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Bound {
Low,
High,
}
struct Axis<'a> {
extent: Option<RangeInclusive<f64>>,
step: Option<&'a str>,
unit: Option<&'a str>,
}
impl Axis<'_> {
fn edge(&self, which: Bound) -> f64 {
self.extent.as_ref().map_or(0.0, |extent| match which {
Bound::Low => *extent.start(),
Bound::High => *extent.end(),
})
}
fn end(&self, ui: &mut Ui, value: &mut String, which: Bound) -> Response {
let mut number = value
.parse::<f64>()
.ok()
.filter(|n| n.is_finite())
.unwrap_or(self.edge(which));
let mut drag = DragValue::new(&mut number);
if let Some(extent) = self.extent.clone() {
drag = drag.range(extent);
}
if let Some(places) = decimals(self.step) {
drag = drag.max_decimals(places);
}
if let Some(step) = step_value(self.step) {
drag = drag.speed(step);
}
if let Some(unit) = self.unit {
drag = drag.suffix(format!(" {unit}"));
}
let response = ui.add(drag);
if response.changed()
&& let Some(text) = written_back(number, self.step)
{
*value = text;
}
response
}
}
fn control(
ui: &mut Ui,
field: &Field<'_>,
editing: Editing<'_>,
palette: &Palette,
style: &FieldStyle,
named_by: Option<egui::Id>,
) -> Response {
let mut discard = String::new();
let mut spare = String::new();
let mut off = false;
match shape_of(field) {
Control::Slid => {
let value = match editing {
Editing::Text(text) => text,
_ => &mut discard,
};
let Some(extent) = extent(field) else {
return ui.label(RichText::new(value.as_str()).color(palette.content));
};
let mut number = value
.parse::<f64>()
.ok()
.filter(|n| n.is_finite())
.unwrap_or(*extent.start());
let step = field.curve.step();
let mut slider = Slider::new(&mut number, extent.clone()).text("");
if let Some(places) = decimals(step) {
slider = slider.max_decimals(places);
}
if let Some(step) = step_value(step) {
slider = slider.step_by(step);
}
if field.curve.is_ratio(*extent.start(), *extent.end()) {
slider = slider.logarithmic(true);
}
if let Some(unit) = field.shown_unit() {
slider = slider.suffix(format!(" {unit}"));
}
let response = ui.add(slider);
if response.changed()
&& let Some(text) = written_back(number, step)
{
*value = text;
}
response
}
Control::Spanned => {
let (lower, upper) = match editing {
Editing::Between { lower, upper } => (lower, upper),
_ => (&mut discard, &mut spare),
};
let axis = Axis {
extent: extent(field),
step: field.step,
unit: field.shown_unit(),
};
ui.horizontal(|ui| {
let low = axis.end(ui, lower, Bound::Low);
ui.label(RichText::new("to").color(palette.content_secondary));
let high = axis.end(ui, upper, Bound::High);
if let Some(id) = named_by {
low.clone().labelled_by(id);
high.clone().labelled_by(id);
}
low | high
})
.inner
}
Control::Typed => {
let text = match editing {
Editing::Text(text) => text,
_ => &mut discard,
};
let mut edit = if field.kind.multiline() {
TextEdit::multiline(text)
} else {
TextEdit::singleline(text)
}
.frame(egui::Frame::NONE)
.margin(Margin::ZERO)
.text_color(palette.content)
.password(field.kind.confidential());
if let Some(ghost) = field.placeholder {
edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
}
let response = frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit));
match field.shown_unit() {
Some(unit) => {
ui.label(RichText::new(unit).color(palette.content_muted));
response
}
None => response,
}
}
Control::Toggled => {
let on = match editing {
Editing::On(on) => on,
_ => &mut off,
};
ui.checkbox(on, RichText::new(field.label).color(palette.content))
}
Control::Listed => {
let value = match editing {
Editing::Text(text) => text,
_ => &mut discard,
};
let group = ui.vertical(|ui| {
let mut answered: Option<Response> = None;
for opt in field.options {
let picked = if let Some(reason) = opt.unavailable {
ui.horizontal(|ui| {
let picked = ui
.add_enabled_ui(false, |ui| {
ui.radio_value(
value,
opt.value.to_owned(),
RichText::new(opt.label).color(palette.content_muted),
)
})
.inner;
ui.label(RichText::new(reason).color(palette.content_muted));
picked
})
.inner
} else {
ui.radio_value(
value,
opt.value.to_owned(),
RichText::new(opt.label).color(option_color(value, opt.value, palette)),
)
};
if let Some(detail) = opt.detail {
ui.horizontal(|ui| {
ui.add_space(OPTION_DETAIL_INDENT);
ui.label(RichText::new(detail).color(palette.content_muted));
});
}
answered = Some(match answered {
Some(prev) => prev.union(picked),
None => picked,
});
}
answered
});
group.inner.unwrap_or(group.response)
}
Control::Ticked => {
let mut seeded: Vec<String>;
let ticked = if let Editing::Ticked(ticked) = editing {
ticked
} else {
seeded = field
.options
.iter()
.filter(|opt| opt.chosen)
.map(|opt| opt.value.to_owned())
.collect();
&mut seeded
};
let group = ui.vertical(|ui| {
let mut answered: Option<Response> = None;
for opt in field.options {
let mut on = ticked.iter().any(|value| value == opt.value);
let before = on;
let color = if !opt.available() {
palette.content_muted
} else if on {
palette.content
} else {
palette.content_secondary
};
let picked = ui
.horizontal(|ui| {
let picked = ui
.add_enabled_ui(opt.available(), |ui| {
ui.checkbox(&mut on, RichText::new(opt.label).color(color))
})
.inner;
if let Some(reason) = opt.unavailable {
ui.label(RichText::new(reason).color(palette.content_muted));
}
picked
})
.inner;
if on != before {
if on {
ticked.push(opt.value.to_owned());
} else {
ticked.retain(|value| value != opt.value);
}
}
if let Some(detail) = opt.detail {
ui.horizontal(|ui| {
ui.add_space(OPTION_DETAIL_INDENT);
ui.label(RichText::new(detail).color(palette.content_muted));
});
}
answered = Some(match answered {
Some(prev) => prev.union(picked),
None => picked,
});
}
answered
});
group.inner.unwrap_or(group.response)
}
Control::Chosen => {
let value = match editing {
Editing::Text(text) => text,
_ => &mut discard,
};
let (shown, tone) = chosen_text(field, value, palette);
ComboBox::from_id_salt(field.name)
.selected_text(RichText::new(shown).color(tone))
.show_ui(ui, |ui| {
for opt in field.options {
let text = combo_row(opt);
if opt.unavailable.is_some() {
ui.add_enabled_ui(false, |ui| {
ui.selectable_value(
value,
opt.value.to_owned(),
RichText::new(text).color(palette.content_muted),
);
});
continue;
}
ui.selectable_value(
value,
opt.value.to_owned(),
RichText::new(text).color(option_color(value, opt.value, palette)),
);
}
})
.response
}
Control::Themed => {
let value = match editing {
Editing::Text(text) => text,
_ => &mut discard,
};
let shown = themed_text(field, value);
ComboBox::from_id_salt(field.name)
.selected_text(RichText::new(shown).color(palette.content))
.show_ui(ui, |ui| {
if let Some(follow) = field.follows {
ui.selectable_value(
value,
follow.value.to_owned(),
RichText::new(follow.label).color(option_color(
value,
follow.value,
palette,
)),
);
}
let mut open: Option<ThemeVariant> = None;
for theme in field.themes {
if open != Some(theme.variant) {
if open.is_some() {
ui.separator();
}
ui.label(
RichText::new(theme.variant.heading()).color(palette.content_muted),
);
open = Some(theme.variant);
}
ui.selectable_value(
value,
theme.id.to_owned(),
RichText::new(format!("{} {}", theme.name, theme.contrast.badge()))
.color(option_color(value, theme.id, palette)),
);
}
})
.response
}
}
}
fn themed_text<'a>(field: &'a Field<'a>, value: &'a str) -> &'a str {
if let Some(follow) = field.follows
&& follow.value == value
{
return follow.label;
}
field
.themes
.iter()
.find(|theme| theme.id == value)
.map_or(value, |theme| theme.name)
}
pub fn field(
ui: &mut Ui,
field: &Field<'_>,
editing: Editing<'_>,
state: Option<State>,
palette: &Palette,
style: &FieldStyle,
) -> Option<Response> {
if !field.kind.visible() {
return None;
}
let enabled = !state.is_some_and(State::suppresses_interaction);
let text = if enabled {
palette.content
} else {
palette.content_muted
};
let response = ui
.vertical(|ui| {
ui.spacing_mut().item_spacing.y = style.gap;
let named_by = (!field.kind.labels_itself()).then(|| {
ui.label(RichText::new(field.marked_label(style.required_marker)).color(text))
});
let response = ui
.add_enabled_ui(enabled, |ui| {
control(
ui,
field,
editing,
palette,
style,
named_by.as_ref().map(|l| l.id),
)
})
.inner;
let response = match named_by {
Some(label) => response.labelled_by(label.id),
None => response,
};
if let Some(hint) = field.hint {
ui.label(RichText::new(hint).color(palette.content_muted));
}
if let Some((tone, note)) = field.note {
ui.label(RichText::new(note).color(palette.tone(tone)));
}
if let Some(error) = field.error {
ui.label(RichText::new(error).color(palette.danger));
}
response
})
.inner;
Some(response)
}
pub fn group<'a>(
ui: &mut Ui,
fields: &'a [Field<'a>],
show_extended: bool,
style: &FieldStyle,
mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
) {
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = style.group_gap;
for f in fields {
if f.extended && !show_extended {
continue;
}
draw(ui, f);
}
});
}
#[cfg(test)]
mod tests;