1use crate::{
2 AbsoluteLength, App, Bounds, DefiniteLength, Edges, Length, Pixels, Point, Size, Style, Window,
3};
4use collections::{FxHashMap, FxHashSet};
5use smallvec::SmallVec;
6use std::{cell::RefCell, fmt::Debug, ops::Range};
7use taffy::{
8 TaffyTree, TraversePartialTree as _,
9 geometry::{Point as TaffyPoint, Rect as TaffyRect, Size as TaffySize},
10 style::AvailableSpace as TaffyAvailableSpace,
11 tree::NodeId,
12};
13
14thread_local! {
15 pub static LAYOUT_ID_TO_DEBUG: RefCell<Option<LayoutId>> = const { RefCell::new(None) };
16}
17
18thread_local! {
19 pub static CONTAINER_LAYOUT_ID_TO_DEBUG: RefCell<Option<LayoutId>> = const { RefCell::new(None) };
20}
21
22thread_local! {
23 pub static LOG_TAFFY: RefCell<bool> = const { RefCell::new(false) };
24}
25
26type NodeMeasureFn = Box<
27 dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>,
28>;
29
30struct NodeContext {
31 measure: NodeMeasureFn,
32}
33pub struct TaffyLayoutEngine {
34 taffy: TaffyTree<NodeContext>,
35 absolute_layout_bounds: FxHashMap<LayoutId, Bounds<Pixels>>,
36 computed_layouts: FxHashSet<LayoutId>,
37}
38
39const EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";
40
41fn layout_id_to_var_name(layout_id: LayoutId) -> String {
42 let node_id: u64 = layout_id.clone().0.into();
43 format!("node_{}", node_id)
44}
45
46impl TaffyLayoutEngine {
47 pub fn new() -> Self {
48 let mut taffy = TaffyTree::new();
49 taffy.disable_rounding();
50 TaffyLayoutEngine {
51 taffy,
52 absolute_layout_bounds: FxHashMap::default(),
53 computed_layouts: FxHashSet::default(),
54 }
55 }
56
57 pub fn clear(&mut self) {
58 self.taffy.clear();
59 self.absolute_layout_bounds.clear();
60 self.computed_layouts.clear();
61 }
62
63 pub fn request_layout(
64 &mut self,
65 style: Style,
66 rem_size: Pixels,
67 children: &[LayoutId],
68 ) -> LayoutId {
69 let should_log = LOG_TAFFY.with_borrow(|log_taffy| *log_taffy);
70 let taffy_style = style.to_taffy(rem_size);
71 let layout_id = if children.is_empty() {
72 let layout_id = self
73 .taffy
74 .new_leaf(taffy_style)
75 .expect(EXPECT_MESSAGE)
76 .into();
77 if should_log {
78 let var_name = layout_id_to_var_name(layout_id);
79 println!(
80 "let {} = taffy.new_leaf({:?}).unwrap();",
81 var_name,
82 serde_json::to_string(&style.to_taffy(rem_size)).unwrap(),
83 );
84 }
85 layout_id
86 } else {
87 let parent_id = self
88 .taffy
89 // This is safe because LayoutId is repr(transparent) to taffy::tree::NodeId.
90 .new_with_children(taffy_style, unsafe {
91 std::mem::transmute::<&[LayoutId], &[taffy::NodeId]>(children)
92 })
93 .expect(EXPECT_MESSAGE)
94 .into();
95 if should_log {
96 let var_name = layout_id_to_var_name(parent_id);
97 println!(
98 "let {} = taffy.new_with_children({:?}, &[{:?}]).unwrap();",
99 var_name,
100 serde_json::to_string(&style.to_taffy(rem_size)).unwrap(),
101 children
102 .iter()
103 .map(|id| layout_id_to_var_name(*id))
104 .collect::<Vec<_>>()
105 .join(", ")
106 );
107 }
108 parent_id
109 };
110 layout_id
111 }
112
113 pub fn request_measured_layout(
114 &mut self,
115 style: Style,
116 rem_size: Pixels,
117 mut measure: impl FnMut(
118 Size<Option<Pixels>>,
119 Size<AvailableSpace>,
120 &mut Window,
121 &mut App,
122 ) -> Size<Pixels>
123 + 'static,
124 ) -> LayoutId {
125 let taffy_style = style.to_taffy(rem_size);
126
127 let should_log = LOG_TAFFY.with_borrow(|log_taffy| *log_taffy);
128
129 let layout_id = self
130 .taffy
131 .new_leaf_with_context(
132 taffy_style,
133 NodeContext {
134 measure: Box::new(move |size, available_space, window, app| {
135 let result = measure(size, available_space, window, app);
136 if should_log {
137 println!("measure({:?}, {:?}) == {:?}", size, available_space, result);
138 }
139 result
140 }),
141 },
142 )
143 .expect(EXPECT_MESSAGE)
144 .into();
145
146 if should_log {
147 println!(
148 "let {} = taffy.new_leaf_with_context({:?}, MEASURE_CONTEXT).unwrap()",
149 layout_id_to_var_name(layout_id),
150 serde_json::to_string(&style.to_taffy(rem_size)).unwrap(),
151 );
152 }
153
154 layout_id
155 }
156
157 // Used to understand performance
158 #[allow(dead_code)]
159 fn count_all_children(&self, parent: LayoutId) -> anyhow::Result<u32> {
160 let mut count = 0;
161
162 for child in self.taffy.children(parent.0)? {
163 // Count this child.
164 count += 1;
165
166 // Count all of this child's children.
167 count += self.count_all_children(LayoutId(child))?
168 }
169
170 Ok(count)
171 }
172
173 // Used to understand performance
174 #[allow(dead_code)]
175 fn max_depth(&self, depth: u32, parent: LayoutId) -> anyhow::Result<u32> {
176 println!(
177 "{parent:?} at depth {depth} has {} children",
178 self.taffy.child_count(parent.0)
179 );
180
181 let mut max_child_depth = 0;
182
183 for child in self.taffy.children(parent.0)? {
184 max_child_depth = std::cmp::max(max_child_depth, self.max_depth(0, LayoutId(child))?);
185 }
186
187 Ok(depth + 1 + max_child_depth)
188 }
189
190 // Used to understand performance
191 #[allow(dead_code)]
192 fn get_edges(&self, parent: LayoutId) -> anyhow::Result<Vec<(LayoutId, LayoutId)>> {
193 let mut edges = Vec::new();
194
195 for child in self.taffy.children(parent.0)? {
196 edges.push((parent, LayoutId(child)));
197
198 edges.extend(self.get_edges(LayoutId(child))?);
199 }
200
201 Ok(edges)
202 }
203
204 pub fn compute_layout(
205 &mut self,
206 id: LayoutId,
207 available_space: Size<AvailableSpace>,
208 window: &mut Window,
209 cx: &mut App,
210 ) {
211 // Leaving this here until we have a better instrumentation approach.
212 // println!("Laying out {} children", self.count_all_children(id)?);
213 // println!("Max layout depth: {}", self.max_depth(0, id)?);
214
215 // Output the edges (branches) of the tree in Mermaid format for visualization.
216 // println!("Edges:");
217 // for (a, b) in self.get_edges(id)? {
218 // println!("N{} --> N{}", u64::from(a), u64::from(b));
219 // }
220 // println!("");
221 //
222
223 if !self.computed_layouts.insert(id) {
224 let mut stack = SmallVec::<[LayoutId; 64]>::new();
225 stack.push(id);
226 while let Some(id) = stack.pop() {
227 self.absolute_layout_bounds.remove(&id);
228 stack.extend(
229 self.taffy
230 .children(id.into())
231 .expect(EXPECT_MESSAGE)
232 .into_iter()
233 .map(Into::into),
234 );
235 }
236 }
237
238 // let started_at = std::time::Instant::now();
239 self.taffy
240 .compute_layout_with_measure(
241 id.into(),
242 available_space.into(),
243 |known_dimensions, available_space, _id, node_context, _style| {
244 let Some(node_context) = node_context else {
245 return taffy::geometry::Size::default();
246 };
247
248 let known_dimensions = Size {
249 width: known_dimensions.width.map(Pixels),
250 height: known_dimensions.height.map(Pixels),
251 };
252
253 (node_context.measure)(known_dimensions, available_space.into(), window, cx)
254 .into()
255 },
256 )
257 .expect(EXPECT_MESSAGE);
258
259 /*
260 LAYOUT_ID_TO_DEBUG.with_borrow(|layout_id_to_debug| {
261 println!("Layout ID Debug: {:?}", layout_id_to_debug);
262 });
263
264 CONTAINER_LAYOUT_ID_TO_DEBUG.with_borrow(|layout_id| {
265 println!("Container Layout ID Debug: {:?}\n", layout_id);
266 });
267 */
268
269 // println!("compute_layout took {:?}", started_at.elapsed());
270 }
271
272 pub fn layout_bounds(&mut self, id: LayoutId) -> Bounds<Pixels> {
273 if let Some(layout) = self.absolute_layout_bounds.get(&id).cloned() {
274 return layout;
275 }
276
277 let layout = self.taffy.layout(id.into()).expect(EXPECT_MESSAGE);
278 let mut bounds = Bounds {
279 origin: layout.location.into(),
280 size: layout.size.into(),
281 };
282
283 if let Some(parent_id) = self.taffy.parent(id.0) {
284 let parent_bounds = self.layout_bounds(parent_id.into());
285 bounds.origin += parent_bounds.origin;
286 }
287 self.absolute_layout_bounds.insert(id, bounds);
288
289 bounds
290 }
291}
292
293/// A unique identifier for a layout node, generated when requesting a layout from Taffy
294#[derive(Copy, Clone, Eq, PartialEq, Debug)]
295#[repr(transparent)]
296pub struct LayoutId(NodeId);
297
298impl std::hash::Hash for LayoutId {
299 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
300 u64::from(self.0).hash(state);
301 }
302}
303
304impl From<NodeId> for LayoutId {
305 fn from(node_id: NodeId) -> Self {
306 Self(node_id)
307 }
308}
309
310impl From<LayoutId> for NodeId {
311 fn from(layout_id: LayoutId) -> NodeId {
312 layout_id.0
313 }
314}
315
316trait ToTaffy<Output> {
317 fn to_taffy(&self, rem_size: Pixels) -> Output;
318}
319
320impl ToTaffy<taffy::style::Style> for Style {
321 fn to_taffy(&self, rem_size: Pixels) -> taffy::style::Style {
322 use taffy::style_helpers::{fr, length, minmax, repeat};
323
324 fn to_grid_line(
325 placement: &Range<crate::GridPlacement>,
326 ) -> taffy::Line<taffy::GridPlacement> {
327 taffy::Line {
328 start: placement.start.into(),
329 end: placement.end.into(),
330 }
331 }
332
333 fn to_grid_repeat<T: taffy::style::CheapCloneStr>(
334 unit: &Option<u16>,
335 ) -> Vec<taffy::GridTemplateComponent<T>> {
336 // grid-template-columns: repeat(<number>, minmax(0, 1fr));
337 unit.map(|count| vec![repeat(count, vec![minmax(length(0.0), fr(1.0))])])
338 .unwrap_or_default()
339 }
340
341 taffy::style::Style {
342 display: self.display.into(),
343 overflow: self.overflow.into(),
344 scrollbar_width: self.scrollbar_width,
345 position: self.position.into(),
346 inset: self.inset.to_taffy(rem_size),
347 size: self.size.to_taffy(rem_size),
348 min_size: self.min_size.to_taffy(rem_size),
349 max_size: self.max_size.to_taffy(rem_size),
350 aspect_ratio: self.aspect_ratio,
351 margin: self.margin.to_taffy(rem_size),
352 padding: self.padding.to_taffy(rem_size),
353 border: self.border_widths.to_taffy(rem_size),
354 align_items: self.align_items.map(|x| x.into()),
355 align_self: self.align_self.map(|x| x.into()),
356 align_content: self.align_content.map(|x| x.into()),
357 justify_content: self.justify_content.map(|x| x.into()),
358 gap: self.gap.to_taffy(rem_size),
359 flex_direction: self.flex_direction.into(),
360 flex_wrap: self.flex_wrap.into(),
361 flex_basis: self.flex_basis.to_taffy(rem_size),
362 flex_grow: self.flex_grow,
363 flex_shrink: self.flex_shrink,
364 grid_template_rows: to_grid_repeat(&self.grid_rows),
365 grid_template_columns: to_grid_repeat(&self.grid_cols),
366 grid_row: self
367 .grid_location
368 .as_ref()
369 .map(|location| to_grid_line(&location.row))
370 .unwrap_or_default(),
371 grid_column: self
372 .grid_location
373 .as_ref()
374 .map(|location| to_grid_line(&location.column))
375 .unwrap_or_default(),
376 ..Default::default()
377 }
378 }
379}
380
381impl ToTaffy<taffy::style::LengthPercentageAuto> for Length {
382 fn to_taffy(&self, rem_size: Pixels) -> taffy::prelude::LengthPercentageAuto {
383 match self {
384 Length::Definite(length) => length.to_taffy(rem_size),
385 Length::Auto => taffy::prelude::LengthPercentageAuto::auto(),
386 }
387 }
388}
389
390impl ToTaffy<taffy::style::Dimension> for Length {
391 fn to_taffy(&self, rem_size: Pixels) -> taffy::prelude::Dimension {
392 match self {
393 Length::Definite(length) => length.to_taffy(rem_size),
394 Length::Auto => taffy::prelude::Dimension::auto(),
395 }
396 }
397}
398
399impl ToTaffy<taffy::style::LengthPercentage> for DefiniteLength {
400 fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentage {
401 match self {
402 DefiniteLength::Absolute(length) => match length {
403 AbsoluteLength::Pixels(pixels) => {
404 taffy::style::LengthPercentage::length(pixels.into())
405 }
406 AbsoluteLength::Rems(rems) => {
407 taffy::style::LengthPercentage::length((*rems * rem_size).into())
408 }
409 },
410 DefiniteLength::Fraction(fraction) => {
411 taffy::style::LengthPercentage::percent(*fraction)
412 }
413 }
414 }
415}
416
417impl ToTaffy<taffy::style::LengthPercentageAuto> for DefiniteLength {
418 fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentageAuto {
419 match self {
420 DefiniteLength::Absolute(length) => match length {
421 AbsoluteLength::Pixels(pixels) => {
422 taffy::style::LengthPercentageAuto::length(pixels.into())
423 }
424 AbsoluteLength::Rems(rems) => {
425 taffy::style::LengthPercentageAuto::length((*rems * rem_size).into())
426 }
427 },
428 DefiniteLength::Fraction(fraction) => {
429 taffy::style::LengthPercentageAuto::percent(*fraction)
430 }
431 }
432 }
433}
434
435impl ToTaffy<taffy::style::Dimension> for DefiniteLength {
436 fn to_taffy(&self, rem_size: Pixels) -> taffy::style::Dimension {
437 match self {
438 DefiniteLength::Absolute(length) => match length {
439 AbsoluteLength::Pixels(pixels) => taffy::style::Dimension::length(pixels.into()),
440 AbsoluteLength::Rems(rems) => {
441 taffy::style::Dimension::length((*rems * rem_size).into())
442 }
443 },
444 DefiniteLength::Fraction(fraction) => taffy::style::Dimension::percent(*fraction),
445 }
446 }
447}
448
449impl ToTaffy<taffy::style::LengthPercentage> for AbsoluteLength {
450 fn to_taffy(&self, rem_size: Pixels) -> taffy::style::LengthPercentage {
451 match self {
452 AbsoluteLength::Pixels(pixels) => taffy::style::LengthPercentage::length(pixels.into()),
453 AbsoluteLength::Rems(rems) => {
454 taffy::style::LengthPercentage::length((*rems * rem_size).into())
455 }
456 }
457 }
458}
459
460impl<T, T2> From<TaffyPoint<T>> for Point<T2>
461where
462 T: Into<T2>,
463 T2: Clone + Debug + Default + PartialEq,
464{
465 fn from(point: TaffyPoint<T>) -> Point<T2> {
466 Point {
467 x: point.x.into(),
468 y: point.y.into(),
469 }
470 }
471}
472
473impl<T, T2> From<Point<T>> for TaffyPoint<T2>
474where
475 T: Into<T2> + Clone + Debug + Default + PartialEq,
476{
477 fn from(val: Point<T>) -> Self {
478 TaffyPoint {
479 x: val.x.into(),
480 y: val.y.into(),
481 }
482 }
483}
484
485impl<T, U> ToTaffy<TaffySize<U>> for Size<T>
486where
487 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
488{
489 fn to_taffy(&self, rem_size: Pixels) -> TaffySize<U> {
490 TaffySize {
491 width: self.width.to_taffy(rem_size),
492 height: self.height.to_taffy(rem_size),
493 }
494 }
495}
496
497impl<T, U> ToTaffy<TaffyRect<U>> for Edges<T>
498where
499 T: ToTaffy<U> + Clone + Debug + Default + PartialEq,
500{
501 fn to_taffy(&self, rem_size: Pixels) -> TaffyRect<U> {
502 TaffyRect {
503 top: self.top.to_taffy(rem_size),
504 right: self.right.to_taffy(rem_size),
505 bottom: self.bottom.to_taffy(rem_size),
506 left: self.left.to_taffy(rem_size),
507 }
508 }
509}
510
511impl<T, U> From<TaffySize<T>> for Size<U>
512where
513 T: Into<U>,
514 U: Clone + Debug + Default + PartialEq,
515{
516 fn from(taffy_size: TaffySize<T>) -> Self {
517 Size {
518 width: taffy_size.width.into(),
519 height: taffy_size.height.into(),
520 }
521 }
522}
523
524impl<T, U> From<Size<T>> for TaffySize<U>
525where
526 T: Into<U> + Clone + Debug + Default + PartialEq,
527{
528 fn from(size: Size<T>) -> Self {
529 TaffySize {
530 width: size.width.into(),
531 height: size.height.into(),
532 }
533 }
534}
535
536/// The space available for an element to be laid out in
537#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
538pub enum AvailableSpace {
539 /// The amount of space available is the specified number of pixels
540 Definite(Pixels),
541 /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
542 #[default]
543 MinContent,
544 /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
545 MaxContent,
546}
547
548impl AvailableSpace {
549 /// Returns a `Size` with both width and height set to `AvailableSpace::MinContent`.
550 ///
551 /// This function is useful when you want to create a `Size` with the minimum content constraints
552 /// for both dimensions.
553 ///
554 /// # Examples
555 ///
556 /// ```
557 /// let min_content_size = AvailableSpace::min_size();
558 /// assert_eq!(min_content_size.width, AvailableSpace::MinContent);
559 /// assert_eq!(min_content_size.height, AvailableSpace::MinContent);
560 /// ```
561 pub const fn min_size() -> Size<Self> {
562 Size {
563 width: Self::MinContent,
564 height: Self::MinContent,
565 }
566 }
567}
568
569impl From<AvailableSpace> for TaffyAvailableSpace {
570 fn from(space: AvailableSpace) -> TaffyAvailableSpace {
571 match space {
572 AvailableSpace::Definite(Pixels(value)) => TaffyAvailableSpace::Definite(value),
573 AvailableSpace::MinContent => TaffyAvailableSpace::MinContent,
574 AvailableSpace::MaxContent => TaffyAvailableSpace::MaxContent,
575 }
576 }
577}
578
579impl From<TaffyAvailableSpace> for AvailableSpace {
580 fn from(space: TaffyAvailableSpace) -> AvailableSpace {
581 match space {
582 TaffyAvailableSpace::Definite(value) => AvailableSpace::Definite(Pixels(value)),
583 TaffyAvailableSpace::MinContent => AvailableSpace::MinContent,
584 TaffyAvailableSpace::MaxContent => AvailableSpace::MaxContent,
585 }
586 }
587}
588
589impl From<Pixels> for AvailableSpace {
590 fn from(pixels: Pixels) -> Self {
591 AvailableSpace::Definite(pixels)
592 }
593}
594
595impl From<Size<Pixels>> for Size<AvailableSpace> {
596 fn from(size: Size<Pixels>) -> Self {
597 Size {
598 width: AvailableSpace::Definite(size.width),
599 height: AvailableSpace::Definite(size.height),
600 }
601 }
602}