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