Skip to main content

dioxus_element_plug/components/
common.rs

1//! Common utilities for component reuse
2//!
3//! Provides shared traits and builders to reduce boilerplate across components.
4
5use dioxus::prelude::*;
6
7/// Builder for constructing CSS class strings with conditional classes.
8///
9/// Eliminates the repetitive `vec![]` → `push` → `join(" ")` pattern.
10#[derive(Debug, Clone)]
11pub struct ClassBuilder {
12    classes: Vec<String>,
13}
14
15impl ClassBuilder {
16    /// Create a new builder with a base class.
17    pub fn new(base: &str) -> Self {
18        Self {
19            classes: vec![base.to_string()],
20        }
21    }
22
23    /// Add a class unconditionally.
24    pub fn add_class(mut self, class: &str) -> Self {
25        if !class.is_empty() {
26            self.classes.push(class.to_string());
27        }
28        self
29    }
30
31    /// Add a class only if `condition` is true.
32    pub fn add_if(mut self, class: &str, condition: bool) -> Self {
33        if condition {
34            self.classes.push(class.to_string());
35        }
36        self
37    }
38
39    /// Add a class from an `Option<String>`.
40    pub fn add_opt(mut self, class: Option<&String>) -> Self {
41        if let Some(c) = class {
42            self.classes.push(c.clone());
43        }
44        self
45    }
46
47    /// Add a class from an `Option<&str>`.
48    pub fn add_opt_str(mut self, class: Option<&str>) -> Self {
49        if let Some(c) = class {
50            self.classes.push(c.to_string());
51        }
52        self
53    }
54
55    /// Build the final class string.
56    pub fn build(self) -> String {
57        self.classes.join(" ")
58    }
59}
60
61/// Extract the style string from an `Option<String>`.
62///
63/// Returns empty string if `None`.
64#[inline]
65pub fn style_str(style: &Option<String>) -> String {
66    style.clone().unwrap_or_default()
67}
68
69/// Call an optional event handler with the given event.
70#[inline]
71pub fn fire_event<E: 'static>(handler: &Option<EventHandler<E>>, event: E) {
72    if let Some(h) = handler {
73        h.call(event);
74    }
75}