use dioxus::prelude::*;
use super::shared::has_content;
use crate::class::{Glass, compose};
#[derive(Props, Clone, PartialEq)]
pub struct CalloutProps {
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = aside)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn Callout(props: CalloutProps) -> Element {
let class = compose([Some("ui-callout"), props.class.as_deref()]);
rsx! {
aside { class, ..props.attributes, {props.children} }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum EmptyVariant {
#[default]
Default,
Compact,
}
impl EmptyVariant {
pub fn as_str(self) -> &'static str {
match self {
Self::Default => "default",
Self::Compact => "compact",
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct EmptyProps {
#[props(default)]
pub variant: EmptyVariant,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = section)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn Empty(props: EmptyProps) -> Element {
let glass = props.glass.class("ui-empty");
let class = compose([
Some("ui-empty"),
(props.variant == EmptyVariant::Compact).then_some("ui-empty--compact"),
glass.as_deref(),
props.class.as_deref(),
]);
rsx! {
section {
class,
"data-variant": props.variant.as_str(),
..props.attributes,
{props.children}
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorStateKind {
#[default]
Error,
Offline,
}
impl ErrorStateKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Error => "error",
Self::Offline => "offline",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorStateLayout {
Compact,
#[default]
Default,
Page,
}
impl ErrorStateLayout {
pub fn as_str(self) -> &'static str {
match self {
Self::Compact => "compact",
Self::Default => "default",
Self::Page => "page",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorStateAnnounce {
#[default]
Off,
Polite,
Assertive,
}
#[derive(Props, Clone, PartialEq)]
pub struct ErrorStateProps {
#[props(into)]
pub title: String,
#[props(into)]
pub description: Option<String>,
#[props(default)]
pub kind: ErrorStateKind,
#[props(default)]
pub layout: ErrorStateLayout,
#[props(default)]
pub announce: ErrorStateAnnounce,
#[props(default = 2)]
pub heading_level: u8,
#[props(into)]
pub id: Option<String>,
#[props(into)]
pub reference: Option<String>,
#[props(default = "Reference".to_string(), into)]
pub reference_label: String,
pub actions: Option<Element>,
pub graphic: Option<Element>,
#[props(default)]
pub hide_graphic: bool,
#[props(into)]
pub aria_live: Option<String>,
#[props(into)]
pub role: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = section)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
fn error_state_announcement(
announce: ErrorStateAnnounce,
aria_live: Option<String>,
role: Option<String>,
) -> (Option<String>, Option<String>) {
match announce {
ErrorStateAnnounce::Assertive => (
Some(aria_live.unwrap_or_else(|| "assertive".to_string())),
Some(role.unwrap_or_else(|| "alert".to_string())),
),
ErrorStateAnnounce::Polite => (
Some(aria_live.unwrap_or_else(|| "polite".to_string())),
Some(role.unwrap_or_else(|| "status".to_string())),
),
ErrorStateAnnounce::Off => (aria_live, role),
}
}
fn error_illustration(kind: ErrorStateKind, small: bool) -> Element {
let class = format!(
"ui-illustration ui-illustration--{} ui-illustration--auto ui-illustration--{}",
kind.as_str(),
if small { "sm" } else { "md" }
);
let artwork = match kind {
ErrorStateKind::Error => rsx! {
circle { cx: "60", cy: "60", r: "28" }
line { x1: "49", x2: "71", y1: "49", y2: "71" }
line { x1: "71", x2: "49", y1: "49", y2: "71" }
},
ErrorStateKind::Offline => rsx! {
rect { height: "35", rx: "18", width: "72", x: "24", y: "45" }
line { x1: "30", x2: "90", y1: "30", y2: "90" }
},
};
rsx! {
span { aria_hidden: "true", class,
svg { "aria-hidden": "true", fill: "none", "viewBox": "0 0 120 120",
circle { class: "ui-illustration__wash", cx: "60", cy: "60", r: "48" }
{artwork}
}
}
}
}
fn error_title(level: u8, id: Option<String>, title: String) -> Element {
match level.clamp(1, 6) {
1 => {
rsx! { h1 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
}
2 => {
rsx! { h2 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
}
3 => {
rsx! { h3 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
}
4 => {
rsx! { h4 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
}
5 => {
rsx! { h5 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
}
_ => {
rsx! { h6 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
}
}
}
#[component]
pub fn ErrorState(props: ErrorStateProps) -> Element {
let kind = props.kind.as_str();
let layout = props.layout.as_str();
let kind_class = format!("ui-error-state--{kind}");
let layout_class = format!("ui-error-state--{layout}");
let class = compose([
Some("ui-error-state"),
Some(kind_class.as_str()),
Some(layout_class.as_str()),
props.class.as_deref(),
]);
let id = props.id.filter(|value| !value.is_empty());
let title_id = id.as_ref().map(|value| format!("{value}-title"));
let (aria_live, role) = error_state_announcement(props.announce, props.aria_live, props.role);
let description = props.description.filter(|value| !value.is_empty());
let reference = props.reference.filter(|value| !value.is_empty());
let graphic = if props.hide_graphic {
None
} else {
Some(props.graphic.unwrap_or_else(|| {
error_illustration(props.kind, props.layout == ErrorStateLayout::Compact)
}))
};
let show_details = has_content(&props.children);
let title = error_title(props.heading_level, title_id.clone(), props.title.clone());
let aria_label = title_id.is_none().then(|| props.title.clone());
rsx! {
section {
aria_label,
aria_labelledby: title_id,
aria_live,
class,
"data-kind": kind,
"data-layout": layout,
"data-ui-error-state": "true",
id,
role,
..props.attributes,
if let Some(graphic) = graphic {
div {
aria_hidden: "true",
class: "ui-error-state__graphic",
"data-slot": "error-state-graphic",
{graphic}
}
}
div { class: "ui-error-state__content", "data-slot": "error-state-content",
{title}
if let Some(description) = description {
p { class: "ui-error-state__description", "data-slot": "error-state-description", {description} }
}
if show_details {
div { class: "ui-error-state__details", "data-slot": "error-state-details", {props.children} }
}
if let Some(reference) = reference {
p { class: "ui-error-state__reference", "data-slot": "error-state-reference",
span { "{props.reference_label}:" }
" "
code { {reference} }
}
}
}
if let Some(actions) = props.actions.filter(has_content) {
div { class: "ui-error-state__actions", "data-slot": "error-state-actions", {actions} }
}
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StatusDotTone {
Brand,
#[default]
Current,
Danger,
Neutral,
Success,
Warning,
}
impl StatusDotTone {
pub fn as_str(self) -> &'static str {
match self {
Self::Brand => "brand",
Self::Current => "current",
Self::Danger => "danger",
Self::Neutral => "neutral",
Self::Success => "success",
Self::Warning => "warning",
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct StatusDotProps {
#[props(into)]
pub label: Option<String>,
#[props(default)]
pub pulse: bool,
#[props(default)]
pub tone: StatusDotTone,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = span)]
pub attributes: Vec<Attribute>,
}
#[component]
pub fn StatusDot(props: StatusDotProps) -> Element {
let label = props
.label
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty());
let tone = (props.tone != StatusDotTone::Current)
.then(|| format!("ui-status-dot--{}", props.tone.as_str()));
let class = compose([
Some("ui-status-dot"),
tone.as_deref(),
props.pulse.then_some("ui-status-dot--pulse"),
props.class.as_deref(),
]);
let named = label.is_some();
rsx! {
span {
aria_hidden: (!named).then_some("true"),
aria_label: label,
class,
"data-tone": props.tone.as_str(),
role: named.then_some("img"),
..props.attributes,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SkeletonShape {
#[default]
Rectangle,
Text,
Circle,
}
impl SkeletonShape {
fn class(self) -> Option<&'static str> {
match self {
Self::Rectangle => None,
Self::Text => Some("ui-skeleton--text"),
Self::Circle => Some("ui-skeleton--circle"),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SkeletonAnimation {
#[default]
Shimmer,
Pulse,
None,
}
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub enum SkeletonSize {
#[default]
Auto,
Pixels(f64),
Css(String),
}
impl From<f64> for SkeletonSize {
fn from(value: f64) -> Self {
Self::Pixels(value)
}
}
impl From<i32> for SkeletonSize {
fn from(value: i32) -> Self {
Self::Pixels(f64::from(value))
}
}
impl From<u32> for SkeletonSize {
fn from(value: u32) -> Self {
Self::Pixels(f64::from(value))
}
}
impl From<&str> for SkeletonSize {
fn from(value: &str) -> Self {
Self::Css(value.to_string())
}
}
impl From<String> for SkeletonSize {
fn from(value: String) -> Self {
Self::Css(value)
}
}
const SKELETON_SIZE_MAX_LENGTH: usize = 64;
fn pixel_size(value: f64) -> Option<String> {
(value.is_finite() && value >= 0.0).then(|| format!("{value}px"))
}
fn is_safe_size_character(character: char) -> bool {
character.is_ascii_alphanumeric() || "%.+-*/(), _".contains(character)
}
fn is_identifier_character(character: char) -> bool {
character.is_ascii_alphanumeric() || character == '_' || character == '-'
}
fn has_css_url_call(size: &str) -> bool {
let lower: Vec<char> = size.to_lowercase().chars().collect();
let mut index = 0;
while index + 3 <= lower.len() {
let is_url = lower[index] == 'u' && lower[index + 1] == 'r' && lower[index + 2] == 'l';
let boundary = index == 0 || !is_identifier_character(lower[index - 1]);
if is_url && boundary {
let mut cursor = index + 3;
while cursor < lower.len() && lower[cursor] == ' ' {
cursor += 1;
}
if cursor < lower.len() && lower[cursor] == '(' {
return true;
}
}
index += 1;
}
false
}
fn is_safe_size_expression(size: &str) -> bool {
if size.is_empty() || size.chars().count() > SKELETON_SIZE_MAX_LENGTH {
return false;
}
if size.contains("/*") || size.contains("*/") || has_css_url_call(size) {
return false;
}
size.chars().all(is_safe_size_character)
}
impl SkeletonSize {
pub fn resolve(&self) -> Option<String> {
match self {
Self::Auto => None,
Self::Pixels(value) => pixel_size(*value),
Self::Css(value) => {
let size = value.trim();
if !is_safe_size_expression(size) {
return None;
}
match size.parse::<f64>() {
Ok(number) if number.is_finite() => pixel_size(number),
_ => Some(size.to_string()),
}
}
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct SkeletonProps {
#[props(default)]
pub shape: SkeletonShape,
#[props(default)]
pub animation: SkeletonAnimation,
#[props(default, into)]
pub width: SkeletonSize,
#[props(default, into)]
pub height: SkeletonSize,
#[props(into)]
pub aria_label: Option<String>,
#[props(into)]
pub aria_labelledby: Option<String>,
pub aria_hidden: Option<bool>,
#[props(into)]
pub role: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
}
fn has_name(value: Option<&String>) -> bool {
value.is_some_and(|text| !text.trim().is_empty())
}
#[component]
pub fn Skeleton(props: SkeletonProps) -> Element {
let named = has_name(props.aria_label.as_ref()) || has_name(props.aria_labelledby.as_ref());
let aria_hidden = match props.aria_hidden {
Some(hidden) => Some(hidden.to_string()),
None => (!named).then(|| "true".to_string()),
};
let role = props.role.or_else(|| named.then(|| "status".to_string()));
let class = compose([
Some("ui-skeleton"),
props.shape.class(),
(props.animation == SkeletonAnimation::Pulse).then_some("ui-skeleton--pulse"),
(props.animation == SkeletonAnimation::None).then_some("ui-skeleton--static"),
props.class.as_deref(),
]);
let height = props.height.resolve();
let width = props.width.resolve();
let mut declarations = Vec::new();
if let Some(height) = height {
declarations.push(format!("--ui-skeleton-height:{height}"));
}
if let Some(width) = width {
declarations.push(format!("--ui-skeleton-width:{width}"));
}
let style = (!declarations.is_empty()).then(|| declarations.join(";"));
rsx! {
div {
aria_hidden,
aria_label: props.aria_label,
aria_labelledby: props.aria_labelledby,
class,
role,
style,
..props.attributes,
}
}
}
#[cfg(test)]
mod tests {
use super::{ErrorStateAnnounce, SkeletonSize, error_state_announcement};
#[test]
fn skeleton_sizes_follow_lumen_core() {
assert_eq!(SkeletonSize::from(48).resolve().as_deref(), Some("48px"));
assert_eq!(SkeletonSize::from(4.5).resolve().as_deref(), Some("4.5px"));
assert_eq!(SkeletonSize::from(-1).resolve(), None);
assert_eq!(SkeletonSize::from(f64::NAN).resolve(), None);
assert_eq!(SkeletonSize::from("60%").resolve().as_deref(), Some("60%"));
assert_eq!(
SkeletonSize::from(" 12 ").resolve().as_deref(),
Some("12px")
);
assert_eq!(
SkeletonSize::from("calc(100% - 2rem)").resolve().as_deref(),
Some("calc(100% - 2rem)")
);
assert_eq!(
SkeletonSize::from("var(--gap)").resolve().as_deref(),
Some("var(--gap)")
);
assert_eq!(SkeletonSize::from("").resolve(), None);
assert_eq!(SkeletonSize::from("1rem; color: red").resolve(), None);
assert_eq!(SkeletonSize::from("url(x)").resolve(), None);
assert_eq!(SkeletonSize::from("URL (x)").resolve(), None);
assert_eq!(SkeletonSize::from("1rem /* x */").resolve(), None);
assert_eq!(
SkeletonSize::from("curl(1)").resolve().as_deref(),
Some("curl(1)")
);
assert_eq!(SkeletonSize::Auto.resolve(), None);
}
#[test]
fn skeleton_sizes_reject_long_input_quickly() {
let long = "1".repeat(100_000);
assert_eq!(SkeletonSize::Css(long).resolve(), None);
let urls = "url ".repeat(16);
assert_eq!(
SkeletonSize::Css(urls).resolve().as_deref(),
Some("url url url url url url url url url url url url url url url url")
);
}
#[test]
fn error_state_announcements_keep_overrides() {
assert_eq!(
error_state_announcement(ErrorStateAnnounce::Assertive, None, None),
(Some("assertive".into()), Some("alert".into()))
);
assert_eq!(
error_state_announcement(ErrorStateAnnounce::Polite, Some("off".into()), None),
(Some("off".into()), Some("status".into()))
);
assert_eq!(
error_state_announcement(ErrorStateAnnounce::Off, None, None),
(None, None)
);
}
}