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    pub fn compute_layout(
 69        &mut self,
 70        id: LayoutId,
 71        available_space: Size<AvailableSpace>,
 72    ) -> Result<()> {
 73        self.taffy
 74            .compute_layout(id.into(), available_space.into())?;
 75        Ok(())
 76    }
 77
 78    pub fn layout_bounds(&mut self, id: LayoutId) -> Result<Bounds<Pixels>> {
 79        if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
 80            return Ok(layout);
 81        }
 82
 83        let layout = self.taffy.layout(id.into())?;
 84        let mut bounds = Bounds {
 85            origin: layout.location.into(),
 86            size: layout.size.into(),
 87        };
 88
 89        if let Some(parent_id) = self.children_to_parents.get(&id).copied() {
 90            let parent_bounds = self.layout_bounds(parent_id)?;
 91            bounds.origin += parent_bounds.origin;
 92        }
 93        self.absolute_layout_bounds.insert(id, bounds);
 94
 95        Ok(bounds)
 96    }
 97}
 98
 99#[derive(Copy, Clone, Eq, PartialEq, Debug)]
100#[repr(transparent)]
101pub struct LayoutId(NodeId);
102
103impl std::hash::Hash for LayoutId {
104    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
105        u64::from(self.0).hash(state);
106    }
107}
108
109impl From<NodeId> for LayoutId {
110    fn from(node_id: NodeId) -> Self {
111        Self(node_id)
112    }
113}
114
115impl From<LayoutId> for NodeId {
116    fn from(layout_id: LayoutId) -> NodeId {
117        layout_id.0
118    }
119}
120
121struct Measureable<F>(F);
122
123impl<F> taffy::tree::Measurable for Measureable<F>
124where
125    F: Send + Sync + Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels>,
126{
127    fn measure(
128        &self,
129        known_dimensions: TaffySize<Option<f32>>,
130        available_space: TaffySize<TaffyAvailableSpace>,
131    ) -> TaffySize<f32> {
132        let known_dimensions: Size<Option<f32>> = known_dimensions.into();
133        let known_dimensions: Size<Option<Pixels>> = known_dimensions.map(|d| d.map(Into::into));
134        let available_space = available_space.into();
135        let size = (self.0)(known_dimensions, available_space);
136        size.into()
137    }
138}
139
140trait ToTaffy<Output> {
141    fn to_taffy(&self, rem_size: Pixels) -> Output;
142}
143
144impl ToTaffy<taffy::style::Style> for Style {
145    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::Style {
146        taffy::style::Style {
147            display: self.display,
148            overflow: self.overflow.clone().into(),
149            scrollbar_width: self.scrollbar_width,
150            position: self.position,
151            inset: self.inset.to_taffy(rem_size),
152            size: self.size.to_taffy(rem_size),
153            min_size: self.min_size.to_taffy(rem_size),
154            max_size: self.max_size.to_taffy(rem_size),
155            aspect_ratio: self.aspect_ratio,
156            margin: self.margin.to_taffy(rem_size),
157            padding: self.padding.to_taffy(rem_size),
158            border: self.border_widths.to_taffy(rem_size),
159            align_items: self.align_items,
160            align_self: self.align_self,
161            align_content: self.align_content,
162            justify_content: self.justify_content,
163            gap: self.gap.to_taffy(rem_size),
164            flex_direction: self.flex_direction,
165            flex_wrap: self.flex_wrap,
166            flex_basis: self.flex_basis.to_taffy(rem_size),
167            flex_grow: self.flex_grow,
168            flex_shrink: self.flex_shrink,
169            ..Default::default() // Ignore grid properties for now
170        }
171    }
172}
173
174// impl ToTaffy for Bounds<Length> {
175//     type Output = taffy::prelude::Bounds<taffy::prelude::LengthPercentageAuto>;
176
177//     fn to_taffy(
178//         &self,
179//         rem_size: Pixels,
180//     ) -> taffy::prelude::Bounds<taffy::prelude::LengthPercentageAuto> {
181//         taffy::prelude::Bounds {
182//             origin: self.origin.to_taffy(rem_size),
183//             size: self.size.to_taffy(rem_size),
184//         }
185//     }
186// }
187
188impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
189    fn to_taffy(&self, rem_size: Pixels) -> taffy::prelude::LengthPercentageAuto {
190        match self {
191            Length::Definite(length) => length.to_taffy(rem_size),
192            Length::Auto => taffy::prelude::LengthPercentageAuto::Auto,
193        }
194    }
195}
196
197impl ToTaffy<taffy::style::Dimension> for Length {
198    fn to_taffy(&self, rem_size: Pixels) -> taffy::prelude::Dimension {
199        match self {
200            Length::Definite(length) => length.to_taffy(rem_size),
201            Length::Auto => taffy::prelude::Dimension::Auto,
202        }
203    }
204}
205
206impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
207    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentage {
208        match self {
209            DefiniteLength::Absolute(length) => match length {
210                AbsoluteLength::Pixels(pixels) => {
211                    taffy::style::LengthPercentage::Length(pixels.into())
212                }
213                AbsoluteLength::Rems(rems) => {
214                    taffy::style::LengthPercentage::Length((*rems * rem_size).into())
215                }
216            },
217            DefiniteLength::Fraction(fraction) => {
218                taffy::style::LengthPercentage::Percent(*fraction)
219            }
220        }
221    }
222}
223
224impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
225    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentageAuto {
226        match self {
227            DefiniteLength::Absolute(length) => match length {
228                AbsoluteLength::Pixels(pixels) => {
229                    taffy::style::LengthPercentageAuto::Length(pixels.into())
230                }
231                AbsoluteLength::Rems(rems) => {
232                    taffy::style::LengthPercentageAuto::Length((*rems * rem_size).into())
233                }
234            },
235            DefiniteLength::Fraction(fraction) => {
236                taffy::style::LengthPercentageAuto::Percent(*fraction)
237            }
238        }
239    }
240}
241
242impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
243    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::Dimension {
244        match self {
245            DefiniteLength::Absolute(length) => match length {
246                AbsoluteLength::Pixels(pixels) => taffy::style::Dimension::Length(pixels.into()),
247                AbsoluteLength::Rems(rems) => {
248                    taffy::style::Dimension::Length((*rems * rem_size).into())
249                }
250            },
251            DefiniteLength::Fraction(fraction) => taffy::style::Dimension::Percent(*fraction),
252        }
253    }
254}
255
256impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
257    fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentage {
258        match self {
259            AbsoluteLength::Pixels(pixels) => taffy::style::LengthPercentage::Length(pixels.into()),
260            AbsoluteLength::Rems(rems) => {
261                taffy::style::LengthPercentage::Length((*rems * rem_size).into())
262            }
263        }
264    }
265}
266
267impl<T, T2: Clone + Debug> From<taffy::geometry::Point<T>> for Point<T2>
268where
269    T: Into<T2>,
270{
271    fn from(point: taffy::geometry::Point<T>) -> Point<T2> {
272        Point {
273            x: point.x.into(),
274            y: point.y.into(),
275        }
276    }
277}
278
279impl<T: Clone + Debug, T2> Into<taffy::geometry::Point<T2>> for Point<T>
280where
281    T: Into<T2>,
282{
283    fn into(self) -> taffy::geometry::Point<T2> {
284        taffy::geometry::Point {
285            x: self.x.into(),
286            y: self.y.into(),
287        }
288    }
289}
290
291impl<T: ToTaffy<U> + Clone + Debug, U> ToTaffy<taffy::geometry::Size<U>> for Size<T> {
292    fn to_taffy(&self, rem_size: Pixels) -> taffy::geometry::Size<U> {
293        taffy::geometry::Size {
294            width: self.width.to_taffy(rem_size).into(),
295            height: self.height.to_taffy(rem_size).into(),
296        }
297    }
298}
299
300impl<T, U> ToTaffy<taffy::geometry::Rect<U>> for Edges<T>
301where
302    T: ToTaffy<U> + Clone + Debug,
303{
304    fn to_taffy(&self, rem_size: Pixels) -> taffy::geometry::Rect<U> {
305        taffy::geometry::Rect {
306            top: self.top.to_taffy(rem_size).into(),
307            right: self.right.to_taffy(rem_size).into(),
308            bottom: self.bottom.to_taffy(rem_size).into(),
309            left: self.left.to_taffy(rem_size).into(),
310        }
311    }
312}
313
314impl<T: Into<U>, U: Clone + Debug> From<TaffySize<T>> for Size<U> {
315    fn from(taffy_size: taffy::geometry::Size<T>) -> Self {
316        Size {
317            width: taffy_size.width.into(),
318            height: taffy_size.height.into(),
319        }
320    }
321}
322
323impl<T: Into<U> + Clone + Debug, U> From<Size<T>> for taffy::geometry::Size<U> {
324    fn from(size: Size<T>) -> Self {
325        taffy::geometry::Size {
326            width: size.width.into(),
327            height: size.height.into(),
328        }
329    }
330}
331
332// impl From<TaffySize<Option<f32>>> for Size<Option<Pixels>> {
333//     fn from(value: TaffySize<Option<f32>>) -> Self {
334//         Self {
335//             width: value.width.map(Into::into),
336//             height: value.height.map(Into::into),
337//         }
338//     }
339// }
340
341#[derive(Copy, Clone, Debug)]
342pub enum AvailableSpace {
343    /// The amount of space available is the specified number of pixels
344    Definite(Pixels),
345    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
346    MinContent,
347    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
348    MaxContent,
349}
350
351impl From<AvailableSpace> for TaffyAvailableSpace {
352    fn from(space: AvailableSpace) -> TaffyAvailableSpace {
353        match space {
354            AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
355            AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
356            AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
357        }
358    }
359}
360
361impl From<TaffyAvailableSpace> for AvailableSpace {
362    fn from(space: TaffyAvailableSpace) -> AvailableSpace {
363        match space {
364            TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
365            TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
366            TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
367        }
368    }
369}
370
371impl From<Pixels> for AvailableSpace {
372    fn from(pixels: Pixels) -> Self {
373        AvailableSpace::Definite(pixels)
374    }
375}