visualci-gallery 0.2.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
//! 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::{HashMap, HashSet};
use std::sync::LazyLock;

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

use crate::Error;

pub const DEFAULT_TITLE: &str = "Screenshots";
pub const SEE_ALL_TEXT: &str = "See all screenshots";
const SIZES: [&str; 2] = ["desktop", "phone"];
const THEMES: [&str; 2] = ["light", "dark"];

// 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").
static EXTENSION: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\z").unwrap());
static WIDTH_THEME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A([0-9]+)-(light|dark)(-2x)?\z").unwrap());
static SCREEN_THEME: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\A((?s:.)+?)-(light|dark)(?:-([0-9]+))?(-2x)?\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());

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Variant {
    pub size: String,
    pub theme: String,
    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),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Screen {
    pub key: String,
    pub title: String,
    pub caption: 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,
    pub sizes: Vec<String>,
    pub screens: Vec<Screen>,
}

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

/// 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 groups: Vec<Group>,
}

/// 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 theme, width and 2x parts.
    pub key: String,
    /// None when the name says nothing: the shot stands for both themes.
    pub theme: Option<String>,
    pub size: String,
    pub x2: bool,
    /// The CSS width the name gives (`-1440`).
    pub css_width: Option<u64>,
}

/// `<screen>-<theme>[-<width>][-2x]`, or `<screen>/<width>-<theme>[-2x]`. A name in neither shape is a screen of its
/// own, in both themes. Under 768 wide is a phone; with no width, a portrait image is a phone and a landscape one a
/// desktop, unless `size` says.
pub fn parse_shot(name: &str, width: u64, height: u64, size: Option<&str>) -> Shot {
    let stripped = EXTENSION.replace(name, "");
    let mut parts: Vec<&str> = stripped.split('/').collect();
    let last = parts.pop().unwrap_or("");
    let folder = parts.join("/");
    // A width too long for u64 is still a desktop's (JS compares the number, which is huge).
    let sized = |w: Option<&str>| -> String {
        match w {
            Some(w) => if w.parse::<u64>().is_ok_and(|n| n < 768) { "phone" } else { "desktop" }.to_string(),
            None => {
                size.map(str::to_string).unwrap_or_else(|| if height > width { "phone" } else { "desktop" }.to_string())
            }
        }
    };
    let css = |w: Option<&str>| w.and_then(|w| w.parse::<u64>().ok());

    if !folder.is_empty() {
        if let Some(m) = WIDTH_THEME.captures(last) {
            let w = m.get(1).map(|x| x.as_str());
            return Shot {
                key: folder,
                theme: Some(m[2].to_string()),
                size: sized(w),
                x2: m.get(3).is_some(),
                css_width: css(w),
            };
        }
    }
    if let Some(m) = SCREEN_THEME.captures(last) {
        let key = if folder.is_empty() { m[1].to_string() } else { format!("{folder}/{}", &m[1]) };
        let w = m.get(3).map(|x| x.as_str());
        return Shot { key, theme: Some(m[2].to_string()), size: sized(w), x2: m.get(4).is_some(), css_width: css(w) };
    }
    let key = if folder.is_empty() { last.to_string() } else { format!("{folder}/{last}") };
    Shot { key, theme: None, size: sized(None), x2: false, css_width: None }
}

/// `["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.
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"));
            }
        }
    }
    Ok(())
}

/// 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 {
    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"),
        }
    }
    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 ("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(), serde_json::json!({ "title": title, "caption": caption }));
        }
        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 no width, 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(), serde_json::json!({ "title": title, "size": size, "fit": fit }));
        }
        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", serde_json::json!({ "href": href, "text": text }))
    }
    /// 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", serde_json::json!({ "fold": fold, "count": count, "bytes": bytes, "parallel": parallel }))
    }

    /// An option's value, with null meaning absent; `check` false is an error.
    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(v: &Value) -> bool {
    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.contains(&s.as_str()),
                    ("fit", Value::String(f)) => f == "cover" || f == "contain",
                    _ => false,
                })
            })
        })
    })
}

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;
    let title = if options.raw.contains_key("title") {
        options.get("title", Value::is_string)?.and_then(Value::as_str).map(str::to_string)
    } else {
        Some(DEFAULT_TITLE.to_string())
    };
    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 screens_opt = options.get("screens", texts(&["title", "caption"]))?;
    let groups_opt = options.get("groups", group_options)?;
    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(true);
    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 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");
        // Screens in the manifest's order, each with its variants in the order they were first filed.
        let mut keys: Vec<String> = Vec::new();
        let mut found: HashMap<String, Vec<Variant>> = HashMap::new();
        for item in g["items"].as_array().unwrap() {
            let (w, h) = (size_of(item.get("width")).unwrap(), size_of(item.get("height")).unwrap());
            let url = item["url"].as_str().unwrap();
            let shot = parse_shot(item["name"].as_str().unwrap(), w, h, size_opt);
            let variants = found.entry(shot.key.clone()).or_insert_with(|| {
                keys.push(shot.key.clone());
                Vec::new()
            });
            let themes: Vec<&str> = match &shot.theme {
                Some(t) => vec![t.as_str()],
                None => THEMES.to_vec(),
            };
            for theme in themes {
                let at = match variants.iter().position(|v| v.size == shot.size && v.theme == theme) {
                    Some(i) => i,
                    None => {
                        variants.push(Variant {
                            size: shot.size.clone(),
                            theme: theme.into(),
                            url: String::new(),
                            url2x: None,
                            width: 0,
                            height: 0,
                            bytes: None,
                            bytes2x: None,
                            thumb: None,
                        });
                        variants.len() - 1
                    }
                };
                let v = &mut variants[at];
                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 mut kept: Vec<(String, Vec<Variant>)> = Vec::new();
        for key in keys {
            let mut variants: Vec<Variant> =
                found.remove(&key).unwrap().into_iter().filter(|v| !v.url.is_empty()).collect();
            variants
                .sort_by_key(|v| (SIZES.iter().position(|s| *s == v.size), THEMES.iter().position(|t| *t == v.theme)));
            if !variants.is_empty() {
                kept.push((key, variants));
            }
        }
        // A screen shows both themes at each of its sizes: one theme's image never stands in for the other's.
        for (key, variants) in &kept {
            for v in variants {
                if !variants.iter().any(|o| o.size == v.size && o.theme != v.theme) {
                    let other = if v.theme == "light" { "dark" } else { "light" };
                    return fail(format!(
                        "gallery screen {key} in group {gname} has a {} {} screenshot but no {other} one",
                        v.theme, v.size
                    ));
                }
            }
        }
        if kept.is_empty() {
            continue;
        }
        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);
                Screen { key, title, caption, 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 sizes = SIZES
            .iter()
            .filter(|s| list.iter().any(|sc| sc.variants.iter().any(|v| v.size == **s)))
            .map(|s| s.to_string())
            .collect();
        let fit = text_of(groups_opt, gname, "fit").unwrap_or("cover").to_string();
        groups.push(Group { name: gname.into(), title, slug, fit, sizes, 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));

    Ok(Model {
        theme_switch: layout == "grid" && switch,
        layout,
        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(|| DEFAULT_TITLE.into()),
        title,
        heading_level,
        id,
        credit,
        preload,
        groups,
    })
}