lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
//! Pure `WorldMap` model: bundled country data, projection, normalization, and navigation.
//!
//! Ports `packages/core/src/world-map.ts` and the zoom, fit, and pan rules of
//! `world-map-zoom.ts`, `world-map-navigation.ts`, and `world-map-pan.ts`. The web adapters zoom by
//! scaling a scrollable plot. Dioxus Native has no scroll APIs, so [`WorldMapView`] zooms and pans
//! by changing the SVG `viewBox` instead. Everything here uses only `std`.

// cspell:words hypot

use std::borrow::Cow;
use std::collections::HashSet;

use super::countries::WORLD_MAP_COUNTRY_DATA;

/// Width of the shared SVG `viewBox`, in map units. It spans longitude -180 to 180.
pub const WORLD_MAP_VIEW_BOX_WIDTH: f64 = 1000.0;

/// Height of the shared SVG `viewBox`, in map units. It spans latitude 84 to -60.
pub const WORLD_MAP_VIEW_BOX_HEIGHT: f64 = 400.0;

/// Southern edge of the projected latitude band. The dataset leaves out Antarctica.
pub const WORLD_MAP_LATITUDE_MIN: f64 = -60.0;

/// Northern edge of the projected latitude band.
pub const WORLD_MAP_LATITUDE_MAX: f64 = 84.0;

/// Smallest zoom level, which shows the whole map.
pub const WORLD_MAP_ZOOM_MIN: f64 = 1.0;

/// Largest zoom level.
pub const WORLD_MAP_ZOOM_MAX: f64 = 8.0;

/// Zoom change for one press of the zoom in or zoom out button.
pub const WORLD_MAP_ZOOM_STEP: f64 = 0.5;

/// Pointer travel, in CSS pixels, before a press on the map becomes a pan instead of a click.
pub const WORLD_MAP_PAN_THRESHOLD: f64 = 4.0;

/// Share of the viewport that fitted bounds fill, leaving a margin around them.
const FIT_PADDING: f64 = 0.85;

/// Wheel deltas beyond this many pixels count as this many, so one event can't jump too far.
const WHEEL_DELTA_LIMIT: f64 = 1000.0;

/// Zoom rate per wheel pixel: each pixel scales the zoom by `exp(-0.002)`.
const WHEEL_ZOOM_RATE: f64 = 0.002;

/// Rounding factor for `viewBox` attribute values (four decimals).
const VIEW_BOX_ROUNDING: f64 = 10_000.0;

/// How country shapes are filled.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum WorldMapVariant {
    /// Countries are filled with a dot pattern.
    #[default]
    Dotted,
    /// Countries are filled with a solid color.
    Solid,
}

impl WorldMapVariant {
    /// The `data-variant` attribute value: `dotted` or `solid`.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Dotted => "dotted",
            Self::Solid => "solid",
        }
    }
}

/// A point in `viewBox` units.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WorldMapPoint {
    /// Horizontal position, from 0 at longitude -180 to 1000 at longitude 180.
    pub x: f64,
    /// Vertical position, from 0 at latitude 84 to 400 at latitude -60.
    pub y: f64,
}

/// An axis-aligned rectangle in `viewBox` units.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WorldMapBounds {
    /// Left edge.
    pub x: f64,
    /// Top edge.
    pub y: f64,
    /// Width.
    pub width: f64,
    /// Height.
    pub height: f64,
}

impl WorldMapBounds {
    /// Creates bounds from the top-left corner and size.
    pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// The center point.
    pub fn center(self) -> WorldMapPoint {
        WorldMapPoint {
            x: self.x + self.width / 2.0,
            y: self.y + self.height / 2.0,
        }
    }

    /// Whether every field is a finite number.
    pub fn is_finite(self) -> bool {
        self.x.is_finite()
            && self.y.is_finite()
            && self.width.is_finite()
            && self.height.is_finite()
    }

    /// The smallest bounds that contain both `self` and `other`.
    #[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,
        }
    }
}

/// One country's projected SVG path and label anchor.
///
/// The bundled data comes from [`world_map_countries`]. Custom geometry can use
/// [`world_map_path_bounds`] to fill in `bounds`.
#[derive(Clone, Debug, PartialEq)]
pub struct WorldMapCountry {
    /// ISO 3166-1 alpha-2 code where one exists, in uppercase. Somaliland uses `SOL` and
    /// Northern Cyprus uses `CYN`.
    pub id: Cow<'static, str>,
    /// English display name.
    pub name: Cow<'static, str>,
    /// SVG path data in `viewBox` units, drawn with `fill-rule: evenodd`.
    pub path: Cow<'static, str>,
    /// Horizontal position of the label anchor.
    pub label_x: f64,
    /// Vertical position of the label anchor.
    pub label_y: f64,
    /// Bounding box of `path`, used to fit highlighted countries.
    pub bounds: WorldMapBounds,
}

/// A consumer-supplied point of interest, placed with the same projection as the countries.
#[derive(Clone, Debug, PartialEq)]
pub struct WorldMapMarker {
    /// Unique identifier.
    pub id: String,
    /// Accessible label.
    pub label: String,
    /// Latitude in degrees. Markers outside -60 to 84 are dropped.
    pub latitude: f64,
    /// Longitude in degrees, from -180 to 180.
    pub longitude: f64,
}

impl WorldMapMarker {
    /// The marker's projected position, or `None` when its coordinates can't be projected.
    pub fn point(&self) -> Option<WorldMapPoint> {
        project_world_map_coordinate(self.longitude, self.latitude)
    }
}

/// Details sent when a country is selected.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorldMapSelectDetail {
    /// The selected country's id.
    pub country_id: String,
    /// Whether the country is highlighted. Selection and highlighting are separate states.
    pub highlighted: bool,
    /// The resolved display label, including any override.
    pub label: String,
}

/// The bundled country geometry: 238 countries and territories from Natural Earth (public
/// domain), with uppercase ids and path bounds.
pub fn world_map_countries() -> &'static [WorldMapCountry] {
    WORLD_MAP_COUNTRY_DATA
}

/// Projects a longitude and latitude to the shared `viewBox` with the equirectangular projection
/// used for every country path.
///
/// Returns `None` for non-finite input, a longitude outside -180 to 180, or a latitude outside
/// -90 to 90. Latitudes outside the visible band still project, just beyond the map's edges.
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,
    })
}

/// Whether converting `value` to uppercase would leave it unchanged.
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()
    })
}

/// Trims an id and converts it to uppercase, borrowing when nothing changes. Blank ids give
/// `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()))
    }
}

/// Normalizes a country's id, keeping a static id borrowed when it is already normal.
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()),
        }),
    }
}

/// Validates country geometry: trims ids and converts them to uppercase, and drops entries with
/// a blank id, name, or path, a non-finite label anchor, or an id seen earlier.
///
/// Already-normal static data is copied without allocating new strings.
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
}

/// Trims, converts to uppercase, and deduplicates highlighted country ids, and drops blank ids
/// and ids that are not in `countries`, so a typo degrades gracefully instead of breaking the map.
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
}

/// Validates markers: trims the id and label, requires both to be non-blank, requires finite
/// coordinates inside the visible latitude band and longitude -180 to 180, and drops markers
/// whose id was seen earlier.
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
}

/// Finds a country by id, ignoring surrounding whitespace and case. Blank ids find nothing.
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)
}

/// Resolves a country's display label.
///
/// `overrides` pairs a country id, such as `CO`, with a label. The last pair for the country wins,
/// like inserting the pairs into a map. A blank override falls back to the dataset name; others
/// are trimmed.
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)
}

/// Builds the selection details for `country`. `highlighted_ids` should be normalized, as
/// returned by [`normalize_world_map_highlighted`].
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(),
    }
}

/// One token of SVG path data.
enum PathToken<'a> {
    /// A command letter.
    Command(char),
    /// The text of one number.
    Number(&'a str),
}

/// Splits path data into command letters and number texts in one forward pass. Commas and
/// whitespace separate numbers, and a sign also starts a new number unless it follows an exponent.
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);

        // A character that can't start a number becomes a one-character token that won't parse.
        let end = if end == 0 { first.len_utf8() } else { end };
        let (number, remaining) = rest.split_at(end);

        rest = remaining;

        Some(PathToken::Number(number))
    })
}

/// Computes the bounding box of SVG path data that uses only absolute `M`, `L`, and `Z`
/// commands, as the bundled countries do.
///
/// Returns `None` for empty data, other commands, malformed numbers, or a missing coordinate.
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,
    ))
}

/// Clamps a zoom level to 1 through 8. Non-finite values reset to 1.
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
    }
}

/// Zoom multiplier for a modified (Ctrl or Cmd) wheel event: `exp(-delta_y * 0.002)`, with the
/// delta clamped to ±1000 pixels. Convert line deltas (×16) and page deltas (× viewport height)
/// to pixels first. A non-finite delta gives 1.
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
    }
}

/// Whether a pointer that moved `dx`, `dy` CSS pixels since it was pressed has traveled far
/// enough to start panning. Shorter moves stay clicks.
pub fn world_map_pan_threshold_reached(dx: f64, dy: f64) -> bool {
    dx.hypot(dy) >= WORLD_MAP_PAN_THRESHOLD
}

/// Keeps a view's center far enough from the edges that the visible span stays inside the map.
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
    }
}

/// Formats a `viewBox` number like JavaScript: no trailing `.0`, no `-0`, at most four decimals.
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()
    }
}

/// The visible region of the map: a zoom level and the center of the region in `viewBox` units.
///
/// The component renders [`WorldMapView::view_box_attribute`] as the SVG `viewBox`, which works on
/// every renderer, including Dioxus Native. Every method returns a clamped view that stays inside
/// the map, and [`WorldMapView::view_box`] clamps fields that were set directly.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WorldMapView {
    /// Zoom level from 1 (whole map) to 8.
    pub zoom: f64,
    /// Horizontal center of the visible region.
    pub center_x: f64,
    /// Vertical center of the visible region.
    pub center_y: f64,
}

impl Default for WorldMapView {
    /// The whole map at zoom 1.
    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 {
    /// Creates a view, clamping the zoom and moving the center so the region stays inside the map.
    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,
            ),
        }
    }

    /// The visible region: `1000 / zoom` by `400 / zoom` units, inside the map.
    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,
        }
    }

    /// The SVG `viewBox` attribute, such as `0 0 1000 400` for the whole map.
    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(" ")
    }

    /// The zoom level as a rounded percentage, such as `150%`.
    pub fn zoom_percent(&self) -> String {
        format!("{}%", (normalize_world_map_zoom(self.zoom) * 100.0).round())
    }

    /// Whether the zoom in button can act.
    pub fn can_zoom_in(&self) -> bool {
        normalize_world_map_zoom(self.zoom) < WORLD_MAP_ZOOM_MAX
    }

    /// Whether the map is zoomed in, which enables zoom out, reset, and panning.
    pub fn can_zoom_out(&self) -> bool {
        normalize_world_map_zoom(self.zoom) > WORLD_MAP_ZOOM_MIN
    }

    /// Zooms to `zoom`, keeping `anchor` (in `viewBox` units) at the same place in the viewport.
    /// Without an anchor, the view zooms around its center.
    #[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,
        )
    }

    /// Zooms in by one button step around the center.
    #[must_use]
    pub fn zoom_in(&self) -> Self {
        self.zoom_to(
            normalize_world_map_zoom(self.zoom) + WORLD_MAP_ZOOM_STEP,
            None,
        )
    }

    /// Zooms out by one button step around the center.
    #[must_use]
    pub fn zoom_out(&self) -> Self {
        self.zoom_to(
            normalize_world_map_zoom(self.zoom) - WORLD_MAP_ZOOM_STEP,
            None,
        )
    }

    /// Applies a modified wheel event's pixel delta, keeping `anchor` in place. See
    /// [`world_map_wheel_zoom_factor`].
    #[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,
        )
    }

    /// Moves the visible region by `dx`, `dy` `viewBox` units, staying inside the map. Positive
    /// values reveal more of the east and south. Non-finite values count as 0.
    #[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),
        )
    }

    /// Converts a pointer position in the rendered viewport, in CSS pixels from its top-left
    /// corner, to `viewBox` units. It follows the default `preserveAspectRatio` (`xMidYMid meet`),
    /// so it also works when the viewport's aspect ratio differs from the map's.
    ///
    /// Returns `None` for a viewport without a positive, finite size or a non-finite position.
    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,
        })
    }

    /// Pans by a pointer drag of `dx`, `dy` CSS pixels so the map follows the pointer. Returns the
    /// view unchanged when the viewport has no positive, finite size.
    #[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),
        }
    }

    /// The view that fits `bounds` with a margin: `min(1000 / width, 400 / height) * 0.85`,
    /// clamped to 1 through 8 and centered on the bounds. Sizes under one unit count as one, and
    /// non-finite bounds give the whole map.
    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)
    }

    /// The view that fits every highlighted country, or `None` when no id matches a country with
    /// finite bounds. Ids are matched like [`find_world_map_country`].
    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)
    }
}

/// CSS pixels per `viewBox` unit under `xMidYMid meet`, or `None` for an unusable viewport.
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() {
        // JS: an 800x320 viewport scrolls to (200, 80) at 150%, which is (166.67, 66.67) in units.
        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() {
        // JS: at 150% in an 800px viewport scrolled to 200, a wheel delta of -100 at clientX 100
        // scrolls to (200 + 100) * e^0.2 - 100 pixels.
        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);
        // A square viewport letterboxes the map: 300px above and below at one pixel per unit.
        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() {
        // JS: the union (100, 50, 250, 100) fits at 340% and scrolls an 800x320 viewport to
        // (212, 112), which is (212, 112) / 2.72 in units.
        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")
        );
    }
}