Add function to display error as alert

Move random modal id generation to function
This commit is contained in:
2026-06-29 20:58:03 -04:00
parent f84e51d13a
commit 2cbc6aeaff

View File

@@ -45,6 +45,20 @@ impl fmt::Display for ErrorLocation {
pub type Result<T, E = Error> = std::result::Result<T, E>; pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Generate a random string to use as an id for the modal
/// This allows multiple toast/modal to be present
fn rand_modal_id() -> String {
use rand::RngExt;
let mut rng = rand::rng();
let random_str = (0..5)
.map(|_| rng.sample(rand::distr::Alphanumeric) as char)
.collect::<String>();
format!("err-modal-{random_str}")
}
#[derive(Debug, Clone, Deserialize, Serialize, thiserror::Error)] #[derive(Debug, Clone, Deserialize, Serialize, thiserror::Error)]
pub struct Error { pub struct Error {
#[source] #[source]
@@ -173,28 +187,9 @@ impl Error {
} }
} }
/// Convert this error to a toast message, which opens a modal when clicked /// Convert this error into an alert label, tied to the given modal id
pub fn as_toast(&self) -> Element { fn as_alert_for(&self, modal_id: String) -> Element {
// Generate a random string to use as an id for the modal
// This allows multiple toast/modal to be present
let modal_id = {
use rand::RngExt;
let mut rng = rand::rng();
let random_str = (0..5)
.map(|_| rng.sample(rand::distr::Alphanumeric) as char)
.collect::<String>();
format!("err-modal-{random_str}")
};
rsx! { rsx! {
{self.as_modal(modal_id.clone())}
div {
class: "toast z-99",
label { label {
class: "alert alert-error alert-soft cursor-pointer", class: "alert alert-error alert-soft cursor-pointer",
role: "alert", role: "alert",
@@ -208,6 +203,29 @@ impl Error {
} }
} }
} }
/// Convert this error to a toast message, which opens a modal when clicked
pub fn as_toast(&self) -> Element {
let modal_id = rand_modal_id();
rsx! {
{self.as_modal(modal_id.clone())}
div {
class: "toast z-99",
{self.as_alert_for(modal_id)}
}
}
}
/// Convert this error into an alert label, which opens a modal when clicked
pub fn as_alert(&self) -> Element {
let modal_id = rand_modal_id();
rsx! {
{self.as_modal(modal_id.clone())}
{self.as_alert_for(modal_id)}
}
} }
} }