1use std::{
2 collections::{
3 HashMap,
4 HashSet,
5 },
6 sync::Arc,
7 time::Duration,
8};
9
10use freya::prelude::*;
11use freya_core::integration::NodeId;
12use freya_devtools::{
13 IncomingMessage,
14 IncomingMessageAction,
15 OutgoingMessage,
16 OutgoingMessageAction,
17};
18use freya_radio::prelude::*;
19use freya_router::prelude::*;
20use futures_util::StreamExt;
21use smol::{
22 Timer,
23 net::TcpStream,
24};
25use state::{
26 DevtoolsChannel,
27 DevtoolsState,
28};
29
30mod components;
31mod hooks;
32mod node;
33mod property;
34mod state;
35mod tabs;
36
37use async_tungstenite::tungstenite::protocol::Message;
38use hooks::use_node_info;
39use tabs::{
40 computed_layout::computed_layout,
41 layout::*,
42 misc::*,
43 style::*,
44 text_style::*,
45 tree::*,
46};
47
48fn main() {
49 launch(
50 LaunchConfig::new().with_window(
51 WindowConfig::new(app)
52 .with_title("Freya Devtools")
53 .with_size(1200., 700.),
54 ),
55 )
56}
57
58pub fn app() -> impl IntoElement {
59 use_init_root_theme(|| DARK_THEME);
60 use_init_radio_station::<DevtoolsState, DevtoolsChannel>(|| DevtoolsState {
61 nodes: HashMap::new(),
62 expanded_nodes: HashSet::default(),
63 client: Arc::default(),
64 animation_speed: AnimationClock::DEFAULT_SPEED / AnimationClock::MAX_SPEED * 100.,
65 });
66 let mut radio = use_radio(DevtoolsChannel::Global);
67
68 use_hook(move || {
69 spawn(async move {
70 async fn connect(
71 mut radio: Radio<DevtoolsState, DevtoolsChannel>,
72 ) -> Result<(), tungstenite::Error> {
73 let tcp_stream = TcpStream::connect("[::1]:7354").await?;
74 let (ws_stream, _response) =
75 async_tungstenite::client_async("ws://[::1]:7354", tcp_stream).await?;
76
77 let (write, read) = ws_stream.split();
78
79 radio.write_silently().client.lock().await.replace(write);
80
81 read.for_each(move |message| async move {
82 if let Ok(message) = message
83 && let Ok(text) = message.into_text()
84 && let Ok(outgoing) = serde_json::from_str::<OutgoingMessage>(&text)
85 {
86 match outgoing.action {
87 OutgoingMessageAction::Update { window_id, nodes } => {
88 radio
89 .write_channel(DevtoolsChannel::UpdatedTree)
90 .nodes
91 .insert(window_id, nodes);
92 }
93 }
94 }
95 })
96 .await;
97
98 Ok(())
99 }
100
101 loop {
102 println!("Connecting to server...");
103 connect(radio).await.ok();
104 radio
105 .write_channel(DevtoolsChannel::UpdatedTree)
106 .nodes
107 .clear();
108 Timer::after(Duration::from_secs(2)).await;
109 }
110 })
111 });
112
113 rect()
114 .width(Size::fill())
115 .height(Size::fill())
116 .color(Color::WHITE)
117 .background((15, 15, 15))
118 .child(router(|| {
119 RouterConfig::<Route>::default().with_initial_path(Route::TreeInspector {})
120 }))
121}
122
123#[derive(PartialEq)]
124struct NavBar;
125impl Component for NavBar {
126 fn render(&self) -> impl IntoElement {
127 SideBar::new()
128 .width(Size::px(100.))
129 .bar(
130 rect()
131 .child(ActivableRoute::new(
132 Route::TreeInspector {},
133 Link::new(Route::TreeInspector {}).child(SideBarItem::new().child("Tree")),
134 ))
135 .child(ActivableRoute::new(
136 Route::Misc {},
137 Link::new(Route::Misc {}).child(SideBarItem::new().child("Misc")),
138 )),
139 )
140 .content(rect().padding(Gaps::new_all(8.)).child(outlet::<Route>()))
141 }
142}
143#[derive(Routable, Clone, PartialEq, Debug)]
144#[rustfmt::skip]
145pub enum Route {
146 #[layout(NavBar)]
147 #[route("/misc")]
148 Misc {},
149 #[layout(LayoutForTreeInspector)]
150 #[nest("/inspector")]
151 #[route("/")]
152 TreeInspector {},
153 #[nest("/node/:node_id/:window_id")]
154 #[layout(LayoutForNodeInspector)]
155 #[route("/style")]
156 NodeInspectorStyle { node_id: NodeId, window_id: u64 },
157 #[route("/layout")]
158 NodeInspectorLayout { node_id: NodeId, window_id: u64 },
159 #[route("/text-style")]
160 NodeInspectorTextStyle { node_id: NodeId, window_id: u64 },
161}
162
163impl Route {
164 pub fn node_id(&self) -> Option<NodeId> {
165 match self {
166 Self::NodeInspectorStyle { node_id, .. }
167 | Self::NodeInspectorLayout { node_id, .. }
168 | Self::NodeInspectorTextStyle { node_id, .. } => Some(*node_id),
169 _ => None,
170 }
171 }
172
173 pub fn window_id(&self) -> Option<u64> {
174 match self {
175 Self::NodeInspectorStyle { window_id, .. }
176 | Self::NodeInspectorLayout { window_id, .. }
177 | Self::NodeInspectorTextStyle { window_id, .. } => Some(*window_id),
178 _ => None,
179 }
180 }
181}
182
183#[derive(PartialEq, Clone, Copy)]
184struct LayoutForNodeInspector {
185 window_id: u64,
186 node_id: NodeId,
187}
188
189impl Component for LayoutForNodeInspector {
190 fn render(&self) -> impl IntoElement {
191 let LayoutForNodeInspector { window_id, node_id } = *self;
192
193 let Some(node_info) = use_node_info(node_id, window_id) else {
194 return rect();
195 };
196
197 let inner_area = format!(
198 "{}x{}",
199 node_info.inner_area.width().round(),
200 node_info.inner_area.height().round()
201 );
202 let area = format!(
203 "{}x{}",
204 node_info.area.width().round(),
205 node_info.area.height().round()
206 );
207 let padding = node_info.state.layout.padding;
208 let margin = node_info.state.layout.margin;
209
210 rect()
211 .expanded()
212 .child(
213 ScrollView::new()
214 .show_scrollbar(false)
215 .height(Size::px(280.))
216 .child(
217 rect()
218 .padding(16.)
219 .width(Size::fill())
220 .cross_align(Alignment::Center)
221 .child(
222 rect()
223 .width(Size::fill())
224 .max_width(Size::px(300.))
225 .spacing(6.)
226 .child(
227 rect()
228 .horizontal()
229 .spacing(6.)
230 .child(
231 paragraph()
232 .max_lines(1)
233 .height(Size::px(20.))
234 .span(Span::new(area))
235 .span(
236 Span::new(" area").color((200, 200, 200)),
237 ),
238 )
239 .child(
240 paragraph()
241 .max_lines(1)
242 .height(Size::px(20.))
243 .span(Span::new(
244 node_info.children_len.to_string(),
245 ))
246 .span(
247 Span::new(" children")
248 .color((200, 200, 200)),
249 ),
250 )
251 .child(
252 paragraph()
253 .max_lines(1)
254 .height(Size::px(20.))
255 .span(Span::new(node_info.layer.to_string()))
256 .span(
257 Span::new(" layer").color((200, 200, 200)),
258 ),
259 ),
260 )
261 .child(computed_layout(inner_area, padding, margin)),
262 ),
263 ),
264 )
265 .child(
266 ScrollView::new()
267 .show_scrollbar(false)
268 .height(Size::auto())
269 .child(
270 rect()
271 .direction(Direction::Horizontal)
272 .padding((0., 4.))
273 .child(ActivableRoute::new(
274 Route::NodeInspectorStyle { node_id, window_id },
275 Link::new(Route::NodeInspectorStyle { node_id, window_id }).child(
276 FloatingTab::new().child(label().text("Style").max_lines(1)),
277 ),
278 ))
279 .child(ActivableRoute::new(
280 Route::NodeInspectorLayout { node_id, window_id },
281 Link::new(Route::NodeInspectorLayout { node_id, window_id }).child(
282 FloatingTab::new().child(label().text("Layout").max_lines(1)),
283 ),
284 ))
285 .child(ActivableRoute::new(
286 Route::NodeInspectorTextStyle { node_id, window_id },
287 Link::new(Route::NodeInspectorTextStyle { node_id, window_id })
288 .child(
289 FloatingTab::new()
290 .child(label().text("Text Style").max_lines(1)),
291 ),
292 )),
293 ),
294 )
295 .child(rect().padding((6., 0.)).child(outlet::<Route>()))
296 }
297}
298
299#[derive(PartialEq)]
300struct LayoutForTreeInspector;
301
302impl Component for LayoutForTreeInspector {
303 fn render(&self) -> impl IntoElement {
304 let route = use_route::<Route>();
305 let radio = use_radio(DevtoolsChannel::Global);
306
307 let selected_node_id = route.node_id();
308 let selected_window_id = route.window_id();
309
310 let is_expanded_vertical = selected_node_id.is_some();
311
312 ResizableContainer::new()
313 .direction(Direction::Horizontal)
314 .panel(
315 ResizablePanel::new(60.).child(rect().padding(10.).child(NodesTree {
316 selected_node_id,
317 selected_window_id,
318 on_selected: EventHandler::new(move |(window_id, node_id)| {
319 let message = Message::Text(
320 serde_json::to_string(&IncomingMessage {
321 action: IncomingMessageAction::HighlightNode { window_id, node_id },
322 })
323 .unwrap()
324 .into(),
325 );
326 let client = radio.read().client.clone();
327 spawn(async move {
328 client
329 .lock()
330 .await
331 .as_mut()
332 .unwrap()
333 .send(message)
334 .await
335 .ok();
336 });
337 }),
338 on_hover: EventHandler::new(move |(window_id, node_id)| {
339 let message = Message::Text(
340 serde_json::to_string(&IncomingMessage {
341 action: IncomingMessageAction::HoverNode { window_id, node_id },
342 })
343 .unwrap()
344 .into(),
345 );
346 let client = radio.read().client.clone();
347 spawn(async move {
348 client
349 .lock()
350 .await
351 .as_mut()
352 .unwrap()
353 .send(message)
354 .await
355 .ok();
356 });
357 }),
358 })),
359 )
360 .panel(is_expanded_vertical.then(|| ResizablePanel::new(40.).child(outlet::<Route>())))
361 }
362}
363
364#[derive(PartialEq)]
365struct TreeInspector;
366
367impl Component for TreeInspector {
368 fn render(&self) -> impl IntoElement {
369 rect()
370 }
371}