#[rustfmt::skip]
mod countries;
mod model;
pub use model::*;
use std::rc::Rc;
use dioxus::html::geometry::WheelDelta;
use dioxus::prelude::*;
use crate::class::compose;
use crate::hooks::{use_controllable, use_unique_id};
use crate::icons::lucide;
use crate::{Button, ButtonSize, ButtonVariant, Icon};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorldMapZoomLabels {
pub fit: String,
pub level: String,
pub reset: String,
pub viewport: String,
pub zoom_in: String,
pub zoom_out: String,
}
impl Default for WorldMapZoomLabels {
fn default() -> Self {
Self {
fit: "Fit highlighted countries".into(),
level: "Zoom level".into(),
reset: "Reset zoom".into(),
viewport: "Map viewport".into(),
zoom_in: "Zoom in".into(),
zoom_out: "Zoom out".into(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum WorldMapInitialView {
World,
Highlighted,
}
impl WorldMapInitialView {
pub fn as_str(self) -> &'static str {
match self {
Self::World => "world",
Self::Highlighted => "highlighted",
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct WorldMapProps {
#[props(into)]
pub label: String,
pub countries: Vec<WorldMapCountry>,
#[props(default)]
pub highlighted_countries: Vec<String>,
#[props(default)]
pub markers: Vec<WorldMapMarker>,
#[props(default)]
pub labels: Vec<(String, String)>,
#[props(default)]
pub variant: WorldMapVariant,
#[props(default = true)]
pub interactive: bool,
#[props(default = true)]
pub zoomable: bool,
pub initial_view: Option<WorldMapInitialView>,
#[props(default = true)]
pub animated: bool,
#[props(into)]
pub selected_country: Option<String>,
#[props(into)]
pub default_selected_country: Option<String>,
pub on_selected_country_change: Option<EventHandler<String>>,
pub on_country_select: Option<EventHandler<WorldMapSelectDetail>>,
#[props(into)]
pub heading: Option<String>,
#[props(into)]
pub description: Option<String>,
#[props(into)]
pub caption: Option<String>,
#[props(default = "Choose a country".to_string(), into)]
pub list_label: String,
#[props(default)]
pub zoom_labels: WorldMapZoomLabels,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = figure)]
pub attributes: Vec<Attribute>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Drag {
x: f64,
y: f64,
start: WorldMapView,
moved: bool,
}
#[component]
#[allow(clippy::too_many_lines)]
pub fn WorldMap(props: WorldMapProps) -> Element {
let unique = use_unique_id();
let neutral_pattern = format!("{unique}-dot-neutral");
let highlight_pattern = format!("{unique}-dot-highlight");
let countries: Rc<[WorldMapCountry]> =
Rc::from(normalize_world_map_countries(&props.countries));
let highlighted: Rc<[String]> = Rc::from(normalize_world_map_highlighted(
&props.highlighted_countries,
&countries,
));
let markers = normalize_world_map_markers(&props.markers);
let labels: Rc<[(String, String)]> = Rc::from(props.labels.clone());
let selection = use_controllable(
props.selected_country.clone(),
|| props.default_selected_country.clone().unwrap_or_default(),
props.on_selected_country_change,
);
let mut hovered = use_signal(|| None::<String>);
let mut view = use_signal(WorldMapView::default);
let mut enhanced = use_signal(|| false);
let mut drag = use_signal(|| None::<Drag>);
let mut suppress_click = use_signal(|| false);
let mut viewport_size = use_signal(|| None::<(f64, f64)>);
let initial_view = props.initial_view;
let fit_countries = countries.clone();
let fit_highlighted = highlighted.clone();
use_effect(move || {
if initial_view == Some(WorldMapInitialView::Highlighted)
&& let Some(fitted) = WorldMapView::fit_highlighted(&fit_countries, &fit_highlighted)
{
view.set(fitted);
}
enhanced.set(true);
});
let selected_id =
find_world_map_country(&countries, &selection.get()).map(|country| country.id.to_string());
let active_id = hovered().or_else(|| selected_id.clone());
let active_label = active_id
.as_deref()
.and_then(|id| find_world_map_country(&countries, id))
.map(|country| resolve_world_map_country_label(country, &labels).to_string());
let selected_path = selected_id
.as_deref()
.and_then(|id| find_world_map_country(&countries, id))
.map_or(String::new(), |country| country.path.to_string());
let interactive = props.interactive;
let zoomable = props.zoomable;
let on_country_select = props.on_country_select;
let select_countries = countries.clone();
let select_highlighted = highlighted.clone();
let select_labels = labels.clone();
let select_country = move |id: String| {
let country = find_world_map_country(&select_countries, &id);
let current = selection.peek();
if country.map(|country| country.id.as_ref())
== find_world_map_country(&select_countries, ¤t)
.map(|country| country.id.as_ref())
{
return;
}
selection.set(country.map_or_else(String::new, |country| country.id.to_string()));
if let (Some(country), Some(handler)) = (country, on_country_select) {
handler.call(world_map_select_detail(
country,
&select_highlighted,
&select_labels,
));
}
};
let current_view = view();
let show = enhanced();
let can_fit = !highlighted.is_empty();
let class = compose([Some("ui-world-map"), props.class.as_deref()]);
let variant = props.variant;
let dotted = variant == WorldMapVariant::Dotted;
let zoom_labels = props.zoom_labels.clone();
let fit_target = WorldMapView::fit_highlighted(&countries, &highlighted);
let pan_step = |view: &WorldMapView| view.view_box().width * 0.1;
rsx! {
figure {
class,
"data-animated": "{props.animated}",
"data-initial-view": initial_view.map(WorldMapInitialView::as_str),
"data-interactive": "{interactive}",
"data-slot": "world-map",
"data-variant": variant.as_str(),
..props.attributes,
if props.heading.is_some() || props.description.is_some() {
header { class: "ui-world-map__heading",
if let Some(heading) = props.heading.clone() {
h3 { "{heading}" }
}
if let Some(description) = props.description.clone() {
p { "{description}" }
}
}
}
if zoomable {
div { class: "ui-world-map__zoom-controls", "data-slot": "world-map-zoom-controls",
Button {
aria_label: "{zoom_labels.zoom_out}",
"data-ui-world-map-zoom": "out",
disabled: !show || !current_view.can_zoom_out(),
size: ButtonSize::Icon,
variant: ButtonVariant::Outline,
onclick: move |_| {
let next = view.peek().zoom_out();
view.set(next);
},
Icon { icon: &lucide::MINUS }
}
output {
aria_label: "{zoom_labels.level}",
aria_live: "polite",
"data-ui-world-map-zoom-status": "true",
"{current_view.zoom_percent()}"
}
Button {
aria_label: "{zoom_labels.zoom_in}",
"data-ui-world-map-zoom": "in",
disabled: !show || !current_view.can_zoom_in(),
size: ButtonSize::Icon,
variant: ButtonVariant::Outline,
onclick: move |_| {
let next = view.peek().zoom_in();
view.set(next);
},
Icon { icon: &lucide::PLUS }
}
Button {
"data-ui-world-map-zoom": "fit",
disabled: !show || !can_fit,
size: ButtonSize::Sm,
variant: ButtonVariant::Outline,
onclick: move |_| {
if let Some(fitted) = fit_target {
view.set(fitted);
}
},
"{zoom_labels.fit}"
}
Button {
"data-ui-world-map-zoom": "reset",
disabled: !show || !current_view.can_zoom_out(),
size: ButtonSize::Sm,
variant: ButtonVariant::Outline,
onclick: move |_| view.set(WorldMapView::default()),
"{zoom_labels.reset}"
}
}
}
div { class: "ui-world-map__frame", "data-slot": "world-map-frame",
div {
aria_label: "{zoom_labels.viewport}: {props.label}",
class: "ui-world-map__viewport",
"data-pan-enabled": (show && zoomable).then(|| (current_view.zoom > 1.0).to_string()),
"data-panning": drag().is_some_and(|drag| drag.moved).then_some(""),
"data-ui-world-map-viewport": "true",
role: "region",
tabindex: zoomable.then_some("0"),
onmounted: move |event| async move {
if let Ok(rect) = event.get_client_rect().await {
viewport_size.set(Some((rect.width(), rect.height())));
}
},
onresize: move |event| {
if let Ok(size) = event.get_border_box_size() {
viewport_size.set(Some((size.width, size.height)));
}
},
onkeydown: move |event| {
if !zoomable {
return;
}
let current = *view.peek();
let step = pan_step(¤t);
let next = match event.key() {
Key::ArrowLeft => current.pan_by(-step, 0.0),
Key::ArrowRight => current.pan_by(step, 0.0),
Key::ArrowUp => current.pan_by(0.0, -step),
Key::ArrowDown => current.pan_by(0.0, step),
Key::Character(text) if text == "+" || text == "=" => current.zoom_in(),
Key::Character(text) if text == "-" => current.zoom_out(),
Key::Character(text) if text == "0" => WorldMapView::default(),
_ => return,
};
event.prevent_default();
view.set(next);
},
onwheel: move |event| {
let modifiers = event.modifiers();
if !zoomable || !(modifiers.ctrl() || modifiers.meta()) {
return;
}
event.prevent_default();
let height = viewport_size.peek().map_or(400.0, |(_, height)| height);
let delta = match event.delta() {
WheelDelta::Pixels(pixels) => pixels.y,
WheelDelta::Lines(lines) => lines.y * 16.0,
WheelDelta::Pages(pages) => pages.y * height,
};
let next = view.peek().zoom_by_wheel(delta, None);
view.set(next);
},
onmousedown: move |event| {
let primary = event.trigger_button().is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);
if !zoomable || !primary || view.peek().zoom <= 1.0 {
return;
}
let point = event.client_coordinates();
drag.set(Some(Drag { x: point.x, y: point.y, start: *view.peek(), moved: false }));
},
onmousemove: move |event| {
let Some(mut current) = *drag.peek() else {
return;
};
let point = event.client_coordinates();
let (dx, dy) = (point.x - current.x, point.y - current.y);
if !current.moved && !world_map_pan_threshold_reached(dx, dy) {
return;
}
current.moved = true;
drag.set(Some(current));
let (width, height) = viewport_size.peek().unwrap_or((WORLD_MAP_VIEW_BOX_WIDTH, WORLD_MAP_VIEW_BOX_HEIGHT));
view.set(current.start.drag_by(dx, dy, width, height));
event.prevent_default();
},
onmouseup: move |_| {
suppress_click.set(drag.peek().is_some_and(|drag| drag.moved));
drag.set(None);
},
onmouseleave: move |_| drag.set(None),
svg {
"aria-label": "{props.label}",
class: "ui-world-map__plot",
role: "img",
view_box: "{current_view.view_box_attribute()}",
if dotted {
defs {
pattern { height: "4", id: "{neutral_pattern}", "patternUnits": "userSpaceOnUse", width: "4",
circle { class: "ui-world-map__dot ui-world-map__dot--neutral", cx: "2", cy: "2", r: "1.1" }
}
pattern { height: "4", id: "{highlight_pattern}", "patternUnits": "userSpaceOnUse", width: "4",
circle { class: "ui-world-map__dot ui-world-map__dot--highlight", cx: "2", cy: "2", r: "1.1" }
}
}
}
g { "aria-hidden": "true", class: "ui-world-map__countries",
for country in countries.iter() {
{
let is_highlighted = highlighted.iter().any(|id| *id == country.id);
let is_selected = selected_id.as_deref() == Some(country.id.as_ref());
let country_class = compose([
Some("ui-world-map__country"),
is_highlighted.then_some("ui-world-map__country--highlighted"),
is_selected.then_some("ui-world-map__country--selected"),
]);
let fill = dotted.then(|| format!("url(#{})", if is_highlighted { &highlight_pattern } else { &neutral_pattern }));
let (click_id, hover_id) = (country.id.to_string(), country.id.to_string());
let select_country = select_country.clone();
rsx! {
path {
key: "{country.id}",
class: country_class,
d: "{country.path}",
fill,
fill_rule: "evenodd",
onclick: move |_| {
if suppress_click() {
suppress_click.set(false);
return;
}
if interactive {
select_country(click_id.clone());
}
},
onmouseenter: move |_| hovered.set(Some(hover_id.clone())),
onmouseleave: move |_| hovered.set(None),
title { "{resolve_world_map_country_label(country, &labels)}" }
}
}
}
}
}
if !markers.is_empty() {
g { "aria-hidden": "true", class: "ui-world-map__markers",
for marker in markers.iter() {
if let Some(point) = marker.point() {
circle { key: "{marker.id}", class: "ui-world-map__marker", cx: "{point.x}", cy: "{point.y}", r: "4",
title { "{marker.label}" }
}
}
}
}
}
path { "aria-hidden": "true", class: "ui-world-map__selection", d: "{selected_path}" }
}
}
if let Some(label) = active_label {
span { class: "ui-world-map__inspection", "{label}" }
}
}
if interactive {
label { class: "ui-world-map__select-label",
span { "{props.list_label}" }
select {
class: "ui-select ui-world-map__select",
oninput: move |event| select_country(event.value()),
option { selected: selected_id.is_none(), value: "", "{props.list_label}" }
for country in countries.iter() {
option {
key: "{country.id}",
selected: selected_id.as_deref() == Some(country.id.as_ref()),
value: "{country.id}",
"{resolve_world_map_country_label(country, &labels)}"
}
}
}
}
}
if !highlighted.is_empty() {
ul { aria_label: "Highlighted countries", class: "ui-world-map__highlights",
for id in highlighted.iter() {
if let Some(country) = find_world_map_country(&countries, id) {
li { key: "{id}", "{resolve_world_map_country_label(country, &labels)}" }
}
}
}
}
if !markers.is_empty() {
ul { aria_label: "Map markers", class: "ui-sr-only",
for marker in markers.iter() {
li { key: "{marker.id}", "{marker.label}" }
}
}
}
if let Some(caption) = props.caption.clone() {
figcaption { "{caption}" }
}
}
}
}