Skip to main content

custom_tree_vec/
custom_tree_vec.rs

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 takia::util::print_tree;
8use takia::{
9    compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_leaf_layout, compute_oof_layout,
10    compute_root_layout, prelude::*, round_layout, Cache, CacheTree,
11};
12
13#[derive(Debug, Copy, Clone)]
14#[allow(dead_code)]
15enum NodeKind {
16    Flexbox,
17    Grid,
18    Text,
19    Image,
20}
21
22struct Node {
23    kind: NodeKind,
24    style: Style,
25    text_data: Option<TextContext>,
26    image_data: Option<ImageContext>,
27    cache: Cache,
28    unrounded_layout: Layout,
29    final_layout: Layout,
30    children: Vec<usize>,
31    hoisted_children: Vec<NodeId>,
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            hoisted_children: Vec::new(),
46        }
47    }
48}
49
50#[allow(dead_code)]
51impl Node {
52    pub fn new_row(style: Style) -> Node {
53        Node {
54            kind: NodeKind::Flexbox,
55            style: Style { display: Display::Flex, flex_direction: FlexDirection::Row, ..style },
56            ..Node::default()
57        }
58    }
59    pub fn new_column(style: Style) -> Node {
60        Node {
61            kind: NodeKind::Flexbox,
62            style: Style { display: Display::Flex, flex_direction: FlexDirection::Column, ..style },
63            ..Node::default()
64        }
65    }
66    pub fn new_grid(style: Style) -> Node {
67        Node { kind: NodeKind::Grid, style: Style { display: Display::Grid, ..style }, ..Node::default() }
68    }
69    pub fn new_text(style: Style, text_data: TextContext) -> Node {
70        Node { kind: NodeKind::Text, style, text_data: Some(text_data), ..Node::default() }
71    }
72    pub fn new_image(style: Style, image_data: ImageContext) -> Node {
73        Node { kind: NodeKind::Image, style, image_data: Some(image_data), ..Node::default() }
74    }
75}
76
77struct Tree {
78    nodes: Vec<Node>,
79}
80
81impl Tree {
82    pub fn new() -> Tree {
83        Tree { nodes: Vec::new() }
84    }
85
86    pub fn add_node(&mut self, node: Node) -> usize {
87        self.nodes.push(node);
88        self.nodes.len() - 1
89    }
90
91    pub fn append_child(&mut self, parent: usize, child: usize) {
92        self.nodes[parent].children.push(child);
93    }
94
95    #[inline(always)]
96    fn node_from_id(&self, node_id: NodeId) -> &Node {
97        &self.nodes[usize::from(node_id)]
98    }
99
100    #[inline(always)]
101    fn node_from_id_mut(&mut self, node_id: NodeId) -> &mut Node {
102        &mut self.nodes[usize::from(node_id)]
103    }
104
105    pub fn compute_layout(&mut self, root: usize, available_space: Size<AvailableSpace>, use_rounding: bool) {
106        compute_root_layout(self, NodeId::from(root), available_space);
107        if use_rounding {
108            round_layout(self, NodeId::from(root))
109        }
110    }
111
112    pub fn print_tree(&mut self, root: usize) {
113        print_tree(self, NodeId::from(root));
114    }
115}
116
117struct ChildIter<'a>(std::slice::Iter<'a, usize>);
118impl Iterator for ChildIter<'_> {
119    type Item = NodeId;
120    fn next(&mut self) -> Option<Self::Item> {
121        self.0.next().copied().map(NodeId::from)
122    }
123}
124
125impl takia::TraversePartialTree for Tree {
126    type ChildIter<'a> = ChildIter<'a>;
127
128    fn child_ids(&self, node_id: NodeId) -> Self::ChildIter<'_> {
129        ChildIter(self.node_from_id(node_id).children.iter())
130    }
131
132    fn child_count(&self, node_id: NodeId) -> usize {
133        self.node_from_id(node_id).children.len()
134    }
135
136    fn get_child_id(&self, node_id: NodeId, index: usize) -> NodeId {
137        NodeId::from(self.node_from_id(node_id).children[index])
138    }
139}
140
141impl takia::TraverseTree for Tree {}
142
143impl takia::LayoutPartialTree for Tree {
144    type CustomIdent = String;
145
146    type CoreContainerStyle<'a>
147        = &'a Style
148    where
149        Self: 'a;
150
151    fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
152        &self.node_from_id(node_id).style
153    }
154
155    fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
156        self.node_from_id_mut(node_id).unrounded_layout = *layout;
157    }
158
159    fn resolve_calc_value(&self, _val: *const (), _basis: f32) -> f32 {
160        0.0
161    }
162
163    fn compute_child_layout(&mut self, node_id: NodeId, inputs: takia::tree::LayoutInput) -> takia::tree::LayoutOutput {
164        compute_cached_layout(self, node_id, inputs, |tree, node_id, inputs| {
165            let node = &mut tree.nodes[usize::from(node_id)];
166            let font_metrics = FontMetrics { char_width: 10.0, char_height: 10.0 };
167
168            let mut output = match node.kind {
169                NodeKind::Flexbox => compute_flexbox_layout(tree, node_id, inputs),
170                NodeKind::Grid => compute_grid_layout(tree, node_id, inputs),
171                NodeKind::Text => compute_leaf_layout(
172                    inputs,
173                    &node.style,
174                    |_val, _basis| 0.0,
175                    |known_dimensions, available_space| {
176                        text_measure_function(
177                            known_dimensions,
178                            available_space,
179                            node.text_data.as_ref().unwrap(),
180                            &font_metrics,
181                        )
182                    },
183                ),
184                NodeKind::Image => compute_leaf_layout(
185                    inputs,
186                    &node.style,
187                    |_val, _basis| 0.0,
188                    |known_dimensions, _available_space| {
189                        image_measure_function(known_dimensions, node.image_data.as_ref().unwrap())
190                    },
191                ),
192            };
193
194            // Lay out any out-of-flow (absolute/fixed) boxes for which this node is the containing block
195            if inputs.run_mode == takia::RunMode::PerformLayout {
196                compute_oof_layout(tree, node_id, &mut output);
197            }
198
199            output
200        })
201    }
202}
203
204impl takia::LayoutContainingBlock for Tree {
205    type OofItemStyle<'a>
206        = &'a Style
207    where
208        Self: 'a;
209
210    fn get_oof_item_style(&self, node_id: NodeId) -> Self::OofItemStyle<'_> {
211        &self.node_from_id(node_id).style
212    }
213
214    fn clear_hoisted_children(&mut self, node_id: NodeId) {
215        self.node_from_id_mut(node_id).hoisted_children.clear();
216    }
217
218    fn add_hoisted_children(&mut self, node_id: NodeId, hoisted: &[NodeId]) {
219        self.node_from_id_mut(node_id).hoisted_children.extend_from_slice(hoisted);
220    }
221}
222
223impl CacheTree for Tree {
224    fn cache_get(&mut self, node_id: NodeId, inputs: &takia::LayoutInput) -> Option<takia::LayoutOutput> {
225        self.node_from_id_mut(node_id).cache.get(inputs)
226    }
227
228    fn cache_store(&mut self, node_id: NodeId, inputs: &takia::LayoutInput, layout_output: takia::LayoutOutput) {
229        self.node_from_id_mut(node_id).cache.store(inputs, layout_output)
230    }
231
232    fn cache_clear(&mut self, node_id: NodeId) {
233        self.node_from_id_mut(node_id).cache.clear();
234    }
235}
236
237impl takia::LayoutFlexboxContainer for Tree {
238    type FlexboxContainerStyle<'a>
239        = &'a Style
240    where
241        Self: 'a;
242
243    type FlexboxItemStyle<'a>
244        = &'a Style
245    where
246        Self: 'a;
247
248    fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
249        &self.node_from_id(node_id).style
250    }
251
252    fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
253        &self.node_from_id(child_node_id).style
254    }
255}
256
257impl takia::LayoutGridContainer for Tree {
258    type GridContainerStyle<'a>
259        = &'a Style
260    where
261        Self: 'a;
262
263    type GridItemStyle<'a>
264        = &'a Style
265    where
266        Self: 'a;
267
268    fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
269        &self.node_from_id(node_id).style
270    }
271
272    fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
273        &self.node_from_id(child_node_id).style
274    }
275}
276
277impl takia::RoundTree for Tree {
278    fn get_unrounded_layout(&self, node_id: NodeId) -> Layout {
279        self.node_from_id(node_id).unrounded_layout
280    }
281
282    fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
283        self.node_from_id_mut(node_id).final_layout = *layout;
284    }
285
286    fn is_out_of_flow(&self, node_id: NodeId) -> bool {
287        self.node_from_id(node_id).style.position.is_out_of_flow()
288    }
289
290    fn hoisted_child_count(&self, node_id: NodeId) -> usize {
291        self.node_from_id(node_id).hoisted_children.len()
292    }
293
294    fn get_hoisted_child_id(&self, node_id: NodeId, index: usize) -> NodeId {
295        self.node_from_id(node_id).hoisted_children[index]
296    }
297}
298
299impl takia::PrintTree for Tree {
300    fn get_debug_label(&self, node_id: NodeId) -> &'static str {
301        match self.node_from_id(node_id).kind {
302            NodeKind::Flexbox => "FLEX",
303            NodeKind::Grid => "GRID",
304            NodeKind::Text => "TEXT",
305            NodeKind::Image => "IMAGE",
306        }
307    }
308
309    fn get_final_layout(&self, node_id: NodeId) -> Layout {
310        self.node_from_id(node_id).final_layout
311    }
312}
313
314fn main() -> Result<(), takia::TakiaError> {
315    let mut tree = Tree::new();
316
317    let root = Node::new_column(Style::DEFAULT);
318    let root_id = tree.add_node(root);
319
320    let text_node = Node::new_text(
321        Style::default(),
322        TextContext { text_content: LOREM_IPSUM.into(), writing_mode: WritingMode::Horizontal },
323    );
324    let text_node_id = tree.add_node(text_node);
325    tree.append_child(root_id, text_node_id);
326
327    let image_node = Node::new_image(Style::default(), ImageContext { width: 400.0, height: 300.0 });
328    let image_node_id = tree.add_node(image_node);
329    tree.append_child(root_id, image_node_id);
330
331    // Compute layout and print result
332    tree.compute_layout(root_id, Size::MAX_CONTENT, true);
333    tree.print_tree(root_id);
334
335    Ok(())
336}