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