use std::sync::Arc;
use super::{
names,
part_style::{FontFamily, Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{fading, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::theme::{BorderSize, OpacityLevel, PaletteColor, RadiusSize, ShadowStyle, Theme, TypographyStyle},
components::{Column, Row},
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{
BackgroundColor, CursorIcon, Element, FocusGroup, border::Border as Edge, dimension::Dimension, outline::Outline,
},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BarListPart {
Root,
Header,
Title,
Description,
Rows,
Row,
Name,
Track,
Bar,
Value,
Empty,
}
names!(BarListPart {
Root => "root",
Header => "header",
Title => "title",
Description => "description",
Rows => "rows",
Row => "row",
Name => "name",
Track => "track",
Bar => "bar",
Value => "value",
Empty => "empty",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BarListState {
Framed,
Pressable,
Disabled,
}
names!(BarListState {
Framed => "framed",
Pressable => "pressable",
Disabled => "disabled",
});
pub type BarListRenderer = Arc<dyn Fn(BarListView) -> Element + Send + Sync>;
type Select = Arc<dyn Fn() + Send + Sync>;
type Told = Arc<dyn Fn(&str) + Send + Sync>;
type ValueText = Arc<dyn Fn(f64) -> String + Send + Sync>;
pub struct BarListItem {
name: Arc<str>,
value: f64,
color: Option<BackgroundColor>,
on_select: Vec<Select>,
disabled: bool,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl BarListItem {
pub fn new(name: &str, value: impl Into<f64>) -> Self {
Self {
name: Arc::from(name),
value: value.into(),
color: None,
on_select: Vec::new(),
disabled: false,
id: None,
key: None,
}
}
pub fn color(mut self, color: impl Into<BackgroundColor>) -> Self {
self.color = Some(color.into());
self
}
pub fn on_select(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_select.push(Arc::new(handler));
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
}
impl<N: AsRef<str>, V: Into<f64>> From<(N, V)> for BarListItem {
fn from((name, value): (N, V)) -> Self {
Self::new(name.as_ref(), value)
}
}
pub struct BarList {
items: Vec<BarListItem>,
title: Option<Arc<str>>,
description: Option<Arc<str>>,
label: Option<Arc<str>>,
max: Option<f64>,
color: BackgroundColor,
value_text: Option<ValueText>,
empty_text: Option<Arc<str>>,
framed: bool,
on_select: Vec<Told>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl BarList {
pub fn new(items: impl IntoIterator<Item = impl Into<BarListItem>>) -> Self {
Self {
items: items.into_iter().map(Into::into).collect(),
title: None,
description: None,
label: None,
max: None,
color: BackgroundColor::Palette(PaletteColor::Chart1),
value_text: None,
empty_text: None,
framed: true,
on_select: Vec::new(),
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn item(mut self, item: impl Into<BarListItem>) -> Self {
self.items.push(item.into());
self
}
pub fn items(mut self, items: impl IntoIterator<Item = impl Into<BarListItem>>) -> Self {
self.items.extend(items.into_iter().map(Into::into));
self
}
pub fn title(mut self, title: &str) -> Self {
self.title = Some(Arc::from(title));
self
}
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn max(mut self, max: impl Into<f64>) -> Self {
self.max = Some(max.into());
self
}
pub fn color(mut self, color: impl Into<BackgroundColor>) -> Self {
self.color = color.into();
self
}
pub fn value_text(mut self, text: impl Fn(f64) -> String + Send + Sync + 'static) -> Self {
self.value_text = Some(Arc::new(text));
self
}
pub fn empty_text(mut self, text: &str) -> Self {
self.empty_text = Some(Arc::from(text));
self
}
pub fn framed(mut self, framed: bool) -> Self {
self.framed = framed;
self
}
pub fn on_select(mut self, handler: impl Fn(&str) + Send + Sync + 'static) -> Self {
self.on_select.push(Arc::new(handler));
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
let view = self.view(theme);
match theme.renderer::<BarList>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
fn view(self, theme: &Theme) -> BarListView {
let base = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(BarListState::Framed, self.framed);
let recipe = theme
.resolve::<BarList>(&base, Some(&self.rules))
.owned_by(self.id.as_ref());
let max = self
.max
.unwrap_or_else(|| round_up(self.items.iter().map(|item| item.value).fold(0.0, f64::max)));
let decimals = self.items.iter().map(|item| decimals_of(item.value)).max().unwrap_or(0);
let text: ValueText = self
.value_text
.unwrap_or_else(|| Arc::new(move |value: f64| format!("{value:.decimals$}")));
let told: Arc<[Told]> = self.on_select.into();
let forced_at = self
.items
.iter()
.position(|item| (!item.on_select.is_empty() || !told.is_empty()) && !item.disabled);
let mut grouped = false;
let rows = self
.items
.into_iter()
.enumerate()
.map(|(index, item)| {
let mut handlers = item.on_select;
if !told.is_empty() {
let (told, key) = (told.clone(), item.key.clone().unwrap_or_else(|| item.name.clone()));
handlers.push(Arc::new(move || {
for handler in told.iter() {
handler(&key);
}
}));
}
grouped |= !handlers.is_empty();
let case = base
.clone()
.state(BarListState::Pressable, !handlers.is_empty())
.state(BarListState::Disabled, item.disabled);
let fraction = if max > 0.0 {
(item.value / max).clamp(0.0, 1.0)
} else {
0.0
};
let row = theme.resolve::<BarList>(&case, Some(&self.rules)).owned_like(&recipe);
let row = match (&item.id, &item.key) {
(None, Some(key)) => row.keyed_item(key, BarListPart::Row),
(id, _) => row.item(id.as_ref(), BarListPart::Row),
};
BarListRow {
value_text: text(item.value),
name: item.name,
value: item.value,
fraction: fraction as f32,
color: item.color.unwrap_or(self.color.clone()),
on_select: handlers,
disabled: item.disabled,
forced: if forced_at == Some(index) { self.forced } else { None },
recipe: row,
id: item.id,
key: item.key,
}
})
.collect();
BarListView {
rows,
title: self.title,
description: self.description,
label: self.label,
max,
empty_text: self
.empty_text
.unwrap_or_else(|| super::current_locale().data.no_data.clone()),
grouped,
recipe,
id: self.id,
key: self.key,
}
}
}
impl From<BarList> for Element {
fn from(list: BarList) -> Self {
list.build(¤t_theme())
}
}
fn round_up(value: f64) -> f64 {
if !value.is_finite() || value <= 0.0 {
return 1.0;
}
let power = 10f64.powf(value.log10().floor());
[1.0, 2.0, 2.5, 5.0, 10.0]
.into_iter()
.map(|step| step * power)
.find(|end| *end >= value * (1.0 - 1e-9))
.unwrap_or(10.0 * power)
}
fn decimals_of(value: f64) -> usize {
(0..2)
.find(|places| {
let scaled = value * 10f64.powi(*places as i32);
(scaled - scaled.round()).abs() < 1e-6
})
.unwrap_or(2)
}
pub struct BarListView {
pub rows: Vec<BarListRow>,
pub title: Option<Arc<str>>,
pub description: Option<Arc<str>>,
pub label: Option<Arc<str>>,
pub max: f64,
pub empty_text: Arc<str>,
pub grouped: bool,
recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl BarListView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn header(&self) -> Option<Column> {
if self.title.is_none() && self.description.is_none() {
return None;
}
let mut header = Column::new()
.width(Dimension::Pct(100.0))
.part(&self.part(BarListPart::Header));
let text = |part: ResolvedPart, content: &str| {
Column::new()
.width(Dimension::Pct(100.0))
.part(&part)
.child(part.text(content))
};
if let Some(title) = &self.title {
header = header.child(text(self.part(BarListPart::Title), title));
}
if let Some(description) = &self.description {
header = header.child(text(self.part(BarListPart::Description), description));
}
Some(header)
}
pub fn rows(&self, rows: Vec<Element>) -> Element {
if rows.is_empty() {
return Row::new()
.part(&self.part(BarListPart::Empty))
.child(self.part(BarListPart::Empty).text(&self.empty_text))
.into();
}
let mut column = Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Stretch)
.overflow_visible()
.part(&self.part(BarListPart::Rows))
.describe("a11y_role", "list");
if self.grouped {
column = column.focus_group(FocusGroup::vertical().one_stop(true).wrap(false).typeahead(true));
}
column.with_children(rows).into()
}
pub fn root(&self, content: Vec<Element>) -> Column {
let mut root = Column::new()
.align_items(Alignment::Stretch)
.part(&self.part(BarListPart::Root))
.describe("a11y_role", "figure");
if let Some(name) = self.label.as_ref().or(self.title.as_ref()) {
root = root.describe("a11y_name", name.clone());
}
if let Some(description) = &self.description {
root = root.describe("a11y_description", description.clone());
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.with_children(content)
}
pub fn render(mut self) -> Element {
let rows: Vec<Element> = std::mem::take(&mut self.rows)
.into_iter()
.map(BarListRow::render)
.collect();
let mut content: Vec<Element> = Vec::new();
content.extend(self.header().map(Into::into));
content.push(self.rows(rows));
self.root(content).into()
}
}
pub struct BarListRow {
pub name: Arc<str>,
pub value: f64,
pub value_text: String,
pub fraction: f32,
pub color: BackgroundColor,
on_select: Vec<Select>,
pub disabled: bool,
forced: Option<Interaction>,
recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl BarListRow {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn pressable(&self) -> bool {
!self.on_select.is_empty()
}
pub fn name(&self) -> Row {
let part = self.part(BarListPart::Name);
Row::new()
.min_width(Dimension::Px(0.0))
.part(&part)
.child(part.text(&self.name).nowrap().width(Dimension::Pct(100.0)))
}
pub fn track(&self) -> Row {
let bar = self.part(BarListPart::Bar);
Row::new()
.flex(1.0)
.min_width(Dimension::Px(0.0))
.align_items(Alignment::Center)
.part(&self.part(BarListPart::Track))
.child(
Row::new()
.width(Dimension::Pct(self.fraction * 100.0))
.part(&bar)
.background(self.color.clone()),
)
}
pub fn value(&self) -> Row {
let part = self.part(BarListPart::Value);
Row::new().part(&part).child(part.text(&self.value_text).nowrap())
}
pub fn root(&self, children: Vec<Element>) -> Element {
let part = self.part(BarListPart::Row);
let line = Row::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.with_children(children);
let mut row = Column::new()
.align_items(Alignment::Stretch)
.overflow_visible()
.describe("a11y_role", "listitem")
.describe("a11y_name", self.name.clone())
.describe("a11y_valuetext", self.value_text.clone());
if let Some(key) = &self.key {
row = row.key(key.clone());
}
if !self.pressable() {
if let Some(id) = &self.id {
row = row.id(id.clone());
}
return row.child(line.part(&part)).into();
}
let handlers = self.on_select.clone();
let mut button = pressable(&part, self.disabled)
.width(Dimension::Pct(100.0))
.justify(Justify::Start)
.align_items(Alignment::Stretch)
.describe("a11y_role", "button")
.describe("a11y_name", format!("{}: {}", self.name, self.value_text))
.focus_label(self.name.clone())
.on_click(move |_| {
for handler in &handlers {
handler();
}
});
if self.disabled {
button = button.describe("a11y_disabled", "true");
}
if let Some(id) = &self.id {
button = button.id(id.clone());
}
row.child(button.child(line)).into()
}
pub fn render(self) -> Element {
let children = vec![self.name().into(), self.track().into(), self.value().into()];
self.root(children)
}
}
impl crate::ui::Styled for BarList {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for BarList {
const NAME: &'static str = "bar_list";
type Renderer = BarListRenderer;
fn parts() -> crate::ui::Declared {
BarListPart::declared()
}
fn states() -> crate::ui::Declared {
BarListState::declared()
}
fn recipe() -> Recipe {
use BarListPart::{Bar, Description, Empty, Header, Name, Root, Row, Rows, Title, Track, Value};
use BarListState::{Disabled, Framed, Pressable};
use PaletteColor::{Card, CardForeground, MutedForeground, Ring, StateHover, StatePressed};
Recipe::new()
.base(Root, |s| s.width(Length::Fill).gap(16.0))
.state(Framed, Root, |s| {
s.background(Card)
.border(Edge::inside(BorderSize::Sm, PaletteColor::Border))
.radius(RadiusSize::Xl)
.shadow(ShadowStyle::Sm)
.padding_x(20.0)
.padding_y(20.0)
})
.base(Header, |s| s.gap(3.0))
.base(Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(15.0)
.weight(FontWeight::SemiBold)
.foreground(CardForeground)
})
.base(Description, |s| {
s.typography(TypographyStyle::Body)
.font_size(12.0)
.foreground(MutedForeground)
})
.base(Rows, |s| s.gap(16.0))
.base(Row, |s| fading(s.gap(10.0).radius(RadiusSize::Sm)))
.state(Pressable, Row, |s| s.cursor(CursorIcon::Pointer))
.when(Selector::new().state(Pressable).hovered(), Row, |s| s.veil(StateHover))
.when(Selector::new().state(Pressable).pressed(), Row, |s| {
s.veil(StatePressed)
})
.focus_visible(Row, |s| s.outline(Outline::new(BorderSize::Md, Ring).offset(-2.0)))
.state(Disabled, Row, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
.base(Name, |s| {
s.width(92.0)
.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(CardForeground)
})
.base(Track, |s| s.height(26.0))
.row_density(Selector::new(), Track, 26.0)
.base(Bar, |s| s.height(14.0).radius(RadiusSize::Sm))
.base(Value, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(Empty, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(MutedForeground)
})
}
}