revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Switch/Toggle widget
//!
//! A toggle switch for boolean values with customizable styles.

use crate::event::{Key, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
use crate::layout::Rect;
use crate::render::{Cell, Modifier};
use crate::style::Color;
use crate::widget::theme::{DISABLED_FG, SEPARATOR_COLOR};
use crate::widget::traits::{EventResult, Interactive, RenderContext, View, WidgetProps};
use crate::{impl_props_builders, impl_styled_view};

/// Switch style
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SwitchStyle {
    /// Default style: [●━━━] / [━━━●]
    #[default]
    Default,
    /// iOS style: (●    ) / (    ●)
    IOS,
    /// Material style: ●━━━○ / ○━━━●
    Material,
    /// Text style: \[OFF\] / \[ON\]
    Text,
    /// Emoji style: ❌ / ✅
    Emoji,
    /// Block style: ▓▓░░ / ░░▓▓
    Block,
}

/// Switch widget
pub struct Switch {
    /// Current state
    on: bool,
    /// Label text
    label: Option<String>,
    /// Label position (true = left)
    label_left: bool,
    /// Visual style
    style: SwitchStyle,
    /// Width of switch track
    width: u16,
    /// Focused state
    focused: bool,
    /// Disabled state
    disabled: bool,
    /// On color
    on_color: Color,
    /// Off color
    off_color: Color,
    /// Track color
    track_color: Color,
    /// Custom on text
    on_text: Option<String>,
    /// Custom off text
    off_text: Option<String>,
    props: WidgetProps,
}

impl Switch {
    /// Create a new switch
    pub fn new() -> Self {
        Self {
            on: false,
            label: None,
            label_left: true,
            style: SwitchStyle::Default,
            width: 6,
            focused: false,
            disabled: false,
            on_color: Color::GREEN,
            off_color: DISABLED_FG,
            track_color: SEPARATOR_COLOR,
            on_text: None,
            off_text: None,
            props: WidgetProps::new(),
        }
    }

    /// Set initial state
    pub fn on(mut self, on: bool) -> Self {
        self.on = on;
        self
    }

    /// Set initial state (alias for `on()` to match Checkbox API)
    pub fn checked(self, checked: bool) -> Self {
        self.on(checked)
    }

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

    /// Set label on right side
    pub fn label_right(mut self) -> Self {
        self.label_left = false;
        self
    }

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

    /// Set width
    pub fn width(mut self, width: u16) -> Self {
        self.width = width.max(4);
        self
    }

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

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

    /// Set on color
    pub fn on_color(mut self, color: Color) -> Self {
        self.on_color = color;
        self
    }

    /// Set off color
    pub fn off_color(mut self, color: Color) -> Self {
        self.off_color = color;
        self
    }

    /// Set track color
    pub fn track_color(mut self, color: Color) -> Self {
        self.track_color = color;
        self
    }

    /// Set custom text
    pub fn text(mut self, on: impl Into<String>, off: impl Into<String>) -> Self {
        self.on_text = Some(on.into());
        self.off_text = Some(off.into());
        self
    }

    /// Toggle state
    pub fn toggle(&mut self) {
        if !self.disabled {
            self.on = !self.on;
        }
    }

    /// Set state (respects disabled state)
    pub fn set(&mut self, on: bool) {
        if !self.disabled {
            self.on = on;
        }
    }

    /// Get current state
    pub fn is_on(&self) -> bool {
        self.on
    }

    /// Get current state (alias for `is_on()` to match Checkbox API)
    pub fn is_checked(&self) -> bool {
        self.is_on()
    }

    /// Handle key input
    pub fn handle_key(&mut self, key: &crate::event::Key) -> bool {
        use crate::event::Key;

        if self.disabled || !self.focused {
            return false;
        }

        match key {
            Key::Enter | Key::Char(' ') => {
                self.toggle();
                true
            }
            _ => false,
        }
    }

    /// Render default style
    fn render_default(&self, ctx: &mut RenderContext, x: u16, y: u16) {
        let color = if self.on {
            self.on_color
        } else {
            self.off_color
        };
        let track_len = self.width.saturating_sub(2);

        // Opening bracket
        let mut open = Cell::new('[');
        open.fg = Some(if self.focused { Color::CYAN } else { color });
        ctx.set(x, y, open);

        // Track
        for i in 0..track_len {
            let is_knob = if self.on { i == track_len - 1 } else { i == 0 };

            let ch = if is_knob { '' } else { '' };
            let mut cell = Cell::new(ch);
            cell.fg = Some(if is_knob { color } else { self.track_color });
            ctx.set(x + 1 + i, y, cell);
        }

        // Closing bracket
        let mut close = Cell::new(']');
        close.fg = Some(if self.focused { Color::CYAN } else { color });
        ctx.set(x + self.width - 1, y, close);
    }

    /// Render iOS style
    fn render_ios(&self, ctx: &mut RenderContext, x: u16, y: u16) {
        let color = if self.on {
            self.on_color
        } else {
            self.off_color
        };
        let bg = if self.on {
            self.on_color
        } else {
            self.track_color
        };
        let track_len = self.width.saturating_sub(2);

        // Opening paren
        let mut open = Cell::new('(');
        open.fg = Some(color);
        ctx.set(x, y, open);

        // Track with knob
        for i in 0..track_len {
            let is_knob = if self.on { i == track_len - 1 } else { i == 0 };

            let ch = if is_knob { '' } else { ' ' };
            let mut cell = Cell::new(ch);
            cell.fg = Some(Color::WHITE);
            cell.bg = Some(bg);
            ctx.set(x + 1 + i, y, cell);
        }

        // Closing paren
        let mut close = Cell::new(')');
        close.fg = Some(color);
        ctx.set(x + self.width - 1, y, close);
    }

    /// Render Material style
    fn render_material(&self, ctx: &mut RenderContext, x: u16, y: u16) {
        let color = if self.on {
            self.on_color
        } else {
            self.off_color
        };
        let track_len = self.width;

        for i in 0..track_len {
            let is_left_knob = i == 0;
            let is_right_knob = i == track_len - 1;

            let (ch, fg) = if self.on {
                if is_right_knob {
                    ('', color)
                } else if is_left_knob {
                    ('', self.track_color)
                } else {
                    ('', color)
                }
            } else if is_left_knob {
                ('', color)
            } else if is_right_knob {
                ('', self.track_color)
            } else {
                ('', self.track_color)
            };

            let mut cell = Cell::new(ch);
            cell.fg = Some(fg);
            ctx.set(x + i, y, cell);
        }
    }

    /// Render text style
    fn render_text(&self, ctx: &mut RenderContext, x: u16, y: u16) {
        let (text, color) = if self.on {
            (self.on_text.as_deref().unwrap_or("ON"), self.on_color)
        } else {
            (self.off_text.as_deref().unwrap_or("OFF"), self.off_color)
        };

        let mut open = Cell::new('[');
        open.fg = Some(if self.focused {
            Color::CYAN
        } else {
            Color::WHITE
        });
        ctx.set(x, y, open);

        for (i, ch) in text.chars().enumerate() {
            let mut cell = Cell::new(ch);
            cell.fg = Some(color);
            if self.on {
                cell.modifier |= Modifier::BOLD;
            }
            ctx.set(x + 1 + i as u16, y, cell);
        }

        let mut close = Cell::new(']');
        close.fg = Some(if self.focused {
            Color::CYAN
        } else {
            Color::WHITE
        });
        ctx.set(x + 1 + text.len() as u16, y, close);
    }

    /// Render emoji style
    fn render_emoji(&self, ctx: &mut RenderContext, x: u16, y: u16) {
        let ch = if self.on { '' } else { '' };
        let mut cell = Cell::new(ch);
        cell.fg = Some(if self.on {
            self.on_color
        } else {
            self.off_color
        });
        ctx.set(x, y, cell);
        // Wide emoji occupies 2 columns — clear the second cell to prevent artifacts
        ctx.set(x + 1, y, Cell::new(' '));
    }

    /// Render block style
    fn render_block(&self, ctx: &mut RenderContext, x: u16, y: u16) {
        let track_len = self.width;
        let half = track_len / 2;

        for i in 0..track_len {
            let is_filled = if self.on { i >= half } else { i < half };
            let ch = if is_filled { '' } else { '' };
            let color = if self.on {
                self.on_color
            } else {
                self.off_color
            };

            let mut cell = Cell::new(ch);
            cell.fg = Some(color);
            ctx.set(x + i, y, cell);
        }
    }
}

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

impl View for Switch {
    fn render(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        if area.width == 0 || area.height == 0 {
            return;
        }

        let mut x: u16 = 0;
        let y: u16 = 0;

        // Render label if on left
        if self.label_left {
            if let Some(ref label) = self.label {
                let label_color = if self.disabled {
                    DISABLED_FG
                } else if let Some(css_fg) = ctx
                    .style
                    .map(|s| s.visual.color)
                    .filter(|c| *c != Color::default())
                {
                    css_fg
                } else {
                    Color::WHITE
                };
                ctx.draw_text_clipped(x, y, label, label_color, area.width.saturating_sub(x));
                x += crate::utils::display_width(label) as u16 + 1;
            }
        }

        // Render switch
        if x < area.width {
            match self.style {
                SwitchStyle::Default => self.render_default(ctx, x, y),
                SwitchStyle::IOS => self.render_ios(ctx, x, y),
                SwitchStyle::Material => self.render_material(ctx, x, y),
                SwitchStyle::Text => self.render_text(ctx, x, y),
                SwitchStyle::Emoji => self.render_emoji(ctx, x, y),
                SwitchStyle::Block => self.render_block(ctx, x, y),
            }

            x += match self.style {
                SwitchStyle::Text => {
                    let text = if self.on {
                        self.on_text.as_deref().unwrap_or("ON")
                    } else {
                        self.off_text.as_deref().unwrap_or("OFF")
                    };
                    text.len() as u16 + 2
                }
                SwitchStyle::Emoji => 2,
                _ => self.width,
            };
        }

        // Render label if on right
        if !self.label_left {
            if let Some(ref label) = self.label {
                x += 1;
                let label_color = if self.disabled {
                    DISABLED_FG
                } else if let Some(css_fg) = ctx
                    .style
                    .map(|s| s.visual.color)
                    .filter(|c| *c != Color::default())
                {
                    css_fg
                } else {
                    Color::WHITE
                };
                ctx.draw_text_clipped(x, y, label, label_color, area.width.saturating_sub(x));
            }
        }

        // Render focus indicator
        if self.focused && !self.disabled {
            // Find switch start position (relative)
            let switch_x = if self.label_left {
                self.label
                    .as_ref()
                    .map(|l| crate::utils::display_width(l) as u16 + 1)
                    .unwrap_or(0)
            } else {
                0u16
            };

            // Draw focus bracket on left
            if switch_x > 0 {
                let mut left = Cell::new('[');
                left.fg = Some(Color::CYAN);
                ctx.set(switch_x.saturating_sub(1), y, left);
            } else {
                let mut left = Cell::new('[');
                left.fg = Some(Color::CYAN);
                ctx.set(0, y, left);
            }

            // Draw focus bracket on right
            let switch_width = match self.style {
                SwitchStyle::Text => {
                    let text = if self.on {
                        self.on_text.as_deref().unwrap_or("ON")
                    } else {
                        self.off_text.as_deref().unwrap_or("OFF")
                    };
                    text.len() as u16 + 2
                }
                SwitchStyle::Emoji => 2,
                _ => self.width,
            };
            let right_x = switch_x + switch_width;
            if right_x < area.width {
                let mut right = Cell::new(']');
                right.fg = Some(Color::CYAN);
                ctx.set(right_x, y, right);
            }
        }
    }

    crate::impl_view_meta!("Switch");
}

impl Interactive for Switch {
    fn handle_key(&mut self, event: &KeyEvent) -> EventResult {
        if self.disabled {
            return EventResult::Ignored;
        }

        match event.key {
            Key::Enter | Key::Char(' ') => {
                self.toggle();
                EventResult::ConsumedAndRender
            }
            _ => EventResult::Ignored,
        }
    }

    fn handle_mouse(&mut self, event: &MouseEvent, _area: Rect) -> EventResult {
        if self.disabled {
            return EventResult::Ignored;
        }

        match event.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                self.toggle();
                EventResult::ConsumedAndRender
            }
            _ => EventResult::Ignored,
        }
    }

    crate::impl_focus_handlers!(direct);
}

/// Helper to create a switch
pub fn switch() -> Switch {
    Switch::new()
}

/// Helper to create a labeled switch
pub fn toggle(label: impl Into<String>) -> Switch {
    Switch::new().label(label)
}

impl_styled_view!(Switch);
impl_props_builders!(Switch);

// All tests moved to tests/widget/switch.rs