rnk 0.15.31

A React-like declarative terminal UI framework for Rust, inspired by Ink
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Color Picker component for selecting colors
//!
//! Provides a color picker UI for terminal applications.
//!
//! # Example
//!
//! ```rust,ignore
//! use rnk::prelude::*;
//! use rnk::components::ColorPicker;
//!
//! fn app() -> Element {
//!     let picker = ColorPicker::new()
//!         .selected(Color::Blue);
//!
//!     picker.into_element()
//! }
//! ```

use crate::components::{Box, Text};
use crate::core::{Color, Element, FlexDirection};

/// Predefined color palette
#[derive(Debug, Clone)]
pub struct ColorPalette {
    /// Colors in the palette
    pub colors: Vec<Color>,
    /// Palette name
    pub name: String,
}

impl ColorPalette {
    /// Create a new palette
    pub fn new(name: impl Into<String>, colors: Vec<Color>) -> Self {
        Self {
            name: name.into(),
            colors,
        }
    }

    /// Basic 16 ANSI colors
    pub fn basic() -> Self {
        Self::new(
            "Basic",
            vec![
                Color::Black,
                Color::Red,
                Color::Green,
                Color::Yellow,
                Color::Blue,
                Color::Magenta,
                Color::Cyan,
                Color::White,
                Color::BrightBlack,
                Color::BrightRed,
                Color::BrightGreen,
                Color::BrightYellow,
                Color::BrightBlue,
                Color::BrightMagenta,
                Color::BrightCyan,
                Color::BrightWhite,
            ],
        )
    }

    /// Grayscale palette
    pub fn grayscale() -> Self {
        let colors: Vec<Color> = (0..24)
            .map(|i| {
                let gray = 8 + i * 10;
                Color::Rgb(gray, gray, gray)
            })
            .collect();
        Self::new("Grayscale", colors)
    }

    /// Rainbow palette
    pub fn rainbow() -> Self {
        Self::new(
            "Rainbow",
            vec![
                Color::Rgb(255, 0, 0),     // Red
                Color::Rgb(255, 127, 0),   // Orange
                Color::Rgb(255, 255, 0),   // Yellow
                Color::Rgb(0, 255, 0),     // Green
                Color::Rgb(0, 255, 255),   // Cyan
                Color::Rgb(0, 0, 255),     // Blue
                Color::Rgb(127, 0, 255),   // Purple
                Color::Rgb(255, 0, 255),   // Magenta
            ],
        )
    }

    /// Pastel palette
    pub fn pastel() -> Self {
        Self::new(
            "Pastel",
            vec![
                Color::Rgb(255, 179, 186), // Pink
                Color::Rgb(255, 223, 186), // Peach
                Color::Rgb(255, 255, 186), // Yellow
                Color::Rgb(186, 255, 201), // Mint
                Color::Rgb(186, 225, 255), // Sky
                Color::Rgb(218, 186, 255), // Lavender
            ],
        )
    }

    /// Material design colors
    pub fn material() -> Self {
        Self::new(
            "Material",
            vec![
                Color::Rgb(244, 67, 54),   // Red
                Color::Rgb(233, 30, 99),   // Pink
                Color::Rgb(156, 39, 176),  // Purple
                Color::Rgb(103, 58, 183),  // Deep Purple
                Color::Rgb(63, 81, 181),   // Indigo
                Color::Rgb(33, 150, 243),  // Blue
                Color::Rgb(3, 169, 244),   // Light Blue
                Color::Rgb(0, 188, 212),   // Cyan
                Color::Rgb(0, 150, 136),   // Teal
                Color::Rgb(76, 175, 80),   // Green
                Color::Rgb(139, 195, 74),  // Light Green
                Color::Rgb(205, 220, 57),  // Lime
                Color::Rgb(255, 235, 59),  // Yellow
                Color::Rgb(255, 193, 7),   // Amber
                Color::Rgb(255, 152, 0),   // Orange
                Color::Rgb(255, 87, 34),   // Deep Orange
            ],
        )
    }
}

impl Default for ColorPalette {
    fn default() -> Self {
        Self::basic()
    }
}

/// Color picker state
#[derive(Debug, Clone, Default)]
pub struct ColorPickerState {
    /// Selected color index
    pub selected: usize,
    /// Whether the picker is open
    pub open: bool,
}

impl ColorPickerState {
    /// Create a new state
    pub fn new() -> Self {
        Self::default()
    }

    /// Open the picker
    pub fn open(&mut self) {
        self.open = true;
    }

    /// Close the picker
    pub fn close(&mut self) {
        self.open = false;
    }

    /// Toggle the picker
    pub fn toggle(&mut self) {
        self.open = !self.open;
    }

    /// Move selection
    pub fn select(&mut self, index: usize) {
        self.selected = index;
    }

    /// Move selection left
    pub fn select_prev(&mut self, max: usize) {
        if self.selected > 0 {
            self.selected -= 1;
        } else if max > 0 {
            self.selected = max - 1;
        }
    }

    /// Move selection right
    pub fn select_next(&mut self, max: usize) {
        if max > 0 && self.selected < max - 1 {
            self.selected += 1;
        } else {
            self.selected = 0;
        }
    }
}

/// Color picker style
#[derive(Debug, Clone)]
pub struct ColorPickerStyle {
    /// Colors per row
    pub colors_per_row: usize,
    /// Show color names
    pub show_names: bool,
    /// Show hex values
    pub show_hex: bool,
    /// Selection indicator
    pub selection_indicator: String,
    /// Border color
    pub border_color: Color,
}

impl Default for ColorPickerStyle {
    fn default() -> Self {
        Self {
            colors_per_row: 8,
            show_names: false,
            show_hex: false,
            selection_indicator: "â–¼".to_string(),
            border_color: Color::White,
        }
    }
}

impl ColorPickerStyle {
    /// Create a new style
    pub fn new() -> Self {
        Self::default()
    }

    /// Set colors per row
    pub fn colors_per_row(mut self, count: usize) -> Self {
        self.colors_per_row = count;
        self
    }

    /// Show color names
    pub fn show_names(mut self, show: bool) -> Self {
        self.show_names = show;
        self
    }

    /// Show hex values
    pub fn show_hex(mut self, show: bool) -> Self {
        self.show_hex = show;
        self
    }

    /// Compact style
    pub fn compact() -> Self {
        Self::new()
            .colors_per_row(16)
            .show_names(false)
            .show_hex(false)
    }

    /// Detailed style
    pub fn detailed() -> Self {
        Self::new()
            .colors_per_row(4)
            .show_names(true)
            .show_hex(true)
    }
}

/// Color picker component
#[derive(Debug)]
pub struct ColorPicker {
    /// Color palette
    palette: ColorPalette,
    /// Current state
    state: ColorPickerState,
    /// Style
    style: ColorPickerStyle,
    /// Title
    title: Option<String>,
}

impl ColorPicker {
    /// Create a new color picker
    pub fn new() -> Self {
        Self {
            palette: ColorPalette::basic(),
            state: ColorPickerState::new(),
            style: ColorPickerStyle::default(),
            title: None,
        }
    }

    /// Set the palette
    pub fn palette(mut self, palette: ColorPalette) -> Self {
        self.palette = palette;
        self
    }

    /// Set the state
    pub fn state(mut self, state: ColorPickerState) -> Self {
        self.state = state;
        self
    }

    /// Set the style
    pub fn style(mut self, style: ColorPickerStyle) -> Self {
        self.style = style;
        self
    }

    /// Set title
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set selected color by index
    pub fn selected(mut self, index: usize) -> Self {
        self.state.selected = index;
        self
    }

    /// Get the selected color
    pub fn selected_color(&self) -> Option<Color> {
        self.palette.colors.get(self.state.selected).copied()
    }

    /// Convert color to hex string
    fn color_to_hex(color: &Color) -> String {
        match color {
            Color::Rgb(r, g, b) => format!("#{:02X}{:02X}{:02X}", r, g, b),
            _ => "#??????".to_string(),
        }
    }

    /// Render a color swatch
    fn render_swatch(&self, color: &Color, is_selected: bool) -> String {
        let block = "██";
        let indicator = if is_selected {
            &self.style.selection_indicator
        } else {
            "  "
        };

        format!(
            "{}{}{}{}",
            color.to_ansi_fg(),
            block,
            "\x1b[0m",
            indicator
        )
    }

    /// Convert to Element
    pub fn into_element(self) -> Element {
        let mut container = Box::new().flex_direction(FlexDirection::Column);

        // Title
        if let Some(title) = &self.title {
            container = container.child(Text::new(title).into_element());
        }

        // Color grid
        let colors = &self.palette.colors;
        let per_row = self.style.colors_per_row;

        for (row_idx, chunk) in colors.chunks(per_row).enumerate() {
            let mut row_str = String::new();

            for (col_idx, color) in chunk.iter().enumerate() {
                let idx = row_idx * per_row + col_idx;
                let is_selected = idx == self.state.selected;
                row_str.push_str(&self.render_swatch(color, is_selected));
            }

            container = container.child(Text::new(row_str).into_element());
        }

        // Selected color info
        if self.style.show_hex || self.style.show_names {
            if let Some(color) = self.selected_color() {
                let mut info = String::new();

                if self.style.show_hex {
                    info.push_str(&Self::color_to_hex(&color));
                }

                if !info.is_empty() {
                    container = container.child(Text::new(info).into_element());
                }
            }
        }

        container.into_element()
    }
}

impl Default for ColorPicker {
    fn default() -> Self {
        Self::new()
    }
}

/// Create a color picker
pub fn color_picker() -> ColorPicker {
    ColorPicker::new()
}

/// Create a color picker with a palette
pub fn color_picker_with_palette(palette: ColorPalette) -> ColorPicker {
    ColorPicker::new().palette(palette)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_color_palette_basic() {
        let palette = ColorPalette::basic();
        assert_eq!(palette.colors.len(), 16);
    }

    #[test]
    fn test_color_palette_grayscale() {
        let palette = ColorPalette::grayscale();
        assert_eq!(palette.colors.len(), 24);
    }

    #[test]
    fn test_color_palette_presets() {
        let _ = ColorPalette::rainbow();
        let _ = ColorPalette::pastel();
        let _ = ColorPalette::material();
    }

    #[test]
    fn test_color_picker_state() {
        let mut state = ColorPickerState::new();
        assert!(!state.open);

        state.open();
        assert!(state.open);

        state.close();
        assert!(!state.open);
    }

    #[test]
    fn test_color_picker_state_navigation() {
        let mut state = ColorPickerState::new();
        state.selected = 0;

        state.select_next(5);
        assert_eq!(state.selected, 1);

        state.select_prev(5);
        assert_eq!(state.selected, 0);

        // Wrap around
        state.select_prev(5);
        assert_eq!(state.selected, 4);
    }

    #[test]
    fn test_color_picker_creation() {
        let picker = ColorPicker::new();
        assert_eq!(picker.palette.colors.len(), 16);
    }

    #[test]
    fn test_color_picker_selected_color() {
        let picker = ColorPicker::new().selected(0);
        let color = picker.selected_color();
        assert!(color.is_some());
    }

    #[test]
    fn test_color_picker_style() {
        let style = ColorPickerStyle::new()
            .colors_per_row(4)
            .show_hex(true);

        assert_eq!(style.colors_per_row, 4);
        assert!(style.show_hex);
    }

    #[test]
    fn test_color_picker_into_element() {
        let picker = ColorPicker::new();
        let _ = picker.into_element();
    }

    #[test]
    fn test_color_to_hex() {
        let hex = ColorPicker::color_to_hex(&Color::Rgb(255, 0, 128));
        assert_eq!(hex, "#FF0080");
    }

    #[test]
    fn test_color_picker_helpers() {
        let _ = color_picker();
        let _ = color_picker_with_palette(ColorPalette::rainbow());
    }
}