Skip to main content

custom_tree_owned_partial/
custom_tree_owned_partial.rs

1//! ## Example: Partial Tree with Directly Owned Children
2//!
3//! The following example demonstrate an implementation of Takia'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 takia::{
15    compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_leaf_layout, compute_oof_layout,
16    compute_root_layout, 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    hoisted_children: Vec<NodeId>,
37}
38
39impl Default for Node {
40    fn default() -> Self {
41        Node {
42            kind: NodeKind::Flexbox,
43            style: Style::default(),
44            text_data: None,
45            image_data: None,
46            cache: Cache::new(),
47            layout: Layout::with_order(0),
48            children: Vec::new(),
49            hoisted_children: Vec::new(),
50        }
51    }
52}
53
54#[allow(dead_code)]
55impl Node {
56    pub fn new_row(style: Style) -> Node {
57        Node {
58            kind: NodeKind::Flexbox,
59            style: Style { display: Display::Flex, flex_direction: FlexDirection::Row, ..style },
60            ..Node::default()
61        }
62    }
63    pub fn new_column(style: Style) -> Node {
64        Node {
65            kind: NodeKind::Flexbox,
66            style: Style { display: Display::Flex, flex_direction: FlexDirection::Column, ..style },
67            ..Node::default()
68        }
69    }
70    pub fn new_grid(style: Style) -> Node {
71        Node { kind: NodeKind::Grid, style: Style { display: Display::Grid, ..style }, ..Node::default() }
72    }
73    pub fn new_text(style: Style, text_data: TextContext) -> Node {
74        Node { kind: NodeKind::Text, style, text_data: Some(text_data), ..Node::default() }
75    }
76    pub fn new_image(style: Style, image_data: ImageContext) -> Node {
77        Node { kind: NodeKind::Image, style, image_data: Some(image_data), ..Node::default() }
78    }
79    pub fn append_child(&mut self, node: Node) {
80        self.children.push(node);
81    }
82
83    pub fn compute_layout(&mut self, available_space: Size<AvailableSpace>) {
84        compute_root_layout(self, NodeId::from(usize::MAX), available_space);
85    }
86
87    /// The methods on LayoutPartialTree need to be able to access:
88    ///
89    ///  - The node being laid out
90    ///  - Direct children of the node being laid out
91    ///
92    /// Each must have an ID. For children we simply use it's index. For the node itself
93    /// we use usize::MAX on the assumption that there will never be that many children.
94    fn node_from_id(&self, node_id: NodeId) -> &Node {
95        let idx = usize::from(node_id);
96        if idx == usize::MAX {
97            self
98        } else {
99            &self.children[idx]
100        }
101    }
102
103    fn node_from_id_mut(&mut self, node_id: NodeId) -> &mut Node {
104        let idx = usize::from(node_id);
105        if idx == usize::MAX {
106            self
107        } else {
108            &mut self.children[idx]
109        }
110    }
111}
112
113struct ChildIter(std::ops::Range<usize>);
114impl Iterator for ChildIter {
115    type Item = NodeId;
116    fn next(&mut self) -> Option<Self::Item> {
117        self.0.next().map(NodeId::from)
118    }
119}
120
121impl takia::TraversePartialTree for Node {
122    type ChildIter<'a> = ChildIter;
123
124    fn child_ids(&self, _node_id: NodeId) -> Self::ChildIter<'_> {
125        ChildIter(0..self.children.len())
126    }
127
128    fn child_count(&self, _node_id: NodeId) -> usize {
129        self.children.len()
130    }
131
132    fn get_child_id(&self, _node_id: NodeId, index: usize) -> NodeId {
133        NodeId::from(index)
134    }
135}
136
137impl takia::LayoutPartialTree for Node {
138    type CoreContainerStyle<'a>
139        = &'a Style
140    where
141        Self: 'a;
142
143    type CustomIdent = String;
144
145    fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
146        &self.node_from_id(node_id).style
147    }
148
149    fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
150        self.node_from_id_mut(node_id).layout = *layout
151    }
152
153    fn resolve_calc_value(&self, _val: *const (), _basis: f32) -> f32 {
154        0.0
155    }
156
157    fn compute_child_layout(&mut self, node_id: NodeId, inputs: takia::tree::LayoutInput) -> takia::tree::LayoutOutput {
158        compute_cached_layout(self, node_id, inputs, |parent, node_id, inputs| {
159            let node = parent.node_from_id_mut(node_id);
160            let font_metrics = FontMetrics { char_width: 10.0, char_height: 10.0 };
161
162            let mut output = match node.kind {
163                NodeKind::Flexbox => compute_flexbox_layout(node, node_id, inputs),
164                NodeKind::Grid => compute_grid_layout(node, node_id, inputs),
165                NodeKind::Text => compute_leaf_layout(
166                    inputs,
167                    &node.style,
168                    |_val, _basis| 0.0,
169                    |known_dimensions, available_space| {
170                        text_measure_function(
171                            known_dimensions,
172                            available_space,
173                            node.text_data.as_ref().unwrap(),
174                            &font_metrics,
175                        )
176                    },
177                ),
178                NodeKind::Image => compute_leaf_layout(
179                    inputs,
180                    &node.style,
181                    |_val, _basis| 0.0,
182                    |known_dimensions, _available_space| {
183                        image_measure_function(known_dimensions, node.image_data.as_ref().unwrap())
184                    },
185                ),
186            };
187
188            // Lay out any out-of-flow (absolute/fixed) boxes for which this node is the containing block
189            if inputs.run_mode == takia::RunMode::PerformLayout {
190                compute_oof_layout(node, node_id, &mut output);
191            }
192
193            output
194        })
195    }
196}
197
198impl takia::LayoutContainingBlock for Node {
199    type OofItemStyle<'a>
200        = &'a Style
201    where
202        Self: 'a;
203
204    fn get_oof_item_style(&self, node_id: NodeId) -> Self::OofItemStyle<'_> {
205        &self.node_from_id(node_id).style
206    }
207
208    fn clear_hoisted_children(&mut self, node_id: NodeId) {
209        self.node_from_id_mut(node_id).hoisted_children.clear();
210    }
211
212    fn add_hoisted_children(&mut self, node_id: NodeId, hoisted: &[NodeId]) {
213        self.node_from_id_mut(node_id).hoisted_children.extend_from_slice(hoisted);
214    }
215}
216
217impl CacheTree for Node {
218    fn cache_get(&mut self, node_id: NodeId, inputs: &takia::LayoutInput) -> Option<takia::LayoutOutput> {
219        self.node_from_id_mut(node_id).cache.get(inputs)
220    }
221
222    fn cache_store(&mut self, node_id: NodeId, inputs: &takia::LayoutInput, layout_output: takia::LayoutOutput) {
223        self.node_from_id_mut(node_id).cache.store(inputs, layout_output)
224    }
225
226    fn cache_clear(&mut self, node_id: NodeId) {
227        self.node_from_id_mut(node_id).cache.clear();
228    }
229}
230
231impl takia::LayoutFlexboxContainer for Node {
232    type FlexboxContainerStyle<'a>
233        = &'a Style
234    where
235        Self: 'a;
236
237    type FlexboxItemStyle<'a>
238        = &'a Style
239    where
240        Self: 'a;
241
242    fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
243        &self.node_from_id(node_id).style
244    }
245
246    fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
247        &self.node_from_id(child_node_id).style
248    }
249}
250
251impl takia::LayoutGridContainer for Node {
252    type GridContainerStyle<'a>
253        = &'a Style
254    where
255        Self: 'a;
256
257    type GridItemStyle<'a>
258        = &'a Style
259    where
260        Self: 'a;
261
262    fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
263        &self.node_from_id(node_id).style
264    }
265
266    fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
267        &self.node_from_id(child_node_id).style
268    }
269}
270
271fn main() -> Result<(), takia::TakiaError> {
272    let mut root = Node::new_column(Style::DEFAULT);
273
274    let text_node = Node::new_text(
275        Style::default(),
276        TextContext { text_content: LOREM_IPSUM.into(), writing_mode: WritingMode::Horizontal },
277    );
278    root.append_child(text_node);
279
280    let image_node = Node::new_image(Style::default(), ImageContext { width: 400.0, height: 300.0 });
281    root.append_child(image_node);
282
283    // Compute layout
284    root.compute_layout(Size::MAX_CONTENT);
285
286    Ok(())
287}