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
//! A markdown rendering component with scroll support.
//!
//! [`MarkdownRenderer`] parses a markdown string using pulldown-cmark and
//! renders the result as styled terminal output with headings, inline
//! formatting, code blocks, lists, links, blockquotes, and horizontal rules.
//!
//! State is stored in [`MarkdownRendererState`], updated via
//! [`MarkdownRendererMessage`], and produces no output (unit `()`).
//!
//!
//! # Feature Gate
//!
//! This component requires the `markdown` feature.
//!
//! # Example
//!
//! ```rust
//! use envision::component::{
//!     Component, MarkdownRenderer, MarkdownRendererState,
//!     MarkdownRendererMessage,
//! };
//!
//! let mut state = MarkdownRendererState::new()
//!     .with_source("# Hello\n\nSome **bold** text.")
//!     .with_title("Preview");
//!
//! assert_eq!(state.source(), "# Hello\n\nSome **bold** text.");
//! assert_eq!(state.title(), Some("Preview"));
//! assert_eq!(state.scroll_offset(), 0);
//! assert!(!state.show_source());
//! ```

pub mod render;

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

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

/// Messages that can be sent to a [`MarkdownRenderer`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum MarkdownRendererMessage {
    /// Scroll up by one line.
    ScrollUp,
    /// Scroll down by one line.
    ScrollDown,
    /// Scroll up by a page (given number of lines).
    PageUp(usize),
    /// Scroll down by a page (given number of lines).
    PageDown(usize),
    /// Scroll to the top.
    Home,
    /// Scroll to the bottom.
    End,
    /// Replace the markdown source.
    SetSource(String),
    /// Toggle between rendered markdown and raw source views.
    ToggleSource,
}

/// State for a [`MarkdownRenderer`] component.
///
/// Contains the markdown source, scroll position, and display options.
///
/// # Example
///
/// ```rust
/// use envision::component::MarkdownRendererState;
///
/// let state = MarkdownRendererState::new()
///     .with_source("# Title\n\nBody text.")
///     .with_title("Document");
///
/// assert_eq!(state.source(), "# Title\n\nBody text.");
/// assert_eq!(state.title(), Some("Document"));
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct MarkdownRendererState {
    /// The markdown source text.
    source: String,
    /// Scroll state tracking offset and providing scrollbar support.
    scroll: ScrollState,
    /// Optional title for the border.
    title: Option<String>,
    /// Whether to show raw source instead of rendered markdown.
    show_source: bool,
}

impl MarkdownRendererState {
    /// Creates a new empty markdown renderer state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let state = MarkdownRendererState::new();
    /// assert!(state.source().is_empty());
    /// assert_eq!(state.scroll_offset(), 0);
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the markdown source (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let state = MarkdownRendererState::new()
    ///     .with_source("# Hello");
    /// assert_eq!(state.source(), "# Hello");
    /// ```
    pub fn with_source(mut self, source: impl Into<String>) -> Self {
        self.source = source.into();
        self.scroll
            .set_content_length(self.source.lines().count().max(1));
        self
    }

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

    /// Sets the show_source flag (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let state = MarkdownRendererState::new()
    ///     .with_show_source(true);
    /// assert!(state.show_source());
    /// ```
    pub fn with_show_source(mut self, show: bool) -> Self {
        self.show_source = show;
        self
    }

    // ---- Source accessors ----

    /// Returns the markdown source text.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let state = MarkdownRendererState::new()
    ///     .with_source("hello");
    /// assert_eq!(state.source(), "hello");
    /// ```
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Sets the markdown source text and resets scroll to the top.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let mut state = MarkdownRendererState::new();
    /// state.set_source("# New");
    /// assert_eq!(state.source(), "# New");
    /// assert_eq!(state.scroll_offset(), 0);
    /// ```
    pub fn set_source(&mut self, source: impl Into<String>) {
        self.source = source.into();
        self.scroll = ScrollState::new(self.source.lines().count().max(1));
    }

    /// Returns the title.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let state = MarkdownRendererState::new()
    ///     .with_title("Title");
    /// assert_eq!(state.title(), Some("Title"));
    /// ```
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Sets the title.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let mut state = MarkdownRendererState::new();
    /// state.set_title(Some("Document".to_string()));
    /// assert_eq!(state.title(), Some("Document"));
    /// ```
    pub fn set_title(&mut self, title: Option<String>) {
        self.title = title;
    }

    // ---- Display options ----

    /// Returns whether the raw source view is active.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let state = MarkdownRendererState::new();
    /// assert!(!state.show_source());
    /// ```
    pub fn show_source(&self) -> bool {
        self.show_source
    }

    /// Sets whether to show raw source.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let mut state = MarkdownRendererState::new();
    /// state.set_show_source(true);
    /// assert!(state.show_source());
    /// ```
    pub fn set_show_source(&mut self, show: bool) {
        self.show_source = show;
    }

    // ---- Scroll accessors ----

    /// Returns the current scroll offset.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let state = MarkdownRendererState::new();
    /// assert_eq!(state.scroll_offset(), 0);
    /// ```
    pub fn scroll_offset(&self) -> usize {
        self.scroll.offset()
    }

    /// Sets the scroll offset.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::MarkdownRendererState;
    ///
    /// let mut state = MarkdownRendererState::new()
    ///     .with_source("line1\nline2\nline3\nline4\nline5");
    /// state.set_scroll_offset(2);
    /// assert_eq!(state.scroll_offset(), 2);
    /// ```
    pub fn set_scroll_offset(&mut self, offset: usize) {
        self.scroll.set_offset(offset);
    }

    // ---- State accessors ----

    // ---- Instance methods ----

    /// Updates the state with a message.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{MarkdownRendererState, MarkdownRendererMessage};
    ///
    /// let mut state = MarkdownRendererState::new()
    ///     .with_source("line 1\nline 2");
    /// state.update(MarkdownRendererMessage::ScrollDown);
    /// assert_eq!(state.scroll_offset(), 1);
    /// ```
    pub fn update(&mut self, msg: MarkdownRendererMessage) {
        MarkdownRenderer::update(self, msg);
    }
}

/// A markdown rendering component with scroll support.
///
/// Parses markdown source text and renders it with styled headings, bold,
/// italic, strikethrough, inline code, code blocks, lists, links,
/// blockquotes, and horizontal rules. Supports toggling between rendered
/// and raw source views.
///
/// # Key Bindings
///
/// - `Up` / `k` -- Scroll up one line
/// - `Down` / `j` -- Scroll down one line
/// - `PageUp` / `Ctrl+u` -- Scroll up half a page
/// - `PageDown` / `Ctrl+d` -- Scroll down half a page
/// - `Home` / `g` -- Scroll to top
/// - `End` / `G` -- Scroll to bottom
/// - `s` -- Toggle between rendered and raw source views
///
/// # Example
///
/// ```rust
/// use envision::component::{Component, MarkdownRenderer, MarkdownRendererState};
///
/// let state = MarkdownRendererState::new()
///     .with_source("# Hello\n\nWorld");
/// assert_eq!(state.source(), "# Hello\n\nWorld");
/// ```
pub struct MarkdownRenderer;

impl Component for MarkdownRenderer {
    type State = MarkdownRendererState;
    type Message = MarkdownRendererMessage;
    type Output = ();

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

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

        let key = event.as_key()?;
        let ctrl = key.modifiers.ctrl();
        let shift = key.modifiers.shift();

        match key.code {
            Key::Up | Key::Char('k') if !ctrl => Some(MarkdownRendererMessage::ScrollUp),
            Key::Down | Key::Char('j') if !ctrl => Some(MarkdownRendererMessage::ScrollDown),
            Key::PageUp => Some(MarkdownRendererMessage::PageUp(10)),
            Key::PageDown => Some(MarkdownRendererMessage::PageDown(10)),
            Key::Char('u') if ctrl => Some(MarkdownRendererMessage::PageUp(10)),
            Key::Char('d') if ctrl => Some(MarkdownRendererMessage::PageDown(10)),
            Key::Char('g') if key.modifiers.shift() => Some(MarkdownRendererMessage::End),
            Key::Home | Key::Char('g') => Some(MarkdownRendererMessage::Home),
            Key::End => Some(MarkdownRendererMessage::End),
            Key::Char('s') if !ctrl && !shift => Some(MarkdownRendererMessage::ToggleSource),
            _ => None,
        }
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            MarkdownRendererMessage::ScrollUp => {
                state.scroll.scroll_up();
            }
            MarkdownRendererMessage::ScrollDown => {
                state.scroll.scroll_down();
            }
            MarkdownRendererMessage::PageUp(n) => {
                state.scroll.page_up(n);
            }
            MarkdownRendererMessage::PageDown(n) => {
                state.scroll.page_down(n);
            }
            MarkdownRendererMessage::Home => {
                state.scroll.scroll_to_start();
            }
            MarkdownRendererMessage::End => {
                state.scroll.scroll_to_end();
            }
            MarkdownRendererMessage::SetSource(source) => {
                state.source = source;
                state.scroll = ScrollState::new(state.source.lines().count().max(1));
            }
            MarkdownRendererMessage::ToggleSource => {
                state.show_source = !state.show_source;
                // Reset scroll when switching views
                state.scroll.set_offset(0);
            }
        }
        None
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        crate::annotation::with_registry(|reg| {
            reg.register(
                ctx.area,
                crate::annotation::Annotation::new(crate::annotation::WidgetType::Custom(
                    "MarkdownRenderer".to_string(),
                ))
                .with_id("markdown_renderer")
                .with_focus(ctx.focused)
                .with_disabled(ctx.disabled),
            );
        });

        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 mut block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style);

        if let Some(title) = &state.title {
            let suffix = if state.show_source { " [source]" } else { "" };
            block = block.title(format!("{}{}", title, suffix));
        }

        let inner = block.inner(ctx.area);
        ctx.frame.render_widget(block, ctx.area);

        if inner.height == 0 || inner.width == 0 {
            return;
        }

        if state.show_source {
            // Raw source view
            let text_style = if ctx.disabled {
                ctx.theme.disabled_style()
            } else {
                ctx.theme.normal_style()
            };

            let total_lines = crate::util::wrapped_line_count(&state.source, inner.width as usize);
            let visible = inner.height as usize;
            let max_scroll = total_lines.saturating_sub(visible);
            let effective_scroll = state.scroll.offset().min(max_scroll);

            let paragraph = Paragraph::new(state.source.as_str())
                .style(text_style)
                .wrap(Wrap { trim: false })
                .scroll((effective_scroll as u16, 0));

            ctx.frame.render_widget(paragraph, inner);

            if total_lines > visible {
                let mut bar_scroll = ScrollState::new(total_lines);
                bar_scroll.set_viewport_height(visible);
                bar_scroll.set_offset(effective_scroll);
                crate::scroll::render_scrollbar_inside_border(
                    &bar_scroll,
                    ctx.frame,
                    ctx.area,
                    ctx.theme,
                );
            }
        } else {
            // Rendered markdown view
            let rendered_lines = render::render_markdown(&state.source, inner.width, ctx.theme);
            let total_lines = rendered_lines.len();
            let visible = inner.height as usize;
            let max_scroll = total_lines.saturating_sub(visible);
            let effective_scroll = state.scroll.offset().min(max_scroll);

            let text = Text::from(rendered_lines);
            let paragraph = Paragraph::new(text)
                .wrap(Wrap { trim: false })
                .scroll((effective_scroll as u16, 0));

            ctx.frame.render_widget(paragraph, inner);

            if total_lines > visible {
                let mut bar_scroll = ScrollState::new(total_lines);
                bar_scroll.set_viewport_height(visible);
                bar_scroll.set_offset(effective_scroll);
                crate::scroll::render_scrollbar_inside_border(
                    &bar_scroll,
                    ctx.frame,
                    ctx.area,
                    ctx.theme,
                );
            }
        }
    }
}

#[cfg(test)]
mod tests;