Skip to main content

lumen_dioxus/data/world_map/
mod.rs

1//! `WorldMap`: an interactive dotted or solid world map with highlighted countries, location
2//! markers, country selection, and zoom and pan that work without JavaScript.
3
4// cspell:words figcaption onmousedown onmousemove onmouseup onresize onwheel
5
6#[rustfmt::skip]
7mod countries;
8mod model;
9
10pub use model::*;
11
12use std::rc::Rc;
13
14use dioxus::html::geometry::WheelDelta;
15use dioxus::prelude::*;
16
17use crate::class::compose;
18use crate::hooks::{use_controllable, use_unique_id};
19use crate::icons::lucide;
20use crate::{Button, ButtonSize, ButtonVariant, Icon};
21
22/// Copy for the [`WorldMap`] zoom controls.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct WorldMapZoomLabels {
25    /// Fit button text.
26    pub fit: String,
27    /// Name of the zoom level output.
28    pub level: String,
29    /// Reset button text.
30    pub reset: String,
31    /// Prefix of the viewport region name.
32    pub viewport: String,
33    /// Name of the zoom-in button.
34    pub zoom_in: String,
35    /// Name of the zoom-out button.
36    pub zoom_out: String,
37}
38
39impl Default for WorldMapZoomLabels {
40    fn default() -> Self {
41        Self {
42            fit: "Fit highlighted countries".into(),
43            level: "Zoom level".into(),
44            reset: "Reset zoom".into(),
45            viewport: "Map viewport".into(),
46            zoom_in: "Zoom in".into(),
47            zoom_out: "Zoom out".into(),
48        }
49    }
50}
51
52/// The view a [`WorldMap`] starts with.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54#[non_exhaustive]
55pub enum WorldMapInitialView {
56    /// The whole map.
57    World,
58    /// Fitted to the highlighted countries.
59    Highlighted,
60}
61
62impl WorldMapInitialView {
63    /// The `data-initial-view` value.
64    pub fn as_str(self) -> &'static str {
65        match self {
66            Self::World => "world",
67            Self::Highlighted => "highlighted",
68        }
69    }
70}
71
72/// Props for [`WorldMap`].
73#[derive(Props, Clone, PartialEq)]
74pub struct WorldMapProps {
75    /// Accessible name of the map image.
76    #[props(into)]
77    pub label: String,
78    /// Country geometry, usually `world_map_countries().to_vec()`. Invalid and duplicate
79    /// entries are dropped.
80    pub countries: Vec<WorldMapCountry>,
81    /// Highlighted country ids (case-insensitive). Unknown ids are ignored.
82    #[props(default)]
83    pub highlighted_countries: Vec<String>,
84    /// Location markers. Invalid markers are dropped.
85    #[props(default)]
86    pub markers: Vec<WorldMapMarker>,
87    /// Country label overrides as `(id, label)` pairs.
88    #[props(default)]
89    pub labels: Vec<(String, String)>,
90    /// Dotted (default) or solid land.
91    #[props(default)]
92    pub variant: WorldMapVariant,
93    /// Lets users select countries by clicking or with the country list.
94    #[props(default = true)]
95    pub interactive: bool,
96    /// Shows the zoom controls and lets users zoom and pan.
97    #[props(default = true)]
98    pub zoomable: bool,
99    /// The first view once the map is mounted.
100    pub initial_view: Option<WorldMapInitialView>,
101    /// Plays the entrance and marker animations (reduced motion turns them off).
102    #[props(default = true)]
103    pub animated: bool,
104    /// Controlled selected country id.
105    #[props(into)]
106    pub selected_country: Option<String>,
107    /// Initially selected country id when uncontrolled.
108    #[props(into)]
109    pub default_selected_country: Option<String>,
110    /// Called with the selected country id, or an empty string when the selection clears.
111    pub on_selected_country_change: Option<EventHandler<String>>,
112    /// Called with details of a newly selected country.
113    pub on_country_select: Option<EventHandler<WorldMapSelectDetail>>,
114    /// Heading above the map.
115    #[props(into)]
116    pub heading: Option<String>,
117    /// Description under the heading.
118    #[props(into)]
119    pub description: Option<String>,
120    /// Caption under the map.
121    #[props(into)]
122    pub caption: Option<String>,
123    /// Label and placeholder of the country list. Defaults to `Choose a country`.
124    #[props(default = "Choose a country".to_string(), into)]
125    pub list_label: String,
126    /// Copy for the zoom controls.
127    #[props(default)]
128    pub zoom_labels: WorldMapZoomLabels,
129    /// Extra classes appended after the Lumen class.
130    #[props(into)]
131    pub class: Option<String>,
132    /// Any other `<figure>` or global attribute.
133    #[props(extends = GlobalAttributes, extends = figure)]
134    pub attributes: Vec<Attribute>,
135}
136
137#[derive(Clone, Copy, Debug, PartialEq)]
138struct Drag {
139    x: f64,
140    y: f64,
141    start: WorldMapView,
142    moved: bool,
143}
144
145/// An interactive world map.
146///
147/// Zoom and pan change the SVG `viewBox` instead of scrolling a scaled plot, so they work on
148/// every renderer: the zoom buttons, `+`, `-`, and `0` on the focused viewport, arrow keys to
149/// pan, Ctrl or Cmd with the wheel, and dragging when zoomed in (where the renderer reports
150/// pointer events). Like lumen-react, the first render keeps the zoom controls disabled until the
151/// component is mounted.
152#[component]
153#[allow(clippy::too_many_lines)]
154pub fn WorldMap(props: WorldMapProps) -> Element {
155    let unique = use_unique_id();
156    let neutral_pattern = format!("{unique}-dot-neutral");
157    let highlight_pattern = format!("{unique}-dot-highlight");
158    let countries: Rc<[WorldMapCountry]> =
159        Rc::from(normalize_world_map_countries(&props.countries));
160    let highlighted: Rc<[String]> = Rc::from(normalize_world_map_highlighted(
161        &props.highlighted_countries,
162        &countries,
163    ));
164    let markers = normalize_world_map_markers(&props.markers);
165    let labels: Rc<[(String, String)]> = Rc::from(props.labels.clone());
166    let selection = use_controllable(
167        props.selected_country.clone(),
168        || props.default_selected_country.clone().unwrap_or_default(),
169        props.on_selected_country_change,
170    );
171    let mut hovered = use_signal(|| None::<String>);
172    let mut view = use_signal(WorldMapView::default);
173    let mut enhanced = use_signal(|| false);
174    let mut drag = use_signal(|| None::<Drag>);
175    let mut suppress_click = use_signal(|| false);
176    let mut viewport_size = use_signal(|| None::<(f64, f64)>);
177    let initial_view = props.initial_view;
178    let fit_countries = countries.clone();
179    let fit_highlighted = highlighted.clone();
180
181    use_effect(move || {
182        if initial_view == Some(WorldMapInitialView::Highlighted)
183            && let Some(fitted) = WorldMapView::fit_highlighted(&fit_countries, &fit_highlighted)
184        {
185            view.set(fitted);
186        }
187
188        enhanced.set(true);
189    });
190
191    let selected_id =
192        find_world_map_country(&countries, &selection.get()).map(|country| country.id.to_string());
193    let active_id = hovered().or_else(|| selected_id.clone());
194    let active_label = active_id
195        .as_deref()
196        .and_then(|id| find_world_map_country(&countries, id))
197        .map(|country| resolve_world_map_country_label(country, &labels).to_string());
198    let selected_path = selected_id
199        .as_deref()
200        .and_then(|id| find_world_map_country(&countries, id))
201        .map_or(String::new(), |country| country.path.to_string());
202    let interactive = props.interactive;
203    let zoomable = props.zoomable;
204    let on_country_select = props.on_country_select;
205    let select_countries = countries.clone();
206    let select_highlighted = highlighted.clone();
207    let select_labels = labels.clone();
208    let select_country = move |id: String| {
209        let country = find_world_map_country(&select_countries, &id);
210        let current = selection.peek();
211
212        if country.map(|country| country.id.as_ref())
213            == find_world_map_country(&select_countries, &current)
214                .map(|country| country.id.as_ref())
215        {
216            return;
217        }
218
219        selection.set(country.map_or_else(String::new, |country| country.id.to_string()));
220
221        if let (Some(country), Some(handler)) = (country, on_country_select) {
222            handler.call(world_map_select_detail(
223                country,
224                &select_highlighted,
225                &select_labels,
226            ));
227        }
228    };
229    let current_view = view();
230    let show = enhanced();
231    let can_fit = !highlighted.is_empty();
232    let class = compose([Some("ui-world-map"), props.class.as_deref()]);
233    let variant = props.variant;
234    let dotted = variant == WorldMapVariant::Dotted;
235    let zoom_labels = props.zoom_labels.clone();
236    let fit_target = WorldMapView::fit_highlighted(&countries, &highlighted);
237    let pan_step = |view: &WorldMapView| view.view_box().width * 0.1;
238
239    rsx! {
240        figure {
241            class,
242            "data-animated": "{props.animated}",
243            "data-initial-view": initial_view.map(WorldMapInitialView::as_str),
244            "data-interactive": "{interactive}",
245            "data-slot": "world-map",
246            "data-variant": variant.as_str(),
247            ..props.attributes,
248            if props.heading.is_some() || props.description.is_some() {
249                header { class: "ui-world-map__heading",
250                    if let Some(heading) = props.heading.clone() {
251                        h3 { "{heading}" }
252                    }
253                    if let Some(description) = props.description.clone() {
254                        p { "{description}" }
255                    }
256                }
257            }
258            if zoomable {
259                div { class: "ui-world-map__zoom-controls", "data-slot": "world-map-zoom-controls",
260                    Button {
261                        aria_label: "{zoom_labels.zoom_out}",
262                        "data-ui-world-map-zoom": "out",
263                        disabled: !show || !current_view.can_zoom_out(),
264                        size: ButtonSize::Icon,
265                        variant: ButtonVariant::Outline,
266                        onclick: move |_| {
267                            let next = view.peek().zoom_out();
268                            view.set(next);
269                        },
270                        Icon { icon: &lucide::MINUS }
271                    }
272                    output {
273                        aria_label: "{zoom_labels.level}",
274                        aria_live: "polite",
275                        "data-ui-world-map-zoom-status": "true",
276                        "{current_view.zoom_percent()}"
277                    }
278                    Button {
279                        aria_label: "{zoom_labels.zoom_in}",
280                        "data-ui-world-map-zoom": "in",
281                        disabled: !show || !current_view.can_zoom_in(),
282                        size: ButtonSize::Icon,
283                        variant: ButtonVariant::Outline,
284                        onclick: move |_| {
285                            let next = view.peek().zoom_in();
286                            view.set(next);
287                        },
288                        Icon { icon: &lucide::PLUS }
289                    }
290                    Button {
291                        "data-ui-world-map-zoom": "fit",
292                        disabled: !show || !can_fit,
293                        size: ButtonSize::Sm,
294                        variant: ButtonVariant::Outline,
295                        onclick: move |_| {
296                            if let Some(fitted) = fit_target {
297                                view.set(fitted);
298                            }
299                        },
300                        "{zoom_labels.fit}"
301                    }
302                    Button {
303                        "data-ui-world-map-zoom": "reset",
304                        disabled: !show || !current_view.can_zoom_out(),
305                        size: ButtonSize::Sm,
306                        variant: ButtonVariant::Outline,
307                        onclick: move |_| view.set(WorldMapView::default()),
308                        "{zoom_labels.reset}"
309                    }
310                }
311            }
312            div { class: "ui-world-map__frame", "data-slot": "world-map-frame",
313                div {
314                    aria_label: "{zoom_labels.viewport}: {props.label}",
315                    class: "ui-world-map__viewport",
316                    "data-pan-enabled": (show && zoomable).then(|| (current_view.zoom > 1.0).to_string()),
317                    "data-panning": drag().is_some_and(|drag| drag.moved).then_some(""),
318                    "data-ui-world-map-viewport": "true",
319                    role: "region",
320                    tabindex: zoomable.then_some("0"),
321                    onmounted: move |event| async move {
322                        if let Ok(rect) = event.get_client_rect().await {
323                            viewport_size.set(Some((rect.width(), rect.height())));
324                        }
325                    },
326                    onresize: move |event| {
327                        if let Ok(size) = event.get_border_box_size() {
328                            viewport_size.set(Some((size.width, size.height)));
329                        }
330                    },
331                    onkeydown: move |event| {
332                        if !zoomable {
333                            return;
334                        }
335
336                        let current = *view.peek();
337                        let step = pan_step(&current);
338                        let next = match event.key() {
339                            Key::ArrowLeft => current.pan_by(-step, 0.0),
340                            Key::ArrowRight => current.pan_by(step, 0.0),
341                            Key::ArrowUp => current.pan_by(0.0, -step),
342                            Key::ArrowDown => current.pan_by(0.0, step),
343                            Key::Character(text) if text == "+" || text == "=" => current.zoom_in(),
344                            Key::Character(text) if text == "-" => current.zoom_out(),
345                            Key::Character(text) if text == "0" => WorldMapView::default(),
346                            _ => return,
347                        };
348
349                        event.prevent_default();
350                        view.set(next);
351                    },
352                    onwheel: move |event| {
353                        let modifiers = event.modifiers();
354
355                        if !zoomable || !(modifiers.ctrl() || modifiers.meta()) {
356                            return;
357                        }
358
359                        event.prevent_default();
360                        let height = viewport_size.peek().map_or(400.0, |(_, height)| height);
361                        let delta = match event.delta() {
362                            WheelDelta::Pixels(pixels) => pixels.y,
363                            WheelDelta::Lines(lines) => lines.y * 16.0,
364                            WheelDelta::Pages(pages) => pages.y * height,
365                        };
366
367                        let next = view.peek().zoom_by_wheel(delta, None);
368                        view.set(next);
369                    },
370                    onmousedown: move |event| {
371                        let primary = event.trigger_button().is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);
372
373                        if !zoomable || !primary || view.peek().zoom <= 1.0 {
374                            return;
375                        }
376
377                        let point = event.client_coordinates();
378                        drag.set(Some(Drag { x: point.x, y: point.y, start: *view.peek(), moved: false }));
379                    },
380                    onmousemove: move |event| {
381                        let Some(mut current) = *drag.peek() else {
382                            return;
383                        };
384
385                        let point = event.client_coordinates();
386                        let (dx, dy) = (point.x - current.x, point.y - current.y);
387
388                        if !current.moved && !world_map_pan_threshold_reached(dx, dy) {
389                            return;
390                        }
391
392                        current.moved = true;
393                        drag.set(Some(current));
394                        let (width, height) = viewport_size.peek().unwrap_or((WORLD_MAP_VIEW_BOX_WIDTH, WORLD_MAP_VIEW_BOX_HEIGHT));
395                        view.set(current.start.drag_by(dx, dy, width, height));
396                        event.prevent_default();
397                    },
398                    onmouseup: move |_| {
399                        suppress_click.set(drag.peek().is_some_and(|drag| drag.moved));
400                        drag.set(None);
401                    },
402                    onmouseleave: move |_| drag.set(None),
403                    svg {
404                        "aria-label": "{props.label}",
405                        class: "ui-world-map__plot",
406                        role: "img",
407                        view_box: "{current_view.view_box_attribute()}",
408                        if dotted {
409                            defs {
410                                pattern { height: "4", id: "{neutral_pattern}", "patternUnits": "userSpaceOnUse", width: "4",
411                                    circle { class: "ui-world-map__dot ui-world-map__dot--neutral", cx: "2", cy: "2", r: "1.1" }
412                                }
413                                pattern { height: "4", id: "{highlight_pattern}", "patternUnits": "userSpaceOnUse", width: "4",
414                                    circle { class: "ui-world-map__dot ui-world-map__dot--highlight", cx: "2", cy: "2", r: "1.1" }
415                                }
416                            }
417                        }
418                        g { "aria-hidden": "true", class: "ui-world-map__countries",
419                            for country in countries.iter() {
420                                {
421                                    let is_highlighted = highlighted.iter().any(|id| *id == country.id);
422                                    let is_selected = selected_id.as_deref() == Some(country.id.as_ref());
423                                    let country_class = compose([
424                                        Some("ui-world-map__country"),
425                                        is_highlighted.then_some("ui-world-map__country--highlighted"),
426                                        is_selected.then_some("ui-world-map__country--selected"),
427                                    ]);
428                                    let fill = dotted.then(|| format!("url(#{})", if is_highlighted { &highlight_pattern } else { &neutral_pattern }));
429                                    let (click_id, hover_id) = (country.id.to_string(), country.id.to_string());
430                                    let select_country = select_country.clone();
431
432                                    rsx! {
433                                        path {
434                                            key: "{country.id}",
435                                            class: country_class,
436                                            d: "{country.path}",
437                                            fill,
438                                            fill_rule: "evenodd",
439                                            onclick: move |_| {
440                                                if suppress_click() {
441                                                    suppress_click.set(false);
442                                                    return;
443                                                }
444
445                                                if interactive {
446                                                    select_country(click_id.clone());
447                                                }
448                                            },
449                                            onmouseenter: move |_| hovered.set(Some(hover_id.clone())),
450                                            onmouseleave: move |_| hovered.set(None),
451                                            title { "{resolve_world_map_country_label(country, &labels)}" }
452                                        }
453                                    }
454                                }
455                            }
456                        }
457                        if !markers.is_empty() {
458                            g { "aria-hidden": "true", class: "ui-world-map__markers",
459                                for marker in markers.iter() {
460                                    if let Some(point) = marker.point() {
461                                        circle { key: "{marker.id}", class: "ui-world-map__marker", cx: "{point.x}", cy: "{point.y}", r: "4",
462                                            title { "{marker.label}" }
463                                        }
464                                    }
465                                }
466                            }
467                        }
468                        path { "aria-hidden": "true", class: "ui-world-map__selection", d: "{selected_path}" }
469                    }
470                }
471                if let Some(label) = active_label {
472                    span { class: "ui-world-map__inspection", "{label}" }
473                }
474            }
475            if interactive {
476                label { class: "ui-world-map__select-label",
477                    span { "{props.list_label}" }
478                    select {
479                        class: "ui-select ui-world-map__select",
480                        oninput: move |event| select_country(event.value()),
481                        option { selected: selected_id.is_none(), value: "", "{props.list_label}" }
482                        for country in countries.iter() {
483                            option {
484                                key: "{country.id}",
485                                selected: selected_id.as_deref() == Some(country.id.as_ref()),
486                                value: "{country.id}",
487                                "{resolve_world_map_country_label(country, &labels)}"
488                            }
489                        }
490                    }
491                }
492            }
493            if !highlighted.is_empty() {
494                ul { aria_label: "Highlighted countries", class: "ui-world-map__highlights",
495                    for id in highlighted.iter() {
496                        if let Some(country) = find_world_map_country(&countries, id) {
497                            li { key: "{id}", "{resolve_world_map_country_label(country, &labels)}" }
498                        }
499                    }
500                }
501            }
502            if !markers.is_empty() {
503                ul { aria_label: "Map markers", class: "ui-sr-only",
504                    for marker in markers.iter() {
505                        li { key: "{marker.id}", "{marker.label}" }
506                    }
507                }
508            }
509            if let Some(caption) = props.caption.clone() {
510                figcaption { "{caption}" }
511            }
512        }
513    }
514}