use crate::components::capsule::capsule_padded;
use crate::core::{Color, Element};
#[derive(Debug, Clone)]
pub struct Tag {
text: String,
color: Color,
background: Color,
closable: bool,
icon: Option<String>,
}
impl Tag {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
color: Color::White,
background: Color::Ansi256(240),
closable: false,
icon: None,
}
}
pub fn color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn background(mut self, color: Color) -> Self {
self.background = color;
self
}
pub fn closable(mut self) -> Self {
self.closable = true;
self
}
pub fn icon(mut self, icon: impl Into<String>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn into_element(self) -> Element {
let mut content = String::new();
if let Some(icon) = &self.icon {
content.push_str(icon);
content.push(' ');
}
content.push_str(&self.text);
if self.closable {
content.push_str(" ×");
}
capsule_padded(content, self.color, self.background).into_element()
}
}
impl Default for Tag {
fn default() -> Self {
Self::new("")
}
}
pub fn tag(text: impl Into<String>) -> Element {
Tag::new(text).into_element()
}
pub fn tag_colored(text: impl Into<String>, color: Color) -> Element {
Tag::new(text).color(color).into_element()
}
impl Tag {
pub fn blue(text: impl Into<String>) -> Self {
Self::new(text).color(Color::White).background(Color::Blue)
}
pub fn green(text: impl Into<String>) -> Self {
Self::new(text).color(Color::White).background(Color::Green)
}
pub fn red(text: impl Into<String>) -> Self {
Self::new(text).color(Color::White).background(Color::Red)
}
pub fn yellow(text: impl Into<String>) -> Self {
Self::new(text)
.color(Color::Black)
.background(Color::Yellow)
}
pub fn cyan(text: impl Into<String>) -> Self {
Self::new(text).color(Color::White).background(Color::Cyan)
}
pub fn magenta(text: impl Into<String>) -> Self {
Self::new(text)
.color(Color::White)
.background(Color::Magenta)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tag_creation() {
let t = Tag::new("test");
assert_eq!(t.text, "test");
}
#[test]
fn test_tag_closable() {
let t = Tag::new("test").closable();
assert!(t.closable);
}
#[test]
fn test_tag_with_icon() {
let t = Tag::new("rust").icon("🦀");
assert_eq!(t.icon, Some("🦀".to_string()));
}
#[test]
fn test_tag_into_element() {
let _ = Tag::new("test").into_element();
let _ = Tag::new("test").closable().into_element();
let _ = Tag::new("test").icon("*").into_element();
}
#[test]
fn test_tag_presets() {
let _ = Tag::blue("blue").into_element();
let _ = Tag::green("green").into_element();
let _ = Tag::red("red").into_element();
}
#[test]
fn test_tag_helpers() {
let _ = tag("simple");
let _ = tag_colored("colored", Color::Cyan);
}
}