use std::sync::Arc;
use super::{
icons, names,
part_style::{Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{fading, glyph},
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::Ctx,
events::KeyboardEvent,
theme::{OpacityLevel, PaletteColor, RadiusSize, Theme},
},
components::{Row, Stack},
core::{ElementRef, Signal},
layout::Alignment,
node::{CursorIcon, Element, dimension::Dimension},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RatingPart {
Root,
Star,
Filled,
Empty,
}
names!(RatingPart {
Root => "root",
Star => "star",
Filled => "filled",
Empty => "empty",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RatingState {
Interactive,
ReadOnly,
Invalid,
Disabled,
}
names!(RatingState {
Interactive => "interactive",
ReadOnly => "read_only",
Invalid => "invalid",
Disabled => "disabled",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum RatingSize {
Sm,
#[default]
Md,
Lg,
}
names!(RatingSize {
Sm => "sm",
Md => "md",
Lg => "lg",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum RatingPrecision {
#[default]
Whole,
Half,
}
impl RatingPrecision {
pub fn step(self) -> f64 {
match self {
Self::Whole => 1.0,
Self::Half => 0.5,
}
}
}
pub trait RatingValue: Copy + PartialEq + Send + Sync + 'static {
fn stars(self) -> Option<f64>;
fn from_stars(stars: Option<f64>) -> Self;
}
impl RatingValue for f64 {
fn stars(self) -> Option<f64> {
(self > 0.0).then_some(self)
}
fn from_stars(stars: Option<f64>) -> Self {
stars.unwrap_or(0.0)
}
}
impl RatingValue for Option<f64> {
fn stars(self) -> Option<f64> {
self.filter(|stars| *stars > 0.0)
}
fn from_stars(stars: Option<f64>) -> Self {
stars
}
}
pub type RatingValueText = Arc<dyn Fn(Option<f64>, u32) -> String + Send + Sync>;
pub type RatingRenderer = Arc<dyn Fn(RatingView) -> Element + Send + Sync>;
type Change = Arc<dyn Fn(Option<f64>) + Send + Sync>;
pub struct Rating<V = f64> {
value: V,
set: Option<Arc<dyn Fn(V) + Send + Sync>>,
on_change: Vec<Arc<dyn Fn(V) + Send + Sync>>,
max: u32,
precision: RatingPrecision,
clearable: bool,
read_only: bool,
disabled: bool,
invalid: bool,
size: Name,
icon: Name,
empty_icon: Name,
label: Option<Arc<str>>,
value_text: RatingValueText,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl<V: RatingValue> Rating<V> {
fn of(value: V, set: Option<Arc<dyn Fn(V) + Send + Sync>>) -> Self {
Self {
value,
set,
on_change: Vec::new(),
max: 5,
precision: RatingPrecision::Whole,
clearable: false,
read_only: false,
disabled: false,
invalid: false,
size: Name::from(RatingSize::Md),
icon: Name::new(icons::STAR_FILL),
empty_icon: Name::new(icons::STAR_FILL),
label: None,
value_text: {
let locale = super::current_locale();
Arc::new(move |stars, max| match stars {
Some(stars) => crate::core::fill(
locale.form(&locale.fields.stars, max as usize),
&[("value", &number(stars)), ("count", &max.to_string())],
),
None => locale.fields.no_rating.to_string(),
})
},
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
}
impl Rating<f64> {
pub fn new(stars: Signal<f64>) -> Self {
Self::of(stars.get(), Some(Arc::new(move |value| stars.set(value))))
}
pub fn controlled(stars: f64, on_change: impl Fn(f64) + Send + Sync + 'static) -> Self {
Self::of(stars, None).on_change(on_change)
}
pub fn at(stars: f64) -> Self {
Self::of(stars, None).read_only(true)
}
}
impl Rating<Option<f64>> {
pub fn optional(stars: Signal<Option<f64>>) -> Self {
Self::of(stars.get(), Some(Arc::new(move |value| stars.set(value))))
}
pub fn controlled_optional(stars: Option<f64>, on_change: impl Fn(Option<f64>) + Send + Sync + 'static) -> Self {
Self::of(stars, None).on_change(on_change)
}
}
impl<V: RatingValue> Rating<V> {
pub fn max(mut self, max: u32) -> Self {
self.max = max.max(1);
self
}
pub fn precision(mut self, precision: RatingPrecision) -> Self {
self.precision = precision;
self
}
pub fn clearable(mut self, clearable: bool) -> Self {
self.clearable = clearable;
self
}
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = read_only;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
pub fn icon(mut self, name: impl Into<Name>) -> Self {
self.icon = name.into();
self
}
pub fn empty_icon(mut self, name: impl Into<Name>) -> Self {
self.empty_icon = name.into();
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn value_text(mut self, text: impl Fn(Option<f64>, u32) -> String + Send + Sync + 'static) -> Self {
self.value_text = Arc::new(text);
self
}
pub fn on_change(mut self, handler: impl Fn(V) + Send + Sync + 'static) -> Self {
self.on_change.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 {
self.core().build(theme, None)
}
pub fn mount(self, ctx: &mut Ctx) -> Element {
ctx.mount::<RatingHost>(RatingProps { core: self.core() })
}
fn core(self) -> Core {
let (set, handlers) = (self.set, self.on_change);
let change: Change = Arc::new(move |stars| {
let value = V::from_stars(stars);
if let Some(set) = &set {
set(value);
}
for handler in &handlers {
handler(value);
}
});
Core {
stars: self.value.stars(),
change,
max: self.max,
step: self.precision.step(),
clearable: self.clearable,
read_only: self.read_only,
disabled: self.disabled,
invalid: self.invalid,
size: self.size,
icon: self.icon,
empty_icon: self.empty_icon,
label: self
.label
.unwrap_or_else(|| super::current_locale().fields.rating.clone()),
value_text: self.value_text,
states: self.states,
rules: self.rules,
forced: self.forced,
id: self.id,
key: self.key,
}
}
}
impl<V: RatingValue> From<Rating<V>> for Element {
fn from(rating: Rating<V>) -> Self {
rating.build(¤t_theme())
}
}
fn number(stars: f64) -> String {
let rounded = (stars * 100.0).round() / 100.0;
if rounded.fract() == 0.0 {
format!("{}", rounded as i64)
} else {
format!("{rounded}")
}
}
#[derive(Clone)]
struct Core {
stars: Option<f64>,
change: Change,
max: u32,
step: f64,
clearable: bool,
read_only: bool,
disabled: bool,
invalid: bool,
size: Name,
icon: Name,
empty_icon: Name,
label: Arc<str>,
value_text: RatingValueText,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Core {
fn build(self, theme: &Theme, preview: Option<Signal<Option<f64>>>) -> Element {
let interactive = !self.read_only && !self.disabled;
let case = Case {
variant: None,
size: Some(self.size.clone()),
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(RatingState::Interactive, interactive)
.state(RatingState::ReadOnly, self.read_only)
.state(RatingState::Invalid, self.invalid)
.state(RatingState::Disabled, self.disabled);
let recipe = theme
.resolve::<Rating>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let shown = preview
.as_ref()
.filter(|_| interactive)
.and_then(|preview| preview.get())
.or(self.stars);
let view = RatingView {
stars: self.stars,
shown,
max: self.max,
step: self.step,
clearable: self.clearable,
read_only: self.read_only,
disabled: self.disabled,
invalid: self.invalid,
label: self.label,
recipe,
forced: self.forced,
icon: self.icon,
empty_icon: self.empty_icon,
value_text: self.value_text,
change: interactive.then_some(self.change),
preview: preview.filter(|_| interactive),
root: ElementRef::new(),
id: self.id,
key: self.key,
};
match theme.renderer::<Rating>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
pub struct RatingView {
pub stars: Option<f64>,
pub shown: Option<f64>,
pub max: u32,
pub step: f64,
pub clearable: bool,
pub read_only: bool,
pub disabled: bool,
pub invalid: bool,
pub label: Arc<str>,
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
icon: Name,
empty_icon: Name,
value_text: RatingValueText,
change: Option<Change>,
preview: Option<Signal<Option<f64>>>,
root: ElementRef,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl RatingView {
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 side(&self) -> f32 {
let theme = self.theme();
match self
.part(RatingPart::Star)
.rest()
.width
.and_then(|width: Length| width.resolve(theme))
{
Some(Dimension::Px(px)) => px,
_ => 20.0,
}
}
pub fn lit(&self, index: u32) -> f32 {
let shown = self.shown.unwrap_or(0.0);
(shown - f64::from(index)).clamp(0.0, 1.0) as f32
}
fn asked(&self, stars: f64) -> Option<f64> {
let stars = stars.clamp(0.0, f64::from(self.max));
if stars <= 0.0 || (self.clearable && Some(stars) == self.stars) {
None
} else {
Some(stars)
}
}
fn setter(&self) -> Option<impl Fn(Option<f64>) + Send + Sync + Clone + 'static> {
let (change, held) = (self.change.clone()?, self.stars);
Some(move |stars: Option<f64>| {
if stars != held {
change(stars);
}
})
}
fn keyed(&self, key: &str) -> Option<Option<f64>> {
let (step, max) = (self.step, f64::from(self.max));
let held = self.stars.unwrap_or(0.0);
let least = if self.clearable { 0.0 } else { step };
let asked = match key {
"ArrowRight" | "ArrowUp" => ((held / step).floor() * step + step).min(max),
"ArrowLeft" | "ArrowDown" => ((held / step).ceil() * step - step).max(least),
"Home" => least,
"End" => max,
"Backspace" | "Delete" if self.clearable => 0.0,
digit if digit.len() == 1 && digit.as_bytes()[0].is_ascii_digit() => {
let stars = f64::from(digit.as_bytes()[0] - b'0');
if stars > max || (stars == 0.0 && !self.clearable) {
return None;
}
stars
}
_ => return None,
};
Some((asked > 0.0).then_some(asked))
}
pub fn root(&self) -> Row {
let text = (self.value_text)(self.stars, self.max);
let mut root = Row::new()
.align_items(Alignment::Center)
.overflow_visible()
.part(&self.part(RatingPart::Root))
.ref_element(self.root.clone())
.describe("a11y_role", "slider")
.describe("a11y_name", self.label.clone())
.describe("a11y_valuemin", number(if self.clearable { 0.0 } else { self.step }))
.describe("a11y_valuemax", self.max.to_string())
.describe("a11y_valuenow", number(self.stars.unwrap_or(0.0)))
.describe("a11y_valuetext", text);
if self.read_only {
root = root.describe("a11y_readonly", "true");
}
if self.disabled {
root = root.describe("a11y_disabled", "true");
}
if self.invalid {
root = root.describe("a11y_invalid", "true");
}
if let Some(set) = self.setter() {
root = root.tab_index(0);
let asks: Vec<(&'static str, Option<Option<f64>>)> = [
"ArrowRight",
"ArrowUp",
"ArrowLeft",
"ArrowDown",
"Home",
"End",
"Backspace",
"Delete",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
]
.into_iter()
.map(|key| (key, self.keyed(key)))
.collect();
root = root.on_key_down(move |event: KeyboardEvent| {
if !event.focus_within || event.ctrl || event.alt || event.meta || event.composing {
return;
}
let Some((_, Some(asked))) = asks.iter().find(|(key, _)| *key == event.key) else {
return;
};
event.prevent_default();
set(*asked);
});
}
if let Some(preview) = self.preview.clone() {
root = root.on_mouse_leave(move || preview.set(None));
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root
}
pub fn star(&self, index: u32) -> Element {
let side = self.side();
let lit = self.lit(index);
let number = index + 1;
let mut star = Stack::new().part(&self.part(RatingPart::Star).keyed(number));
if lit < 1.0 {
star = star.child(glyph(
&self.part(RatingPart::Empty).keyed(number),
self.empty_icon.clone(),
false,
));
}
if lit > 0.0 {
let filled = glyph(&self.part(RatingPart::Filled).keyed(number), self.icon.clone(), false);
star = star.child(if lit < 1.0 {
Row::new().width(side * lit).height(side).child(filled).into()
} else {
filled
});
}
if let Some(set) = self.setter() {
let halves: &[f64] = if self.step < 1.0 { &[0.5, 1.0] } else { &[1.0] };
let mut rooms = Row::new().size(side, side);
for &part in halves {
let stars = f64::from(index) + part;
let asked = self.asked(stars);
let set = set.clone();
let mut room = Row::new()
.size(side / halves.len() as f32, side)
.focuses(&self.root)
.on_click(move |_| set(asked));
if let Some(preview) = self.preview.clone() {
room = room.on_mouse_enter(move || preview.set(Some(stars)));
}
rooms = rooms.child(room);
}
star = star.child(rooms);
}
star.into()
}
pub fn render(self) -> Element {
let stars: Vec<Element> = (0..self.max).map(|index| self.star(index)).collect();
self.root().with_children(stars).into()
}
}
struct RatingProps {
core: Core,
}
impl PartialEq for RatingProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for RatingProps {}
struct RatingHost {
preview: Signal<Option<f64>>,
}
impl Component for RatingHost {
type Props = RatingProps;
fn create(ctx: &mut Ctx) -> Self {
Self {
preview: ctx.signal(None),
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let core = ctx.props::<RatingProps>().core.clone();
core.build(¤t_theme(), Some(self.preview.clone()))
}
}
impl crate::ui::Styled for Rating {
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 Rating {
const NAME: &'static str = "rating";
type Renderer = RatingRenderer;
fn parts() -> crate::ui::Declared {
RatingPart::declared()
}
fn states() -> crate::ui::Declared {
RatingState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{Destructive, Input, Warning};
use RatingPart::{Empty, Filled, Root, Star};
use RatingState::{Disabled, Interactive, Invalid};
let mut recipe = Recipe::new()
.base(Root, |s| fading(s.gap(4.0).radius(RadiusSize::Sm)))
.base(Filled, |s| s.foreground(Warning))
.base(Empty, |s| s.foreground(Input))
.focus_visible(Root, |s| s.focus_ring())
.state(Interactive, Star, |s| s.cursor(CursorIcon::Pointer))
.state(Invalid, Empty, |s| {
s.foreground(Destructive).opacity(OpacityLevel::Disabled)
})
.state(Disabled, Root, |s| s.opacity(OpacityLevel::Disabled));
for (size, side, gap) in [
(RatingSize::Sm, 16.0, 2.0),
(RatingSize::Md, 20.0, 4.0),
(RatingSize::Lg, 24.0, 4.0),
] {
recipe = recipe
.size(size, Root, move |s| s.gap(gap))
.size(size, Star, move |s| s.square(side))
.size(size, Filled, move |s| s.square(side))
.size(size, Empty, move |s| s.square(side));
}
recipe
}
}
impl<V: RatingValue> super::FieldControl for Rating<V> {
fn in_field(mut self, field: &super::InField) -> Element {
if self.label.is_none() && !field.label.is_empty() {
self.label = Some(field.label.clone());
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
self.into()
}
fn mount_in_field(mut self, field: &super::InField, ctx: &mut Ctx) -> Element {
if self.label.is_none() && !field.label.is_empty() {
self.label = Some(field.label.clone());
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
self.mount(ctx)
}
}