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        // println!("");
168        //
169
170        if !self.computed_layouts.insert(id) {
171            let mut stack = SmallVec::<[LayoutId; 64]>::new();
172            stack.push(id);
173            while let Some(id) = stack.pop() {
174                self.absolute_layout_bounds.remove(&id);
175                stack.extend(
176                    self.taffy
177                        .children(id.into())
178                        .expect(EXPECT_MESSAGE)
179                        .into_iter()
180                        .map(Into::into),
181                );
182            }
183        }
184
185        // let started_at = std::time::Instant::now();
186        self.taffy
187            .compute_layout_with_measure(
188                id.into(),
189                available_space.into(),
190                |known_dimensions, available_space, _id, node_context, _style| {
191                    let Some(node_context) = node_context else {
192                        return taffy::geometry::Size::default();
193                    };
194
195                    let known_dimensions = Size {
196                        width: known_dimensions.width.map(Pixels),
197                        height: known_dimensions.height.map(Pixels),
198                    };
199
200                    (node_context.measure)(known_dimensions, available_space.into(), window, cx)
201                        .into()
202                },
203            )
204            .expect(EXPECT_MESSAGE);
205
206        // println!("compute_layout took {:?}", started_at.elapsed());
207    }
208
209    pub fn layout_bounds(&mut self, id: LayoutId) -> Bounds<Pixels> {
210        if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
211            return layout;
212        }
213
214        let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
215        let mut bounds = Bounds {
216            origin: layout.location.into(),
217            size: layout.size.into(),
218        };
219
220        if let Some(parent_id) = self.taffy.parent(id.0) {
221            let parent_bounds = self.layout_bounds(parent_id.into());
222            bounds.origin += parent_bounds.origin;
223        }
224        self.absolute_layout_bounds.insert(id, bounds);
225
226        bounds
227    }
228}
229
230/// A unique identifier for a layout node, generated when requesting a layout from Taffy
231#[derive(Copy, Clone, Eq, PartialEq, Debug)]
232#[repr(transparent)]
233pub struct LayoutId(NodeId);
234
235impl std::hash::Hash for LayoutId {
236    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
237        u64::from(self.0).hash(state);
238    }
239}
240
241impl From<NodeId> for LayoutId {
242    fn from(node_id: NodeId) -> Self {
243        Self(node_id)
244    }
245}
246
247impl From<LayoutId> for NodeId {
248    fn from(layout_id: LayoutId) -> NodeId {
249        layout_id.0
250    }
251}
252
253trait ToTaffy<Output> {
254    fn to_taffy(&self, rem_size: Pixels) -> Output;
255}
256
257impl ToTaffy<taffy::style::Style> for Style {
258    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::Style {
259        use taffy::style_helpers::{fr, length, minmax, repeat};
260
261        fn to_grid_line(
262            placement: &Range<crate::GridPlacement>,
263        ) -> taffy::Line<taffy::GridPlacement> {
264            taffy::Line {
265                start: placement.start.into(),
266                end: placement.end.into(),
267            }
268        }
269
270        fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
271            unit: &Option<u16>,
272        ) -> Vec<taffy::GridTemplateComponent<T>> {
273            // grid-template-columns: repeat(<number>, minmax(0, 1fr));
274            unit.map(|count| vec![repeat(count, vec![minmax(length(0.0), fr(1.0))])])
275                .unwrap_or_default()
276        }
277
278        taffy::style::Style {
279            display: self.display.into(),
280            overflow: self.overflow.into(),
281            scrollbar_width: self.scrollbar_width,
282            position: self.position.into(),
283            inset: self.inset.to_taffy(rem_size),
284            size: self.size.to_taffy(rem_size),
285            min_size: self.min_size.to_taffy(rem_size),
286            max_size: self.max_size.to_taffy(rem_size),
287            aspect_ratio: self.aspect_ratio,
288            margin: self.margin.to_taffy(rem_size),
289            padding: self.padding.to_taffy(rem_size),
290            border: self.border_widths.to_taffy(rem_size),
291            align_items: self.align_items.map(|x| x.into()),
292            align_self: self.align_self.map(|x| x.into()),
293            align_content: self.align_content.map(|x| x.into()),
294            justify_content: self.justify_content.map(|x| x.into()),
295            gap: self.gap.to_taffy(rem_size),
296            flex_direction: self.flex_direction.into(),
297            flex_wrap: self.flex_wrap.into(),
298            flex_basis: self.flex_basis.to_taffy(rem_size),
299            flex_grow: self.flex_grow,
300            flex_shrink: self.flex_shrink,
301            grid_template_rows: to_grid_repeat(&self.grid_rows),
302            grid_template_columns: to_grid_repeat(&self.grid_cols),
303            grid_row: self
304                .grid_location
305                .as_ref()
306                .map(|location| to_grid_line(&location.row))
307                .unwrap_or_default(),
308            grid_column: self
309                .grid_location
310                .as_ref()
311                .map(|location| to_grid_line(&location.column))
312                .unwrap_or_default(),
313            ..Default::default()
314        }
315    }
316}
317
318impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
319    fn to_taffy(&self, rem_size: Pixels) -> taffy::prelude::LengthPercentageAuto {
320        match self {
321            Length::Definite(length) => length.to_taffy(rem_size),
322            Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
323        }
324    }
325}
326
327impl ToTaffy<taffy::style::Dimension> for Length {
328    fn to_taffy(&self, rem_size: Pixels) -> taffy::prelude::Dimension {
329        match self {
330            Length::Definite(length) => length.to_taffy(rem_size),
331            Length::Auto => taffy::prelude::Dimension::auto(),
332        }
333    }
334}
335
336impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
337    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentage {
338        match self {
339            DefiniteLength::Absolute(length) => match length {
340                AbsoluteLength::Pixels(pixels) => {
341                    taffy::style::LengthPercentage::length(pixels.into())
342                }
343                AbsoluteLength::Rems(rems) => {
344                    taffy::style::LengthPercentage::length((*rems * rem_size).into())
345                }
346            },
347            DefiniteLength::Fraction(fraction) => {
348                taffy::style::LengthPercentage::percent(*fraction)
349            }
350        }
351    }
352}
353
354impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
355    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentageAuto {
356        match self {
357            DefiniteLength::Absolute(length) => match length {
358                AbsoluteLength::Pixels(pixels) => {
359                    taffy::style::LengthPercentageAuto::length(pixels.into())
360                }
361                AbsoluteLength::Rems(rems) => {
362                    taffy::style::LengthPercentageAuto::length((*rems * rem_size).into())
363                }
364            },
365            DefiniteLength::Fraction(fraction) => {
366                taffy::style::LengthPercentageAuto::percent(*fraction)
367            }
368        }
369    }
370}
371
372impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
373    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::Dimension {
374        match self {
375            DefiniteLength::Absolute(length) => match length {
376                AbsoluteLength::Pixels(pixels) => taffy::style::Dimension::length(pixels.into()),
377                AbsoluteLength::Rems(rems) => {
378                    taffy::style::Dimension::length((*rems * rem_size).into())
379                }
380            },
381            DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
382        }
383    }
384}
385
386impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
387    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentage {
388        match self {
389            AbsoluteLength::Pixels(pixels) => taffy::style::LengthPercentage::length(pixels.into()),
390            AbsoluteLength::Rems(rems) => {
391                taffy::style::LengthPercentage::length((*rems * rem_size).into())
392            }
393        }
394    }
395}
396
397impl<T, T2> From<TaffyPoint<T>> for Point<T2>
398where
399    T: Into<T2>,
400    T2: Clone + Debug + Default + PartialEq,
401{
402    fn from(point: TaffyPoint<T>) -> Point<T2> {
403        Point {
404            x: point.x.into(),
405            y: point.y.into(),
406        }
407    }
408}
409
410impl<T, T2> From<Point<T>> for TaffyPoint<T2>
411where
412    T: Into<T2> + Clone + Debug + Default + PartialEq,
413{
414    fn from(val: Point<T>) -> Self {
415        TaffyPoint {
416            x: val.x.into(),
417            y: val.y.into(),
418        }
419    }
420}
421
422impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
423where
424    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
425{
426    fn to_taffy(&self, rem_size: Pixels) -> TaffySize<U> {
427        TaffySize {
428            width: self.width.to_taffy(rem_size),
429            height: self.height.to_taffy(rem_size),
430        }
431    }
432}
433
434impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
435where
436    T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
437{
438    fn to_taffy(&self, rem_size: Pixels) -> TaffyRect<U> {
439        TaffyRect {
440            top: self.top.to_taffy(rem_size),
441            right: self.right.to_taffy(rem_size),
442            bottom: self.bottom.to_taffy(rem_size),
443            left: self.left.to_taffy(rem_size),
444        }
445    }
446}
447
448impl<T, U> From<TaffySize<T>> for Size<U>
449where
450    T: Into<U>,
451    U: Clone + Debug + Default + PartialEq,
452{
453    fn from(taffy_size: TaffySize<T>) -> Self {
454        Size {
455            width: taffy_size.width.into(),
456            height: taffy_size.height.into(),
457        }
458    }
459}
460
461impl<T, U> From<Size<T>> for TaffySize<U>
462where
463    T: Into<U> + Clone + Debug + Default + PartialEq,
464{
465    fn from(size: Size<T>) -> Self {
466        TaffySize {
467            width: size.width.into(),
468            height: size.height.into(),
469        }
470    }
471}
472
473/// The space available for an element to be laid out in
474#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
475pub enum AvailableSpace {
476    /// The amount of space available is the specified number of pixels
477    Definite(Pixels),
478    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
479    #[default]
480    MinContent,
481    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
482    MaxContent,
483}
484
485impl AvailableSpace {
486    /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
487    ///
488    /// This function is useful when you want to create a `Size` with the minimum content constraints
489    /// for both dimensions.
490    ///
491    /// # Examples
492    ///
493    /// ```
494    /// let min_content_size = AvailableSpace::min_size();
495    /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
496    /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
497    /// ```
498    pub const fn min_size() -> Size<Self> {
499        Size {
500            width: Self::MinContent,
501            height: Self::MinContent,
502        }
503    }
504}
505
506impl From<AvailableSpace> for TaffyAvailableSpace {
507    fn from(space: AvailableSpace) -> TaffyAvailableSpace {
508        match space {
509            AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
510            AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
511            AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
512        }
513    }
514}
515
516impl From<TaffyAvailableSpace> for AvailableSpace {
517    fn from(space: TaffyAvailableSpace) -> AvailableSpace {
518        match space {
519            TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
520            TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
521            TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
522        }
523    }
524}
525
526impl From<Pixels> for AvailableSpace {
527    fn from(pixels: Pixels) -> Self {
528        AvailableSpace::Definite(pixels)
529    }
530}
531
532impl From<Size<Pixels>> for Size<AvailableSpace> {
533    fn from(size: Size<Pixels>) -> Self {
534        Size {
535            width: AvailableSpace::Definite(size.width),
536            height: AvailableSpace::Definite(size.height),
537        }
538    }
539}