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
use crate::bounds::Rect;
use crate::render_tree::node::{RenderNode, RenderNodeType};
use crate::style::{Dimension, Direction, Overflow};
use std::cell::RefCell;
use std::rc::Rc;
//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------
/// Container for the render tree with layout capabilities.
///
/// The render tree maintains the root node and provides
/// methods for layout calculation and hit testing.
pub struct RenderTree {
/// The root node of the render tree
pub root: Option<Rc<RefCell<RenderNode>>>,
/// The currently focused node (uses RefCell for interior mutability)
focused_node: RefCell<Option<Rc<RefCell<RenderNode>>>>,
}
//--------------------------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------------------------
impl RenderTree {
/// Creates a new empty render tree.
pub fn new() -> Self {
Self {
root: None,
focused_node: RefCell::new(None),
}
}
/// Returns a debug string representation of the render tree.
///
/// This recursively prints the tree structure with indentation showing
/// the hierarchy and node details like position, size, and type.
pub fn debug_string(&self) -> String {
match &self.root {
Some(root) => {
let mut output = String::new();
output.push_str("=== Render Tree ===\n");
Self::debug_node(&root.borrow(), &mut output, 0);
output.push_str("==================\n");
output
}
None => "=== Render Tree ===\n(empty)\n==================\n".to_string(),
}
}
/// Recursively builds debug string for a node and its children.
fn debug_node(node: &RenderNode, output: &mut String, depth: usize) {
let indent = " ".repeat(depth);
// Node type and position
match &node.node_type {
RenderNodeType::Element => {
output.push_str(&format!(
"{}Div @ ({}, {}) [{}x{}]",
indent, node.x, node.y, node.width, node.height
));
}
RenderNodeType::Text(content) => {
output.push_str(&format!(
"{}Text @ ({}, {}) [{}x{}]: \"{}\"",
indent,
node.x,
node.y,
node.width,
node.height,
content.replace('\n', "\\n")
));
}
RenderNodeType::TextWrapped(lines) => {
output.push_str(&format!(
"{}TextWrapped @ ({}, {}) [{}x{}]: {} lines",
indent,
node.x,
node.y,
node.width,
node.height,
lines.len()
));
for line in lines {
output.push_str(&format!("\n{} \"{}\"", indent, line.replace('\n', "\\n")));
}
}
RenderNodeType::RichText(spans) => {
output.push_str(&format!(
"{}RichText @ ({}, {}) [{}x{}]: {} spans",
indent,
node.x,
node.y,
node.width,
node.height,
spans.len()
));
for span in spans {
output.push_str(&format!(
"\n{} \"{}\"",
indent,
span.content.replace('\n', "\\n")
));
}
}
RenderNodeType::RichTextWrapped(lines) => {
output.push_str(&format!(
"{}RichTextWrapped @ ({}, {}) [{}x{}]: {} lines",
indent,
node.x,
node.y,
node.width,
node.height,
lines.len()
));
for (i, line) in lines.iter().enumerate() {
output.push_str(&format!(
"\n{} Line {}: {} spans",
indent,
i + 1,
line.len()
));
for span in line {
output.push_str(&format!(
"\n{} \"{}\"",
indent,
span.content.replace('\n', "\\n")
));
}
}
}
}
// Style info
if let Some(style) = &node.style {
if let Some(bg) = &style.background {
output.push_str(&format!(" bg:{bg:?}"));
}
if let Some(dir) = &style.direction {
output.push_str(&format!(" dir:{dir:?}"));
}
if let Some(padding) = &style.padding {
output.push_str(&format!(
" pad:({},{},{},{})",
padding.top, padding.right, padding.bottom, padding.left
));
}
if let Some(overflow) = &style.overflow {
output.push_str(&format!(" overflow:{overflow:?}"));
}
}
// Text color for text nodes
if matches!(
&node.node_type,
RenderNodeType::Text(_) | RenderNodeType::TextWrapped(_)
) && let Some(color) = &node.text_color
{
output.push_str(&format!(" color:{color:?}"));
}
// Dirty flag
if node.dirty {
output.push_str(" [DIRTY]");
}
output.push('\n');
// Recursively print children
for child in &node.children {
Self::debug_node(&child.borrow(), output, depth + 1);
}
}
/// Sets the root node of the render tree.
pub fn set_root(&mut self, root: Rc<RefCell<RenderNode>>) {
self.root = Some(root);
}
/// Performs layout for the entire tree within the given viewport.
///
/// Respects the root node's specified dimensions if set, otherwise
/// uses the viewport size. Clamps dimensions to viewport bounds.
pub fn layout(&mut self, viewport_width: u16, viewport_height: u16) {
if let Some(root) = &self.root {
let mut root_ref = root.borrow_mut();
root_ref.set_position(0, 0);
// Calculate intrinsic size for content-based dimensions
let (intrinsic_width, intrinsic_height) = root_ref.calculate_intrinsic_size();
// For the root node, resolve dimensions using viewport as parent
if let Some(style) = &root_ref.style {
// Clone the dimension values to avoid borrow checker issues
let width_dim = style.width;
let height_dim = style.height;
// Resolve width
match width_dim {
Some(Dimension::Fixed(w)) => {
root_ref.width = w.min(viewport_width);
}
Some(Dimension::Percentage(pct)) => {
let calculated_width = (viewport_width as f32 * pct) as u16;
root_ref.width = calculated_width.max(1).min(viewport_width);
}
Some(Dimension::Content) => {
// Use intrinsic width, capped at viewport
root_ref.width = intrinsic_width.min(viewport_width);
}
Some(Dimension::Auto) => {
// For root element, auto means full viewport width
root_ref.width = viewport_width;
}
None => {
// No dimension specified - use intrinsic size
root_ref.width = intrinsic_width.min(viewport_width);
}
}
// Resolve height
match height_dim {
Some(Dimension::Fixed(h)) => {
root_ref.height = h.min(viewport_height);
}
Some(Dimension::Percentage(pct)) => {
let calculated_height = (viewport_height as f32 * pct) as u16;
root_ref.height = calculated_height.max(1).min(viewport_height);
}
Some(Dimension::Content) => {
// Use intrinsic height, capped at viewport
root_ref.height = intrinsic_height.min(viewport_height);
}
Some(Dimension::Auto) => {
// For root element, auto means full viewport height
root_ref.height = viewport_height;
}
None => {
// No dimension specified - use intrinsic size
root_ref.height = intrinsic_height.min(viewport_height);
}
}
} else {
// No style - use intrinsic dimensions capped at viewport
root_ref.width = intrinsic_width.min(viewport_width);
root_ref.height = intrinsic_height.min(viewport_height);
}
// Layout children with root's resolved dimensions
let direction = root_ref
.style
.as_ref()
.and_then(|s| s.direction)
.unwrap_or(Direction::Vertical);
root_ref.layout_children_with_parent(direction);
}
}
/// Finds the topmost node at the given terminal coordinates.
///
/// Used for mouse event handling. Returns the deepest node
/// in the tree that contains the given point.
pub fn find_node_at(&self, x: u16, y: u16) -> Option<Rc<RefCell<RenderNode>>> {
if let Some(root) = &self.root {
// Start with no clipping and no scroll offset
Self::find_node_at_recursive(root, x, y, None, 0)
} else {
None
}
}
/// Recursively searches for a node containing the given point.
///
/// Performs depth-first search, checking children before parents
/// to ensure the topmost (visually) node is returned.
/// Respects overflow clipping - nodes with overflow:hidden will
/// clip their children's click areas.
/// Text nodes are transparent to clicks and pass events to their parent.
fn find_node_at_recursive(
node: &Rc<RefCell<RenderNode>>,
x: u16,
y: u16,
clip_rect: Option<Rect>,
parent_scroll_offset: i16,
) -> Option<Rc<RefCell<RenderNode>>> {
let node_ref = node.borrow();
// Calculate the actual rendered position with parent scroll offset
let rendered_y = if parent_scroll_offset > 0 {
node_ref.y.saturating_sub(parent_scroll_offset as u16)
} else {
node_ref.y
};
let rendered_x = node_ref.x;
// Get bounds with scroll offset applied
let node_bounds = Rect::new(rendered_x, rendered_y, node_ref.width, node_ref.height);
// Check if this node is clickable
let is_node_clickable = if let Some(ref clip) = clip_rect {
// If we have a clip rect, the node must be within both its bounds and the clip
node_bounds.contains_point(x, y) && clip.contains_point(x, y)
} else {
// If no clip rect, just check if point is within node bounds
node_bounds.contains_point(x, y)
};
// Calculate clip rect for children based on overflow setting
let child_clip = if let Some(style) = &node_ref.style {
match style.overflow {
Some(Overflow::Hidden) | Some(Overflow::Scroll) | Some(Overflow::Auto) => {
// Clip children at the padding edge for scrollable/hidden containers
if let Some(ref existing_clip) = clip_rect {
Some(node_bounds.intersection(existing_clip))
} else {
Some(node_bounds)
}
}
_ => {
// If overflow is none, pass through the existing clip rect
clip_rect
}
}
} else {
// No style, pass through the existing clip rect
clip_rect
};
// Calculate scroll offset to pass to children
let child_scroll_offset = if node_ref.scrollable {
parent_scroll_offset + node_ref.scroll_y as i16
} else {
parent_scroll_offset
};
// Always check children first, even if this node isn't clickable
// This is important for overflow:none where children can extend outside
for child in &node_ref.children {
if let Some(found) =
Self::find_node_at_recursive(child, x, y, child_clip, child_scroll_offset)
{
// Check if the found child is a text node
let found_ref = found.borrow();
if matches!(
found_ref.node_type,
RenderNodeType::Text(_) | RenderNodeType::TextWrapped(_)
) {
// Text nodes are transparent to clicks, don't return them
drop(found_ref);
continue;
}
drop(found_ref);
return Some(found);
}
}
// Only return this node if it's clickable and no child matched
// Text nodes should never be returned as click targets
if is_node_clickable
&& !matches!(
node_ref.node_type,
RenderNodeType::Text(_) | RenderNodeType::TextWrapped(_)
)
{
drop(node_ref); // Release borrow before cloning
return Some(node.clone());
}
None
}
/// Collects all dirty regions in the render tree.
///
/// Returns a vector of rectangles representing areas that need redrawing.
/// Adjacent rectangles are merged for efficiency.
pub fn collect_dirty_regions(&self) -> Vec<Rect> {
let mut regions = Vec::new();
if let Some(root) = &self.root {
Self::collect_dirty_regions_recursive(root, &mut regions);
}
// Merge overlapping regions
self.merge_regions(regions)
}
/// Recursively collects dirty regions from a node and its children.
fn collect_dirty_regions_recursive(node: &Rc<RefCell<RenderNode>>, regions: &mut Vec<Rect>) {
let node_ref = node.borrow();
if node_ref.dirty {
regions.push(node_ref.bounds());
}
for child in &node_ref.children {
Self::collect_dirty_regions_recursive(child, regions);
}
}
/// Merges overlapping or adjacent rectangles to minimize redraw operations.
fn merge_regions(&self, mut regions: Vec<Rect>) -> Vec<Rect> {
if regions.is_empty() {
return regions;
}
// Simple merge algorithm - can be optimized later
let mut merged = Vec::new();
regions.sort_by_key(|r| (r.y, r.x));
let mut current = regions[0];
for region in regions.into_iter().skip(1) {
if current.intersects(®ion) || self.are_adjacent(¤t, ®ion) {
current = current.union(®ion);
} else {
merged.push(current);
current = region;
}
}
merged.push(current);
merged
}
/// Checks if two rectangles are adjacent (touching but not overlapping).
fn are_adjacent(&self, a: &Rect, b: &Rect) -> bool {
// Horizontally adjacent
(a.right() == b.x || b.right() == a.x) &&
!(a.bottom() <= b.y || b.bottom() <= a.y) ||
// Vertically adjacent
(a.bottom() == b.y || b.bottom() == a.y) &&
!(a.right() <= b.x || b.right() <= a.x)
}
/// Marks all nodes in the tree as clean (not dirty).
pub fn clear_all_dirty(&self) {
if let Some(root) = &self.root {
Self::clear_dirty_recursive(root);
}
}
/// Recursively clears dirty flags in the tree.
fn clear_dirty_recursive(node: &Rc<RefCell<RenderNode>>) {
let mut node_ref = node.borrow_mut();
node_ref.clear_dirty();
let children = node_ref.children.clone();
drop(node_ref);
for child in children {
Self::clear_dirty_recursive(&child);
}
}
//--------------------------------------------------------------------------------------------------
// Focus Management
//--------------------------------------------------------------------------------------------------
/// Collects all focusable nodes in the tree in tab order (depth-first traversal).
pub fn collect_focusable_nodes(&self) -> Vec<Rc<RefCell<RenderNode>>> {
let mut nodes = Vec::new();
if let Some(root) = &self.root {
Self::collect_focusable_recursive(root, &mut nodes);
}
nodes
}
/// Recursively collects focusable nodes.
fn collect_focusable_recursive(
node: &Rc<RefCell<RenderNode>>,
nodes: &mut Vec<Rc<RefCell<RenderNode>>>,
) {
let node_ref = node.borrow();
// Add this node if it's focusable
if node_ref.focusable {
nodes.push(node.clone());
}
// Recurse through children
let children = node_ref.children.clone();
drop(node_ref); // Release borrow before recursing
for child in &children {
Self::collect_focusable_recursive(child, nodes);
}
}
/// Gets the currently focused node.
pub fn get_focused_node(&self) -> Option<Rc<RefCell<RenderNode>>> {
self.focused_node.borrow().clone()
}
/// Sets the focused node and updates the focused flags.
pub fn set_focused_node(&self, node: Option<Rc<RefCell<RenderNode>>>) {
// Clear focus from previous node and trigger on_blur
if let Some(old_focused) = self.focused_node.borrow().as_ref() {
let mut old_ref = old_focused.borrow_mut();
// Trigger on_blur event
if let Some(on_blur) = &old_ref.events.on_blur {
on_blur();
}
old_ref.focused = false;
// Update the style to remove focus styles
old_ref.style = old_ref.styles.base.clone();
// Mark old node as dirty so it redraws without focus style
old_ref.mark_dirty();
}
// Set focus on new node and trigger on_focus
if let Some(new_focused) = &node {
let mut new_ref = new_focused.borrow_mut();
new_ref.focused = true;
// Trigger on_focus event
if let Some(on_focus) = &new_ref.events.on_focus {
on_focus();
}
// Update the style to apply focus styles (base -> default focus -> custom focus)
let default_focus = if new_ref.focusable {
Some(crate::style::Style::default_focus())
} else {
None
};
let focus_with_defaults =
crate::style::Style::merge(default_focus, new_ref.styles.focus.clone());
new_ref.style =
crate::style::Style::merge(new_ref.styles.base.clone(), focus_with_defaults);
// Mark new node as dirty so it redraws with focus style
new_ref.mark_dirty();
}
// Update the focused node reference
*self.focused_node.borrow_mut() = node;
}
/// Moves focus to the next focusable element.
pub fn focus_next(&self) {
let focusable = self.collect_focusable_nodes();
if focusable.is_empty() {
return;
}
let current_focused = self.get_focused_node();
// Find current index or start at -1 if nothing focused
let current_idx = if let Some(current) = ¤t_focused {
focusable.iter().position(|n| Rc::ptr_eq(n, current))
} else {
None
};
// Calculate next index
let next_idx = match current_idx {
Some(idx) => (idx + 1) % focusable.len(),
None => 0, // Focus first element if nothing focused
};
self.set_focused_node(Some(focusable[next_idx].clone()));
}
/// Moves focus to the previous focusable element.
pub fn focus_prev(&self) {
let focusable = self.collect_focusable_nodes();
if focusable.is_empty() {
return;
}
let current_focused = self.get_focused_node();
// Find current index or start at 0 if nothing focused
let current_idx = if let Some(current) = ¤t_focused {
focusable.iter().position(|n| Rc::ptr_eq(n, current))
} else {
None
};
// Calculate previous index
let prev_idx = match current_idx {
Some(idx) => {
if idx == 0 {
focusable.len() - 1
} else {
idx - 1
}
}
None => focusable.len() - 1, // Focus last element if nothing focused
};
self.set_focused_node(Some(focusable[prev_idx].clone()));
}
}
//--------------------------------------------------------------------------------------------------
// Trait Implementations
//--------------------------------------------------------------------------------------------------
impl Default for RenderTree {
fn default() -> Self {
Self::new()
}
}