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