use dioxus::prelude::*;
use crate::class::{Orientation, compose};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StepperStep {
pub title: String,
pub description: Option<String>,
}
impl StepperStep {
pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
Self {
title: title.into(),
description: Some(description.into()),
}
}
}
impl From<&str> for StepperStep {
fn from(title: &str) -> Self {
Self {
title: title.to_string(),
description: None,
}
}
}
impl From<String> for StepperStep {
fn from(title: String) -> Self {
Self {
title,
description: None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum StepperState {
Complete,
Current,
Upcoming,
}
impl StepperState {
pub fn as_str(self) -> &'static str {
match self {
Self::Complete => "complete",
Self::Current => "current",
Self::Upcoming => "upcoming",
}
}
pub fn of(index: usize, current: i64) -> Self {
let index = i64::try_from(index).unwrap_or(i64::MAX);
match index.cmp(¤t) {
std::cmp::Ordering::Less => Self::Complete,
std::cmp::Ordering::Equal => Self::Current,
std::cmp::Ordering::Greater => Self::Upcoming,
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct StepperProps {
#[props(default)]
pub steps: Vec<StepperStep>,
#[props(default)]
pub current_step: i64,
#[props(default)]
pub orientation: Orientation,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = ol)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn Stepper(props: StepperProps) -> Element {
let class = compose([
Some("ui-stepper"),
(props.orientation == Orientation::Vertical).then_some("ui-stepper--vertical"),
props.class.as_deref(),
]);
rsx! {
ol { class, "data-orientation": props.orientation.as_str(), ..props.attributes,
for (index, step) in props.steps.iter().enumerate() {
{
let state = StepperState::of(index, props.current_step);
rsx! {
li {
key: "{step.title}",
aria_current: (state == StepperState::Current).then_some("step"),
class: "ui-stepper__step",
"data-state": state.as_str(),
span { class: "ui-stepper__marker", "{index + 1}" }
span { class: "ui-stepper__content",
span { class: "ui-stepper__title", "{step.title}" }
if let Some(description) = step.description.as_deref().filter(|text| !text.is_empty()) {
span { class: "ui-stepper__description", "{description}" }
}
}
}
}
}
}
{props.children}
}
}
}
#[cfg(test)]
mod tests {
use super::StepperState;
#[test]
fn states_follow_the_current_step() {
assert_eq!(StepperState::of(0, 1), StepperState::Complete);
assert_eq!(StepperState::of(1, 1), StepperState::Current);
assert_eq!(StepperState::of(2, 1), StepperState::Upcoming);
assert_eq!(StepperState::of(0, -1), StepperState::Upcoming);
assert_eq!(
StepperState::of(usize::MAX, i64::MAX),
StepperState::Current
);
}
}