1use dioxus::prelude::*;
4
5use super::shared::has_content;
6use crate::class::{Glass, compose};
7
8#[derive(Props, Clone, PartialEq)]
10pub struct CalloutProps {
11 #[props(into)]
13 pub class: Option<String>,
14 #[props(extends = GlobalAttributes, extends = aside)]
16 pub attributes: Vec<Attribute>,
17 pub children: Element,
19}
20
21#[component]
23pub fn Callout(props: CalloutProps) -> Element {
24 let class = compose([Some("ui-callout"), props.class.as_deref()]);
25
26 rsx! {
27 aside { class, ..props.attributes, {props.children} }
28 }
29}
30
31#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum EmptyVariant {
35 #[default]
37 Default,
38 Compact,
40}
41
42impl EmptyVariant {
43 pub fn as_str(self) -> &'static str {
45 match self {
46 Self::Default => "default",
47 Self::Compact => "compact",
48 }
49 }
50}
51
52#[derive(Props, Clone, PartialEq)]
54pub struct EmptyProps {
55 #[props(default)]
57 pub variant: EmptyVariant,
58 #[props(default, into)]
60 pub glass: Glass,
61 #[props(into)]
63 pub class: Option<String>,
64 #[props(extends = GlobalAttributes, extends = section)]
66 pub attributes: Vec<Attribute>,
67 pub children: Element,
69}
70
71#[component]
73pub fn Empty(props: EmptyProps) -> Element {
74 let glass = props.glass.class("ui-empty");
75 let class = compose([
76 Some("ui-empty"),
77 (props.variant == EmptyVariant::Compact).then_some("ui-empty--compact"),
78 glass.as_deref(),
79 props.class.as_deref(),
80 ]);
81
82 rsx! {
83 section {
84 class,
85 "data-variant": props.variant.as_str(),
86 ..props.attributes,
87 {props.children}
88 }
89 }
90}
91
92#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
94#[non_exhaustive]
95pub enum ErrorStateKind {
96 #[default]
98 Error,
99 Offline,
101}
102
103impl ErrorStateKind {
104 pub fn as_str(self) -> &'static str {
106 match self {
107 Self::Error => "error",
108 Self::Offline => "offline",
109 }
110 }
111}
112
113#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
115#[non_exhaustive]
116pub enum ErrorStateLayout {
117 Compact,
119 #[default]
121 Default,
122 Page,
124}
125
126impl ErrorStateLayout {
127 pub fn as_str(self) -> &'static str {
129 match self {
130 Self::Compact => "compact",
131 Self::Default => "default",
132 Self::Page => "page",
133 }
134 }
135}
136
137#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
139#[non_exhaustive]
140pub enum ErrorStateAnnounce {
141 #[default]
143 Off,
144 Polite,
146 Assertive,
148}
149
150#[derive(Props, Clone, PartialEq)]
152pub struct ErrorStateProps {
153 #[props(into)]
155 pub title: String,
156 #[props(into)]
158 pub description: Option<String>,
159 #[props(default)]
161 pub kind: ErrorStateKind,
162 #[props(default)]
164 pub layout: ErrorStateLayout,
165 #[props(default)]
167 pub announce: ErrorStateAnnounce,
168 #[props(default = 2)]
170 pub heading_level: u8,
171 #[props(into)]
173 pub id: Option<String>,
174 #[props(into)]
176 pub reference: Option<String>,
177 #[props(default = "Reference".to_string(), into)]
179 pub reference_label: String,
180 pub actions: Option<Element>,
182 pub graphic: Option<Element>,
184 #[props(default)]
186 pub hide_graphic: bool,
187 #[props(into)]
189 pub aria_live: Option<String>,
190 #[props(into)]
192 pub role: Option<String>,
193 #[props(into)]
195 pub class: Option<String>,
196 #[props(extends = GlobalAttributes, extends = section)]
198 pub attributes: Vec<Attribute>,
199 pub children: Element,
201}
202
203fn error_state_announcement(
204 announce: ErrorStateAnnounce,
205 aria_live: Option<String>,
206 role: Option<String>,
207) -> (Option<String>, Option<String>) {
208 match announce {
209 ErrorStateAnnounce::Assertive => (
210 Some(aria_live.unwrap_or_else(|| "assertive".to_string())),
211 Some(role.unwrap_or_else(|| "alert".to_string())),
212 ),
213 ErrorStateAnnounce::Polite => (
214 Some(aria_live.unwrap_or_else(|| "polite".to_string())),
215 Some(role.unwrap_or_else(|| "status".to_string())),
216 ),
217 ErrorStateAnnounce::Off => (aria_live, role),
218 }
219}
220
221fn error_illustration(kind: ErrorStateKind, small: bool) -> Element {
223 let class = format!(
224 "ui-illustration ui-illustration--{} ui-illustration--auto ui-illustration--{}",
225 kind.as_str(),
226 if small { "sm" } else { "md" }
227 );
228
229 let artwork = match kind {
230 ErrorStateKind::Error => rsx! {
231 circle { cx: "60", cy: "60", r: "28" }
232 line { x1: "49", x2: "71", y1: "49", y2: "71" }
233 line { x1: "71", x2: "49", y1: "49", y2: "71" }
234 },
235 ErrorStateKind::Offline => rsx! {
236 rect { height: "35", rx: "18", width: "72", x: "24", y: "45" }
237 line { x1: "30", x2: "90", y1: "30", y2: "90" }
238 },
239 };
240
241 rsx! {
242 span { aria_hidden: "true", class,
243 svg { "aria-hidden": "true", fill: "none", "viewBox": "0 0 120 120",
244 circle { class: "ui-illustration__wash", cx: "60", cy: "60", r: "48" }
245 {artwork}
246 }
247 }
248 }
249}
250
251fn error_title(level: u8, id: Option<String>, title: String) -> Element {
252 match level.clamp(1, 6) {
253 1 => {
254 rsx! { h1 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
255 }
256 2 => {
257 rsx! { h2 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
258 }
259 3 => {
260 rsx! { h3 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
261 }
262 4 => {
263 rsx! { h4 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
264 }
265 5 => {
266 rsx! { h5 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
267 }
268 _ => {
269 rsx! { h6 { class: "ui-error-state__title", "data-slot": "error-state-title", id, {title} } }
270 }
271 }
272}
273
274#[component]
277pub fn ErrorState(props: ErrorStateProps) -> Element {
278 let kind = props.kind.as_str();
279 let layout = props.layout.as_str();
280 let kind_class = format!("ui-error-state--{kind}");
281 let layout_class = format!("ui-error-state--{layout}");
282 let class = compose([
283 Some("ui-error-state"),
284 Some(kind_class.as_str()),
285 Some(layout_class.as_str()),
286 props.class.as_deref(),
287 ]);
288 let id = props.id.filter(|value| !value.is_empty());
289 let title_id = id.as_ref().map(|value| format!("{value}-title"));
290 let (aria_live, role) = error_state_announcement(props.announce, props.aria_live, props.role);
291 let description = props.description.filter(|value| !value.is_empty());
292 let reference = props.reference.filter(|value| !value.is_empty());
293 let graphic = if props.hide_graphic {
294 None
295 } else {
296 Some(props.graphic.unwrap_or_else(|| {
297 error_illustration(props.kind, props.layout == ErrorStateLayout::Compact)
298 }))
299 };
300 let show_details = has_content(&props.children);
301 let title = error_title(props.heading_level, title_id.clone(), props.title.clone());
302 let aria_label = title_id.is_none().then(|| props.title.clone());
303
304 rsx! {
305 section {
306 aria_label,
307 aria_labelledby: title_id,
308 aria_live,
309 class,
310 "data-kind": kind,
311 "data-layout": layout,
312 "data-ui-error-state": "true",
313 id,
314 role,
315 ..props.attributes,
316 if let Some(graphic) = graphic {
317 div {
318 aria_hidden: "true",
319 class: "ui-error-state__graphic",
320 "data-slot": "error-state-graphic",
321 {graphic}
322 }
323 }
324 div { class: "ui-error-state__content", "data-slot": "error-state-content",
325 {title}
326 if let Some(description) = description {
327 p { class: "ui-error-state__description", "data-slot": "error-state-description", {description} }
328 }
329 if show_details {
330 div { class: "ui-error-state__details", "data-slot": "error-state-details", {props.children} }
331 }
332 if let Some(reference) = reference {
333 p { class: "ui-error-state__reference", "data-slot": "error-state-reference",
334 span { "{props.reference_label}:" }
335 " "
336 code { {reference} }
337 }
338 }
339 }
340 if let Some(actions) = props.actions.filter(has_content) {
341 div { class: "ui-error-state__actions", "data-slot": "error-state-actions", {actions} }
342 }
343 }
344 }
345}
346
347#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
349#[non_exhaustive]
350pub enum StatusDotTone {
351 Brand,
353 #[default]
355 Current,
356 Danger,
358 Neutral,
360 Success,
362 Warning,
364}
365
366impl StatusDotTone {
367 pub fn as_str(self) -> &'static str {
369 match self {
370 Self::Brand => "brand",
371 Self::Current => "current",
372 Self::Danger => "danger",
373 Self::Neutral => "neutral",
374 Self::Success => "success",
375 Self::Warning => "warning",
376 }
377 }
378}
379
380#[derive(Props, Clone, PartialEq)]
382pub struct StatusDotProps {
383 #[props(into)]
385 pub label: Option<String>,
386 #[props(default)]
388 pub pulse: bool,
389 #[props(default)]
391 pub tone: StatusDotTone,
392 #[props(into)]
394 pub class: Option<String>,
395 #[props(extends = GlobalAttributes, extends = span)]
397 pub attributes: Vec<Attribute>,
398}
399
400#[component]
402pub fn StatusDot(props: StatusDotProps) -> Element {
403 let label = props
404 .label
405 .map(|value| value.trim().to_string())
406 .filter(|value| !value.is_empty());
407 let tone = (props.tone != StatusDotTone::Current)
408 .then(|| format!("ui-status-dot--{}", props.tone.as_str()));
409 let class = compose([
410 Some("ui-status-dot"),
411 tone.as_deref(),
412 props.pulse.then_some("ui-status-dot--pulse"),
413 props.class.as_deref(),
414 ]);
415 let named = label.is_some();
416
417 rsx! {
418 span {
419 aria_hidden: (!named).then_some("true"),
420 aria_label: label,
421 class,
422 "data-tone": props.tone.as_str(),
423 role: named.then_some("img"),
424 ..props.attributes,
425 }
426 }
427}
428
429#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
431#[non_exhaustive]
432pub enum SkeletonShape {
433 #[default]
435 Rectangle,
436 Text,
438 Circle,
440}
441
442impl SkeletonShape {
443 fn class(self) -> Option<&'static str> {
444 match self {
445 Self::Rectangle => None,
446 Self::Text => Some("ui-skeleton--text"),
447 Self::Circle => Some("ui-skeleton--circle"),
448 }
449 }
450}
451
452#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
454#[non_exhaustive]
455pub enum SkeletonAnimation {
456 #[default]
458 Shimmer,
459 Pulse,
461 None,
463}
464
465#[derive(Clone, Debug, Default, PartialEq)]
469#[non_exhaustive]
470pub enum SkeletonSize {
471 #[default]
473 Auto,
474 Pixels(f64),
476 Css(String),
478}
479
480impl From<f64> for SkeletonSize {
481 fn from(value: f64) -> Self {
482 Self::Pixels(value)
483 }
484}
485
486impl From<i32> for SkeletonSize {
487 fn from(value: i32) -> Self {
488 Self::Pixels(f64::from(value))
489 }
490}
491
492impl From<u32> for SkeletonSize {
493 fn from(value: u32) -> Self {
494 Self::Pixels(f64::from(value))
495 }
496}
497
498impl From<&str> for SkeletonSize {
499 fn from(value: &str) -> Self {
500 Self::Css(value.to_string())
501 }
502}
503
504impl From<String> for SkeletonSize {
505 fn from(value: String) -> Self {
506 Self::Css(value)
507 }
508}
509
510const SKELETON_SIZE_MAX_LENGTH: usize = 64;
511
512fn pixel_size(value: f64) -> Option<String> {
513 (value.is_finite() && value >= 0.0).then(|| format!("{value}px"))
514}
515
516fn is_safe_size_character(character: char) -> bool {
517 character.is_ascii_alphanumeric() || "%.+-*/(), _".contains(character)
518}
519
520fn is_identifier_character(character: char) -> bool {
521 character.is_ascii_alphanumeric() || character == '_' || character == '-'
522}
523
524fn has_css_url_call(size: &str) -> bool {
526 let lower: Vec<char> = size.to_lowercase().chars().collect();
527 let mut index = 0;
528
529 while index + 3 <= lower.len() {
530 let is_url = lower[index] == 'u' && lower[index + 1] == 'r' && lower[index + 2] == 'l';
531 let boundary = index == 0 || !is_identifier_character(lower[index - 1]);
532
533 if is_url && boundary {
534 let mut cursor = index + 3;
535
536 while cursor < lower.len() && lower[cursor] == ' ' {
537 cursor += 1;
538 }
539
540 if cursor < lower.len() && lower[cursor] == '(' {
541 return true;
542 }
543 }
544
545 index += 1;
546 }
547
548 false
549}
550
551fn is_safe_size_expression(size: &str) -> bool {
552 if size.is_empty() || size.chars().count() > SKELETON_SIZE_MAX_LENGTH {
553 return false;
554 }
555
556 if size.contains("/*") || size.contains("*/") || has_css_url_call(size) {
557 return false;
558 }
559
560 size.chars().all(is_safe_size_character)
561}
562
563impl SkeletonSize {
564 pub fn resolve(&self) -> Option<String> {
569 match self {
570 Self::Auto => None,
571 Self::Pixels(value) => pixel_size(*value),
572 Self::Css(value) => {
573 let size = value.trim();
574
575 if !is_safe_size_expression(size) {
576 return None;
577 }
578
579 match size.parse::<f64>() {
580 Ok(number) if number.is_finite() => pixel_size(number),
581 _ => Some(size.to_string()),
582 }
583 }
584 }
585 }
586}
587
588#[derive(Props, Clone, PartialEq)]
590pub struct SkeletonProps {
591 #[props(default)]
593 pub shape: SkeletonShape,
594 #[props(default)]
596 pub animation: SkeletonAnimation,
597 #[props(default, into)]
599 pub width: SkeletonSize,
600 #[props(default, into)]
602 pub height: SkeletonSize,
603 #[props(into)]
605 pub aria_label: Option<String>,
606 #[props(into)]
608 pub aria_labelledby: Option<String>,
609 pub aria_hidden: Option<bool>,
611 #[props(into)]
613 pub role: Option<String>,
614 #[props(into)]
616 pub class: Option<String>,
617 #[props(extends = GlobalAttributes, extends = div)]
619 pub attributes: Vec<Attribute>,
620}
621
622fn has_name(value: Option<&String>) -> bool {
623 value.is_some_and(|text| !text.trim().is_empty())
624}
625
626#[component]
628pub fn Skeleton(props: SkeletonProps) -> Element {
629 let named = has_name(props.aria_label.as_ref()) || has_name(props.aria_labelledby.as_ref());
630 let aria_hidden = match props.aria_hidden {
631 Some(hidden) => Some(hidden.to_string()),
632 None => (!named).then(|| "true".to_string()),
633 };
634 let role = props.role.or_else(|| named.then(|| "status".to_string()));
635 let class = compose([
636 Some("ui-skeleton"),
637 props.shape.class(),
638 (props.animation == SkeletonAnimation::Pulse).then_some("ui-skeleton--pulse"),
639 (props.animation == SkeletonAnimation::None).then_some("ui-skeleton--static"),
640 props.class.as_deref(),
641 ]);
642 let height = props.height.resolve();
643 let width = props.width.resolve();
644 let mut declarations = Vec::new();
645
646 if let Some(height) = height {
647 declarations.push(format!("--ui-skeleton-height:{height}"));
648 }
649
650 if let Some(width) = width {
651 declarations.push(format!("--ui-skeleton-width:{width}"));
652 }
653
654 let style = (!declarations.is_empty()).then(|| declarations.join(";"));
655
656 rsx! {
657 div {
658 aria_hidden,
659 aria_label: props.aria_label,
660 aria_labelledby: props.aria_labelledby,
661 class,
662 role,
663 style,
664 ..props.attributes,
665 }
666 }
667}
668
669#[cfg(test)]
670mod tests {
671 use super::{ErrorStateAnnounce, SkeletonSize, error_state_announcement};
672
673 #[test]
674 fn skeleton_sizes_follow_lumen_core() {
675 assert_eq!(SkeletonSize::from(48).resolve().as_deref(), Some("48px"));
676 assert_eq!(SkeletonSize::from(4.5).resolve().as_deref(), Some("4.5px"));
677 assert_eq!(SkeletonSize::from(-1).resolve(), None);
678 assert_eq!(SkeletonSize::from(f64::NAN).resolve(), None);
679 assert_eq!(SkeletonSize::from("60%").resolve().as_deref(), Some("60%"));
680 assert_eq!(
681 SkeletonSize::from(" 12 ").resolve().as_deref(),
682 Some("12px")
683 );
684 assert_eq!(
685 SkeletonSize::from("calc(100% - 2rem)").resolve().as_deref(),
686 Some("calc(100% - 2rem)")
687 );
688 assert_eq!(
689 SkeletonSize::from("var(--gap)").resolve().as_deref(),
690 Some("var(--gap)")
691 );
692 assert_eq!(SkeletonSize::from("").resolve(), None);
693 assert_eq!(SkeletonSize::from("1rem; color: red").resolve(), None);
694 assert_eq!(SkeletonSize::from("url(x)").resolve(), None);
695 assert_eq!(SkeletonSize::from("URL (x)").resolve(), None);
696 assert_eq!(SkeletonSize::from("1rem /* x */").resolve(), None);
697 assert_eq!(
698 SkeletonSize::from("curl(1)").resolve().as_deref(),
699 Some("curl(1)")
700 );
701 assert_eq!(SkeletonSize::Auto.resolve(), None);
702 }
703
704 #[test]
705 fn skeleton_sizes_reject_long_input_quickly() {
706 let long = "1".repeat(100_000);
707 assert_eq!(SkeletonSize::Css(long).resolve(), None);
708 let urls = "url ".repeat(16);
709 assert_eq!(
710 SkeletonSize::Css(urls).resolve().as_deref(),
711 Some("url url url url url url url url url url url url url url url url")
712 );
713 }
714
715 #[test]
716 fn error_state_announcements_keep_overrides() {
717 assert_eq!(
718 error_state_announcement(ErrorStateAnnounce::Assertive, None, None),
719 (Some("assertive".into()), Some("alert".into()))
720 );
721 assert_eq!(
722 error_state_announcement(ErrorStateAnnounce::Polite, Some("off".into()), None),
723 (Some("off".into()), Some("status".into()))
724 );
725 assert_eq!(
726 error_state_announcement(ErrorStateAnnounce::Off, None, None),
727 (None, None)
728 );
729 }
730}