taffy.rs

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