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