Skip to main content

kova_native_layout/
engine.rs

1//! Incremental layout engine backed by taffy.
2
3use crate::style::*;
4use kova_native_core::{Point, Size};
5use taffy::prelude::{TaffyAuto, TaffyMaxContent, TaffyMinContent};
6use taffy::style_helpers;
7
8/// Handle to a node in the [`LayoutEngine`].
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub struct LayoutId(taffy::NodeId);
11
12/// Space available to a node along one axis while measuring.
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub enum AvailableSpace {
15    Definite(f32),
16    MinContent,
17    MaxContent,
18}
19
20impl AvailableSpace {
21    /// The definite size, or `None` for intrinsic sizing queries.
22    pub fn definite(self) -> Option<f32> {
23        match self {
24            AvailableSpace::Definite(v) => Some(v),
25            _ => None,
26        }
27    }
28}
29
30/// Inputs passed to leaf measure functions (e.g. text).
31#[derive(Clone, Copy, Debug, PartialEq)]
32pub struct MeasureInput {
33    /// Sizes already fixed by the parent/style, if any.
34    pub known_width: Option<f32>,
35    pub known_height: Option<f32>,
36    pub available_width: AvailableSpace,
37    pub available_height: AvailableSpace,
38}
39
40/// Computed layout of a node, relative to its parent's border box.
41#[derive(Clone, Copy, Debug, PartialEq, Default)]
42pub struct NodeLayout {
43    pub location: Point,
44    pub size: Size,
45    /// Extent of the scrollable content, measured from the padding box origin.
46    pub content_size: Size,
47    pub padding: kova_native_core::Edges<f32>,
48    pub border: kova_native_core::Edges<f32>,
49}
50
51/// An incremental layout tree.
52///
53/// Nodes keep their computed layout between frames; changing a style or
54/// marking a leaf dirty only recomputes the affected ancestors. Leaves with a
55/// measure context `K` are sized through the measure callback passed to
56/// [`LayoutEngine::compute`].
57pub struct LayoutEngine<K: Copy + 'static> {
58    tree: taffy::TaffyTree<K>,
59}
60
61impl<K: Copy + 'static> Default for LayoutEngine<K> {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl<K: Copy + 'static> LayoutEngine<K> {
68    pub fn new() -> Self {
69        let mut tree = taffy::TaffyTree::new();
70        // Kova Native snaps to device pixels at paint time; logical-pixel rounding
71        // would misalign content at fractional scale factors.
72        tree.disable_rounding();
73        LayoutEngine { tree }
74    }
75
76    /// Creates a node. Leaves that need measuring get a `context`.
77    pub fn create(&mut self, style: &LayoutStyle, context: Option<K>) -> LayoutId {
78        let style = to_taffy(style);
79        let id = match context {
80            Some(ctx) => self.tree.new_leaf_with_context(style, ctx),
81            None => self.tree.new_leaf(style),
82        }
83        .expect("taffy node creation cannot fail");
84        LayoutId(id)
85    }
86
87    /// Sets or clears the measure context of a node (making it a measured leaf).
88    pub fn set_context(&mut self, id: LayoutId, context: Option<K>) {
89        let _ = self.tree.set_node_context(id.0, context);
90    }
91
92    pub fn set_style(&mut self, id: LayoutId, style: &LayoutStyle) {
93        let _ = self.tree.set_style(id.0, to_taffy(style));
94    }
95
96    pub fn set_children(&mut self, id: LayoutId, children: &[LayoutId]) {
97        let children: Vec<taffy::NodeId> = children.iter().map(|c| c.0).collect();
98        let _ = self.tree.set_children(id.0, &children);
99    }
100
101    /// Marks a leaf as needing re-measurement (e.g. its text changed).
102    pub fn mark_dirty(&mut self, id: LayoutId) {
103        let _ = self.tree.mark_dirty(id.0);
104    }
105
106    pub fn is_dirty(&self, id: LayoutId) -> bool {
107        self.tree.dirty(id.0).unwrap_or(false)
108    }
109
110    pub fn remove(&mut self, id: LayoutId) {
111        let _ = self.tree.remove(id.0);
112    }
113
114    pub fn node_count(&self) -> usize {
115        self.tree.total_node_count()
116    }
117
118    /// Computes layout for the subtree rooted at `root` within `available`.
119    pub fn compute(
120        &mut self,
121        root: LayoutId,
122        available: Size,
123        mut measure: impl FnMut(K, MeasureInput) -> Size,
124    ) {
125        let available = taffy::Size {
126            width: taffy::AvailableSpace::Definite(available.width),
127            height: taffy::AvailableSpace::Definite(available.height),
128        };
129        let _ = self.tree.compute_layout_with_measure(
130            root.0,
131            available,
132            |inputs, _node, ctx, style| {
133                taffy::compute_leaf_layout(
134                    inputs,
135                    style,
136                    |_, _| 0.0,
137                    |known, avail| {
138                        let Some(ctx) = ctx else {
139                            return taffy::Size::ZERO;
140                        };
141                        let convert = |a: taffy::AvailableSpace| match a {
142                            taffy::AvailableSpace::Definite(v) => AvailableSpace::Definite(v),
143                            taffy::AvailableSpace::MinContent => AvailableSpace::MinContent,
144                            taffy::AvailableSpace::MaxContent => AvailableSpace::MaxContent,
145                        };
146                        let size = measure(
147                            *ctx,
148                            MeasureInput {
149                                known_width: known.width,
150                                known_height: known.height,
151                                available_width: convert(avail.width),
152                                available_height: convert(avail.height),
153                            },
154                        );
155                        taffy::Size {
156                            width: size.width,
157                            height: size.height,
158                        }
159                    },
160                )
161            },
162        );
163    }
164
165    /// The computed layout of a node.
166    pub fn layout(&self, id: LayoutId) -> NodeLayout {
167        let Ok(l) = self.tree.layout(id.0) else {
168            return NodeLayout::default();
169        };
170        let edges = |r: taffy::Rect<f32>| kova_native_core::Edges {
171            top: r.top,
172            right: r.right,
173            bottom: r.bottom,
174            left: r.left,
175        };
176        NodeLayout {
177            location: Point::new(l.location.x, l.location.y),
178            size: Size::new(l.size.width, l.size.height),
179            content_size: Size::new(
180                l.scrollable_overflow_rect.right.max(0.0),
181                l.scrollable_overflow_rect.bottom.max(0.0),
182            ),
183            padding: edges(l.padding),
184            border: edges(l.border),
185        }
186    }
187}
188
189fn dim(l: Length) -> taffy::Dimension {
190    match l {
191        Length::Auto => taffy::Dimension::auto(),
192        Length::Px(v) => taffy::Dimension::length(v),
193        Length::Relative(f) => taffy::Dimension::percent(f),
194    }
195}
196
197fn lpa(l: Length) -> taffy::LengthPercentageAuto {
198    match l {
199        Length::Auto => taffy::LengthPercentageAuto::auto(),
200        Length::Px(v) => taffy::LengthPercentageAuto::length(v),
201        Length::Relative(f) => taffy::LengthPercentageAuto::percent(f),
202    }
203}
204
205fn lp(l: Length) -> taffy::LengthPercentage {
206    match l {
207        Length::Auto => taffy::LengthPercentage::length(0.0),
208        Length::Px(v) => taffy::LengthPercentage::length(v),
209        Length::Relative(f) => taffy::LengthPercentage::percent(f),
210    }
211}
212
213fn align(a: Align) -> taffy::AlignItems {
214    match a {
215        Align::Start => taffy::AlignItems::FLEX_START,
216        Align::End => taffy::AlignItems::FLEX_END,
217        Align::Center => taffy::AlignItems::CENTER,
218        Align::Stretch => taffy::AlignItems::STRETCH,
219        Align::Baseline => taffy::AlignItems::BASELINE,
220    }
221}
222
223fn justify(j: Justify) -> taffy::JustifyContent {
224    match j {
225        Justify::Start => taffy::JustifyContent::FLEX_START,
226        Justify::End => taffy::JustifyContent::FLEX_END,
227        Justify::Center => taffy::JustifyContent::CENTER,
228        Justify::Stretch => taffy::JustifyContent::STRETCH,
229        Justify::SpaceBetween => taffy::JustifyContent::SPACE_BETWEEN,
230        Justify::SpaceAround => taffy::JustifyContent::SPACE_AROUND,
231        Justify::SpaceEvenly => taffy::JustifyContent::SPACE_EVENLY,
232    }
233}
234
235fn overflow(o: Overflow) -> taffy::Overflow {
236    match o {
237        Overflow::Visible => taffy::Overflow::Visible,
238        Overflow::Hidden => taffy::Overflow::Clip,
239        Overflow::Scroll => taffy::Overflow::Scroll,
240    }
241}
242
243fn track(t: Track) -> taffy::TrackSizingFunction {
244    match t {
245        Track::Px(v) => style_helpers::length(v),
246        Track::Relative(f) => style_helpers::percent(f),
247        Track::Fr(f) => style_helpers::fr(f),
248        Track::Auto => taffy::TrackSizingFunction::AUTO,
249        Track::MinContent => taffy::TrackSizingFunction::MIN_CONTENT,
250        Track::MaxContent => taffy::TrackSizingFunction::MAX_CONTENT,
251        Track::MinMax(min, max_fr) => style_helpers::minmax(
252            taffy::MinTrackSizingFunction::length(min),
253            taffy::MaxTrackSizingFunction::fr(max_fr),
254        ),
255    }
256}
257
258fn placement(p: GridPlacement) -> taffy::Line<taffy::GridPlacement> {
259    match p {
260        GridPlacement::Auto => taffy::Line {
261            start: taffy::GridPlacement::Auto,
262            end: taffy::GridPlacement::Auto,
263        },
264        GridPlacement::Span(n) => taffy::Line {
265            start: style_helpers::span(n),
266            end: taffy::GridPlacement::Auto,
267        },
268        GridPlacement::Line { start, span } => taffy::Line {
269            start: style_helpers::line(start),
270            end: style_helpers::span(span.max(1)),
271        },
272    }
273}
274
275/// Converts a Kova Native layout style to a taffy style.
276pub(crate) fn to_taffy(s: &LayoutStyle) -> taffy::Style {
277    let mut t = taffy::Style {
278        display: match s.display {
279            Display::Flex => taffy::Display::Flex,
280            Display::Grid => taffy::Display::Grid,
281            Display::Block => taffy::Display::Block,
282            Display::None => taffy::Display::None,
283        },
284        position: match s.position {
285            Position::Relative => taffy::Position::Relative,
286            Position::Absolute => taffy::Position::Absolute,
287        },
288        flex_direction: match s.direction {
289            FlexDirection::Row => taffy::FlexDirection::Row,
290            FlexDirection::Column => taffy::FlexDirection::Column,
291            FlexDirection::RowReverse => taffy::FlexDirection::RowReverse,
292            FlexDirection::ColumnReverse => taffy::FlexDirection::ColumnReverse,
293        },
294        flex_wrap: match s.wrap {
295            FlexWrap::NoWrap => taffy::FlexWrap::NoWrap,
296            FlexWrap::Wrap => taffy::FlexWrap::Wrap,
297            FlexWrap::WrapReverse => taffy::FlexWrap::WrapReverse,
298        },
299        align_items: s.align_items.map(align),
300        align_self: s.align_self.map(align),
301        justify_self: s.justify_self.map(align),
302        align_content: s.align_content.map(justify),
303        justify_content: s.justify_content.map(justify),
304        size: taffy::Size {
305            width: dim(s.size.width),
306            height: dim(s.size.height),
307        },
308        min_size: taffy::Size {
309            width: lpa(s.min_size.width),
310            height: lpa(s.min_size.height),
311        },
312        max_size: taffy::Size {
313            width: lpa(s.max_size.width),
314            height: lpa(s.max_size.height),
315        },
316        aspect_ratio: s.aspect_ratio,
317        padding: taffy::Rect {
318            top: lp(s.padding.top),
319            right: lp(s.padding.right),
320            bottom: lp(s.padding.bottom),
321            left: lp(s.padding.left),
322        },
323        margin: taffy::Rect {
324            top: lpa(s.margin.top),
325            right: lpa(s.margin.right),
326            bottom: lpa(s.margin.bottom),
327            left: lpa(s.margin.left),
328        },
329        border: taffy::Rect {
330            top: taffy::LengthPercentage::length(s.border.top),
331            right: taffy::LengthPercentage::length(s.border.right),
332            bottom: taffy::LengthPercentage::length(s.border.bottom),
333            left: taffy::LengthPercentage::length(s.border.left),
334        },
335        inset: taffy::Rect {
336            top: lpa(s.inset.top),
337            right: lpa(s.inset.right),
338            bottom: lpa(s.inset.bottom),
339            left: lpa(s.inset.left),
340        },
341        gap: taffy::Size {
342            width: lp(s.gap.width),
343            height: lp(s.gap.height),
344        },
345        flex_grow: s.flex_grow,
346        flex_shrink: s.flex_shrink,
347        flex_basis: dim(s.flex_basis),
348        overflow: taffy::Point {
349            x: overflow(s.overflow_x),
350            y: overflow(s.overflow_y),
351        },
352        // Kova Native draws overlay scrollbars that do not take layout space.
353        scrollbar_width: 0.0,
354        ..Default::default()
355    };
356    if let Some(grid) = &s.grid {
357        t.grid_template_columns = grid
358            .template_columns
359            .iter()
360            .map(|tr| taffy::GridTemplateComponent::Single(track(*tr)))
361            .collect();
362        t.grid_template_rows = grid
363            .template_rows
364            .iter()
365            .map(|tr| taffy::GridTemplateComponent::Single(track(*tr)))
366            .collect();
367        t.grid_auto_rows = grid.auto_rows.iter().map(|tr| track(*tr)).collect();
368        t.grid_column = placement(grid.column);
369        t.grid_row = placement(grid.row);
370    }
371    t
372}