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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
use crate::bounds::Rect;
use crate::key::Key;
use crate::node::{DivStyles, EventCallbacks, TextSpan};
use crate::style::{
Color, Dimension, Direction, Overflow, Position, Spacing, Style, TextStyle, TextWrap,
};
use crate::utils::{display_width, wrap_text};
use std::cell::RefCell;
use std::rc::{Rc, Weak};
//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------
/// A node in the render tree with calculated position and dimensions.
///
/// RenderNodes are created from Nodes and contain all the information
/// needed to draw elements to the terminal screen.
///
/// ## Node Coordinates
///
/// ```text
/// Terminal Grid:
/// 0 1 2 3 4 5 6 7 8 9
/// 0 ┌──────────────────┐
/// 1 │ RenderNode │ x=1, y=1
/// 2 │ ┌─────────────┐ │ width=13
/// 3 │ │ Content │ │ height=3
/// 4 │ └─────────────┘ │
/// 5 └──────────────────┘
/// ```
#[derive(Debug)]
pub struct RenderNode {
/// The type of node (element container or text)
pub node_type: RenderNodeType,
/// X coordinate in terminal columns (0-based)
pub x: u16,
/// Y coordinate in terminal rows (0-based)
pub y: u16,
/// Width in terminal columns
pub width: u16,
/// Height in terminal rows
pub height: u16,
/// Style properties (colors, borders, padding)
pub style: Option<Style>,
/// Text color (only used for text nodes)
pub text_color: Option<Color>,
/// Full text style (only used for text nodes)
pub text_style: Option<TextStyle>,
/// Child nodes to render inside this node
pub children: Vec<Rc<RefCell<RenderNode>>>,
/// Parent node reference (for traversal)
pub parent: Option<Weak<RefCell<RenderNode>>>,
/// Visual styling for different states
pub styles: DivStyles,
/// Event callbacks
pub events: EventCallbacks,
/// Whether this element can receive focus
pub focusable: bool,
/// Whether this element is currently focused
pub focused: bool,
/// Whether this node needs to be redrawn
pub dirty: bool,
/// Z-index for layering (higher values render on top)
pub z_index: i32,
/// Position type (relative, absolute, fixed)
pub position_type: Position,
/// Vertical scroll offset in rows
pub scroll_y: u16,
/// Actual content width (may exceed container width)
pub content_width: u16,
/// Actual content height (may exceed container height)
pub content_height: u16,
/// Whether this node is scrollable (has overflow:scroll or auto)
pub scrollable: bool,
}
/// Types of nodes that can be rendered.
#[derive(Debug, Clone, PartialEq)]
pub enum RenderNodeType {
/// Div element that can have children and styling
Element,
/// Text content leaf node (single line)
Text(String),
/// Wrapped text content (multiple lines)
TextWrapped(Vec<String>),
/// Text with multiple styled segments
RichText(Vec<TextSpan>),
/// Wrapped styled text (multiple lines, each with styled segments)
RichTextWrapped(Vec<Vec<TextSpan>>),
}
//--------------------------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------------------------
impl RenderNode {
/// Creates a new render node with the specified type.
///
/// Initializes position and dimensions to 0.
pub fn new(node_type: RenderNodeType) -> Self {
Self {
node_type,
x: 0,
y: 0,
width: 0,
height: 0,
style: None,
text_color: None,
text_style: None,
children: Vec::new(),
parent: None,
styles: DivStyles::default(),
events: EventCallbacks::default(),
focusable: false,
focused: false,
dirty: true,
z_index: 0,
position_type: Position::Relative,
scroll_y: 0,
content_width: 0,
content_height: 0,
scrollable: false,
}
}
/// Creates a new element container node.
pub fn element() -> Self {
Self::new(RenderNodeType::Element)
}
/// Creates a new text node with the given content.
pub fn text(content: impl Into<String>) -> Self {
Self::new(RenderNodeType::Text(content.into()))
}
/// Creates a new wrapped text node with multiple lines.
pub fn text_wrapped(lines: Vec<String>) -> Self {
Self::new(RenderNodeType::TextWrapped(lines))
}
/// Sets the absolute position of this node in terminal coordinates.
pub fn set_position(&mut self, x: u16, y: u16) {
self.x = x;
self.y = y;
}
/// Sets the dimensions of this node in terminal cells.
pub fn set_size(&mut self, width: u16, height: u16) {
self.width = width;
self.height = height;
}
/// Adds a child node to this container and sets up parent reference.
pub fn add_child_with_parent(
self_rc: &Rc<RefCell<RenderNode>>,
child: Rc<RefCell<RenderNode>>,
) {
child.borrow_mut().parent = Some(Rc::downgrade(self_rc));
self_rc.borrow_mut().children.push(child);
}
/// Gets the bounds rectangle for this node.
pub fn bounds(&self) -> Rect {
Rect::new(self.x, self.y, self.width, self.height)
}
/// Marks this node as dirty, requiring a redraw.
///
/// Also marks all parent nodes as dirty since they contain
/// this dirty region.
pub fn mark_dirty(&mut self) {
self.dirty = true;
// Note: Parent propagation would require upgrading weak ref
// For now, we'll handle this at the tree level
}
/// Clears the dirty flag after rendering.
pub fn clear_dirty(&mut self) {
self.dirty = false;
}
/// Returns true if this node creates a positioning context for absolute children.
/// A node is "positioned" if it has position: absolute or fixed (not relative).
pub fn is_positioned(&self) -> bool {
matches!(self.position_type, Position::Absolute | Position::Fixed)
}
/// Updates the vertical scroll position by the given delta, clamping to valid range.
///
/// Returns true if the scroll position changed.
pub fn update_scroll(&mut self, delta_y: i16) -> bool {
if !self.scrollable {
return false;
}
let old_scroll_y = self.scroll_y;
// Calculate maximum scroll value
let max_scroll_y = self.content_height.saturating_sub(self.height);
// Update scroll position with clamping
self.scroll_y = (self.scroll_y as i16 + delta_y)
.max(0)
.min(max_scroll_y as i16) as u16;
// Return whether position changed
self.scroll_y != old_scroll_y
}
/// Sets the vertical scroll position to a specific value, clamping to valid range.
pub fn set_scroll_y(&mut self, y: u16) {
if !self.scrollable {
return;
}
let max_scroll_y = self.content_height.saturating_sub(self.height);
self.scroll_y = y.min(max_scroll_y);
}
/// Returns the maximum scrollable range for vertical axis.
pub fn get_max_scroll_y(&self) -> u16 {
self.content_height.saturating_sub(self.height)
}
/// Calculates the intrinsic (content-based) size of this node and its children.
/// Returns (width, height) based on the node's content.
pub fn calculate_intrinsic_size(&self) -> (u16, u16) {
// Use multi-pass calculation for complex scenarios
self.calculate_intrinsic_size_multipass(3, None)
}
/// Multi-pass intrinsic size calculation with convergence detection.
/// Handles complex scenarios like percentage children in content-sized parents.
fn calculate_intrinsic_size_multipass(
&self,
max_passes: usize,
hint: Option<(u16, u16)>,
) -> (u16, u16) {
let mut size = self.calculate_intrinsic_size_single_pass(hint);
let mut prev_size = size;
for _pass in 1..max_passes {
// Use previous size as hint for next pass
size = self.calculate_intrinsic_size_single_pass(Some(prev_size));
// Check for convergence
if size == prev_size {
break;
}
prev_size = size;
}
size
}
/// Single pass of intrinsic size calculation.
/// Uses hint for resolving percentages and simulating wrapping.
fn calculate_intrinsic_size_single_pass(&self, hint: Option<(u16, u16)>) -> (u16, u16) {
match &self.node_type {
RenderNodeType::Text(text) => {
// Check if this text node has wrapping enabled
if let Some(text_style) = &self.text_style
&& let Some(wrap_mode) = text_style.wrap
&& wrap_mode != TextWrap::None
{
// Determine wrap width from either:
// 1. Text node's own fixed width
// 2. Hint from parent (for text in fixed-width containers)
let wrap_width = if let Some(style) = &self.style {
if let Some(Dimension::Fixed(width)) = style.width {
Some(width)
} else {
// Use hint width if available
hint.map(|(w, _)| w)
}
} else {
// No style, use hint width if available
hint.map(|(w, _)| w)
};
if let Some(width) = wrap_width {
// Apply wrapping at the determined width to get accurate height
let wrapped_lines = wrap_text(text, width, wrap_mode);
let height = wrapped_lines.len() as u16;
let actual_width = wrapped_lines
.iter()
.map(|l| display_width(l))
.max()
.unwrap_or(0) as u16;
return (actual_width.min(width), height);
}
}
// Default: unwrapped text size
(display_width(text) as u16, 1)
}
RenderNodeType::TextWrapped(lines) => {
// Already wrapped text: width is longest line, height is line count
let width = lines.iter().map(|l| display_width(l)).max().unwrap_or(0) as u16;
let height = lines.len() as u16;
(width, height)
}
RenderNodeType::RichText(spans) => {
// Calculate total width by summing all span content widths
let width = spans
.iter()
.map(|span| display_width(&span.content) as u16)
.sum();
// RichText is single line for now
(width, 1)
}
RenderNodeType::RichTextWrapped(lines) => {
// Already wrapped styled text: width is longest line, height is line count
let width = lines
.iter()
.map(|line| {
line.iter()
.map(|span| display_width(&span.content) as u16)
.sum::<u16>()
})
.max()
.unwrap_or(0);
let height = lines.len() as u16;
(width, height)
}
RenderNodeType::Element => {
// Element nodes calculate size based on children and layout direction
if self.children.is_empty() {
return (0, 0);
}
let style = self.style.as_ref();
let direction = style
.and_then(|s| s.direction)
.unwrap_or(Direction::Vertical);
let padding = style.and_then(|s| s.padding).unwrap_or(Spacing::all(0));
let border_size = if style
.and_then(|s| s.border.as_ref())
.is_some_and(|b| b.enabled)
{
2 // 1 cell on each side
} else {
0
};
// Check for wrapping mode and constraints
let wrap_mode = style.and_then(|s| s.wrap);
let gap = style.and_then(|s| s.gap).unwrap_or(0);
// Check if we should simulate wrapping
let should_wrap = if let Some(crate::style::WrapMode::Wrap) = wrap_mode {
match direction {
Direction::Horizontal => {
// Wrap horizontally if we have a fixed width constraint
style
.and_then(|s| s.width)
.is_some_and(|w| matches!(w, Dimension::Fixed(_)))
}
Direction::Vertical => {
// Wrap vertically if we have a fixed height constraint
style
.and_then(|s| s.height)
.is_some_and(|h| matches!(h, Dimension::Fixed(_)))
}
}
} else {
false
};
if should_wrap {
// Simulate wrapping layout to calculate intrinsic size
self.calculate_wrapped_intrinsic_size(
direction,
padding,
border_size,
gap,
hint,
)
} else {
// Standard layout calculation (no wrapping)
self.calculate_standard_intrinsic_size(direction, padding, border_size, hint)
}
}
}
}
/// Calculate intrinsic size for standard (non-wrapped) layout.
fn calculate_standard_intrinsic_size(
&self,
direction: Direction,
padding: Spacing,
border_size: u16,
hint: Option<(u16, u16)>,
) -> (u16, u16) {
let mut total_width = 0u16;
let mut total_height = 0u16;
let mut max_width = 0u16;
let mut max_height = 0u16;
// Calculate hint to pass to children based on parent's constraints
let child_hint = if let Some(style) = &self.style {
match (style.width, style.height) {
(Some(Dimension::Fixed(w)), Some(Dimension::Fixed(h))) => {
// Both dimensions fixed: pass content area as hint
let content_width =
w.saturating_sub(padding.left + padding.right + border_size);
let content_height =
h.saturating_sub(padding.top + padding.bottom + border_size);
Some((content_width, content_height))
}
(Some(Dimension::Fixed(w)), _) => {
// Width fixed: pass content width, keep height from original hint
let content_width =
w.saturating_sub(padding.left + padding.right + border_size);
Some((content_width, hint.map(|(_, h)| h).unwrap_or(0)))
}
(_, Some(Dimension::Fixed(h))) => {
// Height fixed: pass content height, keep width from original hint
let content_height =
h.saturating_sub(padding.top + padding.bottom + border_size);
Some((hint.map(|(w, _)| w).unwrap_or(0), content_height))
}
_ => hint, // No fixed dimensions, pass hint through
}
} else {
hint
};
for child in &self.children {
let child_ref = child.borrow();
// Calculate child's size, considering hints for percentages
let (child_width, child_height) = {
let intrinsic = child_ref.calculate_intrinsic_size_multipass(2, child_hint);
let mut width = intrinsic.0;
let mut height = intrinsic.1;
// Apply fixed dimensions if specified
if let Some(style) = &child_ref.style {
if let Some(Dimension::Fixed(w)) = style.width {
width = w;
} else if let Some(Dimension::Percentage(pct)) = style.width {
// Use hint to resolve percentage if available
if let Some((hint_w, _)) = hint {
width = (hint_w as f32 * pct) as u16;
}
}
if let Some(Dimension::Fixed(h)) = style.height {
height = h;
} else if let Some(Dimension::Percentage(pct)) = style.height {
// Use hint to resolve percentage if available
if let Some((_, hint_h)) = hint {
height = (hint_h as f32 * pct) as u16;
}
}
}
(width, height)
};
match direction {
Direction::Horizontal => {
total_width = total_width.saturating_add(child_width);
max_height = max_height.max(child_height);
}
Direction::Vertical => {
total_height = total_height.saturating_add(child_height);
max_width = max_width.max(child_width);
}
}
}
let content_width = match direction {
Direction::Horizontal => total_width,
Direction::Vertical => max_width,
};
let content_height = match direction {
Direction::Horizontal => max_height,
Direction::Vertical => total_height,
};
let final_width = content_width
.saturating_add(padding.left + padding.right)
.saturating_add(border_size);
let final_height = content_height
.saturating_add(padding.top + padding.bottom)
.saturating_add(border_size);
(final_width, final_height)
}
/// Calculate intrinsic size for wrapped layout.
fn calculate_wrapped_intrinsic_size(
&self,
direction: Direction,
padding: Spacing,
border_size: u16,
gap: u16,
hint: Option<(u16, u16)>,
) -> (u16, u16) {
// Get the fixed constraint dimension
let constraint = match direction {
Direction::Horizontal => {
// For horizontal wrap, we need fixed width
if let Some(Dimension::Fixed(w)) = self.style.as_ref().and_then(|s| s.width) {
w.saturating_sub(padding.left + padding.right + border_size)
} else {
// Shouldn't happen due to should_wrap check, but fallback to hint or large value
hint.map(|(w, _)| w).unwrap_or(u16::MAX)
}
}
Direction::Vertical => {
// For vertical wrap, we need fixed height
if let Some(Dimension::Fixed(h)) = self.style.as_ref().and_then(|s| s.height) {
h.saturating_sub(padding.top + padding.bottom + border_size)
} else {
// Shouldn't happen due to should_wrap check, but fallback to hint or large value
hint.map(|(_, h)| h).unwrap_or(u16::MAX)
}
}
};
// Calculate hint to pass to children based on constraint
let child_hint = match direction {
Direction::Horizontal => {
// Pass the constrained width as hint
Some((constraint, hint.map(|(_, h)| h).unwrap_or(0)))
}
Direction::Vertical => {
// Pass the constrained height as hint
Some((hint.map(|(w, _)| w).unwrap_or(0), constraint))
}
};
// Collect children sizes
let mut child_sizes = Vec::new();
for child in &self.children {
let child_ref = child.borrow();
let (child_width, child_height) = {
let intrinsic = child_ref.calculate_intrinsic_size_multipass(2, child_hint);
let mut width = intrinsic.0;
let mut height = intrinsic.1;
// Apply fixed dimensions if specified
if let Some(style) = &child_ref.style {
if let Some(Dimension::Fixed(w)) = style.width {
width = w;
} else if let Some(Dimension::Percentage(pct)) = style.width
&& let Some((hint_w, _)) = hint
{
width = (hint_w as f32 * pct) as u16;
}
if let Some(Dimension::Fixed(h)) = style.height {
height = h;
} else if let Some(Dimension::Percentage(pct)) = style.height
&& let Some((_, hint_h)) = hint
{
height = (hint_h as f32 * pct) as u16;
}
}
(width, height)
};
child_sizes.push((child_width, child_height));
}
// Simulate wrapping layout
match direction {
Direction::Horizontal => {
// Horizontal wrap: children flow left to right, wrap to new rows
let mut rows = Vec::new();
let mut current_row = Vec::new();
let mut current_row_width = 0u16;
for (child_width, child_height) in child_sizes {
if current_row_width > 0 && current_row_width + gap + child_width > constraint {
// Start new row
rows.push(current_row);
current_row = vec![(child_width, child_height)];
current_row_width = child_width;
} else {
if !current_row.is_empty() {
current_row_width += gap;
}
current_row_width += child_width;
current_row.push((child_width, child_height));
}
}
if !current_row.is_empty() {
rows.push(current_row);
}
// Calculate total size from rows
let total_width = constraint; // Width is fixed
let total_height = rows
.iter()
.map(|row| row.iter().map(|(_, h)| *h).max().unwrap_or(0))
.sum::<u16>()
+ (rows.len().saturating_sub(1) as u16 * gap);
let final_width = total_width
.saturating_add(padding.left + padding.right)
.saturating_add(border_size);
let final_height = total_height
.saturating_add(padding.top + padding.bottom)
.saturating_add(border_size);
(final_width, final_height)
}
Direction::Vertical => {
// Vertical wrap: children flow top to bottom, wrap to new columns
let mut columns = Vec::new();
let mut current_column = Vec::new();
let mut current_column_height = 0u16;
for (child_width, child_height) in child_sizes {
if current_column_height > 0
&& current_column_height + gap + child_height > constraint
{
// Start new column
columns.push(current_column);
current_column = vec![(child_width, child_height)];
current_column_height = child_height;
} else {
if !current_column.is_empty() {
current_column_height += gap;
}
current_column_height += child_height;
current_column.push((child_width, child_height));
}
}
if !current_column.is_empty() {
columns.push(current_column);
}
// Calculate total size from columns
let total_width = columns
.iter()
.map(|col| col.iter().map(|(w, _)| *w).max().unwrap_or(0))
.sum::<u16>()
+ (columns.len().saturating_sub(1) as u16 * gap);
let total_height = constraint; // Height is fixed
let final_width = total_width
.saturating_add(padding.left + padding.right)
.saturating_add(border_size);
let final_height = total_height
.saturating_add(padding.top + padding.bottom)
.saturating_add(border_size);
(final_width, final_height)
}
}
}
/// Applies text wrapping to a text node if needed based on width and text style.
/// Converts Text node to TextWrapped if wrapping is enabled.
pub fn apply_text_wrapping(&mut self, available_width: u16) {
match &self.node_type {
RenderNodeType::Text(text) => {
// Only apply to single-line text nodes with text style
if let Some(text_style) = &self.text_style
&& let Some(wrap_mode) = text_style.wrap
&& wrap_mode != TextWrap::None
&& available_width > 0
{
// Apply wrapping
let wrapped_lines = wrap_text(text, available_width, wrap_mode);
// Update node type and dimensions
self.node_type = RenderNodeType::TextWrapped(wrapped_lines.clone());
self.height = wrapped_lines.len() as u16;
self.width = wrapped_lines
.iter()
.map(|l| display_width(l))
.max()
.unwrap_or(0) as u16;
}
}
RenderNodeType::RichText(spans) => {
// Check if we have wrapping enabled in text_style
if let Some(text_style) = &self.text_style
&& let Some(wrap_mode) = text_style.wrap
&& wrap_mode != TextWrap::None
&& available_width > 0
{
// Build a mapping of character positions to span indices, styles, and cursor flag
let mut char_to_span = Vec::new();
let full_text: String = spans
.iter()
.enumerate()
.map(|(idx, span)| {
// Store which span each character belongs to
for _ in 0..span.content.chars().count() {
char_to_span.push((idx, span.style.clone(), span.is_cursor));
}
span.content.as_str()
})
.collect();
// Apply wrapping to the full text
let wrapped_lines = wrap_text(&full_text, available_width, wrap_mode);
// Build wrapped lines with correct span information
let mut wrapped_styled_lines = Vec::new();
let mut char_offset = 0;
for line in wrapped_lines {
let mut line_spans = Vec::new();
let mut current_span_idx = None;
let mut current_content = String::new();
let mut current_style = None;
let mut current_is_cursor = false;
// Process each character in the line
for ch in line.chars() {
if char_offset < char_to_span.len() {
let (span_idx, style, is_cursor) = &char_to_span[char_offset];
// Check if we're starting a new span (different index, style, or cursor flag)
if current_span_idx != Some(*span_idx)
|| current_style != *style
|| current_is_cursor != *is_cursor
{
// Save previous span if it exists
if !current_content.is_empty() {
line_spans.push(TextSpan {
content: current_content.clone(),
style: current_style.clone(),
is_cursor: current_is_cursor,
});
}
// Start new span
current_content = String::new();
current_span_idx = Some(*span_idx);
current_style = style.clone();
current_is_cursor = *is_cursor;
}
current_content.push(ch);
}
char_offset += 1;
}
// Add the last span in the line
if !current_content.is_empty() {
line_spans.push(TextSpan {
content: current_content,
style: current_style,
is_cursor: current_is_cursor,
});
}
if !line_spans.is_empty() {
wrapped_styled_lines.push(line_spans);
}
}
// Update node type and dimensions
if !wrapped_styled_lines.is_empty() {
self.height = wrapped_styled_lines.len() as u16;
self.width = wrapped_styled_lines
.iter()
.map(|line| {
line.iter()
.map(|span| display_width(&span.content) as u16)
.sum::<u16>()
})
.max()
.unwrap_or(0);
self.node_type = RenderNodeType::RichTextWrapped(wrapped_styled_lines);
}
}
}
_ => {}
}
}
/// Performs layout calculation for this node and its children.
///
/// Layout determines the position of child nodes based on
/// the layout direction (vertical or horizontal) and padding.
pub fn layout(&mut self) {
match &self.style {
Some(style) => {
let direction = style.direction.unwrap_or(Direction::Vertical);
self.layout_children(direction);
}
None => {
self.layout_children(Direction::Vertical);
}
}
}
/// Performs layout calculation with parent dimensions for percentage resolution.
///
/// This method resolves percentage-based dimensions before laying out children.
pub fn layout_with_parent(&mut self, parent_width: u16, parent_height: u16) {
// First, calculate intrinsic size if we need it
let (intrinsic_width, intrinsic_height) = self.calculate_intrinsic_size();
// Resolve percentage and fixed dimensions first (auto handled in layout_children_with_parent)
if let Some(style) = &self.style {
// Resolve width
match style.width {
Some(Dimension::Percentage(pct)) => {
// Calculate percentage of parent width
let calculated_width = (parent_width as f32 * pct) as u16;
// Ensure at least 1 cell width
self.width = calculated_width.max(1);
}
Some(Dimension::Fixed(w)) => {
self.width = w;
}
Some(Dimension::Content) => {
// Use intrinsic width, but cap at parent width
self.width = intrinsic_width.min(parent_width);
}
Some(Dimension::Auto) => {
// Auto should have been resolved by parent's layout
// Don't override if already set
}
None => {
// If no width specified, use intrinsic size (content-based)
self.width = intrinsic_width.min(parent_width);
}
}
// Resolve height
match style.height {
Some(Dimension::Percentage(pct)) => {
// Calculate percentage of parent height
let calculated_height = (parent_height as f32 * pct) as u16;
// Ensure at least 1 cell height
self.height = calculated_height.max(1);
}
Some(Dimension::Fixed(h)) => {
self.height = h;
}
Some(Dimension::Content) => {
// Use intrinsic height, but cap at parent height
self.height = intrinsic_height.min(parent_height);
}
Some(Dimension::Auto) => {
// Auto should have been resolved by parent's layout
// Don't override if already set
}
None => {
// If no height specified, use intrinsic size (content-based)
self.height = intrinsic_height.min(parent_height);
}
}
} else {
// No style - use intrinsic (content) size
self.width = intrinsic_width.min(parent_width);
self.height = intrinsic_height.min(parent_height);
}
// Apply text wrapping if this is a text node with wrapping enabled
// Use the node's own width (which may have been set to Fixed) as the constraint
// Note: Skip if already wrapped (TextWrapped or RichTextWrapped)
if matches!(
self.node_type,
RenderNodeType::Text(_) | RenderNodeType::RichText(_)
) {
// If we have a fixed width, use that; otherwise use parent width
let wrap_width = if let Some(style) = &self.style {
match style.width {
Some(Dimension::Fixed(w)) => w,
_ => self.width.min(parent_width),
}
} else {
self.width.min(parent_width)
};
self.apply_text_wrapping(wrap_width);
}
// Now layout children with resolved dimensions
let direction = self
.style
.as_ref()
.and_then(|s| s.direction)
.unwrap_or(Direction::Vertical);
self.layout_children_with_parent(direction);
}
/// Lays out child nodes according to the specified direction.
///
/// ## Vertical Layout
/// ```text
/// ┌──────────┐
/// │ Child 1 │ ← y = parent.y + padding.top
/// │──────────│
/// │ Child 2 │ ← y = child1.y + child1.height
/// │──────────│
/// │ Child 3 │ ← y = child2.y + child2.height
/// └──────────┘
/// ```
///
/// ## Horizontal Layout
/// ```text
/// ┌──────┬──────┬──────┐
/// │ Ch1 │ Ch2 │ Ch3 │
/// └──────┴──────┴──────┘
/// ↑ ↑ ↑
/// x=0 x=6 x=12
/// ```
fn layout_children(&mut self, direction: Direction) {
let padding = self
.style
.as_ref()
.and_then(|s| s.padding)
.unwrap_or(Spacing::all(0));
// Check if border is enabled and adjust content area accordingly
let border_offset = if self
.style
.as_ref()
.and_then(|s| s.border.as_ref())
.is_some_and(|b| b.enabled)
{
1
} else {
0
};
let mut offset = 0u16;
for child in &self.children {
let mut child_ref = child.borrow_mut();
match direction {
Direction::Vertical => {
child_ref.set_position(
self.x + padding.left + border_offset,
self.y + padding.top + border_offset + offset,
);
offset += child_ref.height;
}
Direction::Horizontal => {
child_ref.set_position(
self.x + padding.left + border_offset + offset,
self.y + padding.top + border_offset,
);
offset += child_ref.width;
}
}
child_ref.layout();
}
}
/// Lays out child nodes with wrapping enabled.
fn layout_children_with_wrap(
&mut self,
direction: Direction,
content_width: u16,
content_height: u16,
padding: Spacing,
border_offset: u16,
gap: u16,
) {
let start_x = self.x + padding.left + border_offset;
let start_y = self.y + padding.top + border_offset;
match direction {
Direction::Horizontal => {
// Horizontal wrapping: items flow left to right, wrap to next row
let mut current_x = start_x;
let mut current_y = start_y;
let mut row_height = 0u16;
let mut row_start_index = 0;
for (i, child) in self.children.iter().enumerate() {
let mut child_ref = child.borrow_mut();
// Resolve child dimensions
child_ref.layout_with_parent(content_width, content_height);
// Check if child fits in current row
// current_x already includes gap from previous item, so just add child width
if current_x > start_x && current_x + child_ref.width > start_x + content_width
{
// Wrap to next row
current_x = start_x;
current_y += row_height + gap;
// Update heights for previous row
for j in row_start_index..i {
let prev_child = self.children[j].borrow_mut();
if prev_child.height < row_height {
// Optionally stretch items to row height
// For now, keep original height
}
}
row_height = child_ref.height;
row_start_index = i;
}
// Position the child
child_ref.set_position(current_x, current_y);
// Update row height
row_height = row_height.max(child_ref.height);
// Move x position for next child
current_x += child_ref.width + gap;
}
}
Direction::Vertical => {
// Vertical wrapping: items flow top to bottom, wrap to next column
let mut current_x = start_x;
let mut current_y = start_y;
let mut col_width = 0u16;
let mut col_start_index = 0;
for (i, child) in self.children.iter().enumerate() {
let mut child_ref = child.borrow_mut();
// Resolve child dimensions
child_ref.layout_with_parent(content_width, content_height);
// Check if child fits in current column
// current_y already includes gap from previous item, so just add child height
if current_y > start_y
&& current_y + child_ref.height > start_y + content_height
{
// Wrap to next column
current_y = start_y;
current_x += col_width + gap;
// Update widths for previous column
for j in col_start_index..i {
let prev_child = self.children[j].borrow_mut();
if prev_child.width < col_width {
// Optionally stretch items to column width
// For now, keep original width
}
}
col_width = child_ref.width;
col_start_index = i;
}
// Position the child
child_ref.set_position(current_x, current_y);
// Update column width
col_width = col_width.max(child_ref.width);
// Move y position for next child
current_y += child_ref.height + gap;
}
}
}
// Layout children of each child
for child in &self.children {
let mut child_ref = child.borrow_mut();
if let Some(child_style) = &child_ref.style {
let child_direction = child_style.direction.unwrap_or(Direction::Vertical);
child_ref.layout_children_with_parent(child_direction);
} else {
child_ref.layout_children_with_parent(Direction::Vertical);
}
}
}
/// Lays out child nodes with parent dimension context for percentage resolution.
pub(crate) fn layout_children_with_parent(&mut self, direction: Direction) {
let padding = self
.style
.as_ref()
.and_then(|s| s.padding)
.unwrap_or(Spacing::all(0));
// Check if border is enabled and adjust content area accordingly
let border_offset = if self
.style
.as_ref()
.and_then(|s| s.border.as_ref())
.is_some_and(|b| b.enabled)
{
1
} else {
0
};
// Calculate content box dimensions (after padding and border)
let content_width = self
.width
.saturating_sub(padding.left + padding.right + (border_offset * 2));
let content_height = self
.height
.saturating_sub(padding.top + padding.bottom + (border_offset * 2));
// Check if wrapping is enabled
let wrap_mode = self.style.as_ref().and_then(|s| s.wrap);
let gap = self.style.as_ref().and_then(|s| s.gap).unwrap_or(0);
// If wrapping is enabled, use wrapping layout
if let Some(crate::style::WrapMode::Wrap) = wrap_mode {
self.layout_children_with_wrap(
direction,
content_width,
content_height,
padding,
border_offset,
gap,
);
return;
}
// First pass: Identify child types and calculate fixed/percentage sizes
let mut absolute_children = Vec::new();
let mut auto_children = Vec::new();
let mut used_space = 0u16;
let mut child_sizes = Vec::new();
for (index, child) in self.children.iter().enumerate() {
let mut child_ref = child.borrow_mut();
// Extract position info from style
let (position_type, z_index) = if let Some(style) = &child_ref.style {
(
style.position.unwrap_or(Position::Relative),
style.z_index.unwrap_or(0),
)
} else {
(Position::Relative, 0)
};
child_ref.position_type = position_type;
child_ref.z_index = z_index;
// Skip absolute/fixed positioned children in normal flow
if matches!(
child_ref.position_type,
Position::Absolute | Position::Fixed
) {
absolute_children.push(index);
child_sizes.push(0);
continue;
}
// Apply text wrapping early for text/richtext nodes if they have wrapping enabled
// This must happen before size calculation to get correct heights
if matches!(
child_ref.node_type,
RenderNodeType::Text(_) | RenderNodeType::RichText(_)
) && let Some(text_style) = &child_ref.text_style
&& let Some(wrap_mode) = text_style.wrap
&& wrap_mode != TextWrap::None
{
// Determine the available width for wrapping
let wrap_width = if let Some(style) = &child_ref.style {
match style.width {
Some(Dimension::Fixed(w)) => w,
Some(Dimension::Percentage(pct)) => (content_width as f32 * pct) as u16,
_ => content_width,
}
} else {
content_width
};
child_ref.apply_text_wrapping(wrap_width);
}
// Determine child size based on dimension type
let dimension = match direction {
Direction::Vertical => child_ref.style.as_ref().and_then(|s| s.height),
Direction::Horizontal => child_ref.style.as_ref().and_then(|s| s.width),
};
let child_size = match dimension {
Some(Dimension::Fixed(size)) => {
used_space = used_space.saturating_add(size);
size
}
Some(Dimension::Percentage(pct)) => {
let parent_size = match direction {
Direction::Vertical => content_height,
Direction::Horizontal => content_width,
};
let size = (parent_size as f32 * pct) as u16;
used_space = used_space.saturating_add(size);
size
}
Some(Dimension::Content) => {
// Calculate intrinsic size for content-based dimension
let (intrinsic_w, intrinsic_h) = child_ref.calculate_intrinsic_size();
let size = match direction {
Direction::Horizontal => intrinsic_w,
Direction::Vertical => intrinsic_h,
};
used_space = used_space.saturating_add(size);
size
}
Some(Dimension::Auto) => {
auto_children.push(index);
// For text nodes with auto sizing, use content size
match &child_ref.node_type {
RenderNodeType::Text(text) => match direction {
Direction::Horizontal => {
let size = display_width(text) as u16;
used_space = used_space.saturating_add(size);
size
}
Direction::Vertical => {
used_space = used_space.saturating_add(1);
1
}
},
RenderNodeType::RichText(spans) => match direction {
Direction::Horizontal => {
let size: u16 = spans
.iter()
.map(|span| display_width(&span.content) as u16)
.sum();
used_space = used_space.saturating_add(size);
size
}
Direction::Vertical => {
used_space = used_space.saturating_add(1);
1
}
},
RenderNodeType::TextWrapped(lines) => match direction {
Direction::Horizontal => {
let size = lines.iter().map(|l| display_width(l)).max().unwrap_or(0)
as u16;
used_space = used_space.saturating_add(size);
size
}
Direction::Vertical => {
let size = lines.len() as u16;
used_space = used_space.saturating_add(size);
size
}
},
RenderNodeType::RichTextWrapped(lines) => match direction {
Direction::Horizontal => {
let size = lines
.iter()
.map(|line| {
line.iter()
.map(|span| display_width(&span.content) as u16)
.sum::<u16>()
})
.max()
.unwrap_or(0);
used_space = used_space.saturating_add(size);
size
}
Direction::Vertical => {
let size = lines.len() as u16;
used_space = used_space.saturating_add(size);
size
}
},
_ => 0, // Will be calculated in second pass
}
}
None => {
// If no dimension specified, use content-based sizing
let (intrinsic_w, intrinsic_h) = child_ref.calculate_intrinsic_size();
let size = match direction {
Direction::Horizontal => intrinsic_w,
Direction::Vertical => intrinsic_h,
};
used_space = used_space.saturating_add(size);
size
}
};
child_sizes.push(child_size);
}
// Second pass: Calculate auto sizes
let available_space = match direction {
Direction::Vertical => content_height.saturating_sub(used_space),
Direction::Horizontal => content_width.saturating_sub(used_space),
};
let auto_size = if !auto_children.is_empty() {
available_space / auto_children.len() as u16
} else {
0
};
// Update auto-sized children
for &index in &auto_children {
let is_text = {
let child_ref = self.children[index].borrow();
matches!(
child_ref.node_type,
RenderNodeType::Text(_)
| RenderNodeType::TextWrapped(_)
| RenderNodeType::RichText(_)
| RenderNodeType::RichTextWrapped(_)
)
};
// Skip text nodes as they already have their size
if !is_text {
child_sizes[index] = auto_size;
}
}
// Third pass: Position and layout all children
let mut offset = 0u16;
let gap = self.style.as_ref().and_then(|s| s.gap).unwrap_or(0);
for (index, child) in self.children.iter().enumerate() {
let mut child_ref = child.borrow_mut();
// Skip absolute/fixed positioned children
if absolute_children.contains(&index) {
continue;
}
// Set child dimensions based on calculated sizes
match direction {
Direction::Vertical => {
child_ref.height = child_sizes[index];
// Set width for the child (respecting its own width setting)
if let Some(style) = &child_ref.style {
match style.width {
Some(Dimension::Fixed(w)) => child_ref.width = w,
Some(Dimension::Percentage(pct)) => {
child_ref.width = (content_width as f32 * pct) as u16;
}
Some(Dimension::Content) => {
// Content-based width
let (intrinsic_w, _) = child_ref.calculate_intrinsic_size();
child_ref.width = intrinsic_w.min(content_width);
}
Some(Dimension::Auto) => {
// Auto in perpendicular direction means fill available space
match &child_ref.node_type {
RenderNodeType::Text(text) => {
child_ref.width = display_width(text) as u16;
}
RenderNodeType::RichText(spans) => {
child_ref.width = spans
.iter()
.map(|span| display_width(&span.content) as u16)
.sum();
}
RenderNodeType::TextWrapped(lines) => {
child_ref.width = lines
.iter()
.map(|l| display_width(l))
.max()
.unwrap_or(0)
as u16;
}
RenderNodeType::RichTextWrapped(lines) => {
child_ref.width = lines
.iter()
.map(|line| {
line.iter()
.map(|span| display_width(&span.content) as u16)
.sum::<u16>()
})
.max()
.unwrap_or(0);
}
_ => {
child_ref.width = content_width;
}
}
}
None => {
// None means use content-based sizing
let (intrinsic_w, _) = child_ref.calculate_intrinsic_size();
child_ref.width = intrinsic_w.min(content_width);
}
}
} else {
// No style - use intrinsic width
let (intrinsic_w, _) = child_ref.calculate_intrinsic_size();
child_ref.width = intrinsic_w.min(content_width);
}
child_ref.set_position(
self.x + padding.left + border_offset,
self.y + padding.top + border_offset + offset,
);
offset += child_sizes[index];
// Add gap after each child except the last
if index < self.children.len() - 1 {
offset += gap;
}
}
Direction::Horizontal => {
// Set width from calculated size (includes auto-sizing)
child_ref.width = child_sizes[index];
// Set height for the child (respecting its own height setting)
if let Some(style) = &child_ref.style {
match style.height {
Some(Dimension::Fixed(h)) => child_ref.height = h,
Some(Dimension::Percentage(pct)) => {
child_ref.height = (content_height as f32 * pct) as u16;
}
Some(Dimension::Content) => {
// Content-based height
let (_, intrinsic_h) = child_ref.calculate_intrinsic_size();
child_ref.height = intrinsic_h.min(content_height);
}
Some(Dimension::Auto) => match &child_ref.node_type {
RenderNodeType::Text(_) | RenderNodeType::RichText(_) => {
child_ref.height = 1;
}
RenderNodeType::TextWrapped(lines) => {
child_ref.height = lines.len() as u16;
}
RenderNodeType::RichTextWrapped(lines) => {
child_ref.height = lines.len() as u16;
}
_ => {
child_ref.height = content_height;
}
},
None => {
// None means use content-based sizing
let (_, intrinsic_h) = child_ref.calculate_intrinsic_size();
child_ref.height = intrinsic_h.min(content_height);
}
}
} else {
// No style - use intrinsic height
let (_, intrinsic_h) = child_ref.calculate_intrinsic_size();
child_ref.height = intrinsic_h.min(content_height);
}
child_ref.set_position(
self.x + padding.left + border_offset + offset,
self.y + padding.top + border_offset,
);
offset += child_sizes[index];
// Add gap after each child except the last
if index < self.children.len() - 1 {
offset += gap;
}
}
}
// Layout child's children
child_ref.layout_with_parent(content_width, content_height);
}
// Second pass: position absolute/fixed children
for index in absolute_children {
let child = &self.children[index];
let mut child_ref = child.borrow_mut();
match child_ref.position_type {
Position::Fixed => {
// Fixed positioning: relative to viewport (0, 0)
self.position_absolute_child(
&mut child_ref,
0,
0,
content_width,
content_height,
);
}
Position::Absolute => {
// Absolute positioning: relative to this container
self.position_absolute_child(
&mut child_ref,
self.x,
self.y,
self.width,
self.height,
);
}
_ => {} // Already handled
}
// Layout the absolutely positioned child
child_ref.layout_with_parent(content_width, content_height);
}
// Track content dimensions for scrolling
self.calculate_content_dimensions();
// Set scrollable flag based on overflow style
if let Some(style) = &self.style {
match style.overflow {
Some(Overflow::Scroll) | Some(Overflow::Auto) => {
self.scrollable = true;
// Make scrollable elements focusable by default
if !self.focusable && self.events.on_click.is_none() {
self.focusable = true;
}
}
_ => {
self.scrollable = false;
}
}
}
}
/// Calculates the actual content dimensions (may exceed container bounds).
/// This is used to determine scrollable area.
fn calculate_content_dimensions(&mut self) {
if self.children.is_empty() {
// For leaf nodes, content dimensions equal node dimensions
self.content_width = self.width;
self.content_height = self.height;
return;
}
// Get padding values to account for them in content dimensions
let padding = self
.style
.as_ref()
.and_then(|s| s.padding)
.unwrap_or(Spacing::all(0));
// Check if border is enabled
let border_offset = if self
.style
.as_ref()
.and_then(|s| s.border.as_ref())
.is_some_and(|b| b.enabled)
{
1
} else {
0
};
// Find the maximum extent of all children
let mut max_x = 0u16;
let mut max_y = 0u16;
for child in &self.children {
let child_ref = child.borrow();
// Skip absolute/fixed positioned children as they don't affect content size
if matches!(
child_ref.position_type,
Position::Absolute | Position::Fixed
) {
continue;
}
let child_right = child_ref.x + child_ref.width;
let child_bottom = child_ref.y + child_ref.height;
// Update max extents relative to this node's position
if child_ref.x >= self.x && child_right > self.x {
max_x = max_x.max(child_right - self.x);
}
if child_ref.y >= self.y && child_bottom > self.y {
max_y = max_y.max(child_bottom - self.y);
}
}
// Add padding to the content dimensions if children extend beyond the container
// This ensures scrollable content includes padding after the last child
if max_x > self.width {
max_x = max_x + padding.right + border_offset;
}
if max_y > self.height {
max_y = max_y + padding.bottom + border_offset;
}
// Content dimensions are the maximum of container size and children extent with padding
self.content_width = self.width.max(max_x);
self.content_height = self.height.max(max_y);
}
/// Positions an absolutely positioned child based on its offset properties.
fn position_absolute_child(
&self,
child: &mut RenderNode,
container_x: u16,
container_y: u16,
container_width: u16,
container_height: u16,
) {
if let Some(style) = &child.style {
let mut x = container_x;
let mut y = container_y;
// Apply position offsets
if let Some(left) = style.left {
x = container_x.saturating_add_signed(left);
} else if let Some(right) = style.right {
// Position from right edge
x = (container_x + container_width)
.saturating_sub(child.width)
.saturating_add_signed(-right);
}
if let Some(top) = style.top {
y = container_y.saturating_add_signed(top);
} else if let Some(bottom) = style.bottom {
// Position from bottom edge
y = (container_y + container_height)
.saturating_sub(child.height)
.saturating_add_signed(-bottom);
}
child.set_position(x, y);
}
}
/// Handles a click event on this node.
///
/// Calls the registered click handler if one exists.
pub fn handle_click(&self) {
if let Some(on_click) = &self.events.on_click {
on_click();
}
}
/// Handles a key press event on this node.
///
/// Checks if a handler is registered for the pressed key
/// and calls it if found. Only processes non-global handlers.
pub fn handle_key(&self, key: Key) {
// First check on_any_key handler
if let Some(ref handler) = self.events.on_any_key {
handler(key);
}
// Check on_any_char handler for character keys
if let Key::Char(ch) = key
&& let Some(ref handler) = self.events.on_any_char
{
handler(ch);
}
// Then check specific key handlers
for (k, handler, is_global) in &self.events.on_key {
if *k == key && !is_global {
handler();
break;
}
}
}
/// Handles a key press for global handlers only.
///
/// Global handlers work regardless of focus state.
pub fn handle_global_key(&self, key: Key) {
for (k, handler, is_global) in &self.events.on_key {
if *k == key && *is_global {
handler();
// Don't break - allow multiple global handlers for same key
}
}
}
/// Checks if a handler is registered for the pressed key with modifiers
/// and calls it if found. Only processes non-global handlers.
pub fn handle_key_with_modifiers(&self, key_with_modifiers: crate::key::KeyWithModifiers) {
// Check specific key with modifiers handlers
for (k, handler, is_global) in &self.events.on_key_with_modifiers {
if *k == key_with_modifiers && !is_global {
handler();
break;
}
}
}
/// Checks if a global handler is registered for the pressed key with modifiers and calls it.
/// Global handlers work regardless of focus state.
pub fn handle_global_key_with_modifiers(
&self,
key_with_modifiers: crate::key::KeyWithModifiers,
) {
for (k, handler, is_global) in &self.events.on_key_with_modifiers {
if *k == key_with_modifiers && *is_global {
handler();
// Don't break - allow multiple global handlers for same key
}
}
}
}