gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 695HTML 648Markdown 12TOML 62320 Sutichaykuna

⎇ 6d7f3cf86a923a02c9d7b67053096a8b3486f15f examples/custom_layout_tree_vec.rs Rust · 215 siq'ikuna · 6.5 KB Ñawpa willay Pi imata llamkarqan ch'uya

Refactor `LayoutTree` + add examples of custom trees (#564) d4374b93f · Nico Burns ·

1mod common {
2    pub mod image;
3    pub mod text;
4}
5use common::image::{image_measure_function, ImageContext};
6use common::text::{text_measure_function, FontMetrics, TextContext, WritingMode, LOREM_IPSUM};
7use taffy::tree::{Cache, PartialLayoutTree};
8use taffy::util::print_tree;
9use taffy::{
10    compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_layout, compute_leaf_layout,
11    prelude::*, round_layout,
12};
13
14#[derive(Debug, Copy, Clone)]
15#[allow(dead_code)]
16enum NodeKind {
17    Flexbox,
18    Grid,
19    Text,
20    Image,
21}
22
23struct Node {
24    kind: NodeKind,
25    style: Style,
26    text_data: Option<TextContext>,
27    image_data: Option<ImageContext>,
28    cache: Cache,
29    unrounded_layout: Layout,
30    final_layout: Layout,
31    children: Vec<usize>,
32}
33
34impl Default for Node {
35    fn default() -> Self {
36        Node {
37            kind: NodeKind::Flexbox,
38            style: Style::default(),
39            text_data: None,
40            image_data: None,
41            cache: Cache::new(),
42            unrounded_layout: Layout::with_order(0),
43            final_layout: Layout::with_order(0),
44            children: Vec::new(),
45        }
46    }
47}
48
49#[allow(dead_code)]
50impl Node {
51    pub fn new_row(style: Style) -> Node {
52        Node {
53            kind: NodeKind::Flexbox,
54            style: Style { display: Display::Flex, flex_direction: FlexDirection::Row, ..style },
55            ..Node::default()
56        }
57    }
58    pub fn new_column(style: Style) -> Node {
59        Node {
60            kind: NodeKind::Flexbox,
61            style: Style { display: Display::Flex, flex_direction: FlexDirection::Column, ..style },
62            ..Node::default()
63        }
64    }
65    pub fn new_grid(style: Style) -> Node {
66        Node { kind: NodeKind::Grid, style: Style { display: Display::Grid, ..style }, ..Node::default() }
67    }
68    pub fn new_text(style: Style, text_data: TextContext) -> Node {
69        Node { kind: NodeKind::Text, style, text_data: Some(text_data), ..Node::default() }
70    }
71    pub fn new_image(style: Style, image_data: ImageContext) -> Node {
72        Node { kind: NodeKind::Image, style, image_data: Some(image_data), ..Node::default() }
73    }
74}
75
76struct Tree {
77    nodes: Vec<Node>,
78}
79
80impl Tree {
81    pub fn new() -> Tree {
82        Tree { nodes: Vec::new() }
83    }
84
85    pub fn add_node(&mut self, node: Node) -> usize {
86        self.nodes.push(node);
87        self.nodes.len() - 1
88    }
89
90    pub fn append_child(&mut self, parent: usize, child: usize) {
91        self.nodes[parent].children.push(child);
92    }
93
94    #[inline(always)]
95    fn node_from_id(&self, node_id: NodeId) -> &Node {
96        &self.nodes[usize::from(node_id)]
97    }
98
99    #[inline(always)]
100    fn node_from_id_mut(&mut self, node_id: NodeId) -> &mut Node {
101        &mut self.nodes[usize::from(node_id)]
102    }
103
104    pub fn compute_layout(&mut self, root: usize, available_space: Size<AvailableSpace>, use_rounding: bool) {
105        compute_layout(self, NodeId::from(root), available_space);
106        if use_rounding {
107            round_layout(self, NodeId::from(root))
108        }
109    }
110
111    pub fn print_tree(&mut self, root: usize) {
112        print_tree(self, NodeId::from(root));
113    }
114}
115
116struct ChildIter<'a>(std::slice::Iter<'a, usize>);
117impl<'a> Iterator for ChildIter<'a> {
118    type Item = NodeId;
119    fn next(&mut self) -> Option<Self::Item> {
120        self.0.next().copied().map(NodeId::from)
121    }
122}
123
124impl PartialLayoutTree for Tree {
125    type ChildIter<'a> = ChildIter<'a>;
126
127    fn child_ids(&self, node_id: NodeId) -> Self::ChildIter<'_> {
128        ChildIter(self.node_from_id(node_id).children.iter())
129    }
130
131    fn child_count(&self, node_id: NodeId) -> usize {
132        self.node_from_id(node_id).children.len()
133    }
134
135    fn get_child_id(&self, node_id: NodeId, index: usize) -> NodeId {
136        NodeId::from(self.node_from_id(node_id).children[index])
137    }
138
139    fn get_style(&self, node_id: NodeId) -> &Style {
140        &self.node_from_id(node_id).style
141    }
142
143    fn get_unrounded_layout_mut(&mut self, node_id: NodeId) -> &mut Layout {
144        &mut self.node_from_id_mut(node_id).unrounded_layout
145    }
146
147    fn get_cache_mut(&mut self, node_id: NodeId) -> &mut Cache {
148        &mut self.node_from_id_mut(node_id).cache
149    }
150
151    fn compute_child_layout(&mut self, node_id: NodeId, inputs: taffy::tree::LayoutInput) -> taffy::tree::LayoutOutput {
152        compute_cached_layout(self, node_id, inputs, |tree, node_id, inputs| {
153            let node = tree.node_from_id_mut(node_id);
154            let font_metrics = FontMetrics { char_width: 10.0, char_height: 10.0 };
155
156            match node.kind {
157                NodeKind::Flexbox => compute_flexbox_layout(tree, node_id, inputs),
158                NodeKind::Grid => compute_grid_layout(tree, node_id, inputs),
159                NodeKind::Text => compute_leaf_layout(
160                    inputs,
161                    &node.style,
162                    Some(|known_dimensions, available_space| {
163                        text_measure_function(
164                            known_dimensions,
165                            available_space,
166                            node.text_data.as_ref().unwrap(),
167                            &font_metrics,
168                        )
169                    }),
170                ),
171                NodeKind::Image => compute_leaf_layout(
172                    inputs,
173                    &node.style,
174                    Some(|known_dimensions, _available_space| {
175                        image_measure_function(known_dimensions, node.image_data.as_ref().unwrap())
176                    }),
177                ),
178            }
179        })
180    }
181}
182
183impl LayoutTree for Tree {
184    fn get_final_layout(&self, node_id: NodeId) -> &Layout {
185        &self.node_from_id(node_id).final_layout
186    }
187
188    fn get_final_layout_mut(&mut self, node_id: NodeId) -> &mut Layout {
189        &mut self.node_from_id_mut(node_id).final_layout
190    }
191}
192
193fn main() -> Result<(), taffy::TaffyError> {
194    let mut tree = Tree::new();
195
196    let root = Node::new_column(Style::DEFAULT);
197    let root_id = tree.add_node(root);
198
199    let text_node = Node::new_text(
200        Style::default(),
201        TextContext { text_content: LOREM_IPSUM.into(), writing_mode: WritingMode::Horizontal },
202    );
203    let text_node_id = tree.add_node(text_node);
204    tree.append_child(root_id, text_node_id);
205
206    let image_node = Node::new_image(Style::default(), ImageContext { width: 400.0, height: 300.0 });
207    let image_node_id = tree.add_node(image_node);
208    tree.append_child(root_id, image_node_id);
209
210    // Compute layout and print result
211    tree.compute_layout(root_id, Size::MAX_CONTENT, true);
212    tree.print_tree(root_id);
213
214    Ok(())
215}