visualci-gallery 0.7.0

A screenshots page from VisualCI's public gallery, rendered in Rust (or an Askama template) and hydrated by the visualci-gallery script.
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
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
//! The gallery's model from a VisualCI public gallery manifest (contract/SPEC.md): a line-for-line port of the JS
//! library's model.ts, so every renderer gives the same model and markup.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::LazyLock;

use regex::Regex;
use serde::{Serialize, Serializer};
use serde_json::{Map, Value};

use crate::Error;

/// The gallery's own words by key, with their defaults (contract/SPEC.md, "Text"), in the model's order.
pub const TEXT_DEFAULTS: [(&str, &str); 15] = [
    ("label", "Screenshots"),
    ("open", "{title}: view full size"),
    ("previous", "Previous screen"),
    ("next", "Next screen"),
    ("close", "Close"),
    ("back", "Scroll back"),
    ("forward", "Scroll forward"),
    ("credit", "Screenshots by {link}"),
    ("and", " and "),
    ("search", "Search screens"),
    ("empty", "No screens match"),
    ("new", "New"),
    ("change", "New in {title}: see what changed"),
    ("version", "Version"),
    ("latest", "Latest"),
];
pub const SEE_ALL_TEXT: &str = "See all screenshots";
/// The search box's default threshold: shown once the gallery has this many screens.
pub const SEARCH_FROM: u64 = 40;
/// The New badge's default window, in days.
pub const NEW_DAYS: u64 = 30;

// Whole-string matches (\A…\z), ASCII digits only and "any character" including line breaks, so every language's
// regex engine agrees (contract/SPEC.md, "A shot's name").
pub(crate) static EXTENSION: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\z").unwrap());
static KEY: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A[a-z0-9]+(-[a-z0-9]+)*\z").unwrap());
static ABSOLUTE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\A[hH][tT][tT][pP][sS]?://[^\x00-\x20\x7f]+\z").unwrap());
static CONTROL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\x00-\x20\x7f]").unwrap());
static SCHEME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A[A-Za-z][A-Za-z0-9+.-]*:").unwrap());
static ID: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A[A-Za-z][A-Za-z0-9_-]*\z").unwrap());

/// A dimension's value key per dimension key (`{"theme": "dark", "size": "phone"}`).
pub type Values = BTreeMap<String, String>;

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Variant {
    /// A value key per dimension.
    pub values: Values,
    pub url: String,
    pub url2x: Option<String>,
    pub width: u64,
    pub height: u64,
    /// Bytes of `url` and `url2x`, when the manifest gives them.
    pub bytes: Option<u64>,
    pub bytes2x: Option<u64>,
    /// The cards' small copy, when the manifest gives one; the full-size view shows `url`.
    pub thumb: Option<Thumb>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Thumb {
    pub url: String,
    pub width: u64,
    pub height: u64,
    pub bytes: Option<u64>,
}

/// The preloader's limits: `fold` above-the-fold thumbnails always load; past them at most `count` images and `bytes`
/// bytes; `parallel` requests at once.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PreloadCaps {
    pub fold: u64,
    pub count: u64,
    pub bytes: u64,
    pub parallel: u64,
}

impl Default for PreloadCaps {
    /// The caps when the site sets none (contract/SPEC.md, "Options").
    fn default() -> Self {
        PreloadCaps { fold: 250, count: 500, bytes: 50_000_000, parallel: 4 }
    }
}

/// Predictive preloading other than the default (the model's `preload`: `"off"`, or the caps, every one filled in).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Preload {
    Off,
    Caps(PreloadCaps),
}

impl Serialize for Preload {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Preload::Off => serializer.serialize_str("off"),
            Preload::Caps(caps) => caps.serialize(serializer),
        }
    }
}

/// What a card does with no shot for the chosen value (contract/SPEC.md, "Dimensions"): `Error`, every screen needs
/// every value; `Hide`, the card isn't shown; `First`, it shows its own first value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Missing {
    Error,
    Hide,
    First,
}

impl Missing {
    pub fn as_str(self) -> &'static str {
        match self {
            Missing::Error => "error",
            Missing::Hide => "hide",
            Missing::First => "first",
        }
    }
    fn parse(s: &str) -> Option<Self> {
        match s {
            "error" => Some(Missing::Error),
            "hide" => Some(Missing::Hide),
            "first" => Some(Missing::First),
            _ => None,
        }
    }
}

/// The shape of most of a size value's images.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Shape {
    Landscape,
    Portrait,
}

impl Shape {
    pub fn as_str(self) -> &'static str {
        match self {
            Shape::Landscape => "landscape",
            Shape::Portrait => "portrait",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DimensionValue {
    pub key: String,
    pub label: String,
    pub below: Option<u64>,
    /// Size values only: the shape of most of their images.
    pub shape: Option<Shape>,
}

/// A way a screen's shots differ (contract/SPEC.md, "Dimensions"): `theme` and `size` are built in, a site adds others.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Dimension {
    pub key: String,
    pub label: String,
    pub missing: Missing,
    pub values: Vec<DimensionValue>,
}

fn value(key: &str, label: &str, below: Option<u64>) -> DimensionValue {
    DimensionValue { key: key.into(), label: label.into(), below, shape: None }
}

/// The built-in dimensions: the theme (light, dark) and the size (desktop, phone below 768).
pub fn default_dimensions() -> Vec<Dimension> {
    vec![
        Dimension {
            key: "theme".into(),
            label: "Theme".into(),
            missing: Missing::Error,
            values: vec![value("light", "Light", None), value("dark", "Dark", None)],
        },
        Dimension {
            key: "size".into(),
            label: "Screen size".into(),
            missing: Missing::Hide,
            values: vec![value("desktop", "Desktop", None), value("phone", "Phone", Some(768))],
        },
    ]
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Screen {
    pub key: String,
    pub title: String,
    pub caption: Option<String>,
    /// The newest `since` of the manifest items it's made from (the last time one of its pictures changed).
    pub since: Option<String>,
    /// The page of the snapshot its newest picture came from (`snapshot` of an item with that `since`).
    pub change: Option<String>,
    pub variants: Vec<Variant>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Group {
    pub name: String,
    pub title: String,
    pub slug: String,
    pub fit: String,
    /// The value keys the group has, per dimension, in each dimension's order.
    pub values: BTreeMap<String, Vec<String>>,
    pub screens: Vec<Screen>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SeeAll {
    pub href: String,
    pub text: String,
}

/// The gallery's own words (contract/SPEC.md, "Text"), every one filled in. `{title}` in `open` is the screen's
/// title; `{link}` in `credit` is the link to VisualCI. `label` is the default title, and the gallery's name when its
/// title is null. `and` joins the values in an image's alt text.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Text {
    pub label: String,
    pub open: String,
    pub previous: String,
    pub next: String,
    pub close: String,
    pub back: String,
    pub forward: String,
    pub credit: String,
    pub and: String,
    pub search: String,
    pub empty: String,
    pub new: String,
    pub change: String,
    /// The Version switch's accessible name.
    pub version: String,
    /// The Version switch's value for the gallery as it is now (the main manifest).
    pub latest: String,
}

impl Text {
    /// The words with the given ones (by key; a missing one keeps its default).
    fn with(get: impl Fn(&str) -> Option<String>) -> Self {
        let w = |k: &str| get(k).unwrap_or_else(|| TEXT_DEFAULTS.iter().find(|(d, _)| *d == k).unwrap().1.into());
        Text {
            label: w("label"),
            open: w("open"),
            previous: w("previous"),
            next: w("next"),
            close: w("close"),
            back: w("back"),
            forward: w("forward"),
            credit: w("credit"),
            and: w("and"),
            search: w("search"),
            empty: w("empty"),
            new: w("new"),
            change: w("change"),
            version: w("version"),
            latest: w("latest"),
        }
    }
}

impl Default for Text {
    fn default() -> Self {
        Text::with(|_| None)
    }
}

/// The manifest as the gallery shows it, with the keys of the contract fixtures' model.json.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Model {
    pub layout: String,
    pub theme_switch: bool,
    pub see_all: Option<SeeAll>,
    pub title: Option<String>,
    pub label: String,
    pub heading_level: u8,
    pub id: String,
    pub credit: bool,
    /// None: preloading with the defaults.
    pub preload: Option<Preload>,
    pub deep_links: bool,
    pub text: Text,
    /// Whether the grid shows its search box.
    pub search: bool,
    pub zoom: bool,
    /// The New badge's window in days; None: no badges.
    pub new_badges: Option<u64>,
    pub dimensions: Vec<Dimension>,
    pub groups: Vec<Group>,
    /// The Version switch; None: none.
    pub versions: Option<Versions>,
}

/// The Version switch (contract/SPEC.md, "The model"): the listed versions, the one shown and Latest's manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Versions {
    /// The key of the version shown: a listed version's, or "latest".
    pub current: String,
    /// The main manifest's URL, Latest's.
    pub latest: String,
    /// The options as canonical JSON ([`options_json`]), for the browser to build another version's gallery the same
    /// way.
    pub options: String,
    pub list: Vec<Version>,
}

/// A version the manifest lists.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Version {
    pub key: String,
    pub label: String,
    /// The version's own manifest: `…/<project>@<key>.json`.
    pub manifest: String,
}

/// How a manifest name pairs (contract/SPEC.md, "A shot's name").
#[derive(Debug, Clone, PartialEq)]
pub struct Shot {
    /// The screen's key: the name without its values, width and 2x.
    pub key: String,
    /// The value the name gives, by dimension key; a dimension it gives none of stands for every value.
    pub values: Values,
    pub x2: bool,
    /// The CSS width the name gives (`-1440`).
    pub css_width: Option<u64>,
}

fn digits(s: &str) -> bool {
    !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}

/// Trailing `-`-separated tokens that are value keys of `dimensions`, a CSS width and `2x` are peeled off the end, and
/// the rest is the screen's key (contract/SPEC.md, "A shot's name").
pub fn parse_shot(name: &str, dimensions: &[Dimension]) -> Shot {
    let base = EXTENSION.replace(name, "").into_owned();
    let mut parts: Vec<&str> = base.split('/').collect();
    let last = parts.pop().unwrap_or("");
    let folder = parts.join("/");
    let owner: HashMap<&str, &str> =
        dimensions.iter().flat_map(|d| d.values.iter().map(move |v| (v.key.as_str(), d.key.as_str()))).collect();
    let mut tokens: Vec<&str> = last.split('-').collect();
    let mut x2 = false;
    if tokens.last() == Some(&"2x") {
        tokens.pop();
        x2 = true;
    }
    let mut values = Values::new();
    let mut css_width: Option<u64> = None;
    let mut named = false;
    loop {
        let mut peeled = false;
        for n in (1..=tokens.len()).rev() {
            let candidate = tokens[tokens.len() - n..].join("-");
            if let Some(dim) = owner.get(candidate.as_str())
                && !values.contains_key(*dim)
            {
                values.insert(dim.to_string(), candidate);
                tokens.truncate(tokens.len() - n);
                named = true;
                peeled = true;
                break;
            }
        }
        if peeled {
            continue;
        }
        if css_width.is_none()
            && let Some(t) = tokens.last().filter(|t| digits(t))
        {
            // A width too long for u64 is as wide as any (JS holds the huge number).
            css_width = Some(t.parse::<u64>().unwrap_or(u64::MAX));
            tokens.pop();
            continue;
        }
        break;
    }
    // `<screen>/<width>` (the last part only a width, under a folder) pairs by its folder.
    let width_only = css_width.is_some() && tokens.is_empty() && !folder.is_empty();
    if (!named && !width_only) || (tokens.is_empty() && folder.is_empty()) {
        return Shot { key: base, values: Values::new(), x2: false, css_width: None };
    }
    let rest = tokens.join("-");
    let key = if tokens.is_empty() {
        folder
    } else if folder.is_empty() {
        rest
    } else {
        format!("{folder}/{rest}")
    };
    Shot { key, values, x2, css_width }
}

/// A shot's size: the one its name gives, else the one its CSS width falls under, else the group's, else by the
/// image's shape.
fn size_of_shot(shot: &Shot, sizes: &[DimensionValue], width: u64, height: u64, group_size: Option<&str>) -> String {
    if let Some(s) = shot.values.get("size") {
        return s.clone();
    }
    let open = &sizes.iter().find(|v| v.below.is_none()).expect("a size with no below").key;
    let mut bounded: Vec<&DimensionValue> = sizes.iter().filter(|v| v.below.is_some()).collect();
    bounded.sort_by_key(|v| v.below);
    if let Some(cw) = shot.css_width {
        return bounded.iter().find(|v| cw < v.below.unwrap()).map_or(open, |v| &v.key).clone();
    }
    if let Some(g) = group_size {
        return g.to_string();
    }
    if height > width && !bounded.is_empty() { bounded[0].key.clone() } else { open.clone() }
}

/// `["billing", "free"]` → "Billing, free".
pub fn humanize(segments: &[&str]) -> String {
    static RUNS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[-_]+").unwrap());
    let text =
        segments.iter().map(|s| RUNS.replace_all(s, " ").trim_matches(' ').to_string()).collect::<Vec<_>>().join(", ");
    let mut chars = text.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().chain(chars).collect(),
        None => text,
    }
}

/// A group's name as an id: ASCII lower case, runs of anything else as one hyphen.
pub fn slugify(name: &str) -> String {
    let mut out = String::new();
    let mut dash = false;
    for c in name.chars() {
        let c = c.to_ascii_lowercase();
        if c.is_ascii_lowercase() || c.is_ascii_digit() {
            if dash && !out.is_empty() {
                out.push('-');
            }
            dash = false;
            out.push(c);
        } else {
            dash = true;
        }
    }
    if out.is_empty() { "group".to_string() } else { out }
}

fn common_folder(keys: &[&str]) -> usize {
    let folders: Vec<Vec<&str>> = keys
        .iter()
        .map(|k| {
            let mut p: Vec<&str> = k.split('/').collect();
            p.pop();
            p
        })
        .collect();
    let Some(first) = folders.first() else { return 0 };
    let mut common = first.len();
    for f in &folders[1..] {
        let mut i = 0;
        while i < common && i < f.len() && first[i] == f[i] {
            i += 1;
        }
        common = i;
    }
    common
}

fn rank(order: &Option<Vec<String>>, key: &str) -> usize {
    let list = order.as_deref().unwrap_or(&[]);
    list.iter().position(|k| k == key).unwrap_or(list.len())
}

fn safe_href(value: &str) -> bool {
    ABSOLUTE.is_match(value) || (!value.is_empty() && !CONTROL.is_match(value) && !SCHEME.is_match(value))
}

fn fail<T>(message: impl Into<String>) -> Result<T, Error> {
    Err(Error::Invalid(message.into()))
}

/// An integer as JSON has it: 1440 or 1440.0 (JavaScript can't tell them apart).
fn integral(v: &Value) -> Option<f64> {
    let n = v.as_f64()?;
    (n.is_finite() && n.fract() == 0.0).then_some(n)
}

/// The largest width or height (contract/SPEC.md, "Validation"): the density maths stays exact in every language.
pub const MAX_SIZE: u64 = 1_000_000;

fn size_of(v: Option<&Value>) -> Option<u64> {
    let n = integral(v?)?;
    (n > 0.0 && n <= MAX_SIZE as f64).then_some(n as u64)
}

/// The largest size in bytes or preload cap: a whole number every language holds exactly.
const MAX_CAP: u64 = 1_000_000_000_000;

/// A whole number from `min` to `max`.
fn whole_in(v: &Value, min: u64, max: u64) -> Option<u64> {
    let n = integral(v)?;
    (n >= min as f64 && n <= max as f64).then_some(n as u64)
}

/// An optional size in bytes: Ok(None) when absent or null, Err(()) when it isn't a whole number from 0 to 10^12.
fn bytes_of(v: Option<&Value>) -> Result<Option<u64>, ()> {
    match v {
        None | Some(Value::Null) => Ok(None),
        Some(v) => whole_in(v, 0, MAX_CAP).map(Some).ok_or(()),
    }
}

/// A manifest item's thumb, when it has a valid one; Err(()) when it has one that isn't.
fn thumb_of(v: Option<&Value>) -> Result<Option<Thumb>, ()> {
    let t = match v {
        None | Some(Value::Null) => return Ok(None),
        Some(t) => t,
    };
    let url = t.get("url").and_then(Value::as_str).filter(|u| t.is_object() && ABSOLUTE.is_match(u)).ok_or(())?;
    let (width, height) = (size_of(t.get("width")).ok_or(())?, size_of(t.get("height")).ok_or(())?);
    Ok(Some(Thumb { url: url.into(), width, height, bytes: bytes_of(t.get("bytes"))? }))
}

/// The preload option: true, false, or an object with only fold, count and bytes (null or 0..10^12) and parallel
/// (null or 1..8).
fn preload_valid(v: &Value) -> bool {
    v.is_boolean()
        || v.as_object().is_some_and(|m| {
            m.iter().all(|(k, x)| match k.as_str() {
                "fold" | "count" | "bytes" => x.is_null() || whole_in(x, 0, MAX_CAP).is_some(),
                "parallel" => x.is_null() || whole_in(x, 1, 8).is_some(),
                _ => false,
            })
        })
}

fn preload_model(v: Option<&Value>) -> Option<Preload> {
    match v? {
        Value::Bool(true) => None,
        Value::Bool(false) => Some(Preload::Off),
        v => {
            let d = PreloadCaps::default();
            let cap = |k: &str, d: u64| v.get(k).and_then(integral).map_or(d, |n| n as u64);
            Some(Preload::Caps(PreloadCaps {
                fold: cap("fold", d.fold),
                count: cap("count", d.count),
                bytes: cap("bytes", d.bytes),
                parallel: cap("parallel", d.parallel),
            }))
        }
    }
}

/// The manifest's shape (contract/SPEC.md, "Validation"): anything else is refused.
pub(crate) fn check_manifest(manifest: &Value) -> Result<(), Error> {
    let Some(groups) = manifest.get("groups").filter(|_| manifest.is_object()).and_then(Value::as_array) else {
        return fail("not a gallery manifest: it has no groups");
    };
    for (i, g) in groups.iter().enumerate() {
        let name = match g.get("name").and_then(Value::as_str) {
            Some(n) if g.is_object() && !n.is_empty() => n,
            _ => return fail(format!("gallery manifest group {i} has no name")),
        };
        if !matches!(g.get("title"), None | Some(Value::Null) | Some(Value::String(_))) {
            return fail(format!("gallery manifest group {name}: its title isn't a string"));
        }
        let Some(items) = g.get("items").and_then(Value::as_array) else {
            return fail(format!("gallery manifest group {name} has no items"));
        };
        for (j, item) in items.iter().enumerate() {
            let place = format!("gallery manifest group {name}, item {j}");
            let iname = match item.get("name").and_then(Value::as_str) {
                Some(n) if item.is_object() && !n.is_empty() => n,
                _ => return fail(format!("{place} has no name")),
            };
            if !item.get("url").and_then(Value::as_str).is_some_and(|u| ABSOLUTE.is_match(u)) {
                return fail(format!("{place} ({iname}): its url isn't an http(s) URL"));
            }
            if size_of(item.get("width")).is_none() || size_of(item.get("height")).is_none() {
                return fail(format!(
                    "{place} ({iname}): its width and height aren't whole numbers from 1 to {MAX_SIZE}"
                ));
            }
            if bytes_of(item.get("bytes")).is_err() {
                return fail(format!("{place} ({iname}): its bytes isn't a whole number"));
            }
            if thumb_of(item.get("thumb")).is_err() {
                return fail(format!("{place} ({iname}): its thumb needs an http(s) url, a width and a height"));
            }
        }
    }
    if !versions_valid(manifest) {
        return fail("the gallery manifest's versions are invalid");
    }
    Ok(())
}

/// The manifest's `versions` (each with a unique key that isn't `latest`, a label and its own manifest's URL) and
/// `version` (an object whose key is absent, null or a string).
fn versions_valid(manifest: &Value) -> bool {
    let mut seen: HashSet<&str> = HashSet::new();
    let listed = match manifest.get("versions") {
        None | Some(Value::Null) => true,
        Some(Value::Array(list)) => list.iter().all(|v| {
            let Some(key) = v.get("key").and_then(Value::as_str).filter(|k| v.is_object() && KEY.is_match(k)) else {
                return false;
            };
            key != "latest"
                && seen.insert(key)
                && v.get("label").and_then(Value::as_str).is_some_and(|l| !l.is_empty())
                && v.get("manifest")
                    .and_then(Value::as_str)
                    .is_some_and(|m| ABSOLUTE.is_match(m) && m.ends_with(&format!("@{key}.json")))
        }),
        Some(_) => false,
    };
    listed
        && match manifest.get("version") {
            None | Some(Value::Null) => true,
            Some(v @ Value::Object(_)) => text_or_null(v.get("key")),
            Some(_) => false,
        }
}

/// The options' names, in the contract's order: what the Version switch carries to the browser.
const OPTION_KEYS: [&str; 19] = [
    "title",
    "headingLevel",
    "id",
    "dimensions",
    "screens",
    "order",
    "groups",
    "groupOrder",
    "credit",
    "layout",
    "themeSwitch",
    "seeAll",
    "preload",
    "deepLinks",
    "text",
    "search",
    "zoom",
    "newBadges",
    "versions",
];

/// A JSON string as the contract writes it: `"`, `\` and U+0000 to U+001F escaped, nothing else.
fn canonical_string(s: &str, out: &mut String) {
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\u{8}' => out.push_str("\\b"),
            '\t' => out.push_str("\\t"),
            '\n' => out.push_str("\\n"),
            '\u{c}' => out.push_str("\\f"),
            '\r' => out.push_str("\\r"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
}

/// JSON with every object's keys sorted by code point and no white space: the same bytes in every language.
fn canonical(value: &Value, out: &mut String) {
    match value {
        Value::Null => out.push_str("null"),
        Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        Value::Number(n) => match (n.as_i64(), n.as_u64(), n.as_f64()) {
            (Some(i), _, _) => out.push_str(&i.to_string()),
            (_, Some(u), _) => out.push_str(&u.to_string()),
            // Every number an option takes is whole: 3.0 is 3, as in JavaScript.
            // -0.0 matches too: JSON.stringify(-0) is "0".
            (_, _, Some(0.0)) => out.push('0'),
            (_, _, Some(f)) => out.push_str(&f.to_string()),
            _ => out.push_str(&n.to_string()),
        },
        Value::String(s) => canonical_string(s, out),
        Value::Array(a) => {
            out.push('[');
            for (i, v) in a.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                canonical(v, out);
            }
            out.push(']');
        }
        Value::Object(m) => {
            // Rust compares strings by their UTF-8 bytes, which is code point order.
            let mut keys: Vec<&String> = m.keys().collect();
            keys.sort();
            out.push('{');
            for (i, k) in keys.into_iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                canonical_string(k, out);
                out.push(':');
                canonical(&m[k], out);
            }
            out.push('}');
        }
    }
}

/// The options as the Version switch carries them (the model's `versions.options`): those of the contract's table
/// that are set and not null (a null title too), as canonical JSON (contract/SPEC.md, "The model").
pub fn options_json(options: &Options) -> String {
    let set: Map<String, Value> = OPTION_KEYS
        .iter()
        .filter_map(|k| {
            options.raw.get(*k).filter(|v| !v.is_null() || *k == "title").map(|v| (k.to_string(), v.clone()))
        })
        .collect();
    let mut out = String::new();
    canonical(&Value::Object(set), &mut out);
    out
}

/// A JSON object of the pairs whose value isn't null: a setter's `None` leaves its field out, as a site writing the
/// options as JSON would.
fn object(pairs: Vec<(&str, Value)>) -> Value {
    Value::Object(pairs.into_iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.to_string(), v)).collect())
}

/// The options a site can set (contract/SPEC.md, "Input"), as JSON-shaped values so every renderer takes the same
/// ones. Build them with [`Options::default`] and the setters, or [`Options::from_json`].
#[derive(Debug, Clone, Default)]
pub struct Options {
    pub(crate) raw: Map<String, Value>,
}

impl Options {
    /// Options from a JSON object with the contract's names (`headingLevel`, `groupOrder`, `themeSwitch`, `seeAll`).
    pub fn from_json(value: &Value) -> Result<Self, Error> {
        match value {
            Value::Object(m) => Ok(Options { raw: m.clone() }),
            _ => fail("gallery options must be an object"),
        }
    }
    pub(crate) fn set(mut self, key: &str, value: Value) -> Self {
        self.raw.insert(key.to_string(), value);
        self
    }
    /// The gallery's heading and accessible name; `None` keeps the name (text `label`, "Screenshots") but shows no
    /// heading.
    pub fn title(self, title: Option<&str>) -> Self {
        self.set("title", title.map_or(Value::Null, |t| Value::String(t.into())))
    }
    pub fn heading_level(self, level: u8) -> Self {
        self.set("headingLevel", level.into())
    }
    pub fn id(self, id: &str) -> Self {
        self.set("id", id.into())
    }
    /// A screen's title and caption, by key (`ios/usage`, `overview`).
    pub fn screen(mut self, key: &str, title: Option<&str>, caption: Option<&str>) -> Self {
        let screens = self.raw.entry("screens").or_insert_with(|| Value::Object(Map::new()));
        if let Value::Object(m) = screens {
            m.insert(key.into(), object(vec![("title", title.into()), ("caption", caption.into())]));
        }
        self
    }
    pub fn order<S: AsRef<str>>(self, keys: &[S]) -> Self {
        self.set("order", keys.iter().map(|k| Value::String(k.as_ref().into())).collect())
    }
    /// A group's title, the size of its shots whose names give none (a value of the `size` dimension: `"desktop"` or
    /// `"phone"` by default), and how its images fit their cards (`"cover"` or `"contain"`).
    pub fn group(mut self, name: &str, title: Option<&str>, size: Option<&str>, fit: Option<&str>) -> Self {
        let groups = self.raw.entry("groups").or_insert_with(|| Value::Object(Map::new()));
        if let Value::Object(m) = groups {
            m.insert(name.into(), object(vec![("title", title.into()), ("size", size.into()), ("fit", fit.into())]));
        }
        self
    }
    /// A dimension (contract/SPEC.md, "Dimensions"): `theme` or `size` changes the built-in one, any other key adds
    /// one after them, in the order of the calls. `missing` is `"error"`, `"hide"` or `"first"`; `values` are
    /// `(key, label, below)`, where `below` is only for sizes. `None` or an empty `values` keeps the built-in one's
    /// (a new dimension needs values).
    pub fn dimension(
        mut self,
        key: &str,
        label: Option<&str>,
        missing: Option<&str>,
        values: &[(&str, Option<&str>, Option<u64>)],
    ) -> Self {
        let mut entry = object(vec![("key", key.into()), ("label", label.into()), ("missing", missing.into())]);
        if !values.is_empty() {
            entry["values"] = values
                .iter()
                .map(|(k, label, below)| {
                    object(vec![("key", (*k).into()), ("label", (*label).into()), ("below", (*below).into())])
                })
                .collect();
        }
        let list = self.raw.entry("dimensions").or_insert_with(|| Value::Array(Vec::new()));
        if let Value::Array(a) = list {
            a.push(entry);
        }
        self
    }
    pub fn group_order<S: AsRef<str>>(self, names: &[S]) -> Self {
        self.set("groupOrder", names.iter().map(|k| Value::String(k.as_ref().into())).collect())
    }
    pub fn credit(self, on: bool) -> Self {
        self.set("credit", on.into())
    }
    /// `"grid"` (tabs per group) or `"strip"` (one row that scrolls sideways).
    pub fn layout(self, layout: &str) -> Self {
        self.set("layout", layout.into())
    }
    pub fn theme_switch(self, on: bool) -> Self {
        self.set("themeSwitch", on.into())
    }
    pub fn see_all(self, href: &str, text: Option<&str>) -> Self {
        self.set("seeAll", object(vec![("href", href.into()), ("text", text.into())]))
    }
    /// Predictive preloading of the images a reader is likely to look at next: on by default, `false` turns it off.
    pub fn preload(self, on: bool) -> Self {
        self.set("preload", on.into())
    }
    /// Preloading with caps of the site's own: `fold` above-the-fold thumbnails always load, past them at most `count`
    /// images and `bytes` bytes, `parallel` requests at once (1 to 8). `None` keeps a cap's default (250, 500,
    /// 50000000, 4).
    pub fn preload_caps(
        self,
        fold: Option<u64>,
        count: Option<u64>,
        bytes: Option<u64>,
        parallel: Option<u64>,
    ) -> Self {
        self.set(
            "preload",
            object(vec![
                ("fold", fold.into()),
                ("count", count.into()),
                ("bytes", bytes.into()),
                ("parallel", parallel.into()),
            ]),
        )
    }
    /// The URL's hash names the shown tab, the open screen and the chosen values, so a link opens them. Off by
    /// default: the gallery leaves the page's URL alone.
    pub fn deep_links(self, on: bool) -> Self {
        self.set("deepLinks", on.into())
    }
    /// The grid's search box, which filters the cards by title and caption across tabs: `true` always shows it,
    /// `false` never. By default it shows once the gallery has 40 screens; the strip never has one.
    pub fn search(self, on: bool) -> Self {
        self.set("search", on.into())
    }
    /// The grid's search box, shown once the gallery has this many screens (in every group), from 0 to 1000000.
    pub fn search_from(self, screens: u64) -> Self {
        self.set("search", screens.into())
    }
    /// Zoom in the full-size view, by gestures and keys only: on by default, `false` turns it off.
    pub fn zoom(self, on: bool) -> Self {
        self.set("zoom", on.into())
    }
    /// A New badge on each screen whose picture changed in the last 30 days (`true`); off by default.
    pub fn new_badges(self, on: bool) -> Self {
        self.set("newBadges", on.into())
    }
    /// A New badge on each screen whose picture changed in the last `days` days, from 1 to 3650.
    pub fn new_badges_days(self, days: u64) -> Self {
        self.set("newBadges", days.into())
    }
    /// The Version switch, when the manifest lists versions: Latest and each release the project reported, the grid
    /// only. Off by default.
    pub fn versions(self, on: bool) -> Self {
        self.set("versions", on.into())
    }
    /// One of the gallery's own words, by key (contract/SPEC.md, "Text"): `label`, `open` (`{title}` is the screen's
    /// title), `previous`, `next`, `close`, `back`, `forward`, `credit` (`{link}` is the link to VisualCI), `and`,
    /// `search`, `empty`, `new`, `change` (`{title}` is the screen's title), `version` or `latest`. An unknown key makes
    /// the options invalid.
    pub fn text(mut self, key: &str, value: &str) -> Self {
        let text = self.raw.entry("text").or_insert_with(|| Value::Object(Map::new()));
        if let Value::Object(m) = text {
            m.insert(key.into(), value.into());
        }
        self
    }

    /// An option's value, with null meaning absent; `check` false is an error.
    pub(crate) fn get(&self, key: &str, check: impl Fn(&Value) -> bool) -> Result<Option<&Value>, Error> {
        match self.raw.get(key) {
            None | Some(Value::Null) => Ok(None),
            Some(v) if check(v) => Ok(Some(v)),
            Some(_) => fail(format!("gallery option {key} is invalid")),
        }
    }
}

fn texts(keys: &'static [&'static str]) -> impl Fn(&Value) -> bool {
    move |v| {
        v.as_object().is_some_and(|m| {
            m.values().all(|entry| {
                entry.as_object().is_some_and(|e| {
                    e.iter().all(|(k, x)| keys.contains(&k.as_str()) && (x.is_null() || x.is_string()))
                })
            })
        })
    }
}

fn group_options(sizes: &[DimensionValue]) -> impl Fn(&Value) -> bool {
    move |v| {
        v.as_object().is_some_and(|m| {
            m.values().all(|entry| {
                entry.as_object().is_some_and(|e| {
                    e.iter().all(|(k, x)| match (k.as_str(), x) {
                        ("title" | "size" | "fit", Value::Null) => true,
                        ("title", Value::String(_)) => true,
                        ("size", Value::String(s)) => sizes.iter().any(|v| &v.key == s),
                        ("fit", Value::String(f)) => f == "cover" || f == "contain",
                        _ => false,
                    })
                })
            })
        })
    }
}

/// Absent, null or a string.
fn text_or_null(v: Option<&Value>) -> bool {
    matches!(v, None | Some(Value::Null) | Some(Value::String(_)))
}

/// The `dimensions` option's shape (contract/SPEC.md, "Validation").
pub(crate) fn check_dimensions(list: &Value) -> bool {
    let Some(list) = list.as_array() else { return false };
    let mut keys: HashSet<&str> = HashSet::new();
    let mut value_keys: HashSet<String> = HashSet::new();
    let value_key = |k: Option<&Value>| -> Option<String> {
        let k = k?.as_str()?;
        // Not only digits (a width), and not ending in "2x" (a name's last "2x" marks a high-density copy).
        (KEY.is_match(k) && !digits(k) && k != "2x" && !k.ends_with("-2x")).then(|| k.to_string())
    };
    for d in list {
        let Some(m) = d.as_object() else { return false };
        if !m.keys().all(|k| matches!(k.as_str(), "key" | "label" | "missing" | "values")) {
            return false;
        }
        let Some(key) = m.get("key").and_then(Value::as_str).filter(|k| KEY.is_match(k) && !keys.contains(k)) else {
            return false;
        };
        keys.insert(key);
        let built_in = key == "theme" || key == "size";
        if !text_or_null(m.get("label")) {
            return false;
        }
        match m.get("missing") {
            None | Some(Value::Null) => {}
            Some(x) if x.as_str().and_then(Missing::parse).is_some() => {}
            Some(_) => return false,
        }
        let values = match m.get("values") {
            None | Some(Value::Null) => {
                if !built_in {
                    return false;
                }
                continue;
            }
            Some(Value::Array(a)) if !a.is_empty() => a,
            Some(_) => return false,
        };
        for v in values {
            let Some(vm) = v.as_object() else { return false };
            if !vm.keys().all(|k| matches!(k.as_str(), "key" | "label" | "below")) {
                return false;
            }
            let Some(vk) = value_key(vm.get("key")).filter(|k| !value_keys.contains(k)) else { return false };
            value_keys.insert(vk);
            if !text_or_null(vm.get("label")) {
                return false;
            }
            match vm.get("below") {
                None | Some(Value::Null) => {}
                Some(b) if key == "size" && size_of(Some(b)).is_some() => {}
                Some(_) => return false,
            }
        }
        if key == "size" && !values.iter().any(|v| matches!(v.get("below"), None | Some(Value::Null))) {
            return false;
        }
    }
    // The built-in values a dimension doesn't replace still count.
    for d in default_dimensions() {
        if list.iter().any(|x| {
            x.get("key").and_then(Value::as_str) == Some(&d.key) && x.get("values").is_some_and(Value::is_array)
        }) {
            continue;
        }
        for v in d.values {
            if !value_keys.insert(v.key) {
                return false;
            }
        }
    }
    true
}

/// The built-in dimensions with the option's changes, then the option's own (already checked).
pub(crate) fn resolve_dimensions(list: Option<&Value>) -> Vec<Dimension> {
    let given: &[Value] = list.and_then(Value::as_array).map_or(&[], Vec::as_slice);
    let resolve = |d: &Value, base: Option<&Dimension>| -> Dimension {
        let key = d["key"].as_str().unwrap().to_string();
        let label = d.get("label").and_then(Value::as_str).map(str::to_string);
        let missing = d.get("missing").and_then(Value::as_str).and_then(Missing::parse);
        let values = match d.get("values").and_then(Value::as_array) {
            Some(vs) => vs
                .iter()
                .map(|v| {
                    let vk = v["key"].as_str().unwrap();
                    DimensionValue {
                        key: vk.into(),
                        label: v.get("label").and_then(Value::as_str).unwrap_or(vk).into(),
                        below: v.get("below").and_then(|b| size_of(Some(b))),
                        shape: None,
                    }
                })
                .collect(),
            None => base.unwrap().values.clone(),
        };
        Dimension {
            label: label.or_else(|| base.map(|b| b.label.clone())).unwrap_or_else(|| key.clone()),
            missing: missing.or(base.map(|b| b.missing)).unwrap_or(Missing::First),
            key,
            values,
        }
    };
    let defaults = default_dimensions();
    let mut out: Vec<Dimension> = defaults
        .iter()
        .map(|base| match given.iter().find(|x| x["key"].as_str() == Some(&base.key)) {
            Some(d) => resolve(d, Some(base)),
            None => base.clone(),
        })
        .collect();
    for d in given {
        if !defaults.iter().any(|base| d["key"].as_str() == Some(&base.key)) {
            out.push(resolve(d, None));
        }
    }
    out
}

/// Every combination of one value per dimension, the first dimension varying slowest, each in the order given.
fn combinations(dimensions: &[Dimension], values_for: impl Fn(&Dimension) -> Vec<String>) -> Vec<Vec<String>> {
    let mut out: Vec<Vec<String>> = vec![Vec::new()];
    for d in dimensions {
        let vs = values_for(d);
        out = out
            .into_iter()
            .flat_map(|c| {
                vs.iter().map(move |k| {
                    let mut c = c.clone();
                    c.push(k.clone());
                    c
                })
            })
            .collect();
    }
    out
}

/// A variant's value keys in the dimensions' order.
fn keys_of<'a>(dimensions: &[Dimension], values: &'a Values) -> Vec<&'a str> {
    dimensions.iter().map(|d| values[&d.key].as_str()).collect()
}

/// The value keys some of `variants` have, per dimension, in each dimension's order.
fn values_of(dimensions: &[Dimension], variants: &[&Variant]) -> BTreeMap<String, Vec<String>> {
    dimensions
        .iter()
        .map(|d| {
            let keys = d
                .values
                .iter()
                .filter(|v| variants.iter().any(|x| x.values[&d.key] == v.key))
                .map(|v| v.key.clone())
                .collect();
            (d.key.clone(), keys)
        })
        .collect()
}

/// Each size value's shape: portrait when more of its variants are taller than wide than aren't.
fn with_shapes(mut dimensions: Vec<Dimension>, groups: &[Group]) -> Vec<Dimension> {
    let variants: Vec<&Variant> =
        groups.iter().flat_map(|g| g.screens.iter().flat_map(|sc| sc.variants.iter())).collect();
    for d in dimensions.iter_mut().filter(|d| d.key == "size") {
        for v in &mut d.values {
            let at: Vec<&&Variant> = variants.iter().filter(|x| x.values["size"] == v.key).collect();
            let tall = at.iter().filter(|x| x.height > x.width).count();
            v.shape = Some(if tall > at.len() - tall { Shape::Portrait } else { Shape::Landscape });
        }
    }
    dimensions
}

fn strings(v: &Value) -> bool {
    v.as_array().is_some_and(|a| a.iter().all(Value::is_string))
}

fn string_list(v: Option<&Value>) -> Option<Vec<String>> {
    v.map(|v| v.as_array().unwrap().iter().map(|s| s.as_str().unwrap().to_string()).collect())
}

fn text_of<'a>(map: Option<&'a Value>, outer: &str, inner: &str) -> Option<&'a str> {
    map?.get(outer)?.get(inner)?.as_str()
}

/// The manifest as the gallery shows it (contract/SPEC.md). Fails when it or the options are invalid, or nothing in
/// it can be shown.
pub fn build_model(manifest: &Value, options: &Options) -> Result<Model, Error> {
    check_manifest(manifest)?;
    let level = options.get("headingLevel", |v| integral(v).is_some())?.and_then(integral).unwrap_or(2.0);
    let heading_level = level.clamp(1.0, 4.0) as u8;
    // None: absent, so text.label (text is checked last).
    let title_opt = if options.raw.contains_key("title") {
        Some(options.get("title", Value::is_string)?.and_then(Value::as_str).map(str::to_string))
    } else {
        None
    };
    let id = options
        .get("id", |v| v.as_str().is_some_and(|s| ID.is_match(s)))?
        .and_then(Value::as_str)
        .unwrap_or("vg")
        .to_string();
    let dimensions = resolve_dimensions(options.get("dimensions", check_dimensions)?);
    let size_values = dimensions.iter().find(|d| d.key == "size").unwrap().values.clone();
    let screens_opt = options.get("screens", texts(&["title", "caption"]))?;
    let groups_opt = options.get("groups", group_options(&size_values))?;
    let order = string_list(options.get("order", strings)?);
    let group_order = string_list(options.get("groupOrder", strings)?);
    let credit = options.get("credit", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(false);
    let switch = options.get("themeSwitch", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(true);
    let layout = options
        .get("layout", |v| matches!(v.as_str(), Some("grid" | "strip")))?
        .and_then(Value::as_str)
        .unwrap_or("grid")
        .to_string();
    let see_all = options.get("seeAll", |v| {
        v.is_object()
            && v.get("href").and_then(Value::as_str).is_some_and(safe_href)
            && matches!(v.get("text"), None | Some(Value::Null) | Some(Value::String(_)))
    })?;
    let preload = preload_model(options.get("preload", preload_valid)?);
    let deep_links = options.get("deepLinks", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(false);
    let text_opt = options.get("text", |v| {
        v.as_object().is_some_and(|m| {
            m.iter().all(|(k, x)| TEXT_DEFAULTS.iter().any(|(d, _)| d == k) && (x.is_null() || x.is_string()))
        })
    })?;
    let text = Text::with(|k| text_opt.and_then(|t| t.get(k)).and_then(Value::as_str).map(str::to_string));
    let title = title_opt.unwrap_or_else(|| Some(text.label.clone()));
    let search_opt = options.get("search", |v| v.is_boolean() || whole_in(v, 0, MAX_SIZE).is_some())?;
    let zoom = options.get("zoom", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(true);
    let new_badges = match options.get("newBadges", |v| v.is_boolean() || whole_in(v, 1, 3650).is_some())? {
        None | Some(Value::Bool(false)) => None,
        Some(Value::Bool(true)) => Some(NEW_DAYS),
        Some(v) => integral(v).map(|n| n as u64),
    };
    let versions_on = options.get("versions", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(false);
    let rank_of = |v: &Variant| -> Vec<usize> {
        dimensions.iter().map(|d| d.values.iter().position(|x| x.key == v.values[&d.key]).unwrap()).collect()
    };

    let mut slugs = HashSet::new();
    let mut groups: Vec<Group> = Vec::new();
    for g in manifest["groups"].as_array().unwrap() {
        let gname = g["name"].as_str().unwrap();
        let size_opt = text_of(groups_opt, gname, "size");
        let items = g["items"].as_array().unwrap();
        let shots: Vec<Shot> = items
            .iter()
            .map(|item| {
                let (w, h) = (size_of(item.get("width")).unwrap(), size_of(item.get("height")).unwrap());
                let mut shot = parse_shot(item["name"].as_str().unwrap(), &dimensions);
                let size = size_of_shot(&shot, &size_values, w, h, size_opt);
                shot.values.insert("size".into(), size);
                shot
            })
            .collect();
        // The group's values of each dimension: those its items name, else the dimension's first.
        let named: HashMap<&str, Vec<String>> = dimensions
            .iter()
            .map(|d| {
                let keys: Vec<String> = d
                    .values
                    .iter()
                    .filter(|v| shots.iter().any(|s| s.values.get(&d.key) == Some(&v.key)))
                    .map(|v| v.key.clone())
                    .collect();
                (d.key.as_str(), if keys.is_empty() { vec![d.values[0].key.clone()] } else { keys })
            })
            .collect();
        // Screens in the order their key first appears, each with its variants in the order they were first filed.
        let mut screens: Vec<(String, Vec<(String, Variant)>)> = Vec::new();
        let mut sinces: HashMap<String, String> = HashMap::new();
        // The snapshot pages of the items with each screen's newest since so far: the first that has one wins a tie.
        let mut changes: HashMap<String, Option<String>> = HashMap::new();
        for (item, shot) in items.iter().zip(&shots) {
            // Compared by code point: VisualCI writes every time in the same RFC 3339 form, in UTC.
            let since = item.get("since").and_then(Value::as_str).filter(|s| !s.is_empty());
            let snapshot =
                item.get("snapshot").and_then(Value::as_str).filter(|s| ABSOLUTE.is_match(s)).map(str::to_string);
            if let Some(since) = since {
                match sinces.get(&shot.key) {
                    Some(was) if since < was.as_str() => {}
                    Some(was) if since == was.as_str() => {
                        if changes.get(&shot.key).is_none_or(Option::is_none) {
                            changes.insert(shot.key.clone(), snapshot);
                        }
                    }
                    _ => {
                        sinces.insert(shot.key.clone(), since.into());
                        changes.insert(shot.key.clone(), snapshot);
                    }
                }
            }
            let (w, h) = (size_of(item.get("width")).unwrap(), size_of(item.get("height")).unwrap());
            let url = item["url"].as_str().unwrap();
            let at = match screens.iter().position(|(k, _)| *k == shot.key) {
                Some(i) => i,
                None => {
                    screens.push((shot.key.clone(), Vec::new()));
                    screens.len() - 1
                }
            };
            let variants = &mut screens[at].1;
            let combos = combinations(&dimensions, |d| match shot.values.get(&d.key) {
                Some(v) => vec![v.clone()],
                None => named[d.key.as_str()].clone(),
            });
            for combo in combos {
                let vid = combo.join(".");
                let i = match variants.iter().position(|(id, _)| *id == vid) {
                    Some(i) => i,
                    None => {
                        let values = dimensions.iter().map(|d| d.key.clone()).zip(combo).collect();
                        variants.push((
                            vid,
                            Variant {
                                values,
                                url: String::new(),
                                url2x: None,
                                width: 0,
                                height: 0,
                                bytes: None,
                                bytes2x: None,
                                thumb: None,
                            },
                        ));
                        variants.len() - 1
                    }
                };
                let v = &mut variants[i].1;
                if shot.x2 {
                    if v.url2x.is_none() {
                        v.url2x = Some(url.into());
                        v.bytes2x = bytes_of(item.get("bytes")).unwrap();
                    }
                } else if v.url.is_empty() {
                    // An image wider than the width its name gives was taken at a higher density: shown at the
                    // name's width, its height rounded half up in integers (the same in every language).
                    match shot.css_width {
                        Some(cw) if w > cw => {
                            let height = (2 * h as u128 * cw as u128 + w as u128) / (2 * w as u128);
                            (v.url, v.width, v.height) = (url.into(), cw, height as u64);
                        }
                        _ => (v.url, v.width, v.height) = (url.into(), w, h),
                    }
                    v.bytes = bytes_of(item.get("bytes")).unwrap();
                    v.thumb = thumb_of(item.get("thumb")).unwrap();
                }
            }
        }
        // The screens that have something to show; titles are made from these keys only.
        let kept: Vec<(String, Vec<Variant>)> = screens
            .into_iter()
            .filter_map(|(key, variants)| {
                let mut variants: Vec<Variant> =
                    variants.into_iter().map(|(_, v)| v).filter(|v| !v.url.is_empty()).collect();
                variants.sort_by_key(|v| rank_of(v));
                (!variants.is_empty()).then_some((key, variants))
            })
            .collect();
        if kept.is_empty() {
            continue;
        }
        let values = values_of(&dimensions, &kept.iter().flat_map(|(_, vs)| vs.iter()).collect::<Vec<_>>());
        // Every combination a screen should have: the group's values of each "error" dimension, the screen's own of
        // the rest. One theme's picture never stands in for another's.
        for (key, variants) in &kept {
            let own = values_of(&dimensions, &variants.iter().collect::<Vec<_>>());
            let have: HashSet<String> = variants.iter().map(|v| keys_of(&dimensions, &v.values).join(".")).collect();
            let wanted = combinations(&dimensions, |d| {
                if d.missing == Missing::Error { values[&d.key].clone() } else { own[&d.key].clone() }
            });
            for combo in wanted {
                if !have.contains(&combo.join(".")) {
                    return fail(format!(
                        "gallery screen {key} in group {gname} has no {} screenshot",
                        combo.join(" ")
                    ));
                }
            }
        }
        let prefix = common_folder(&kept.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>());
        let mut list: Vec<Screen> = kept
            .into_iter()
            .map(|(key, variants)| {
                let set = screens_opt.and_then(|m| m.get(&key));
                let title =
                    set.and_then(|s| s.get("title")).and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| {
                        let parts: Vec<&str> = key.split('/').skip(prefix).collect();
                        humanize(&parts)
                    });
                let caption = set.and_then(|s| s.get("caption")).and_then(Value::as_str).map(str::to_string);
                let since = sinces.get(&key).cloned();
                let change = changes.get(&key).cloned().flatten();
                Screen { key, title, caption, since, change, variants }
            })
            .collect();
        // Rust compares strings by code point, as the contract does.
        list.sort_by(|a, b| rank(&order, &a.key).cmp(&rank(&order, &b.key)).then_with(|| a.key.cmp(&b.key)));

        let base = slugify(gname);
        let mut slug = base.clone();
        let mut n = 2;
        while slugs.contains(&slug) {
            slug = format!("{base}-{n}");
            n += 1;
        }
        slugs.insert(slug.clone());
        let title = text_of(groups_opt, gname, "title")
            .or_else(|| g.get("title").and_then(Value::as_str))
            .unwrap_or(gname)
            .to_string();
        let fit = text_of(groups_opt, gname, "fit").unwrap_or("cover").to_string();
        groups.push(Group { name: gname.into(), title, slug, fit, values, screens: list });
    }
    if groups.is_empty() {
        return fail("the gallery manifest has no screenshots to show");
    }
    // Named groups first; the rest keep the manifest's order (the sort is stable).
    groups.sort_by_key(|g| rank(&group_order, &g.name));
    let screen_count = groups.iter().map(|g| g.screens.len() as u64).sum::<u64>();
    let search = layout == "grid"
        && match search_opt {
            None => screen_count >= SEARCH_FROM,
            Some(Value::Bool(on)) => *on,
            Some(v) => integral(v).is_some_and(|n| screen_count as f64 >= n),
        };

    Ok(Model {
        see_all: see_all.map(|v| SeeAll {
            href: v["href"].as_str().unwrap().into(),
            text: v.get("text").and_then(Value::as_str).unwrap_or(SEE_ALL_TEXT).into(),
        }),
        label: title.clone().unwrap_or_else(|| text.label.clone()),
        title,
        heading_level,
        id,
        credit,
        preload,
        deep_links,
        text,
        search,
        zoom,
        new_badges,
        versions: if versions_on && layout == "grid" { versions_of(manifest, options) } else { None },
        theme_switch: layout == "grid" && switch,
        layout,
        dimensions: with_shapes(dimensions, &groups),
        groups,
    })
}

/// The Version switch's model (already checked): the listed versions, the one shown and Latest's manifest; None when
/// the manifest lists none.
fn versions_of(manifest: &Value, options: &Options) -> Option<Versions> {
    let list: Vec<Version> = manifest
        .get("versions")
        .and_then(Value::as_array)?
        .iter()
        .map(|v| Version {
            key: v["key"].as_str().unwrap().into(),
            label: v["label"].as_str().unwrap().into(),
            manifest: v["manifest"].as_str().unwrap().into(),
        })
        .collect();
    let first = list.first()?;
    let latest = format!("{}.json", &first.manifest[..first.manifest.len() - format!("@{}.json", first.key).len()]);
    let key = manifest.get("version").and_then(|v| v.get("key")).and_then(Value::as_str);
    let current = key.filter(|k| list.iter().any(|v| v.key == *k)).unwrap_or("latest").to_string();
    Some(Versions { current, latest, options: options_json(options), list })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn shot(key: &str, values: &[(&str, &str)], x2: bool, css_width: Option<u64>) -> Shot {
        let values = values.iter().map(|(d, v)| (d.to_string(), v.to_string())).collect();
        Shot { key: key.into(), values, x2, css_width }
    }

    #[test]
    fn parses_shot_names() {
        let dims = default_dimensions();
        let cases = [
            ("overview-dark-1440", shot("overview", &[("theme", "dark")], false, Some(1440))),
            ("ios/usage-light.png", shot("ios/usage", &[("theme", "light")], false, None)),
            ("shots/app/billing/1440-dark-2x", shot("shots/app/billing", &[("theme", "dark")], true, Some(1440))),
            ("dark-mode-light", shot("dark-mode", &[("theme", "light")], false, None)),
            // Values and the width in any order, and a size by name.
            ("home-1440-light", shot("home", &[("theme", "light")], false, Some(1440))),
            ("home-phone-dark", shot("home", &[("theme", "dark"), ("size", "phone")], false, None)),
            ("shots/home/phone-light", shot("shots/home", &[("theme", "light"), ("size", "phone")], false, None)),
            // `<screen>/<width>`: a theme-less app's sizes pair by folder.
            ("issues/1440", shot("issues", &[], false, Some(1440))),
            ("issues/390-2x", shot("issues", &[], true, Some(390))),
            // A width alone after other words, or a name that is only values, is a screen of its own.
            ("overview-1440", shot("overview-1440", &[], false, None)),
            ("light", shot("light", &[], false, None)),
            ("1440-dark", shot("1440-dark", &[], false, None)),
            ("a-1440-2x", shot("a-1440-2x", &[], false, None)),
            (
                "x/\u{661}\u{664}\u{664}\u{660}-light",
                shot("x/\u{661}\u{664}\u{664}\u{660}", &[("theme", "light")], false, None),
            ),
            ("a-light-1440\n", shot("a-light-1440\n", &[], false, None)),
        ];
        for (name, want) in cases {
            assert_eq!(parse_shot(name, &dims), want, "{name}");
        }
    }

    #[test]
    fn peels_the_longest_value_key_a_dimension_at_most_once() {
        let manifest =
            json!({"groups": [{"name": "G", "items": [{"name": "a", "url": "https://x/a", "width": 1, "height": 1}]}]});
        let options = Options::from_json(&json!({"dimensions": [
            {"key": "theme", "values": [{"key": "light"}, {"key": "dark"}, {"key": "high-contrast"}]},
            {"key": "lang", "values": [{"key": "en"}, {"key": "fr"}]}
        ]}))
        .unwrap();
        let dims = build_model(&manifest, &options).unwrap().dimensions;
        assert_eq!(
            parse_shot("pricing-high-contrast-fr", &dims),
            shot("pricing", &[("theme", "high-contrast"), ("lang", "fr")], false, None)
        );
        assert_eq!(parse_shot("dark-light", &dims), shot("dark", &[("theme", "light")], false, None));
    }

    #[test]
    fn resolves_dimensions() {
        let manifest =
            json!({"groups": [{"name": "G", "items": [{"name": "a", "url": "https://x/a", "width": 1, "height": 1}]}]});
        let options = Options::default().dimension("size", Some("Device"), None, &[]).dimension(
            "plan",
            None,
            None,
            &[("free", None, None), ("pro", Some("Pro"), None)],
        );
        let dims = build_model(&manifest, &options).unwrap().dimensions;
        let keys: Vec<&str> = dims.iter().map(|d| d.key.as_str()).collect();
        assert_eq!(keys, ["theme", "size", "plan"]);
        assert_eq!((dims[1].label.as_str(), dims[1].missing, dims[1].values.len()), ("Device", Missing::Hide, 2));
        assert_eq!((dims[2].label.as_str(), dims[2].missing), ("plan", Missing::First));
        assert_eq!((dims[2].values[0].label.as_str(), dims[2].values[1].label.as_str()), ("free", "Pro"));
    }
}