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