dioxus_maplibre/handle/escape_hatch.rs
1//! Escape-hatch MapHandle methods.
2
3use super::MapHandle;
4#[cfg(target_arch = "wasm32")]
5use dioxus::prelude::document;
6
7impl MapHandle {
8 /// Execute arbitrary JavaScript against this map's instance.
9 ///
10 /// The JS code receives `map` as a variable referencing the MapLibre map object.
11 /// This is a fire-and-forget operation.
12 pub fn eval(&self, js_code: &str) {
13 let find = crate::interop::find_map_js(&self.map_id);
14 let full_js = format!("(function() {{ {find} {js_code} }})();");
15 self.eval_raw(&full_js);
16 }
17
18 /// Execute arbitrary JavaScript and return a deserialized result.
19 ///
20 /// The JS code should be a function body that `return`s a value.
21 /// It receives `map` as a variable.
22 ///
23 /// Prefer:
24 /// `handle.eval_async::<bool>("return map.hasImage('my-icon');").await`
25 ///
26 /// Avoid wrapping in your own immediately-invoked function expression (IIFE),
27 /// because this method already wraps and executes the provided code.
28 #[cfg(target_arch = "wasm32")]
29 pub async fn eval_async<T: serde::de::DeserializeOwned>(&self, js_code: &str) -> Option<T> {
30 let find = crate::interop::find_map_js(&self.map_id);
31 let full_js = format!(
32 r#"
33 {find}
34 return (async function() {{
35 {js_code}
36 }})();
37 "#
38 );
39 document::eval(&full_js).join::<T>().await.ok()
40 }
41
42 #[allow(clippy::unused_async)]
43 #[cfg(not(target_arch = "wasm32"))]
44 pub async fn eval_async<T: serde::de::DeserializeOwned>(&self, _js_code: &str) -> Option<T> {
45 None
46 }
47}