use std::fmt::Display;
use std::time::Duration;
use dioxus_core::ScopeId;
use dioxus_hot_reload::{DevserverMsg, HotReloadMsg};
use dioxus_html::prelude::eval;
use futures_channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use js_sys::JsString;
use wasm_bindgen::JsCast;
use wasm_bindgen::{closure::Closure, JsValue};
use web_sys::{window, CloseEvent, MessageEvent, WebSocket};
const POLL_INTERVAL_MIN: i32 = 250;
const POLL_INTERVAL_MAX: i32 = 4000;
const POLL_INTERVAL_SCALE_FACTOR: i32 = 2;
const TOAST_TIMEOUT: Duration = Duration::from_secs(5);
pub(crate) fn init() -> UnboundedReceiver<HotReloadMsg> {
let (tx, rx) = unbounded();
make_ws(tx, POLL_INTERVAL_MIN, false);
rx
}
fn make_ws(tx: UnboundedSender<HotReloadMsg>, poll_interval: i32, reload: bool) {
let location = web_sys::window().unwrap().location();
let url = format!(
"{protocol}//{host}/_dioxus",
protocol = match location.protocol().unwrap() {
prot if prot == "https:" => "wss:",
_ => "ws:",
},
host = location.host().unwrap(),
);
let ws = WebSocket::new(&url).unwrap();
let tx_ = tx.clone();
ws.set_onmessage(Some(
Closure::<dyn FnMut(MessageEvent)>::new(move |e: MessageEvent| {
let Ok(text) = e.data().dyn_into::<JsString>() else {
return;
};
let string: String = text.into();
let leaked: &'static str = Box::leak(Box::new(string));
match serde_json::from_str::<DevserverMsg>(leaked) {
Ok(DevserverMsg::HotReload(hr)) => _ = tx_.unbounded_send(hr),
Ok(DevserverMsg::Shutdown) => {
web_sys::console::error_1(&"Connection to the devserver was closed".into())
}
Ok(DevserverMsg::FullReloadStart) => show_toast(
"Your app is being rebuilt.",
"A non-hot-reloadable change occurred and we must rebuild.",
ToastLevel::Info,
TOAST_TIMEOUT,
false,
),
Ok(DevserverMsg::FullReloadFailed) => show_toast(
"Oops! The build failed.",
"We tried to rebuild your app, but something went wrong.",
ToastLevel::Error,
TOAST_TIMEOUT,
false,
),
Ok(DevserverMsg::FullReloadCommand) => {
show_toast(
"Successfully rebuilt.",
"Your app was rebuilt successfully and without error.",
ToastLevel::Success,
TOAST_TIMEOUT,
true,
);
window().unwrap().location().reload().unwrap()
}
Err(e) => web_sys::console::error_1(
&format!("Error parsing devserver message: {}", e).into(),
),
}
})
.into_js_value()
.as_ref()
.unchecked_ref(),
));
ws.set_onclose(Some(
Closure::<dyn FnMut(CloseEvent)>::new(move |e: CloseEvent| {
if e.code() == 1001 {
return;
}
let tx = tx.clone();
web_sys::window()
.unwrap()
.set_timeout_with_callback_and_timeout_and_arguments_0(
Closure::<dyn FnMut()>::new(move || {
make_ws(
tx.clone(),
POLL_INTERVAL_MAX.min(poll_interval * POLL_INTERVAL_SCALE_FACTOR),
true,
);
})
.into_js_value()
.as_ref()
.unchecked_ref(),
poll_interval,
)
.unwrap();
})
.into_js_value()
.as_ref()
.unchecked_ref(),
));
ws.set_onopen(Some(
Closure::<dyn FnMut(MessageEvent)>::new(move |_evt| {
if reload {
window().unwrap().location().reload().unwrap()
}
})
.into_js_value()
.as_ref()
.unchecked_ref(),
));
if !reload {
let ws: &JsValue = ws.as_ref();
dioxus_interpreter_js::minimal_bindings::monkeyPatchConsole(ws.clone());
}
}
enum ToastLevel {
Success,
Info,
Error,
}
impl Display for ToastLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ToastLevel::Success => write!(f, "success"),
ToastLevel::Info => write!(f, "info"),
ToastLevel::Error => write!(f, "error"),
}
}
}
fn show_toast(
header_text: &str,
message: &str,
level: ToastLevel,
duration: Duration,
after_reload: bool,
) {
let as_ms = duration.as_millis();
let js_fn_name = match after_reload {
true => "scheduleDXToast",
false => "showDXToast",
};
ScopeId::ROOT.in_runtime(|| {
eval(&format!(
r#"
if (typeof {js_fn_name} !== "undefined") {{
{js_fn_name}("{header_text}", "{message}", "{level}", {as_ms});
}}
"#,
));
});
}
pub(crate) fn invalidate_browser_asset_cache() {
let links = web_sys::window()
.unwrap()
.document()
.unwrap()
.query_selector_all("link[rel=stylesheet]")
.unwrap();
let noise = js_sys::Math::random();
for x in 0..links.length() {
use wasm_bindgen::JsCast;
let link: web_sys::Element = links.get(x).unwrap().unchecked_into();
let href = link.get_attribute("href").unwrap();
_ = link.set_attribute("href", &format!("{}?{}", href, noise));
}
}