use alloc::string::String;
use core::fmt::Display;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Navigation {
url: String,
new_tab: bool,
anchor: bool,
tooltip: Option<String>,
}
impl Navigation {
pub fn new(url: impl Into<String>) -> Self {
Self { url: url.into(), new_tab: false, anchor: false, tooltip: None }
}
pub fn new_tab(mut self, new_tab: bool) -> Self {
self.new_tab = new_tab;
self
}
pub fn anchor(mut self, anchor: bool) -> Self {
self.anchor = anchor;
self
}
pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
self.tooltip = Some(tooltip.into());
self
}
}
impl Display for Navigation {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if self.anchor {
write!(f, "href")?;
}
write!(f, " \"{}\"", self.url)?;
if let Some(tooltip) = &self.tooltip {
write!(f, " \"{tooltip}\"")?;
}
if self.new_tab {
write!(f, " _blank")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use alloc::{format, string::ToString};
use super::*;
#[test]
fn test_navigation_display() {
let nav = Navigation {
url: "https://example.com".to_string(),
new_tab: false,
anchor: false,
tooltip: None,
};
assert_eq!(format!("{nav}"), " \"https://example.com\"");
let nav = Navigation {
url: "https://example.com".to_string(),
new_tab: true,
anchor: false,
tooltip: None,
};
assert_eq!(format!("{nav}"), " \"https://example.com\" _blank");
let nav = Navigation {
url: "https://example.com".to_string(),
new_tab: false,
anchor: true,
tooltip: None,
};
assert_eq!(format!("{nav}"), "href \"https://example.com\"");
let nav = Navigation {
url: "https://example.com".to_string(),
new_tab: true,
anchor: true,
tooltip: Some("Tooltip".to_string()),
};
assert_eq!(format!("{nav}"), "href \"https://example.com\" \"Tooltip\" _blank");
}
}