Skip to main content

slt/
layout.rs

1//! Flexbox layout engine: builds a tree from commands, computes positions,
2//! and renders to a [`Buffer`].
3
4use crate::buffer::Buffer;
5use crate::rect::Rect;
6use crate::style::{
7    Align, Border, BorderSides, Color, Constraints, Justify, Margin, Padding, Style,
8};
9use unicode_width::UnicodeWidthChar;
10use unicode_width::UnicodeWidthStr;
11
12/// Main axis direction for a container's children.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Direction {
15    /// Lay out children horizontally (left to right).
16    Row,
17    /// Lay out children vertically (top to bottom).
18    Column,
19}
20
21#[derive(Debug, Clone)]
22pub(crate) enum Command {
23    Text {
24        content: String,
25        style: Style,
26        grow: u16,
27        align: Align,
28        wrap: bool,
29        margin: Margin,
30        constraints: Constraints,
31    },
32    BeginContainer {
33        direction: Direction,
34        gap: u32,
35        align: Align,
36        justify: Justify,
37        border: Option<Border>,
38        border_sides: BorderSides,
39        border_style: Style,
40        bg_color: Option<Color>,
41        padding: Padding,
42        margin: Margin,
43        constraints: Constraints,
44        title: Option<(String, Style)>,
45        grow: u16,
46        group_name: Option<String>,
47    },
48    BeginScrollable {
49        grow: u16,
50        border: Option<Border>,
51        border_sides: BorderSides,
52        border_style: Style,
53        padding: Padding,
54        margin: Margin,
55        constraints: Constraints,
56        title: Option<(String, Style)>,
57        scroll_offset: u32,
58    },
59    Link {
60        text: String,
61        url: String,
62        style: Style,
63        margin: Margin,
64        constraints: Constraints,
65    },
66    RichText {
67        segments: Vec<(String, Style)>,
68        wrap: bool,
69        align: Align,
70        margin: Margin,
71        constraints: Constraints,
72    },
73    EndContainer,
74    BeginOverlay {
75        modal: bool,
76    },
77    EndOverlay,
78    Spacer {
79        grow: u16,
80    },
81    FocusMarker(usize),
82    RawDraw {
83        draw_id: usize,
84        constraints: Constraints,
85        grow: u16,
86        margin: Margin,
87    },
88}
89
90#[derive(Debug, Clone)]
91struct OverlayLayer {
92    node: LayoutNode,
93    modal: bool,
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97enum NodeKind {
98    Text,
99    Container(Direction),
100    Spacer,
101    RawDraw(usize),
102}
103
104#[derive(Debug, Clone)]
105pub(crate) struct LayoutNode {
106    kind: NodeKind,
107    content: Option<String>,
108    style: Style,
109    pub grow: u16,
110    align: Align,
111    justify: Justify,
112    wrap: bool,
113    gap: u32,
114    border: Option<Border>,
115    border_sides: BorderSides,
116    border_style: Style,
117    bg_color: Option<Color>,
118    padding: Padding,
119    margin: Margin,
120    constraints: Constraints,
121    title: Option<(String, Style)>,
122    children: Vec<LayoutNode>,
123    pos: (u32, u32),
124    size: (u32, u32),
125    is_scrollable: bool,
126    scroll_offset: u32,
127    content_height: u32,
128    cached_wrapped: Option<Vec<String>>,
129    segments: Option<Vec<(String, Style)>>,
130    cached_wrapped_segments: Option<Vec<Vec<(String, Style)>>>,
131    pub(crate) focus_id: Option<usize>,
132    link_url: Option<String>,
133    group_name: Option<String>,
134    overlays: Vec<OverlayLayer>,
135}
136
137#[derive(Debug, Clone)]
138struct ContainerConfig {
139    gap: u32,
140    align: Align,
141    justify: Justify,
142    border: Option<Border>,
143    border_sides: BorderSides,
144    border_style: Style,
145    bg_color: Option<Color>,
146    padding: Padding,
147    margin: Margin,
148    constraints: Constraints,
149    title: Option<(String, Style)>,
150    grow: u16,
151}
152
153impl LayoutNode {
154    fn text(
155        content: String,
156        style: Style,
157        grow: u16,
158        align: Align,
159        wrap: bool,
160        margin: Margin,
161        constraints: Constraints,
162    ) -> Self {
163        let width = UnicodeWidthStr::width(content.as_str()) as u32;
164        Self {
165            kind: NodeKind::Text,
166            content: Some(content),
167            style,
168            grow,
169            align,
170            justify: Justify::Start,
171            wrap,
172            gap: 0,
173            border: None,
174            border_sides: BorderSides::all(),
175            border_style: Style::new(),
176            bg_color: None,
177            padding: Padding::default(),
178            margin,
179            constraints,
180            title: None,
181            children: Vec::new(),
182            pos: (0, 0),
183            size: (width, 1),
184            is_scrollable: false,
185            scroll_offset: 0,
186            content_height: 0,
187            cached_wrapped: None,
188            segments: None,
189            cached_wrapped_segments: None,
190            focus_id: None,
191            link_url: None,
192            group_name: None,
193            overlays: Vec::new(),
194        }
195    }
196
197    fn rich_text(
198        segments: Vec<(String, Style)>,
199        wrap: bool,
200        align: Align,
201        margin: Margin,
202        constraints: Constraints,
203    ) -> Self {
204        let width: u32 = segments
205            .iter()
206            .map(|(s, _)| UnicodeWidthStr::width(s.as_str()) as u32)
207            .sum();
208        Self {
209            kind: NodeKind::Text,
210            content: None,
211            style: Style::new(),
212            grow: 0,
213            align,
214            justify: Justify::Start,
215            wrap,
216            gap: 0,
217            border: None,
218            border_sides: BorderSides::all(),
219            border_style: Style::new(),
220            bg_color: None,
221            padding: Padding::default(),
222            margin,
223            constraints,
224            title: None,
225            children: Vec::new(),
226            pos: (0, 0),
227            size: (width, 1),
228            is_scrollable: false,
229            scroll_offset: 0,
230            content_height: 0,
231            cached_wrapped: None,
232            segments: Some(segments),
233            cached_wrapped_segments: None,
234            focus_id: None,
235            link_url: None,
236            group_name: None,
237            overlays: Vec::new(),
238        }
239    }
240
241    fn container(direction: Direction, config: ContainerConfig) -> Self {
242        Self {
243            kind: NodeKind::Container(direction),
244            content: None,
245            style: Style::new(),
246            grow: config.grow,
247            align: config.align,
248            justify: config.justify,
249            wrap: false,
250            gap: config.gap,
251            border: config.border,
252            border_sides: config.border_sides,
253            border_style: config.border_style,
254            bg_color: config.bg_color,
255            padding: config.padding,
256            margin: config.margin,
257            constraints: config.constraints,
258            title: config.title,
259            children: Vec::new(),
260            pos: (0, 0),
261            size: (0, 0),
262            is_scrollable: false,
263            scroll_offset: 0,
264            content_height: 0,
265            cached_wrapped: None,
266            segments: None,
267            cached_wrapped_segments: None,
268            focus_id: None,
269            link_url: None,
270            group_name: None,
271            overlays: Vec::new(),
272        }
273    }
274
275    fn spacer(grow: u16) -> Self {
276        Self {
277            kind: NodeKind::Spacer,
278            content: None,
279            style: Style::new(),
280            grow,
281            align: Align::Start,
282            justify: Justify::Start,
283            wrap: false,
284            gap: 0,
285            border: None,
286            border_sides: BorderSides::all(),
287            border_style: Style::new(),
288            bg_color: None,
289            padding: Padding::default(),
290            margin: Margin::default(),
291            constraints: Constraints::default(),
292            title: None,
293            children: Vec::new(),
294            pos: (0, 0),
295            size: (0, 0),
296            is_scrollable: false,
297            scroll_offset: 0,
298            content_height: 0,
299            cached_wrapped: None,
300            segments: None,
301            cached_wrapped_segments: None,
302            focus_id: None,
303            link_url: None,
304            group_name: None,
305            overlays: Vec::new(),
306        }
307    }
308
309    fn border_inset(&self) -> u32 {
310        if self.border.is_some() {
311            1
312        } else {
313            0
314        }
315    }
316
317    fn border_left_inset(&self) -> u32 {
318        if self.border.is_some() && self.border_sides.left {
319            1
320        } else {
321            0
322        }
323    }
324
325    fn border_right_inset(&self) -> u32 {
326        if self.border.is_some() && self.border_sides.right {
327            1
328        } else {
329            0
330        }
331    }
332
333    fn border_top_inset(&self) -> u32 {
334        if self.border.is_some() && self.border_sides.top {
335            1
336        } else {
337            0
338        }
339    }
340
341    fn border_bottom_inset(&self) -> u32 {
342        if self.border.is_some() && self.border_sides.bottom {
343            1
344        } else {
345            0
346        }
347    }
348
349    fn frame_horizontal(&self) -> u32 {
350        self.padding.horizontal() + self.border_left_inset() + self.border_right_inset()
351    }
352
353    fn frame_vertical(&self) -> u32 {
354        self.padding.vertical() + self.border_top_inset() + self.border_bottom_inset()
355    }
356
357    fn min_width(&self) -> u32 {
358        let width = match self.kind {
359            NodeKind::Text => self.size.0,
360            NodeKind::Spacer | NodeKind::RawDraw(_) => 0,
361            NodeKind::Container(Direction::Row) => {
362                let gaps = if self.children.is_empty() {
363                    0
364                } else {
365                    (self.children.len() as u32 - 1) * self.gap
366                };
367                let children_width: u32 = self.children.iter().map(|c| c.min_width()).sum();
368                children_width + gaps + self.frame_horizontal()
369            }
370            NodeKind::Container(Direction::Column) => {
371                self.children
372                    .iter()
373                    .map(|c| c.min_width())
374                    .max()
375                    .unwrap_or(0)
376                    + self.frame_horizontal()
377            }
378        };
379
380        let width = width.max(self.constraints.min_width.unwrap_or(0));
381        let width = match self.constraints.max_width {
382            Some(max_w) => width.min(max_w),
383            None => width,
384        };
385        width.saturating_add(self.margin.horizontal())
386    }
387
388    fn min_height(&self) -> u32 {
389        let height = match self.kind {
390            NodeKind::Text => 1,
391            NodeKind::Spacer | NodeKind::RawDraw(_) => 0,
392            NodeKind::Container(Direction::Row) => {
393                self.children
394                    .iter()
395                    .map(|c| c.min_height())
396                    .max()
397                    .unwrap_or(0)
398                    + self.frame_vertical()
399            }
400            NodeKind::Container(Direction::Column) => {
401                let gaps = if self.children.is_empty() {
402                    0
403                } else {
404                    (self.children.len() as u32 - 1) * self.gap
405                };
406                let children_height: u32 = self.children.iter().map(|c| c.min_height()).sum();
407                children_height + gaps + self.frame_vertical()
408            }
409        };
410
411        let height = height.max(self.constraints.min_height.unwrap_or(0));
412        height.saturating_add(self.margin.vertical())
413    }
414
415    fn min_height_for_width(&self, available_width: u32) -> u32 {
416        match self.kind {
417            NodeKind::Text if self.wrap => {
418                let inner_width = available_width.saturating_sub(self.margin.horizontal());
419                let lines = if let Some(ref segs) = self.segments {
420                    wrap_segments(segs, inner_width).len().max(1) as u32
421                } else {
422                    let text = self.content.as_deref().unwrap_or("");
423                    wrap_lines(text, inner_width).len().max(1) as u32
424                };
425                lines.saturating_add(self.margin.vertical())
426            }
427            _ => self.min_height(),
428        }
429    }
430}
431
432fn wrap_lines(text: &str, max_width: u32) -> Vec<String> {
433    if text.is_empty() {
434        return vec![String::new()];
435    }
436    if max_width == 0 {
437        return vec![text.to_string()];
438    }
439
440    fn split_long_word(word: &str, max_width: u32) -> Vec<(String, u32)> {
441        let mut chunks: Vec<(String, u32)> = Vec::new();
442        let mut chunk = String::new();
443        let mut chunk_width = 0_u32;
444
445        for ch in word.chars() {
446            let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0) as u32;
447            if chunk.is_empty() {
448                if ch_width > max_width {
449                    chunks.push((ch.to_string(), ch_width));
450                } else {
451                    chunk.push(ch);
452                    chunk_width = ch_width;
453                }
454                continue;
455            }
456
457            if chunk_width + ch_width > max_width {
458                chunks.push((std::mem::take(&mut chunk), chunk_width));
459                if ch_width > max_width {
460                    chunks.push((ch.to_string(), ch_width));
461                    chunk_width = 0;
462                } else {
463                    chunk.push(ch);
464                    chunk_width = ch_width;
465                }
466            } else {
467                chunk.push(ch);
468                chunk_width += ch_width;
469            }
470        }
471
472        if !chunk.is_empty() {
473            chunks.push((chunk, chunk_width));
474        }
475
476        chunks
477    }
478
479    fn push_word_into_line(
480        lines: &mut Vec<String>,
481        current_line: &mut String,
482        current_width: &mut u32,
483        word: &str,
484        word_width: u32,
485        max_width: u32,
486    ) {
487        if word.is_empty() {
488            return;
489        }
490
491        if word_width > max_width {
492            let chunks = split_long_word(word, max_width);
493            for (chunk, chunk_width) in chunks {
494                if current_line.is_empty() {
495                    *current_line = chunk;
496                    *current_width = chunk_width;
497                } else if *current_width + 1 + chunk_width <= max_width {
498                    current_line.push(' ');
499                    current_line.push_str(&chunk);
500                    *current_width += 1 + chunk_width;
501                } else {
502                    lines.push(std::mem::take(current_line));
503                    *current_line = chunk;
504                    *current_width = chunk_width;
505                }
506            }
507            return;
508        }
509
510        if current_line.is_empty() {
511            *current_line = word.to_string();
512            *current_width = word_width;
513        } else if *current_width + 1 + word_width <= max_width {
514            current_line.push(' ');
515            current_line.push_str(word);
516            *current_width += 1 + word_width;
517        } else {
518            lines.push(std::mem::take(current_line));
519            *current_line = word.to_string();
520            *current_width = word_width;
521        }
522    }
523
524    let mut lines: Vec<String> = Vec::new();
525    let mut current_line = String::new();
526    let mut current_width: u32 = 0;
527    let mut current_word = String::new();
528    let mut word_width: u32 = 0;
529
530    for ch in text.chars() {
531        if ch == ' ' {
532            push_word_into_line(
533                &mut lines,
534                &mut current_line,
535                &mut current_width,
536                &current_word,
537                word_width,
538                max_width,
539            );
540            current_word.clear();
541            word_width = 0;
542            continue;
543        }
544
545        current_word.push(ch);
546        word_width += UnicodeWidthChar::width(ch).unwrap_or(0) as u32;
547    }
548
549    push_word_into_line(
550        &mut lines,
551        &mut current_line,
552        &mut current_width,
553        &current_word,
554        word_width,
555        max_width,
556    );
557
558    if !current_line.is_empty() {
559        lines.push(current_line);
560    }
561
562    if lines.is_empty() {
563        vec![String::new()]
564    } else {
565        lines
566    }
567}
568
569fn wrap_segments(segments: &[(String, Style)], max_width: u32) -> Vec<Vec<(String, Style)>> {
570    if max_width == 0 || segments.is_empty() {
571        return vec![vec![]];
572    }
573    let mut chars: Vec<(char, Style)> = Vec::new();
574    for (text, style) in segments {
575        for ch in text.chars() {
576            chars.push((ch, *style));
577        }
578    }
579    if chars.is_empty() {
580        return vec![vec![]];
581    }
582
583    let mut lines: Vec<Vec<(String, Style)>> = Vec::new();
584    let mut i = 0;
585    while i < chars.len() {
586        let mut line_chars: Vec<(char, Style)> = Vec::new();
587        let mut line_width: u32 = 0;
588
589        if !lines.is_empty() {
590            while i < chars.len() && chars[i].0 == ' ' {
591                i += 1;
592            }
593        }
594
595        while i < chars.len() {
596            let (ch, st) = chars[i];
597            let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0) as u32;
598            if line_width + ch_width > max_width && line_width > 0 {
599                if let Some(bp) = line_chars.iter().rposition(|(c, _)| *c == ' ') {
600                    let rewind = line_chars.len() - bp - 1;
601                    i -= rewind;
602                    line_chars.truncate(bp);
603                }
604                break;
605            }
606            line_chars.push((ch, st));
607            line_width += ch_width;
608            i += 1;
609        }
610
611        let mut line_segs: Vec<(String, Style)> = Vec::new();
612        let mut cur = String::new();
613        let mut cur_style: Option<Style> = None;
614        for (ch, st) in &line_chars {
615            if cur_style == Some(*st) {
616                cur.push(*ch);
617            } else {
618                if let Some(s) = cur_style {
619                    if !cur.is_empty() {
620                        line_segs.push((std::mem::take(&mut cur), s));
621                    }
622                }
623                cur_style = Some(*st);
624                cur.push(*ch);
625            }
626        }
627        if let Some(s) = cur_style {
628            if !cur.is_empty() {
629                let trimmed = cur.trim_end().to_string();
630                if !trimmed.is_empty() {
631                    line_segs.push((trimmed, s));
632                } else if !line_segs.is_empty() {
633                    if let Some(last) = line_segs.last_mut() {
634                        let t = last.0.trim_end().to_string();
635                        if t.is_empty() {
636                            line_segs.pop();
637                        } else {
638                            last.0 = t;
639                        }
640                    }
641                }
642            }
643        }
644        lines.push(line_segs);
645    }
646    if lines.is_empty() {
647        vec![vec![]]
648    } else {
649        lines
650    }
651}
652
653pub(crate) fn build_tree(commands: &[Command]) -> LayoutNode {
654    let mut root = LayoutNode::container(Direction::Column, default_container_config());
655    let mut overlays: Vec<OverlayLayer> = Vec::new();
656    build_children(&mut root, commands, &mut 0, &mut overlays, false);
657    root.overlays = overlays;
658    root
659}
660
661fn default_container_config() -> ContainerConfig {
662    ContainerConfig {
663        gap: 0,
664        align: Align::Start,
665        justify: Justify::Start,
666        border: None,
667        border_sides: BorderSides::all(),
668        border_style: Style::new(),
669        bg_color: None,
670        padding: Padding::default(),
671        margin: Margin::default(),
672        constraints: Constraints::default(),
673        title: None,
674        grow: 0,
675    }
676}
677
678fn build_children(
679    parent: &mut LayoutNode,
680    commands: &[Command],
681    pos: &mut usize,
682    overlays: &mut Vec<OverlayLayer>,
683    stop_on_end_overlay: bool,
684) {
685    let mut pending_focus_id: Option<usize> = None;
686    while *pos < commands.len() {
687        match &commands[*pos] {
688            Command::FocusMarker(id) => {
689                pending_focus_id = Some(*id);
690                *pos += 1;
691            }
692            Command::Text {
693                content,
694                style,
695                grow,
696                align,
697                wrap,
698                margin,
699                constraints,
700            } => {
701                let mut node = LayoutNode::text(
702                    content.clone(),
703                    *style,
704                    *grow,
705                    *align,
706                    *wrap,
707                    *margin,
708                    *constraints,
709                );
710                node.focus_id = pending_focus_id.take();
711                parent.children.push(node);
712                *pos += 1;
713            }
714            Command::RichText {
715                segments,
716                wrap,
717                align,
718                margin,
719                constraints,
720            } => {
721                let mut node =
722                    LayoutNode::rich_text(segments.clone(), *wrap, *align, *margin, *constraints);
723                node.focus_id = pending_focus_id.take();
724                parent.children.push(node);
725                *pos += 1;
726            }
727            Command::Link {
728                text,
729                url,
730                style,
731                margin,
732                constraints,
733            } => {
734                let mut node = LayoutNode::text(
735                    text.clone(),
736                    *style,
737                    0,
738                    Align::Start,
739                    false,
740                    *margin,
741                    *constraints,
742                );
743                node.link_url = Some(url.clone());
744                node.focus_id = pending_focus_id.take();
745                parent.children.push(node);
746                *pos += 1;
747            }
748            Command::BeginContainer {
749                direction,
750                gap,
751                align,
752                justify,
753                border,
754                border_sides,
755                border_style,
756                bg_color,
757                padding,
758                margin,
759                constraints,
760                title,
761                grow,
762                group_name,
763            } => {
764                let mut node = LayoutNode::container(
765                    *direction,
766                    ContainerConfig {
767                        gap: *gap,
768                        align: *align,
769                        justify: *justify,
770                        border: *border,
771                        border_sides: *border_sides,
772                        border_style: *border_style,
773                        bg_color: *bg_color,
774                        padding: *padding,
775                        margin: *margin,
776                        constraints: *constraints,
777                        title: title.clone(),
778                        grow: *grow,
779                    },
780                );
781                node.focus_id = pending_focus_id.take();
782                node.group_name = group_name.clone();
783                *pos += 1;
784                build_children(&mut node, commands, pos, overlays, false);
785                parent.children.push(node);
786            }
787            Command::BeginScrollable {
788                grow,
789                border,
790                border_sides,
791                border_style,
792                padding,
793                margin,
794                constraints,
795                title,
796                scroll_offset,
797            } => {
798                let mut node = LayoutNode::container(
799                    Direction::Column,
800                    ContainerConfig {
801                        gap: 0,
802                        align: Align::Start,
803                        justify: Justify::Start,
804                        border: *border,
805                        border_sides: *border_sides,
806                        border_style: *border_style,
807                        bg_color: None,
808                        padding: *padding,
809                        margin: *margin,
810                        constraints: *constraints,
811                        title: title.clone(),
812                        grow: *grow,
813                    },
814                );
815                node.is_scrollable = true;
816                node.scroll_offset = *scroll_offset;
817                node.focus_id = pending_focus_id.take();
818                *pos += 1;
819                build_children(&mut node, commands, pos, overlays, false);
820                parent.children.push(node);
821            }
822            Command::BeginOverlay { modal } => {
823                *pos += 1;
824                let mut overlay_node =
825                    LayoutNode::container(Direction::Column, default_container_config());
826                build_children(&mut overlay_node, commands, pos, overlays, true);
827                overlays.push(OverlayLayer {
828                    node: overlay_node,
829                    modal: *modal,
830                });
831            }
832            Command::Spacer { grow } => {
833                parent.children.push(LayoutNode::spacer(*grow));
834                *pos += 1;
835            }
836            Command::RawDraw {
837                draw_id,
838                constraints,
839                grow,
840                margin,
841            } => {
842                let node = LayoutNode {
843                    kind: NodeKind::RawDraw(*draw_id),
844                    content: None,
845                    style: Style::new(),
846                    grow: *grow,
847                    align: Align::Start,
848                    justify: Justify::Start,
849                    wrap: false,
850                    gap: 0,
851                    border: None,
852                    border_sides: BorderSides::all(),
853                    border_style: Style::new(),
854                    bg_color: None,
855                    padding: Padding::default(),
856                    margin: *margin,
857                    constraints: *constraints,
858                    title: None,
859                    children: Vec::new(),
860                    pos: (0, 0),
861                    size: (
862                        constraints.min_width.unwrap_or(0),
863                        constraints.min_height.unwrap_or(0),
864                    ),
865                    is_scrollable: false,
866                    scroll_offset: 0,
867                    content_height: 0,
868                    cached_wrapped: None,
869                    segments: None,
870                    cached_wrapped_segments: None,
871                    focus_id: pending_focus_id.take(),
872                    link_url: None,
873                    group_name: None,
874                    overlays: Vec::new(),
875                };
876                parent.children.push(node);
877                *pos += 1;
878            }
879            Command::EndContainer => {
880                *pos += 1;
881                return;
882            }
883            Command::EndOverlay => {
884                *pos += 1;
885                if stop_on_end_overlay {
886                    return;
887                }
888            }
889        }
890    }
891}
892
893pub(crate) fn compute(node: &mut LayoutNode, area: Rect) {
894    if let Some(pct) = node.constraints.width_pct {
895        let resolved = (area.width as u64 * pct.min(100) as u64 / 100) as u32;
896        node.constraints.min_width = Some(resolved);
897        node.constraints.max_width = Some(resolved);
898        node.constraints.width_pct = None;
899    }
900    if let Some(pct) = node.constraints.height_pct {
901        let resolved = (area.height as u64 * pct.min(100) as u64 / 100) as u32;
902        node.constraints.min_height = Some(resolved);
903        node.constraints.max_height = Some(resolved);
904        node.constraints.height_pct = None;
905    }
906
907    node.pos = (area.x, area.y);
908    node.size = (
909        area.width.clamp(
910            node.constraints.min_width.unwrap_or(0),
911            node.constraints.max_width.unwrap_or(u32::MAX),
912        ),
913        area.height.clamp(
914            node.constraints.min_height.unwrap_or(0),
915            node.constraints.max_height.unwrap_or(u32::MAX),
916        ),
917    );
918
919    if matches!(node.kind, NodeKind::Text) && node.wrap {
920        if let Some(ref segs) = node.segments {
921            let wrapped = wrap_segments(segs, area.width);
922            node.size = (area.width, wrapped.len().max(1) as u32);
923            node.cached_wrapped_segments = Some(wrapped);
924            node.cached_wrapped = None;
925        } else {
926            let lines = wrap_lines(node.content.as_deref().unwrap_or(""), area.width);
927            node.size = (area.width, lines.len().max(1) as u32);
928            node.cached_wrapped = Some(lines);
929            node.cached_wrapped_segments = None;
930        }
931    } else {
932        node.cached_wrapped = None;
933        node.cached_wrapped_segments = None;
934    }
935
936    match node.kind {
937        NodeKind::Text | NodeKind::Spacer | NodeKind::RawDraw(_) => {}
938        NodeKind::Container(Direction::Row) => {
939            layout_row(
940                node,
941                inner_area(
942                    node,
943                    Rect::new(node.pos.0, node.pos.1, node.size.0, node.size.1),
944                ),
945            );
946            node.content_height = 0;
947        }
948        NodeKind::Container(Direction::Column) => {
949            let viewport_area = inner_area(
950                node,
951                Rect::new(node.pos.0, node.pos.1, node.size.0, node.size.1),
952            );
953            if node.is_scrollable {
954                let saved_grows: Vec<u16> = node.children.iter().map(|c| c.grow).collect();
955                for child in &mut node.children {
956                    child.grow = 0;
957                }
958                let total_gaps = if node.children.is_empty() {
959                    0
960                } else {
961                    (node.children.len() as u32 - 1) * node.gap
962                };
963                let natural_height: u32 = node
964                    .children
965                    .iter()
966                    .map(|c| c.min_height_for_width(viewport_area.width))
967                    .sum::<u32>()
968                    + total_gaps;
969
970                if natural_height > viewport_area.height {
971                    let virtual_area = Rect::new(
972                        viewport_area.x,
973                        viewport_area.y,
974                        viewport_area.width,
975                        natural_height,
976                    );
977                    layout_column(node, virtual_area);
978                } else {
979                    for (child, &grow) in node.children.iter_mut().zip(saved_grows.iter()) {
980                        child.grow = grow;
981                    }
982                    layout_column(node, viewport_area);
983                }
984                node.content_height = scroll_content_height(node, viewport_area.y);
985            } else {
986                layout_column(node, viewport_area);
987                node.content_height = 0;
988            }
989        }
990    }
991
992    for overlay in &mut node.overlays {
993        let width = overlay.node.min_width().min(area.width);
994        let height = overlay.node.min_height_for_width(width).min(area.height);
995        let x = area.x.saturating_add(area.width.saturating_sub(width) / 2);
996        let y = area
997            .y
998            .saturating_add(area.height.saturating_sub(height) / 2);
999        compute(&mut overlay.node, Rect::new(x, y, width, height));
1000    }
1001}
1002
1003fn scroll_content_height(node: &LayoutNode, inner_y: u32) -> u32 {
1004    let Some(max_bottom) = node
1005        .children
1006        .iter()
1007        .map(|child| {
1008            child
1009                .pos
1010                .1
1011                .saturating_add(child.size.1)
1012                .saturating_add(child.margin.bottom)
1013        })
1014        .max()
1015    else {
1016        return 0;
1017    };
1018
1019    max_bottom.saturating_sub(inner_y)
1020}
1021
1022fn justify_offsets(justify: Justify, remaining: u32, n: u32, gap: u32) -> (u32, u32) {
1023    if n <= 1 {
1024        let start = match justify {
1025            Justify::Center => remaining / 2,
1026            Justify::End => remaining,
1027            _ => 0,
1028        };
1029        return (start, gap);
1030    }
1031
1032    match justify {
1033        Justify::Start => (0, gap),
1034        Justify::Center => (remaining.saturating_sub((n - 1) * gap) / 2, gap),
1035        Justify::End => (remaining.saturating_sub((n - 1) * gap), gap),
1036        Justify::SpaceBetween => (0, remaining / (n - 1)),
1037        Justify::SpaceAround => {
1038            let slot = remaining / n;
1039            (slot / 2, slot)
1040        }
1041        Justify::SpaceEvenly => {
1042            let slot = remaining / (n + 1);
1043            (slot, slot)
1044        }
1045    }
1046}
1047
1048fn inner_area(node: &LayoutNode, area: Rect) -> Rect {
1049    let x = area.x + node.border_left_inset() + node.padding.left;
1050    let y = area.y + node.border_top_inset() + node.padding.top;
1051    let width = area
1052        .width
1053        .saturating_sub(node.border_left_inset() + node.border_right_inset())
1054        .saturating_sub(node.padding.horizontal());
1055    let height = area
1056        .height
1057        .saturating_sub(node.border_top_inset() + node.border_bottom_inset())
1058        .saturating_sub(node.padding.vertical());
1059
1060    Rect::new(x, y, width, height)
1061}
1062
1063fn layout_row(node: &mut LayoutNode, area: Rect) {
1064    if node.children.is_empty() {
1065        return;
1066    }
1067
1068    for child in &mut node.children {
1069        if let Some(pct) = child.constraints.width_pct {
1070            let resolved = (area.width as u64 * pct.min(100) as u64 / 100) as u32;
1071            child.constraints.min_width = Some(resolved);
1072            child.constraints.max_width = Some(resolved);
1073            child.constraints.width_pct = None;
1074        }
1075        if let Some(pct) = child.constraints.height_pct {
1076            let resolved = (area.height as u64 * pct.min(100) as u64 / 100) as u32;
1077            child.constraints.min_height = Some(resolved);
1078            child.constraints.max_height = Some(resolved);
1079            child.constraints.height_pct = None;
1080        }
1081    }
1082
1083    let n = node.children.len() as u32;
1084    let total_gaps = (n - 1) * node.gap;
1085    let available = area.width.saturating_sub(total_gaps);
1086    let min_widths: Vec<u32> = node
1087        .children
1088        .iter()
1089        .map(|child| child.min_width())
1090        .collect();
1091
1092    let mut total_grow: u32 = 0;
1093    let mut fixed_width: u32 = 0;
1094    for (child, &min_width) in node.children.iter().zip(min_widths.iter()) {
1095        if child.grow > 0 {
1096            total_grow += child.grow as u32;
1097        } else {
1098            fixed_width += min_width;
1099        }
1100    }
1101
1102    let mut flex_space = available.saturating_sub(fixed_width);
1103    let mut remaining_grow = total_grow;
1104
1105    let mut child_widths: Vec<u32> = Vec::with_capacity(node.children.len());
1106    for (i, child) in node.children.iter().enumerate() {
1107        let w = if child.grow > 0 && total_grow > 0 {
1108            let share = if remaining_grow == 0 {
1109                0
1110            } else {
1111                flex_space * child.grow as u32 / remaining_grow
1112            };
1113            flex_space = flex_space.saturating_sub(share);
1114            remaining_grow = remaining_grow.saturating_sub(child.grow as u32);
1115            share
1116        } else {
1117            min_widths[i].min(available)
1118        };
1119        child_widths.push(w);
1120    }
1121
1122    let total_children_width: u32 = child_widths.iter().sum();
1123    let remaining = area.width.saturating_sub(total_children_width);
1124    let (start_offset, inter_gap) = justify_offsets(node.justify, remaining, n, node.gap);
1125
1126    let mut x = area.x + start_offset;
1127    for (i, child) in node.children.iter_mut().enumerate() {
1128        let w = child_widths[i];
1129        let child_outer_h = match node.align {
1130            Align::Start => area.height,
1131            _ => child.min_height_for_width(w).min(area.height),
1132        };
1133        let child_x = x.saturating_add(child.margin.left);
1134        let child_y = area.y.saturating_add(child.margin.top);
1135        let child_w = w.saturating_sub(child.margin.horizontal());
1136        let child_h = child_outer_h.saturating_sub(child.margin.vertical());
1137        compute(child, Rect::new(child_x, child_y, child_w, child_h));
1138        let child_total_h = child.size.1.saturating_add(child.margin.vertical());
1139        let y_offset = match node.align {
1140            Align::Start => 0,
1141            Align::Center => area.height.saturating_sub(child_total_h) / 2,
1142            Align::End => area.height.saturating_sub(child_total_h),
1143        };
1144        child.pos.1 = child.pos.1.saturating_add(y_offset);
1145        x += w + inter_gap;
1146    }
1147}
1148
1149fn layout_column(node: &mut LayoutNode, area: Rect) {
1150    if node.children.is_empty() {
1151        return;
1152    }
1153
1154    for child in &mut node.children {
1155        if let Some(pct) = child.constraints.width_pct {
1156            let resolved = (area.width as u64 * pct.min(100) as u64 / 100) as u32;
1157            child.constraints.min_width = Some(resolved);
1158            child.constraints.max_width = Some(resolved);
1159            child.constraints.width_pct = None;
1160        }
1161        if let Some(pct) = child.constraints.height_pct {
1162            let resolved = (area.height as u64 * pct.min(100) as u64 / 100) as u32;
1163            child.constraints.min_height = Some(resolved);
1164            child.constraints.max_height = Some(resolved);
1165            child.constraints.height_pct = None;
1166        }
1167    }
1168
1169    let n = node.children.len() as u32;
1170    let total_gaps = (n - 1) * node.gap;
1171    let available = area.height.saturating_sub(total_gaps);
1172    let min_heights: Vec<u32> = node
1173        .children
1174        .iter()
1175        .map(|child| child.min_height_for_width(area.width))
1176        .collect();
1177
1178    let mut total_grow: u32 = 0;
1179    let mut fixed_height: u32 = 0;
1180    for (child, &min_height) in node.children.iter().zip(min_heights.iter()) {
1181        if child.grow > 0 {
1182            total_grow += child.grow as u32;
1183        } else {
1184            fixed_height += min_height;
1185        }
1186    }
1187
1188    let mut flex_space = available.saturating_sub(fixed_height);
1189    let mut remaining_grow = total_grow;
1190
1191    let mut child_heights: Vec<u32> = Vec::with_capacity(node.children.len());
1192    for (i, child) in node.children.iter().enumerate() {
1193        let h = if child.grow > 0 && total_grow > 0 {
1194            let share = if remaining_grow == 0 {
1195                0
1196            } else {
1197                flex_space * child.grow as u32 / remaining_grow
1198            };
1199            flex_space = flex_space.saturating_sub(share);
1200            remaining_grow = remaining_grow.saturating_sub(child.grow as u32);
1201            share
1202        } else {
1203            min_heights[i].min(available)
1204        };
1205        child_heights.push(h);
1206    }
1207
1208    let total_children_height: u32 = child_heights.iter().sum();
1209    let remaining = area.height.saturating_sub(total_children_height);
1210    let (start_offset, inter_gap) = justify_offsets(node.justify, remaining, n, node.gap);
1211
1212    let mut y = area.y + start_offset;
1213    for (i, child) in node.children.iter_mut().enumerate() {
1214        let h = child_heights[i];
1215        let child_outer_w = match node.align {
1216            Align::Start => area.width,
1217            _ => child.min_width().min(area.width),
1218        };
1219        let child_x = area.x.saturating_add(child.margin.left);
1220        let child_y = y.saturating_add(child.margin.top);
1221        let child_w = child_outer_w.saturating_sub(child.margin.horizontal());
1222        let child_h = h.saturating_sub(child.margin.vertical());
1223        compute(child, Rect::new(child_x, child_y, child_w, child_h));
1224        let child_total_w = child.size.0.saturating_add(child.margin.horizontal());
1225        let x_offset = match node.align {
1226            Align::Start => 0,
1227            Align::Center => area.width.saturating_sub(child_total_w) / 2,
1228            Align::End => area.width.saturating_sub(child_total_w),
1229        };
1230        child.pos.0 = child.pos.0.saturating_add(x_offset);
1231        y += h + inter_gap;
1232    }
1233}
1234
1235pub(crate) fn render(node: &LayoutNode, buf: &mut Buffer) {
1236    render_inner(node, buf, 0, None);
1237    buf.clip_stack.clear();
1238    for overlay in &node.overlays {
1239        if overlay.modal {
1240            dim_entire_buffer(buf);
1241        }
1242        render_inner(&overlay.node, buf, 0, None);
1243    }
1244}
1245
1246fn dim_entire_buffer(buf: &mut Buffer) {
1247    for y in buf.area.y..buf.area.bottom() {
1248        for x in buf.area.x..buf.area.right() {
1249            let cell = buf.get_mut(x, y);
1250            cell.style.modifiers |= crate::style::Modifiers::DIM;
1251        }
1252    }
1253}
1254
1255pub(crate) fn render_debug_overlay(
1256    node: &LayoutNode,
1257    buf: &mut Buffer,
1258    frame_time_us: u64,
1259    fps: f32,
1260) {
1261    for child in &node.children {
1262        render_debug_overlay_inner(child, buf, 0, 0);
1263    }
1264    render_debug_status_bar(node, buf, frame_time_us, fps);
1265}
1266
1267fn render_debug_status_bar(node: &LayoutNode, buf: &mut Buffer, frame_time_us: u64, fps: f32) {
1268    if buf.area.height == 0 || buf.area.width == 0 {
1269        return;
1270    }
1271
1272    let widgets: u32 = node.children.iter().map(count_leaf_widgets).sum();
1273    let width = buf.area.width;
1274    let height = buf.area.height;
1275    let y = buf.area.bottom() - 1;
1276    let style = Style::new().fg(Color::Black).bg(Color::Yellow).bold();
1277
1278    let status = format!(
1279        "[SLT Debug] {}x{} | {} widgets | {:.1}ms | {:.0}fps",
1280        width,
1281        height,
1282        widgets,
1283        frame_time_us as f64 / 1_000.0,
1284        fps.max(0.0)
1285    );
1286
1287    let row_fill = " ".repeat(width as usize);
1288    buf.set_string(buf.area.x, y, &row_fill, style);
1289    buf.set_string(buf.area.x, y, &status, style);
1290}
1291
1292fn count_leaf_widgets(node: &LayoutNode) -> u32 {
1293    let mut total = if node.children.is_empty() {
1294        match node.kind {
1295            NodeKind::Spacer => 0,
1296            _ => 1,
1297        }
1298    } else {
1299        node.children.iter().map(count_leaf_widgets).sum()
1300    };
1301
1302    for overlay in &node.overlays {
1303        total = total.saturating_add(count_leaf_widgets(&overlay.node));
1304    }
1305
1306    total
1307}
1308
1309fn render_debug_overlay_inner(node: &LayoutNode, buf: &mut Buffer, depth: u32, y_offset: u32) {
1310    let child_offset = if node.is_scrollable {
1311        y_offset.saturating_add(node.scroll_offset)
1312    } else {
1313        y_offset
1314    };
1315
1316    if let NodeKind::Container(_) = node.kind {
1317        let sy = screen_y(node.pos.1, y_offset);
1318        if sy + node.size.1 as i64 > 0 {
1319            let color = debug_color_for_depth(depth);
1320            let style = Style::new().fg(color);
1321            let clamped_y = sy.max(0) as u32;
1322            draw_debug_border(node.pos.0, clamped_y, node.size.0, node.size.1, buf, style);
1323            if sy >= 0 {
1324                buf.set_string(node.pos.0, clamped_y, &depth.to_string(), style);
1325            }
1326        }
1327    }
1328
1329    if node.is_scrollable {
1330        if let Some(area) = visible_area(node, y_offset) {
1331            let inner = inner_area(node, area);
1332            buf.push_clip(inner);
1333            for child in &node.children {
1334                render_debug_overlay_inner(child, buf, depth.saturating_add(1), child_offset);
1335            }
1336            buf.pop_clip();
1337        }
1338    } else {
1339        for child in &node.children {
1340            render_debug_overlay_inner(child, buf, depth.saturating_add(1), child_offset);
1341        }
1342    }
1343}
1344
1345fn debug_color_for_depth(depth: u32) -> Color {
1346    match depth {
1347        0 => Color::Cyan,
1348        1 => Color::Yellow,
1349        2 => Color::Magenta,
1350        _ => Color::Red,
1351    }
1352}
1353
1354fn draw_debug_border(x: u32, y: u32, w: u32, h: u32, buf: &mut Buffer, style: Style) {
1355    if w == 0 || h == 0 {
1356        return;
1357    }
1358    let right = x + w - 1;
1359    let bottom = y + h - 1;
1360
1361    if w == 1 && h == 1 {
1362        buf.set_char(x, y, '┼', style);
1363        return;
1364    }
1365    if h == 1 {
1366        for xx in x..=right {
1367            buf.set_char(xx, y, '─', style);
1368        }
1369        return;
1370    }
1371    if w == 1 {
1372        for yy in y..=bottom {
1373            buf.set_char(x, yy, '│', style);
1374        }
1375        return;
1376    }
1377
1378    buf.set_char(x, y, '┌', style);
1379    buf.set_char(right, y, '┐', style);
1380    buf.set_char(x, bottom, '└', style);
1381    buf.set_char(right, bottom, '┘', style);
1382
1383    for xx in (x + 1)..right {
1384        buf.set_char(xx, y, '─', style);
1385        buf.set_char(xx, bottom, '─', style);
1386    }
1387    for yy in (y + 1)..bottom {
1388        buf.set_char(x, yy, '│', style);
1389        buf.set_char(right, yy, '│', style);
1390    }
1391}
1392
1393#[allow(dead_code)]
1394fn draw_debug_padding_markers(node: &LayoutNode, y_offset: u32, buf: &mut Buffer, style: Style) {
1395    if node.size.0 == 0 || node.size.1 == 0 {
1396        return;
1397    }
1398
1399    if node.padding == Padding::default() {
1400        return;
1401    }
1402
1403    let Some(area) = visible_area(node, y_offset) else {
1404        return;
1405    };
1406    let inner = inner_area(node, area);
1407    if inner.width == 0 || inner.height == 0 {
1408        return;
1409    }
1410
1411    let right = inner.right() - 1;
1412    let bottom = inner.bottom() - 1;
1413    buf.set_char(inner.x, inner.y, 'p', style);
1414    buf.set_char(right, inner.y, 'p', style);
1415    buf.set_char(inner.x, bottom, 'p', style);
1416    buf.set_char(right, bottom, 'p', style);
1417}
1418
1419#[allow(dead_code)]
1420fn draw_debug_margin_markers(node: &LayoutNode, y_offset: u32, buf: &mut Buffer, style: Style) {
1421    if node.margin == Margin::default() {
1422        return;
1423    }
1424
1425    let margin_y_i = node.pos.1 as i64 - node.margin.top as i64 - y_offset as i64;
1426    let w = node
1427        .size
1428        .0
1429        .saturating_add(node.margin.horizontal())
1430        .max(node.margin.horizontal());
1431    let h = node
1432        .size
1433        .1
1434        .saturating_add(node.margin.vertical())
1435        .max(node.margin.vertical());
1436
1437    if w == 0 || h == 0 || margin_y_i + h as i64 <= 0 {
1438        return;
1439    }
1440
1441    let x = node.pos.0.saturating_sub(node.margin.left);
1442    let y = margin_y_i.max(0) as u32;
1443    let bottom_i = margin_y_i + h as i64 - 1;
1444    if bottom_i < 0 {
1445        return;
1446    }
1447    let right = x + w - 1;
1448    let bottom = bottom_i as u32;
1449    if margin_y_i >= 0 {
1450        buf.set_char(x, y, 'm', style);
1451        buf.set_char(right, y, 'm', style);
1452    }
1453    buf.set_char(x, bottom, 'm', style);
1454    buf.set_char(right, bottom, 'm', style);
1455}
1456
1457fn screen_y(layout_y: u32, y_offset: u32) -> i64 {
1458    layout_y as i64 - y_offset as i64
1459}
1460
1461fn visible_area(node: &LayoutNode, y_offset: u32) -> Option<Rect> {
1462    let sy = screen_y(node.pos.1, y_offset);
1463    let bottom = sy + node.size.1 as i64;
1464    if bottom <= 0 || node.size.0 == 0 || node.size.1 == 0 {
1465        return None;
1466    }
1467    let clamped_y = sy.max(0) as u32;
1468    let clamped_h = (bottom as u32).saturating_sub(clamped_y);
1469    Some(Rect::new(node.pos.0, clamped_y, node.size.0, clamped_h))
1470}
1471
1472fn render_inner(node: &LayoutNode, buf: &mut Buffer, y_offset: u32, parent_bg: Option<Color>) {
1473    if node.size.0 == 0 || node.size.1 == 0 {
1474        return;
1475    }
1476
1477    let sy = screen_y(node.pos.1, y_offset);
1478    let sx = i64::from(node.pos.0);
1479    let ex = sx.saturating_add(i64::from(node.size.0));
1480    let ey = sy.saturating_add(i64::from(node.size.1));
1481    let viewport_left = i64::from(buf.area.x);
1482    let viewport_top = i64::from(buf.area.y);
1483    let viewport_right = viewport_left.saturating_add(i64::from(buf.area.width));
1484    let viewport_bottom = viewport_top.saturating_add(i64::from(buf.area.height));
1485
1486    if ex <= viewport_left || ey <= viewport_top || sx >= viewport_right || sy >= viewport_bottom {
1487        return;
1488    }
1489
1490    match node.kind {
1491        NodeKind::Text => {
1492            if let Some(ref segs) = node.segments {
1493                if node.wrap {
1494                    let fallback;
1495                    let wrapped = if let Some(cached) = &node.cached_wrapped_segments {
1496                        cached.as_slice()
1497                    } else {
1498                        fallback = wrap_segments(segs, node.size.0);
1499                        &fallback
1500                    };
1501                    for (i, line_segs) in wrapped.iter().enumerate() {
1502                        let line_y = sy + i as i64;
1503                        if line_y < 0 {
1504                            continue;
1505                        }
1506                        let mut x = node.pos.0;
1507                        for (text, style) in line_segs {
1508                            let mut s = *style;
1509                            if s.bg.is_none() {
1510                                s.bg = parent_bg;
1511                            }
1512                            buf.set_string(x, line_y as u32, text, s);
1513                            x += UnicodeWidthStr::width(text.as_str()) as u32;
1514                        }
1515                    }
1516                } else {
1517                    if sy < 0 {
1518                        return;
1519                    }
1520                    let mut x = node.pos.0;
1521                    for (text, style) in segs {
1522                        let mut s = *style;
1523                        if s.bg.is_none() {
1524                            s.bg = parent_bg;
1525                        }
1526                        buf.set_string(x, sy as u32, text, s);
1527                        x += UnicodeWidthStr::width(text.as_str()) as u32;
1528                    }
1529                }
1530            } else if let Some(ref text) = node.content {
1531                let mut style = node.style;
1532                if style.bg.is_none() {
1533                    style.bg = parent_bg;
1534                }
1535                if node.wrap {
1536                    let fallback;
1537                    let lines = if let Some(cached) = &node.cached_wrapped {
1538                        cached.as_slice()
1539                    } else {
1540                        fallback = wrap_lines(text, node.size.0);
1541                        fallback.as_slice()
1542                    };
1543                    for (i, line) in lines.iter().enumerate() {
1544                        let line_y = sy + i as i64;
1545                        if line_y < 0 {
1546                            continue;
1547                        }
1548                        let text_width = UnicodeWidthStr::width(line.as_str()) as u32;
1549                        let x_offset = if text_width < node.size.0 {
1550                            match node.align {
1551                                Align::Start => 0,
1552                                Align::Center => (node.size.0 - text_width) / 2,
1553                                Align::End => node.size.0 - text_width,
1554                            }
1555                        } else {
1556                            0
1557                        };
1558                        buf.set_string(
1559                            node.pos.0.saturating_add(x_offset),
1560                            line_y as u32,
1561                            line,
1562                            style,
1563                        );
1564                    }
1565                } else {
1566                    if sy < 0 {
1567                        return;
1568                    }
1569                    let text_width = UnicodeWidthStr::width(text.as_str()) as u32;
1570                    let x_offset = if text_width < node.size.0 {
1571                        match node.align {
1572                            Align::Start => 0,
1573                            Align::Center => (node.size.0 - text_width) / 2,
1574                            Align::End => node.size.0 - text_width,
1575                        }
1576                    } else {
1577                        0
1578                    };
1579                    let draw_x = node.pos.0.saturating_add(x_offset);
1580                    if let Some(ref url) = node.link_url {
1581                        buf.set_string_linked(draw_x, sy as u32, text, style, url);
1582                    } else {
1583                        buf.set_string(draw_x, sy as u32, text, style);
1584                    }
1585                }
1586            }
1587        }
1588        NodeKind::Spacer | NodeKind::RawDraw(_) => {}
1589        NodeKind::Container(_) => {
1590            if let Some(color) = node.bg_color {
1591                if let Some(area) = visible_area(node, y_offset) {
1592                    let fill_style = Style::new().bg(color);
1593                    for y in area.y..area.bottom() {
1594                        for x in area.x..area.right() {
1595                            buf.set_string(x, y, " ", fill_style);
1596                        }
1597                    }
1598                }
1599            }
1600            let child_bg = node.bg_color.or(parent_bg);
1601            render_container_border(node, buf, y_offset, child_bg);
1602            if node.is_scrollable {
1603                let Some(area) = visible_area(node, y_offset) else {
1604                    return;
1605                };
1606                let inner = inner_area(node, area);
1607                let child_offset = y_offset.saturating_add(node.scroll_offset);
1608                let render_y_start = inner.y as i64;
1609                let render_y_end = inner.bottom() as i64;
1610                buf.push_clip(inner);
1611                for child in &node.children {
1612                    let child_top = child.pos.1 as i64 - child_offset as i64;
1613                    let child_bottom = child_top + child.size.1 as i64;
1614                    if child_bottom <= render_y_start || child_top >= render_y_end {
1615                        continue;
1616                    }
1617                    render_inner(child, buf, child_offset, child_bg);
1618                }
1619                buf.pop_clip();
1620                render_scroll_indicators(node, inner, buf, child_bg);
1621            } else {
1622                let Some(area) = visible_area(node, y_offset) else {
1623                    return;
1624                };
1625                let clip = inner_area(node, area);
1626                buf.push_clip(clip);
1627                for child in &node.children {
1628                    render_inner(child, buf, y_offset, child_bg);
1629                }
1630                buf.pop_clip();
1631            }
1632        }
1633    }
1634}
1635
1636fn render_container_border(
1637    node: &LayoutNode,
1638    buf: &mut Buffer,
1639    y_offset: u32,
1640    inherit_bg: Option<Color>,
1641) {
1642    if node.border_inset() == 0 {
1643        return;
1644    }
1645    let Some(border) = node.border else {
1646        return;
1647    };
1648    let sides = node.border_sides;
1649    let chars = border.chars();
1650    let x = node.pos.0;
1651    let w = node.size.0;
1652    let h = node.size.1;
1653    if w == 0 || h == 0 {
1654        return;
1655    }
1656
1657    let mut style = node.border_style;
1658    if style.bg.is_none() {
1659        style.bg = inherit_bg;
1660    }
1661
1662    let top_i = screen_y(node.pos.1, y_offset);
1663    let bottom_i = top_i + h as i64 - 1;
1664    if bottom_i < 0 {
1665        return;
1666    }
1667    let right = x + w - 1;
1668
1669    if sides.top && top_i >= 0 {
1670        let y = top_i as u32;
1671        for xx in x..=right {
1672            buf.set_char(xx, y, chars.h, style);
1673        }
1674    }
1675    if sides.bottom {
1676        let y = bottom_i as u32;
1677        for xx in x..=right {
1678            buf.set_char(xx, y, chars.h, style);
1679        }
1680    }
1681    if sides.left {
1682        let vert_start = top_i.max(0) as u32;
1683        let vert_end = bottom_i as u32;
1684        for yy in vert_start..=vert_end {
1685            buf.set_char(x, yy, chars.v, style);
1686        }
1687    }
1688    if sides.right {
1689        let vert_start = top_i.max(0) as u32;
1690        let vert_end = bottom_i as u32;
1691        for yy in vert_start..=vert_end {
1692            buf.set_char(right, yy, chars.v, style);
1693        }
1694    }
1695
1696    if top_i >= 0 {
1697        let y = top_i as u32;
1698        let tl = match (sides.top, sides.left) {
1699            (true, true) => Some(chars.tl),
1700            (true, false) => Some(chars.h),
1701            (false, true) => Some(chars.v),
1702            (false, false) => None,
1703        };
1704        if let Some(ch) = tl {
1705            buf.set_char(x, y, ch, style);
1706        }
1707
1708        let tr = match (sides.top, sides.right) {
1709            (true, true) => Some(chars.tr),
1710            (true, false) => Some(chars.h),
1711            (false, true) => Some(chars.v),
1712            (false, false) => None,
1713        };
1714        if let Some(ch) = tr {
1715            buf.set_char(right, y, ch, style);
1716        }
1717    }
1718
1719    let y = bottom_i as u32;
1720    let bl = match (sides.bottom, sides.left) {
1721        (true, true) => Some(chars.bl),
1722        (true, false) => Some(chars.h),
1723        (false, true) => Some(chars.v),
1724        (false, false) => None,
1725    };
1726    if let Some(ch) = bl {
1727        buf.set_char(x, y, ch, style);
1728    }
1729
1730    let br = match (sides.bottom, sides.right) {
1731        (true, true) => Some(chars.br),
1732        (true, false) => Some(chars.h),
1733        (false, true) => Some(chars.v),
1734        (false, false) => None,
1735    };
1736    if let Some(ch) = br {
1737        buf.set_char(right, y, ch, style);
1738    }
1739
1740    if sides.top && top_i >= 0 {
1741        if let Some((title, title_style)) = &node.title {
1742            let mut ts = *title_style;
1743            if ts.bg.is_none() {
1744                ts.bg = inherit_bg;
1745            }
1746            let y = top_i as u32;
1747            let title_x = x.saturating_add(2);
1748            if title_x <= right {
1749                let max_width = (right - title_x + 1) as usize;
1750                let trimmed: String = title.chars().take(max_width).collect();
1751                buf.set_string(title_x, y, &trimmed, ts);
1752            }
1753        }
1754    }
1755}
1756
1757fn render_scroll_indicators(
1758    node: &LayoutNode,
1759    inner: Rect,
1760    buf: &mut Buffer,
1761    inherit_bg: Option<Color>,
1762) {
1763    if inner.width == 0 || inner.height == 0 {
1764        return;
1765    }
1766
1767    let mut style = node.border_style;
1768    if style.bg.is_none() {
1769        style.bg = inherit_bg;
1770    }
1771
1772    let indicator_x = inner.right() - 1;
1773    if node.scroll_offset > 0 {
1774        buf.set_char(indicator_x, inner.y, '▲', style);
1775    }
1776    if node.scroll_offset.saturating_add(inner.height) < node.content_height {
1777        buf.set_char(indicator_x, inner.bottom() - 1, '▼', style);
1778    }
1779}
1780
1781/// All per-frame data collected from a laid-out tree in a single traversal.
1782#[derive(Default)]
1783pub(crate) struct FrameData {
1784    pub scroll_infos: Vec<(u32, u32)>,
1785    pub scroll_rects: Vec<Rect>,
1786    pub hit_areas: Vec<Rect>,
1787    pub group_rects: Vec<(String, Rect)>,
1788    pub content_areas: Vec<(Rect, Rect)>,
1789    pub focus_rects: Vec<(usize, Rect)>,
1790    pub focus_groups: Vec<Option<String>>,
1791}
1792
1793/// Collect all per-frame data from a laid-out tree in a single DFS pass.
1794///
1795/// Replaces the 7 individual `collect_*` functions that each traversed the
1796/// tree independently, reducing per-frame traversals from 7× to 1×.
1797pub(crate) fn collect_all(node: &LayoutNode) -> FrameData {
1798    let mut data = FrameData::default();
1799
1800    // scroll_infos, scroll_rects, focus_rects process the root node itself.
1801    // hit_areas, group_rects, content_areas, focus_groups skip the root.
1802    if node.is_scrollable {
1803        let viewport_h = node.size.1.saturating_sub(node.frame_vertical());
1804        data.scroll_infos.push((node.content_height, viewport_h));
1805        data.scroll_rects
1806            .push(Rect::new(node.pos.0, node.pos.1, node.size.0, node.size.1));
1807    }
1808    if let Some(id) = node.focus_id {
1809        if node.pos.1 + node.size.1 > 0 {
1810            data.focus_rects.push((
1811                id,
1812                Rect::new(node.pos.0, node.pos.1, node.size.0, node.size.1),
1813            ));
1814        }
1815    }
1816
1817    let child_offset = if node.is_scrollable {
1818        node.scroll_offset
1819    } else {
1820        0
1821    };
1822    for child in &node.children {
1823        collect_all_inner(child, &mut data, child_offset, None);
1824    }
1825
1826    for overlay in &node.overlays {
1827        collect_all_inner(&overlay.node, &mut data, 0, None);
1828    }
1829
1830    data
1831}
1832
1833fn collect_all_inner(
1834    node: &LayoutNode,
1835    data: &mut FrameData,
1836    y_offset: u32,
1837    active_group: Option<&str>,
1838) {
1839    // --- scroll_infos (no y_offset dependency) ---
1840    if node.is_scrollable {
1841        let viewport_h = node.size.1.saturating_sub(node.frame_vertical());
1842        data.scroll_infos.push((node.content_height, viewport_h));
1843    }
1844
1845    // --- scroll_rects (uses y_offset) ---
1846    if node.is_scrollable {
1847        let adj_y = node.pos.1.saturating_sub(y_offset);
1848        data.scroll_rects
1849            .push(Rect::new(node.pos.0, adj_y, node.size.0, node.size.1));
1850    }
1851
1852    // --- hit_areas (container or link) ---
1853    if matches!(node.kind, NodeKind::Container(_)) || node.link_url.is_some() {
1854        if node.pos.1 + node.size.1 > y_offset {
1855            data.hit_areas.push(Rect::new(
1856                node.pos.0,
1857                node.pos.1.saturating_sub(y_offset),
1858                node.size.0,
1859                node.size.1,
1860            ));
1861        } else {
1862            data.hit_areas.push(Rect::new(0, 0, 0, 0));
1863        }
1864    }
1865
1866    // --- group_rects ---
1867    if let Some(name) = &node.group_name {
1868        if node.pos.1 + node.size.1 > y_offset {
1869            data.group_rects.push((
1870                name.clone(),
1871                Rect::new(
1872                    node.pos.0,
1873                    node.pos.1.saturating_sub(y_offset),
1874                    node.size.0,
1875                    node.size.1,
1876                ),
1877            ));
1878        }
1879    }
1880
1881    // --- content_areas ---
1882    if matches!(node.kind, NodeKind::Container(_)) {
1883        let adj_y = node.pos.1.saturating_sub(y_offset);
1884        let full = Rect::new(node.pos.0, adj_y, node.size.0, node.size.1);
1885        let inset_x = node.padding.left + node.border_left_inset();
1886        let inset_y = node.padding.top + node.border_top_inset();
1887        let inner_w = node.size.0.saturating_sub(node.frame_horizontal());
1888        let inner_h = node.size.1.saturating_sub(node.frame_vertical());
1889        let content = Rect::new(node.pos.0 + inset_x, adj_y + inset_y, inner_w, inner_h);
1890        data.content_areas.push((full, content));
1891    }
1892
1893    // --- focus_rects ---
1894    if let Some(id) = node.focus_id {
1895        if node.pos.1 + node.size.1 > y_offset {
1896            data.focus_rects.push((
1897                id,
1898                Rect::new(
1899                    node.pos.0,
1900                    node.pos.1.saturating_sub(y_offset),
1901                    node.size.0,
1902                    node.size.1,
1903                ),
1904            ));
1905        }
1906    }
1907
1908    // --- focus_groups ---
1909    let current_group = node.group_name.as_deref().or(active_group);
1910    if let Some(id) = node.focus_id {
1911        if id >= data.focus_groups.len() {
1912            data.focus_groups.resize(id + 1, None);
1913        }
1914        data.focus_groups[id] = current_group.map(ToString::to_string);
1915    }
1916
1917    // --- Recurse into children ---
1918    let child_offset = if node.is_scrollable {
1919        y_offset.saturating_add(node.scroll_offset)
1920    } else {
1921        y_offset
1922    };
1923    for child in &node.children {
1924        collect_all_inner(child, data, child_offset, current_group);
1925    }
1926}
1927
1928pub(crate) fn collect_raw_draw_rects(node: &LayoutNode) -> Vec<(usize, Rect)> {
1929    let mut rects = Vec::new();
1930    collect_raw_draw_rects_inner(node, &mut rects, 0);
1931    for overlay in &node.overlays {
1932        collect_raw_draw_rects_inner(&overlay.node, &mut rects, 0);
1933    }
1934    rects
1935}
1936
1937fn collect_raw_draw_rects_inner(node: &LayoutNode, rects: &mut Vec<(usize, Rect)>, y_offset: u32) {
1938    if let NodeKind::RawDraw(draw_id) = node.kind {
1939        let adj_y = node.pos.1.saturating_sub(y_offset);
1940        rects.push((
1941            draw_id,
1942            Rect::new(node.pos.0, adj_y, node.size.0, node.size.1),
1943        ));
1944    }
1945    let child_offset = if node.is_scrollable {
1946        y_offset.saturating_add(node.scroll_offset)
1947    } else {
1948        y_offset
1949    };
1950    for child in &node.children {
1951        collect_raw_draw_rects_inner(child, rects, child_offset);
1952    }
1953}
1954
1955#[cfg(test)]
1956mod tests {
1957    use super::*;
1958
1959    #[test]
1960    fn wrap_empty() {
1961        assert_eq!(wrap_lines("", 10), vec![""]);
1962    }
1963
1964    #[test]
1965    fn wrap_fits() {
1966        assert_eq!(wrap_lines("hello", 10), vec!["hello"]);
1967    }
1968
1969    #[test]
1970    fn wrap_word_boundary() {
1971        assert_eq!(wrap_lines("hello world", 7), vec!["hello", "world"]);
1972    }
1973
1974    #[test]
1975    fn wrap_multiple_words() {
1976        assert_eq!(
1977            wrap_lines("one two three four", 9),
1978            vec!["one two", "three", "four"]
1979        );
1980    }
1981
1982    #[test]
1983    fn wrap_long_word() {
1984        assert_eq!(wrap_lines("abcdefghij", 4), vec!["abcd", "efgh", "ij"]);
1985    }
1986
1987    #[test]
1988    fn wrap_zero_width() {
1989        assert_eq!(wrap_lines("hello", 0), vec!["hello"]);
1990    }
1991
1992    #[test]
1993    fn diagnostic_demo_layout() {
1994        use super::{compute, ContainerConfig, Direction, LayoutNode};
1995        use crate::rect::Rect;
1996        use crate::style::{Align, Border, Constraints, Justify, Margin, Padding, Style};
1997
1998        // Build the tree structure matching demo.rs:
1999        // Root (Column, grow:0)
2000        //   └─ Container (Column, grow:1, border:Rounded, padding:all(1))
2001        //        ├─ Text "header" (grow:0)
2002        //        ├─ Text "separator" (grow:0)
2003        //        ├─ Container (Column, grow:1)  ← simulates scrollable
2004        //        │    ├─ Text "content1" (grow:0)
2005        //        │    ├─ Text "content2" (grow:0)
2006        //        │    └─ Text "content3" (grow:0)
2007        //        ├─ Text "separator2" (grow:0)
2008        //        └─ Text "footer" (grow:0)
2009
2010        let mut root = LayoutNode::container(
2011            Direction::Column,
2012            ContainerConfig {
2013                gap: 0,
2014                align: Align::Start,
2015                justify: Justify::Start,
2016                border: None,
2017                border_sides: BorderSides::all(),
2018                border_style: Style::new(),
2019                bg_color: None,
2020                padding: Padding::default(),
2021                margin: Margin::default(),
2022                constraints: Constraints::default(),
2023                title: None,
2024                grow: 0,
2025            },
2026        );
2027
2028        // Outer bordered container with grow:1
2029        let mut outer_container = LayoutNode::container(
2030            Direction::Column,
2031            ContainerConfig {
2032                gap: 0,
2033                align: Align::Start,
2034                justify: Justify::Start,
2035                border: Some(Border::Rounded),
2036                border_sides: BorderSides::all(),
2037                border_style: Style::new(),
2038                bg_color: None,
2039                padding: Padding::all(1),
2040                margin: Margin::default(),
2041                constraints: Constraints::default(),
2042                title: None,
2043                grow: 1,
2044            },
2045        );
2046
2047        // Header text
2048        outer_container.children.push(LayoutNode::text(
2049            "header".to_string(),
2050            Style::new(),
2051            0,
2052            Align::Start,
2053            false,
2054            Margin::default(),
2055            Constraints::default(),
2056        ));
2057
2058        // Separator 1
2059        outer_container.children.push(LayoutNode::text(
2060            "separator".to_string(),
2061            Style::new(),
2062            0,
2063            Align::Start,
2064            false,
2065            Margin::default(),
2066            Constraints::default(),
2067        ));
2068
2069        // Inner scrollable-like container with grow:1
2070        let mut inner_container = LayoutNode::container(
2071            Direction::Column,
2072            ContainerConfig {
2073                gap: 0,
2074                align: Align::Start,
2075                justify: Justify::Start,
2076                border: None,
2077                border_sides: BorderSides::all(),
2078                border_style: Style::new(),
2079                bg_color: None,
2080                padding: Padding::default(),
2081                margin: Margin::default(),
2082                constraints: Constraints::default(),
2083                title: None,
2084                grow: 1,
2085            },
2086        );
2087
2088        // Content items
2089        inner_container.children.push(LayoutNode::text(
2090            "content1".to_string(),
2091            Style::new(),
2092            0,
2093            Align::Start,
2094            false,
2095            Margin::default(),
2096            Constraints::default(),
2097        ));
2098        inner_container.children.push(LayoutNode::text(
2099            "content2".to_string(),
2100            Style::new(),
2101            0,
2102            Align::Start,
2103            false,
2104            Margin::default(),
2105            Constraints::default(),
2106        ));
2107        inner_container.children.push(LayoutNode::text(
2108            "content3".to_string(),
2109            Style::new(),
2110            0,
2111            Align::Start,
2112            false,
2113            Margin::default(),
2114            Constraints::default(),
2115        ));
2116
2117        outer_container.children.push(inner_container);
2118
2119        // Separator 2
2120        outer_container.children.push(LayoutNode::text(
2121            "separator2".to_string(),
2122            Style::new(),
2123            0,
2124            Align::Start,
2125            false,
2126            Margin::default(),
2127            Constraints::default(),
2128        ));
2129
2130        // Footer
2131        outer_container.children.push(LayoutNode::text(
2132            "footer".to_string(),
2133            Style::new(),
2134            0,
2135            Align::Start,
2136            false,
2137            Margin::default(),
2138            Constraints::default(),
2139        ));
2140
2141        root.children.push(outer_container);
2142
2143        // Compute layout with 80x50 terminal
2144        compute(&mut root, Rect::new(0, 0, 80, 50));
2145
2146        // Debug output
2147        eprintln!("\n=== DIAGNOSTIC LAYOUT TEST ===");
2148        eprintln!("Root node:");
2149        eprintln!("  pos: {:?}, size: {:?}", root.pos, root.size);
2150
2151        let outer = &root.children[0];
2152        eprintln!("\nOuter bordered container (grow:1):");
2153        eprintln!("  pos: {:?}, size: {:?}", outer.pos, outer.size);
2154
2155        let inner = &outer.children[2];
2156        eprintln!("\nInner container (grow:1, simulates scrollable):");
2157        eprintln!("  pos: {:?}, size: {:?}", inner.pos, inner.size);
2158
2159        eprintln!("\nAll children of outer container:");
2160        for (i, child) in outer.children.iter().enumerate() {
2161            eprintln!("  [{}] pos: {:?}, size: {:?}", i, child.pos, child.size);
2162        }
2163
2164        // Assertions
2165        // Root should fill the entire 80x50 area
2166        assert_eq!(
2167            root.size,
2168            (80, 50),
2169            "Root node should fill entire terminal (80x50)"
2170        );
2171
2172        // Outer container should also be 80x50 (full height due to grow:1)
2173        assert_eq!(
2174            outer.size,
2175            (80, 50),
2176            "Outer bordered container should fill entire terminal (80x50)"
2177        );
2178
2179        // Calculate expected inner container height:
2180        // Available height = 50 (total)
2181        // Border inset = 1 (top) + 1 (bottom) = 2
2182        // Padding = 1 (top) + 1 (bottom) = 2
2183        // Fixed children heights: header(1) + sep(1) + sep2(1) + footer(1) = 4
2184        // Expected inner height = 50 - 2 - 2 - 4 = 42
2185        let expected_inner_height = 50 - 2 - 2 - 4;
2186        assert_eq!(
2187            inner.size.1, expected_inner_height as u32,
2188            "Inner container height should be {} (50 - border(2) - padding(2) - fixed(4))",
2189            expected_inner_height
2190        );
2191
2192        // Inner container should start at y = border(1) + padding(1) + header(1) + sep(1) = 4
2193        let expected_inner_y = 1 + 1 + 1 + 1;
2194        assert_eq!(
2195            inner.pos.1, expected_inner_y as u32,
2196            "Inner container should start at y={} (border+padding+header+sep)",
2197            expected_inner_y
2198        );
2199
2200        eprintln!("\n✓ All assertions passed!");
2201        eprintln!("  Root size: {:?}", root.size);
2202        eprintln!("  Outer container size: {:?}", outer.size);
2203        eprintln!("  Inner container size: {:?}", inner.size);
2204        eprintln!("  Inner container pos: {:?}", inner.pos);
2205    }
2206
2207    #[test]
2208    fn collect_focus_rects_from_markers() {
2209        use super::*;
2210        use crate::style::Style;
2211
2212        let commands = vec![
2213            Command::FocusMarker(0),
2214            Command::Text {
2215                content: "input1".into(),
2216                style: Style::new(),
2217                grow: 0,
2218                align: Align::Start,
2219                wrap: false,
2220                margin: Default::default(),
2221                constraints: Default::default(),
2222            },
2223            Command::FocusMarker(1),
2224            Command::Text {
2225                content: "input2".into(),
2226                style: Style::new(),
2227                grow: 0,
2228                align: Align::Start,
2229                wrap: false,
2230                margin: Default::default(),
2231                constraints: Default::default(),
2232            },
2233        ];
2234
2235        let mut tree = build_tree(&commands);
2236        let area = crate::rect::Rect::new(0, 0, 40, 10);
2237        compute(&mut tree, area);
2238
2239        let fd = collect_all(&tree);
2240        assert_eq!(fd.focus_rects.len(), 2);
2241        assert_eq!(fd.focus_rects[0].0, 0);
2242        assert_eq!(fd.focus_rects[1].0, 1);
2243        assert!(fd.focus_rects[0].1.width > 0);
2244        assert!(fd.focus_rects[1].1.width > 0);
2245        assert_ne!(fd.focus_rects[0].1.y, fd.focus_rects[1].1.y);
2246    }
2247
2248    #[test]
2249    fn focus_marker_tags_container() {
2250        use super::*;
2251        use crate::style::{Border, Style};
2252
2253        let commands = vec![
2254            Command::FocusMarker(0),
2255            Command::BeginContainer {
2256                direction: Direction::Column,
2257                gap: 0,
2258                align: Align::Start,
2259                justify: Justify::Start,
2260                border: Some(Border::Single),
2261                border_sides: BorderSides::all(),
2262                border_style: Style::new(),
2263                bg_color: None,
2264                padding: Padding::default(),
2265                margin: Default::default(),
2266                constraints: Default::default(),
2267                title: None,
2268                grow: 0,
2269                group_name: None,
2270            },
2271            Command::Text {
2272                content: "inside".into(),
2273                style: Style::new(),
2274                grow: 0,
2275                align: Align::Start,
2276                wrap: false,
2277                margin: Default::default(),
2278                constraints: Default::default(),
2279            },
2280            Command::EndContainer,
2281        ];
2282
2283        let mut tree = build_tree(&commands);
2284        let area = crate::rect::Rect::new(0, 0, 40, 10);
2285        compute(&mut tree, area);
2286
2287        let fd = collect_all(&tree);
2288        assert_eq!(fd.focus_rects.len(), 1);
2289        assert_eq!(fd.focus_rects[0].0, 0);
2290        assert!(fd.focus_rects[0].1.width >= 8);
2291        assert!(fd.focus_rects[0].1.height >= 3);
2292    }
2293}