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