1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use std::vec::IntoIter;

use dioxus_native_core::prelude::ElementNode;
use dioxus_native_core::real_dom::NodeImmutable;
use dioxus_native_core::tree::TreeRef;
use dioxus_native_core::{node::NodeType, NodeId};
use freya_common::NodeReferenceLayout;
use freya_dom::dom::DioxusNode;
use freya_dom::prelude::{DioxusDOM, FreyaDOM};
use itertools::sorted;

use freya_engine::prelude::*;
use freya_node_state::{CursorMode, CursorSettings, LayoutState, References, Style};
use rustc_hash::FxHashMap;
use torin::torin::Torin;
use uuid::Uuid;

use crate::layout::*;

fn traverse_dom(rdom: &DioxusDOM, mut f: impl FnMut(DioxusNode) -> bool) {
    let mut stack = vec![rdom.root_id()];
    let tree = rdom.tree_ref();
    while let Some(id) = stack.pop() {
        if let Some(node) = rdom.get(id) {
            let traverse_children = f(node);
            if traverse_children {
                let children = tree.children_ids_advanced(id, true);
                stack.extend(children.iter().copied().rev());
            }
        }
    }
}

#[derive(Default, Clone)]
pub struct Layers {
    pub layers: FxHashMap<i16, Vec<NodeId>>,
    pub paragraph_elements: FxHashMap<Uuid, Vec<NodeId>>,
}

impl Layers {
    pub fn new(
        rdom: &DioxusDOM,
        layout: &Torin<NodeId>,
        font_collection: &FontCollection,
        scale_factor: f32,
    ) -> Self {
        let mut layers = Layers::default();
        let mut inherit_layers = FxHashMap::default();

        traverse_dom(rdom, |node| {
            let areas = layout.get(node.id());

            // Some elements like placeholders are not measured
            if let Some(areas) = areas {
                // Add the Node to a Layer
                let node_style = node.get::<Style>().unwrap();

                let inherited_relative_layer = node
                    .parent_id()
                    .map(|p| *inherit_layers.get(&p).unwrap())
                    .unwrap_or(0);

                let (node_layer, node_relative_layer) = Layers::calculate_layer(
                    node_style.relative_layer,
                    node.height() as i16,
                    inherited_relative_layer,
                );

                inherit_layers.insert(node.id(), node_relative_layer);
                layers.add_element(node.id(), node_layer);

                // Register paragraph elements

                let traverse_inner_children =
                    if let NodeType::Element(ElementNode { tag, .. }) = &*node.node_type() {
                        let is_paragraph = tag == "paragraph";
                        if is_paragraph {
                            let cursor_settings = node.get::<CursorSettings>().unwrap();
                            let is_editable = CursorMode::Editable == cursor_settings.mode;

                            let references = node.get::<References>().unwrap();
                            if is_editable {
                                if let Some(cursor_ref) = &references.cursor_ref {
                                    let text_group = layers
                                        .paragraph_elements
                                        .entry(cursor_ref.text_id)
                                        .or_default();

                                    text_group.push(node.id());
                                }
                            }
                        }

                        // Traverse all elements except paragraphs
                        !is_paragraph
                    } else {
                        false
                    };

                // Notify layout references

                let size_state = &*node.get::<LayoutState>().unwrap();

                if let Some(reference) = &size_state.node_ref {
                    let mut node_layout = NodeReferenceLayout {
                        area: areas.area,
                        inner: areas.inner_sizes,
                    };
                    node_layout.div(scale_factor);
                    reference.send(node_layout).ok();
                }

                traverse_inner_children
            } else {
                false
            }
        });

        layers.measure_all_paragraph_elements(rdom, layout, font_collection, scale_factor);

        layers
    }

    pub fn layers(&self) -> IntoIter<(&i16, &Vec<NodeId>)> {
        sorted(self.layers.iter())
    }

    pub fn len_paragraph_elements(&self) -> usize {
        self.paragraph_elements.len()
    }

    pub fn len_layers(&self) -> usize {
        self.layers.len()
    }

    /// Measure all the paragraphs
    pub fn measure_all_paragraph_elements(
        &self,
        rdom: &DioxusDOM,
        layout: &Torin<NodeId>,
        font_collection: &FontCollection,
        scale_factor: f32,
    ) {
        for group in self.paragraph_elements.values() {
            for node_id in group {
                let node = rdom.get(*node_id);
                let areas = layout.get(*node_id);
                if let Some((node, areas)) = node.zip(areas) {
                    measure_paragraph(&node, &areas.area, font_collection, true, scale_factor);
                }
            }
        }
    }

    /// Measure all the paragraphs registered under the given TextId
    pub fn measure_paragraph_elements(
        &self,
        text_id: &Uuid,
        dom: &FreyaDOM,
        font_collection: &FontCollection,
        scale_factor: f32,
    ) {
        let group = self.paragraph_elements.get(text_id);
        let layout = dom.layout();
        if let Some(group) = group {
            for node_id in group {
                let node = dom.rdom().get(*node_id);
                let areas = layout.get(*node_id);

                if let Some((node, areas)) = node.zip(areas) {
                    measure_paragraph(&node, &areas.area, font_collection, true, scale_factor);
                }
            }
        }
    }

    /// Given the height in the DOM of the Node, it's inherited layer from it's parent
    /// and the defined layer via the `layer` attribute,
    /// calculate it's corresponding layer and it's relative layer for it's children to inherit
    pub fn calculate_layer(
        relative_layer: i16,
        height: i16,
        inherited_relative_layer: i16,
    ) -> (i16, i16) {
        let element_layer = -relative_layer + height - inherited_relative_layer;
        (element_layer, relative_layer + inherited_relative_layer)
    }

    /// Insert a Node into a layer
    pub fn add_element(&mut self, node_id: NodeId, node_layer: i16) {
        let layer = self.layers.entry(node_layer).or_default();

        layer.push(node_id);
    }
}