termtui 0.1.0

A framework for building beautiful, responsive terminal user interfaces with a DOM-style hierarchical approach
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
use crate::app::Context;
use crate::buffer::{DoubleBuffer, ScreenBuffer};
use crate::component::{Action, Component, ComponentId};
use crate::node::Div;
use crate::node::Node;
use crate::terminal::TerminalRenderer;
use crate::vnode::VNode;
use crate::{Rect, VDom};
use crossterm::{
    ExecutableCommand, cursor,
    event::{self, Event},
    execute,
    style::{Print, ResetColor, SetBackgroundColor, SetForegroundColor},
    terminal,
};
use std::cell::RefCell;
use std::io;
use std::rc::Rc;

use super::config::RenderConfig;
use super::events::{handle_key_event, handle_mouse_event};
use super::renderer::render_node_to_buffer;
use std::collections::HashMap;

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// Type alias for the render log callback function.
type RenderLogFn = Box<dyn Fn(&str)>;

/// Signal to indicate that the application should exit.
/// Used to propagate exit requests through the component tree.
pub struct ExitSignal;

/// Main application controller for terminal UI applications.
///
/// Manages the lifecycle of a terminal application including:
/// - Terminal initialization and cleanup
/// - Event loop processing (keyboard, mouse, resize)
/// - Virtual DOM rendering and updates
/// - Model state management through init-view-update pattern
///
/// ## Application Flow
///
/// ```text
///     ┌─────────────┐
///     │   App::new  │ ← Initialize terminal, enable raw mode
///     └──────┬──────┘
/////////     ┌─────────────┐
///     │  App::run   │ ← Start event loop with root model
///     └──────┬──────┘
/////////    ┌───────────────┐
///    │  Event Loop   │ ◄─┐
///    └───────┬───────┘   │
///            │           │
///     ┌──────▼──────┐    │
///     │   Render    │    │
///     │   Model     │    │
///     └──────┬──────┘    │
///            │           │
///     ┌──────▼──────┐    │
///     │ Update VDom │    │
///     └──────┬──────┘    │
///            │           │
///     ┌──────▼──────┐    │
///     │    Draw     │    │
///     │  Terminal   │    │
///     └──────┬──────┘    │
///            │           │
///     ┌──────▼──────┐    │
///     │Handle Events│────┘
///     └─────────────┘
/// ```
pub struct App {
    /// Virtual DOM instance that manages the UI tree
    vdom: VDom,

    /// Shared flag to control the application lifecycle
    running: Rc<RefCell<bool>>,

    /// Flag indicating whether a render is needed
    needs_render: Rc<RefCell<bool>>,

    /// Double buffer for flicker-free rendering
    double_buffer: DoubleBuffer,

    /// Optional function to call after each render for logging
    render_log_fn: Option<RenderLogFn>,

    /// Terminal renderer for optimized output
    terminal_renderer: TerminalRenderer,

    /// Rendering configuration for debugging and optimization control
    config: RenderConfig,
}

//--------------------------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------------------------

impl App {
    /// Creates a new terminal UI application.
    ///
    /// Initializes the terminal by:
    /// - Enabling raw mode for character-by-character input
    /// - Switching to alternate screen buffer
    /// - Hiding the cursor
    /// - Enabling mouse capture for click events
    ///
    /// The terminal state is automatically restored when the app is dropped.
    pub fn new() -> io::Result<Self> {
        terminal::enable_raw_mode()?;
        let mut stdout = io::stdout();

        // Try to enable keyboard enhancement for better modifier support
        // This may not work on all terminals, so we ignore errors
        // Note: We're temporarily disabling this as it causes issues with terminal cleanup
        // use crossterm::event::{KeyboardEnhancementFlags, PushKeyboardEnhancementFlags};
        // let _ = stdout.execute(PushKeyboardEnhancementFlags(
        //     KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
        //         | KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES,
        // ));

        stdout.execute(terminal::EnterAlternateScreen)?;
        stdout.execute(cursor::Hide)?;
        stdout.execute(event::EnableMouseCapture)?;

        let running = Rc::new(RefCell::new(true));
        let needs_render = Rc::new(RefCell::new(true));

        // Get initial terminal size for double buffer
        let (width, height) = terminal::size()?;

        Ok(Self {
            vdom: VDom::new(),
            running,
            needs_render,
            double_buffer: DoubleBuffer::new(width, height),
            render_log_fn: None,
            terminal_renderer: TerminalRenderer::new(),
            config: RenderConfig::default(),
        })
    }

    /// Runs the application with a component instance.
    ///
    /// This uses the component system that provides:
    /// - Component-based architecture
    /// - Message-driven state updates
    /// - Tree expansion from components to VNodes
    ///
    /// ## Example
    /// ```rust,ignore
    /// let mut app = App::new()?;
    /// let root = MyRootComponent::new();
    /// app.run(root)?;
    /// ```
    ///
    /// This method blocks until the application exits.
    pub fn run<C>(&mut self, root_component: C) -> io::Result<()>
    where
        C: Component + Clone,
    {
        self.run_loop(root_component)
    }

    /// Sets the render configuration for debugging and optimization control.
    pub fn render_config(mut self, config: RenderConfig) -> Self {
        self.config = config;
        self
    }

    /// Disables all rendering optimizations for debugging.
    /// This is equivalent to calling all disable_* methods.
    pub fn disable_all_optimizations(mut self) -> Self {
        self.config = RenderConfig::debug();
        self
    }

    /// Disables double buffering, causing direct terminal rendering.
    /// Warning: This may cause visible flicker during updates.
    pub fn disable_double_buffering(mut self) -> Self {
        self.config.double_buffering = false;
        self
    }

    /// Disables terminal-specific optimizations.
    /// This uses simpler, more compatible terminal commands.
    pub fn disable_terminal_optimizations(mut self) -> Self {
        self.config.terminal_optimizations = false;
        self
    }

    /// Disables cell-level diffing.
    /// This causes the entire screen to be redrawn on each update.
    pub fn disable_cell_diffing(mut self) -> Self {
        self.config.cell_diffing = false;
        self
    }

    /// Main event loop using component-based architecture.
    ///
    /// Manages component state through messages and actions,
    /// expanding component trees into VNode trees for rendering.
    ///
    /// Only renders when:
    /// 1. Initial render
    /// 2. Messages are processed and state changes
    /// 3. External events trigger render
    /// 4. Terminal is resized
    fn run_loop<C>(&mut self, root_component: C) -> io::Result<()>
    where
        C: Component + Clone,
    {
        let mut context = Context::new();
        let mut components: HashMap<ComponentId, Box<dyn Component>> = HashMap::new();

        // Store the root component
        let root_id = ComponentId::default();
        components.insert(
            root_id.clone(),
            Box::new(root_component) as Box<dyn Component>,
        );

        let mut needs_render = true; // Initial render

        while *self.running.borrow() {
            // Messages are now processed during tree expansion, not here

            // Expand component tree to VNode tree
            let vnode_tree = if let Some(root_component) = components.get(&root_id) {
                context.current_component_id = root_id.clone();
                // Create a temporary clone of components to avoid borrow issues
                let mut temp_components = HashMap::new();

                // Expand the tree, processing messages and handling exit signals
                match self.expand_component_tree(
                    root_component.as_ref(),
                    &mut context,
                    &mut temp_components,
                ) {
                    Ok(vnode) => {
                        // Merge temp_components back into main components map
                        // This is critical for nested components to receive messages
                        components.extend(temp_components);
                        vnode
                    }
                    Err(ExitSignal) => {
                        *self.running.borrow_mut() = false;
                        break;
                    }
                }
            } else {
                VNode::div()
            };

            // Render if needed
            if needs_render || *self.needs_render.borrow() {
                // Render VNode tree
                self.vdom.render(vnode_tree);

                let (width, height) = terminal::size()?;
                self.vdom.layout(width, height);

                self.draw()?;

                // Log render tree if callback is set
                if let Some(log_fn) = &self.render_log_fn {
                    let debug_string = self.render_tree_debug_string();
                    log_fn(&debug_string);
                }

                // Clear render flags
                *self.needs_render.borrow_mut() = false;
                needs_render = false;
            }

            // Poll for events with a shorter timeout since we're not rendering constantly
            if event::poll(std::time::Duration::from_millis(100))? {
                match event::read()? {
                    Event::Key(key_event) => {
                        handle_key_event(&self.vdom, key_event);
                        // Key events may have triggered messages via event handlers
                        needs_render = true;
                    }
                    Event::Mouse(mouse_event) => {
                        handle_mouse_event(&self.vdom, mouse_event);
                        // Mouse events may have triggered messages via event handlers
                        needs_render = true;
                    }
                    Event::Resize(width, height) => {
                        self.vdom.layout(width, height);
                        self.double_buffer.resize(width, height);
                        *self.needs_render.borrow_mut() = true;
                    }
                    _ => {}
                }
            }
        }

        Ok(())
    }

    /// Expands a component tree into a VNode tree recursively
    fn expand_component_tree(
        &self,
        component: &dyn Component,
        context: &mut Context,
        components: &mut HashMap<ComponentId, Box<dyn Component>>,
    ) -> Result<VNode, ExitSignal> {
        // Process all pending messages (regular, owned topics, and unassigned topics)
        let messages = context.drain_all_messages();
        for (msg, topic) in messages {
            let action = component.update(context, msg, topic.as_deref());

            match action {
                Action::Update(new_state) => {
                    context
                        .states
                        .insert(context.current_component_id.clone(), new_state);

                    // If this was an unassigned topic message and we handled it, claim the topic
                    if let Some(topic_name) = topic
                        && context
                            .topics
                            .claim_topic(topic_name.clone(), context.current_component_id.clone())
                    {
                        // We just claimed this topic, drain its remaining messages
                        context.drain_topic_if_claimed(&topic_name, &context.current_component_id);
                    }
                }
                Action::UpdateTopic(topic_name, new_state) => {
                    // Update topic state (idempotent - first writer becomes owner)
                    context.topics.update_topic(
                        topic_name.clone(),
                        new_state,
                        context.current_component_id.clone(),
                    );

                    // If this was an unassigned topic message for the same topic, drain it
                    if let Some(msg_topic) = topic
                        && msg_topic == topic_name
                    {
                        context.drain_topic_if_claimed(&topic_name, &context.current_component_id);
                    }
                }
                Action::Exit => {
                    return Err(ExitSignal);
                }
                Action::None => {
                    // Component didn't handle this message, leave topic unassigned
                }
            }
        }

        // Get the node from the component's view
        let node = component.view(context);

        // Convert Node to VNode, expanding any nested components
        self.node_to_vnode(node, context, components, 0)
    }

    /// Converts a Node to a VNode, expanding components recursively
    fn node_to_vnode(
        &self,
        node: Node,
        context: &mut Context,
        components: &mut HashMap<ComponentId, Box<dyn Component>>,
        child_index: usize,
    ) -> Result<VNode, ExitSignal> {
        match node {
            Node::Component(mut component) => {
                // Update context for this component
                let parent_id = context.current_component_id.clone();
                context.current_component_id = parent_id.child(child_index);

                // Store component in the map
                let component_id = context.current_component_id.clone();
                component.set_id(component_id.clone());

                // Expand the component recursively, propagating any exit signal
                let vnode = self.expand_component_tree(component.as_ref(), context, components)?;

                // Store the component for future updates
                components.insert(component_id, component);

                // Restore parent context
                context.current_component_id = parent_id;

                Ok(vnode)
            }
            Node::Div(div) => {
                // Convert div children
                let mut vnode_children = Vec::new();
                for (i, child) in div.children.into_iter().enumerate() {
                    // Propagate any exit signal from children
                    vnode_children.push(self.node_to_vnode(child, context, components, i)?);
                }

                // Create VNode div with converted children
                let mut vnode_div = Div::new();
                vnode_div.children = vnode_children;

                // Copy over the style and event properties
                vnode_div.styles = div.styles;
                vnode_div.events = div.events;
                vnode_div.focusable = div.focusable;
                vnode_div.focused = div.focused;

                Ok(VNode::Div(vnode_div))
            }
            Node::Text(text) => {
                // Text nodes are directly converted
                Ok(VNode::Text(text))
            }
            Node::RichText(rich) => {
                // RichText nodes are directly converted
                Ok(VNode::RichText(rich))
            }
        }
    }

    /// Returns a debug string representation of the current render tree.
    ///
    /// This is useful for debugging and logging the UI structure.
    pub fn render_tree_debug_string(&self) -> String {
        self.vdom.get_render_tree().debug_string()
    }

    /// Sets a callback function to be called after each render with the render tree debug string.
    ///
    /// This is useful for logging the render tree state for debugging purposes.
    pub fn set_render_log_fn<F: Fn(&str) + 'static>(&mut self, log_fn: F) {
        self.render_log_fn = Some(Box::new(log_fn));
    }

    /// Renders the current UI tree to the terminal using double buffering.
    ///
    /// This completely eliminates flicker by:
    /// 1. Rendering to a memory buffer
    /// 2. Diffing against the previous frame
    /// 3. Only updating cells that changed
    fn draw(&mut self) -> io::Result<()> {
        if self.config.double_buffering {
            // Use double buffering for flicker-free rendering
            self.draw_with_double_buffer()
        } else {
            // Direct rendering for debugging
            self.draw_direct()
        }
    }

    /// Draws using double buffering and cell diffing for optimal performance.
    fn draw_with_double_buffer(&mut self) -> io::Result<()> {
        // Clear the back buffer
        self.double_buffer.clear_back();

        // Render the tree to the back buffer
        if let Some(root) = &self.vdom.get_render_tree().root {
            let root_ref = root.borrow();
            let buffer = self.double_buffer.back_buffer_mut();
            let (width, height) = buffer.dimensions();
            let clip_rect = Rect::new(0, 0, width, height);
            render_node_to_buffer(&root_ref, buffer, &clip_rect, None);
        }

        if self.config.cell_diffing {
            // Diff the buffers to find changes
            let updates = self.double_buffer.diff();

            // Apply updates to terminal
            if self.config.terminal_optimizations {
                self.terminal_renderer.apply_updates(updates)?;
            } else {
                // Apply updates without optimizations
                self.terminal_renderer.apply_updates_direct(updates)?;
            }
        } else {
            // Redraw entire screen without diffing
            let buffer = self.double_buffer.back_buffer_mut();
            self.terminal_renderer.draw_full_buffer(buffer)?;
        }

        // Swap buffers for next frame
        self.double_buffer.swap();

        // Clear all dirty flags after drawing
        self.vdom.get_render_tree().clear_all_dirty();

        Ok(())
    }

    /// Draws directly to terminal without double buffering (for debugging).
    fn draw_direct(&mut self) -> io::Result<()> {
        // Clear screen
        execute!(io::stdout(), terminal::Clear(terminal::ClearType::All))?;

        // Create a temporary buffer for direct rendering
        let (width, height) = terminal::size()?;
        let mut buffer = ScreenBuffer::new(width, height);

        // Render the tree to the temporary buffer
        if let Some(root) = &self.vdom.get_render_tree().root {
            let root_ref = root.borrow();
            let clip_rect = Rect::new(0, 0, width, height);
            render_node_to_buffer(&root_ref, &mut buffer, &clip_rect, None);
        }

        // Draw each cell directly to terminal
        let mut stdout = io::stdout();
        for y in 0..height {
            for x in 0..width {
                if let Some(cell) = buffer.get_cell(x, y) {
                    execute!(stdout, cursor::MoveTo(x, y))?;

                    // Set colors if present
                    if let Some(fg) = &cell.fg {
                        execute!(
                            stdout,
                            SetForegroundColor(self.terminal_renderer.color_to_crossterm(*fg))
                        )?;
                    }
                    if let Some(bg) = &cell.bg {
                        execute!(
                            stdout,
                            SetBackgroundColor(self.terminal_renderer.color_to_crossterm(*bg))
                        )?;
                    }

                    // Print character
                    execute!(stdout, Print(cell.char))?;

                    // Reset colors
                    if cell.fg.is_some() || cell.bg.is_some() {
                        execute!(stdout, ResetColor)?;
                    }
                }
            }
        }

        // Clear all dirty flags after drawing
        self.vdom.get_render_tree().clear_all_dirty();

        Ok(())
    }
}

//--------------------------------------------------------------------------------------------------
// Trait Implementations
//--------------------------------------------------------------------------------------------------

/// Cleanup handler that restores terminal state on application exit.
///
/// Automatically:
/// - Disables mouse capture
/// - Shows the cursor
/// - Returns to main screen buffer
/// - Disables raw mode
impl Drop for App {
    fn drop(&mut self) {
        // Note: PopKeyboardEnhancementFlags is commented out since we're not pushing them
        // use crossterm::event::PopKeyboardEnhancementFlags;
        use std::io::Write;

        let mut stdout = io::stdout();

        // Pop keyboard enhancement flags if they were enabled
        // let _ = stdout.execute(PopKeyboardEnhancementFlags);

        // Restore terminal state
        let _ = stdout.execute(event::DisableMouseCapture);
        let _ = stdout.execute(cursor::Show);
        let _ = stdout.execute(terminal::LeaveAlternateScreen);

        // Flush to ensure all commands are sent before disabling raw mode
        let _ = stdout.flush();

        // Finally disable raw mode
        let _ = terminal::disable_raw_mode();
    }
}