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
//! Virtual DOM implementation for efficient UI updates.
//!
//! The Virtual DOM (VDom) is the core of the reactive rendering system.
//! It maintains the current UI state, performs diffing, and applies patches
//! to update the render tree efficiently.
//!
//! ## Virtual DOM Architecture
//!
//! ```text
//!   Model Render                  VDom Processing
//!   ┌─────────────┐            ┌──────────────┐
//!   │  New Node   │───render──▶│     VDom     │
//!   │    Tree     │            └──────┬───────┘
//!   └─────────────┘                   │
//!//!                               ┌──────────────┐
//!                               │  Diff with   │
//!                               │Current State │
//!                               └──────┬───────┘
//!//!//!                               ┌──────────────┐
//!                               │   Generate   │
//!                               │   Patches    │
//!                               └──────┬───────┘
//!//!//!                               ┌──────────────┐
//!                               │Apply Patches │
//!                               │to RenderTree │
//!                               └──────────────┘
//! ```
//!
//! ## Update Flow
//!
//! 1. Model renders new Node tree
//! 2. VDom diffs new tree against current tree
//! 3. Diff generates minimal set of patches
//! 4. Patches are applied to update render tree
//! 5. Render tree is drawn to terminal

use crate::diff::{Patch, diff};
use crate::render_tree::{RenderNode, RenderNodeType, RenderTree};
use crate::utils::display_width;
use crate::vnode::VNode;
use std::cell::RefCell;
use std::rc::Rc;

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

/// Virtual DOM manager that coordinates rendering and updates.
///
/// Maintains the current virtual node tree and render tree,
/// performing efficient updates through diffing and patching.
pub struct VDom {
    /// The render tree containing positioned nodes ready for drawing
    render_tree: RenderTree,

    /// The current vnode tree representing the UI state
    current_vnode: Option<VNode>,
}

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

impl VDom {
    /// Creates a new empty virtual DOM.
    pub fn new() -> Self {
        Self {
            render_tree: RenderTree::new(),
            current_vnode: None,
        }
    }

    /// Renders a new node tree, updating the UI efficiently.
    ///
    /// This method:
    /// 1. Diffs the new tree against the current render tree
    /// 2. Generates patches for changes
    /// 3. Applies patches to update the render tree
    /// 4. Stores the new node as current state
    ///
    /// ## First Render vs Updates
    ///
    /// ```text
    /// First Render:           Subsequent Renders:
    /// ┌─────────┐           ┌─────────┐
    /// │  Node   │           │  Node   │
    /// └────┬────┘           └────┬────┘
    ///      │                     │
    ///      ▼                     ▼
    /// Create Full           Diff & Patch
    /// RenderTree            RenderTree
    /// ```
    pub fn render(&mut self, vnode: VNode) {
        match &self.render_tree.root {
            Some(root) => {
                let patches = diff(root, &vnode);
                self.apply_patches(patches);
            }
            None => {
                let render_node = self.create_render_node(&vnode);
                self.render_tree.set_root(render_node);
            }
        }
        self.current_vnode = Some(vnode);
    }

    /// Performs layout calculation on the render tree.
    ///
    /// Calculates positions and sizes for all nodes based on
    /// the viewport dimensions and layout rules.
    pub fn layout(&mut self, width: u16, height: u16) {
        self.render_tree.layout(width, height);
    }

    /// Gets a reference to the current render tree.
    ///
    /// Used by the App to access the tree for drawing and event handling.
    pub fn get_render_tree(&self) -> &RenderTree {
        &self.render_tree
    }

    /// Creates a render node from a node.
    ///
    /// Recursively converts the node tree into render nodes
    /// with styling and event handlers attached.
    fn create_render_node(&self, vnode: &VNode) -> Rc<RefCell<RenderNode>> {
        match vnode {
            VNode::Div(container) => self.create_div_node(container),
            VNode::Text(text) => self.create_text_node(text),
            VNode::RichText(rich) => self.create_rich_text_node(rich),
        }
    }

    /// Creates a render node for a div.
    ///
    /// Transfers all properties from the div including:
    /// - Style (colors, padding, direction)
    /// - Dimensions (width, height)
    /// - Event handlers (click, keyboard)
    /// - Child nodes (recursively created)
    fn create_div_node(&self, div: &crate::node::Div<VNode>) -> Rc<RefCell<RenderNode>> {
        // Create a standard element render node
        let mut render_node = RenderNode::element();

        // Apply the correct style based on focus state
        let effective_style = if div.focused {
            // For focused elements, merge: base -> default focus -> custom focus
            let default_focus = if div.focusable {
                Some(crate::style::Style::default_focus())
            } else {
                None
            };

            let focus_with_defaults =
                crate::style::Style::merge(default_focus, div.styles.focus.clone());
            crate::style::Style::merge(div.styles.base.clone(), focus_with_defaults)
        } else {
            div.styles.base.clone()
        };

        if let Some(style) = effective_style {
            // Extract dimensions from style before moving it
            match style.width {
                Some(crate::style::Dimension::Fixed(width)) => {
                    render_node.width = width;
                }
                Some(crate::style::Dimension::Percentage(_)) => {
                    // Percentage will be resolved during layout
                    // Keep width as 0 to indicate it needs resolution
                }
                Some(crate::style::Dimension::Auto) => {
                    // Auto will be resolved during layout
                    // Keep width as 0 to indicate it needs resolution
                }
                Some(crate::style::Dimension::Content) => {
                    // Content will be resolved during layout
                    // Keep width as 0 to indicate it needs resolution
                }
                None => {}
            }

            match style.height {
                Some(crate::style::Dimension::Fixed(height)) => {
                    render_node.height = height;
                }
                Some(crate::style::Dimension::Percentage(_)) => {
                    // Percentage will be resolved during layout
                    // Keep height as 0 to indicate it needs resolution
                }
                Some(crate::style::Dimension::Auto) => {
                    // Auto will be resolved during layout
                    // Keep height as 0 to indicate it needs resolution
                }
                Some(crate::style::Dimension::Content) => {
                    // Content will be resolved during layout
                    // Keep height as 0 to indicate it needs resolution
                }
                None => {}
            }

            // Extract positioning and z-index
            render_node.position_type = style.position.unwrap_or(crate::style::Position::Relative);
            render_node.z_index = style.z_index.unwrap_or(0);

            // Now assign the style after we're done extracting values from it
            render_node.style = Some(style);
        }

        // Copy div properties to render node
        render_node.styles = div.styles.clone();
        render_node.events = div.events.clone();
        render_node.focusable = div.focusable;
        render_node.focused = div.focused;

        let node_rc = Rc::new(RefCell::new(render_node));

        // Process div children
        for child_vnode in &div.children {
            let child_render = match child_vnode {
                VNode::Text(text) => {
                    let mut text_node = RenderNode::text(&text.content);
                    text_node.width = display_width(&text.content) as u16;
                    text_node.height = 1;
                    // Apply text-specific style
                    if let Some(ts) = &text.style {
                        text_node.text_color = ts.color;
                        text_node.text_style = Some(ts.clone());
                        text_node.style = ts.background.map(|bg| crate::style::Style {
                            background: Some(bg),
                            ..Default::default()
                        });
                    }
                    Rc::new(RefCell::new(text_node))
                }
                VNode::RichText(rich) => {
                    let mut rich_node =
                        RenderNode::new(RenderNodeType::RichText(rich.spans.clone()));
                    rich_node.width = rich
                        .spans
                        .iter()
                        .map(|span| display_width(&span.content) as u16)
                        .sum();
                    rich_node.height = 1;

                    // Apply top-level text style if present (for wrapping, etc)
                    if let Some(ts) = &rich.style {
                        rich_node.text_style = Some(ts.clone());
                        // Extract common color if all spans have the same
                        if !rich.spans.is_empty() {
                            let first_color = rich.spans[0].style.as_ref().and_then(|s| s.color);
                            if rich.spans.iter().all(|span| {
                                span.style.as_ref().and_then(|s| s.color) == first_color
                            }) {
                                rich_node.text_color = first_color;
                            }
                        }
                    }

                    Rc::new(RefCell::new(rich_node))
                }
                VNode::Div(_) => self.create_render_node(child_vnode),
            };
            RenderNode::add_child_with_parent(&node_rc, child_render);
        }

        node_rc
    }

    /// Creates a render node for text content.
    ///
    /// Text nodes are leaf nodes that contain string content.
    fn create_text_node(&self, text: &crate::node::Text) -> Rc<RefCell<RenderNode>> {
        let mut render_node = RenderNode::text(&text.content);
        // Set proper dimensions for text nodes
        render_node.width = display_width(&text.content) as u16;
        render_node.height = 1;
        // Apply text-specific style
        if let Some(ts) = &text.style {
            render_node.text_color = ts.color;
            render_node.text_style = Some(ts.clone());
            render_node.style = ts.background.map(|bg| crate::style::Style {
                background: Some(bg),
                ..Default::default()
            });
        }
        Rc::new(RefCell::new(render_node))
    }

    /// Creates a render node for styled text content.
    ///
    /// RichText nodes contain multiple text spans with individual styling.
    fn create_rich_text_node(&self, rich: &crate::node::RichText) -> Rc<RefCell<RenderNode>> {
        let mut render_node = RenderNode::new(RenderNodeType::RichText(rich.spans.clone()));
        // Calculate dimensions - sum of all span widths
        render_node.width = rich
            .spans
            .iter()
            .map(|span| display_width(&span.content) as u16)
            .sum();
        render_node.height = 1;

        // Apply top-level text style if present (for wrapping, etc)
        if let Some(ts) = &rich.style {
            render_node.text_style = Some(ts.clone());
            // Extract common color if all spans have the same
            if !rich.spans.is_empty() {
                let first_color = rich.spans[0].style.as_ref().and_then(|s| s.color);
                if rich
                    .spans
                    .iter()
                    .all(|span| span.style.as_ref().and_then(|s| s.color) == first_color)
                {
                    render_node.text_color = first_color;
                }
            }
        }

        Rc::new(RefCell::new(render_node))
    }

    /// Applies a list of patches to update the render tree.
    ///
    /// Patches are applied in order to transform the current
    /// render tree to match the new node tree.
    fn apply_patches(&mut self, patches: Vec<Patch>) {
        for patch in patches {
            self.apply_patch(patch);
        }
    }

    /// Applies a single patch operation to the render tree.
    ///
    /// ## Patch Types
    ///
    /// - **Replace**: Swap entire node with new one
    /// - **UpdateText**: Change text content
    /// - **UpdateProps**: Update styles/dimensions
    /// - **AddChild**: Insert new child node
    /// - **RemoveChild**: Delete child node
    /// - **ReorderChildren**: Rearrange child order
    fn apply_patch(&mut self, patch: Patch) {
        match patch {
            Patch::Replace { old, new } => {
                let new_render = self.create_render_node(&new);
                // Mark new node as dirty
                new_render.borrow_mut().mark_dirty();

                if let Some(parent) = &old.borrow().parent {
                    if let Some(parent_strong) = parent.upgrade() {
                        let mut parent_ref = parent_strong.borrow_mut();
                        if let Some(index) =
                            parent_ref.children.iter().position(|c| Rc::ptr_eq(c, &old))
                        {
                            parent_ref.children[index] = new_render.clone();
                            new_render.borrow_mut().parent = Some(Rc::downgrade(&parent_strong));
                        }
                        // Mark parent as dirty too
                        parent_ref.mark_dirty();
                    }
                } else {
                    self.render_tree.set_root(new_render);
                }
            }
            Patch::UpdateText {
                node,
                new_text,
                new_style,
            } => {
                let mut node_ref = node.borrow_mut();
                // Update dimensions when text changes
                node_ref.width = display_width(&new_text) as u16;
                node_ref.height = 1;
                node_ref.node_type = RenderNodeType::Text(new_text);

                // Update text style
                node_ref.text_style = new_style.clone();
                if let Some(ts) = &new_style {
                    node_ref.text_color = ts.color;
                    // Update background style if present
                    node_ref.style = ts.background.map(|bg| crate::style::Style {
                        background: Some(bg),
                        ..Default::default()
                    });
                } else {
                    node_ref.text_color = None;
                    // Clear background style if no text style
                    if let Some(existing_style) = &mut node_ref.style {
                        existing_style.background = None;
                    }
                }

                node_ref.mark_dirty();
            }
            Patch::UpdateRichText { node, new_spans } => {
                let mut node_ref = node.borrow_mut();
                // Update dimensions when spans change
                node_ref.width = new_spans
                    .iter()
                    .map(|span| display_width(&span.content) as u16)
                    .sum();
                node_ref.height = 1;
                node_ref.node_type = RenderNodeType::RichText(new_spans);
                node_ref.mark_dirty();
            }
            Patch::UpdateProps { node, div } => {
                let mut node_ref = node.borrow_mut();

                // Preserve the existing focus state from the old node
                let is_focused = node_ref.focused;

                // Apply the correct style based on the preserved focus state
                let effective_style = if is_focused {
                    // For focused elements, merge: base -> default focus -> custom focus
                    let default_focus = if div.focusable {
                        Some(crate::style::Style::default_focus())
                    } else {
                        None
                    };

                    let focus_with_defaults =
                        crate::style::Style::merge(default_focus, div.styles.focus.clone());
                    crate::style::Style::merge(div.styles.base.clone(), focus_with_defaults)
                } else {
                    div.styles.base.clone()
                };

                if let Some(style) = effective_style {
                    // Extract dimensions from style before assigning
                    match style.width {
                        Some(crate::style::Dimension::Fixed(width)) => {
                            node_ref.width = width;
                        }
                        Some(crate::style::Dimension::Percentage(_)) => {
                            // Percentage will be resolved during layout
                            // Keep width as 0 to indicate it needs resolution
                        }
                        Some(crate::style::Dimension::Auto) => {
                            // Auto will be resolved during layout
                            // Keep width as 0 to indicate it needs resolution
                        }
                        Some(crate::style::Dimension::Content) => {
                            // Content will be resolved during layout
                            // Keep width as 0 to indicate it needs resolution
                        }
                        None => {}
                    }

                    match style.height {
                        Some(crate::style::Dimension::Fixed(height)) => {
                            node_ref.height = height;
                        }
                        Some(crate::style::Dimension::Percentage(_)) => {
                            // Percentage will be resolved during layout
                            // Keep height as 0 to indicate it needs resolution
                        }
                        Some(crate::style::Dimension::Auto) => {
                            // Auto will be resolved during layout
                            // Keep height as 0 to indicate it needs resolution
                        }
                        Some(crate::style::Dimension::Content) => {
                            // Content will be resolved during layout
                            // Keep height as 0 to indicate it needs resolution
                        }
                        None => {}
                    }

                    // Now assign the style
                    node_ref.style = Some(style);
                }

                // Update container properties but preserve focus state
                node_ref.styles = div.styles.clone();
                node_ref.events = div.events.clone();
                node_ref.focusable = div.focusable;
                node_ref.focused = is_focused;
                node_ref.mark_dirty();
            }
            Patch::AddChild {
                parent,
                child,
                index,
            } => {
                let child_render = self.create_render_node(&child);
                {
                    let mut parent_ref = parent.borrow_mut();
                    if index >= parent_ref.children.len() {
                        parent_ref.children.push(child_render.clone());
                    } else {
                        parent_ref.children.insert(index, child_render.clone());
                    }
                    // Mark parent as dirty since its children changed
                    parent_ref.mark_dirty();
                }
                // Set parent reference after inserting
                child_render.borrow_mut().parent = Some(Rc::downgrade(&parent));
            }
            Patch::RemoveChild { parent, index } => {
                let mut parent_ref = parent.borrow_mut();
                if index < parent_ref.children.len() {
                    parent_ref.children.remove(index);
                    // Mark parent as dirty since its children changed
                    parent_ref.mark_dirty();
                }
            }
            Patch::ReorderChildren { parent, moves } => {
                let mut parent_ref = parent.borrow_mut();
                for mov in moves {
                    if mov.from < parent_ref.children.len() && mov.to < parent_ref.children.len() {
                        let child = parent_ref.children.remove(mov.from);
                        parent_ref.children.insert(mov.to, child);
                    }
                }
                // Mark parent as dirty since its children were reordered
                parent_ref.mark_dirty();
            }
        }
    }
}

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

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