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;
pub const TEXT_DEFAULTS: [(&str, &str); 13] = [
("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"),
];
pub const SEE_ALL_TEXT: &str = "See all screenshots";
pub const SEARCH_FROM: u64 = 40;
pub const NEW_DAYS: u64 = 30;
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());
pub type Values = BTreeMap<String, String>;
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Variant {
pub values: Values,
pub url: String,
pub url2x: Option<String>,
pub width: u64,
pub height: u64,
pub bytes: Option<u64>,
pub bytes2x: Option<u64>,
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>,
}
#[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 {
fn default() -> Self {
PreloadCaps { fold: 250, count: 500, bytes: 50_000_000, parallel: 4 }
}
}
#[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, 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,
}
}
}
#[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>,
pub shape: Option<Shape>,
}
#[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 }
}
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>,
pub since: Option<String>,
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,
pub values: BTreeMap<String, Vec<String>>,
pub screens: Vec<Screen>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SeeAll {
pub href: String,
pub text: String,
}
#[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,
}
impl Text {
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"),
}
}
}
impl Default for Text {
fn default() -> Self {
Text::with(|_| None)
}
}
#[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,
pub preload: Option<Preload>,
pub deep_links: bool,
pub text: Text,
pub search: bool,
pub zoom: bool,
pub new_badges: Option<u64>,
pub dimensions: Vec<Dimension>,
pub groups: Vec<Group>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Shot {
pub key: String,
pub values: Values,
pub x2: bool,
pub css_width: Option<u64>,
}
fn digits(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}
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))
{
css_width = Some(t.parse::<u64>().unwrap_or(u64::MAX));
tokens.pop();
continue;
}
break;
}
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 }
}
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() }
}
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,
}
}
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()))
}
fn integral(v: &Value) -> Option<f64> {
let n = v.as_f64()?;
(n.is_finite() && n.fract() == 0.0).then_some(n)
}
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)
}
const MAX_CAP: u64 = 1_000_000_000_000;
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)
}
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(()),
}
}
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"))? }))
}
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),
}))
}
}
}
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"));
}
}
}
Ok(())
}
#[derive(Debug, Clone, Default)]
pub struct Options {
pub(crate) raw: Map<String, Value>,
}
impl Options {
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
}
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())
}
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())
}
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 dimension(
mut self,
key: &str,
label: Option<&str>,
missing: Option<&str>,
values: &[(&str, Option<&str>, Option<u64>)],
) -> Self {
let mut entry = serde_json::json!({ "key": key, "label": label, "missing": missing });
if !values.is_empty() {
entry["values"] = values
.iter()
.map(|(k, label, below)| serde_json::json!({ "key": k, "label": label, "below": below }))
.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())
}
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 }))
}
pub fn preload(self, on: bool) -> Self {
self.set("preload", on.into())
}
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 }))
}
pub fn deep_links(self, on: bool) -> Self {
self.set("deepLinks", on.into())
}
pub fn search(self, on: bool) -> Self {
self.set("search", on.into())
}
pub fn search_from(self, screens: u64) -> Self {
self.set("search", screens.into())
}
pub fn zoom(self, on: bool) -> Self {
self.set("zoom", on.into())
}
pub fn new_badges(self, on: bool) -> Self {
self.set("newBadges", on.into())
}
pub fn new_badges_days(self, days: u64) -> Self {
self.set("newBadges", days.into())
}
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
}
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,
})
})
})
})
}
}
fn text_or_null(v: Option<&Value>) -> bool {
matches!(v, None | Some(Value::Null) | Some(Value::String(_)))
}
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()?;
(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;
}
}
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
}
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
}
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
}
fn keys_of<'a>(dimensions: &[Dimension], values: &'a Values) -> Vec<&'a str> {
dimensions.iter().map(|d| values[&d.key].as_str()).collect()
}
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()
}
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()
}
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_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 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();
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();
let mut screens: Vec<(String, Vec<(String, Variant)>)> = Vec::new();
let mut sinces: HashMap<String, String> = HashMap::new();
let mut changes: HashMap<String, Option<String>> = HashMap::new();
for (item, shot) in items.iter().zip(&shots) {
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() {
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();
}
}
}
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<_>>());
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();
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");
}
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 {
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(|| text.label.clone()),
title,
heading_level,
id,
credit,
preload,
deep_links,
text,
search,
zoom,
new_badges,
dimensions: with_shapes(dimensions, &groups),
groups,
})
}
#[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)),
("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)),
("issues/1440", shot("issues", &[], false, Some(1440))),
("issues/390-2x", shot("issues", &[], true, Some(390))),
("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"));
}
}