Skip to main content

lumen_dioxus/data/world_map/
model.rs

1//! Pure `WorldMap` model: bundled country data, projection, normalization, and navigation.
2//!
3//! Ports `packages/core/src/world-map.ts` and the zoom, fit, and pan rules of
4//! `world-map-zoom.ts`, `world-map-navigation.ts`, and `world-map-pan.ts`. The web adapters zoom by
5//! scaling a scrollable plot. Dioxus Native has no scroll APIs, so [`WorldMapView`] zooms and pans
6//! by changing the SVG `viewBox` instead. Everything here uses only `std`.
7
8// cspell:words hypot
9
10use std::borrow::Cow;
11use std::collections::HashSet;
12
13use super::countries::WORLD_MAP_COUNTRY_DATA;
14
15/// Width of the shared SVG `viewBox`, in map units. It spans longitude -180 to 180.
16pub const WORLD_MAP_VIEW_BOX_WIDTH: f64 = 1000.0;
17
18/// Height of the shared SVG `viewBox`, in map units. It spans latitude 84 to -60.
19pub const WORLD_MAP_VIEW_BOX_HEIGHT: f64 = 400.0;
20
21/// Southern edge of the projected latitude band. The dataset leaves out Antarctica.
22pub const WORLD_MAP_LATITUDE_MIN: f64 = -60.0;
23
24/// Northern edge of the projected latitude band.
25pub const WORLD_MAP_LATITUDE_MAX: f64 = 84.0;
26
27/// Smallest zoom level, which shows the whole map.
28pub const WORLD_MAP_ZOOM_MIN: f64 = 1.0;
29
30/// Largest zoom level.
31pub const WORLD_MAP_ZOOM_MAX: f64 = 8.0;
32
33/// Zoom change for one press of the zoom in or zoom out button.
34pub const WORLD_MAP_ZOOM_STEP: f64 = 0.5;
35
36/// Pointer travel, in CSS pixels, before a press on the map becomes a pan instead of a click.
37pub const WORLD_MAP_PAN_THRESHOLD: f64 = 4.0;
38
39/// Share of the viewport that fitted bounds fill, leaving a margin around them.
40const FIT_PADDING: f64 = 0.85;
41
42/// Wheel deltas beyond this many pixels count as this many, so one event can't jump too far.
43const WHEEL_DELTA_LIMIT: f64 = 1000.0;
44
45/// Zoom rate per wheel pixel: each pixel scales the zoom by `exp(-0.002)`.
46const WHEEL_ZOOM_RATE: f64 = 0.002;
47
48/// Rounding factor for `viewBox` attribute values (four decimals).
49const VIEW_BOX_ROUNDING: f64 = 10_000.0;
50
51/// How country shapes are filled.
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
53#[non_exhaustive]
54pub enum WorldMapVariant {
55    /// Countries are filled with a dot pattern.
56    #[default]
57    Dotted,
58    /// Countries are filled with a solid color.
59    Solid,
60}
61
62impl WorldMapVariant {
63    /// The `data-variant` attribute value: `dotted` or `solid`.
64    pub const fn as_str(self) -> &'static str {
65        match self {
66            Self::Dotted => "dotted",
67            Self::Solid => "solid",
68        }
69    }
70}
71
72/// A point in `viewBox` units.
73#[derive(Clone, Copy, Debug, Default, PartialEq)]
74pub struct WorldMapPoint {
75    /// Horizontal position, from 0 at longitude -180 to 1000 at longitude 180.
76    pub x: f64,
77    /// Vertical position, from 0 at latitude 84 to 400 at latitude -60.
78    pub y: f64,
79}
80
81/// An axis-aligned rectangle in `viewBox` units.
82#[derive(Clone, Copy, Debug, Default, PartialEq)]
83pub struct WorldMapBounds {
84    /// Left edge.
85    pub x: f64,
86    /// Top edge.
87    pub y: f64,
88    /// Width.
89    pub width: f64,
90    /// Height.
91    pub height: f64,
92}
93
94impl WorldMapBounds {
95    /// Creates bounds from the top-left corner and size.
96    pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
97        Self {
98            x,
99            y,
100            width,
101            height,
102        }
103    }
104
105    /// The center point.
106    pub fn center(self) -> WorldMapPoint {
107        WorldMapPoint {
108            x: self.x + self.width / 2.0,
109            y: self.y + self.height / 2.0,
110        }
111    }
112
113    /// Whether every field is a finite number.
114    pub fn is_finite(self) -> bool {
115        self.x.is_finite()
116            && self.y.is_finite()
117            && self.width.is_finite()
118            && self.height.is_finite()
119    }
120
121    /// The smallest bounds that contain both `self` and `other`.
122    #[must_use]
123    pub fn union(self, other: Self) -> Self {
124        let x = self.x.min(other.x);
125        let y = self.y.min(other.y);
126        let right = (self.x + self.width).max(other.x + other.width);
127        let bottom = (self.y + self.height).max(other.y + other.height);
128
129        Self {
130            x,
131            y,
132            width: right - x,
133            height: bottom - y,
134        }
135    }
136}
137
138/// One country's projected SVG path and label anchor.
139///
140/// The bundled data comes from [`world_map_countries`]. Custom geometry can use
141/// [`world_map_path_bounds`] to fill in `bounds`.
142#[derive(Clone, Debug, PartialEq)]
143pub struct WorldMapCountry {
144    /// ISO 3166-1 alpha-2 code where one exists, in uppercase. Somaliland uses `SOL` and
145    /// Northern Cyprus uses `CYN`.
146    pub id: Cow<'static, str>,
147    /// English display name.
148    pub name: Cow<'static, str>,
149    /// SVG path data in `viewBox` units, drawn with `fill-rule: evenodd`.
150    pub path: Cow<'static, str>,
151    /// Horizontal position of the label anchor.
152    pub label_x: f64,
153    /// Vertical position of the label anchor.
154    pub label_y: f64,
155    /// Bounding box of `path`, used to fit highlighted countries.
156    pub bounds: WorldMapBounds,
157}
158
159/// A consumer-supplied point of interest, placed with the same projection as the countries.
160#[derive(Clone, Debug, PartialEq)]
161pub struct WorldMapMarker {
162    /// Unique identifier.
163    pub id: String,
164    /// Accessible label.
165    pub label: String,
166    /// Latitude in degrees. Markers outside -60 to 84 are dropped.
167    pub latitude: f64,
168    /// Longitude in degrees, from -180 to 180.
169    pub longitude: f64,
170}
171
172impl WorldMapMarker {
173    /// The marker's projected position, or `None` when its coordinates can't be projected.
174    pub fn point(&self) -> Option<WorldMapPoint> {
175        project_world_map_coordinate(self.longitude, self.latitude)
176    }
177}
178
179/// Details sent when a country is selected.
180#[derive(Clone, Debug, PartialEq, Eq)]
181pub struct WorldMapSelectDetail {
182    /// The selected country's id.
183    pub country_id: String,
184    /// Whether the country is highlighted. Selection and highlighting are separate states.
185    pub highlighted: bool,
186    /// The resolved display label, including any override.
187    pub label: String,
188}
189
190/// The bundled country geometry: 238 countries and territories from Natural Earth (public
191/// domain), with uppercase ids and path bounds.
192pub fn world_map_countries() -> &'static [WorldMapCountry] {
193    WORLD_MAP_COUNTRY_DATA
194}
195
196/// Projects a longitude and latitude to the shared `viewBox` with the equirectangular projection
197/// used for every country path.
198///
199/// Returns `None` for non-finite input, a longitude outside -180 to 180, or a latitude outside
200/// -90 to 90. Latitudes outside the visible band still project, just beyond the map's edges.
201pub fn project_world_map_coordinate(longitude: f64, latitude: f64) -> Option<WorldMapPoint> {
202    if !longitude.is_finite() || !latitude.is_finite() {
203        return None;
204    }
205
206    if !(-180.0..=180.0).contains(&longitude) || !(-90.0..=90.0).contains(&latitude) {
207        return None;
208    }
209
210    Some(WorldMapPoint {
211        x: (longitude + 180.0) / 360.0 * WORLD_MAP_VIEW_BOX_WIDTH,
212        y: (WORLD_MAP_LATITUDE_MAX - latitude) / (WORLD_MAP_LATITUDE_MAX - WORLD_MAP_LATITUDE_MIN)
213            * WORLD_MAP_VIEW_BOX_HEIGHT,
214    })
215}
216
217/// Whether converting `value` to uppercase would leave it unchanged.
218fn is_uppercase_stable(value: &str) -> bool {
219    value.chars().all(|character| {
220        let mut upper = character.to_uppercase();
221
222        upper.next() == Some(character) && upper.next().is_none()
223    })
224}
225
226/// Trims an id and converts it to uppercase, borrowing when nothing changes. Blank ids give
227/// `None`.
228fn normalize_id(id: &str) -> Option<Cow<'_, str>> {
229    let trimmed = id.trim();
230
231    if trimmed.is_empty() {
232        None
233    } else if is_uppercase_stable(trimmed) {
234        Some(Cow::Borrowed(trimmed))
235    } else {
236        Some(Cow::Owned(trimmed.to_uppercase()))
237    }
238}
239
240/// Normalizes a country's id, keeping a static id borrowed when it is already normal.
241fn normalize_country_id(country: &WorldMapCountry) -> Option<Cow<'static, str>> {
242    match normalize_id(&country.id)? {
243        Cow::Owned(upper) => Some(Cow::Owned(upper)),
244        Cow::Borrowed(trimmed) => Some(match &country.id {
245            Cow::Borrowed(value) => Cow::Borrowed(value.trim()),
246            Cow::Owned(_) => Cow::Owned(trimmed.to_owned()),
247        }),
248    }
249}
250
251/// Validates country geometry: trims ids and converts them to uppercase, and drops entries with
252/// a blank id, name, or path, a non-finite label anchor, or an id seen earlier.
253///
254/// Already-normal static data is copied without allocating new strings.
255pub fn normalize_world_map_countries(countries: &[WorldMapCountry]) -> Vec<WorldMapCountry> {
256    let mut seen: HashSet<Cow<'static, str>> = HashSet::with_capacity(countries.len());
257    let mut result = Vec::with_capacity(countries.len());
258
259    for country in countries {
260        if country.name.trim().is_empty()
261            || country.path.trim().is_empty()
262            || !country.label_x.is_finite()
263            || !country.label_y.is_finite()
264        {
265            continue;
266        }
267
268        let Some(id) = normalize_country_id(country) else {
269            continue;
270        };
271
272        if !seen.insert(id.clone()) {
273            continue;
274        }
275
276        result.push(WorldMapCountry {
277            id,
278            name: country.name.clone(),
279            path: country.path.clone(),
280            label_x: country.label_x,
281            label_y: country.label_y,
282            bounds: country.bounds,
283        });
284    }
285
286    result
287}
288
289/// Trims, converts to uppercase, and deduplicates highlighted country ids, and drops blank ids
290/// and ids that are not in `countries`, so a typo degrades gracefully instead of breaking the map.
291pub fn normalize_world_map_highlighted<S: AsRef<str>>(
292    ids: &[S],
293    countries: &[WorldMapCountry],
294) -> Vec<String> {
295    let known: HashSet<&str> = countries
296        .iter()
297        .map(|country| country.id.as_ref())
298        .collect();
299    let mut result: Vec<String> = Vec::new();
300
301    for raw in ids {
302        let Some(id) = normalize_id(raw.as_ref()) else {
303            continue;
304        };
305
306        if known.contains(id.as_ref()) && !result.iter().any(|existing| *existing == id) {
307            result.push(id.into_owned());
308        }
309    }
310
311    result
312}
313
314/// Validates markers: trims the id and label, requires both to be non-blank, requires finite
315/// coordinates inside the visible latitude band and longitude -180 to 180, and drops markers
316/// whose id was seen earlier.
317pub fn normalize_world_map_markers(markers: &[WorldMapMarker]) -> Vec<WorldMapMarker> {
318    let mut seen: HashSet<&str> = HashSet::with_capacity(markers.len());
319    let mut result = Vec::with_capacity(markers.len());
320
321    for marker in markers {
322        let id = marker.id.trim();
323        let label = marker.label.trim();
324
325        if id.is_empty() || label.is_empty() {
326            continue;
327        }
328
329        let in_band = marker.latitude.is_finite()
330            && marker.longitude.is_finite()
331            && (WORLD_MAP_LATITUDE_MIN..=WORLD_MAP_LATITUDE_MAX).contains(&marker.latitude)
332            && (-180.0..=180.0).contains(&marker.longitude);
333
334        if !in_band || !seen.insert(id) {
335            continue;
336        }
337
338        result.push(WorldMapMarker {
339            id: id.to_owned(),
340            label: label.to_owned(),
341            latitude: marker.latitude,
342            longitude: marker.longitude,
343        });
344    }
345
346    result
347}
348
349/// Finds a country by id, ignoring surrounding whitespace and case. Blank ids find nothing.
350pub fn find_world_map_country<'a>(
351    countries: &'a [WorldMapCountry],
352    country_id: &str,
353) -> Option<&'a WorldMapCountry> {
354    let id = normalize_id(country_id)?;
355
356    countries.iter().find(|country| country.id == id)
357}
358
359/// Resolves a country's display label.
360///
361/// `overrides` pairs a country id, such as `CO`, with a label. The last pair for the country wins,
362/// like inserting the pairs into a map. A blank override falls back to the dataset name; others
363/// are trimmed.
364pub fn resolve_world_map_country_label<'a, K, V>(
365    country: &'a WorldMapCountry,
366    overrides: &'a [(K, V)],
367) -> &'a str
368where
369    K: AsRef<str>,
370    V: AsRef<str>,
371{
372    overrides
373        .iter()
374        .rev()
375        .find(|(id, _)| id.as_ref() == country.id)
376        .map(|(_, label)| label.as_ref().trim())
377        .filter(|label| !label.is_empty())
378        .unwrap_or(&country.name)
379}
380
381/// Builds the selection details for `country`. `highlighted_ids` should be normalized, as
382/// returned by [`normalize_world_map_highlighted`].
383pub fn world_map_select_detail<S, K, V>(
384    country: &WorldMapCountry,
385    highlighted_ids: &[S],
386    overrides: &[(K, V)],
387) -> WorldMapSelectDetail
388where
389    S: AsRef<str>,
390    K: AsRef<str>,
391    V: AsRef<str>,
392{
393    WorldMapSelectDetail {
394        country_id: country.id.clone().into_owned(),
395        highlighted: highlighted_ids.iter().any(|id| id.as_ref() == country.id),
396        label: resolve_world_map_country_label(country, overrides).to_owned(),
397    }
398}
399
400/// One token of SVG path data.
401enum PathToken<'a> {
402    /// A command letter.
403    Command(char),
404    /// The text of one number.
405    Number(&'a str),
406}
407
408/// Splits path data into command letters and number texts in one forward pass. Commas and
409/// whitespace separate numbers, and a sign also starts a new number unless it follows an exponent.
410fn path_tokens(path: &str) -> impl Iterator<Item = PathToken<'_>> {
411    let mut rest = path;
412
413    std::iter::from_fn(move || {
414        rest = rest
415            .trim_start_matches(|character: char| character == ',' || character.is_whitespace());
416
417        let first = rest.chars().next()?;
418
419        if first.is_ascii_alphabetic() {
420            rest = &rest[first.len_utf8()..];
421
422            return Some(PathToken::Command(first));
423        }
424
425        let mut previous = None;
426        let end = rest
427            .char_indices()
428            .find(|&(index, character)| {
429                let continues = character.is_ascii_digit()
430                    || character == '.'
431                    || matches!(character, 'e' | 'E')
432                    || (matches!(character, '+' | '-')
433                        && (index == 0 || matches!(previous, Some('e' | 'E'))));
434
435                previous = Some(character);
436
437                !continues
438            })
439            .map_or(rest.len(), |(index, _)| index);
440
441        // A character that can't start a number becomes a one-character token that won't parse.
442        let end = if end == 0 { first.len_utf8() } else { end };
443        let (number, remaining) = rest.split_at(end);
444
445        rest = remaining;
446
447        Some(PathToken::Number(number))
448    })
449}
450
451/// Computes the bounding box of SVG path data that uses only absolute `M`, `L`, and `Z`
452/// commands, as the bundled countries do.
453///
454/// Returns `None` for empty data, other commands, malformed numbers, or a missing coordinate.
455pub fn world_map_path_bounds(path: &str) -> Option<WorldMapBounds> {
456    let mut min = WorldMapPoint {
457        x: f64::INFINITY,
458        y: f64::INFINITY,
459    };
460    let mut max = WorldMapPoint {
461        x: f64::NEG_INFINITY,
462        y: f64::NEG_INFINITY,
463    };
464    let mut started = false;
465    let mut pending_x: Option<f64> = None;
466
467    for token in path_tokens(path) {
468        match token {
469            PathToken::Command(command) => {
470                if pending_x.is_some() || !matches!(command, 'M' | 'L' | 'Z') {
471                    return None;
472                }
473
474                if !started && command != 'M' {
475                    return None;
476                }
477
478                started = true;
479            }
480            PathToken::Number(text) => {
481                let value: f64 = text.parse().ok().filter(|value: &f64| value.is_finite())?;
482
483                if !started {
484                    return None;
485                }
486
487                if let Some(x) = pending_x.take() {
488                    min = WorldMapPoint {
489                        x: min.x.min(x),
490                        y: min.y.min(value),
491                    };
492                    max = WorldMapPoint {
493                        x: max.x.max(x),
494                        y: max.y.max(value),
495                    };
496                } else {
497                    pending_x = Some(value);
498                }
499            }
500        }
501    }
502
503    if pending_x.is_some() || !min.x.is_finite() {
504        return None;
505    }
506
507    Some(WorldMapBounds::new(
508        min.x,
509        min.y,
510        max.x - min.x,
511        max.y - min.y,
512    ))
513}
514
515/// Clamps a zoom level to 1 through 8. Non-finite values reset to 1.
516pub fn normalize_world_map_zoom(value: f64) -> f64 {
517    if value.is_finite() {
518        value.clamp(WORLD_MAP_ZOOM_MIN, WORLD_MAP_ZOOM_MAX)
519    } else {
520        WORLD_MAP_ZOOM_MIN
521    }
522}
523
524/// Zoom multiplier for a modified (Ctrl or Cmd) wheel event: `exp(-delta_y * 0.002)`, with the
525/// delta clamped to ±1000 pixels. Convert line deltas (×16) and page deltas (× viewport height)
526/// to pixels first. A non-finite delta gives 1.
527pub fn world_map_wheel_zoom_factor(delta_y: f64) -> f64 {
528    if delta_y.is_finite() {
529        (-delta_y.clamp(-WHEEL_DELTA_LIMIT, WHEEL_DELTA_LIMIT) * WHEEL_ZOOM_RATE).exp()
530    } else {
531        1.0
532    }
533}
534
535/// Whether a pointer that moved `dx`, `dy` CSS pixels since it was pressed has traveled far
536/// enough to start panning. Shorter moves stay clicks.
537pub fn world_map_pan_threshold_reached(dx: f64, dy: f64) -> bool {
538    dx.hypot(dy) >= WORLD_MAP_PAN_THRESHOLD
539}
540
541/// Keeps a view's center far enough from the edges that the visible span stays inside the map.
542fn clamp_center(center: f64, span: f64, extent: f64) -> f64 {
543    let half = span / 2.0;
544
545    if center.is_finite() {
546        center.max(half).min(extent - half)
547    } else {
548        extent / 2.0
549    }
550}
551
552/// Formats a `viewBox` number like JavaScript: no trailing `.0`, no `-0`, at most four decimals.
553fn format_view_box_number(value: f64) -> String {
554    let rounded = (value * VIEW_BOX_ROUNDING).round() / VIEW_BOX_ROUNDING;
555
556    if rounded == 0.0 {
557        "0".to_owned()
558    } else {
559        rounded.to_string()
560    }
561}
562
563/// The visible region of the map: a zoom level and the center of the region in `viewBox` units.
564///
565/// The component renders [`WorldMapView::view_box_attribute`] as the SVG `viewBox`, which works on
566/// every renderer, including Dioxus Native. Every method returns a clamped view that stays inside
567/// the map, and [`WorldMapView::view_box`] clamps fields that were set directly.
568#[derive(Clone, Copy, Debug, PartialEq)]
569pub struct WorldMapView {
570    /// Zoom level from 1 (whole map) to 8.
571    pub zoom: f64,
572    /// Horizontal center of the visible region.
573    pub center_x: f64,
574    /// Vertical center of the visible region.
575    pub center_y: f64,
576}
577
578impl Default for WorldMapView {
579    /// The whole map at zoom 1.
580    fn default() -> Self {
581        Self {
582            zoom: WORLD_MAP_ZOOM_MIN,
583            center_x: WORLD_MAP_VIEW_BOX_WIDTH / 2.0,
584            center_y: WORLD_MAP_VIEW_BOX_HEIGHT / 2.0,
585        }
586    }
587}
588
589impl WorldMapView {
590    /// Creates a view, clamping the zoom and moving the center so the region stays inside the map.
591    pub fn new(zoom: f64, center_x: f64, center_y: f64) -> Self {
592        let zoom = normalize_world_map_zoom(zoom);
593
594        Self {
595            zoom,
596            center_x: clamp_center(
597                center_x,
598                WORLD_MAP_VIEW_BOX_WIDTH / zoom,
599                WORLD_MAP_VIEW_BOX_WIDTH,
600            ),
601            center_y: clamp_center(
602                center_y,
603                WORLD_MAP_VIEW_BOX_HEIGHT / zoom,
604                WORLD_MAP_VIEW_BOX_HEIGHT,
605            ),
606        }
607    }
608
609    /// The visible region: `1000 / zoom` by `400 / zoom` units, inside the map.
610    pub fn view_box(&self) -> WorldMapBounds {
611        let view = Self::new(self.zoom, self.center_x, self.center_y);
612        let width = WORLD_MAP_VIEW_BOX_WIDTH / view.zoom;
613        let height = WORLD_MAP_VIEW_BOX_HEIGHT / view.zoom;
614
615        WorldMapBounds {
616            x: view.center_x - width / 2.0,
617            y: view.center_y - height / 2.0,
618            width,
619            height,
620        }
621    }
622
623    /// The SVG `viewBox` attribute, such as `0 0 1000 400` for the whole map.
624    pub fn view_box_attribute(&self) -> String {
625        let view_box = self.view_box();
626
627        [view_box.x, view_box.y, view_box.width, view_box.height]
628            .map(format_view_box_number)
629            .join(" ")
630    }
631
632    /// The zoom level as a rounded percentage, such as `150%`.
633    pub fn zoom_percent(&self) -> String {
634        format!("{}%", (normalize_world_map_zoom(self.zoom) * 100.0).round())
635    }
636
637    /// Whether the zoom in button can act.
638    pub fn can_zoom_in(&self) -> bool {
639        normalize_world_map_zoom(self.zoom) < WORLD_MAP_ZOOM_MAX
640    }
641
642    /// Whether the map is zoomed in, which enables zoom out, reset, and panning.
643    pub fn can_zoom_out(&self) -> bool {
644        normalize_world_map_zoom(self.zoom) > WORLD_MAP_ZOOM_MIN
645    }
646
647    /// Zooms to `zoom`, keeping `anchor` (in `viewBox` units) at the same place in the viewport.
648    /// Without an anchor, the view zooms around its center.
649    #[must_use]
650    pub fn zoom_to(&self, zoom: f64, anchor: Option<WorldMapPoint>) -> Self {
651        let current = self.view_box();
652        let next = normalize_world_map_zoom(zoom);
653        let anchor = anchor
654            .filter(|point| point.x.is_finite() && point.y.is_finite())
655            .unwrap_or_else(|| current.center());
656        let fraction_x = (anchor.x - current.x) / current.width;
657        let fraction_y = (anchor.y - current.y) / current.height;
658        let width = WORLD_MAP_VIEW_BOX_WIDTH / next;
659        let height = WORLD_MAP_VIEW_BOX_HEIGHT / next;
660
661        Self::new(
662            next,
663            anchor.x - fraction_x * width + width / 2.0,
664            anchor.y - fraction_y * height + height / 2.0,
665        )
666    }
667
668    /// Zooms in by one button step around the center.
669    #[must_use]
670    pub fn zoom_in(&self) -> Self {
671        self.zoom_to(
672            normalize_world_map_zoom(self.zoom) + WORLD_MAP_ZOOM_STEP,
673            None,
674        )
675    }
676
677    /// Zooms out by one button step around the center.
678    #[must_use]
679    pub fn zoom_out(&self) -> Self {
680        self.zoom_to(
681            normalize_world_map_zoom(self.zoom) - WORLD_MAP_ZOOM_STEP,
682            None,
683        )
684    }
685
686    /// Applies a modified wheel event's pixel delta, keeping `anchor` in place. See
687    /// [`world_map_wheel_zoom_factor`].
688    #[must_use]
689    pub fn zoom_by_wheel(&self, delta_y: f64, anchor: Option<WorldMapPoint>) -> Self {
690        self.zoom_to(
691            normalize_world_map_zoom(self.zoom) * world_map_wheel_zoom_factor(delta_y),
692            anchor,
693        )
694    }
695
696    /// Moves the visible region by `dx`, `dy` `viewBox` units, staying inside the map. Positive
697    /// values reveal more of the east and south. Non-finite values count as 0.
698    #[must_use]
699    pub fn pan_by(&self, dx: f64, dy: f64) -> Self {
700        let view = self.view_box().center();
701        let finite_or_zero = |value: f64| if value.is_finite() { value } else { 0.0 };
702
703        Self::new(
704            self.zoom,
705            view.x + finite_or_zero(dx),
706            view.y + finite_or_zero(dy),
707        )
708    }
709
710    /// Converts a pointer position in the rendered viewport, in CSS pixels from its top-left
711    /// corner, to `viewBox` units. It follows the default `preserveAspectRatio` (`xMidYMid meet`),
712    /// so it also works when the viewport's aspect ratio differs from the map's.
713    ///
714    /// Returns `None` for a viewport without a positive, finite size or a non-finite position.
715    pub fn viewport_point(
716        &self,
717        x: f64,
718        y: f64,
719        viewport_width: f64,
720        viewport_height: f64,
721    ) -> Option<WorldMapPoint> {
722        let view_box = self.view_box();
723        let scale = meet_scale(view_box, viewport_width, viewport_height)?;
724
725        if !x.is_finite() || !y.is_finite() {
726            return None;
727        }
728
729        let offset_x = (viewport_width - view_box.width * scale) / 2.0;
730        let offset_y = (viewport_height - view_box.height * scale) / 2.0;
731
732        Some(WorldMapPoint {
733            x: view_box.x + (x - offset_x) / scale,
734            y: view_box.y + (y - offset_y) / scale,
735        })
736    }
737
738    /// Pans by a pointer drag of `dx`, `dy` CSS pixels so the map follows the pointer. Returns the
739    /// view unchanged when the viewport has no positive, finite size.
740    #[must_use]
741    pub fn drag_by(&self, dx: f64, dy: f64, viewport_width: f64, viewport_height: f64) -> Self {
742        match meet_scale(self.view_box(), viewport_width, viewport_height) {
743            Some(scale) => self.pan_by(-dx / scale, -dy / scale),
744            None => Self::new(self.zoom, self.center_x, self.center_y),
745        }
746    }
747
748    /// The view that fits `bounds` with a margin: `min(1000 / width, 400 / height) * 0.85`,
749    /// clamped to 1 through 8 and centered on the bounds. Sizes under one unit count as one, and
750    /// non-finite bounds give the whole map.
751    pub fn fit_bounds(bounds: WorldMapBounds) -> Self {
752        if !bounds.is_finite() {
753            return Self::default();
754        }
755
756        let scale = (WORLD_MAP_VIEW_BOX_WIDTH / bounds.width.max(1.0))
757            .min(WORLD_MAP_VIEW_BOX_HEIGHT / bounds.height.max(1.0));
758        let center = bounds.center();
759
760        Self::new(scale * FIT_PADDING, center.x, center.y)
761    }
762
763    /// The view that fits every highlighted country, or `None` when no id matches a country with
764    /// finite bounds. Ids are matched like [`find_world_map_country`].
765    pub fn fit_highlighted<S: AsRef<str>>(
766        countries: &[WorldMapCountry],
767        highlighted_ids: &[S],
768    ) -> Option<Self> {
769        highlighted_ids
770            .iter()
771            .filter_map(|id| find_world_map_country(countries, id.as_ref()))
772            .map(|country| country.bounds)
773            .filter(|bounds| bounds.is_finite())
774            .reduce(WorldMapBounds::union)
775            .map(Self::fit_bounds)
776    }
777}
778
779/// CSS pixels per `viewBox` unit under `xMidYMid meet`, or `None` for an unusable viewport.
780fn meet_scale(view_box: WorldMapBounds, viewport_width: f64, viewport_height: f64) -> Option<f64> {
781    let usable = |value: f64| value.is_finite() && value > 0.0;
782
783    if !usable(viewport_width) || !usable(viewport_height) {
784        return None;
785    }
786
787    Some((viewport_width / view_box.width).min(viewport_height / view_box.height))
788}
789
790#[cfg(test)]
791mod tests {
792    use super::*;
793
794    const EPSILON: f64 = 1e-9;
795
796    fn close(actual: f64, expected: f64) -> bool {
797        (actual - expected).abs() < EPSILON
798    }
799
800    fn assert_close(actual: f64, expected: f64) {
801        assert!(close(actual, expected), "expected {expected}, got {actual}");
802    }
803
804    fn assert_point(actual: Option<WorldMapPoint>, expected: WorldMapPoint) {
805        assert!(
806            actual.is_some_and(|actual| close(actual.x, expected.x) && close(actual.y, expected.y)),
807            "expected {expected:?}, got {actual:?}"
808        );
809    }
810
811    fn assert_bounds(actual: WorldMapBounds, expected: WorldMapBounds) {
812        assert!(
813            close(actual.x, expected.x)
814                && close(actual.y, expected.y)
815                && close(actual.width, expected.width)
816                && close(actual.height, expected.height),
817            "expected {expected:?}, got {actual:?}"
818        );
819    }
820
821    fn country(id: &str, name: &str, label_x: f64, path: &str) -> WorldMapCountry {
822        WorldMapCountry {
823            id: Cow::Owned(id.to_owned()),
824            name: Cow::Owned(name.to_owned()),
825            path: Cow::Owned(path.to_owned()),
826            label_x,
827            label_y: 220.0,
828            bounds: WorldMapBounds::new(0.0, 0.0, 1.0, 1.0),
829        }
830    }
831
832    fn colombia() -> WorldMapCountry {
833        country("CO", "Colombia", 300.0, "M0 0Z")
834    }
835
836    fn japan() -> WorldMapCountry {
837        country("JP", "Japan", 820.0, "M1 1Z")
838    }
839
840    fn marker(id: &str, label: &str, latitude: f64, longitude: f64) -> WorldMapMarker {
841        WorldMapMarker {
842            id: id.to_owned(),
843            label: label.to_owned(),
844            latitude,
845            longitude,
846        }
847    }
848
849    fn no_overrides() -> &'static [(&'static str, &'static str)] {
850        &[]
851    }
852
853    #[test]
854    fn projects_the_corners_and_center_of_the_view_box() {
855        let top_left = project_world_map_coordinate(-180.0, WORLD_MAP_LATITUDE_MAX);
856        let bottom_right = project_world_map_coordinate(180.0, WORLD_MAP_LATITUDE_MIN);
857
858        assert_eq!(top_left, Some(WorldMapPoint { x: 0.0, y: 0.0 }));
859        assert_eq!(
860            bottom_right,
861            Some(WorldMapPoint {
862                x: WORLD_MAP_VIEW_BOX_WIDTH,
863                y: WORLD_MAP_VIEW_BOX_HEIGHT,
864            })
865        );
866        assert_close(
867            project_world_map_coordinate(0.0, 0.0).map_or(f64::NAN, |point| point.x),
868            WORLD_MAP_VIEW_BOX_WIDTH / 2.0,
869        );
870    }
871
872    #[test]
873    fn rejects_coordinates_that_cannot_be_projected() {
874        for (longitude, latitude) in [
875            (f64::NAN, 0.0),
876            (0.0, f64::NAN),
877            (f64::INFINITY, 0.0),
878            (0.0, f64::NEG_INFINITY),
879            (181.0, 0.0),
880            (-181.0, 0.0),
881            (0.0, 91.0),
882            (0.0, -91.0),
883        ] {
884            assert_eq!(project_world_map_coordinate(longitude, latitude), None);
885        }
886
887        let north_of_band = project_world_map_coordinate(0.0, 90.0);
888
889        assert!(north_of_band.is_some_and(|point| point.y < 0.0));
890    }
891
892    #[test]
893    fn normalizes_untrusted_geometry() {
894        let mut lower_case = colombia();
895        lower_case.id = Cow::Owned(" co ".to_owned());
896        let mut blank_id = japan();
897        blank_id.id = Cow::Borrowed("  ");
898        let mut blank_name = japan();
899        blank_name.name = Cow::Borrowed(" ");
900        let mut blank_path = japan();
901        blank_path.path = Cow::Borrowed("");
902        let mut bad_label = japan();
903        bad_label.label_x = f64::NAN;
904
905        let countries = normalize_world_map_countries(&[
906            blank_id,
907            blank_name,
908            blank_path,
909            lower_case,
910            colombia(),
911            bad_label,
912        ]);
913
914        assert_eq!(countries, vec![colombia()]);
915        assert_eq!(normalize_world_map_countries(&[]), Vec::new());
916    }
917
918    #[test]
919    fn keeps_already_normal_static_ids_borrowed() {
920        let trimmed = WorldMapCountry {
921            id: Cow::Borrowed(" FR "),
922            ..colombia()
923        };
924        let countries = normalize_world_map_countries(&[trimmed]);
925
926        assert!(matches!(countries[0].id, Cow::Borrowed("FR")));
927    }
928
929    #[test]
930    fn normalizes_highlighted_ids() {
931        let countries = [colombia(), japan()];
932        let highlighted =
933            normalize_world_map_highlighted(&[" co ", "jp", "co", "ZZ", "", "  "], &countries);
934
935        assert_eq!(highlighted, vec!["CO".to_owned(), "JP".to_owned()]);
936        assert_eq!(
937            normalize_world_map_highlighted::<String>(&[], &countries),
938            Vec::<String>::new()
939        );
940        assert_eq!(
941            normalize_world_map_highlighted(&["CO"], &[]),
942            Vec::<String>::new()
943        );
944    }
945
946    #[test]
947    fn normalizes_markers() {
948        let markers = normalize_world_map_markers(&[
949            marker(" bogota ", " Bogotá ", 4.711, -74.072),
950            marker("bogota", "Duplicate", 0.0, 0.0),
951            marker("", "No id", 0.0, 0.0),
952            marker("no-label", " ", 0.0, 0.0),
953            marker("bad-lat", "Out of range", 95.0, 0.0),
954            marker("nan-lon", "Not finite", 0.0, f64::NAN),
955            marker("north-pole", "Outside the view", 90.0, 0.0),
956            marker("south-pole", "Outside the view", -90.0, 0.0),
957            marker("south-of-band", "Outside the view", -60.5, 0.0),
958            marker("bad-lon", "Out of range", 0.0, 180.5),
959            marker("edge", "Band edge", WORLD_MAP_LATITUDE_MAX, 180.0),
960        ]);
961
962        assert_eq!(
963            markers,
964            vec![
965                marker("bogota", "Bogotá", 4.711, -74.072),
966                marker("edge", "Band edge", WORLD_MAP_LATITUDE_MAX, 180.0),
967            ]
968        );
969        assert_eq!(normalize_world_map_markers(&[]), Vec::new());
970        assert_eq!(
971            markers[1].point(),
972            Some(WorldMapPoint {
973                x: WORLD_MAP_VIEW_BOX_WIDTH,
974                y: 0.0,
975            })
976        );
977    }
978
979    #[test]
980    fn finds_countries_case_insensitively() {
981        let countries = [colombia(), japan()];
982
983        assert_eq!(
984            find_world_map_country(&countries, " co "),
985            Some(&countries[0])
986        );
987        assert_eq!(find_world_map_country(&countries, "ZZ"), None);
988        assert_eq!(find_world_map_country(&countries, ""), None);
989        assert_eq!(find_world_map_country(&countries, "   "), None);
990    }
991
992    #[test]
993    fn resolves_labels_with_overrides() {
994        let colombia = colombia();
995
996        assert_eq!(
997            resolve_world_map_country_label(&colombia, no_overrides()),
998            "Colombia"
999        );
1000        assert_eq!(
1001            resolve_world_map_country_label(&colombia, &[("CO", " Home base ")]),
1002            "Home base"
1003        );
1004        assert_eq!(
1005            resolve_world_map_country_label(&colombia, &[("CO", "   ")]),
1006            "Colombia"
1007        );
1008        assert_eq!(
1009            resolve_world_map_country_label(&colombia, &[("JP", "Tokyo")]),
1010            "Colombia"
1011        );
1012        assert_eq!(
1013            resolve_world_map_country_label(&colombia, &[("CO", "First"), ("CO", "Last")]),
1014            "Last"
1015        );
1016
1017        let owned = [("CO".to_owned(), "Home".to_owned())];
1018
1019        assert_eq!(resolve_world_map_country_label(&colombia, &owned), "Home");
1020    }
1021
1022    #[test]
1023    fn builds_select_details() {
1024        let highlighted = ["CO"];
1025
1026        assert_eq!(
1027            world_map_select_detail(&colombia(), &highlighted, no_overrides()),
1028            WorldMapSelectDetail {
1029                country_id: "CO".to_owned(),
1030                highlighted: true,
1031                label: "Colombia".to_owned(),
1032            }
1033        );
1034        assert_eq!(
1035            world_map_select_detail(&japan(), &highlighted, no_overrides()),
1036            WorldMapSelectDetail {
1037                country_id: "JP".to_owned(),
1038                highlighted: false,
1039                label: "Japan".to_owned(),
1040            }
1041        );
1042        assert_eq!(
1043            world_map_select_detail(&colombia(), &highlighted, &[("CO", "Home")]).label,
1044            "Home"
1045        );
1046    }
1047
1048    #[test]
1049    fn variant_strings_match_the_data_attribute() {
1050        assert_eq!(WorldMapVariant::default(), WorldMapVariant::Dotted);
1051        assert_eq!(WorldMapVariant::Dotted.as_str(), "dotted");
1052        assert_eq!(WorldMapVariant::Solid.as_str(), "solid");
1053    }
1054
1055    #[test]
1056    fn clamps_zoom() {
1057        for (value, expected) in [
1058            (0.0, 1.0),
1059            (1.5, 1.5),
1060            (10.0, 8.0),
1061            (f64::NAN, 1.0),
1062            (f64::INFINITY, 1.0),
1063            (f64::NEG_INFINITY, 1.0),
1064        ] {
1065            assert_close(normalize_world_map_zoom(value), expected);
1066        }
1067    }
1068
1069    #[test]
1070    fn default_view_shows_the_whole_map() {
1071        let view = WorldMapView::default();
1072
1073        assert_bounds(
1074            view.view_box(),
1075            WorldMapBounds::new(0.0, 0.0, 1000.0, 400.0),
1076        );
1077        assert_eq!(view.view_box_attribute(), "0 0 1000 400");
1078        assert_eq!(view.zoom_percent(), "100%");
1079        assert!(view.can_zoom_in());
1080        assert!(!view.can_zoom_out());
1081    }
1082
1083    #[test]
1084    fn clamps_the_view_box_inside_the_map() {
1085        assert_bounds(
1086            WorldMapView::new(2.0, 0.0, 0.0).view_box(),
1087            WorldMapBounds::new(0.0, 0.0, 500.0, 200.0),
1088        );
1089        assert_bounds(
1090            WorldMapView::new(2.0, 1000.0, 400.0).view_box(),
1091            WorldMapBounds::new(500.0, 200.0, 500.0, 200.0),
1092        );
1093        assert_bounds(
1094            WorldMapView::new(1.0, 900.0, 10.0).view_box(),
1095            WorldMapBounds::new(0.0, 0.0, 1000.0, 400.0),
1096        );
1097
1098        let unclamped = WorldMapView {
1099            zoom: 20.0,
1100            center_x: f64::NAN,
1101            center_y: -50.0,
1102        };
1103
1104        assert_bounds(
1105            unclamped.view_box(),
1106            WorldMapBounds::new(437.5, 0.0, 125.0, 50.0),
1107        );
1108    }
1109
1110    #[test]
1111    fn zoom_buttons_keep_the_center_and_clamp_limits() {
1112        // JS: an 800x320 viewport scrolls to (200, 80) at 150%, which is (166.67, 66.67) in units.
1113        let view = WorldMapView::default().zoom_in();
1114
1115        assert_eq!(view.zoom_percent(), "150%");
1116        assert_bounds(
1117            view.view_box(),
1118            WorldMapBounds::new(200.0 / 1.2, 80.0 / 1.2, 1000.0 / 1.5, 400.0 / 1.5),
1119        );
1120
1121        let mut view = view;
1122
1123        for _ in 0..20 {
1124            view = view.zoom_in();
1125        }
1126
1127        assert_eq!(view.zoom_percent(), "800%");
1128        assert!(!view.can_zoom_in());
1129        assert_eq!(view.zoom_out().zoom_percent(), "750%");
1130        assert_eq!(WorldMapView::default().zoom_out(), WorldMapView::default());
1131    }
1132
1133    #[test]
1134    fn zoom_keeps_the_anchor_in_place() {
1135        // JS: at 150% in an 800px viewport scrolled to 200, a wheel delta of -100 at clientX 100
1136        // scrolls to (200 + 100) * e^0.2 - 100 pixels.
1137        let view = WorldMapView::default().zoom_in();
1138        let anchor = WorldMapPoint { x: 250.0, y: 120.0 };
1139        let zoomed = view.zoom_by_wheel(-100.0, Some(anchor));
1140        let zoom = 1.5 * 0.2_f64.exp();
1141        let pixels_per_unit = 800.0 * zoom / 1000.0;
1142
1143        assert_close(zoomed.zoom, zoom);
1144        assert_close(
1145            zoomed.view_box().x * pixels_per_unit,
1146            (200.0 + 100.0) * 0.2_f64.exp() - 100.0,
1147        );
1148
1149        let before = view.view_box();
1150        let after = zoomed.view_box();
1151
1152        assert_close(
1153            (anchor.x - before.x) / before.width,
1154            (anchor.x - after.x) / after.width,
1155        );
1156        assert_close(
1157            (anchor.y - before.y) / before.height,
1158            (anchor.y - after.y) / after.height,
1159        );
1160    }
1161
1162    #[test]
1163    fn zooming_out_near_an_edge_stays_inside_the_map() {
1164        let view = WorldMapView::new(8.0, 990.0, 390.0)
1165            .zoom_to(2.0, Some(WorldMapPoint { x: 999.0, y: 399.0 }));
1166
1167        assert_bounds(
1168            view.view_box(),
1169            WorldMapBounds::new(500.0, 200.0, 500.0, 200.0),
1170        );
1171    }
1172
1173    #[test]
1174    fn pans_within_the_map() {
1175        let view = WorldMapView::new(2.0, 500.0, 200.0);
1176
1177        assert_bounds(
1178            view.pan_by(1000.0, 0.0).view_box(),
1179            WorldMapBounds::new(500.0, 100.0, 500.0, 200.0),
1180        );
1181        assert_bounds(
1182            view.pan_by(-1000.0, -1000.0).view_box(),
1183            WorldMapBounds::new(0.0, 0.0, 500.0, 200.0),
1184        );
1185        assert_bounds(
1186            view.pan_by(25.0, -10.0).view_box(),
1187            WorldMapBounds::new(275.0, 90.0, 500.0, 200.0),
1188        );
1189        assert_eq!(view.pan_by(f64::NAN, f64::INFINITY), view);
1190        assert_eq!(
1191            WorldMapView::default().pan_by(100.0, 50.0),
1192            WorldMapView::default()
1193        );
1194    }
1195
1196    #[test]
1197    fn converts_viewport_pixels_to_map_units() {
1198        let view = WorldMapView::default();
1199
1200        let center = WorldMapPoint { x: 500.0, y: 200.0 };
1201
1202        assert_point(view.viewport_point(400.0, 160.0, 800.0, 320.0), center);
1203        // A square viewport letterboxes the map: 300px above and below at one pixel per unit.
1204        assert_point(view.viewport_point(500.0, 500.0, 1000.0, 1000.0), center);
1205        assert_point(
1206            WorldMapView::new(2.0, 250.0, 100.0).viewport_point(0.0, 0.0, 800.0, 320.0),
1207            WorldMapPoint { x: 0.0, y: 0.0 },
1208        );
1209        assert_eq!(view.viewport_point(1.0, 1.0, 0.0, 320.0), None);
1210        assert_eq!(view.viewport_point(f64::NAN, 1.0, 800.0, 320.0), None);
1211
1212        let zoomed = WorldMapView::new(2.0, 500.0, 200.0);
1213
1214        assert_close(
1215            zoomed.drag_by(100.0, 0.0, 800.0, 320.0).center_x,
1216            500.0 - 62.5,
1217        );
1218        assert_eq!(zoomed.drag_by(100.0, 0.0, f64::NAN, 320.0), zoomed);
1219    }
1220
1221    #[test]
1222    fn wheel_and_pan_thresholds() {
1223        assert_close(world_map_wheel_zoom_factor(-100.0), 0.2_f64.exp());
1224        assert_close(world_map_wheel_zoom_factor(5000.0), (-2.0_f64).exp());
1225        assert_close(world_map_wheel_zoom_factor(f64::NAN), 1.0);
1226        assert!(!world_map_pan_threshold_reached(3.0, 0.0));
1227        assert!(world_map_pan_threshold_reached(4.0, 0.0));
1228        assert!(world_map_pan_threshold_reached(-3.0, 3.0));
1229        assert!(!world_map_pan_threshold_reached(f64::NAN, 0.0));
1230    }
1231
1232    #[test]
1233    fn fits_bounds_with_padding() {
1234        // JS: the union (100, 50, 250, 100) fits at 340% and scrolls an 800x320 viewport to
1235        // (212, 112), which is (212, 112) / 2.72 in units.
1236        let union = WorldMapBounds::new(100.0, 50.0, 100.0, 50.0)
1237            .union(WorldMapBounds::new(300.0, 100.0, 50.0, 50.0));
1238
1239        assert_bounds(union, WorldMapBounds::new(100.0, 50.0, 250.0, 100.0));
1240
1241        let view = WorldMapView::fit_bounds(union);
1242
1243        assert_close(view.zoom, 3.4);
1244        assert_close(view.view_box().x, 212.0 / 2.72);
1245        assert_close(view.view_box().y, 112.0 / 2.72);
1246        assert_eq!(view.zoom_percent(), "340%");
1247
1248        let tiny = WorldMapView::fit_bounds(WorldMapBounds::new(500.0, 200.0, 0.0, 0.0));
1249
1250        assert_close(tiny.zoom, WORLD_MAP_ZOOM_MAX);
1251        assert_close(tiny.center_x, 500.0);
1252
1253        let huge = WorldMapView::fit_bounds(WorldMapBounds::new(-50.0, -20.0, 2000.0, 800.0));
1254
1255        assert_eq!(huge, WorldMapView::default());
1256        assert_eq!(
1257            WorldMapView::fit_bounds(WorldMapBounds::new(f64::NAN, 0.0, 1.0, 1.0)),
1258            WorldMapView::default()
1259        );
1260    }
1261
1262    #[test]
1263    fn fits_highlighted_countries() {
1264        let countries = world_map_countries();
1265        let none: [&str; 0] = [];
1266
1267        assert_eq!(WorldMapView::fit_highlighted(countries, &none), None);
1268        assert_eq!(WorldMapView::fit_highlighted(countries, &["ZZ"]), None);
1269
1270        let colombia = find_world_map_country(countries, "co").map(|country| country.bounds);
1271        let view = WorldMapView::fit_highlighted(countries, &["co", "ZZ"]);
1272
1273        assert_eq!(view, colombia.map(WorldMapView::fit_bounds));
1274
1275        let visible = view.map(|view| view.view_box());
1276
1277        assert!(visible.zip(colombia).is_some_and(|(visible, colombia)| {
1278            visible.x <= colombia.x
1279                && visible.y <= colombia.y
1280                && visible.x + visible.width >= colombia.x + colombia.width
1281                && visible.y + visible.height >= colombia.y + colombia.height
1282        }));
1283
1284        let pair = WorldMapView::fit_highlighted(countries, &["CO", "JP"]);
1285        let japan = find_world_map_country(countries, "JP").map(|country| country.bounds);
1286
1287        assert_eq!(
1288            pair,
1289            colombia
1290                .zip(japan)
1291                .map(|(colombia, japan)| WorldMapView::fit_bounds(colombia.union(japan)))
1292        );
1293    }
1294
1295    #[test]
1296    fn formats_the_view_box_attribute_like_javascript() {
1297        assert_eq!(
1298            WorldMapView::new(1.5, 500.0, 200.0).view_box_attribute(),
1299            "166.6667 66.6667 666.6667 266.6667"
1300        );
1301        assert_eq!(
1302            WorldMapView::new(2.0, 0.0, 0.0).view_box_attribute(),
1303            "0 0 500 200"
1304        );
1305        assert_eq!(format_view_box_number(-0.000_01), "0");
1306        assert_eq!(format_view_box_number(12.5), "12.5");
1307    }
1308
1309    #[test]
1310    fn computes_path_bounds() {
1311        assert_eq!(
1312            world_map_path_bounds("M0 0L10 5L3 -2ZM-1 1L2 2Z"),
1313            Some(WorldMapBounds::new(-1.0, -2.0, 11.0, 7.0))
1314        );
1315        assert_eq!(
1316            world_map_path_bounds(" M 1,2 L 3,4\nL-1e1-2 Z "),
1317            Some(WorldMapBounds::new(-10.0, -2.0, 13.0, 6.0))
1318        );
1319
1320        for invalid in [
1321            "",
1322            "Z",
1323            "L1 2",
1324            "M1",
1325            "M1 2L3",
1326            "M0 0C1 1 2 2 3 3Z",
1327            "m0 0l1 1z",
1328            "M0 0L1 xZ",
1329            "M0 0L1 1..2Z",
1330            "M0 0L1 NaNZ",
1331            "1 2",
1332        ] {
1333            assert_eq!(world_map_path_bounds(invalid), None, "{invalid:?}");
1334        }
1335    }
1336
1337    #[test]
1338    fn path_bounds_stay_linear_on_long_input() {
1339        let mut path = String::from("M0 0");
1340
1341        for index in 0..50_000_u32 {
1342            path.push('L');
1343            path.push_str(&index.to_string());
1344            path.push(' ');
1345            path.push_str(&(index % 7).to_string());
1346        }
1347
1348        path.push('Z');
1349
1350        assert_eq!(
1351            world_map_path_bounds(&path),
1352            Some(WorldMapBounds::new(0.0, 0.0, 49_999.0, 6.0))
1353        );
1354        assert_eq!(world_map_path_bounds(&"-".repeat(100_000)), None);
1355        assert_eq!(world_map_path_bounds(&"1".repeat(100_000)), None);
1356    }
1357
1358    #[test]
1359    fn bundled_data_is_complete_and_normal() {
1360        let countries = world_map_countries();
1361
1362        assert!(countries.len() > 230, "only {} countries", countries.len());
1363
1364        let mut ids = HashSet::new();
1365
1366        for country in countries {
1367            assert!(!country.id.is_empty() && country.id.trim() == country.id);
1368            assert_eq!(country.id.to_uppercase(), country.id);
1369            assert!(
1370                ids.insert(country.id.as_ref()),
1371                "duplicate id {}",
1372                country.id
1373            );
1374            assert!(
1375                !country.name.trim().is_empty(),
1376                "{} has no name",
1377                country.id
1378            );
1379            assert!(country.path.starts_with('M') && country.path.ends_with('Z'));
1380            assert!(country.label_x.is_finite() && country.label_y.is_finite());
1381
1382            let bounds = country.bounds;
1383
1384            assert!(bounds.is_finite(), "{} bounds {bounds:?}", country.id);
1385            assert!(bounds.width >= 0.0 && bounds.height >= 0.0);
1386            assert!(
1387                bounds.x >= 0.0
1388                    && bounds.y >= 0.0
1389                    && bounds.x + bounds.width <= WORLD_MAP_VIEW_BOX_WIDTH
1390                    && bounds.y + bounds.height <= WORLD_MAP_VIEW_BOX_HEIGHT,
1391                "{} bounds {bounds:?} leave the map",
1392                country.id
1393            );
1394
1395            let measured = world_map_path_bounds(&country.path);
1396
1397            assert!(
1398                measured.is_some_and(|measured| {
1399                    (measured.x - bounds.x).abs() < 1e-6
1400                        && (measured.y - bounds.y).abs() < 1e-6
1401                        && (measured.width - bounds.width).abs() < 1e-6
1402                        && (measured.height - bounds.height).abs() < 1e-6
1403                }),
1404                "{} bounds {bounds:?} differ from its path {measured:?}",
1405                country.id
1406            );
1407        }
1408
1409        for id in ["CO", "JP", "SOL", "CYN", "XK"] {
1410            assert!(ids.contains(id), "missing {id}");
1411        }
1412
1413        let normalized = normalize_world_map_countries(countries);
1414
1415        assert_eq!(normalized, countries);
1416        assert!(
1417            normalized
1418                .iter()
1419                .all(|country| matches!(country.id, Cow::Borrowed(_)))
1420        );
1421        assert_eq!(
1422            find_world_map_country(countries, "ci").map(|country| country.name.as_ref()),
1423            Some("Côte d'Ivoire")
1424        );
1425    }
1426}