1use std::borrow::Cow;
11use std::collections::HashSet;
12
13use super::countries::WORLD_MAP_COUNTRY_DATA;
14
15pub const WORLD_MAP_VIEW_BOX_WIDTH: f64 = 1000.0;
17
18pub const WORLD_MAP_VIEW_BOX_HEIGHT: f64 = 400.0;
20
21pub const WORLD_MAP_LATITUDE_MIN: f64 = -60.0;
23
24pub const WORLD_MAP_LATITUDE_MAX: f64 = 84.0;
26
27pub const WORLD_MAP_ZOOM_MIN: f64 = 1.0;
29
30pub const WORLD_MAP_ZOOM_MAX: f64 = 8.0;
32
33pub const WORLD_MAP_ZOOM_STEP: f64 = 0.5;
35
36pub const WORLD_MAP_PAN_THRESHOLD: f64 = 4.0;
38
39const FIT_PADDING: f64 = 0.85;
41
42const WHEEL_DELTA_LIMIT: f64 = 1000.0;
44
45const WHEEL_ZOOM_RATE: f64 = 0.002;
47
48const VIEW_BOX_ROUNDING: f64 = 10_000.0;
50
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
53#[non_exhaustive]
54pub enum WorldMapVariant {
55 #[default]
57 Dotted,
58 Solid,
60}
61
62impl WorldMapVariant {
63 pub const fn as_str(self) -> &'static str {
65 match self {
66 Self::Dotted => "dotted",
67 Self::Solid => "solid",
68 }
69 }
70}
71
72#[derive(Clone, Copy, Debug, Default, PartialEq)]
74pub struct WorldMapPoint {
75 pub x: f64,
77 pub y: f64,
79}
80
81#[derive(Clone, Copy, Debug, Default, PartialEq)]
83pub struct WorldMapBounds {
84 pub x: f64,
86 pub y: f64,
88 pub width: f64,
90 pub height: f64,
92}
93
94impl WorldMapBounds {
95 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 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 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 #[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#[derive(Clone, Debug, PartialEq)]
143pub struct WorldMapCountry {
144 pub id: Cow<'static, str>,
147 pub name: Cow<'static, str>,
149 pub path: Cow<'static, str>,
151 pub label_x: f64,
153 pub label_y: f64,
155 pub bounds: WorldMapBounds,
157}
158
159#[derive(Clone, Debug, PartialEq)]
161pub struct WorldMapMarker {
162 pub id: String,
164 pub label: String,
166 pub latitude: f64,
168 pub longitude: f64,
170}
171
172impl WorldMapMarker {
173 pub fn point(&self) -> Option<WorldMapPoint> {
175 project_world_map_coordinate(self.longitude, self.latitude)
176 }
177}
178
179#[derive(Clone, Debug, PartialEq, Eq)]
181pub struct WorldMapSelectDetail {
182 pub country_id: String,
184 pub highlighted: bool,
186 pub label: String,
188}
189
190pub fn world_map_countries() -> &'static [WorldMapCountry] {
193 WORLD_MAP_COUNTRY_DATA
194}
195
196pub 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
217fn 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
226fn 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
240fn 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
251pub 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
289pub 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
314pub 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
349pub 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
359pub 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
381pub 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
400enum PathToken<'a> {
402 Command(char),
404 Number(&'a str),
406}
407
408fn 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 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
451pub 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
515pub 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
524pub 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
535pub fn world_map_pan_threshold_reached(dx: f64, dy: f64) -> bool {
538 dx.hypot(dy) >= WORLD_MAP_PAN_THRESHOLD
539}
540
541fn 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
552fn 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#[derive(Clone, Copy, Debug, PartialEq)]
569pub struct WorldMapView {
570 pub zoom: f64,
572 pub center_x: f64,
574 pub center_y: f64,
576}
577
578impl Default for WorldMapView {
579 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 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 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 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 pub fn zoom_percent(&self) -> String {
634 format!("{}%", (normalize_world_map_zoom(self.zoom) * 100.0).round())
635 }
636
637 pub fn can_zoom_in(&self) -> bool {
639 normalize_world_map_zoom(self.zoom) < WORLD_MAP_ZOOM_MAX
640 }
641
642 pub fn can_zoom_out(&self) -> bool {
644 normalize_world_map_zoom(self.zoom) > WORLD_MAP_ZOOM_MIN
645 }
646
647 #[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 #[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 #[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 #[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 #[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 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 #[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 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 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
779fn 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 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 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 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 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}