envision 0.16.0

A ratatui framework for collaborative TUI development with headless testing support
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
//! A numeric range selection component with keyboard control.
//!
//! [`Slider`] provides an interactive slider for selecting a numeric value
//! within a configurable range. State is stored in [`SliderState`], updated
//! via [`SliderMessage`], and produces [`SliderOutput`].
//!
//!
//! See also [`ProgressBar`](super::ProgressBar) for a display-only progress indicator.
//!
//! # Example
//!
//! ```rust
//! use envision::component::{Slider, SliderMessage, SliderOutput, SliderState, Component};
//!
//! // Create a slider with range 0..=100
//! let mut state = SliderState::new(0.0, 100.0);
//! assert_eq!(state.value(), 0.0);
//!
//! // Increment the value
//! let output = Slider::update(&mut state, SliderMessage::Increment);
//! assert_eq!(output, Some(SliderOutput::ValueChanged(1.0)));
//! assert_eq!(state.value(), 1.0);
//!
//! // Set value directly (clamped to range)
//! let output = Slider::update(&mut state, SliderMessage::SetValue(50.0));
//! assert_eq!(output, Some(SliderOutput::ValueChanged(50.0)));
//! assert_eq!(state.value(), 50.0);
//!
//! // Check percentage
//! assert!((state.percentage() - 0.5).abs() < f64::EPSILON);
//! ```

use ratatui::prelude::*;
use ratatui::widgets::Paragraph;

use super::{Component, EventContext, RenderContext};
use crate::input::{Event, Key};
use crate::theme::Theme;

/// Orientation of the slider.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum SliderOrientation {
    /// Horizontal slider (left to right).
    #[default]
    Horizontal,
    /// Vertical slider (bottom to top).
    Vertical,
}

/// Messages that can be sent to a Slider.
#[derive(Clone, Debug, PartialEq)]
pub enum SliderMessage {
    /// Increase value by one step.
    Increment,
    /// Decrease value by one step.
    Decrement,
    /// Increase value by step * 10.
    IncrementPage,
    /// Decrease value by step * 10.
    DecrementPage,
    /// Set value directly (clamped to range).
    SetValue(f64),
    /// Set value to the minimum.
    SetMin,
    /// Set value to the maximum.
    SetMax,
}

/// Output messages from a Slider.
#[derive(Clone, Debug, PartialEq)]
pub enum SliderOutput {
    /// The slider value changed. Contains the new value.
    ValueChanged(f64),
}

/// State for a Slider component.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct SliderState {
    /// The current value.
    value: f64,
    /// The minimum value.
    min: f64,
    /// The maximum value.
    max: f64,
    /// The step increment.
    step: f64,
    /// The slider orientation.
    orientation: SliderOrientation,
    /// Optional label.
    label: Option<String>,
    /// Whether to display the current value.
    show_value: bool,
}

impl Default for SliderState {
    fn default() -> Self {
        Self {
            value: 0.0,
            min: 0.0,
            max: 100.0,
            step: 1.0,
            orientation: SliderOrientation::default(),
            label: None,
            show_value: true,
        }
    }
}

impl SliderState {
    /// Creates a new slider with the given range.
    ///
    /// The initial value is set to `min`. The step size defaults to 1.0.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(0.0, 100.0);
    /// assert_eq!(state.value(), 0.0);
    /// assert_eq!(state.min(), 0.0);
    /// assert_eq!(state.max(), 100.0);
    /// assert_eq!(state.step(), 1.0);
    /// ```
    pub fn new(min: f64, max: f64) -> Self {
        Self {
            value: min,
            min,
            max,
            ..Self::default()
        }
    }

    /// Sets the initial value (builder pattern).
    ///
    /// The value is clamped to the slider's range.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(0.0, 100.0).with_value(50.0);
    /// assert_eq!(state.value(), 50.0);
    /// ```
    pub fn with_value(mut self, value: f64) -> Self {
        self.value = value.clamp(self.min, self.max);
        self
    }

    /// Sets the step size (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(0.0, 100.0).with_step(5.0);
    /// assert_eq!(state.step(), 5.0);
    /// ```
    pub fn with_step(mut self, step: f64) -> Self {
        self.step = step;
        self
    }

    /// Sets the orientation (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{SliderState, SliderOrientation};
    ///
    /// let state = SliderState::new(0.0, 100.0)
    ///     .with_orientation(SliderOrientation::Vertical);
    /// ```
    pub fn with_orientation(mut self, orientation: SliderOrientation) -> Self {
        self.orientation = orientation;
        self
    }

    /// Sets the label (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(0.0, 100.0).with_label("Volume");
    /// assert_eq!(state.label(), Some("Volume"));
    /// ```
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Sets whether to show the current value (builder pattern).
    ///
    /// Default is `true`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(0.0, 100.0).with_show_value(false);
    /// ```
    pub fn with_show_value(mut self, show_value: bool) -> Self {
        self.show_value = show_value;
        self
    }

    /// Returns the current value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(0.0, 100.0).with_value(42.0);
    /// assert_eq!(state.value(), 42.0);
    /// ```
    pub fn value(&self) -> f64 {
        self.value
    }

    /// Sets the current value, clamping it to the range.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let mut state = SliderState::new(0.0, 100.0);
    /// state.set_value(50.0);
    /// assert_eq!(state.value(), 50.0);
    ///
    /// // Values are clamped to the range
    /// state.set_value(200.0);
    /// assert_eq!(state.value(), 100.0);
    /// ```
    pub fn set_value(&mut self, value: f64) {
        self.value = value.clamp(self.min, self.max);
    }

    /// Returns the minimum value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(10.0, 90.0);
    /// assert_eq!(state.min(), 10.0);
    /// ```
    pub fn min(&self) -> f64 {
        self.min
    }

    /// Returns the maximum value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(10.0, 90.0);
    /// assert_eq!(state.max(), 90.0);
    /// ```
    pub fn max(&self) -> f64 {
        self.max
    }

    /// Returns the step size.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(0.0, 100.0).with_step(5.0);
    /// assert_eq!(state.step(), 5.0);
    /// ```
    pub fn step(&self) -> f64 {
        self.step
    }

    /// Returns the current value as a percentage (0.0..=1.0).
    ///
    /// Returns 0.0 if min equals max (degenerate range).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(0.0, 100.0).with_value(25.0);
    /// assert!((state.percentage() - 0.25).abs() < f64::EPSILON);
    ///
    /// let state = SliderState::new(10.0, 10.0);
    /// assert!((state.percentage() - 0.0).abs() < f64::EPSILON);
    /// ```
    pub fn percentage(&self) -> f64 {
        let range = self.max - self.min;
        if range == 0.0 {
            0.0
        } else {
            (self.value - self.min) / range
        }
    }

    /// Returns the label, if set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(0.0, 100.0).with_label("Volume");
    /// assert_eq!(state.label(), Some("Volume"));
    /// ```
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    /// Returns whether the value display is enabled.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let state = SliderState::new(0.0, 100.0).with_show_value(false);
    /// assert!(!state.show_value());
    /// ```
    pub fn show_value(&self) -> bool {
        self.show_value
    }

    /// Sets whether the value display is enabled.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SliderState;
    ///
    /// let mut state = SliderState::new(0.0, 100.0);
    /// state.set_show_value(true);
    /// assert!(state.show_value());
    /// ```
    pub fn set_show_value(&mut self, show: bool) {
        self.show_value = show;
    }

    /// Returns the orientation.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{SliderState, SliderOrientation};
    ///
    /// let state = SliderState::new(0.0, 100.0).with_orientation(SliderOrientation::Vertical);
    /// assert_eq!(state.orientation(), &SliderOrientation::Vertical);
    /// ```
    pub fn orientation(&self) -> &SliderOrientation {
        &self.orientation
    }

    /// Sets the orientation.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{SliderState, SliderOrientation};
    ///
    /// let mut state = SliderState::new(0.0, 100.0);
    /// state.set_orientation(SliderOrientation::Vertical);
    /// assert_eq!(state.orientation(), &SliderOrientation::Vertical);
    /// ```
    pub fn set_orientation(&mut self, orientation: SliderOrientation) {
        self.orientation = orientation;
    }

    /// Updates the slider state with a message, returning any output.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{SliderMessage, SliderOutput, SliderState};
    ///
    /// let mut state = SliderState::new(0.0, 100.0);
    /// let output = state.update(SliderMessage::Increment);
    /// assert_eq!(output, Some(SliderOutput::ValueChanged(1.0)));
    /// assert_eq!(state.value(), 1.0);
    /// ```
    pub fn update(&mut self, msg: SliderMessage) -> Option<SliderOutput> {
        Slider::update(self, msg)
    }
}

/// A numeric range selection component with keyboard control.
///
/// `Slider` provides an interactive control for selecting a numeric value
/// within a configurable range. The slider supports both horizontal and
/// vertical orientations, configurable step sizes, and optional labels.
///
/// # Keyboard Controls
///
/// Horizontal mode:
/// - Right / l: increment by step
/// - Left / h: decrement by step
///
/// Vertical mode:
/// - Up / k: increment by step
/// - Down / j: decrement by step
///
/// Both modes:
/// - PageUp: increment by step * 10
/// - PageDown: decrement by step * 10
/// - Home: set to minimum
/// - End: set to maximum
///
/// # Visual Format
///
/// Horizontal:
/// ```text
/// Label: 42.0
/// ████████████░░░░░░░░░░░░░░░░░░░
/// ```
///
/// The filled portion uses block characters (`\u{2588}`) and the empty
/// portion uses light shade characters (`\u{2591}`).
///
/// # Example
///
/// ```rust
/// use envision::component::{Slider, SliderMessage, SliderOutput, SliderState, Component};
///
/// let mut state = SliderState::new(0.0, 100.0)
///     .with_value(50.0)
///     .with_step(5.0)
///     .with_label("Volume");
///
/// // Increment the value
/// let output = Slider::update(&mut state, SliderMessage::Increment);
/// assert_eq!(output, Some(SliderOutput::ValueChanged(55.0)));
/// assert_eq!(state.value(), 55.0);
/// ```
pub struct Slider;

impl Component for Slider {
    type State = SliderState;
    type Message = SliderMessage;
    type Output = SliderOutput;

    fn init() -> Self::State {
        SliderState::default()
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        let old_value = state.value;

        match msg {
            SliderMessage::Increment => {
                state.value = (state.value + state.step).min(state.max);
            }
            SliderMessage::Decrement => {
                state.value = (state.value - state.step).max(state.min);
            }
            SliderMessage::IncrementPage => {
                state.value = (state.value + state.step * 10.0).min(state.max);
            }
            SliderMessage::DecrementPage => {
                state.value = (state.value - state.step * 10.0).max(state.min);
            }
            SliderMessage::SetValue(v) => {
                state.value = v.clamp(state.min, state.max);
            }
            SliderMessage::SetMin => {
                state.value = state.min;
            }
            SliderMessage::SetMax => {
                state.value = state.max;
            }
        }

        if (state.value - old_value).abs() > f64::EPSILON {
            Some(SliderOutput::ValueChanged(state.value))
        } else {
            None
        }
    }

    fn handle_event(
        state: &Self::State,
        event: &Event,
        ctx: &EventContext,
    ) -> Option<Self::Message> {
        if !ctx.focused || ctx.disabled {
            return None;
        }

        if let Some(key) = event.as_key() {
            match state.orientation {
                SliderOrientation::Horizontal => match key.code {
                    Key::Right | Key::Char('l') => Some(SliderMessage::Increment),
                    Key::Left | Key::Char('h') => Some(SliderMessage::Decrement),
                    Key::PageUp => Some(SliderMessage::IncrementPage),
                    Key::PageDown => Some(SliderMessage::DecrementPage),
                    Key::Home => Some(SliderMessage::SetMin),
                    Key::End => Some(SliderMessage::SetMax),
                    _ => None,
                },
                SliderOrientation::Vertical => match key.code {
                    Key::Up | Key::Char('k') => Some(SliderMessage::Increment),
                    Key::Down | Key::Char('j') => Some(SliderMessage::Decrement),
                    Key::PageUp => Some(SliderMessage::IncrementPage),
                    Key::PageDown => Some(SliderMessage::DecrementPage),
                    Key::Home => Some(SliderMessage::SetMin),
                    Key::End => Some(SliderMessage::SetMax),
                    _ => None,
                },
            }
        } else {
            None
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        match state.orientation {
            SliderOrientation::Horizontal => view_horizontal(state, ctx),
            SliderOrientation::Vertical => view_vertical(state, ctx),
        }
    }
}

/// Renders the slider in horizontal orientation.
fn view_horizontal(state: &SliderState, ctx: &mut RenderContext<'_, '_>) {
    if ctx.area.height == 0 || ctx.area.width == 0 {
        return;
    }

    let (label_style, filled_style, empty_style) = compute_styles(ctx.theme, &ctx.event_context());

    let mut lines = Vec::new();

    // Build label line if needed
    if state.label.is_some() || state.show_value {
        let label_text = build_label_text(state);
        lines.push(Line::from(Span::styled(label_text, label_style)));
    }

    // Build track line
    let track_width = ctx.area.width as usize;
    let pct = state.percentage();
    let filled = (pct * track_width as f64).round() as usize;
    let empty = track_width.saturating_sub(filled);

    let mut spans = Vec::new();
    if filled > 0 {
        spans.push(Span::styled("\u{2588}".repeat(filled), filled_style));
    }
    if empty > 0 {
        spans.push(Span::styled("\u{2591}".repeat(empty), empty_style));
    }
    lines.push(Line::from(spans));

    let paragraph = Paragraph::new(Text::from(lines));

    let value_str = format_value(state.value);
    let annotation = crate::annotation::Annotation::new(crate::annotation::WidgetType::Custom(
        "Slider".to_string(),
    ))
    .with_id("slider")
    .with_value(value_str);

    let annotation = if let Some(label) = &state.label {
        annotation.with_label(label.as_str())
    } else {
        annotation
    };

    let annotated = crate::annotation::Annotate::new(paragraph, annotation)
        .focused(ctx.focused)
        .disabled(ctx.disabled);
    ctx.frame.render_widget(annotated, ctx.area);
}

/// Renders the slider in vertical orientation.
fn view_vertical(state: &SliderState, ctx: &mut RenderContext<'_, '_>) {
    if ctx.area.height == 0 || ctx.area.width == 0 {
        return;
    }

    let (label_style, filled_style, empty_style) = compute_styles(ctx.theme, &ctx.event_context());

    let mut lines = Vec::new();

    // Reserve space for label at top
    let label_lines = if state.label.is_some() || state.show_value {
        1
    } else {
        0
    };
    let track_height = (ctx.area.height as usize).saturating_sub(label_lines);

    // Label at top
    if state.label.is_some() || state.show_value {
        let label_text = build_label_text(state);
        lines.push(Line::from(Span::styled(label_text, label_style)));
    }

    // Track from top (max) to bottom (min)
    let pct = state.percentage();
    let filled = (pct * track_height as f64).round() as usize;
    let empty = track_height.saturating_sub(filled);

    // Empty portion at top (higher values not yet reached)
    for _ in 0..empty {
        lines.push(Line::from(Span::styled("\u{2591}", empty_style)));
    }
    // Filled portion at bottom (lower values, already reached)
    for _ in 0..filled {
        lines.push(Line::from(Span::styled("\u{2588}", filled_style)));
    }

    let paragraph = Paragraph::new(Text::from(lines));

    let value_str = format_value(state.value);
    let annotation = crate::annotation::Annotation::new(crate::annotation::WidgetType::Custom(
        "Slider".to_string(),
    ))
    .with_id("slider")
    .with_value(value_str);

    let annotation = if let Some(label) = &state.label {
        annotation.with_label(label.as_str())
    } else {
        annotation
    };

    let annotated = crate::annotation::Annotate::new(paragraph, annotation)
        .focused(ctx.focused)
        .disabled(ctx.disabled);
    ctx.frame.render_widget(annotated, ctx.area);
}

/// Computes the styles for label, filled, and empty portions.
fn compute_styles(theme: &Theme, ctx: &EventContext) -> (Style, Style, Style) {
    if ctx.disabled {
        let disabled = theme.disabled_style();
        (disabled, disabled, disabled)
    } else if ctx.focused {
        let label_style = theme.focused_style();
        let filled_style = theme.focused_style();
        let empty_style = theme.normal_style();
        (label_style, filled_style, empty_style)
    } else {
        let label_style = theme.normal_style();
        let filled_style = theme.normal_style();
        let empty_style = theme.normal_style();
        (label_style, filled_style, empty_style)
    }
}

/// Builds the label text combining label and value display.
fn build_label_text(state: &SliderState) -> String {
    let mut parts = Vec::new();

    if let Some(label) = &state.label {
        parts.push(label.clone());
    }

    if state.show_value {
        parts.push(format_value(state.value));
    }

    parts.join(": ")
}

/// Formats a value for display, omitting decimal places when the value is a whole number.
fn format_value(value: f64) -> String {
    if value.fract() == 0.0 {
        format!("{}", value as i64)
    } else {
        format!("{value}")
    }
}

#[cfg(test)]
mod tests;