taffy.rs

  1use crate::{
  2    AbsoluteLength, App, Bounds, DefiniteLength, Edges, Length, Pixels, Point, Size, Style, Window,
  3};
  4use collections::{FxHashMap, FxHashSet};
  5use smallvec::SmallVec;
  6use std::fmt::Debug;
  7use taffy::{
  8    TaffyTree, TraversePartialTree as _,
  9    geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
 10    style::AvailableSpace as TaffyAvailableSpace,
 11    tree::NodeId,
 12};
 13
 14type NodeMeasureFn = Box<
 15    dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>,
 16>;
 17
 18struct NodeContext {
 19    measure: NodeMeasureFn,
 20}
 21pub struct TaffyLayoutEngine {
 22    taffy: TaffyTree<NodeContext>,
 23    absolute_layout_bounds: FxHashMap<LayoutId, Bounds<Pixels>>,
 24    computed_layouts: FxHashSet<LayoutId>,
 25}
 26
 27const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
 28
 29impl TaffyLayoutEngine {
 30    pub fn new() -> Self {
 31        TaffyLayoutEngine {
 32            taffy: TaffyTree::new(),
 33            absolute_layout_bounds: FxHashMap::default(),
 34            computed_layouts: FxHashSet::default(),
 35        }
 36    }
 37
 38    pub fn clear(&mut self) {
 39        self.taffy.clear();
 40        self.absolute_layout_bounds.clear();
 41        self.computed_layouts.clear();
 42    }
 43
 44    pub fn request_layout(
 45        &mut self,
 46        style: Style,
 47        rem_size: Pixels,
 48        children: &[LayoutId],
 49    ) -> LayoutId {
 50        let taffy_style = style.to_taffy(rem_size);
 51        let layout_id = if children.is_empty() {
 52            self.taffy
 53                .new_leaf(taffy_style)
 54                .expect(EXPECT_MESSAGE)
 55                .into()
 56        } else {
 57            let parent_id = self
 58                .taffy
 59                // This is safe because LayoutId is repr(transparent) to taffy::tree::NodeId.
 60                .new_with_children(taffy_style, unsafe {
 61                    std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(children)
 62                })
 63                .expect(EXPECT_MESSAGE)
 64                .into();
 65            parent_id
 66        };
 67        layout_id
 68    }
 69
 70    pub fn request_measured_layout(
 71        &mut self,
 72        style: Style,
 73        rem_size: Pixels,
 74        measure: impl FnMut(
 75            Size<Option<Pixels>>,
 76            Size<AvailableSpace>,
 77            &mut Window,
 78            &mut App,
 79        ) -> Size<Pixels>
 80        + 'static,
 81    ) -> LayoutId {
 82        let taffy_style = style.to_taffy(rem_size);
 83
 84        let layout_id = self
 85            .taffy
 86            .new_leaf_with_context(
 87                taffy_style,
 88                NodeContext {
 89                    measure: Box::new(measure),
 90                },
 91            )
 92            .expect(EXPECT_MESSAGE)
 93            .into();
 94        layout_id
 95    }
 96
 97    // Used to understand performance
 98    #[allow(dead_code)]
 99    fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
100        let mut count = 0;
101
102        for child in self.taffy.children(parent.0)? {
103            // Count this child.
104            count += 1;
105
106            // Count all of this child's children.
107            count += self.count_all_children(LayoutId(child))?
108        }
109
110        Ok(count)
111    }
112
113    // Used to understand performance
114    #[allow(dead_code)]
115    fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
116        println!(
117            "{parent:?} at depth {depth} has {} children",
118            self.taffy.child_count(parent.0)
119        );
120
121        let mut max_child_depth = 0;
122
123        for child in self.taffy.children(parent.0)? {
124            max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
125        }
126
127        Ok(depth + 1 + max_child_depth)
128    }
129
130    // Used to understand performance
131    #[allow(dead_code)]
132    fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
133        let mut edges = Vec::new();
134
135        for child in self.taffy.children(parent.0)? {
136            edges.push((parent, LayoutId(child)));
137
138            edges.extend(self.get_edges(LayoutId(child))?);
139        }
140
141        Ok(edges)
142    }
143
144    pub fn compute_layout(
145        &mut self,
146        id: LayoutId,
147        available_space: Size<AvailableSpace>,
148        window: &mut Window,
149        cx: &mut App,
150    ) {
151        // Leaving this here until we have a better instrumentation approach.
152        // println!("Laying out {} children", self.count_all_children(id)?);
153        // println!("Max layout depth: {}", self.max_depth(0, id)?);
154
155        // Output the edges (branches) of the tree in Mermaid format for visualization.
156        // println!("Edges:");
157        // for (a, b) in self.get_edges(id)? {
158        //     println!("N{} --> N{}", u64::from(a), u64::from(b));
159        // }
160        // println!("");
161        //
162
163        if !self.computed_layouts.insert(id) {
164            let mut stack = SmallVec::<[LayoutId; 64]>::new();
165            stack.push(id);
166            while let Some(id) = stack.pop() {
167                self.absolute_layout_bounds.remove(&id);
168                stack.extend(
169                    self.taffy
170                        .children(id.into())
171                        .expect(EXPECT_MESSAGE)
172                        .into_iter()
173                        .map(Into::into),
174                );
175            }
176        }
177
178        // let started_at = std::time::Instant::now();
179        self.taffy
180            .compute_layout_with_measure(
181                id.into(),
182                available_space.into(),
183                |known_dimensions, available_space, _id, node_context| {
184                    let Some(node_context) = node_context else {
185                        return taffy::geometry::Size::default();
186                    };
187
188                    let known_dimensions = Size {
189                        width: known_dimensions.width.map(Pixels),
190                        height: known_dimensions.height.map(Pixels),
191                    };
192
193                    (node_context.measure)(known_dimensions, available_space.into(), window, cx)
194                        .into()
195                },
196            )
197            .expect(EXPECT_MESSAGE);
198
199        // println!("compute_layout took {:?}", started_at.elapsed());
200    }
201
202    pub fn layout_bounds(&mut self, id: LayoutId) -> Bounds<Pixels> {
203        if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
204            return layout;
205        }
206
207        let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
208        let mut bounds = Bounds {
209            origin: layout.location.into(),
210            size: layout.size.into(),
211        };
212
213        if let Some(parent_id) = self.taffy.parent(id.0) {
214            let parent_bounds = self.layout_bounds(parent_id.into());
215            bounds.origin += parent_bounds.origin;
216        }
217        self.absolute_layout_bounds.insert(id, bounds);
218
219        bounds
220    }
221}
222
223/// A unique identifier for a layout node, generated when requesting a layout from Taffy
224#[derive(Copy, Clone, Eq, PartialEq, Debug)]
225#[repr(transparent)]
226pub struct LayoutId(NodeId);
227
228impl std::hash::Hash for LayoutId {
229    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
230        u64::from(self.0).hash(state);
231    }
232}
233
234impl From<NodeId> for LayoutId {
235    fn from(node_id: NodeId) -> Self {
236        Self(node_id)
237    }
238}
239
240impl From<LayoutId> for NodeId {
241    fn from(layout_id: LayoutId) -> NodeId {
242        layout_id.0
243    }
244}
245
246trait ToTaffy<Output> {
247    fn to_taffy(&self, rem_size: Pixels) -> Output;
248}
249
250impl ToTaffy<taffy::style::Style> for Style {
251    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::Style {
252        taffy::style::Style {
253            display: self.display.into(),
254            overflow: self.overflow.into(),
255            scrollbar_width: self.scrollbar_width,
256            position: self.position.into(),
257            inset: self.inset.to_taffy(rem_size),
258            size: self.size.to_taffy(rem_size),
259            min_size: self.min_size.to_taffy(rem_size),
260            max_size: self.max_size.to_taffy(rem_size),
261            aspect_ratio: self.aspect_ratio,
262            margin: self.margin.to_taffy(rem_size),
263            padding: self.padding.to_taffy(rem_size),
264            border: self.border_widths.to_taffy(rem_size),
265            align_items: self.align_items.map(|x| x.into()),
266            align_self: self.align_self.map(|x| x.into()),
267            align_content: self.align_content.map(|x| x.into()),
268            justify_content: self.justify_content.map(|x| x.into()),
269            gap: self.gap.to_taffy(rem_size),
270            flex_direction: self.flex_direction.into(),
271            flex_wrap: self.flex_wrap.into(),
272            flex_basis: self.flex_basis.to_taffy(rem_size),
273            flex_grow: self.flex_grow,
274            flex_shrink: self.flex_shrink,
275            ..Default::default() // Ignore grid properties for now
276        }
277    }
278}
279
280impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
281    fn to_taffy(&self, rem_size: Pixels) -> taffy::prelude::LengthPercentageAuto {
282        match self {
283            Length::Definite(length) => length.to_taffy(rem_size),
284            Length::Auto => taffy::prelude::LengthPercentageAuto::Auto,
285        }
286    }
287}
288
289impl ToTaffy<taffy::style::Dimension> for Length {
290    fn to_taffy(&self, rem_size: Pixels) -> taffy::prelude::Dimension {
291        match self {
292            Length::Definite(length) => length.to_taffy(rem_size),
293            Length::Auto => taffy::prelude::Dimension::Auto,
294        }
295    }
296}
297
298impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
299    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentage {
300        match self {
301            DefiniteLength::Absolute(length) => match length {
302                AbsoluteLength::Pixels(pixels) => {
303                    taffy::style::LengthPercentage::Length(pixels.into())
304                }
305                AbsoluteLength::Rems(rems) => {
306                    taffy::style::LengthPercentage::Length((*rems * rem_size).into())
307                }
308            },
309            DefiniteLength::Fraction(fraction) => {
310                taffy::style::LengthPercentage::Percent(*fraction)
311            }
312        }
313    }
314}
315
316impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
317    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentageAuto {
318        match self {
319            DefiniteLength::Absolute(length) => match length {
320                AbsoluteLength::Pixels(pixels) => {
321                    taffy::style::LengthPercentageAuto::Length(pixels.into())
322                }
323                AbsoluteLength::Rems(rems) => {
324                    taffy::style::LengthPercentageAuto::Length((*rems * rem_size).into())
325                }
326            },
327            DefiniteLength::Fraction(fraction) => {
328                taffy::style::LengthPercentageAuto::Percent(*fraction)
329            }
330        }
331    }
332}
333
334impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
335    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::Dimension {
336        match self {
337            DefiniteLength::Absolute(length) => match length {
338                AbsoluteLength::Pixels(pixels) => taffy::style::Dimension::Length(pixels.into()),
339                AbsoluteLength::Rems(rems) => {
340                    taffy::style::Dimension::Length((*rems * rem_size).into())
341                }
342            },
343            DefiniteLength::Fraction(fraction) => taffy::style::Dimension::Percent(*fraction),
344        }
345    }
346}
347
348impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
349    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentage {
350        match self {
351            AbsoluteLength::Pixels(pixels) => taffy::style::LengthPercentage::Length(pixels.into()),
352            AbsoluteLength::Rems(rems) => {
353                taffy::style::LengthPercentage::Length((*rems * rem_size).into())
354            }
355        }
356    }
357}
358
359impl<T, T2> From<TaffyPoint<T>> for Point<T2>
360where
361    T: Into<T2>,
362    T2: Clone + Debug + Default + PartialEq,
363{
364    fn from(point: TaffyPoint<T>) -> Point<T2> {
365        Point {
366            x: point.x.into(),
367            y: point.y.into(),
368        }
369    }
370}
371
372impl<T, T2> From<Point<T>> for TaffyPoint<T2>
373where
374    T: Into<T2> + Clone + Debug + Default + PartialEq,
375{
376    fn from(val: Point<T>) -> Self {
377        TaffyPoint {
378            x: val.x.into(),
379            y: val.y.into(),
380        }
381    }
382}
383
384impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
385where
386    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
387{
388    fn to_taffy(&self, rem_size: Pixels) -> TaffySize<U> {
389        TaffySize {
390            width: self.width.to_taffy(rem_size),
391            height: self.height.to_taffy(rem_size),
392        }
393    }
394}
395
396impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
397where
398    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
399{
400    fn to_taffy(&self, rem_size: Pixels) -> TaffyRect<U> {
401        TaffyRect {
402            top: self.top.to_taffy(rem_size),
403            right: self.right.to_taffy(rem_size),
404            bottom: self.bottom.to_taffy(rem_size),
405            left: self.left.to_taffy(rem_size),
406        }
407    }
408}
409
410impl<T, U> From<TaffySize<T>> for Size<U>
411where
412    T: Into<U>,
413    U: Clone + Debug + Default + PartialEq,
414{
415    fn from(taffy_size: TaffySize<T>) -> Self {
416        Size {
417            width: taffy_size.width.into(),
418            height: taffy_size.height.into(),
419        }
420    }
421}
422
423impl<T, U> From<Size<T>> for TaffySize<U>
424where
425    T: Into<U> + Clone + Debug + Default + PartialEq,
426{
427    fn from(size: Size<T>) -> Self {
428        TaffySize {
429            width: size.width.into(),
430            height: size.height.into(),
431        }
432    }
433}
434
435/// The space available for an element to be laid out in
436#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
437pub enum AvailableSpace {
438    /// The amount of space available is the specified number of pixels
439    Definite(Pixels),
440    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
441    #[default]
442    MinContent,
443    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
444    MaxContent,
445}
446
447impl AvailableSpace {
448    /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
449    ///
450    /// This function is useful when you want to create a `Size` with the minimum content constraints
451    /// for both dimensions.
452    ///
453    /// # Examples
454    ///
455    /// ```
456    /// let min_content_size = AvailableSpace::min_size();
457    /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
458    /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
459    /// ```
460    pub const fn min_size() -> Size<Self> {
461        Size {
462            width: Self::MinContent,
463            height: Self::MinContent,
464        }
465    }
466}
467
468impl From<AvailableSpace> for TaffyAvailableSpace {
469    fn from(space: AvailableSpace) -> TaffyAvailableSpace {
470        match space {
471            AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
472            AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
473            AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
474        }
475    }
476}
477
478impl From<TaffyAvailableSpace> for AvailableSpace {
479    fn from(space: TaffyAvailableSpace) -> AvailableSpace {
480        match space {
481            TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
482            TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
483            TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
484        }
485    }
486}
487
488impl From<Pixels> for AvailableSpace {
489    fn from(pixels: Pixels) -> Self {
490        AvailableSpace::Definite(pixels)
491    }
492}
493
494impl From<Size<Pixels>> for Size<AvailableSpace> {
495    fn from(size: Size<Pixels>) -> Self {
496        Size {
497            width: AvailableSpace::Definite(size.width),
498            height: AvailableSpace::Definite(size.height),
499        }
500    }
501}