gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 5364Rust 86Markdown 12TOML 91841 Definitions

⎇ 54603379f1342a23a63606a7bbd2674c2a2ded70 src/tree/taffy_tree.rs Rust · 1199 lines · 44.2 KB History Who touched what raw

Fixup for passing style to measure functions 54603379f · Nico Burns ·

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