⎇ 539fd458ba2ea1102b019422dd5c4f1106340902
src/tree/traits.rs
Ñawpa willay
Pi imata llamkarqan
ch'uya
Make CacheMut an associated type
1//! The abstractions that make up the core of Taffy's low-level API
2//!
3//! ## Examples
4//!
5//! The following examples demonstrate end-to-end implementation of Taffy's traits and usage of the low-level compute APIs:
6//!
7//! - [custom_tree_vec](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_vec.rs) which implements a custom Taffy tree using a `Vec` as an arena with NodeId's being index's into the Vec.
8//! - [custom_tree_owned_partial](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_owned_partial.rs) which implements a custom Taffy tree using directly owned children with NodeId's being pointers.
9//! - [custom_tree_owned_unsafe](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_owned_unsafe.rs) which implements a custom Taffy tree using directly owned children with NodeId's being pointers.
10//!
11//! ## Overview
12//!
13//! ### Trait dependency tree
14//!
15//! The tree below illustrates which traits depend on which other traits.
16//!
17//! ```text
18//! TraversePartialTree - Access a node's children
19//! ├── LayoutPartialTree - Run layout algorithms on a node and it's direct children
20//! └── TraverseTree - Recursively access a node's descendants
21//! ├── RoundTree - Round a float-valued` layout to integer pixels
22//! └── PrintTree - Print a debug representation of a node tree
23//! ```
24//!
25//! ### A table of traits
26//!
27//! | Trait | Requires | Enables |
28//! | --- | --- | --- |
29//! | [`LayoutPartialTree`] | [`TraversePartialTree`] | [`compute_flexbox_layout`](crate::compute_flexbox_layout)<br />[`compute_grid_layout`](crate::compute_grid_layout)<br />[`compute_block_layout`](crate::compute_block_layout)<br />[`compute_root_layout`](crate::compute_root_layout)<br />[`compute_leaf_layout`](crate::compute_leaf_layout)<br />[`compute_hidden_layout`](crate::compute_hidden_layout)<br />[`compute_cached_layout`](crate::compute_cached_layout) |
30//! | [`RoundTree`] | [`TraverseTree`] | [`round_layout`](crate::round_layout) |
31//! | [`PrintTree`] | [`TraverseTree`] | [`print_tree`](crate::print_tree) |
32//!
33//! ## All of the traits on one page
34//!
35//! ### TraversePartialTree and TraverseTree
36//! These traits are Taffy's abstraction for downward tree traversal:
37//! - [`TraversePartialTree`] allows access to a single container node, and it's immediate children. This is the only "traverse" trait that is required
38//! for use of Taffy's core layout algorithms (flexbox, grid, etc).
39//! - [`TraverseTree`] is a marker trait which uses the same API signature as `TraversePartialTree`, but extends it with a guarantee that the child/children methods can be used to recurse
40//! infinitely down the tree. It is required by the `RoundTree` and
41//! the `PrintTree` traits.
42//! ```rust
43//! # use taffy::*;
44//! pub trait TraversePartialTree {
45//! /// Type representing an iterator of the children of a node
46//! type ChildIter<'a>: Iterator<Item = NodeId>
47//! where
48//! Self: 'a;
49//!
50//! /// Get the list of children IDs for the given node
51//! fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_>;
52//!
53//! /// Get the number of children for the given node
54//! fn child_count(&self, parent_node_id: NodeId) -> usize;
55//!
56//! /// Get a specific child of a node, where the index represents the nth child
57//! fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId;
58//! }
59//!
60//! pub trait TraverseTree: TraversePartialTree {}
61//! ```
62//!
63//! You must implement [`TraversePartialTree`] to access any of Taffy's low-level API. If your tree implementation allows you to implement [`TraverseTree`] with
64//! the correct semantics (full recursive traversal is available) then you should.
65//!
66//! ### LayoutPartialTree
67//!
68//! **Requires:** `TraversePartialTree`<br />
69//! **Enables:** Flexbox, Grid, Block and Leaf layout algorithms from the [`crate::compute`] module
70//!
71//! Any type that implements [`LayoutPartialTree`] can be laid out using [Taffy's algorithms](crate::compute)
72//!
73//! Note that this trait extends [`TraversePartialTree`] (not [`TraverseTree`]). Taffy's algorithm implementations have been designed such that they can be used for a laying out a single
74//! node that only has access to it's immediate children.
75//!
76//! ```rust
77//! # use taffy::*;
78//! pub trait LayoutPartialTree: TraversePartialTree {
79//! /// Get a reference to the [`Style`] for this node.
80//! fn get_style(&self, node_id: NodeId) -> &Style;
81//!
82//! /// Set the node's unrounded layout
83//! fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout);
84//!
85//! /// Get a mutable reference to the [`Cache`] for this node.
86//! fn get_cache_mut(&mut self, node_id: NodeId) -> &mut Cache;
87//!
88//! /// Compute the specified node's size or full layout given the specified constraints
89//! fn compute_child_layout(&mut self, node_id: NodeId, inputs: LayoutInput) -> LayoutOutput;
90//! }
91//! ```
92//!
93//! ### RoundTree
94//!
95//! **Requires:** `TraverseTree`
96//!
97//! Trait used by the `round_layout` method which takes a tree of unrounded float-valued layouts and performs
98//! rounding to snap the values to the pixel grid.
99//!
100//! As indicated by it's dependence on `TraverseTree`, it required full recursive access to the tree.
101//!
102//! ```rust
103//! # use taffy::*;
104//! pub trait RoundTree: TraverseTree {
105//! /// Get the node's unrounded layout
106//! fn get_unrounded_layout(&self, node_id: NodeId) -> &Layout;
107//! /// Get a reference to the node's final layout
108//! fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout);
109//! }
110//! ```
111//!
112//! ### PrintTree
113//!
114//! **Requires:** `TraverseTree`
115//!
116//! ```rust
117//! /// Trait used by the `print_tree` method which prints a debug representation
118//! ///
119//! /// As indicated by it's dependence on `TraverseTree`, it required full recursive access to the tree.
120//! # use taffy::*;
121//! pub trait PrintTree: TraverseTree {
122//! /// Get a debug label for the node (typically the type of node: flexbox, grid, text, image, etc)
123//! fn get_debug_label(&self, node_id: NodeId) -> &'static str;
124//! /// Get a reference to the node's final layout
125//! fn get_final_layout(&self, node_id: NodeId) -> &Layout;
126//! }
127//! ```
128//!
129use super::{Cache, Layout, LayoutInput, LayoutOutput, NodeId, RequestedAxis, RunMode, SizingMode};
130use crate::geometry::{AbsoluteAxis, Line, Size};
131use crate::style::{AvailableSpace, CoreStyle};
132#[cfg(feature = "flexbox")]
133use crate::style::{FlexboxContainerStyle, FlexboxItemStyle};
134#[cfg(feature = "grid")]
135use crate::style::{GridContainerStyle, GridItemStyle};
136use core::ops::{Deref, DerefMut};
137
138/// This trait is Taffy's abstraction for downward tree traversal.
139/// However, this trait does *not* require access to any node's other than a single container node's immediate children unless you also intend to implement `TraverseTree`.
140pub trait TraversePartialTree {
141 /// Type representing an iterator of the children of a node
142 type ChildIter<'a>: Iterator<Item = NodeId>
143 where
144 Self: 'a;
145
146 /// Get the list of children IDs for the given node
147 fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_>;
148
149 /// Get the number of children for the given node
150 fn child_count(&self, parent_node_id: NodeId) -> usize;
151
152 /// Get a specific child of a node, where the index represents the nth child
153 fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId;
154}
155
156/// A marker trait which extends `TraversePartialTree` with the additional guarantee that the child/children methods can be used to recurse
157/// infinitely down the tree. Is required by the `RoundTree` and the `PrintTree` traits.
158pub trait TraverseTree: TraversePartialTree {}
159
160/// Any type that implements [`LayoutPartialTree`] can be laid out using [Taffy's algorithms](crate::compute)
161///
162/// Note that this trait extends [`TraversePartialTree`] (not [`TraverseTree`]). Taffy's algorithm implementations have been designed such that they can be used for a laying out a single
163/// node that only has access to it's immediate children.
164pub trait LayoutPartialTree: TraversePartialTree {
165 /// The style type representing the core container styles that all containers should have
166 /// Used when laying out the root node of a tree
167 type CoreContainerStyle<'a>: CoreStyle
168 where
169 Self: 'a;
170
171 /// A mutable reference to the cache. This is an associated type to allow for different
172 /// types of mutable reference such as mutex or refcell guards
173 type CacheMut<'b>: Deref<Target = Cache> + DerefMut
174 where
175 Self: 'b;
176
177 /// Get core style
178 fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_>;
179
180 /// Set the node's unrounded layout
181 fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout);
182
183 /// Get a mutable reference to the [`Cache`] for this node.
184 fn get_cache_mut(&mut self, node_id: NodeId) -> Self::CacheMut<'_>;
185
186 /// Compute the specified node's size or full layout given the specified constraints
187 fn compute_child_layout(&mut self, node_id: NodeId, inputs: LayoutInput) -> LayoutOutput;
188}
189
190/// Trait used by the `round_layout` method which takes a tree of unrounded float-valued layouts and performs
191/// rounding to snap the values to the pixel grid.
192///
193/// As indicated by it's dependence on `TraverseTree`, it required full recursive access to the tree.
194pub trait RoundTree: TraverseTree {
195 /// Get the node's unrounded layout
196 fn get_unrounded_layout(&self, node_id: NodeId) -> &Layout;
197 /// Get a reference to the node's final layout
198 fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout);
199}
200
201/// Trait used by the `print_tree` method which prints a debug representation
202///
203/// As indicated by it's dependence on `TraverseTree`, it required full recursive access to the tree.
204pub trait PrintTree: TraverseTree {
205 /// Get a debug label for the node (typically the type of node: flexbox, grid, text, image, etc)
206 fn get_debug_label(&self, node_id: NodeId) -> &'static str;
207 /// Get a reference to the node's final layout
208 fn get_final_layout(&self, node_id: NodeId) -> &Layout;
209}
210
211#[cfg(feature = "flexbox")]
212/// Extends [`LayoutPartialTree`] with getters for the styles required for Flexbox layout
213pub trait LayoutFlexboxContainer: LayoutPartialTree {
214 /// The style type representing the Flexbox container's styles
215 type ContainerStyle<'a>: FlexboxContainerStyle
216 where
217 Self: 'a;
218 /// The style type representing each Flexbox item's styles
219 type ItemStyle<'a>: FlexboxItemStyle
220 where
221 Self: 'a;
222
223 /// Get the container's styles
224 fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::ContainerStyle<'_>;
225
226 /// Get the child's styles
227 fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::ItemStyle<'_>;
228}
229
230#[cfg(feature = "grid")]
231/// Extends [`LayoutPartialTree`] with getters for the styles required for CSS Grid layout
232pub trait LayoutGridContainer: LayoutPartialTree {
233 /// The style type representing the CSS Grid container's styles
234 type ContainerStyle<'a>: GridContainerStyle
235 where
236 Self: 'a;
237
238 /// The style type representing each CSS Grid item's styles
239 type ItemStyle<'a>: GridItemStyle
240 where
241 Self: 'a;
242
243 /// Get the container's styles
244 fn get_grid_container_style(&self, node_id: NodeId) -> Self::ContainerStyle<'_>;
245
246 /// Get the child's styles
247 fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::ItemStyle<'_>;
248}
249
250#[cfg(feature = "block_layout")]
251/// Extends [`LayoutPartialTree`] with getters for the styles required for CSS Block layout
252pub trait LayoutBlockContainer: LayoutPartialTree {
253 /// The style type representing the CSS Block container's styles
254 type ContainerStyle<'a>: CoreStyle
255 where
256 Self: 'a;
257 /// The style type representing each CSS Block item's styles
258 type ItemStyle<'a>: CoreStyle
259 where
260 Self: 'a;
261
262 /// Get the container's styles
263 fn get_block_container_style(&self, node_id: NodeId) -> Self::ContainerStyle<'_>;
264
265 /// Get the child's styles
266 fn get_block_child_style(&self, child_node_id: NodeId) -> Self::ItemStyle<'_>;
267}
268
269// --- PRIVATE TRAITS
270
271/// A private trait which allows us to add extra convenience methods to types which implement
272/// LayoutTree without making those methods public.
273pub(crate) trait LayoutPartialTreeExt: LayoutPartialTree {
274 /// Compute the size of the node given the specified constraints
275 #[inline(always)]
276 #[allow(clippy::too_many_arguments)]
277 fn measure_child_size(
278 &mut self,
279 node_id: NodeId,
280 known_dimensions: Size<Option<f32>>,
281 parent_size: Size<Option<f32>>,
282 available_space: Size<AvailableSpace>,
283 sizing_mode: SizingMode,
284 axis: AbsoluteAxis,
285 vertical_margins_are_collapsible: Line<bool>,
286 ) -> f32 {
287 self.compute_child_layout(
288 node_id,
289 LayoutInput {
290 known_dimensions,
291 parent_size,
292 available_space,
293 sizing_mode,
294 axis: axis.into(),
295 run_mode: RunMode::ComputeSize,
296 vertical_margins_are_collapsible,
297 },
298 )
299 .size
300 .get_abs(axis)
301 }
302
303 /// Perform a full layout on the node given the specified constraints
304 #[inline(always)]
305 fn perform_child_layout(
306 &mut self,
307 node_id: NodeId,
308 known_dimensions: Size<Option<f32>>,
309 parent_size: Size<Option<f32>>,
310 available_space: Size<AvailableSpace>,
311 sizing_mode: SizingMode,
312 vertical_margins_are_collapsible: Line<bool>,
313 ) -> LayoutOutput {
314 self.compute_child_layout(
315 node_id,
316 LayoutInput {
317 known_dimensions,
318 parent_size,
319 available_space,
320 sizing_mode,
321 axis: RequestedAxis::Both,
322 run_mode: RunMode::PerformLayout,
323 vertical_margins_are_collapsible,
324 },
325 )
326 }
327}
328
329impl<T: LayoutPartialTree> LayoutPartialTreeExt for T {}