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
//! A collapsible component with an expandable content section.
//!
//! [`Collapsible`] provides a single section with a clickable header that
//! expands or collapses a content area. Unlike [`Accordion`](super::Accordion)
//! which manages multiple panels, `Collapsible` is a standalone building block
//! that can be composed into larger layouts.
//!
//! The component renders a header with an expand/collapse indicator and an
//! optional bordered content area. The parent application is responsible for
//! rendering actual content into the area returned by
//! [`CollapsibleState::content_area()`].
//!
//! State is stored in [`CollapsibleState`], updated via [`CollapsibleMessage`],
//! and produces [`CollapsibleOutput`].
//!
//! Implements [`Toggleable`].
//!
//! # Example
//!
//! ```rust
//! use envision::component::{Collapsible, CollapsibleMessage, CollapsibleOutput, CollapsibleState, Component};
//!
//! let mut state = CollapsibleState::new("Details");
//!
//! // Toggle the section (collapses it, since default is expanded)
//! let output = Collapsible::update(&mut state, CollapsibleMessage::Toggle);
//! assert_eq!(output, Some(CollapsibleOutput::Toggled(false)));
//! assert!(!state.is_expanded());
//!
//! // Expand the section
//! let output = Collapsible::update(&mut state, CollapsibleMessage::Expand);
//! assert_eq!(output, Some(CollapsibleOutput::Expanded));
//! assert!(state.is_expanded());
//! ```

use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Paragraph};

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

/// Messages that can be sent to a Collapsible.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CollapsibleMessage {
    /// Toggle the expanded state.
    Toggle,
    /// Set expanded to true.
    Expand,
    /// Set expanded to false.
    Collapse,
    /// Change the header text.
    SetHeader(String),
    /// Change the content height.
    SetContentHeight(u16),
}

/// Output messages from a Collapsible.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CollapsibleOutput {
    /// The section was expanded.
    Expanded,
    /// The section was collapsed.
    Collapsed,
    /// The section was toggled to the given expanded state.
    Toggled(bool),
}

/// State for a Collapsible component.
///
/// # Example
///
/// ```rust
/// use envision::component::CollapsibleState;
///
/// let state = CollapsibleState::new("Settings")
///     .with_expanded(false)
///     .with_content_height(10);
/// assert_eq!(state.header(), "Settings");
/// assert!(!state.is_expanded());
/// assert_eq!(state.content_height(), 10);
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct CollapsibleState {
    /// The header text.
    header: String,
    /// Whether the content is visible.
    expanded: bool,
    /// Height to allocate for content when expanded.
    content_height: u16,
}

impl Default for CollapsibleState {
    fn default() -> Self {
        Self {
            header: String::new(),
            expanded: true,
            content_height: 5,
        }
    }
}

impl CollapsibleState {
    /// Creates a new collapsible with the given header text.
    ///
    /// The section starts expanded with a content height of 5.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    ///
    /// let state = CollapsibleState::new("Details");
    /// assert_eq!(state.header(), "Details");
    /// assert!(state.is_expanded());
    /// assert_eq!(state.content_height(), 5);
    /// ```
    pub fn new(header: impl Into<String>) -> Self {
        Self {
            header: header.into(),
            ..Default::default()
        }
    }

    /// Sets the initial expanded state (builder method).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    ///
    /// let state = CollapsibleState::new("Details").with_expanded(false);
    /// assert!(!state.is_expanded());
    /// ```
    pub fn with_expanded(mut self, expanded: bool) -> Self {
        self.expanded = expanded;
        self
    }

    /// Sets the content area height (builder method).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    ///
    /// let state = CollapsibleState::new("Details").with_content_height(10);
    /// assert_eq!(state.content_height(), 10);
    /// ```
    pub fn with_content_height(mut self, height: u16) -> Self {
        self.content_height = height;
        self
    }

    /// Returns the header text.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    ///
    /// let state = CollapsibleState::new("My Section");
    /// assert_eq!(state.header(), "My Section");
    /// ```
    pub fn header(&self) -> &str {
        &self.header
    }

    /// Sets the header text.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    ///
    /// let mut state = CollapsibleState::new("Old Header");
    /// state.set_header("New Header");
    /// assert_eq!(state.header(), "New Header");
    /// ```
    pub fn set_header(&mut self, header: impl Into<String>) {
        self.header = header.into();
    }

    /// Returns whether the section is expanded.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    ///
    /// let state = CollapsibleState::new("Details");
    /// assert!(state.is_expanded());
    /// ```
    pub fn is_expanded(&self) -> bool {
        self.expanded
    }

    /// Sets the expanded state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    ///
    /// let mut state = CollapsibleState::new("Details");
    /// state.set_expanded(false);
    /// assert!(!state.is_expanded());
    /// ```
    pub fn set_expanded(&mut self, expanded: bool) {
        self.expanded = expanded;
    }

    /// Toggles the expanded state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    ///
    /// let mut state = CollapsibleState::new("Details");
    /// assert!(state.is_expanded());
    /// state.toggle();
    /// assert!(!state.is_expanded());
    /// state.toggle();
    /// assert!(state.is_expanded());
    /// ```
    pub fn toggle(&mut self) {
        self.expanded = !self.expanded;
    }

    /// Returns the content area height.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    ///
    /// let state = CollapsibleState::new("Details").with_content_height(8);
    /// assert_eq!(state.content_height(), 8);
    /// ```
    pub fn content_height(&self) -> u16 {
        self.content_height
    }

    /// Sets the content area height.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    ///
    /// let mut state = CollapsibleState::new("Details");
    /// state.set_content_height(12);
    /// assert_eq!(state.content_height(), 12);
    /// ```
    pub fn set_content_height(&mut self, height: u16) {
        self.content_height = height;
    }

    /// Returns the content area `Rect` for rendering content below the header.
    ///
    /// When expanded, this returns the area below the header row, bounded by
    /// the available space and the configured `content_height`. When collapsed,
    /// returns a zero-height `Rect`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CollapsibleState;
    /// use ratatui::prelude::Rect;
    ///
    /// let state = CollapsibleState::new("Details").with_content_height(5);
    /// let area = Rect::new(0, 0, 40, 10);
    ///
    /// let content = state.content_area(area);
    /// assert_eq!(content.y, 1); // Below header
    /// assert_eq!(content.height, 5);
    ///
    /// let collapsed = CollapsibleState::new("Details").with_expanded(false);
    /// let content = collapsed.content_area(area);
    /// assert_eq!(content.height, 0);
    /// ```
    pub fn content_area(&self, area: Rect) -> Rect {
        if !self.expanded || area.height <= 1 {
            return Rect::new(
                area.x,
                area.y.saturating_add(1).min(area.bottom()),
                area.width,
                0,
            );
        }

        let available = area.height.saturating_sub(1);
        let height = self.content_height.min(available);

        Rect::new(area.x, area.y + 1, area.width, height)
    }

    /// Updates the collapsible state with a message, returning any output.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CollapsibleMessage, CollapsibleOutput, CollapsibleState};
    ///
    /// let mut state = CollapsibleState::new("Details");
    /// let output = state.update(CollapsibleMessage::Collapse);
    /// assert_eq!(output, Some(CollapsibleOutput::Collapsed));
    /// assert!(!state.is_expanded());
    /// ```
    pub fn update(&mut self, msg: CollapsibleMessage) -> Option<CollapsibleOutput> {
        Collapsible::update(self, msg)
    }
}

/// A collapsible component with an expandable content section.
///
/// The collapsible displays a header with an expand/collapse indicator. When
/// expanded, a bordered content area is shown below the header. The parent
/// application renders content into the area returned by
/// [`CollapsibleState::content_area()`].
///
/// # Keyboard Navigation
///
/// When focused:
/// - Space or Enter: toggle expanded state
/// - Right arrow: expand
/// - Left arrow: collapse
///
/// # Visual Layout
///
/// ```text
/// â–¾ Section Header          (expanded)
/// │ [content rendered by parent]
/// └─────────────────────
///
/// â–¸ Section Header          (collapsed)
/// ```
///
/// # Example
///
/// ```rust
/// use envision::component::{Collapsible, CollapsibleMessage, CollapsibleState, Component};
///
/// let mut state = CollapsibleState::new("Advanced Settings");
///
/// // Collapse
/// Collapsible::update(&mut state, CollapsibleMessage::Collapse);
/// assert!(!state.is_expanded());
///
/// // Expand
/// Collapsible::update(&mut state, CollapsibleMessage::Expand);
/// assert!(state.is_expanded());
/// ```
pub struct Collapsible;

impl Component for Collapsible {
    type State = CollapsibleState;
    type Message = CollapsibleMessage;
    type Output = CollapsibleOutput;

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

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            CollapsibleMessage::Toggle => {
                state.expanded = !state.expanded;
                Some(CollapsibleOutput::Toggled(state.expanded))
            }
            CollapsibleMessage::Expand => {
                if !state.expanded {
                    state.expanded = true;
                    Some(CollapsibleOutput::Expanded)
                } else {
                    None
                }
            }
            CollapsibleMessage::Collapse => {
                if state.expanded {
                    state.expanded = false;
                    Some(CollapsibleOutput::Collapsed)
                } else {
                    None
                }
            }
            CollapsibleMessage::SetHeader(header) => {
                state.header = header;
                None
            }
            CollapsibleMessage::SetContentHeight(height) => {
                state.content_height = height;
                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 key.code {
                Key::Char(' ') | Key::Enter => Some(CollapsibleMessage::Toggle),
                Key::Right => Some(CollapsibleMessage::Expand),
                Key::Left => Some(CollapsibleMessage::Collapse),
                _ => None,
            }
        } else {
            None
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        if ctx.area.height == 0 || ctx.area.width == 0 {
            return;
        }

        crate::annotation::with_registry(|reg| {
            reg.register(
                ctx.area,
                crate::annotation::Annotation::new(crate::annotation::WidgetType::Custom(
                    "Collapsible".to_string(),
                ))
                .with_id("collapsible")
                .with_focus(ctx.focused)
                .with_disabled(ctx.disabled)
                .with_expanded(state.expanded),
            );
        });

        let indicator = if state.expanded {
            "\u{25be}"
        } else {
            "\u{25b8}"
        };
        let header_text = format!("{} {}", indicator, state.header);

        let header_style = if ctx.disabled {
            ctx.theme.disabled_style()
        } else if ctx.focused {
            ctx.theme.focused_style()
        } else {
            ctx.theme.normal_style()
        };

        let header_line = Line::from(Span::styled(header_text, header_style));
        let header_area = Rect::new(ctx.area.x, ctx.area.y, ctx.area.width, 1);
        ctx.frame
            .render_widget(Paragraph::new(header_line), header_area);

        // Content ctx.area (below header) -- only render border when expanded
        if state.expanded && ctx.area.height > 1 {
            let available = ctx.area.height.saturating_sub(1);
            let content_h = state.content_height.min(available);

            if content_h > 0 {
                let content_area = Rect::new(ctx.area.x, ctx.area.y + 1, ctx.area.width, content_h);
                let border_style = if ctx.disabled {
                    ctx.theme.disabled_style()
                } else if ctx.focused {
                    ctx.theme.focused_border_style()
                } else {
                    ctx.theme.border_style()
                };
                let content_block = Block::default()
                    .borders(Borders::LEFT | Borders::BOTTOM)
                    .border_style(border_style);
                ctx.frame.render_widget(content_block, content_area);
            }
        }
    }
}

impl Toggleable for Collapsible {
    fn is_visible(state: &Self::State) -> bool {
        state.expanded
    }

    fn set_visible(state: &mut Self::State, visible: bool) {
        state.expanded = visible;
    }
}

#[cfg(test)]
mod tests;