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