Fix rounding accumulation bug (#521)
1//! UI [`Node`] types and related data structures.
2//!
3//! Layouts are composed of multiple nodes, which live in a tree-like data structure.
4use slotmap::{DefaultKey, SlotMap, SparseSecondaryMap};
5
6/// A node in a layout.
7pub type Node = slotmap::DefaultKey;
8
9use crate::error::{TaffyError, TaffyResult};
10use crate::geometry::Size;
11use crate::layout::{Cache, Layout};
12use crate::prelude::LayoutTree;
13use crate::style::{AvailableSpace, Style};
14#[cfg(any(feature = "std", feature = "alloc"))]
15use crate::sys::Box;
16use crate::sys::{new_vec_with_capacity, ChildrenVec, Vec};
17use crate::{data::NodeData, error};
18
19/// A function type that can be used in a [`MeasureFunc`]
20///
21/// This trait is automatically implemented for all types (including closures) that define a function with the appropriate type signature.
22pub trait Measurable: Send + Sync + Fn(Size<Option<f32>>, Size<AvailableSpace>) -> Size<f32> {}
23impl<F: Send + Sync + Fn(Size<Option<f32>>, Size<AvailableSpace>) -> Size<f32>> Measurable for F {}
24
25/// A function that can be used to compute the intrinsic size of a node
26pub enum MeasureFunc {
27 /// Stores an unboxed function
28 Raw(fn(Size<Option<f32>>, Size<AvailableSpace>) -> Size<f32>),
29
30 /// Stores a boxed function
31 #[cfg(any(feature = "std", feature = "alloc"))]
32 Boxed(Box<dyn Measurable>),
33}
34
35/// Global configuration values for a Taffy instance
36pub(crate) struct TaffyConfig {
37 /// Whether to round layout values
38 pub(crate) use_rounding: bool,
39}
40
41impl Default for TaffyConfig {
42 fn default() -> Self {
43 Self { use_rounding: true }
44 }
45}
46
47/// A tree of UI [`Nodes`](`Node`), suitable for UI layout
48pub struct Taffy {
49 /// The [`NodeData`] for each node stored in this tree
50 pub(crate) nodes: SlotMap<Node, NodeData>,
51
52 /// Functions/closures that compute the intrinsic size of leaf nodes
53 pub(crate) measure_funcs: SparseSecondaryMap<Node, MeasureFunc>,
54
55 /// The children of each node
56 ///
57 /// The indexes in the outer vector correspond to the position of the parent [`NodeData`]
58 pub(crate) children: SlotMap<Node, ChildrenVec<Node>>,
59
60 /// The parents of each node
61 ///
62 /// The indexes in the outer vector correspond to the position of the child [`NodeData`]
63 pub(crate) parents: SlotMap<Node, Option<Node>>,
64
65 /// Layout mode configuration
66 pub(crate) config: TaffyConfig,
67
68 /// Hack to allow the `LayoutTree::layout_mut` function to expose the `NodeData.unrounded_layout` of a node to
69 /// the layout algorithms during layout, while exposing the `NodeData.final_layout` when called by external users.
70 /// This allows us to fix <https://github.com/DioxusLabs/taffy/issues/501> without breaking backwards compatibility
71 pub(crate) is_layouting: bool,
72}
73
74impl Default for Taffy {
75 fn default() -> Self {
76 Taffy::new()
77 }
78}
79
80impl LayoutTree for Taffy {
81 type ChildIter<'a> = core::slice::Iter<'a, DefaultKey>;
82
83 fn children(&self, node: Node) -> Self::ChildIter<'_> {
84 self.children[node].iter()
85 }
86
87 fn child_count(&self, node: Node) -> usize {
88 self.children[node].len()
89 }
90
91 fn is_childless(&self, node: Node) -> bool {
92 self.children[node].is_empty()
93 }
94
95 fn parent(&self, node: Node) -> Option<Node> {
96 self.parents.get(node).copied().flatten()
97 }
98
99 fn style(&self, node: Node) -> &Style {
100 &self.nodes[node].style
101 }
102
103 #[inline(always)]
104 fn layout(&self, node: Node) -> &Layout {
105 if self.is_layouting && self.config.use_rounding {
106 &self.nodes[node].unrounded_layout
107 } else {
108 &self.nodes[node].final_layout
109 }
110 }
111
112 #[inline(always)]
113 fn layout_mut(&mut self, node: Node) -> &mut Layout {
114 if self.is_layouting && self.config.use_rounding {
115 &mut self.nodes[node].unrounded_layout
116 } else {
117 &mut self.nodes[node].final_layout
118 }
119 }
120
121 #[inline(always)]
122 fn mark_dirty(&mut self, node: Node) -> TaffyResult<()> {
123 self.mark_dirty_internal(node)
124 }
125
126 fn measure_node(
127 &self,
128 node: Node,
129 known_dimensions: Size<Option<f32>>,
130 available_space: Size<AvailableSpace>,
131 ) -> Size<f32> {
132 match &self.measure_funcs[node] {
133 MeasureFunc::Raw(measure) => measure(known_dimensions, available_space),
134
135 #[cfg(any(feature = "std", feature = "alloc"))]
136 MeasureFunc::Boxed(measure) => (measure as &dyn Fn(_, _) -> _)(known_dimensions, available_space),
137 }
138 }
139
140 fn needs_measure(&self, node: Node) -> bool {
141 self.nodes[node].needs_measure && self.measure_funcs.get(node).is_some()
142 }
143
144 fn cache_mut(&mut self, node: Node, index: usize) -> &mut Option<Cache> {
145 &mut self.nodes[node].size_cache[index]
146 }
147
148 fn child(&self, node: Node, id: usize) -> Node {
149 self.children[node][id]
150 }
151}
152
153#[allow(clippy::iter_cloned_collect)] // due to no-std support, we need to use `iter_cloned` instead of `collect`
154impl Taffy {
155 /// Creates a new [`Taffy`]
156 ///
157 /// The default capacity of a [`Taffy`] is 16 nodes.
158 #[must_use]
159 pub fn new() -> Self {
160 Self::with_capacity(16)
161 }
162
163 /// Creates a new [`Taffy`] that can store `capacity` nodes before reallocation
164 #[must_use]
165 pub fn with_capacity(capacity: usize) -> Self {
166 Self {
167 // TODO: make this method const upstream,
168 // so constructors here can be const
169 nodes: SlotMap::with_capacity(capacity),
170 children: SlotMap::with_capacity(capacity),
171 parents: SlotMap::with_capacity(capacity),
172 measure_funcs: SparseSecondaryMap::with_capacity(capacity),
173 config: TaffyConfig::default(),
174 is_layouting: false,
175 }
176 }
177
178 /// Enable rounding of layout values. Rounding is enabled by default.
179 pub fn enable_rounding(&mut self) {
180 self.config.use_rounding = true;
181 }
182
183 /// Disable rounding of layout values. Rounding is enabled by default.
184 pub fn disable_rounding(&mut self) {
185 self.config.use_rounding = false;
186 }
187
188 /// Creates and adds a new unattached leaf node to the tree, and returns the [`Node`] of the new node
189 pub fn new_leaf(&mut self, layout: Style) -> TaffyResult<Node> {
190 let id = self.nodes.insert(NodeData::new(layout));
191 let _ = self.children.insert(new_vec_with_capacity(0));
192 let _ = self.parents.insert(None);
193
194 Ok(id)
195 }
196
197 /// Creates and adds a new unattached leaf node to the tree, and returns the [`Node`] of the new node
198 ///
199 /// Creates and adds a new leaf node with a supplied [`MeasureFunc`]
200 pub fn new_leaf_with_measure(&mut self, layout: Style, measure: MeasureFunc) -> TaffyResult<Node> {
201 let mut data = NodeData::new(layout);
202 data.needs_measure = true;
203
204 let id = self.nodes.insert(data);
205 self.measure_funcs.insert(id, measure);
206
207 let _ = self.children.insert(new_vec_with_capacity(0));
208 let _ = self.parents.insert(None);
209
210 Ok(id)
211 }
212
213 /// Creates and adds a new node, which may have any number of `children`
214 pub fn new_with_children(&mut self, layout: Style, children: &[Node]) -> TaffyResult<Node> {
215 let id = self.nodes.insert(NodeData::new(layout));
216
217 for child in children {
218 self.parents[*child] = Some(id);
219 }
220
221 let _ = self.children.insert(children.iter().copied().collect::<_>());
222 let _ = self.parents.insert(None);
223
224 Ok(id)
225 }
226
227 /// Drops all nodes in the tree
228 pub fn clear(&mut self) {
229 self.nodes.clear();
230 self.children.clear();
231 self.parents.clear();
232 }
233
234 /// Remove a specific [`Node`] from the tree and drops it
235 ///
236 /// Returns the id of the node removed.
237 pub fn remove(&mut self, node: Node) -> TaffyResult<Node> {
238 if let Some(parent) = self.parents[node] {
239 if let Some(children) = self.children.get_mut(parent) {
240 children.retain(|f| *f != node);
241 }
242 }
243
244 let _ = self.children.remove(node);
245 let _ = self.parents.remove(node);
246 let _ = self.nodes.remove(node);
247
248 Ok(node)
249 }
250
251 /// Sets the [`MeasureFunc`] of the associated node
252 pub fn set_measure(&mut self, node: Node, measure: Option<MeasureFunc>) -> TaffyResult<()> {
253 if let Some(measure) = measure {
254 self.nodes[node].needs_measure = true;
255 self.measure_funcs.insert(node, measure);
256 } else {
257 self.nodes[node].needs_measure = false;
258 self.measure_funcs.remove(node);
259 }
260
261 self.mark_dirty_internal(node)?;
262
263 Ok(())
264 }
265
266 /// Adds a `child` [`Node`] under the supplied `parent`
267 pub fn add_child(&mut self, parent: Node, child: Node) -> TaffyResult<()> {
268 self.parents[child] = Some(parent);
269 self.children[parent].push(child);
270 self.mark_dirty_internal(parent)?;
271
272 Ok(())
273 }
274
275 /// Directly sets the `children` of the supplied `parent`
276 pub fn set_children(&mut self, parent: Node, children: &[Node]) -> TaffyResult<()> {
277 // Remove node as parent from all its current children.
278 for child in &self.children[parent] {
279 self.parents[*child] = None;
280 }
281
282 // Build up relation node <-> child
283 for child in children {
284 self.parents[*child] = Some(parent);
285 }
286
287 self.children[parent] = children.iter().copied().collect::<_>();
288
289 self.mark_dirty_internal(parent)?;
290
291 Ok(())
292 }
293
294 /// Removes the `child` of the parent `node`
295 ///
296 /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
297 pub fn remove_child(&mut self, parent: Node, child: Node) -> TaffyResult<Node> {
298 let index = self.children[parent].iter().position(|n| *n == child).unwrap();
299 self.remove_child_at_index(parent, index)
300 }
301
302 /// Removes the child at the given `index` from the `parent`
303 ///
304 /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
305 pub fn remove_child_at_index(&mut self, parent: Node, child_index: usize) -> TaffyResult<Node> {
306 let child_count = self.children[parent].len();
307 if child_index >= child_count {
308 return Err(error::TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
309 }
310
311 let child = self.children[parent].remove(child_index);
312 self.parents[child] = None;
313
314 self.mark_dirty_internal(parent)?;
315
316 Ok(child)
317 }
318
319 /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
320 ///
321 /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
322 pub fn replace_child_at_index(&mut self, parent: Node, child_index: usize, new_child: Node) -> TaffyResult<Node> {
323 let child_count = self.children[parent].len();
324 if child_index >= child_count {
325 return Err(error::TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
326 }
327
328 self.parents[new_child] = Some(parent);
329 let old_child = core::mem::replace(&mut self.children[parent][child_index], new_child);
330 self.parents[old_child] = None;
331
332 self.mark_dirty_internal(parent)?;
333
334 Ok(old_child)
335 }
336
337 /// Returns the child [`Node`] of the parent `node` at the provided `child_index`
338 pub fn child_at_index(&self, parent: Node, child_index: usize) -> TaffyResult<Node> {
339 let child_count = self.children[parent].len();
340 if child_index >= child_count {
341 return Err(error::TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
342 }
343
344 Ok(self.children[parent][child_index])
345 }
346
347 /// Returns the number of children of the `parent` [`Node`]
348 pub fn child_count(&self, parent: Node) -> TaffyResult<usize> {
349 Ok(self.children[parent].len())
350 }
351
352 /// Returns a list of children that belong to the parent [`Node`]
353 pub fn children(&self, parent: Node) -> TaffyResult<Vec<Node>> {
354 Ok(self.children[parent].iter().copied().collect::<_>())
355 }
356
357 /// Sets the [`Style`] of the provided `node`
358 pub fn set_style(&mut self, node: Node, style: Style) -> TaffyResult<()> {
359 self.nodes[node].style = style;
360 self.mark_dirty_internal(node)?;
361 Ok(())
362 }
363
364 /// Gets the [`Style`] of the provided `node`
365 pub fn style(&self, node: Node) -> TaffyResult<&Style> {
366 Ok(&self.nodes[node].style)
367 }
368
369 /// Return this node layout relative to its parent
370 pub fn layout(&self, node: Node) -> TaffyResult<&Layout> {
371 Ok(&self.nodes[node].final_layout)
372 }
373
374 /// Marks the layout computation of this node and its children as outdated
375 ///
376 /// Performs a recursive depth-first search up the tree until the root node is reached
377 ///
378 /// WARNING: this will stack-overflow if the tree contains a cycle
379 fn mark_dirty_internal(&mut self, node: Node) -> TaffyResult<()> {
380 /// WARNING: this will stack-overflow if the tree contains a cycle
381 fn mark_dirty_recursive(
382 nodes: &mut SlotMap<Node, NodeData>,
383 parents: &SlotMap<Node, Option<Node>>,
384 node_id: Node,
385 ) {
386 nodes[node_id].mark_dirty();
387
388 if let Some(Some(node)) = parents.get(node_id) {
389 mark_dirty_recursive(nodes, parents, *node);
390 }
391 }
392
393 mark_dirty_recursive(&mut self.nodes, &self.parents, node);
394
395 Ok(())
396 }
397
398 /// Indicates whether the layout of this node (and its children) need to be recomputed
399 pub fn dirty(&self, node: Node) -> TaffyResult<bool> {
400 Ok(self.nodes[node].size_cache.iter().all(|entry| entry.is_none()))
401 }
402
403 /// Updates the stored layout of the provided `node` and its children
404 pub fn compute_layout(&mut self, node: Node, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
405 crate::compute::compute_layout(self, node, available_space)
406 }
407}
408
409#[cfg(test)]
410mod tests {
411 #![allow(clippy::bool_assert_comparison)]
412
413 use super::*;
414 use crate::style::{Dimension, Display, FlexDirection};
415 use crate::style_helpers::*;
416 use crate::sys;
417
418 #[test]
419 fn new_should_allocate_default_capacity() {
420 const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
421 let taffy = Taffy::new();
422
423 assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
424 assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
425 assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
426 }
427
428 #[test]
429 fn test_with_capacity() {
430 const CAPACITY: usize = 8;
431 let taffy = Taffy::with_capacity(CAPACITY);
432
433 assert!(taffy.children.capacity() >= CAPACITY);
434 assert!(taffy.parents.capacity() >= CAPACITY);
435 assert!(taffy.nodes.capacity() >= CAPACITY);
436 }
437
438 #[test]
439 fn test_new_leaf() {
440 let mut taffy = Taffy::new();
441
442 let res = taffy.new_leaf(Style::default());
443 assert!(res.is_ok());
444 let node = res.unwrap();
445
446 // node should be in the taffy tree and have no children
447 assert!(taffy.child_count(node).unwrap() == 0);
448 }
449
450 #[test]
451 fn new_leaf_with_measure() {
452 let mut taffy = Taffy::new();
453
454 let res = taffy.new_leaf_with_measure(Style::default(), MeasureFunc::Raw(|_, _| Size::ZERO));
455 assert!(res.is_ok());
456 let node = res.unwrap();
457
458 // node should be in the taffy tree and have no children
459 assert!(taffy.child_count(node).unwrap() == 0);
460 }
461
462 /// Test that new_with_children works as expected
463 #[test]
464 fn test_new_with_children() {
465 let mut taffy = Taffy::new();
466 let child0 = taffy.new_leaf(Style::default()).unwrap();
467 let child1 = taffy.new_leaf(Style::default()).unwrap();
468 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
469
470 // node should have two children
471 assert_eq!(taffy.child_count(node).unwrap(), 2);
472 assert_eq!(taffy.children(node).unwrap()[0], child0);
473 assert_eq!(taffy.children(node).unwrap()[1], child1);
474 }
475
476 #[test]
477 fn remove_node_should_remove() {
478 let mut taffy = Taffy::new();
479
480 let node = taffy.new_leaf(Style::default()).unwrap();
481
482 let _ = taffy.remove(node).unwrap();
483 }
484
485 #[test]
486 fn remove_node_should_detach_herarchy() {
487 let mut taffy = Taffy::new();
488
489 // Build a linear tree layout: <0> <- <1> <- <2>
490 let node2 = taffy.new_leaf(Style::default()).unwrap();
491 let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
492 let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
493
494 // Both node0 and node1 should have 1 child nodes
495 assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
496 assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
497
498 // Disconnect the tree: <0> <2>
499 let _ = taffy.remove(node1).unwrap();
500
501 // Both remaining nodes should have no child nodes
502 assert!(taffy.children(node0).unwrap().is_empty());
503 assert!(taffy.children(node2).unwrap().is_empty());
504 }
505
506 #[test]
507 fn remove_last_node() {
508 let mut taffy = Taffy::new();
509
510 let parent = taffy.new_leaf(Style::default()).unwrap();
511 let child = taffy.new_leaf(Style::default()).unwrap();
512 taffy.add_child(parent, child).unwrap();
513
514 taffy.remove(child).unwrap();
515 taffy.remove(parent).unwrap();
516 }
517
518 #[test]
519 fn set_measure() {
520 let mut taffy = Taffy::new();
521 let node = taffy
522 .new_leaf_with_measure(Style::default(), MeasureFunc::Raw(|_, _| Size { width: 200.0, height: 200.0 }))
523 .unwrap();
524 taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
525 assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
526
527 taffy.set_measure(node, Some(MeasureFunc::Raw(|_, _| Size { width: 100.0, height: 100.0 }))).unwrap();
528 taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
529 assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
530 }
531
532 #[test]
533 fn set_measure_of_previously_unmeasured_node() {
534 let mut taffy = Taffy::new();
535 let node = taffy.new_leaf(Style::default()).unwrap();
536 taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
537 assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
538
539 taffy.set_measure(node, Some(MeasureFunc::Raw(|_, _| Size { width: 100.0, height: 100.0 }))).unwrap();
540 taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
541 assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
542 }
543
544 /// Test that adding `add_child()` works
545 #[test]
546 fn add_child() {
547 let mut taffy = Taffy::new();
548 let node = taffy.new_leaf(Style::default()).unwrap();
549 assert_eq!(taffy.child_count(node).unwrap(), 0);
550
551 let child0 = taffy.new_leaf(Style::default()).unwrap();
552 taffy.add_child(node, child0).unwrap();
553 assert_eq!(taffy.child_count(node).unwrap(), 1);
554
555 let child1 = taffy.new_leaf(Style::default()).unwrap();
556 taffy.add_child(node, child1).unwrap();
557 assert_eq!(taffy.child_count(node).unwrap(), 2);
558 }
559
560 #[test]
561 fn set_children() {
562 let mut taffy = Taffy::new();
563
564 let child0 = taffy.new_leaf(Style::default()).unwrap();
565 let child1 = taffy.new_leaf(Style::default()).unwrap();
566 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
567
568 assert_eq!(taffy.child_count(node).unwrap(), 2);
569 assert_eq!(taffy.children(node).unwrap()[0], child0);
570 assert_eq!(taffy.children(node).unwrap()[1], child1);
571
572 let child2 = taffy.new_leaf(Style::default()).unwrap();
573 let child3 = taffy.new_leaf(Style::default()).unwrap();
574 taffy.set_children(node, &[child2, child3]).unwrap();
575
576 assert_eq!(taffy.child_count(node).unwrap(), 2);
577 assert_eq!(taffy.children(node).unwrap()[0], child2);
578 assert_eq!(taffy.children(node).unwrap()[1], child3);
579 }
580
581 /// Test that removing a child works
582 #[test]
583 fn remove_child() {
584 let mut taffy = Taffy::new();
585 let child0 = taffy.new_leaf(Style::default()).unwrap();
586 let child1 = taffy.new_leaf(Style::default()).unwrap();
587 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
588
589 assert_eq!(taffy.child_count(node).unwrap(), 2);
590
591 taffy.remove_child(node, child0).unwrap();
592 assert_eq!(taffy.child_count(node).unwrap(), 1);
593 assert_eq!(taffy.children(node).unwrap()[0], child1);
594
595 taffy.remove_child(node, child1).unwrap();
596 assert_eq!(taffy.child_count(node).unwrap(), 0);
597 }
598
599 #[test]
600 fn remove_child_at_index() {
601 let mut taffy = Taffy::new();
602 let child0 = taffy.new_leaf(Style::default()).unwrap();
603 let child1 = taffy.new_leaf(Style::default()).unwrap();
604 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
605
606 assert_eq!(taffy.child_count(node).unwrap(), 2);
607
608 taffy.remove_child_at_index(node, 0).unwrap();
609 assert_eq!(taffy.child_count(node).unwrap(), 1);
610 assert_eq!(taffy.children(node).unwrap()[0], child1);
611
612 taffy.remove_child_at_index(node, 0).unwrap();
613 assert_eq!(taffy.child_count(node).unwrap(), 0);
614 }
615
616 #[test]
617 fn replace_child_at_index() {
618 let mut taffy = Taffy::new();
619
620 let child0 = taffy.new_leaf(Style::default()).unwrap();
621 let child1 = taffy.new_leaf(Style::default()).unwrap();
622
623 let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
624 assert_eq!(taffy.child_count(node).unwrap(), 1);
625 assert_eq!(taffy.children(node).unwrap()[0], child0);
626
627 taffy.replace_child_at_index(node, 0, child1).unwrap();
628 assert_eq!(taffy.child_count(node).unwrap(), 1);
629 assert_eq!(taffy.children(node).unwrap()[0], child1);
630 }
631 #[test]
632 fn test_child_at_index() {
633 let mut taffy = Taffy::new();
634 let child0 = taffy.new_leaf(Style::default()).unwrap();
635 let child1 = taffy.new_leaf(Style::default()).unwrap();
636 let child2 = taffy.new_leaf(Style::default()).unwrap();
637 let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
638
639 assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
640 assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
641 assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
642 }
643 #[test]
644 fn test_child_count() {
645 let mut taffy = Taffy::new();
646 let child0 = taffy.new_leaf(Style::default()).unwrap();
647 let child1 = taffy.new_leaf(Style::default()).unwrap();
648 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
649
650 assert!(if let Ok(count) = taffy.child_count(node) { count == 2 } else { false });
651 assert!(if let Ok(count) = taffy.child_count(child0) { count == 0 } else { false });
652 assert!(if let Ok(count) = taffy.child_count(child1) { count == 0 } else { false });
653 }
654
655 #[allow(clippy::vec_init_then_push)]
656 #[test]
657 fn test_children() {
658 let mut taffy = Taffy::new();
659 let child0 = taffy.new_leaf(Style::default()).unwrap();
660 let child1 = taffy.new_leaf(Style::default()).unwrap();
661 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
662
663 let mut children: sys::Vec<Node> = sys::Vec::new();
664 children.push(child0);
665 children.push(child1);
666
667 let children_result = taffy.children(node).unwrap();
668 assert_eq!(children_result, children);
669
670 assert!(taffy.children(child0).unwrap().is_empty());
671 }
672 #[test]
673 fn test_set_style() {
674 let mut taffy = Taffy::new();
675
676 let node = taffy.new_leaf(Style::default()).unwrap();
677 assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
678
679 taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
680 assert_eq!(taffy.style(node).unwrap().display, Display::None);
681 }
682 #[test]
683 fn test_style() {
684 let mut taffy = Taffy::new();
685
686 let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
687
688 let node = taffy.new_leaf(style.clone()).unwrap();
689
690 let res = taffy.style(node);
691 assert!(res.is_ok());
692 assert!(res.unwrap() == &style);
693 }
694 #[test]
695 fn test_layout() {
696 let mut taffy = Taffy::new();
697 let node = taffy.new_leaf(Style::default()).unwrap();
698
699 // TODO: Improve this test?
700 let res = taffy.layout(node);
701 assert!(res.is_ok());
702 }
703
704 #[test]
705 fn test_mark_dirty() {
706 let mut taffy = Taffy::new();
707 let child0 = taffy.new_leaf(Style::default()).unwrap();
708 let child1 = taffy.new_leaf(Style::default()).unwrap();
709 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
710
711 taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
712
713 assert_eq!(taffy.dirty(child0).unwrap(), false);
714 assert_eq!(taffy.dirty(child1).unwrap(), false);
715 assert_eq!(taffy.dirty(node).unwrap(), false);
716
717 taffy.mark_dirty(node).unwrap();
718 assert_eq!(taffy.dirty(child0).unwrap(), false);
719 assert_eq!(taffy.dirty(child1).unwrap(), false);
720 assert_eq!(taffy.dirty(node).unwrap(), true);
721
722 taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
723 taffy.mark_dirty(child0).unwrap();
724 assert_eq!(taffy.dirty(child0).unwrap(), true);
725 assert_eq!(taffy.dirty(child1).unwrap(), false);
726 assert_eq!(taffy.dirty(node).unwrap(), true);
727 }
728
729 #[test]
730 fn compute_layout_should_produce_valid_result() {
731 let mut taffy = Taffy::new();
732 let node_result = taffy.new_leaf(Style {
733 size: Size { width: Dimension::Points(10f32), height: Dimension::Points(10f32) },
734 ..Default::default()
735 });
736 assert!(node_result.is_ok());
737 let node = node_result.unwrap();
738 let layout_result = taffy.compute_layout(
739 node,
740 Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
741 );
742 assert!(layout_result.is_ok());
743 }
744
745 #[test]
746 fn measure_func_is_send_and_sync() {
747 fn is_send_and_sync<T: Send + Sync>() {}
748 is_send_and_sync::<MeasureFunc>();
749 }
750}