taffy.rs

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