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
//! Main Map component
use dioxus::prelude::*;
use crate::context::MapContext;
use crate::events::{MapClickEvent, MapMoveEvent, MarkerClickEvent, LayerClickEvent, LayerHoverEvent};
use crate::interop::generate_map_id;
use crate::types::LatLng;
/// Event sent from JS when hovering over a marker
#[derive(Debug, Clone, serde::Deserialize)]
pub struct MarkerHoverEvent {
pub marker_id: String,
pub latlng: LatLng,
pub hover: bool,
/// Mouse cursor X position (viewport pixels)
pub cursor_x: f64,
/// Mouse cursor Y position (viewport pixels)
pub cursor_y: f64,
}
/// Props for the Map component
#[derive(Props, Clone, PartialEq)]
pub struct MapProps {
/// MapLibre style URL (e.g., "https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json")
#[props(default = "https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json".to_string())]
pub style: String,
/// Initial center coordinate
#[props(default = LatLng::helsinki())]
pub center: LatLng,
/// Initial zoom level (0-22)
#[props(default = 10.0)]
pub zoom: f64,
/// Container height (CSS value)
#[props(default = "100%".to_string())]
pub height: String,
/// Container width (CSS value)
#[props(default = "100%".to_string())]
pub width: String,
/// Callback when map is clicked
#[props(optional)]
pub on_click: Option<EventHandler<MapClickEvent>>,
/// Callback when a marker is clicked
#[props(optional)]
pub on_marker_click: Option<EventHandler<MarkerClickEvent>>,
/// Callback when hovering over a marker
#[props(optional)]
pub on_marker_hover: Option<EventHandler<MarkerHoverEvent>>,
/// Callback when map view changes
#[props(optional)]
pub on_move: Option<EventHandler<MapMoveEvent>>,
/// Callback when a feature in a layer is clicked
#[props(optional)]
pub on_layer_click: Option<EventHandler<LayerClickEvent>>,
/// Callback when hovering over a feature in a layer
#[props(optional)]
pub on_layer_hover: Option<EventHandler<LayerHoverEvent>>,
/// Child components (Marker, GeoJsonSource, etc.)
pub children: Element,
}
/// The main Map component
#[component]
pub fn Map(props: MapProps) -> Element {
// Generate unique map ID on first render
let map_id = use_hook(generate_map_id);
let container_id = format!("{map_id}_container");
// Track if map is ready
#[allow(unused_mut)] // mut needed only on wasm32
let mut is_ready = use_signal(|| false);
// Track if initialization has been started (to prevent multiple inits)
#[allow(unused_variables, unused_mut)] // only used on wasm32
let mut init_started = use_signal(|| false);
// Create context for child components
let ctx = MapContext {
map_id,
is_ready,
};
use_context_provider(|| ctx);
// Only initialize map on web/wasm targets
#[cfg(target_arch = "wasm32")]
{
use crate::interop::{destroy_map_js, init_map_js};
use tracing::debug;
// Store props for effect closure
let style = props.style.clone();
let center = props.center;
let zoom = props.zoom;
let on_click = props.on_click;
let on_marker_click = props.on_marker_click;
let on_marker_hover = props.on_marker_hover;
let on_move = props.on_move;
let on_layer_click = props.on_layer_click;
let on_layer_hover = props.on_layer_hover;
// Initialize map and set up event loop - only once
{
let map_id = map_id.clone();
let container_id = container_id.clone();
use_effect(move || {
// Only initialize once per component instance
if init_started() {
debug!("Map init already started, skipping");
return;
}
init_started.set(true);
// Clone values for the async block
let container_id = container_id.clone();
let map_id = map_id.clone();
let style = style.clone();
debug!("Starting map initialization for: {}", map_id);
// Spawn the async initialization
spawn(async move {
// Create the eval that will receive events from the map
// We use the SAME eval to execute the init code so dioxus.send() works
let init_js = init_map_js(
&container_id,
&map_id,
&style,
center.lng,
center.lat,
zoom,
);
// Execute init JS in the event loop's eval context
let mut eval = document::eval(&init_js);
debug!("Map init JS executed in event loop eval for: {}", map_id);
// Process events from JS
loop {
match eval.recv::<String>().await {
Ok(json) => {
debug!("Received event: {}", json);
// Parse the event
if let Ok(event) = serde_json::from_str::<serde_json::Value>(&json) {
match event.get("type").and_then(|t| t.as_str()) {
Some("ready") => {
debug!("Map ready!");
is_ready.set(true);
}
Some("click") => {
if let Ok(click_event) = serde_json::from_value::<MapClickEvent>(event.clone()) {
if let Some(handler) = &on_click {
handler.call(click_event);
}
}
}
Some("marker_click") => {
if let Ok(marker_event) = serde_json::from_value::<MarkerClickEvent>(event.clone()) {
if let Some(handler) = &on_marker_click {
handler.call(marker_event);
}
}
}
Some("marker_hover") => {
if let Ok(hover_event) = serde_json::from_value::<MarkerHoverEvent>(event.clone()) {
if let Some(handler) = &on_marker_hover {
handler.call(hover_event);
}
}
}
Some("move") => {
if let Ok(move_event) = serde_json::from_value::<MapMoveEvent>(event.clone()) {
if let Some(handler) = &on_move {
handler.call(move_event);
}
}
}
Some("layer_click") => {
if let Ok(layer_event) = serde_json::from_value::<LayerClickEvent>(event.clone()) {
if let Some(handler) = &on_layer_click {
handler.call(layer_event);
}
}
}
Some("layer_hover") => {
if let Ok(layer_event) = serde_json::from_value::<LayerHoverEvent>(event.clone()) {
if let Some(handler) = &on_layer_hover {
handler.call(layer_event);
}
}
}
_ => {}
}
}
}
Err(e) => {
// Channel closed, component unmounting
debug!("Event channel closed: {:?}", e);
break;
}
}
}
});
});
}
// Cleanup on unmount
{
let map_id = map_id.clone();
use_drop(move || {
debug!("Cleaning up map: {}", map_id);
let cleanup_js = destroy_map_js(&map_id);
spawn(async move {
let _ = document::eval(&cleanup_js).await;
});
});
}
}
rsx! {
div {
id: "{container_id}",
style: "width: {props.width}; height: {props.height};",
// Render children (markers) only when map is ready
if is_ready() {
{props.children}
}
}
}
}
/// Fly to a location on the map
#[cfg(target_arch = "wasm32")]
pub fn fly_to(map_id: &str, latlng: LatLng, zoom: Option<f64>) {
use crate::interop::fly_to_js;
let js = fly_to_js(map_id, latlng.lat, latlng.lng, zoom);
spawn(async move {
let _ = document::eval(&js).await;
});
}
/// No-op on non-wasm targets
#[cfg(not(target_arch = "wasm32"))]
pub fn fly_to(_map_id: &str, _latlng: LatLng, _zoom: Option<f64>) {}
/// Pan the map by pixel offset (instant, no animation)
/// Useful for compensating visual center when sidebars open/close
#[cfg(target_arch = "wasm32")]
pub fn pan_by(x: i32, y: i32) {
use crate::interop::pan_by_js;
let js = pan_by_js(x, y);
spawn(async move {
let _ = document::eval(&js).await;
});
}
/// No-op on non-wasm targets
#[cfg(not(target_arch = "wasm32"))]
pub fn pan_by(_x: i32, _y: i32) {}