feat(colors): add colorize_label and colorize_value helpers

Swadhin Biswas committed 7 months ago
4e91418
1 parent 2d5bd2d
commit 4e91418
1 file changed
+50 -0
Showing 1 changed file+50-0
▼src/colors/mod.rs
+50-0
178
178
/// Apply a gradient effect to text using 256-color (or RGB) ANSI codes.
179
179
/// Interpolates between `start_color` (r,g,b) and `end_color` (r,g,b) across the text.
180
180
#[allow(dead_code)]
181
+pub fn gradient_text(text: &str, start: (u8, u8, u8), end: (u8, u8, u8)) -> String {
182
+ let chars: Vec<char> = text.chars().collect();
183
+ let len = chars.len();
184
+ if len == 0 {
185
+ return String::new();
186
+ }
187
+
188
+ let mut result = String::with_capacity(text.len() * 20);
189
+ for (i, ch) in chars.iter().enumerate() {
190
+ let t = if len > 1 {
191
+ i as f64 / (len - 1) as f64
192
+ } else {
193
+ 0.0
194
+ };
195
+ let r = (start.0 as f64 + (end.0 as f64 - start.0 as f64) * t) as u8;
196
+ let g = (start.1 as f64 + (end.1 as f64 - start.1 as f64) * t) as u8;
197
+ let b = (start.2 as f64 + (end.2 as f64 - start.2 as f64) * t) as u8;
198
+ result.push_str(&format!("\x1b[38;2;{};{};{}m{}", r, g, b, ch));
199
+ }
200
+ result.push_str(RESET);
201
+ result
202
+}
203
+
204
+#[cfg(test)]
205
+mod tests {
206
+ use super::*;
207
+
208
+ #[test]
209
+ fn test_color_standard() {
210
+ assert_eq!(color(0), "\x1b[0m\x1b[30m");
211
+ assert_eq!(color(1), "\x1b[0m\x1b[31m");
212
+ assert_eq!(color(7), "\x1b[0m\x1b[37m");
213
+ }
214
+
215
+ #[test]
216
+ fn test_color_256() {
217
+ assert_eq!(color(8), "\x1b[38;5;8m");
218
+ assert_eq!(color(255), "\x1b[38;5;255m");
219
+ }
220
+
221
+ #[test]
222
+ fn test_color_scheme_from_colors() {
223
+ let scheme = ColorScheme::from_colors(&[6, 6, 7, 1], true);
224
+ assert_eq!(scheme.c.len(), 6);
225
+ // c1 should be cyan (6)
226
+ assert!(scheme.c[0].contains("\x1b[36m"));
227
+ }
228
+
229
+ #[test]
230
+ fn test_color_scheme_plain() {
181
231