TaffyTree::set_children: Remove from previous parent (#749)
1//! Contains [TaffyTree](crate::tree::TaffyTree): the default implementation of [LayoutTree](crate::tree::LayoutTree), and the error type for Taffy.
2#[cfg(not(feature = "std"))]
3use slotmap::SecondaryMap;
4#[cfg(feature = "std")]
5use slotmap::SparseSecondaryMap as SecondaryMap;
6use slotmap::{DefaultKey, SlotMap};
7
8use crate::geometry::Size;
9use crate::style::{AvailableSpace, Display, Style};
10use crate::tree::{
11 Cache, Layout, LayoutInput, LayoutOutput, LayoutPartialTree, NodeId, PrintTree, RoundTree, RunMode,
12 TraversePartialTree, TraverseTree,
13};
14use crate::util::debug::{debug_log, debug_log_node};
15use crate::util::sys::{new_vec_with_capacity, ChildrenVec, Vec};
16
17use crate::compute::{
18 compute_cached_layout, compute_hidden_layout, compute_leaf_layout, compute_root_layout, round_layout,
19};
20#[cfg(feature = "block_layout")]
21use crate::{compute::compute_block_layout, LayoutBlockContainer};
22#[cfg(feature = "flexbox")]
23use crate::{compute::compute_flexbox_layout, LayoutFlexboxContainer};
24#[cfg(feature = "grid")]
25use crate::{compute::compute_grid_layout, LayoutGridContainer};
26
27/// The error Taffy generates on invalid operations
28pub type TaffyResult<T> = Result<T, TaffyError>;
29
30/// An error that occurs while trying to access or modify a node's children by index.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum TaffyError {
33 /// The parent node does not have a child at `child_index`. It only has `child_count` children
34 ChildIndexOutOfBounds {
35 /// The parent node whose child was being looked up
36 parent: NodeId,
37 /// The index that was looked up
38 child_index: usize,
39 /// The total number of children the parent has
40 child_count: usize,
41 },
42 /// The parent node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
43 InvalidParentNode(NodeId),
44 /// The child node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
45 InvalidChildNode(NodeId),
46 /// The supplied node was not found in the [`TaffyTree`](crate::TaffyTree) instance.
47 InvalidInputNode(NodeId),
48}
49
50impl core::fmt::Display for TaffyError {
51 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
52 match self {
53 TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count } => {
54 write!(f, "Index (is {child_index}) should be < child_count ({child_count}) for parent node {parent:?}")
55 }
56 TaffyError::InvalidParentNode(parent) => {
57 write!(f, "Parent Node {parent:?} is not in the TaffyTree instance")
58 }
59 TaffyError::InvalidChildNode(child) => write!(f, "Child Node {child:?} is not in the TaffyTree instance"),
60 TaffyError::InvalidInputNode(node) => write!(f, "Supplied Node {node:?} is not in the TaffyTree instance"),
61 }
62 }
63}
64
65#[cfg(feature = "std")]
66impl std::error::Error for TaffyError {}
67
68/// Global configuration values for a TaffyTree instance
69#[derive(Debug, Clone, Copy)]
70pub(crate) struct TaffyConfig {
71 /// Whether to round layout values
72 pub(crate) use_rounding: bool,
73}
74
75impl Default for TaffyConfig {
76 fn default() -> Self {
77 Self { use_rounding: true }
78 }
79}
80
81/// Layout information for a given [`Node`](crate::node::Node)
82///
83/// Stored in a [`TaffyTree`].
84#[derive(Debug, Clone, PartialEq)]
85struct NodeData {
86 /// The layout strategy used by this node
87 pub(crate) style: Style,
88
89 /// The always unrounded results of the layout computation. We must store this separately from the rounded
90 /// layout to avoid errors from rounding already-rounded values. See <https://github.com/DioxusLabs/taffy/issues/501>.
91 pub(crate) unrounded_layout: Layout,
92
93 /// The final results of the layout computation.
94 /// These may be rounded or unrounded depending on what the `use_rounding` config setting is set to.
95 pub(crate) final_layout: Layout,
96
97 /// Whether the node has context data associated with it or not
98 pub(crate) has_context: bool,
99
100 /// The cached results of the layout computation
101 pub(crate) cache: Cache,
102}
103
104impl NodeData {
105 /// Create the data for a new node
106 #[must_use]
107 pub const fn new(style: Style) -> Self {
108 Self {
109 style,
110 cache: Cache::new(),
111 unrounded_layout: Layout::new(),
112 final_layout: Layout::new(),
113 has_context: false,
114 }
115 }
116
117 /// Marks a node and all of its ancestors as requiring relayout
118 ///
119 /// This clears any cached data and signals that the data must be recomputed.
120 #[inline]
121 pub fn mark_dirty(&mut self) {
122 self.cache.clear()
123 }
124}
125
126/// An entire tree of UI nodes. The entry point to Taffy's high-level API.
127///
128/// Allows you to build a tree of UI nodes, run Taffy's layout algorithms over that tree, and then access the resultant layout.]
129#[derive(Debug, Clone)]
130pub struct TaffyTree<NodeContext = ()> {
131 /// The [`NodeData`] for each node stored in this tree
132 nodes: SlotMap<DefaultKey, NodeData>,
133
134 /// Functions/closures that compute the intrinsic size of leaf nodes
135 node_context_data: SecondaryMap<DefaultKey, NodeContext>,
136
137 /// The children of each node
138 ///
139 /// The indexes in the outer vector correspond to the position of the parent [`NodeData`]
140 children: SlotMap<DefaultKey, ChildrenVec<NodeId>>,
141
142 /// The parents of each node
143 ///
144 /// The indexes in the outer vector correspond to the position of the child [`NodeData`]
145 parents: SlotMap<DefaultKey, Option<NodeId>>,
146
147 /// Layout mode configuration
148 config: TaffyConfig,
149}
150
151impl Default for TaffyTree {
152 fn default() -> TaffyTree<()> {
153 TaffyTree::new()
154 }
155}
156
157/// Iterator that wraps a slice of nodes, lazily converting them to u64
158pub struct TaffyTreeChildIter<'a>(core::slice::Iter<'a, NodeId>);
159impl Iterator for TaffyTreeChildIter<'_> {
160 type Item = NodeId;
161
162 fn next(&mut self) -> Option<Self::Item> {
163 self.0.next().copied()
164 }
165}
166
167// TraversePartialTree impl for TaffyTree
168impl<NodeContext> TraversePartialTree for TaffyTree<NodeContext> {
169 type ChildIter<'a>
170 = TaffyTreeChildIter<'a>
171 where
172 Self: 'a;
173
174 #[inline(always)]
175 fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
176 TaffyTreeChildIter(self.children[parent_node_id.into()].iter())
177 }
178
179 #[inline(always)]
180 fn child_count(&self, parent_node_id: NodeId) -> usize {
181 self.children[parent_node_id.into()].len()
182 }
183
184 #[inline(always)]
185 fn get_child_id(&self, parent_node_id: NodeId, id: usize) -> NodeId {
186 self.children[parent_node_id.into()][id]
187 }
188}
189
190// TraverseTree impl for TaffyTree
191impl<NodeContext> TraverseTree for TaffyTree<NodeContext> {}
192
193// PrintTree impl for TaffyTree
194impl<NodeContext> PrintTree for TaffyTree<NodeContext> {
195 #[inline(always)]
196 fn get_debug_label(&self, node_id: NodeId) -> &'static str {
197 let node = &self.nodes[node_id.into()];
198 let display = node.style.display;
199 let num_children = self.child_count(node_id);
200
201 match (num_children, display) {
202 (_, Display::None) => "NONE",
203 (0, _) => "LEAF",
204 #[cfg(feature = "block_layout")]
205 (_, Display::Block) => "BLOCK",
206 #[cfg(feature = "flexbox")]
207 (_, Display::Flex) => {
208 use crate::FlexDirection;
209 match node.style.flex_direction {
210 FlexDirection::Row | FlexDirection::RowReverse => "FLEX ROW",
211 FlexDirection::Column | FlexDirection::ColumnReverse => "FLEX COL",
212 }
213 }
214 #[cfg(feature = "grid")]
215 (_, Display::Grid) => "GRID",
216 }
217 }
218
219 #[inline(always)]
220 fn get_final_layout(&self, node_id: NodeId) -> &Layout {
221 if self.config.use_rounding {
222 &self.nodes[node_id.into()].final_layout
223 } else {
224 &self.nodes[node_id.into()].unrounded_layout
225 }
226 }
227}
228
229/// View over the Taffy tree that holds the tree itself along with a reference to the context
230/// and implements LayoutTree. This allows the context to be stored outside of the TaffyTree struct
231/// which makes the lifetimes of the context much more flexible.
232pub(crate) struct TaffyView<'t, NodeContext, MeasureFunction>
233where
234 MeasureFunction:
235 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
236{
237 /// A reference to the TaffyTree
238 pub(crate) taffy: &'t mut TaffyTree<NodeContext>,
239 /// The context provided for passing to measure functions if layout is run over this struct
240 pub(crate) measure_function: MeasureFunction,
241}
242
243// TraversePartialTree impl for TaffyView
244impl<NodeContext, MeasureFunction> TraversePartialTree for TaffyView<'_, NodeContext, MeasureFunction>
245where
246 MeasureFunction:
247 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
248{
249 type ChildIter<'a>
250 = TaffyTreeChildIter<'a>
251 where
252 Self: 'a;
253
254 #[inline(always)]
255 fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
256 self.taffy.child_ids(parent_node_id)
257 }
258
259 #[inline(always)]
260 fn child_count(&self, parent_node_id: NodeId) -> usize {
261 self.taffy.child_count(parent_node_id)
262 }
263
264 #[inline(always)]
265 fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId {
266 self.taffy.get_child_id(parent_node_id, child_index)
267 }
268}
269
270// TraverseTree impl for TaffyView
271impl<NodeContext, MeasureFunction> TraverseTree for TaffyView<'_, NodeContext, MeasureFunction> where
272 MeasureFunction:
273 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>
274{
275}
276
277// LayoutPartialTree impl for TaffyView
278impl<NodeContext, MeasureFunction> LayoutPartialTree for TaffyView<'_, NodeContext, MeasureFunction>
279where
280 MeasureFunction:
281 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
282{
283 type CoreContainerStyle<'a>
284 = &'a Style
285 where
286 Self: 'a;
287 type CacheMut<'b>
288 = &'b mut Cache
289 where
290 Self: 'b;
291
292 #[inline(always)]
293 fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
294 &self.taffy.nodes[node_id.into()].style
295 }
296
297 #[inline(always)]
298 fn get_cache_mut(&mut self, node: NodeId) -> &mut Cache {
299 &mut self.taffy.nodes[node.into()].cache
300 }
301
302 #[inline(always)]
303 fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
304 self.taffy.nodes[node_id.into()].unrounded_layout = *layout;
305 }
306
307 #[inline(always)]
308 fn compute_child_layout(&mut self, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
309 // If RunMode is PerformHiddenLayout then this indicates that an ancestor node is `Display::None`
310 // and thus that we should lay out this node using hidden layout regardless of it's own display style.
311 if inputs.run_mode == RunMode::PerformHiddenLayout {
312 debug_log!("HIDDEN");
313 return compute_hidden_layout(self, node);
314 }
315
316 // We run the following wrapped in "compute_cached_layout", which will check the cache for an entry matching the node and inputs and:
317 // - Return that entry if exists
318 // - Else call the passed closure (below) to compute the result
319 //
320 // If there was no cache match and a new result needs to be computed then that result will be added to the cache
321 compute_cached_layout(self, node, inputs, |tree, node, inputs| {
322 let display_mode = tree.taffy.nodes[node.into()].style.display;
323 let has_children = tree.child_count(node) > 0;
324
325 debug_log!(display_mode);
326 debug_log_node!(
327 inputs.known_dimensions,
328 inputs.parent_size,
329 inputs.available_space,
330 inputs.run_mode,
331 inputs.sizing_mode
332 );
333
334 // Dispatch to a layout algorithm based on the node's display style and whether the node has children or not.
335 match (display_mode, has_children) {
336 (Display::None, _) => compute_hidden_layout(tree, node),
337 #[cfg(feature = "block_layout")]
338 (Display::Block, true) => compute_block_layout(tree, node, inputs),
339 #[cfg(feature = "flexbox")]
340 (Display::Flex, true) => compute_flexbox_layout(tree, node, inputs),
341 #[cfg(feature = "grid")]
342 (Display::Grid, true) => compute_grid_layout(tree, node, inputs),
343 (_, false) => {
344 let node_key = node.into();
345 let style = &tree.taffy.nodes[node_key].style;
346 let has_context = tree.taffy.nodes[node_key].has_context;
347 let node_context = has_context.then(|| tree.taffy.node_context_data.get_mut(node_key)).flatten();
348 let measure_function = |known_dimensions, available_space| {
349 (tree.measure_function)(known_dimensions, available_space, node, node_context, style)
350 };
351 compute_leaf_layout(inputs, style, measure_function)
352 }
353 }
354 })
355 }
356}
357
358#[cfg(feature = "block_layout")]
359impl<NodeContext, MeasureFunction> LayoutBlockContainer for TaffyView<'_, NodeContext, MeasureFunction>
360where
361 MeasureFunction:
362 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
363{
364 type BlockContainerStyle<'a>
365 = &'a Style
366 where
367 Self: 'a;
368 type BlockItemStyle<'a>
369 = &'a Style
370 where
371 Self: 'a;
372
373 #[inline(always)]
374 fn get_block_container_style(&self, node_id: NodeId) -> Self::BlockContainerStyle<'_> {
375 self.get_core_container_style(node_id)
376 }
377
378 #[inline(always)]
379 fn get_block_child_style(&self, child_node_id: NodeId) -> Self::BlockItemStyle<'_> {
380 self.get_core_container_style(child_node_id)
381 }
382}
383
384#[cfg(feature = "flexbox")]
385impl<NodeContext, MeasureFunction> LayoutFlexboxContainer for TaffyView<'_, NodeContext, MeasureFunction>
386where
387 MeasureFunction:
388 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
389{
390 type FlexboxContainerStyle<'a>
391 = &'a Style
392 where
393 Self: 'a;
394 type FlexboxItemStyle<'a>
395 = &'a Style
396 where
397 Self: 'a;
398
399 #[inline(always)]
400 fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
401 &self.taffy.nodes[node_id.into()].style
402 }
403
404 #[inline(always)]
405 fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
406 &self.taffy.nodes[child_node_id.into()].style
407 }
408}
409
410#[cfg(feature = "grid")]
411impl<NodeContext, MeasureFunction> LayoutGridContainer for TaffyView<'_, NodeContext, MeasureFunction>
412where
413 MeasureFunction:
414 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
415{
416 type GridContainerStyle<'a>
417 = &'a Style
418 where
419 Self: 'a;
420 type GridItemStyle<'a>
421 = &'a Style
422 where
423 Self: 'a;
424
425 #[inline(always)]
426 fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
427 &self.taffy.nodes[node_id.into()].style
428 }
429
430 #[inline(always)]
431 fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
432 &self.taffy.nodes[child_node_id.into()].style
433 }
434}
435
436// RoundTree impl for TaffyView
437impl<NodeContext, MeasureFunction> RoundTree for TaffyView<'_, NodeContext, MeasureFunction>
438where
439 MeasureFunction:
440 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
441{
442 #[inline(always)]
443 fn get_unrounded_layout(&self, node: NodeId) -> &Layout {
444 &self.taffy.nodes[node.into()].unrounded_layout
445 }
446
447 #[inline(always)]
448 fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
449 self.taffy.nodes[node_id.into()].final_layout = *layout;
450 }
451}
452
453#[allow(clippy::iter_cloned_collect)] // due to no-std support, we need to use `iter_cloned` instead of `collect`
454impl<NodeContext> TaffyTree<NodeContext> {
455 /// Creates a new [`TaffyTree`]
456 ///
457 /// The default capacity of a [`TaffyTree`] is 16 nodes.
458 #[must_use]
459 pub fn new() -> Self {
460 Self::with_capacity(16)
461 }
462
463 /// Creates a new [`TaffyTree`] that can store `capacity` nodes before reallocation
464 #[must_use]
465 pub fn with_capacity(capacity: usize) -> Self {
466 TaffyTree {
467 // TODO: make this method const upstream,
468 // so constructors here can be const
469 nodes: SlotMap::with_capacity(capacity),
470 children: SlotMap::with_capacity(capacity),
471 parents: SlotMap::with_capacity(capacity),
472 node_context_data: SecondaryMap::with_capacity(capacity),
473 config: TaffyConfig::default(),
474 }
475 }
476
477 /// Enable rounding of layout values. Rounding is enabled by default.
478 pub fn enable_rounding(&mut self) {
479 self.config.use_rounding = true;
480 }
481
482 /// Disable rounding of layout values. Rounding is enabled by default.
483 pub fn disable_rounding(&mut self) {
484 self.config.use_rounding = false;
485 }
486
487 /// Creates and adds a new unattached leaf node to the tree, and returns the node of the new node
488 pub fn new_leaf(&mut self, layout: Style) -> TaffyResult<NodeId> {
489 let id = self.nodes.insert(NodeData::new(layout));
490 let _ = self.children.insert(new_vec_with_capacity(0));
491 let _ = self.parents.insert(None);
492
493 Ok(id.into())
494 }
495
496 /// Creates and adds a new unattached leaf node to the tree, and returns the [`NodeId`] of the new node
497 ///
498 /// Creates and adds a new leaf node with a supplied context
499 pub fn new_leaf_with_context(&mut self, layout: Style, context: NodeContext) -> TaffyResult<NodeId> {
500 let mut data = NodeData::new(layout);
501 data.has_context = true;
502
503 let id = self.nodes.insert(data);
504 self.node_context_data.insert(id, context);
505
506 let _ = self.children.insert(new_vec_with_capacity(0));
507 let _ = self.parents.insert(None);
508
509 Ok(id.into())
510 }
511
512 /// Creates and adds a new node, which may have any number of `children`
513 pub fn new_with_children(&mut self, layout: Style, children: &[NodeId]) -> TaffyResult<NodeId> {
514 let id = NodeId::from(self.nodes.insert(NodeData::new(layout)));
515
516 for child in children {
517 self.parents[(*child).into()] = Some(id);
518 }
519
520 let _ = self.children.insert(children.iter().copied().collect::<_>());
521 let _ = self.parents.insert(None);
522
523 Ok(id)
524 }
525
526 /// Drops all nodes in the tree
527 pub fn clear(&mut self) {
528 self.nodes.clear();
529 self.children.clear();
530 self.parents.clear();
531 }
532
533 /// Remove a specific node from the tree and drop it
534 ///
535 /// Returns the id of the node removed.
536 pub fn remove(&mut self, node: NodeId) -> TaffyResult<NodeId> {
537 let key = node.into();
538 if let Some(parent) = self.parents[key] {
539 if let Some(children) = self.children.get_mut(parent.into()) {
540 children.retain(|f| *f != node);
541 }
542 }
543
544 // Remove "parent" references to a node when removing that node
545 if let Some(children) = self.children.get(key) {
546 for child in children.iter().copied() {
547 self.parents[child.into()] = None;
548 }
549 }
550
551 let _ = self.children.remove(key);
552 let _ = self.parents.remove(key);
553 let _ = self.nodes.remove(key);
554
555 Ok(node)
556 }
557
558 /// Sets the context data associated with the node
559 pub fn set_node_context(&mut self, node: NodeId, measure: Option<NodeContext>) -> TaffyResult<()> {
560 let key = node.into();
561 if let Some(measure) = measure {
562 self.nodes[key].has_context = true;
563 self.node_context_data.insert(key, measure);
564 } else {
565 self.nodes[key].has_context = false;
566 self.node_context_data.remove(key);
567 }
568
569 self.mark_dirty(node)?;
570
571 Ok(())
572 }
573
574 /// Gets a reference to the the context data associated with the node
575 pub fn get_node_context(&self, node: NodeId) -> Option<&NodeContext> {
576 self.node_context_data.get(node.into())
577 }
578
579 /// Gets a mutable reference to the the context data associated with the node
580 pub fn get_node_context_mut(&mut self, node: NodeId) -> Option<&mut NodeContext> {
581 self.node_context_data.get_mut(node.into())
582 }
583
584 /// Gets mutable references to the the context data associated with the nodes. All keys must be valid and disjoint, otherwise None is returned.
585 pub fn get_disjoint_node_context_mut<const N: usize>(
586 &mut self,
587 keys: [NodeId; N],
588 ) -> Option<[&mut NodeContext; N]> {
589 self.node_context_data.get_disjoint_mut(keys.map(|k| k.into()))
590 }
591
592 /// Adds a `child` node under the supplied `parent`
593 pub fn add_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<()> {
594 let parent_key = parent.into();
595 let child_key = child.into();
596 self.parents[child_key] = Some(parent);
597 self.children[parent_key].push(child);
598 self.mark_dirty(parent)?;
599
600 Ok(())
601 }
602
603 /// Inserts a `child` node at the given `child_index` under the supplied `parent`, shifting all children after it to the right.
604 pub fn insert_child_at_index(&mut self, parent: NodeId, child_index: usize, child: NodeId) -> TaffyResult<()> {
605 let parent_key = parent.into();
606
607 let child_count = self.children[parent_key].len();
608 if child_index > child_count {
609 return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
610 }
611
612 self.parents[child.into()] = Some(parent);
613 self.children[parent_key].insert(child_index, child);
614 self.mark_dirty(parent)?;
615
616 Ok(())
617 }
618
619 /// Directly sets the `children` of the supplied `parent`
620 pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) -> TaffyResult<()> {
621 let parent_key = parent.into();
622
623 // Remove node as parent from all its current children.
624 for child in &self.children[parent_key] {
625 self.parents[(*child).into()] = None;
626 }
627
628 // Build up relation node <-> child
629 for &child in children {
630 // Remove child from previous parent
631 if let Some(previous_parent) = self.parents[child.into()] {
632 self.remove_child(previous_parent, child).unwrap();
633 }
634 self.parents[child.into()] = Some(parent);
635 }
636
637 let parent_children = &mut self.children[parent_key];
638 parent_children.clear();
639 children.iter().for_each(|child| parent_children.push(*child));
640
641 self.mark_dirty(parent)?;
642
643 Ok(())
644 }
645
646 /// Removes the `child` of the parent `node`
647 ///
648 /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
649 pub fn remove_child(&mut self, parent: NodeId, child: NodeId) -> TaffyResult<NodeId> {
650 let index = self.children[parent.into()].iter().position(|n| *n == child).unwrap();
651 self.remove_child_at_index(parent, index)
652 }
653
654 /// Removes the child at the given `index` from the `parent`
655 ///
656 /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
657 pub fn remove_child_at_index(&mut self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
658 let parent_key = parent.into();
659 let child_count = self.children[parent_key].len();
660 if child_index >= child_count {
661 return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
662 }
663
664 let child = self.children[parent_key].remove(child_index);
665 self.parents[child.into()] = None;
666
667 self.mark_dirty(parent)?;
668
669 Ok(child)
670 }
671
672 /// Replaces the child at the given `child_index` from the `parent` node with the new `child` node
673 ///
674 /// The child is not removed from the tree entirely, it is simply no longer attached to its previous parent.
675 pub fn replace_child_at_index(
676 &mut self,
677 parent: NodeId,
678 child_index: usize,
679 new_child: NodeId,
680 ) -> TaffyResult<NodeId> {
681 let parent_key = parent.into();
682
683 let child_count = self.children[parent_key].len();
684 if child_index >= child_count {
685 return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
686 }
687
688 self.parents[new_child.into()] = Some(parent);
689 let old_child = core::mem::replace(&mut self.children[parent_key][child_index], new_child);
690 self.parents[old_child.into()] = None;
691
692 self.mark_dirty(parent)?;
693
694 Ok(old_child)
695 }
696
697 /// Returns the child node of the parent `node` at the provided `child_index`
698 pub fn child_at_index(&self, parent: NodeId, child_index: usize) -> TaffyResult<NodeId> {
699 let parent_key = parent.into();
700 let child_count = self.children[parent_key].len();
701 if child_index >= child_count {
702 return Err(TaffyError::ChildIndexOutOfBounds { parent, child_index, child_count });
703 }
704
705 Ok(self.children[parent_key][child_index])
706 }
707
708 /// Returns the total number of nodes in the tree
709 pub fn total_node_count(&self) -> usize {
710 self.nodes.len()
711 }
712
713 /// Returns the `NodeId` of the parent node of the specified node (if it exists)
714 ///
715 /// - Return None if the specified node has no parent
716 /// - Panics if the specified node does not exist
717 pub fn parent(&self, child_id: NodeId) -> Option<NodeId> {
718 self.parents[child_id.into()]
719 }
720
721 /// Returns a list of children that belong to the parent node
722 pub fn children(&self, parent: NodeId) -> TaffyResult<Vec<NodeId>> {
723 Ok(self.children[parent.into()].iter().copied().collect::<_>())
724 }
725
726 /// Sets the [`Style`] of the provided `node`
727 pub fn set_style(&mut self, node: NodeId, style: Style) -> TaffyResult<()> {
728 self.nodes[node.into()].style = style;
729 self.mark_dirty(node)?;
730 Ok(())
731 }
732
733 /// Gets the [`Style`] of the provided `node`
734 pub fn style(&self, node: NodeId) -> TaffyResult<&Style> {
735 Ok(&self.nodes[node.into()].style)
736 }
737
738 /// Return this node layout relative to its parent
739 pub fn layout(&self, node: NodeId) -> TaffyResult<&Layout> {
740 if self.config.use_rounding {
741 Ok(&self.nodes[node.into()].final_layout)
742 } else {
743 Ok(&self.nodes[node.into()].unrounded_layout)
744 }
745 }
746
747 /// Marks the layout of this node and its ancestors as outdated
748 ///
749 /// WARNING: this may stack-overflow if the tree contains a cycle
750 pub fn mark_dirty(&mut self, node: NodeId) -> TaffyResult<()> {
751 /// WARNING: this will stack-overflow if the tree contains a cycle
752 fn mark_dirty_recursive(
753 nodes: &mut SlotMap<DefaultKey, NodeData>,
754 parents: &SlotMap<DefaultKey, Option<NodeId>>,
755 node_key: DefaultKey,
756 ) {
757 nodes[node_key].mark_dirty();
758
759 if let Some(Some(node)) = parents.get(node_key) {
760 mark_dirty_recursive(nodes, parents, (*node).into());
761 }
762 }
763
764 mark_dirty_recursive(&mut self.nodes, &self.parents, node.into());
765
766 Ok(())
767 }
768
769 /// Indicates whether the layout of this node needs to be recomputed
770 pub fn dirty(&self, node: NodeId) -> TaffyResult<bool> {
771 Ok(self.nodes[node.into()].cache.is_empty())
772 }
773
774 /// Updates the stored layout of the provided `node` and its children
775 pub fn compute_layout_with_measure<MeasureFunction>(
776 &mut self,
777 node_id: NodeId,
778 available_space: Size<AvailableSpace>,
779 measure_function: MeasureFunction,
780 ) -> Result<(), TaffyError>
781 where
782 MeasureFunction:
783 FnMut(Size<Option<f32>>, Size<AvailableSpace>, NodeId, Option<&mut NodeContext>, &Style) -> Size<f32>,
784 {
785 let use_rounding = self.config.use_rounding;
786 let mut taffy_view = TaffyView { taffy: self, measure_function };
787 compute_root_layout(&mut taffy_view, node_id, available_space);
788 if use_rounding {
789 round_layout(&mut taffy_view, node_id);
790 }
791 Ok(())
792 }
793
794 /// Updates the stored layout of the provided `node` and its children
795 pub fn compute_layout(&mut self, node: NodeId, available_space: Size<AvailableSpace>) -> Result<(), TaffyError> {
796 self.compute_layout_with_measure(node, available_space, |_, _, _, _, _| Size::ZERO)
797 }
798
799 /// Prints a debug representation of the tree's layout
800 #[cfg(feature = "std")]
801 pub fn print_tree(&mut self, root: NodeId) {
802 crate::util::print_tree(self, root)
803 }
804
805 /// Returns an instance of LayoutTree representing the TaffyTree
806 #[cfg(test)]
807 pub(crate) fn as_layout_tree(&mut self) -> impl LayoutPartialTree + '_ {
808 TaffyView { taffy: self, measure_function: |_, _, _, _, _| Size::ZERO }
809 }
810}
811
812#[cfg(test)]
813mod tests {
814
815 use super::*;
816 use crate::style::{Dimension, Display, FlexDirection};
817 use crate::style_helpers::*;
818 use crate::util::sys;
819
820 fn size_measure_function(
821 known_dimensions: Size<Option<f32>>,
822 _available_space: Size<AvailableSpace>,
823 _node_id: NodeId,
824 node_context: Option<&mut Size<f32>>,
825 _style: &Style,
826 ) -> Size<f32> {
827 known_dimensions.unwrap_or(node_context.cloned().unwrap_or(Size::ZERO))
828 }
829
830 #[test]
831 fn new_should_allocate_default_capacity() {
832 const DEFAULT_CAPACITY: usize = 16; // This is the capacity defined in the `impl Default`
833 let taffy: TaffyTree<()> = TaffyTree::new();
834
835 assert!(taffy.children.capacity() >= DEFAULT_CAPACITY);
836 assert!(taffy.parents.capacity() >= DEFAULT_CAPACITY);
837 assert!(taffy.nodes.capacity() >= DEFAULT_CAPACITY);
838 }
839
840 #[test]
841 fn test_with_capacity() {
842 const CAPACITY: usize = 8;
843 let taffy: TaffyTree<()> = TaffyTree::with_capacity(CAPACITY);
844
845 assert!(taffy.children.capacity() >= CAPACITY);
846 assert!(taffy.parents.capacity() >= CAPACITY);
847 assert!(taffy.nodes.capacity() >= CAPACITY);
848 }
849
850 #[test]
851 fn test_new_leaf() {
852 let mut taffy: TaffyTree<()> = TaffyTree::new();
853
854 let res = taffy.new_leaf(Style::default());
855 assert!(res.is_ok());
856 let node = res.unwrap();
857
858 // node should be in the taffy tree and have no children
859 assert!(taffy.child_count(node) == 0);
860 }
861
862 #[test]
863 fn new_leaf_with_context() {
864 let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
865
866 let res = taffy.new_leaf_with_context(Style::default(), Size::ZERO);
867 assert!(res.is_ok());
868 let node = res.unwrap();
869
870 // node should be in the taffy tree and have no children
871 assert!(taffy.child_count(node) == 0);
872 }
873
874 /// Test that new_with_children works as expected
875 #[test]
876 fn test_new_with_children() {
877 let mut taffy: TaffyTree<()> = TaffyTree::new();
878 let child0 = taffy.new_leaf(Style::default()).unwrap();
879 let child1 = taffy.new_leaf(Style::default()).unwrap();
880 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
881
882 // node should have two children
883 assert_eq!(taffy.child_count(node), 2);
884 assert_eq!(taffy.children(node).unwrap()[0], child0);
885 assert_eq!(taffy.children(node).unwrap()[1], child1);
886 }
887
888 #[test]
889 fn remove_node_should_remove() {
890 let mut taffy: TaffyTree<()> = TaffyTree::new();
891
892 let node = taffy.new_leaf(Style::default()).unwrap();
893
894 let _ = taffy.remove(node).unwrap();
895 }
896
897 #[test]
898 fn remove_node_should_detach_hierarchy() {
899 let mut taffy: TaffyTree<()> = TaffyTree::new();
900
901 // Build a linear tree layout: <0> <- <1> <- <2>
902 let node2 = taffy.new_leaf(Style::default()).unwrap();
903 let node1 = taffy.new_with_children(Style::default(), &[node2]).unwrap();
904 let node0 = taffy.new_with_children(Style::default(), &[node1]).unwrap();
905
906 // Both node0 and node1 should have 1 child nodes
907 assert_eq!(taffy.children(node0).unwrap().as_slice(), &[node1]);
908 assert_eq!(taffy.children(node1).unwrap().as_slice(), &[node2]);
909
910 // Disconnect the tree: <0> <2>
911 let _ = taffy.remove(node1).unwrap();
912
913 // Both remaining nodes should have no child nodes
914 assert!(taffy.children(node0).unwrap().is_empty());
915 assert!(taffy.children(node2).unwrap().is_empty());
916 }
917
918 #[test]
919 fn remove_last_node() {
920 let mut taffy: TaffyTree<()> = TaffyTree::new();
921
922 let parent = taffy.new_leaf(Style::default()).unwrap();
923 let child = taffy.new_leaf(Style::default()).unwrap();
924 taffy.add_child(parent, child).unwrap();
925
926 taffy.remove(child).unwrap();
927 taffy.remove(parent).unwrap();
928 }
929
930 #[test]
931 fn set_measure() {
932 let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
933 let node = taffy.new_leaf_with_context(Style::default(), Size { width: 200.0, height: 200.0 }).unwrap();
934 taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
935 assert_eq!(taffy.layout(node).unwrap().size.width, 200.0);
936
937 taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
938 taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
939 assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
940 }
941
942 #[test]
943 fn set_measure_of_previously_unmeasured_node() {
944 let mut taffy: TaffyTree<Size<f32>> = TaffyTree::new();
945 let node = taffy.new_leaf(Style::default()).unwrap();
946 taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
947 assert_eq!(taffy.layout(node).unwrap().size.width, 0.0);
948
949 taffy.set_node_context(node, Some(Size { width: 100.0, height: 100.0 })).unwrap();
950 taffy.compute_layout_with_measure(node, Size::MAX_CONTENT, size_measure_function).unwrap();
951 assert_eq!(taffy.layout(node).unwrap().size.width, 100.0);
952 }
953
954 /// Test that adding `add_child()` works
955 #[test]
956 fn add_child() {
957 let mut taffy: TaffyTree<()> = TaffyTree::new();
958 let node = taffy.new_leaf(Style::default()).unwrap();
959 assert_eq!(taffy.child_count(node), 0);
960
961 let child0 = taffy.new_leaf(Style::default()).unwrap();
962 taffy.add_child(node, child0).unwrap();
963 assert_eq!(taffy.child_count(node), 1);
964
965 let child1 = taffy.new_leaf(Style::default()).unwrap();
966 taffy.add_child(node, child1).unwrap();
967 assert_eq!(taffy.child_count(node), 2);
968 }
969
970 #[test]
971 fn insert_child_at_index() {
972 let mut taffy: TaffyTree<()> = TaffyTree::new();
973
974 let child0 = taffy.new_leaf(Style::default()).unwrap();
975 let child1 = taffy.new_leaf(Style::default()).unwrap();
976 let child2 = taffy.new_leaf(Style::default()).unwrap();
977
978 let node = taffy.new_leaf(Style::default()).unwrap();
979 assert_eq!(taffy.child_count(node), 0);
980
981 taffy.insert_child_at_index(node, 0, child0).unwrap();
982 assert_eq!(taffy.child_count(node), 1);
983 assert_eq!(taffy.children(node).unwrap()[0], child0);
984
985 taffy.insert_child_at_index(node, 0, child1).unwrap();
986 assert_eq!(taffy.child_count(node), 2);
987 assert_eq!(taffy.children(node).unwrap()[0], child1);
988 assert_eq!(taffy.children(node).unwrap()[1], child0);
989
990 taffy.insert_child_at_index(node, 1, child2).unwrap();
991 assert_eq!(taffy.child_count(node), 3);
992 assert_eq!(taffy.children(node).unwrap()[0], child1);
993 assert_eq!(taffy.children(node).unwrap()[1], child2);
994 assert_eq!(taffy.children(node).unwrap()[2], child0);
995 }
996
997 #[test]
998 fn set_children() {
999 let mut taffy: TaffyTree<()> = TaffyTree::new();
1000
1001 let child0 = taffy.new_leaf(Style::default()).unwrap();
1002 let child1 = taffy.new_leaf(Style::default()).unwrap();
1003 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1004
1005 assert_eq!(taffy.child_count(node), 2);
1006 assert_eq!(taffy.children(node).unwrap()[0], child0);
1007 assert_eq!(taffy.children(node).unwrap()[1], child1);
1008
1009 let child2 = taffy.new_leaf(Style::default()).unwrap();
1010 let child3 = taffy.new_leaf(Style::default()).unwrap();
1011 taffy.set_children(node, &[child2, child3]).unwrap();
1012
1013 assert_eq!(taffy.child_count(node), 2);
1014 assert_eq!(taffy.children(node).unwrap()[0], child2);
1015 assert_eq!(taffy.children(node).unwrap()[1], child3);
1016 }
1017
1018 /// Test that removing a child works
1019 #[test]
1020 fn remove_child() {
1021 let mut taffy: TaffyTree<()> = TaffyTree::new();
1022 let child0 = taffy.new_leaf(Style::default()).unwrap();
1023 let child1 = taffy.new_leaf(Style::default()).unwrap();
1024 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1025
1026 assert_eq!(taffy.child_count(node), 2);
1027
1028 taffy.remove_child(node, child0).unwrap();
1029 assert_eq!(taffy.child_count(node), 1);
1030 assert_eq!(taffy.children(node).unwrap()[0], child1);
1031
1032 taffy.remove_child(node, child1).unwrap();
1033 assert_eq!(taffy.child_count(node), 0);
1034 }
1035
1036 #[test]
1037 fn remove_child_at_index() {
1038 let mut taffy: TaffyTree<()> = TaffyTree::new();
1039 let child0 = taffy.new_leaf(Style::default()).unwrap();
1040 let child1 = taffy.new_leaf(Style::default()).unwrap();
1041 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1042
1043 assert_eq!(taffy.child_count(node), 2);
1044
1045 taffy.remove_child_at_index(node, 0).unwrap();
1046 assert_eq!(taffy.child_count(node), 1);
1047 assert_eq!(taffy.children(node).unwrap()[0], child1);
1048
1049 taffy.remove_child_at_index(node, 0).unwrap();
1050 assert_eq!(taffy.child_count(node), 0);
1051 }
1052
1053 // Related to: https://github.com/DioxusLabs/taffy/issues/510
1054 #[test]
1055 fn remove_child_updates_parents() {
1056 let mut taffy: TaffyTree<()> = TaffyTree::new();
1057
1058 let parent = taffy.new_leaf(Style::default()).unwrap();
1059 let child = taffy.new_leaf(Style::default()).unwrap();
1060
1061 taffy.add_child(parent, child).unwrap();
1062
1063 taffy.remove(parent).unwrap();
1064
1065 // Once the parent is removed this shouldn't panic.
1066 assert!(taffy.set_children(child, &[]).is_ok());
1067 }
1068
1069 #[test]
1070 fn replace_child_at_index() {
1071 let mut taffy: TaffyTree<()> = TaffyTree::new();
1072
1073 let child0 = taffy.new_leaf(Style::default()).unwrap();
1074 let child1 = taffy.new_leaf(Style::default()).unwrap();
1075
1076 let node = taffy.new_with_children(Style::default(), &[child0]).unwrap();
1077 assert_eq!(taffy.child_count(node), 1);
1078 assert_eq!(taffy.children(node).unwrap()[0], child0);
1079
1080 taffy.replace_child_at_index(node, 0, child1).unwrap();
1081 assert_eq!(taffy.child_count(node), 1);
1082 assert_eq!(taffy.children(node).unwrap()[0], child1);
1083 }
1084 #[test]
1085 fn test_child_at_index() {
1086 let mut taffy: TaffyTree<()> = TaffyTree::new();
1087 let child0 = taffy.new_leaf(Style::default()).unwrap();
1088 let child1 = taffy.new_leaf(Style::default()).unwrap();
1089 let child2 = taffy.new_leaf(Style::default()).unwrap();
1090 let node = taffy.new_with_children(Style::default(), &[child0, child1, child2]).unwrap();
1091
1092 assert!(if let Ok(result) = taffy.child_at_index(node, 0) { result == child0 } else { false });
1093 assert!(if let Ok(result) = taffy.child_at_index(node, 1) { result == child1 } else { false });
1094 assert!(if let Ok(result) = taffy.child_at_index(node, 2) { result == child2 } else { false });
1095 }
1096 #[test]
1097 fn test_child_count() {
1098 let mut taffy: TaffyTree<()> = TaffyTree::new();
1099 let child0 = taffy.new_leaf(Style::default()).unwrap();
1100 let child1 = taffy.new_leaf(Style::default()).unwrap();
1101 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1102
1103 assert!(taffy.child_count(node) == 2);
1104 assert!(taffy.child_count(child0) == 0);
1105 assert!(taffy.child_count(child1) == 0);
1106 }
1107
1108 #[allow(clippy::vec_init_then_push)]
1109 #[test]
1110 fn test_children() {
1111 let mut taffy: TaffyTree<()> = TaffyTree::new();
1112 let child0 = taffy.new_leaf(Style::default()).unwrap();
1113 let child1 = taffy.new_leaf(Style::default()).unwrap();
1114 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1115
1116 let mut children = sys::Vec::new();
1117 children.push(child0);
1118 children.push(child1);
1119
1120 let children_result = taffy.children(node).unwrap();
1121 assert_eq!(children_result, children);
1122
1123 assert!(taffy.children(child0).unwrap().is_empty());
1124 }
1125 #[test]
1126 fn test_set_style() {
1127 let mut taffy: TaffyTree<()> = TaffyTree::new();
1128
1129 let node = taffy.new_leaf(Style::default()).unwrap();
1130 assert_eq!(taffy.style(node).unwrap().display, Display::Flex);
1131
1132 taffy.set_style(node, Style { display: Display::None, ..Style::default() }).unwrap();
1133 assert_eq!(taffy.style(node).unwrap().display, Display::None);
1134 }
1135 #[test]
1136 fn test_style() {
1137 let mut taffy: TaffyTree<()> = TaffyTree::new();
1138
1139 let style = Style { display: Display::None, flex_direction: FlexDirection::RowReverse, ..Default::default() };
1140
1141 let node = taffy.new_leaf(style.clone()).unwrap();
1142
1143 let res = taffy.style(node);
1144 assert!(res.is_ok());
1145 assert!(res.unwrap() == &style);
1146 }
1147 #[test]
1148 fn test_layout() {
1149 let mut taffy: TaffyTree<()> = TaffyTree::new();
1150 let node = taffy.new_leaf(Style::default()).unwrap();
1151
1152 // TODO: Improve this test?
1153 let res = taffy.layout(node);
1154 assert!(res.is_ok());
1155 }
1156
1157 #[test]
1158 fn test_mark_dirty() {
1159 let mut taffy: TaffyTree<()> = TaffyTree::new();
1160 let child0 = taffy.new_leaf(Style::default()).unwrap();
1161 let child1 = taffy.new_leaf(Style::default()).unwrap();
1162 let node = taffy.new_with_children(Style::default(), &[child0, child1]).unwrap();
1163
1164 taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1165
1166 assert_eq!(taffy.dirty(child0), Ok(false));
1167 assert_eq!(taffy.dirty(child1), Ok(false));
1168 assert_eq!(taffy.dirty(node), Ok(false));
1169
1170 taffy.mark_dirty(node).unwrap();
1171 assert_eq!(taffy.dirty(child0), Ok(false));
1172 assert_eq!(taffy.dirty(child1), Ok(false));
1173 assert_eq!(taffy.dirty(node), Ok(true));
1174
1175 taffy.compute_layout(node, Size::MAX_CONTENT).unwrap();
1176 taffy.mark_dirty(child0).unwrap();
1177 assert_eq!(taffy.dirty(child0), Ok(true));
1178 assert_eq!(taffy.dirty(child1), Ok(false));
1179 assert_eq!(taffy.dirty(node), Ok(true));
1180 }
1181
1182 #[test]
1183 fn compute_layout_should_produce_valid_result() {
1184 let mut taffy: TaffyTree<()> = TaffyTree::new();
1185 let node_result = taffy.new_leaf(Style {
1186 size: Size { width: Dimension::Length(10f32), height: Dimension::Length(10f32) },
1187 ..Default::default()
1188 });
1189 assert!(node_result.is_ok());
1190 let node = node_result.unwrap();
1191 let layout_result = taffy.compute_layout(
1192 node,
1193 Size { width: AvailableSpace::Definite(100.), height: AvailableSpace::Definite(100.) },
1194 );
1195 assert!(layout_result.is_ok());
1196 }
1197
1198 #[test]
1199 fn make_sure_layout_location_is_top_left() {
1200 use crate::prelude::Rect;
1201
1202 let mut taffy: TaffyTree<()> = TaffyTree::new();
1203
1204 let node = taffy
1205 .new_leaf(Style {
1206 size: Size { width: Dimension::Percent(1f32), height: Dimension::Percent(1f32) },
1207 ..Default::default()
1208 })
1209 .unwrap();
1210
1211 let root = taffy
1212 .new_with_children(
1213 Style {
1214 size: Size { width: Dimension::Length(100f32), height: Dimension::Length(100f32) },
1215 padding: Rect {
1216 left: length(10f32),
1217 right: length(20f32),
1218 top: length(30f32),
1219 bottom: length(40f32),
1220 },
1221 ..Default::default()
1222 },
1223 &[node],
1224 )
1225 .unwrap();
1226
1227 taffy.compute_layout(root, Size::MAX_CONTENT).unwrap();
1228
1229 // If Layout::location represents top-left coord, 'node' location
1230 // must be (due applied 'root' padding): {x: 10, y: 30}.
1231 //
1232 // It's important, since result will be different for each other
1233 // coordinate space:
1234 // - bottom-left: {x: 10, y: 40}
1235 // - top-right: {x: 20, y: 30}
1236 // - bottom-right: {x: 20, y: 40}
1237 let layout = taffy.layout(node).unwrap();
1238 assert_eq!(layout.location.x, 10f32);
1239 assert_eq!(layout.location.y, 30f32);
1240 }
1241
1242 #[test]
1243 fn set_children_reparents() {
1244 let mut taffy: TaffyTree<()> = TaffyTree::new();
1245 let child = taffy.new_leaf(Style::default()).unwrap();
1246 let old_parent = taffy.new_with_children(Style::default(), &[child]).unwrap();
1247
1248 let new_parent = taffy.new_leaf(Style::default()).unwrap();
1249 taffy.set_children(new_parent, &[child]).unwrap();
1250
1251 assert!(taffy.children(old_parent).unwrap().is_empty());
1252 }
1253}