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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
use std::collections::HashSet;

use dioxus::prelude::*;
use dioxus_radio::prelude::*;
use dioxus_router::prelude::{
    use_route,
    Outlet,
    Routable,
    Router,
};
use freya_components::*;
use freya_core::prelude::EventMessage;
use freya_elements::elements as dioxus_elements;
use freya_hooks::{
    use_applied_theme,
    use_init_theme,
    use_platform,
    DARK_THEME,
};
use freya_native_core::NodeId;
use freya_renderer::{
    devtools::DevtoolsReceiver,
    HoveredNode,
};
use state::{
    DevtoolsChannel,
    DevtoolsState,
};

mod hooks;
mod node;
mod property;
mod state;
mod tabs;

use tabs::{
    layout::*,
    style::*,
    tree::*,
};

/// Run the [`VirtualDom`] with a sidepanel where the devtools are located.
pub fn with_devtools(
    root: fn() -> Element,
    devtools_receiver: DevtoolsReceiver,
    hovered_node: HoveredNode,
) -> VirtualDom {
    VirtualDom::new_with_props(
        AppWithDevtools,
        AppWithDevtoolsProps {
            root,
            devtools_receiver,
            hovered_node,
        },
    )
}

#[derive(Props, Clone)]
struct AppWithDevtoolsProps {
    root: fn() -> Element,
    devtools_receiver: DevtoolsReceiver,
    hovered_node: HoveredNode,
}

impl PartialEq for AppWithDevtoolsProps {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

#[allow(non_snake_case)]
fn AppWithDevtools(props: AppWithDevtoolsProps) -> Element {
    #[allow(non_snake_case)]
    let Root = props.root;
    let devtools_receiver = props.devtools_receiver;
    let hovered_node = props.hovered_node;

    rsx!(
        NativeContainer {
            ResizableContainer {
                direction: "horizontal",
                ResizablePanel {
                    initial_size: 75.,
                    Root { },
                }
                ResizableHandle { }
                ResizablePanel {
                    initial_size: 25.,
                    min_size: 10.,
                    rect {
                        background: "rgb(40, 40, 40)",
                        height: "fill",
                        width: "fill",
                        ThemeProvider {
                            DevTools {
                                devtools_receiver,
                                hovered_node
                            }
                        }
                    }
                }
            }
        }
    )
}

#[derive(Props, Clone)]
pub struct DevToolsProps {
    devtools_receiver: DevtoolsReceiver,
    hovered_node: HoveredNode,
}

impl PartialEq for DevToolsProps {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

#[allow(non_snake_case)]
pub fn DevTools(props: DevToolsProps) -> Element {
    use_init_theme(|| DARK_THEME);
    use_init_radio_station::<DevtoolsState, DevtoolsChannel>(|| DevtoolsState {
        hovered_node: props.hovered_node.clone(),
        devtools_receiver: props.devtools_receiver.clone(),
        devtools_tree: HashSet::default(),
    });

    let theme = use_applied_theme!(None, body);
    let color = &theme.color;

    rsx!(
        rect {
            width: "fill",
            height: "fill",
            color: "{color}",
            Router::<Route> { }
        }
    )
}

#[component]
#[allow(non_snake_case)]
pub fn DevtoolsBar() -> Element {
    rsx!(
        Tabsbar {
            Link {
                to: Route::DOMInspector { },
                ActivableRoute {
                    route: Route::DOMInspector { },
                    Tab {
                        label {
                            "Elements"
                        }
                    }
                }
            }
        }
        Outlet::<Route> {}
    )
}

#[derive(Routable, Clone, PartialEq)]
#[rustfmt::skip]
pub enum Route {
    #[layout(DevtoolsBar)]
        #[nest("/")]
            #[layout(LayoutForDOMInspector)]
                #[route("/")]
                DOMInspector  {},
                #[nest("/node/:node_id")]
                    #[layout(LayoutForNodeInspector)]
                        #[route("/style")]
                        NodeInspectorStyle { node_id: String },
                        #[route("/layout")]
                        NodeInspectorLayout { node_id: String },
                    #[end_layout]
                #[end_nest]
            #[end_layout]
        #[end_nest]
    #[end_layout]
    #[route("/..route")]
    PageNotFound { },
}

impl Route {
    pub fn get_node_id(&self) -> Option<NodeId> {
        match self {
            Self::NodeInspectorStyle { node_id } | Self::NodeInspectorLayout { node_id } => {
                Some(NodeId::deserialize(node_id))
            }
            _ => None,
        }
    }
}

#[allow(non_snake_case)]
#[component]
fn PageNotFound() -> Element {
    rsx!(
        label {
            "Page not found."
        }
    )
}

#[allow(non_snake_case)]
#[component]
fn LayoutForNodeInspector(node_id: String) -> Element {
    rsx!(
        rect {
            overflow: "clip",
            width: "100%",
            height: "50%",
            Tabsbar {
                Link {
                    to: Route::NodeInspectorStyle { node_id: node_id.clone() },
                    ActivableRoute {
                        route: Route::NodeInspectorStyle { node_id: node_id.clone() },
                        Tab {
                            label {
                                "Style"
                            }
                        }
                    }
                }
                Link {
                    to: Route::NodeInspectorLayout { node_id: node_id.clone() },
                    ActivableRoute {
                        route: Route::NodeInspectorLayout { node_id },
                        Tab {
                            label {
                                "Layout"
                            }
                        }
                    }
                }
            }
            Outlet::<Route> {}
        }
    )
}

#[allow(non_snake_case)]
#[component]
fn LayoutForDOMInspector() -> Element {
    let route = use_route::<Route>();
    let platform = use_platform();
    let mut radio = use_radio(DevtoolsChannel::Global);
    use_hook(move || {
        spawn(async move {
            let mut devtools_receiver = radio.read().devtools_receiver.clone();
            loop {
                devtools_receiver
                    .changed()
                    .await
                    .expect("Failed while waiting for DOM changes.");

                radio.write_channel(DevtoolsChannel::UpdatedDOM);
            }
        });
    });

    let selected_node_id = route.get_node_id();

    let is_expanded_vertical = selected_node_id.is_some();

    let height = if is_expanded_vertical {
        "calc(50% - 35)"
    } else {
        "fill"
    };

    rsx!(
        NodesTree {
            height,
            selected_node_id,
            onselected: move |node_id: NodeId| {
                if let Some(hovered_node) = &radio.read().hovered_node.as_ref() {
                    hovered_node.lock().unwrap().replace(node_id);
                    platform.send(EventMessage::RequestFullRerender).ok();
                }
            }
        }
        Outlet::<Route> {}
    )
}

#[allow(non_snake_case)]
#[component]
fn DOMInspector() -> Element {
    None
}

pub trait NodeIdSerializer {
    fn serialize(&self) -> String;

    fn deserialize(node_id: &str) -> Self;
}

impl NodeIdSerializer for NodeId {
    fn serialize(&self) -> String {
        format!("{}-{}", self.index(), self.gen())
    }

    fn deserialize(node_id: &str) -> Self {
        let (index, gen) = node_id.split_once('-').unwrap();
        NodeId::new_from_index_and_gen(index.parse().unwrap(), gen.parse().unwrap())
    }
}