dioxus_devtools/
lib.rs

1use dioxus_core::{ScopeId, VirtualDom};
2pub use dioxus_devtools_types::*;
3use dioxus_signals::{GlobalKey, Writable};
4use warnings::Warning;
5
6/// Applies template and literal changes to the VirtualDom
7///
8/// Assets need to be handled by the renderer.
9pub fn apply_changes(dom: &VirtualDom, msg: &HotReloadMsg) {
10    dom.runtime().on_scope(ScopeId::ROOT, || {
11        let ctx = dioxus_signals::get_global_context();
12
13        for template in &msg.templates {
14            let value = template.template.clone();
15            let key = GlobalKey::File {
16                file: template.key.file.as_str(),
17                line: template.key.line as _,
18                column: template.key.column as _,
19                index: template.key.index as _,
20            };
21            if let Some(mut signal) = ctx.get_signal_with_key(key.clone()) {
22                dioxus_signals::warnings::signal_read_and_write_in_reactive_scope::allow(|| {
23                    dioxus_signals::warnings::signal_write_in_component_body::allow(|| {
24                        signal.set(Some(value));
25                    });
26                });
27            }
28        }
29    });
30}
31
32/// Connect to the devserver and handle its messages with a callback.
33///
34/// This doesn't use any form of security or protocol, so it's not safe to expose to the internet.
35#[cfg(not(target_arch = "wasm32"))]
36pub fn connect(endpoint: String, mut callback: impl FnMut(DevserverMsg) + Send + 'static) {
37    std::thread::spawn(move || {
38        let (mut websocket, _req) = match tungstenite::connect(endpoint.clone()) {
39            Ok((websocket, req)) => (websocket, req),
40            Err(_) => return,
41        };
42
43        while let Ok(msg) = websocket.read() {
44            if let tungstenite::Message::Text(text) = msg {
45                if let Ok(msg) = serde_json::from_str(&text) {
46                    callback(msg);
47                }
48            }
49        }
50    });
51}