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