titanium_model/ui.rs
1//! UI Utilities for creating rich embeds and messages.
2
3/// A text-based progress bar generator.
4#[derive(Debug, Clone)]
5pub struct ProgressBar {
6 /// Total number of steps.
7 pub length: u32,
8 /// Character for the filled portion.
9 pub filled_char: char,
10 /// Character for the empty portion.
11 pub empty_char: char,
12 /// Character for the current position (head).
13 pub head_char: Option<char>,
14 /// Opening bracket/character.
15 pub start_char: Option<String>,
16 /// Closing bracket/character.
17 pub end_char: Option<String>,
18}
19
20impl Default for ProgressBar {
21 fn default() -> Self {
22 Self {
23 length: 10,
24 filled_char: '▬',
25 empty_char: '▬',
26 head_char: Some('🔘'),
27 start_char: None,
28 end_char: None,
29 }
30 }
31}
32
33impl ProgressBar {
34 /// Create a new default progress bar with specified length.
35 pub fn new(length: u32) -> Self {
36 Self {
37 length,
38 ..Default::default()
39 }
40 }
41
42 /// Create a new "Pac-Man" style progress bar (Arch Linux style).
43 /// e.g. [------C o o o]
44 pub fn pacman(length: u32) -> Self {
45 Self {
46 length,
47 filled_char: '-', // Eaten path
48 empty_char: 'o', // Pellets
49 head_char: Some('C'), // Pac-Man
50 start_char: Some("[".to_string()),
51 end_char: Some("]".to_string()),
52 }
53 }
54
55 /// Generate the progress bar string.
56 ///
57 /// # Arguments
58 /// * `percent` - A value between 0.0 and 1.0.
59 #[inline]
60 pub fn create(&self, percent: f32) -> String {
61 let percent = percent.clamp(0.0, 1.0);
62 let filled_count = (self.length as f32 * percent).round() as u32;
63 let filled_count = filled_count.min(self.length); // clamp to max length
64
65 // Calculate exact capacity to avoid re-allocation
66 // Base length + overhead for start/end/head chars (approximate but sufficient)
67 let capacity = (self.length as usize * 4) + 16;
68 let mut result = String::with_capacity(capacity);
69
70 if let Some(s) = &self.start_char {
71 result.push_str(s);
72 }
73
74 for i in 0..self.length {
75 if let Some(head) = self.head_char {
76 if i == filled_count {
77 result.push(head);
78 continue;
79 }
80 // If we are at the very end and filled_count == length, we might want to show head?
81 // Current logic: head replaces the character AT the split point.
82 // If split == length (100%), i never equals split in 0..length loop?
83 // Wait, if 100%, filled_count=10. i goes 0..9. i never equals 10.
84 // So head is not shown at 100%? That seems wrong if head is a 'thumb'.
85 // But for a progress bar, usually full = all filled.
86 }
87
88 if i < filled_count {
89 result.push(self.filled_char);
90 } else {
91 result.push(self.empty_char);
92 }
93 }
94
95 // Handle 100% case if head should be visible at the very end?
96 // Or if we strictly follow "head is the current step".
97 // If 100%, there is no "next step", so full bar is appropriate.
98
99 if let Some(e) = &self.end_char {
100 result.push_str(e);
101 }
102
103 result
104 }
105}
106
107/// Discord Timestamp formatting styles.
108#[derive(Debug, Clone, Copy, PartialEq)]
109pub enum TimestampStyle {
110 /// Short Time (e.g. 16:20)
111 ShortTime, // t
112 /// Long Time (e.g. 16:20:30)
113 LongTime, // T
114 /// Short Date (e.g. 20/04/2021)
115 ShortDate, // d
116 /// Long Date (e.g. 20 April 2021)
117 LongDate, // D
118 /// Short Date/Time (e.g. 20 April 2021 16:20)
119 ShortDateTime, // f (default)
120 /// Long Date/Time (e.g. Tuesday, 20 April 2021 16:20)
121 LongDateTime, // F
122 /// Relative Time (e.g. 2 months ago)
123 Relative, // R
124}
125
126impl TimestampStyle {
127 pub fn as_char(&self) -> char {
128 match self {
129 Self::ShortTime => 't',
130 Self::LongTime => 'T',
131 Self::ShortDate => 'd',
132 Self::LongDate => 'D',
133 Self::ShortDateTime => 'f',
134 Self::LongDateTime => 'F',
135 Self::Relative => 'R',
136 }
137 }
138}
139
140/// Helper for generating Discord timestamp strings.
141pub struct Timestamp;
142
143impl Timestamp {
144 /// Create a Discord timestamp tag from unix seconds.
145 pub fn from_unix(seconds: i64, style: TimestampStyle) -> String {
146 format!("<t:{}:{}>", seconds, style.as_char())
147 }
148
149 /// Create a Discord timestamp tag from time remaining (now + duration).
150 /// Useful for "Ends in..."
151 pub fn expires_in(duration_secs: u64) -> String {
152 use std::time::{SystemTime, UNIX_EPOCH};
153 let start = SystemTime::now();
154 let since_the_epoch = start
155 .duration_since(UNIX_EPOCH)
156 .expect("Time went backwards")
157 .as_secs();
158 let target = since_the_epoch + duration_secs;
159 format!("<t:{}:R>", target)
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166
167 #[test]
168 fn test_progress_bar() {
169 let bar = ProgressBar::new(10);
170 // 50% -> 5 filled
171 // 0 1 2 3 4 [5] 6 7 8 9
172 // ▬ ▬ ▬ ▬ ▬ 🔘 ▬ ▬ ▬ ▬
173 let output = bar.create(0.5);
174 assert!(output.contains('🔘'));
175 assert_eq!(output.chars().count(), 10);
176 }
177
178 #[test]
179 fn test_pacman_bar() {
180 let bar = ProgressBar::pacman(10);
181 // 50%
182 // [-----C o o o o]
183 let output = bar.create(0.5);
184 assert!(output.contains("C"));
185 assert!(output.contains("-"));
186 assert!(output.contains("o"));
187 assert!(output.starts_with('['));
188 assert!(output.ends_with(']'));
189 }
190
191 #[test]
192 fn test_timestamp() {
193 let ts = Timestamp::from_unix(1234567890, TimestampStyle::Relative);
194 assert_eq!(ts, "<t:1234567890:R>");
195 }
196}