demand/
option.rs

1use std::fmt::Display;
2use std::sync::atomic::AtomicUsize;
3
4/// An individual option in a select or multi-select.
5#[derive(Debug, Clone)]
6pub struct DemandOption<T> {
7    /// Unique ID for this option.
8    pub(crate) id: usize,
9    /// The item this option represents.
10    pub item: T,
11    /// Display label for this option.
12    pub label: String,
13    /// Whether this option is initially selected.
14    pub selected: bool,
15    /// Optional description shown on the side.
16    pub description: Option<String>,
17}
18
19impl<T: ToString> DemandOption<T> {
20    /// Create a new option with the item as the label
21    pub fn new(item: T) -> Self {
22        static ID: AtomicUsize = AtomicUsize::new(0);
23        Self {
24            id: ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
25            label: item.to_string(),
26            item,
27            selected: false,
28            description: None,
29        }
30    }
31}
32
33impl<T> DemandOption<T> {
34    /// Create a new option with a label and item
35    pub fn with_label<S: Into<String>>(label: S, item: T) -> Self {
36        static ID: AtomicUsize = AtomicUsize::new(0);
37        Self {
38            id: ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
39            label: label.into(),
40            item,
41            selected: false,
42            description: None,
43        }
44    }
45    pub fn item<I>(self, item: I) -> DemandOption<I> {
46        DemandOption {
47            id: self.id,
48            item,
49            label: self.label,
50            selected: self.selected,
51            description: None,
52        }
53    }
54    /// Set the display label for this option.
55    pub fn label(mut self, name: &str) -> Self {
56        self.label = name.to_string();
57        self
58    }
59
60    /// Set whether this option is initially selected.
61    pub fn selected(mut self, selected: bool) -> Self {
62        self.selected = selected;
63        self
64    }
65
66    pub fn description(mut self, description: &str) -> Self {
67        self.description = Some(description.to_string());
68        self
69    }
70}
71
72impl<T: Display> PartialEq for DemandOption<T> {
73    fn eq(&self, other: &Self) -> bool {
74        self.id == other.id
75    }
76}
77
78impl<T: Display> Eq for DemandOption<T> {}