use std::borrow::Cow;
use std::collections::HashSet;
use super::countries::WORLD_MAP_COUNTRY_DATA;
pub const WORLD_MAP_VIEW_BOX_WIDTH: f64 = 1000.0;
pub const WORLD_MAP_VIEW_BOX_HEIGHT: f64 = 400.0;
pub const WORLD_MAP_LATITUDE_MIN: f64 = -60.0;
pub const WORLD_MAP_LATITUDE_MAX: f64 = 84.0;
pub const WORLD_MAP_ZOOM_MIN: f64 = 1.0;
pub const WORLD_MAP_ZOOM_MAX: f64 = 8.0;
pub const WORLD_MAP_ZOOM_STEP: f64 = 0.5;
pub const WORLD_MAP_PAN_THRESHOLD: f64 = 4.0;
const FIT_PADDING: f64 = 0.85;
const WHEEL_DELTA_LIMIT: f64 = 1000.0;
const WHEEL_ZOOM_RATE: f64 = 0.002;
const VIEW_BOX_ROUNDING: f64 = 10_000.0;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum WorldMapVariant {
#[default]
Dotted,
Solid,
}
impl WorldMapVariant {
pub const fn as_str(self) -> &'static str {
match self {
Self::Dotted => "dotted",
Self::Solid => "solid",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WorldMapPoint {
pub x: f64,
pub y: f64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WorldMapBounds {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
impl WorldMapBounds {
pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
Self {
x,
y,
width,
height,
}
}
pub fn center(self) -> WorldMapPoint {
WorldMapPoint {
x: self.x + self.width / 2.0,
y: self.y + self.height / 2.0,
}
}
pub fn is_finite(self) -> bool {
self.x.is_finite()
&& self.y.is_finite()
&& self.width.is_finite()
&& self.height.is_finite()
}
#[must_use]
pub fn union(self, other: Self) -> Self {
let x = self.x.min(other.x);
let y = self.y.min(other.y);
let right = (self.x + self.width).max(other.x + other.width);
let bottom = (self.y + self.height).max(other.y + other.height);
Self {
x,
y,
width: right - x,
height: bottom - y,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct WorldMapCountry {
pub id: Cow<'static, str>,
pub name: Cow<'static, str>,
pub path: Cow<'static, str>,
pub label_x: f64,
pub label_y: f64,
pub bounds: WorldMapBounds,
}
#[derive(Clone, Debug, PartialEq)]
pub struct WorldMapMarker {
pub id: String,
pub label: String,
pub latitude: f64,
pub longitude: f64,
}
impl WorldMapMarker {
pub fn point(&self) -> Option<WorldMapPoint> {
project_world_map_coordinate(self.longitude, self.latitude)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorldMapSelectDetail {
pub country_id: String,
pub highlighted: bool,
pub label: String,
}
pub fn world_map_countries() -> &'static [WorldMapCountry] {
WORLD_MAP_COUNTRY_DATA
}
pub fn project_world_map_coordinate(longitude: f64, latitude: f64) -> Option<WorldMapPoint> {
if !longitude.is_finite() || !latitude.is_finite() {
return None;
}
if !(-180.0..=180.0).contains(&longitude) || !(-90.0..=90.0).contains(&latitude) {
return None;
}
Some(WorldMapPoint {
x: (longitude + 180.0) / 360.0 * WORLD_MAP_VIEW_BOX_WIDTH,
y: (WORLD_MAP_LATITUDE_MAX - latitude) / (WORLD_MAP_LATITUDE_MAX - WORLD_MAP_LATITUDE_MIN)
* WORLD_MAP_VIEW_BOX_HEIGHT,
})
}
fn is_uppercase_stable(value: &str) -> bool {
value.chars().all(|character| {
let mut upper = character.to_uppercase();
upper.next() == Some(character) && upper.next().is_none()
})
}
fn normalize_id(id: &str) -> Option<Cow<'_, str>> {
let trimmed = id.trim();
if trimmed.is_empty() {
None
} else if is_uppercase_stable(trimmed) {
Some(Cow::Borrowed(trimmed))
} else {
Some(Cow::Owned(trimmed.to_uppercase()))
}
}
fn normalize_country_id(country: &WorldMapCountry) -> Option<Cow<'static, str>> {
match normalize_id(&country.id)? {
Cow::Owned(upper) => Some(Cow::Owned(upper)),
Cow::Borrowed(trimmed) => Some(match &country.id {
Cow::Borrowed(value) => Cow::Borrowed(value.trim()),
Cow::Owned(_) => Cow::Owned(trimmed.to_owned()),
}),
}
}
pub fn normalize_world_map_countries(countries: &[WorldMapCountry]) -> Vec<WorldMapCountry> {
let mut seen: HashSet<Cow<'static, str>> = HashSet::with_capacity(countries.len());
let mut result = Vec::with_capacity(countries.len());
for country in countries {
if country.name.trim().is_empty()
|| country.path.trim().is_empty()
|| !country.label_x.is_finite()
|| !country.label_y.is_finite()
{
continue;
}
let Some(id) = normalize_country_id(country) else {
continue;
};
if !seen.insert(id.clone()) {
continue;
}
result.push(WorldMapCountry {
id,
name: country.name.clone(),
path: country.path.clone(),
label_x: country.label_x,
label_y: country.label_y,
bounds: country.bounds,
});
}
result
}
pub fn normalize_world_map_highlighted<S: AsRef<str>>(
ids: &[S],
countries: &[WorldMapCountry],
) -> Vec<String> {
let known: HashSet<&str> = countries
.iter()
.map(|country| country.id.as_ref())
.collect();
let mut result: Vec<String> = Vec::new();
for raw in ids {
let Some(id) = normalize_id(raw.as_ref()) else {
continue;
};
if known.contains(id.as_ref()) && !result.iter().any(|existing| *existing == id) {
result.push(id.into_owned());
}
}
result
}
pub fn normalize_world_map_markers(markers: &[WorldMapMarker]) -> Vec<WorldMapMarker> {
let mut seen: HashSet<&str> = HashSet::with_capacity(markers.len());
let mut result = Vec::with_capacity(markers.len());
for marker in markers {
let id = marker.id.trim();
let label = marker.label.trim();
if id.is_empty() || label.is_empty() {
continue;
}
let in_band = marker.latitude.is_finite()
&& marker.longitude.is_finite()
&& (WORLD_MAP_LATITUDE_MIN..=WORLD_MAP_LATITUDE_MAX).contains(&marker.latitude)
&& (-180.0..=180.0).contains(&marker.longitude);
if !in_band || !seen.insert(id) {
continue;
}
result.push(WorldMapMarker {
id: id.to_owned(),
label: label.to_owned(),
latitude: marker.latitude,
longitude: marker.longitude,
});
}
result
}
pub fn find_world_map_country<'a>(
countries: &'a [WorldMapCountry],
country_id: &str,
) -> Option<&'a WorldMapCountry> {
let id = normalize_id(country_id)?;
countries.iter().find(|country| country.id == id)
}
pub fn resolve_world_map_country_label<'a, K, V>(
country: &'a WorldMapCountry,
overrides: &'a [(K, V)],
) -> &'a str
where
K: AsRef<str>,
V: AsRef<str>,
{
overrides
.iter()
.rev()
.find(|(id, _)| id.as_ref() == country.id)
.map(|(_, label)| label.as_ref().trim())
.filter(|label| !label.is_empty())
.unwrap_or(&country.name)
}
pub fn world_map_select_detail<S, K, V>(
country: &WorldMapCountry,
highlighted_ids: &[S],
overrides: &[(K, V)],
) -> WorldMapSelectDetail
where
S: AsRef<str>,
K: AsRef<str>,
V: AsRef<str>,
{
WorldMapSelectDetail {
country_id: country.id.clone().into_owned(),
highlighted: highlighted_ids.iter().any(|id| id.as_ref() == country.id),
label: resolve_world_map_country_label(country, overrides).to_owned(),
}
}
enum PathToken<'a> {
Command(char),
Number(&'a str),
}
fn path_tokens(path: &str) -> impl Iterator<Item = PathToken<'_>> {
let mut rest = path;
std::iter::from_fn(move || {
rest = rest
.trim_start_matches(|character: char| character == ',' || character.is_whitespace());
let first = rest.chars().next()?;
if first.is_ascii_alphabetic() {
rest = &rest[first.len_utf8()..];
return Some(PathToken::Command(first));
}
let mut previous = None;
let end = rest
.char_indices()
.find(|&(index, character)| {
let continues = character.is_ascii_digit()
|| character == '.'
|| matches!(character, 'e' | 'E')
|| (matches!(character, '+' | '-')
&& (index == 0 || matches!(previous, Some('e' | 'E'))));
previous = Some(character);
!continues
})
.map_or(rest.len(), |(index, _)| index);
let end = if end == 0 { first.len_utf8() } else { end };
let (number, remaining) = rest.split_at(end);
rest = remaining;
Some(PathToken::Number(number))
})
}
pub fn world_map_path_bounds(path: &str) -> Option<WorldMapBounds> {
let mut min = WorldMapPoint {
x: f64::INFINITY,
y: f64::INFINITY,
};
let mut max = WorldMapPoint {
x: f64::NEG_INFINITY,
y: f64::NEG_INFINITY,
};
let mut started = false;
let mut pending_x: Option<f64> = None;
for token in path_tokens(path) {
match token {
PathToken::Command(command) => {
if pending_x.is_some() || !matches!(command, 'M' | 'L' | 'Z') {
return None;
}
if !started && command != 'M' {
return None;
}
started = true;
}
PathToken::Number(text) => {
let value: f64 = text.parse().ok().filter(|value: &f64| value.is_finite())?;
if !started {
return None;
}
if let Some(x) = pending_x.take() {
min = WorldMapPoint {
x: min.x.min(x),
y: min.y.min(value),
};
max = WorldMapPoint {
x: max.x.max(x),
y: max.y.max(value),
};
} else {
pending_x = Some(value);
}
}
}
}
if pending_x.is_some() || !min.x.is_finite() {
return None;
}
Some(WorldMapBounds::new(
min.x,
min.y,
max.x - min.x,
max.y - min.y,
))
}
pub fn normalize_world_map_zoom(value: f64) -> f64 {
if value.is_finite() {
value.clamp(WORLD_MAP_ZOOM_MIN, WORLD_MAP_ZOOM_MAX)
} else {
WORLD_MAP_ZOOM_MIN
}
}
pub fn world_map_wheel_zoom_factor(delta_y: f64) -> f64 {
if delta_y.is_finite() {
(-delta_y.clamp(-WHEEL_DELTA_LIMIT, WHEEL_DELTA_LIMIT) * WHEEL_ZOOM_RATE).exp()
} else {
1.0
}
}
pub fn world_map_pan_threshold_reached(dx: f64, dy: f64) -> bool {
dx.hypot(dy) >= WORLD_MAP_PAN_THRESHOLD
}
fn clamp_center(center: f64, span: f64, extent: f64) -> f64 {
let half = span / 2.0;
if center.is_finite() {
center.max(half).min(extent - half)
} else {
extent / 2.0
}
}
fn format_view_box_number(value: f64) -> String {
let rounded = (value * VIEW_BOX_ROUNDING).round() / VIEW_BOX_ROUNDING;
if rounded == 0.0 {
"0".to_owned()
} else {
rounded.to_string()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WorldMapView {
pub zoom: f64,
pub center_x: f64,
pub center_y: f64,
}
impl Default for WorldMapView {
fn default() -> Self {
Self {
zoom: WORLD_MAP_ZOOM_MIN,
center_x: WORLD_MAP_VIEW_BOX_WIDTH / 2.0,
center_y: WORLD_MAP_VIEW_BOX_HEIGHT / 2.0,
}
}
}
impl WorldMapView {
pub fn new(zoom: f64, center_x: f64, center_y: f64) -> Self {
let zoom = normalize_world_map_zoom(zoom);
Self {
zoom,
center_x: clamp_center(
center_x,
WORLD_MAP_VIEW_BOX_WIDTH / zoom,
WORLD_MAP_VIEW_BOX_WIDTH,
),
center_y: clamp_center(
center_y,
WORLD_MAP_VIEW_BOX_HEIGHT / zoom,
WORLD_MAP_VIEW_BOX_HEIGHT,
),
}
}
pub fn view_box(&self) -> WorldMapBounds {
let view = Self::new(self.zoom, self.center_x, self.center_y);
let width = WORLD_MAP_VIEW_BOX_WIDTH / view.zoom;
let height = WORLD_MAP_VIEW_BOX_HEIGHT / view.zoom;
WorldMapBounds {
x: view.center_x - width / 2.0,
y: view.center_y - height / 2.0,
width,
height,
}
}
pub fn view_box_attribute(&self) -> String {
let view_box = self.view_box();
[view_box.x, view_box.y, view_box.width, view_box.height]
.map(format_view_box_number)
.join(" ")
}
pub fn zoom_percent(&self) -> String {
format!("{}%", (normalize_world_map_zoom(self.zoom) * 100.0).round())
}
pub fn can_zoom_in(&self) -> bool {
normalize_world_map_zoom(self.zoom) < WORLD_MAP_ZOOM_MAX
}
pub fn can_zoom_out(&self) -> bool {
normalize_world_map_zoom(self.zoom) > WORLD_MAP_ZOOM_MIN
}
#[must_use]
pub fn zoom_to(&self, zoom: f64, anchor: Option<WorldMapPoint>) -> Self {
let current = self.view_box();
let next = normalize_world_map_zoom(zoom);
let anchor = anchor
.filter(|point| point.x.is_finite() && point.y.is_finite())
.unwrap_or_else(|| current.center());
let fraction_x = (anchor.x - current.x) / current.width;
let fraction_y = (anchor.y - current.y) / current.height;
let width = WORLD_MAP_VIEW_BOX_WIDTH / next;
let height = WORLD_MAP_VIEW_BOX_HEIGHT / next;
Self::new(
next,
anchor.x - fraction_x * width + width / 2.0,
anchor.y - fraction_y * height + height / 2.0,
)
}
#[must_use]
pub fn zoom_in(&self) -> Self {
self.zoom_to(
normalize_world_map_zoom(self.zoom) + WORLD_MAP_ZOOM_STEP,
None,
)
}
#[must_use]
pub fn zoom_out(&self) -> Self {
self.zoom_to(
normalize_world_map_zoom(self.zoom) - WORLD_MAP_ZOOM_STEP,
None,
)
}
#[must_use]
pub fn zoom_by_wheel(&self, delta_y: f64, anchor: Option<WorldMapPoint>) -> Self {
self.zoom_to(
normalize_world_map_zoom(self.zoom) * world_map_wheel_zoom_factor(delta_y),
anchor,
)
}
#[must_use]
pub fn pan_by(&self, dx: f64, dy: f64) -> Self {
let view = self.view_box().center();
let finite_or_zero = |value: f64| if value.is_finite() { value } else { 0.0 };
Self::new(
self.zoom,
view.x + finite_or_zero(dx),
view.y + finite_or_zero(dy),
)
}
pub fn viewport_point(
&self,
x: f64,
y: f64,
viewport_width: f64,
viewport_height: f64,
) -> Option<WorldMapPoint> {
let view_box = self.view_box();
let scale = meet_scale(view_box, viewport_width, viewport_height)?;
if !x.is_finite() || !y.is_finite() {
return None;
}
let offset_x = (viewport_width - view_box.width * scale) / 2.0;
let offset_y = (viewport_height - view_box.height * scale) / 2.0;
Some(WorldMapPoint {
x: view_box.x + (x - offset_x) / scale,
y: view_box.y + (y - offset_y) / scale,
})
}
#[must_use]
pub fn drag_by(&self, dx: f64, dy: f64, viewport_width: f64, viewport_height: f64) -> Self {
match meet_scale(self.view_box(), viewport_width, viewport_height) {
Some(scale) => self.pan_by(-dx / scale, -dy / scale),
None => Self::new(self.zoom, self.center_x, self.center_y),
}
}
pub fn fit_bounds(bounds: WorldMapBounds) -> Self {
if !bounds.is_finite() {
return Self::default();
}
let scale = (WORLD_MAP_VIEW_BOX_WIDTH / bounds.width.max(1.0))
.min(WORLD_MAP_VIEW_BOX_HEIGHT / bounds.height.max(1.0));
let center = bounds.center();
Self::new(scale * FIT_PADDING, center.x, center.y)
}
pub fn fit_highlighted<S: AsRef<str>>(
countries: &[WorldMapCountry],
highlighted_ids: &[S],
) -> Option<Self> {
highlighted_ids
.iter()
.filter_map(|id| find_world_map_country(countries, id.as_ref()))
.map(|country| country.bounds)
.filter(|bounds| bounds.is_finite())
.reduce(WorldMapBounds::union)
.map(Self::fit_bounds)
}
}
fn meet_scale(view_box: WorldMapBounds, viewport_width: f64, viewport_height: f64) -> Option<f64> {
let usable = |value: f64| value.is_finite() && value > 0.0;
if !usable(viewport_width) || !usable(viewport_height) {
return None;
}
Some((viewport_width / view_box.width).min(viewport_height / view_box.height))
}
#[cfg(test)]
mod tests {
use super::*;
const EPSILON: f64 = 1e-9;
fn close(actual: f64, expected: f64) -> bool {
(actual - expected).abs() < EPSILON
}
fn assert_close(actual: f64, expected: f64) {
assert!(close(actual, expected), "expected {expected}, got {actual}");
}
fn assert_point(actual: Option<WorldMapPoint>, expected: WorldMapPoint) {
assert!(
actual.is_some_and(|actual| close(actual.x, expected.x) && close(actual.y, expected.y)),
"expected {expected:?}, got {actual:?}"
);
}
fn assert_bounds(actual: WorldMapBounds, expected: WorldMapBounds) {
assert!(
close(actual.x, expected.x)
&& close(actual.y, expected.y)
&& close(actual.width, expected.width)
&& close(actual.height, expected.height),
"expected {expected:?}, got {actual:?}"
);
}
fn country(id: &str, name: &str, label_x: f64, path: &str) -> WorldMapCountry {
WorldMapCountry {
id: Cow::Owned(id.to_owned()),
name: Cow::Owned(name.to_owned()),
path: Cow::Owned(path.to_owned()),
label_x,
label_y: 220.0,
bounds: WorldMapBounds::new(0.0, 0.0, 1.0, 1.0),
}
}
fn colombia() -> WorldMapCountry {
country("CO", "Colombia", 300.0, "M0 0Z")
}
fn japan() -> WorldMapCountry {
country("JP", "Japan", 820.0, "M1 1Z")
}
fn marker(id: &str, label: &str, latitude: f64, longitude: f64) -> WorldMapMarker {
WorldMapMarker {
id: id.to_owned(),
label: label.to_owned(),
latitude,
longitude,
}
}
fn no_overrides() -> &'static [(&'static str, &'static str)] {
&[]
}
#[test]
fn projects_the_corners_and_center_of_the_view_box() {
let top_left = project_world_map_coordinate(-180.0, WORLD_MAP_LATITUDE_MAX);
let bottom_right = project_world_map_coordinate(180.0, WORLD_MAP_LATITUDE_MIN);
assert_eq!(top_left, Some(WorldMapPoint { x: 0.0, y: 0.0 }));
assert_eq!(
bottom_right,
Some(WorldMapPoint {
x: WORLD_MAP_VIEW_BOX_WIDTH,
y: WORLD_MAP_VIEW_BOX_HEIGHT,
})
);
assert_close(
project_world_map_coordinate(0.0, 0.0).map_or(f64::NAN, |point| point.x),
WORLD_MAP_VIEW_BOX_WIDTH / 2.0,
);
}
#[test]
fn rejects_coordinates_that_cannot_be_projected() {
for (longitude, latitude) in [
(f64::NAN, 0.0),
(0.0, f64::NAN),
(f64::INFINITY, 0.0),
(0.0, f64::NEG_INFINITY),
(181.0, 0.0),
(-181.0, 0.0),
(0.0, 91.0),
(0.0, -91.0),
] {
assert_eq!(project_world_map_coordinate(longitude, latitude), None);
}
let north_of_band = project_world_map_coordinate(0.0, 90.0);
assert!(north_of_band.is_some_and(|point| point.y < 0.0));
}
#[test]
fn normalizes_untrusted_geometry() {
let mut lower_case = colombia();
lower_case.id = Cow::Owned(" co ".to_owned());
let mut blank_id = japan();
blank_id.id = Cow::Borrowed(" ");
let mut blank_name = japan();
blank_name.name = Cow::Borrowed(" ");
let mut blank_path = japan();
blank_path.path = Cow::Borrowed("");
let mut bad_label = japan();
bad_label.label_x = f64::NAN;
let countries = normalize_world_map_countries(&[
blank_id,
blank_name,
blank_path,
lower_case,
colombia(),
bad_label,
]);
assert_eq!(countries, vec![colombia()]);
assert_eq!(normalize_world_map_countries(&[]), Vec::new());
}
#[test]
fn keeps_already_normal_static_ids_borrowed() {
let trimmed = WorldMapCountry {
id: Cow::Borrowed(" FR "),
..colombia()
};
let countries = normalize_world_map_countries(&[trimmed]);
assert!(matches!(countries[0].id, Cow::Borrowed("FR")));
}
#[test]
fn normalizes_highlighted_ids() {
let countries = [colombia(), japan()];
let highlighted =
normalize_world_map_highlighted(&[" co ", "jp", "co", "ZZ", "", " "], &countries);
assert_eq!(highlighted, vec!["CO".to_owned(), "JP".to_owned()]);
assert_eq!(
normalize_world_map_highlighted::<String>(&[], &countries),
Vec::<String>::new()
);
assert_eq!(
normalize_world_map_highlighted(&["CO"], &[]),
Vec::<String>::new()
);
}
#[test]
fn normalizes_markers() {
let markers = normalize_world_map_markers(&[
marker(" bogota ", " Bogotá ", 4.711, -74.072),
marker("bogota", "Duplicate", 0.0, 0.0),
marker("", "No id", 0.0, 0.0),
marker("no-label", " ", 0.0, 0.0),
marker("bad-lat", "Out of range", 95.0, 0.0),
marker("nan-lon", "Not finite", 0.0, f64::NAN),
marker("north-pole", "Outside the view", 90.0, 0.0),
marker("south-pole", "Outside the view", -90.0, 0.0),
marker("south-of-band", "Outside the view", -60.5, 0.0),
marker("bad-lon", "Out of range", 0.0, 180.5),
marker("edge", "Band edge", WORLD_MAP_LATITUDE_MAX, 180.0),
]);
assert_eq!(
markers,
vec![
marker("bogota", "Bogotá", 4.711, -74.072),
marker("edge", "Band edge", WORLD_MAP_LATITUDE_MAX, 180.0),
]
);
assert_eq!(normalize_world_map_markers(&[]), Vec::new());
assert_eq!(
markers[1].point(),
Some(WorldMapPoint {
x: WORLD_MAP_VIEW_BOX_WIDTH,
y: 0.0,
})
);
}
#[test]
fn finds_countries_case_insensitively() {
let countries = [colombia(), japan()];
assert_eq!(
find_world_map_country(&countries, " co "),
Some(&countries[0])
);
assert_eq!(find_world_map_country(&countries, "ZZ"), None);
assert_eq!(find_world_map_country(&countries, ""), None);
assert_eq!(find_world_map_country(&countries, " "), None);
}
#[test]
fn resolves_labels_with_overrides() {
let colombia = colombia();
assert_eq!(
resolve_world_map_country_label(&colombia, no_overrides()),
"Colombia"
);
assert_eq!(
resolve_world_map_country_label(&colombia, &[("CO", " Home base ")]),
"Home base"
);
assert_eq!(
resolve_world_map_country_label(&colombia, &[("CO", " ")]),
"Colombia"
);
assert_eq!(
resolve_world_map_country_label(&colombia, &[("JP", "Tokyo")]),
"Colombia"
);
assert_eq!(
resolve_world_map_country_label(&colombia, &[("CO", "First"), ("CO", "Last")]),
"Last"
);
let owned = [("CO".to_owned(), "Home".to_owned())];
assert_eq!(resolve_world_map_country_label(&colombia, &owned), "Home");
}
#[test]
fn builds_select_details() {
let highlighted = ["CO"];
assert_eq!(
world_map_select_detail(&colombia(), &highlighted, no_overrides()),
WorldMapSelectDetail {
country_id: "CO".to_owned(),
highlighted: true,
label: "Colombia".to_owned(),
}
);
assert_eq!(
world_map_select_detail(&japan(), &highlighted, no_overrides()),
WorldMapSelectDetail {
country_id: "JP".to_owned(),
highlighted: false,
label: "Japan".to_owned(),
}
);
assert_eq!(
world_map_select_detail(&colombia(), &highlighted, &[("CO", "Home")]).label,
"Home"
);
}
#[test]
fn variant_strings_match_the_data_attribute() {
assert_eq!(WorldMapVariant::default(), WorldMapVariant::Dotted);
assert_eq!(WorldMapVariant::Dotted.as_str(), "dotted");
assert_eq!(WorldMapVariant::Solid.as_str(), "solid");
}
#[test]
fn clamps_zoom() {
for (value, expected) in [
(0.0, 1.0),
(1.5, 1.5),
(10.0, 8.0),
(f64::NAN, 1.0),
(f64::INFINITY, 1.0),
(f64::NEG_INFINITY, 1.0),
] {
assert_close(normalize_world_map_zoom(value), expected);
}
}
#[test]
fn default_view_shows_the_whole_map() {
let view = WorldMapView::default();
assert_bounds(
view.view_box(),
WorldMapBounds::new(0.0, 0.0, 1000.0, 400.0),
);
assert_eq!(view.view_box_attribute(), "0 0 1000 400");
assert_eq!(view.zoom_percent(), "100%");
assert!(view.can_zoom_in());
assert!(!view.can_zoom_out());
}
#[test]
fn clamps_the_view_box_inside_the_map() {
assert_bounds(
WorldMapView::new(2.0, 0.0, 0.0).view_box(),
WorldMapBounds::new(0.0, 0.0, 500.0, 200.0),
);
assert_bounds(
WorldMapView::new(2.0, 1000.0, 400.0).view_box(),
WorldMapBounds::new(500.0, 200.0, 500.0, 200.0),
);
assert_bounds(
WorldMapView::new(1.0, 900.0, 10.0).view_box(),
WorldMapBounds::new(0.0, 0.0, 1000.0, 400.0),
);
let unclamped = WorldMapView {
zoom: 20.0,
center_x: f64::NAN,
center_y: -50.0,
};
assert_bounds(
unclamped.view_box(),
WorldMapBounds::new(437.5, 0.0, 125.0, 50.0),
);
}
#[test]
fn zoom_buttons_keep_the_center_and_clamp_limits() {
let view = WorldMapView::default().zoom_in();
assert_eq!(view.zoom_percent(), "150%");
assert_bounds(
view.view_box(),
WorldMapBounds::new(200.0 / 1.2, 80.0 / 1.2, 1000.0 / 1.5, 400.0 / 1.5),
);
let mut view = view;
for _ in 0..20 {
view = view.zoom_in();
}
assert_eq!(view.zoom_percent(), "800%");
assert!(!view.can_zoom_in());
assert_eq!(view.zoom_out().zoom_percent(), "750%");
assert_eq!(WorldMapView::default().zoom_out(), WorldMapView::default());
}
#[test]
fn zoom_keeps_the_anchor_in_place() {
let view = WorldMapView::default().zoom_in();
let anchor = WorldMapPoint { x: 250.0, y: 120.0 };
let zoomed = view.zoom_by_wheel(-100.0, Some(anchor));
let zoom = 1.5 * 0.2_f64.exp();
let pixels_per_unit = 800.0 * zoom / 1000.0;
assert_close(zoomed.zoom, zoom);
assert_close(
zoomed.view_box().x * pixels_per_unit,
(200.0 + 100.0) * 0.2_f64.exp() - 100.0,
);
let before = view.view_box();
let after = zoomed.view_box();
assert_close(
(anchor.x - before.x) / before.width,
(anchor.x - after.x) / after.width,
);
assert_close(
(anchor.y - before.y) / before.height,
(anchor.y - after.y) / after.height,
);
}
#[test]
fn zooming_out_near_an_edge_stays_inside_the_map() {
let view = WorldMapView::new(8.0, 990.0, 390.0)
.zoom_to(2.0, Some(WorldMapPoint { x: 999.0, y: 399.0 }));
assert_bounds(
view.view_box(),
WorldMapBounds::new(500.0, 200.0, 500.0, 200.0),
);
}
#[test]
fn pans_within_the_map() {
let view = WorldMapView::new(2.0, 500.0, 200.0);
assert_bounds(
view.pan_by(1000.0, 0.0).view_box(),
WorldMapBounds::new(500.0, 100.0, 500.0, 200.0),
);
assert_bounds(
view.pan_by(-1000.0, -1000.0).view_box(),
WorldMapBounds::new(0.0, 0.0, 500.0, 200.0),
);
assert_bounds(
view.pan_by(25.0, -10.0).view_box(),
WorldMapBounds::new(275.0, 90.0, 500.0, 200.0),
);
assert_eq!(view.pan_by(f64::NAN, f64::INFINITY), view);
assert_eq!(
WorldMapView::default().pan_by(100.0, 50.0),
WorldMapView::default()
);
}
#[test]
fn converts_viewport_pixels_to_map_units() {
let view = WorldMapView::default();
let center = WorldMapPoint { x: 500.0, y: 200.0 };
assert_point(view.viewport_point(400.0, 160.0, 800.0, 320.0), center);
assert_point(view.viewport_point(500.0, 500.0, 1000.0, 1000.0), center);
assert_point(
WorldMapView::new(2.0, 250.0, 100.0).viewport_point(0.0, 0.0, 800.0, 320.0),
WorldMapPoint { x: 0.0, y: 0.0 },
);
assert_eq!(view.viewport_point(1.0, 1.0, 0.0, 320.0), None);
assert_eq!(view.viewport_point(f64::NAN, 1.0, 800.0, 320.0), None);
let zoomed = WorldMapView::new(2.0, 500.0, 200.0);
assert_close(
zoomed.drag_by(100.0, 0.0, 800.0, 320.0).center_x,
500.0 - 62.5,
);
assert_eq!(zoomed.drag_by(100.0, 0.0, f64::NAN, 320.0), zoomed);
}
#[test]
fn wheel_and_pan_thresholds() {
assert_close(world_map_wheel_zoom_factor(-100.0), 0.2_f64.exp());
assert_close(world_map_wheel_zoom_factor(5000.0), (-2.0_f64).exp());
assert_close(world_map_wheel_zoom_factor(f64::NAN), 1.0);
assert!(!world_map_pan_threshold_reached(3.0, 0.0));
assert!(world_map_pan_threshold_reached(4.0, 0.0));
assert!(world_map_pan_threshold_reached(-3.0, 3.0));
assert!(!world_map_pan_threshold_reached(f64::NAN, 0.0));
}
#[test]
fn fits_bounds_with_padding() {
let union = WorldMapBounds::new(100.0, 50.0, 100.0, 50.0)
.union(WorldMapBounds::new(300.0, 100.0, 50.0, 50.0));
assert_bounds(union, WorldMapBounds::new(100.0, 50.0, 250.0, 100.0));
let view = WorldMapView::fit_bounds(union);
assert_close(view.zoom, 3.4);
assert_close(view.view_box().x, 212.0 / 2.72);
assert_close(view.view_box().y, 112.0 / 2.72);
assert_eq!(view.zoom_percent(), "340%");
let tiny = WorldMapView::fit_bounds(WorldMapBounds::new(500.0, 200.0, 0.0, 0.0));
assert_close(tiny.zoom, WORLD_MAP_ZOOM_MAX);
assert_close(tiny.center_x, 500.0);
let huge = WorldMapView::fit_bounds(WorldMapBounds::new(-50.0, -20.0, 2000.0, 800.0));
assert_eq!(huge, WorldMapView::default());
assert_eq!(
WorldMapView::fit_bounds(WorldMapBounds::new(f64::NAN, 0.0, 1.0, 1.0)),
WorldMapView::default()
);
}
#[test]
fn fits_highlighted_countries() {
let countries = world_map_countries();
let none: [&str; 0] = [];
assert_eq!(WorldMapView::fit_highlighted(countries, &none), None);
assert_eq!(WorldMapView::fit_highlighted(countries, &["ZZ"]), None);
let colombia = find_world_map_country(countries, "co").map(|country| country.bounds);
let view = WorldMapView::fit_highlighted(countries, &["co", "ZZ"]);
assert_eq!(view, colombia.map(WorldMapView::fit_bounds));
let visible = view.map(|view| view.view_box());
assert!(visible.zip(colombia).is_some_and(|(visible, colombia)| {
visible.x <= colombia.x
&& visible.y <= colombia.y
&& visible.x + visible.width >= colombia.x + colombia.width
&& visible.y + visible.height >= colombia.y + colombia.height
}));
let pair = WorldMapView::fit_highlighted(countries, &["CO", "JP"]);
let japan = find_world_map_country(countries, "JP").map(|country| country.bounds);
assert_eq!(
pair,
colombia
.zip(japan)
.map(|(colombia, japan)| WorldMapView::fit_bounds(colombia.union(japan)))
);
}
#[test]
fn formats_the_view_box_attribute_like_javascript() {
assert_eq!(
WorldMapView::new(1.5, 500.0, 200.0).view_box_attribute(),
"166.6667 66.6667 666.6667 266.6667"
);
assert_eq!(
WorldMapView::new(2.0, 0.0, 0.0).view_box_attribute(),
"0 0 500 200"
);
assert_eq!(format_view_box_number(-0.000_01), "0");
assert_eq!(format_view_box_number(12.5), "12.5");
}
#[test]
fn computes_path_bounds() {
assert_eq!(
world_map_path_bounds("M0 0L10 5L3 -2ZM-1 1L2 2Z"),
Some(WorldMapBounds::new(-1.0, -2.0, 11.0, 7.0))
);
assert_eq!(
world_map_path_bounds(" M 1,2 L 3,4\nL-1e1-2 Z "),
Some(WorldMapBounds::new(-10.0, -2.0, 13.0, 6.0))
);
for invalid in [
"",
"Z",
"L1 2",
"M1",
"M1 2L3",
"M0 0C1 1 2 2 3 3Z",
"m0 0l1 1z",
"M0 0L1 xZ",
"M0 0L1 1..2Z",
"M0 0L1 NaNZ",
"1 2",
] {
assert_eq!(world_map_path_bounds(invalid), None, "{invalid:?}");
}
}
#[test]
fn path_bounds_stay_linear_on_long_input() {
let mut path = String::from("M0 0");
for index in 0..50_000_u32 {
path.push('L');
path.push_str(&index.to_string());
path.push(' ');
path.push_str(&(index % 7).to_string());
}
path.push('Z');
assert_eq!(
world_map_path_bounds(&path),
Some(WorldMapBounds::new(0.0, 0.0, 49_999.0, 6.0))
);
assert_eq!(world_map_path_bounds(&"-".repeat(100_000)), None);
assert_eq!(world_map_path_bounds(&"1".repeat(100_000)), None);
}
#[test]
fn bundled_data_is_complete_and_normal() {
let countries = world_map_countries();
assert!(countries.len() > 230, "only {} countries", countries.len());
let mut ids = HashSet::new();
for country in countries {
assert!(!country.id.is_empty() && country.id.trim() == country.id);
assert_eq!(country.id.to_uppercase(), country.id);
assert!(
ids.insert(country.id.as_ref()),
"duplicate id {}",
country.id
);
assert!(
!country.name.trim().is_empty(),
"{} has no name",
country.id
);
assert!(country.path.starts_with('M') && country.path.ends_with('Z'));
assert!(country.label_x.is_finite() && country.label_y.is_finite());
let bounds = country.bounds;
assert!(bounds.is_finite(), "{} bounds {bounds:?}", country.id);
assert!(bounds.width >= 0.0 && bounds.height >= 0.0);
assert!(
bounds.x >= 0.0
&& bounds.y >= 0.0
&& bounds.x + bounds.width <= WORLD_MAP_VIEW_BOX_WIDTH
&& bounds.y + bounds.height <= WORLD_MAP_VIEW_BOX_HEIGHT,
"{} bounds {bounds:?} leave the map",
country.id
);
let measured = world_map_path_bounds(&country.path);
assert!(
measured.is_some_and(|measured| {
(measured.x - bounds.x).abs() < 1e-6
&& (measured.y - bounds.y).abs() < 1e-6
&& (measured.width - bounds.width).abs() < 1e-6
&& (measured.height - bounds.height).abs() < 1e-6
}),
"{} bounds {bounds:?} differ from its path {measured:?}",
country.id
);
}
for id in ["CO", "JP", "SOL", "CYN", "XK"] {
assert!(ids.contains(id), "missing {id}");
}
let normalized = normalize_world_map_countries(countries);
assert_eq!(normalized, countries);
assert!(
normalized
.iter()
.all(|country| matches!(country.id, Cow::Borrowed(_)))
);
assert_eq!(
find_world_map_country(countries, "ci").map(|country| country.name.as_ref()),
Some("Côte d'Ivoire")
);
}
}