tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 229Rust 8TOML 3CSS 1310 Definiciones

⎇ 5db1a9d99aeb127615eb3d3dae90d83e7d5eaace examples/custom_tree_owned_partial.rs Rust · 270 líneas · 8.2 KB Historia Quién tocó qué crudo

Use `*const ()` to represent `CompactLength` and add implementation for 32 bit platforms (#789) 8d2a036c1 · Nico Burns ·

1//! ## Example: Partial Tree with Directly Owned Children
2//!
3//! The following example demonstrate an implementation of Taffy's Partial trait and usage of the low-level compute APIs.
4//! This example uses directly owned children with NodeId's being index's into vec on parent node.
5//! Since an iterator created from a node can't access grandchildren, we are limited to only implement `TraversePartialTree`.
6//! See the [`crate::tree::traits`] module for more details about the low-level traits.
7
8mod common {
9    pub mod image;
10    pub mod text;
11}
12use common::image::{image_measure_function, ImageContext};
13use common::text::{text_measure_function, FontMetrics, TextContext, WritingMode, LOREM_IPSUM};
14use taffy::{
15    compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_leaf_layout, compute_root_layout,
16    prelude::*, Cache, CacheTree, Layout, Style,
17};
18
19#[derive(Debug, Copy, Clone)]
20#[allow(dead_code)]
21enum NodeKind {
22    Flexbox,
23    Grid,
24    Text,
25    Image,
26}
27
28struct Node {
29    kind: NodeKind,
30    style: Style,
31    text_data: Option<TextContext>,
32    image_data: Option<ImageContext>,
33    cache: Cache,
34    layout: Layout,
35    children: Vec<Node>,
36}
37
38impl Default for Node {
39    fn default() -> Self {
40        Node {
41            kind: NodeKind::Flexbox,
42            style: Style::default(),
43            text_data: None,
44            image_data: None,
45            cache: Cache::new(),
46            layout: Layout::with_order(0),
47            children: Vec::new(),
48        }
49    }
50}
51
52#[allow(dead_code)]
53impl Node {
54    pub fn new_row(style: Style) -> Node {
55        Node {
56            kind: NodeKind::Flexbox,
57            style: Style { display: Display::Flex, flex_direction: FlexDirection::Row, ..style },
58            ..Node::default()
59        }
60    }
61    pub fn new_column(style: Style) -> Node {
62        Node {
63            kind: NodeKind::Flexbox,
64            style: Style { display: Display::Flex, flex_direction: FlexDirection::Column, ..style },
65            ..Node::default()
66        }
67    }
68    pub fn new_grid(style: Style) -> Node {
69        Node { kind: NodeKind::Grid, style: Style { display: Display::Grid, ..style }, ..Node::default() }
70    }
71    pub fn new_text(style: Style, text_data: TextContext) -> Node {
72        Node { kind: NodeKind::Text, style, text_data: Some(text_data), ..Node::default() }
73    }
74    pub fn new_image(style: Style, image_data: ImageContext) -> Node {
75        Node { kind: NodeKind::Image, style, image_data: Some(image_data), ..Node::default() }
76    }
77    pub fn append_child(&mut self, node: Node) {
78        self.children.push(node);
79    }
80
81    pub fn compute_layout(&mut self, available_space: Size<AvailableSpace>) {
82        compute_root_layout(self, NodeId::from(usize::MAX), available_space);
83    }
84
85    /// The methods on LayoutPartialTree need to be able to access:
86    ///
87    ///  - The node being laid out
88    ///  - Direct children of the node being laid out
89    ///
90    /// Each must have an ID. For children we simply use it's index. For the node itself
91    /// we use usize::MAX on the assumption that there will never be that many children.
92    fn node_from_id(&self, node_id: NodeId) -> &Node {
93        let idx = usize::from(node_id);
94        if idx == usize::MAX {
95            self
96        } else {
97            &self.children[idx]
98        }
99    }
100
101    fn node_from_id_mut(&mut self, node_id: NodeId) -> &mut Node {
102        let idx = usize::from(node_id);
103        if idx == usize::MAX {
104            self
105        } else {
106            &mut self.children[idx]
107        }
108    }
109}
110
111struct ChildIter(std::ops::Range<usize>);
112impl Iterator for ChildIter {
113    type Item = NodeId;
114    fn next(&mut self) -> Option<Self::Item> {
115        self.0.next().map(NodeId::from)
116    }
117}
118
119impl taffy::TraversePartialTree for Node {
120    type ChildIter<'a> = ChildIter;
121
122    fn child_ids(&self, _node_id: NodeId) -> Self::ChildIter<'_> {
123        ChildIter(0..self.children.len())
124    }
125
126    fn child_count(&self, _node_id: NodeId) -> usize {
127        self.children.len()
128    }
129
130    fn get_child_id(&self, _node_id: NodeId, index: usize) -> NodeId {
131        NodeId::from(index)
132    }
133}
134
135impl taffy::LayoutPartialTree for Node {
136    type CoreContainerStyle<'a>
137        = &'a Style
138    where
139        Self: 'a;
140
141    fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
142        &self.node_from_id(node_id).style
143    }
144
145    fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
146        self.node_from_id_mut(node_id).layout = *layout
147    }
148
149    fn resolve_calc_value(&self, _val: *const (), _basis: f32) -> f32 {
150        0.0
151    }
152
153    fn compute_child_layout(&mut self, node_id: NodeId, inputs: taffy::tree::LayoutInput) -> taffy::tree::LayoutOutput {
154        compute_cached_layout(self, node_id, inputs, |parent, node_id, inputs| {
155            let node = parent.node_from_id_mut(node_id);
156            let font_metrics = FontMetrics { char_width: 10.0, char_height: 10.0 };
157
158            match node.kind {
159                NodeKind::Flexbox => compute_flexbox_layout(node, node_id, inputs),
160                NodeKind::Grid => compute_grid_layout(node, node_id, inputs),
161                NodeKind::Text => compute_leaf_layout(
162                    inputs,
163                    &node.style,
164                    |_val, _basis| 0.0,
165                    |known_dimensions, available_space| {
166                        text_measure_function(
167                            known_dimensions,
168                            available_space,
169                            node.text_data.as_ref().unwrap(),
170                            &font_metrics,
171                        )
172                    },
173                ),
174                NodeKind::Image => compute_leaf_layout(
175                    inputs,
176                    &node.style,
177                    |_val, _basis| 0.0,
178                    |known_dimensions, _available_space| {
179                        image_measure_function(known_dimensions, node.image_data.as_ref().unwrap())
180                    },
181                ),
182            }
183        })
184    }
185}
186
187impl CacheTree for Node {
188    fn cache_get(
189        &self,
190        node_id: NodeId,
191        known_dimensions: Size<Option<f32>>,
192        available_space: Size<AvailableSpace>,
193        run_mode: taffy::RunMode,
194    ) -> Option<taffy::LayoutOutput> {
195        self.node_from_id(node_id).cache.get(known_dimensions, available_space, run_mode)
196    }
197
198    fn cache_store(
199        &mut self,
200        node_id: NodeId,
201        known_dimensions: Size<Option<f32>>,
202        available_space: Size<AvailableSpace>,
203        run_mode: taffy::RunMode,
204        layout_output: taffy::LayoutOutput,
205    ) {
206        self.node_from_id_mut(node_id).cache.store(known_dimensions, available_space, run_mode, layout_output)
207    }
208
209    fn cache_clear(&mut self, node_id: NodeId) {
210        self.node_from_id_mut(node_id).cache.clear();
211    }
212}
213
214impl taffy::LayoutFlexboxContainer for Node {
215    type FlexboxContainerStyle<'a>
216        = &'a Style
217    where
218        Self: 'a;
219
220    type FlexboxItemStyle<'a>
221        = &'a Style
222    where
223        Self: 'a;
224
225    fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
226        &self.node_from_id(node_id).style
227    }
228
229    fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
230        &self.node_from_id(child_node_id).style
231    }
232}
233
234impl taffy::LayoutGridContainer for Node {
235    type GridContainerStyle<'a>
236        = &'a Style
237    where
238        Self: 'a;
239
240    type GridItemStyle<'a>
241        = &'a Style
242    where
243        Self: 'a;
244
245    fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
246        &self.node_from_id(node_id).style
247    }
248
249    fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
250        &self.node_from_id(child_node_id).style
251    }
252}
253
254fn main() -> Result<(), taffy::TaffyError> {
255    let mut root = Node::new_column(Style::DEFAULT);
256
257    let text_node = Node::new_text(
258        Style::default(),
259        TextContext { text_content: LOREM_IPSUM.into(), writing_mode: WritingMode::Horizontal },
260    );
261    root.append_child(text_node);
262
263    let image_node = Node::new_image(Style::default(), ImageContext { width: 400.0, height: 300.0 });
264    root.append_child(image_node);
265
266    // Compute layout
267    root.compute_layout(Size::MAX_CONTENT);
268
269    Ok(())
270}