1use std::collections::{BTreeMap, HashMap, HashSet};
5use std::sync::LazyLock;
6
7use regex::Regex;
8use serde::{Serialize, Serializer};
9use serde_json::{Map, Value};
10
11use crate::Error;
12
13pub const TEXT_DEFAULTS: [(&str, &str); 15] = [
15 ("label", "Screenshots"),
16 ("open", "{title}: view full size"),
17 ("previous", "Previous screen"),
18 ("next", "Next screen"),
19 ("close", "Close"),
20 ("back", "Scroll back"),
21 ("forward", "Scroll forward"),
22 ("credit", "Screenshots by {link}"),
23 ("and", " and "),
24 ("search", "Search screens"),
25 ("empty", "No screens match"),
26 ("new", "New"),
27 ("change", "New in {title}: see what changed"),
28 ("version", "Version"),
29 ("latest", "Latest"),
30];
31pub const SEE_ALL_TEXT: &str = "See all screenshots";
32pub const SEARCH_FROM: u64 = 40;
34pub const NEW_DAYS: u64 = 30;
36
37pub(crate) static EXTENSION: LazyLock<Regex> =
40 LazyLock::new(|| Regex::new(r"\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\z").unwrap());
41static KEY: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A[a-z0-9]+(-[a-z0-9]+)*\z").unwrap());
42static ABSOLUTE: LazyLock<Regex> =
43 LazyLock::new(|| Regex::new(r"\A[hH][tT][tT][pP][sS]?://[^\x00-\x20\x7f]+\z").unwrap());
44static CONTROL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\x00-\x20\x7f]").unwrap());
45static SCHEME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A[A-Za-z][A-Za-z0-9+.-]*:").unwrap());
46static ID: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A[A-Za-z][A-Za-z0-9_-]*\z").unwrap());
47
48pub type Values = BTreeMap<String, String>;
50
51#[derive(Debug, Clone, PartialEq, Serialize)]
52pub struct Variant {
53 pub values: Values,
55 pub url: String,
56 pub url2x: Option<String>,
57 pub width: u64,
58 pub height: u64,
59 pub bytes: Option<u64>,
61 pub bytes2x: Option<u64>,
62 pub thumb: Option<Thumb>,
64}
65
66#[derive(Debug, Clone, PartialEq, Serialize)]
67pub struct Thumb {
68 pub url: String,
69 pub width: u64,
70 pub height: u64,
71 pub bytes: Option<u64>,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
77pub struct PreloadCaps {
78 pub fold: u64,
79 pub count: u64,
80 pub bytes: u64,
81 pub parallel: u64,
82}
83
84impl Default for PreloadCaps {
85 fn default() -> Self {
87 PreloadCaps { fold: 250, count: 500, bytes: 50_000_000, parallel: 4 }
88 }
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum Preload {
94 Off,
95 Caps(PreloadCaps),
96}
97
98impl Serialize for Preload {
99 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
100 match self {
101 Preload::Off => serializer.serialize_str("off"),
102 Preload::Caps(caps) => caps.serialize(serializer),
103 }
104 }
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
110#[serde(rename_all = "lowercase")]
111pub enum Missing {
112 Error,
113 Hide,
114 First,
115}
116
117impl Missing {
118 pub fn as_str(self) -> &'static str {
119 match self {
120 Missing::Error => "error",
121 Missing::Hide => "hide",
122 Missing::First => "first",
123 }
124 }
125 fn parse(s: &str) -> Option<Self> {
126 match s {
127 "error" => Some(Missing::Error),
128 "hide" => Some(Missing::Hide),
129 "first" => Some(Missing::First),
130 _ => None,
131 }
132 }
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
137#[serde(rename_all = "lowercase")]
138pub enum Shape {
139 Landscape,
140 Portrait,
141}
142
143impl Shape {
144 pub fn as_str(self) -> &'static str {
145 match self {
146 Shape::Landscape => "landscape",
147 Shape::Portrait => "portrait",
148 }
149 }
150}
151
152#[derive(Debug, Clone, PartialEq, Serialize)]
153pub struct DimensionValue {
154 pub key: String,
155 pub label: String,
156 pub below: Option<u64>,
157 pub shape: Option<Shape>,
159}
160
161#[derive(Debug, Clone, PartialEq, Serialize)]
163pub struct Dimension {
164 pub key: String,
165 pub label: String,
166 pub missing: Missing,
167 pub values: Vec<DimensionValue>,
168}
169
170fn value(key: &str, label: &str, below: Option<u64>) -> DimensionValue {
171 DimensionValue { key: key.into(), label: label.into(), below, shape: None }
172}
173
174pub fn default_dimensions() -> Vec<Dimension> {
176 vec![
177 Dimension {
178 key: "theme".into(),
179 label: "Theme".into(),
180 missing: Missing::Error,
181 values: vec![value("light", "Light", None), value("dark", "Dark", None)],
182 },
183 Dimension {
184 key: "size".into(),
185 label: "Screen size".into(),
186 missing: Missing::Hide,
187 values: vec![value("desktop", "Desktop", None), value("phone", "Phone", Some(768))],
188 },
189 ]
190}
191
192#[derive(Debug, Clone, PartialEq, Serialize)]
193pub struct Screen {
194 pub key: String,
195 pub title: String,
196 pub caption: Option<String>,
197 pub since: Option<String>,
199 pub change: Option<String>,
201 pub variants: Vec<Variant>,
202}
203
204#[derive(Debug, Clone, PartialEq, Serialize)]
205pub struct Group {
206 pub name: String,
207 pub title: String,
208 pub slug: String,
209 pub fit: String,
210 pub values: BTreeMap<String, Vec<String>>,
212 pub screens: Vec<Screen>,
213}
214
215#[derive(Debug, Clone, PartialEq, Serialize)]
216pub struct SeeAll {
217 pub href: String,
218 pub text: String,
219}
220
221#[derive(Debug, Clone, PartialEq, Serialize)]
225pub struct Text {
226 pub label: String,
227 pub open: String,
228 pub previous: String,
229 pub next: String,
230 pub close: String,
231 pub back: String,
232 pub forward: String,
233 pub credit: String,
234 pub and: String,
235 pub search: String,
236 pub empty: String,
237 pub new: String,
238 pub change: String,
239 pub version: String,
241 pub latest: String,
243}
244
245impl Text {
246 fn with(get: impl Fn(&str) -> Option<String>) -> Self {
248 let w = |k: &str| get(k).unwrap_or_else(|| TEXT_DEFAULTS.iter().find(|(d, _)| *d == k).unwrap().1.into());
249 Text {
250 label: w("label"),
251 open: w("open"),
252 previous: w("previous"),
253 next: w("next"),
254 close: w("close"),
255 back: w("back"),
256 forward: w("forward"),
257 credit: w("credit"),
258 and: w("and"),
259 search: w("search"),
260 empty: w("empty"),
261 new: w("new"),
262 change: w("change"),
263 version: w("version"),
264 latest: w("latest"),
265 }
266 }
267}
268
269impl Default for Text {
270 fn default() -> Self {
271 Text::with(|_| None)
272 }
273}
274
275#[derive(Debug, Clone, PartialEq, Serialize)]
277#[serde(rename_all = "camelCase")]
278pub struct Model {
279 pub layout: String,
280 pub theme_switch: bool,
281 pub see_all: Option<SeeAll>,
282 pub title: Option<String>,
283 pub label: String,
284 pub heading_level: u8,
285 pub id: String,
286 pub credit: bool,
287 pub preload: Option<Preload>,
289 pub deep_links: bool,
290 pub text: Text,
291 pub search: bool,
293 pub zoom: bool,
294 pub new_badges: Option<u64>,
296 pub dimensions: Vec<Dimension>,
297 pub groups: Vec<Group>,
298 pub versions: Option<Versions>,
300}
301
302#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
304pub struct Versions {
305 pub current: String,
307 pub latest: String,
309 pub options: String,
312 pub list: Vec<Version>,
313}
314
315#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
317pub struct Version {
318 pub key: String,
319 pub label: String,
320 pub manifest: String,
322}
323
324#[derive(Debug, Clone, PartialEq)]
326pub struct Shot {
327 pub key: String,
329 pub values: Values,
331 pub x2: bool,
332 pub css_width: Option<u64>,
334}
335
336fn digits(s: &str) -> bool {
337 !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
338}
339
340pub fn parse_shot(name: &str, dimensions: &[Dimension]) -> Shot {
343 let base = EXTENSION.replace(name, "").into_owned();
344 let mut parts: Vec<&str> = base.split('/').collect();
345 let last = parts.pop().unwrap_or("");
346 let folder = parts.join("/");
347 let owner: HashMap<&str, &str> =
348 dimensions.iter().flat_map(|d| d.values.iter().map(move |v| (v.key.as_str(), d.key.as_str()))).collect();
349 let mut tokens: Vec<&str> = last.split('-').collect();
350 let mut x2 = false;
351 if tokens.last() == Some(&"2x") {
352 tokens.pop();
353 x2 = true;
354 }
355 let mut values = Values::new();
356 let mut css_width: Option<u64> = None;
357 let mut named = false;
358 loop {
359 let mut peeled = false;
360 for n in (1..=tokens.len()).rev() {
361 let candidate = tokens[tokens.len() - n..].join("-");
362 if let Some(dim) = owner.get(candidate.as_str())
363 && !values.contains_key(*dim)
364 {
365 values.insert(dim.to_string(), candidate);
366 tokens.truncate(tokens.len() - n);
367 named = true;
368 peeled = true;
369 break;
370 }
371 }
372 if peeled {
373 continue;
374 }
375 if css_width.is_none()
376 && let Some(t) = tokens.last().filter(|t| digits(t))
377 {
378 css_width = Some(t.parse::<u64>().unwrap_or(u64::MAX));
380 tokens.pop();
381 continue;
382 }
383 break;
384 }
385 let width_only = css_width.is_some() && tokens.is_empty() && !folder.is_empty();
387 if (!named && !width_only) || (tokens.is_empty() && folder.is_empty()) {
388 return Shot { key: base, values: Values::new(), x2: false, css_width: None };
389 }
390 let rest = tokens.join("-");
391 let key = if tokens.is_empty() {
392 folder
393 } else if folder.is_empty() {
394 rest
395 } else {
396 format!("{folder}/{rest}")
397 };
398 Shot { key, values, x2, css_width }
399}
400
401fn size_of_shot(shot: &Shot, sizes: &[DimensionValue], width: u64, height: u64, group_size: Option<&str>) -> String {
404 if let Some(s) = shot.values.get("size") {
405 return s.clone();
406 }
407 let open = &sizes.iter().find(|v| v.below.is_none()).expect("a size with no below").key;
408 let mut bounded: Vec<&DimensionValue> = sizes.iter().filter(|v| v.below.is_some()).collect();
409 bounded.sort_by_key(|v| v.below);
410 if let Some(cw) = shot.css_width {
411 return bounded.iter().find(|v| cw < v.below.unwrap()).map_or(open, |v| &v.key).clone();
412 }
413 if let Some(g) = group_size {
414 return g.to_string();
415 }
416 if height > width && !bounded.is_empty() { bounded[0].key.clone() } else { open.clone() }
417}
418
419pub fn humanize(segments: &[&str]) -> String {
421 static RUNS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[-_]+").unwrap());
422 let text =
423 segments.iter().map(|s| RUNS.replace_all(s, " ").trim_matches(' ').to_string()).collect::<Vec<_>>().join(", ");
424 let mut chars = text.chars();
425 match chars.next() {
426 Some(first) => first.to_uppercase().chain(chars).collect(),
427 None => text,
428 }
429}
430
431pub fn slugify(name: &str) -> String {
433 let mut out = String::new();
434 let mut dash = false;
435 for c in name.chars() {
436 let c = c.to_ascii_lowercase();
437 if c.is_ascii_lowercase() || c.is_ascii_digit() {
438 if dash && !out.is_empty() {
439 out.push('-');
440 }
441 dash = false;
442 out.push(c);
443 } else {
444 dash = true;
445 }
446 }
447 if out.is_empty() { "group".to_string() } else { out }
448}
449
450fn common_folder(keys: &[&str]) -> usize {
451 let folders: Vec<Vec<&str>> = keys
452 .iter()
453 .map(|k| {
454 let mut p: Vec<&str> = k.split('/').collect();
455 p.pop();
456 p
457 })
458 .collect();
459 let Some(first) = folders.first() else { return 0 };
460 let mut common = first.len();
461 for f in &folders[1..] {
462 let mut i = 0;
463 while i < common && i < f.len() && first[i] == f[i] {
464 i += 1;
465 }
466 common = i;
467 }
468 common
469}
470
471fn rank(order: &Option<Vec<String>>, key: &str) -> usize {
472 let list = order.as_deref().unwrap_or(&[]);
473 list.iter().position(|k| k == key).unwrap_or(list.len())
474}
475
476fn safe_href(value: &str) -> bool {
477 ABSOLUTE.is_match(value) || (!value.is_empty() && !CONTROL.is_match(value) && !SCHEME.is_match(value))
478}
479
480fn fail<T>(message: impl Into<String>) -> Result<T, Error> {
481 Err(Error::Invalid(message.into()))
482}
483
484fn integral(v: &Value) -> Option<f64> {
486 let n = v.as_f64()?;
487 (n.is_finite() && n.fract() == 0.0).then_some(n)
488}
489
490pub const MAX_SIZE: u64 = 1_000_000;
492
493fn size_of(v: Option<&Value>) -> Option<u64> {
494 let n = integral(v?)?;
495 (n > 0.0 && n <= MAX_SIZE as f64).then_some(n as u64)
496}
497
498const MAX_CAP: u64 = 1_000_000_000_000;
500
501fn whole_in(v: &Value, min: u64, max: u64) -> Option<u64> {
503 let n = integral(v)?;
504 (n >= min as f64 && n <= max as f64).then_some(n as u64)
505}
506
507fn bytes_of(v: Option<&Value>) -> Result<Option<u64>, ()> {
509 match v {
510 None | Some(Value::Null) => Ok(None),
511 Some(v) => whole_in(v, 0, MAX_CAP).map(Some).ok_or(()),
512 }
513}
514
515fn thumb_of(v: Option<&Value>) -> Result<Option<Thumb>, ()> {
517 let t = match v {
518 None | Some(Value::Null) => return Ok(None),
519 Some(t) => t,
520 };
521 let url = t.get("url").and_then(Value::as_str).filter(|u| t.is_object() && ABSOLUTE.is_match(u)).ok_or(())?;
522 let (width, height) = (size_of(t.get("width")).ok_or(())?, size_of(t.get("height")).ok_or(())?);
523 Ok(Some(Thumb { url: url.into(), width, height, bytes: bytes_of(t.get("bytes"))? }))
524}
525
526fn preload_valid(v: &Value) -> bool {
529 v.is_boolean()
530 || v.as_object().is_some_and(|m| {
531 m.iter().all(|(k, x)| match k.as_str() {
532 "fold" | "count" | "bytes" => x.is_null() || whole_in(x, 0, MAX_CAP).is_some(),
533 "parallel" => x.is_null() || whole_in(x, 1, 8).is_some(),
534 _ => false,
535 })
536 })
537}
538
539fn preload_model(v: Option<&Value>) -> Option<Preload> {
540 match v? {
541 Value::Bool(true) => None,
542 Value::Bool(false) => Some(Preload::Off),
543 v => {
544 let d = PreloadCaps::default();
545 let cap = |k: &str, d: u64| v.get(k).and_then(integral).map_or(d, |n| n as u64);
546 Some(Preload::Caps(PreloadCaps {
547 fold: cap("fold", d.fold),
548 count: cap("count", d.count),
549 bytes: cap("bytes", d.bytes),
550 parallel: cap("parallel", d.parallel),
551 }))
552 }
553 }
554}
555
556pub(crate) fn check_manifest(manifest: &Value) -> Result<(), Error> {
558 let Some(groups) = manifest.get("groups").filter(|_| manifest.is_object()).and_then(Value::as_array) else {
559 return fail("not a gallery manifest: it has no groups");
560 };
561 for (i, g) in groups.iter().enumerate() {
562 let name = match g.get("name").and_then(Value::as_str) {
563 Some(n) if g.is_object() && !n.is_empty() => n,
564 _ => return fail(format!("gallery manifest group {i} has no name")),
565 };
566 if !matches!(g.get("title"), None | Some(Value::Null) | Some(Value::String(_))) {
567 return fail(format!("gallery manifest group {name}: its title isn't a string"));
568 }
569 let Some(items) = g.get("items").and_then(Value::as_array) else {
570 return fail(format!("gallery manifest group {name} has no items"));
571 };
572 for (j, item) in items.iter().enumerate() {
573 let place = format!("gallery manifest group {name}, item {j}");
574 let iname = match item.get("name").and_then(Value::as_str) {
575 Some(n) if item.is_object() && !n.is_empty() => n,
576 _ => return fail(format!("{place} has no name")),
577 };
578 if !item.get("url").and_then(Value::as_str).is_some_and(|u| ABSOLUTE.is_match(u)) {
579 return fail(format!("{place} ({iname}): its url isn't an http(s) URL"));
580 }
581 if size_of(item.get("width")).is_none() || size_of(item.get("height")).is_none() {
582 return fail(format!(
583 "{place} ({iname}): its width and height aren't whole numbers from 1 to {MAX_SIZE}"
584 ));
585 }
586 if bytes_of(item.get("bytes")).is_err() {
587 return fail(format!("{place} ({iname}): its bytes isn't a whole number"));
588 }
589 if thumb_of(item.get("thumb")).is_err() {
590 return fail(format!("{place} ({iname}): its thumb needs an http(s) url, a width and a height"));
591 }
592 }
593 }
594 if !versions_valid(manifest) {
595 return fail("the gallery manifest's versions are invalid");
596 }
597 Ok(())
598}
599
600fn versions_valid(manifest: &Value) -> bool {
603 let mut seen: HashSet<&str> = HashSet::new();
604 let listed = match manifest.get("versions") {
605 None | Some(Value::Null) => true,
606 Some(Value::Array(list)) => list.iter().all(|v| {
607 let Some(key) = v.get("key").and_then(Value::as_str).filter(|k| v.is_object() && KEY.is_match(k)) else {
608 return false;
609 };
610 key != "latest"
611 && seen.insert(key)
612 && v.get("label").and_then(Value::as_str).is_some_and(|l| !l.is_empty())
613 && v.get("manifest")
614 .and_then(Value::as_str)
615 .is_some_and(|m| ABSOLUTE.is_match(m) && m.ends_with(&format!("@{key}.json")))
616 }),
617 Some(_) => false,
618 };
619 listed
620 && match manifest.get("version") {
621 None | Some(Value::Null) => true,
622 Some(v @ Value::Object(_)) => text_or_null(v.get("key")),
623 Some(_) => false,
624 }
625}
626
627const OPTION_KEYS: [&str; 19] = [
629 "title",
630 "headingLevel",
631 "id",
632 "dimensions",
633 "screens",
634 "order",
635 "groups",
636 "groupOrder",
637 "credit",
638 "layout",
639 "themeSwitch",
640 "seeAll",
641 "preload",
642 "deepLinks",
643 "text",
644 "search",
645 "zoom",
646 "newBadges",
647 "versions",
648];
649
650fn canonical_string(s: &str, out: &mut String) {
652 out.push('"');
653 for c in s.chars() {
654 match c {
655 '"' => out.push_str("\\\""),
656 '\\' => out.push_str("\\\\"),
657 '\u{8}' => out.push_str("\\b"),
658 '\t' => out.push_str("\\t"),
659 '\n' => out.push_str("\\n"),
660 '\u{c}' => out.push_str("\\f"),
661 '\r' => out.push_str("\\r"),
662 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
663 c => out.push(c),
664 }
665 }
666 out.push('"');
667}
668
669fn canonical(value: &Value, out: &mut String) {
671 match value {
672 Value::Null => out.push_str("null"),
673 Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
674 Value::Number(n) => match (n.as_i64(), n.as_u64(), n.as_f64()) {
675 (Some(i), _, _) => out.push_str(&i.to_string()),
676 (_, Some(u), _) => out.push_str(&u.to_string()),
677 (_, _, Some(0.0)) => out.push('0'),
680 (_, _, Some(f)) => out.push_str(&f.to_string()),
681 _ => out.push_str(&n.to_string()),
682 },
683 Value::String(s) => canonical_string(s, out),
684 Value::Array(a) => {
685 out.push('[');
686 for (i, v) in a.iter().enumerate() {
687 if i > 0 {
688 out.push(',');
689 }
690 canonical(v, out);
691 }
692 out.push(']');
693 }
694 Value::Object(m) => {
695 let mut keys: Vec<&String> = m.keys().collect();
697 keys.sort();
698 out.push('{');
699 for (i, k) in keys.into_iter().enumerate() {
700 if i > 0 {
701 out.push(',');
702 }
703 canonical_string(k, out);
704 out.push(':');
705 canonical(&m[k], out);
706 }
707 out.push('}');
708 }
709 }
710}
711
712pub fn options_json(options: &Options) -> String {
715 let set: Map<String, Value> = OPTION_KEYS
716 .iter()
717 .filter_map(|k| {
718 options.raw.get(*k).filter(|v| !v.is_null() || *k == "title").map(|v| (k.to_string(), v.clone()))
719 })
720 .collect();
721 let mut out = String::new();
722 canonical(&Value::Object(set), &mut out);
723 out
724}
725
726fn object(pairs: Vec<(&str, Value)>) -> Value {
729 Value::Object(pairs.into_iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.to_string(), v)).collect())
730}
731
732#[derive(Debug, Clone, Default)]
735pub struct Options {
736 pub(crate) raw: Map<String, Value>,
737}
738
739impl Options {
740 pub fn from_json(value: &Value) -> Result<Self, Error> {
742 match value {
743 Value::Object(m) => Ok(Options { raw: m.clone() }),
744 _ => fail("gallery options must be an object"),
745 }
746 }
747 pub(crate) fn set(mut self, key: &str, value: Value) -> Self {
748 self.raw.insert(key.to_string(), value);
749 self
750 }
751 pub fn title(self, title: Option<&str>) -> Self {
754 self.set("title", title.map_or(Value::Null, |t| Value::String(t.into())))
755 }
756 pub fn heading_level(self, level: u8) -> Self {
757 self.set("headingLevel", level.into())
758 }
759 pub fn id(self, id: &str) -> Self {
760 self.set("id", id.into())
761 }
762 pub fn screen(mut self, key: &str, title: Option<&str>, caption: Option<&str>) -> Self {
764 let screens = self.raw.entry("screens").or_insert_with(|| Value::Object(Map::new()));
765 if let Value::Object(m) = screens {
766 m.insert(key.into(), object(vec![("title", title.into()), ("caption", caption.into())]));
767 }
768 self
769 }
770 pub fn order<S: AsRef<str>>(self, keys: &[S]) -> Self {
771 self.set("order", keys.iter().map(|k| Value::String(k.as_ref().into())).collect())
772 }
773 pub fn group(mut self, name: &str, title: Option<&str>, size: Option<&str>, fit: Option<&str>) -> Self {
776 let groups = self.raw.entry("groups").or_insert_with(|| Value::Object(Map::new()));
777 if let Value::Object(m) = groups {
778 m.insert(name.into(), object(vec![("title", title.into()), ("size", size.into()), ("fit", fit.into())]));
779 }
780 self
781 }
782 pub fn dimension(
787 mut self,
788 key: &str,
789 label: Option<&str>,
790 missing: Option<&str>,
791 values: &[(&str, Option<&str>, Option<u64>)],
792 ) -> Self {
793 let mut entry = object(vec![("key", key.into()), ("label", label.into()), ("missing", missing.into())]);
794 if !values.is_empty() {
795 entry["values"] = values
796 .iter()
797 .map(|(k, label, below)| {
798 object(vec![("key", (*k).into()), ("label", (*label).into()), ("below", (*below).into())])
799 })
800 .collect();
801 }
802 let list = self.raw.entry("dimensions").or_insert_with(|| Value::Array(Vec::new()));
803 if let Value::Array(a) = list {
804 a.push(entry);
805 }
806 self
807 }
808 pub fn group_order<S: AsRef<str>>(self, names: &[S]) -> Self {
809 self.set("groupOrder", names.iter().map(|k| Value::String(k.as_ref().into())).collect())
810 }
811 pub fn credit(self, on: bool) -> Self {
812 self.set("credit", on.into())
813 }
814 pub fn layout(self, layout: &str) -> Self {
816 self.set("layout", layout.into())
817 }
818 pub fn theme_switch(self, on: bool) -> Self {
819 self.set("themeSwitch", on.into())
820 }
821 pub fn see_all(self, href: &str, text: Option<&str>) -> Self {
822 self.set("seeAll", object(vec![("href", href.into()), ("text", text.into())]))
823 }
824 pub fn preload(self, on: bool) -> Self {
826 self.set("preload", on.into())
827 }
828 pub fn preload_caps(
832 self,
833 fold: Option<u64>,
834 count: Option<u64>,
835 bytes: Option<u64>,
836 parallel: Option<u64>,
837 ) -> Self {
838 self.set(
839 "preload",
840 object(vec![
841 ("fold", fold.into()),
842 ("count", count.into()),
843 ("bytes", bytes.into()),
844 ("parallel", parallel.into()),
845 ]),
846 )
847 }
848 pub fn deep_links(self, on: bool) -> Self {
851 self.set("deepLinks", on.into())
852 }
853 pub fn search(self, on: bool) -> Self {
856 self.set("search", on.into())
857 }
858 pub fn search_from(self, screens: u64) -> Self {
860 self.set("search", screens.into())
861 }
862 pub fn zoom(self, on: bool) -> Self {
864 self.set("zoom", on.into())
865 }
866 pub fn new_badges(self, on: bool) -> Self {
868 self.set("newBadges", on.into())
869 }
870 pub fn new_badges_days(self, days: u64) -> Self {
872 self.set("newBadges", days.into())
873 }
874 pub fn versions(self, on: bool) -> Self {
877 self.set("versions", on.into())
878 }
879 pub fn text(mut self, key: &str, value: &str) -> Self {
884 let text = self.raw.entry("text").or_insert_with(|| Value::Object(Map::new()));
885 if let Value::Object(m) = text {
886 m.insert(key.into(), value.into());
887 }
888 self
889 }
890
891 pub(crate) fn get(&self, key: &str, check: impl Fn(&Value) -> bool) -> Result<Option<&Value>, Error> {
893 match self.raw.get(key) {
894 None | Some(Value::Null) => Ok(None),
895 Some(v) if check(v) => Ok(Some(v)),
896 Some(_) => fail(format!("gallery option {key} is invalid")),
897 }
898 }
899}
900
901fn texts(keys: &'static [&'static str]) -> impl Fn(&Value) -> bool {
902 move |v| {
903 v.as_object().is_some_and(|m| {
904 m.values().all(|entry| {
905 entry.as_object().is_some_and(|e| {
906 e.iter().all(|(k, x)| keys.contains(&k.as_str()) && (x.is_null() || x.is_string()))
907 })
908 })
909 })
910 }
911}
912
913fn group_options(sizes: &[DimensionValue]) -> impl Fn(&Value) -> bool {
914 move |v| {
915 v.as_object().is_some_and(|m| {
916 m.values().all(|entry| {
917 entry.as_object().is_some_and(|e| {
918 e.iter().all(|(k, x)| match (k.as_str(), x) {
919 ("title" | "size" | "fit", Value::Null) => true,
920 ("title", Value::String(_)) => true,
921 ("size", Value::String(s)) => sizes.iter().any(|v| &v.key == s),
922 ("fit", Value::String(f)) => f == "cover" || f == "contain",
923 _ => false,
924 })
925 })
926 })
927 })
928 }
929}
930
931fn text_or_null(v: Option<&Value>) -> bool {
933 matches!(v, None | Some(Value::Null) | Some(Value::String(_)))
934}
935
936pub(crate) fn check_dimensions(list: &Value) -> bool {
938 let Some(list) = list.as_array() else { return false };
939 let mut keys: HashSet<&str> = HashSet::new();
940 let mut value_keys: HashSet<String> = HashSet::new();
941 let value_key = |k: Option<&Value>| -> Option<String> {
942 let k = k?.as_str()?;
943 (KEY.is_match(k) && !digits(k) && k != "2x" && !k.ends_with("-2x")).then(|| k.to_string())
945 };
946 for d in list {
947 let Some(m) = d.as_object() else { return false };
948 if !m.keys().all(|k| matches!(k.as_str(), "key" | "label" | "missing" | "values")) {
949 return false;
950 }
951 let Some(key) = m.get("key").and_then(Value::as_str).filter(|k| KEY.is_match(k) && !keys.contains(k)) else {
952 return false;
953 };
954 keys.insert(key);
955 let built_in = key == "theme" || key == "size";
956 if !text_or_null(m.get("label")) {
957 return false;
958 }
959 match m.get("missing") {
960 None | Some(Value::Null) => {}
961 Some(x) if x.as_str().and_then(Missing::parse).is_some() => {}
962 Some(_) => return false,
963 }
964 let values = match m.get("values") {
965 None | Some(Value::Null) => {
966 if !built_in {
967 return false;
968 }
969 continue;
970 }
971 Some(Value::Array(a)) if !a.is_empty() => a,
972 Some(_) => return false,
973 };
974 for v in values {
975 let Some(vm) = v.as_object() else { return false };
976 if !vm.keys().all(|k| matches!(k.as_str(), "key" | "label" | "below")) {
977 return false;
978 }
979 let Some(vk) = value_key(vm.get("key")).filter(|k| !value_keys.contains(k)) else { return false };
980 value_keys.insert(vk);
981 if !text_or_null(vm.get("label")) {
982 return false;
983 }
984 match vm.get("below") {
985 None | Some(Value::Null) => {}
986 Some(b) if key == "size" && size_of(Some(b)).is_some() => {}
987 Some(_) => return false,
988 }
989 }
990 if key == "size" && !values.iter().any(|v| matches!(v.get("below"), None | Some(Value::Null))) {
991 return false;
992 }
993 }
994 for d in default_dimensions() {
996 if list.iter().any(|x| {
997 x.get("key").and_then(Value::as_str) == Some(&d.key) && x.get("values").is_some_and(Value::is_array)
998 }) {
999 continue;
1000 }
1001 for v in d.values {
1002 if !value_keys.insert(v.key) {
1003 return false;
1004 }
1005 }
1006 }
1007 true
1008}
1009
1010pub(crate) fn resolve_dimensions(list: Option<&Value>) -> Vec<Dimension> {
1012 let given: &[Value] = list.and_then(Value::as_array).map_or(&[], Vec::as_slice);
1013 let resolve = |d: &Value, base: Option<&Dimension>| -> Dimension {
1014 let key = d["key"].as_str().unwrap().to_string();
1015 let label = d.get("label").and_then(Value::as_str).map(str::to_string);
1016 let missing = d.get("missing").and_then(Value::as_str).and_then(Missing::parse);
1017 let values = match d.get("values").and_then(Value::as_array) {
1018 Some(vs) => vs
1019 .iter()
1020 .map(|v| {
1021 let vk = v["key"].as_str().unwrap();
1022 DimensionValue {
1023 key: vk.into(),
1024 label: v.get("label").and_then(Value::as_str).unwrap_or(vk).into(),
1025 below: v.get("below").and_then(|b| size_of(Some(b))),
1026 shape: None,
1027 }
1028 })
1029 .collect(),
1030 None => base.unwrap().values.clone(),
1031 };
1032 Dimension {
1033 label: label.or_else(|| base.map(|b| b.label.clone())).unwrap_or_else(|| key.clone()),
1034 missing: missing.or(base.map(|b| b.missing)).unwrap_or(Missing::First),
1035 key,
1036 values,
1037 }
1038 };
1039 let defaults = default_dimensions();
1040 let mut out: Vec<Dimension> = defaults
1041 .iter()
1042 .map(|base| match given.iter().find(|x| x["key"].as_str() == Some(&base.key)) {
1043 Some(d) => resolve(d, Some(base)),
1044 None => base.clone(),
1045 })
1046 .collect();
1047 for d in given {
1048 if !defaults.iter().any(|base| d["key"].as_str() == Some(&base.key)) {
1049 out.push(resolve(d, None));
1050 }
1051 }
1052 out
1053}
1054
1055fn combinations(dimensions: &[Dimension], values_for: impl Fn(&Dimension) -> Vec<String>) -> Vec<Vec<String>> {
1057 let mut out: Vec<Vec<String>> = vec![Vec::new()];
1058 for d in dimensions {
1059 let vs = values_for(d);
1060 out = out
1061 .into_iter()
1062 .flat_map(|c| {
1063 vs.iter().map(move |k| {
1064 let mut c = c.clone();
1065 c.push(k.clone());
1066 c
1067 })
1068 })
1069 .collect();
1070 }
1071 out
1072}
1073
1074fn keys_of<'a>(dimensions: &[Dimension], values: &'a Values) -> Vec<&'a str> {
1076 dimensions.iter().map(|d| values[&d.key].as_str()).collect()
1077}
1078
1079fn values_of(dimensions: &[Dimension], variants: &[&Variant]) -> BTreeMap<String, Vec<String>> {
1081 dimensions
1082 .iter()
1083 .map(|d| {
1084 let keys = d
1085 .values
1086 .iter()
1087 .filter(|v| variants.iter().any(|x| x.values[&d.key] == v.key))
1088 .map(|v| v.key.clone())
1089 .collect();
1090 (d.key.clone(), keys)
1091 })
1092 .collect()
1093}
1094
1095fn with_shapes(mut dimensions: Vec<Dimension>, groups: &[Group]) -> Vec<Dimension> {
1097 let variants: Vec<&Variant> =
1098 groups.iter().flat_map(|g| g.screens.iter().flat_map(|sc| sc.variants.iter())).collect();
1099 for d in dimensions.iter_mut().filter(|d| d.key == "size") {
1100 for v in &mut d.values {
1101 let at: Vec<&&Variant> = variants.iter().filter(|x| x.values["size"] == v.key).collect();
1102 let tall = at.iter().filter(|x| x.height > x.width).count();
1103 v.shape = Some(if tall > at.len() - tall { Shape::Portrait } else { Shape::Landscape });
1104 }
1105 }
1106 dimensions
1107}
1108
1109fn strings(v: &Value) -> bool {
1110 v.as_array().is_some_and(|a| a.iter().all(Value::is_string))
1111}
1112
1113fn string_list(v: Option<&Value>) -> Option<Vec<String>> {
1114 v.map(|v| v.as_array().unwrap().iter().map(|s| s.as_str().unwrap().to_string()).collect())
1115}
1116
1117fn text_of<'a>(map: Option<&'a Value>, outer: &str, inner: &str) -> Option<&'a str> {
1118 map?.get(outer)?.get(inner)?.as_str()
1119}
1120
1121pub fn build_model(manifest: &Value, options: &Options) -> Result<Model, Error> {
1124 check_manifest(manifest)?;
1125 let level = options.get("headingLevel", |v| integral(v).is_some())?.and_then(integral).unwrap_or(2.0);
1126 let heading_level = level.clamp(1.0, 4.0) as u8;
1127 let title_opt = if options.raw.contains_key("title") {
1129 Some(options.get("title", Value::is_string)?.and_then(Value::as_str).map(str::to_string))
1130 } else {
1131 None
1132 };
1133 let id = options
1134 .get("id", |v| v.as_str().is_some_and(|s| ID.is_match(s)))?
1135 .and_then(Value::as_str)
1136 .unwrap_or("vg")
1137 .to_string();
1138 let dimensions = resolve_dimensions(options.get("dimensions", check_dimensions)?);
1139 let size_values = dimensions.iter().find(|d| d.key == "size").unwrap().values.clone();
1140 let screens_opt = options.get("screens", texts(&["title", "caption"]))?;
1141 let groups_opt = options.get("groups", group_options(&size_values))?;
1142 let order = string_list(options.get("order", strings)?);
1143 let group_order = string_list(options.get("groupOrder", strings)?);
1144 let credit = options.get("credit", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(false);
1145 let switch = options.get("themeSwitch", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(true);
1146 let layout = options
1147 .get("layout", |v| matches!(v.as_str(), Some("grid" | "strip")))?
1148 .and_then(Value::as_str)
1149 .unwrap_or("grid")
1150 .to_string();
1151 let see_all = options.get("seeAll", |v| {
1152 v.is_object()
1153 && v.get("href").and_then(Value::as_str).is_some_and(safe_href)
1154 && matches!(v.get("text"), None | Some(Value::Null) | Some(Value::String(_)))
1155 })?;
1156 let preload = preload_model(options.get("preload", preload_valid)?);
1157 let deep_links = options.get("deepLinks", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(false);
1158 let text_opt = options.get("text", |v| {
1159 v.as_object().is_some_and(|m| {
1160 m.iter().all(|(k, x)| TEXT_DEFAULTS.iter().any(|(d, _)| d == k) && (x.is_null() || x.is_string()))
1161 })
1162 })?;
1163 let text = Text::with(|k| text_opt.and_then(|t| t.get(k)).and_then(Value::as_str).map(str::to_string));
1164 let title = title_opt.unwrap_or_else(|| Some(text.label.clone()));
1165 let search_opt = options.get("search", |v| v.is_boolean() || whole_in(v, 0, MAX_SIZE).is_some())?;
1166 let zoom = options.get("zoom", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(true);
1167 let new_badges = match options.get("newBadges", |v| v.is_boolean() || whole_in(v, 1, 3650).is_some())? {
1168 None | Some(Value::Bool(false)) => None,
1169 Some(Value::Bool(true)) => Some(NEW_DAYS),
1170 Some(v) => integral(v).map(|n| n as u64),
1171 };
1172 let versions_on = options.get("versions", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(false);
1173 let rank_of = |v: &Variant| -> Vec<usize> {
1174 dimensions.iter().map(|d| d.values.iter().position(|x| x.key == v.values[&d.key]).unwrap()).collect()
1175 };
1176
1177 let mut slugs = HashSet::new();
1178 let mut groups: Vec<Group> = Vec::new();
1179 for g in manifest["groups"].as_array().unwrap() {
1180 let gname = g["name"].as_str().unwrap();
1181 let size_opt = text_of(groups_opt, gname, "size");
1182 let items = g["items"].as_array().unwrap();
1183 let shots: Vec<Shot> = items
1184 .iter()
1185 .map(|item| {
1186 let (w, h) = (size_of(item.get("width")).unwrap(), size_of(item.get("height")).unwrap());
1187 let mut shot = parse_shot(item["name"].as_str().unwrap(), &dimensions);
1188 let size = size_of_shot(&shot, &size_values, w, h, size_opt);
1189 shot.values.insert("size".into(), size);
1190 shot
1191 })
1192 .collect();
1193 let named: HashMap<&str, Vec<String>> = dimensions
1195 .iter()
1196 .map(|d| {
1197 let keys: Vec<String> = d
1198 .values
1199 .iter()
1200 .filter(|v| shots.iter().any(|s| s.values.get(&d.key) == Some(&v.key)))
1201 .map(|v| v.key.clone())
1202 .collect();
1203 (d.key.as_str(), if keys.is_empty() { vec![d.values[0].key.clone()] } else { keys })
1204 })
1205 .collect();
1206 let mut screens: Vec<(String, Vec<(String, Variant)>)> = Vec::new();
1208 let mut sinces: HashMap<String, String> = HashMap::new();
1209 let mut changes: HashMap<String, Option<String>> = HashMap::new();
1211 for (item, shot) in items.iter().zip(&shots) {
1212 let since = item.get("since").and_then(Value::as_str).filter(|s| !s.is_empty());
1214 let snapshot =
1215 item.get("snapshot").and_then(Value::as_str).filter(|s| ABSOLUTE.is_match(s)).map(str::to_string);
1216 if let Some(since) = since {
1217 match sinces.get(&shot.key) {
1218 Some(was) if since < was.as_str() => {}
1219 Some(was) if since == was.as_str() => {
1220 if changes.get(&shot.key).is_none_or(Option::is_none) {
1221 changes.insert(shot.key.clone(), snapshot);
1222 }
1223 }
1224 _ => {
1225 sinces.insert(shot.key.clone(), since.into());
1226 changes.insert(shot.key.clone(), snapshot);
1227 }
1228 }
1229 }
1230 let (w, h) = (size_of(item.get("width")).unwrap(), size_of(item.get("height")).unwrap());
1231 let url = item["url"].as_str().unwrap();
1232 let at = match screens.iter().position(|(k, _)| *k == shot.key) {
1233 Some(i) => i,
1234 None => {
1235 screens.push((shot.key.clone(), Vec::new()));
1236 screens.len() - 1
1237 }
1238 };
1239 let variants = &mut screens[at].1;
1240 let combos = combinations(&dimensions, |d| match shot.values.get(&d.key) {
1241 Some(v) => vec![v.clone()],
1242 None => named[d.key.as_str()].clone(),
1243 });
1244 for combo in combos {
1245 let vid = combo.join(".");
1246 let i = match variants.iter().position(|(id, _)| *id == vid) {
1247 Some(i) => i,
1248 None => {
1249 let values = dimensions.iter().map(|d| d.key.clone()).zip(combo).collect();
1250 variants.push((
1251 vid,
1252 Variant {
1253 values,
1254 url: String::new(),
1255 url2x: None,
1256 width: 0,
1257 height: 0,
1258 bytes: None,
1259 bytes2x: None,
1260 thumb: None,
1261 },
1262 ));
1263 variants.len() - 1
1264 }
1265 };
1266 let v = &mut variants[i].1;
1267 if shot.x2 {
1268 if v.url2x.is_none() {
1269 v.url2x = Some(url.into());
1270 v.bytes2x = bytes_of(item.get("bytes")).unwrap();
1271 }
1272 } else if v.url.is_empty() {
1273 match shot.css_width {
1276 Some(cw) if w > cw => {
1277 let height = (2 * h as u128 * cw as u128 + w as u128) / (2 * w as u128);
1278 (v.url, v.width, v.height) = (url.into(), cw, height as u64);
1279 }
1280 _ => (v.url, v.width, v.height) = (url.into(), w, h),
1281 }
1282 v.bytes = bytes_of(item.get("bytes")).unwrap();
1283 v.thumb = thumb_of(item.get("thumb")).unwrap();
1284 }
1285 }
1286 }
1287 let kept: Vec<(String, Vec<Variant>)> = screens
1289 .into_iter()
1290 .filter_map(|(key, variants)| {
1291 let mut variants: Vec<Variant> =
1292 variants.into_iter().map(|(_, v)| v).filter(|v| !v.url.is_empty()).collect();
1293 variants.sort_by_key(|v| rank_of(v));
1294 (!variants.is_empty()).then_some((key, variants))
1295 })
1296 .collect();
1297 if kept.is_empty() {
1298 continue;
1299 }
1300 let values = values_of(&dimensions, &kept.iter().flat_map(|(_, vs)| vs.iter()).collect::<Vec<_>>());
1301 for (key, variants) in &kept {
1304 let own = values_of(&dimensions, &variants.iter().collect::<Vec<_>>());
1305 let have: HashSet<String> = variants.iter().map(|v| keys_of(&dimensions, &v.values).join(".")).collect();
1306 let wanted = combinations(&dimensions, |d| {
1307 if d.missing == Missing::Error { values[&d.key].clone() } else { own[&d.key].clone() }
1308 });
1309 for combo in wanted {
1310 if !have.contains(&combo.join(".")) {
1311 return fail(format!(
1312 "gallery screen {key} in group {gname} has no {} screenshot",
1313 combo.join(" ")
1314 ));
1315 }
1316 }
1317 }
1318 let prefix = common_folder(&kept.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>());
1319 let mut list: Vec<Screen> = kept
1320 .into_iter()
1321 .map(|(key, variants)| {
1322 let set = screens_opt.and_then(|m| m.get(&key));
1323 let title =
1324 set.and_then(|s| s.get("title")).and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| {
1325 let parts: Vec<&str> = key.split('/').skip(prefix).collect();
1326 humanize(&parts)
1327 });
1328 let caption = set.and_then(|s| s.get("caption")).and_then(Value::as_str).map(str::to_string);
1329 let since = sinces.get(&key).cloned();
1330 let change = changes.get(&key).cloned().flatten();
1331 Screen { key, title, caption, since, change, variants }
1332 })
1333 .collect();
1334 list.sort_by(|a, b| rank(&order, &a.key).cmp(&rank(&order, &b.key)).then_with(|| a.key.cmp(&b.key)));
1336
1337 let base = slugify(gname);
1338 let mut slug = base.clone();
1339 let mut n = 2;
1340 while slugs.contains(&slug) {
1341 slug = format!("{base}-{n}");
1342 n += 1;
1343 }
1344 slugs.insert(slug.clone());
1345 let title = text_of(groups_opt, gname, "title")
1346 .or_else(|| g.get("title").and_then(Value::as_str))
1347 .unwrap_or(gname)
1348 .to_string();
1349 let fit = text_of(groups_opt, gname, "fit").unwrap_or("cover").to_string();
1350 groups.push(Group { name: gname.into(), title, slug, fit, values, screens: list });
1351 }
1352 if groups.is_empty() {
1353 return fail("the gallery manifest has no screenshots to show");
1354 }
1355 groups.sort_by_key(|g| rank(&group_order, &g.name));
1357 let screen_count = groups.iter().map(|g| g.screens.len() as u64).sum::<u64>();
1358 let search = layout == "grid"
1359 && match search_opt {
1360 None => screen_count >= SEARCH_FROM,
1361 Some(Value::Bool(on)) => *on,
1362 Some(v) => integral(v).is_some_and(|n| screen_count as f64 >= n),
1363 };
1364
1365 Ok(Model {
1366 see_all: see_all.map(|v| SeeAll {
1367 href: v["href"].as_str().unwrap().into(),
1368 text: v.get("text").and_then(Value::as_str).unwrap_or(SEE_ALL_TEXT).into(),
1369 }),
1370 label: title.clone().unwrap_or_else(|| text.label.clone()),
1371 title,
1372 heading_level,
1373 id,
1374 credit,
1375 preload,
1376 deep_links,
1377 text,
1378 search,
1379 zoom,
1380 new_badges,
1381 versions: if versions_on && layout == "grid" { versions_of(manifest, options) } else { None },
1382 theme_switch: layout == "grid" && switch,
1383 layout,
1384 dimensions: with_shapes(dimensions, &groups),
1385 groups,
1386 })
1387}
1388
1389fn versions_of(manifest: &Value, options: &Options) -> Option<Versions> {
1392 let list: Vec<Version> = manifest
1393 .get("versions")
1394 .and_then(Value::as_array)?
1395 .iter()
1396 .map(|v| Version {
1397 key: v["key"].as_str().unwrap().into(),
1398 label: v["label"].as_str().unwrap().into(),
1399 manifest: v["manifest"].as_str().unwrap().into(),
1400 })
1401 .collect();
1402 let first = list.first()?;
1403 let latest = format!("{}.json", &first.manifest[..first.manifest.len() - format!("@{}.json", first.key).len()]);
1404 let key = manifest.get("version").and_then(|v| v.get("key")).and_then(Value::as_str);
1405 let current = key.filter(|k| list.iter().any(|v| v.key == *k)).unwrap_or("latest").to_string();
1406 Some(Versions { current, latest, options: options_json(options), list })
1407}
1408
1409#[cfg(test)]
1410mod tests {
1411 use super::*;
1412 use serde_json::json;
1413
1414 fn shot(key: &str, values: &[(&str, &str)], x2: bool, css_width: Option<u64>) -> Shot {
1415 let values = values.iter().map(|(d, v)| (d.to_string(), v.to_string())).collect();
1416 Shot { key: key.into(), values, x2, css_width }
1417 }
1418
1419 #[test]
1420 fn parses_shot_names() {
1421 let dims = default_dimensions();
1422 let cases = [
1423 ("overview-dark-1440", shot("overview", &[("theme", "dark")], false, Some(1440))),
1424 ("ios/usage-light.png", shot("ios/usage", &[("theme", "light")], false, None)),
1425 ("shots/app/billing/1440-dark-2x", shot("shots/app/billing", &[("theme", "dark")], true, Some(1440))),
1426 ("dark-mode-light", shot("dark-mode", &[("theme", "light")], false, None)),
1427 ("home-1440-light", shot("home", &[("theme", "light")], false, Some(1440))),
1429 ("home-phone-dark", shot("home", &[("theme", "dark"), ("size", "phone")], false, None)),
1430 ("shots/home/phone-light", shot("shots/home", &[("theme", "light"), ("size", "phone")], false, None)),
1431 ("issues/1440", shot("issues", &[], false, Some(1440))),
1433 ("issues/390-2x", shot("issues", &[], true, Some(390))),
1434 ("overview-1440", shot("overview-1440", &[], false, None)),
1436 ("light", shot("light", &[], false, None)),
1437 ("1440-dark", shot("1440-dark", &[], false, None)),
1438 ("a-1440-2x", shot("a-1440-2x", &[], false, None)),
1439 (
1440 "x/\u{661}\u{664}\u{664}\u{660}-light",
1441 shot("x/\u{661}\u{664}\u{664}\u{660}", &[("theme", "light")], false, None),
1442 ),
1443 ("a-light-1440\n", shot("a-light-1440\n", &[], false, None)),
1444 ];
1445 for (name, want) in cases {
1446 assert_eq!(parse_shot(name, &dims), want, "{name}");
1447 }
1448 }
1449
1450 #[test]
1451 fn peels_the_longest_value_key_a_dimension_at_most_once() {
1452 let manifest =
1453 json!({"groups": [{"name": "G", "items": [{"name": "a", "url": "https://x/a", "width": 1, "height": 1}]}]});
1454 let options = Options::from_json(&json!({"dimensions": [
1455 {"key": "theme", "values": [{"key": "light"}, {"key": "dark"}, {"key": "high-contrast"}]},
1456 {"key": "lang", "values": [{"key": "en"}, {"key": "fr"}]}
1457 ]}))
1458 .unwrap();
1459 let dims = build_model(&manifest, &options).unwrap().dimensions;
1460 assert_eq!(
1461 parse_shot("pricing-high-contrast-fr", &dims),
1462 shot("pricing", &[("theme", "high-contrast"), ("lang", "fr")], false, None)
1463 );
1464 assert_eq!(parse_shot("dark-light", &dims), shot("dark", &[("theme", "light")], false, None));
1465 }
1466
1467 #[test]
1468 fn resolves_dimensions() {
1469 let manifest =
1470 json!({"groups": [{"name": "G", "items": [{"name": "a", "url": "https://x/a", "width": 1, "height": 1}]}]});
1471 let options = Options::default().dimension("size", Some("Device"), None, &[]).dimension(
1472 "plan",
1473 None,
1474 None,
1475 &[("free", None, None), ("pro", Some("Pro"), None)],
1476 );
1477 let dims = build_model(&manifest, &options).unwrap().dimensions;
1478 let keys: Vec<&str> = dims.iter().map(|d| d.key.as_str()).collect();
1479 assert_eq!(keys, ["theme", "size", "plan"]);
1480 assert_eq!((dims[1].label.as_str(), dims[1].missing, dims[1].values.len()), ("Device", Missing::Hide, 2));
1481 assert_eq!((dims[2].label.as_str(), dims[2].missing), ("plan", Missing::First));
1482 assert_eq!((dims[2].values[0].label.as_str(), dims[2].values[1].label.as_str()), ("free", "Pro"));
1483 }
1484}