~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
1196 lines · 53.5 KB Raw History
//! Pictures and sound, as the web renderer's GalleryNode, CoversNode,
//! ContentWarningNode and PlayerNode read them: a gallery's pictures, cover
//! cards that open what they stand for, a warning over what its author
//! labelled, and a player's tracks.
//!
//! - `Gallery`: `p: { page? }`, `items: [{ src, full, alt, ratio, info? }]`;
//!   `src` the picture drawn small, `full` its full size to open (a page),
//!   `ratio` its width over its height, null when its record gives none,
//!   `info` its lines of words (`[{ text }]`, its camera), where it has any.
//! - `Covers`: `p: { page?, style?, select? }`, `items: [{ open?, src,
//!   title, count, stat, date, labels, pick? }]`; `count` written out ("16
//!   photos"), `stat` `{ value, icon? }`, `date` the timestamp as given,
//!   `labels` the self-labels that hide its picture until shown; `select`
//!   `{ label, action, one, many, confirm?, tone?, method, service }` where
//!   some may be picked, and each such item's `pick` the input its call
//!   takes.
//! - `ContentWarning`: `p: { labels, key? }` over its children (`k`); with
//!   no labels, its children as they are; `key` what it hides, for a reveal
//!   kept as it is drawn again.
//! - `Player`: `p: { page? }`, `items: [{ src, title, subtitle,
//!   subtitleOpen?, duration, art }]`; `src` the audio, null where nothing
//!   may play ("not playable"), `duration` in seconds.
//!
//! `page` as a `List`'s (`paged`): items that are a page's, which a page
//! more grows.

use super::*;

/// A component's `items`: nothing there is Missing, something not an array an error.
fn items<'a>(p: &'a Value, scope: &'a Value) -> R<&'a Vec<Value>> {
    match value(&p["items"], scope, Value::is_array)? {
        Some(Value::Array(a)) => Ok(a),
        _ if value(&p["items"], scope, present)?.is_some() => bad("items: no array"),
        _ => Err(Fail::Missing),
    }
}

/// `{c, p: {page?}, items}`: `page` when its items are a page's (`paged`).
fn listing(c: &str, p: &Value, scope: &Value, ctx: &Ctx, drawn: Vec<Value>) -> Value {
    let mut o = Map::new();
    if paged(p, scope, ctx) {
        o.insert("page".into(), true.into());
    }
    let mut out = make(c, o, vec![]);
    out["items"] = Value::Array(drawn);
    out
}

/// A picture as these components draw one: a blob small (its `thumb`), a
/// URL on the origins as it is (no view's thumbnails, as today's).
fn picture(found: Option<&Value>, ctx: &Ctx) -> Value {
    source_of(found, ctx, found.is_some_and(Value::is_object))
}

fn picture_at(prop: &Value, item: &Value, ctx: &Ctx) -> R<Value> {
    let found = value(prop, item, |v| url_of(v, ctx).is_some())?;
    Ok(picture(found, ctx))
}

/// Self-labels: an array of values or of `{ val }`s, or a selfLabels
/// object (`{ values: [{ val }] }`); none where there is none.
fn labels(prop: &Value, scope: &Value) -> R<Vec<String>> {
    let list = match value(prop, scope, present)? {
        Some(v) if v.is_object() => v["values"].as_array(),
        Some(Value::Array(a)) => Some(a),
        _ => None,
    };
    Ok(list
        .into_iter()
        .flatten()
        .filter_map(|l| l.as_str().or_else(|| l["val"].as_str()))
        .map(str::to_string)
        .collect())
}

/// A number as JavaScript writes it: a whole one without a fraction.
fn number(n: f64) -> String {
    if n.fract() == 0.0 && n.abs() < 1e15 {
        format!("{}", n as i64)
    } else {
        n.to_string()
    }
}

pub(super) fn gallery(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
    let wide = matches!(p["style"].as_str(), Some("stack" | "carousel"));
    let mut drawn = Vec::new();
    for item in items(p, scope)? {
        let found = value(&p["src"], item, |v| url_of(v, ctx).is_some())?;
        let full = found.and_then(|f| url_of(f, ctx)).filter(|u| http_url(u));
        let ratio = value(&p["aspectRatio"], item, |v| ratio_of(v).is_some())?.and_then(ratio_of);
        let mut photo = json!({
            "src": picture(found, ctx),
            "full": full,
            "alt": text_of(&p["alt"], item)?,
            "ratio": ratio,
        });
        let info = info(&p["info"], item)?;
        if !info.is_empty() {
            photo["info"] = Value::Array(info);
        }
        if let Some(set) = wide.then(|| srcset(&p["srcset"], item, ctx)).flatten() {
            photo["srcset"] = set.into();
        }
        drawn.push(photo);
    }
    let mut out = listing("Gallery", p, scope, ctx, drawn);
    if let Some(style @ ("stack" | "carousel")) = p["style"].as_str() {
        out["p"]["style"] = style.into();
    }
    for flag in ["bleed", "showAlt", "zoom"] {
        if p[flag] == true {
            out["p"][flag] = true.into();
        }
    }
    // The Action a double-tap on a photo runs, by its label (a gallery's ♡).
    if let Some(like) = p["like"].as_str() {
        out["p"]["like"] = like.into();
    }
    Ok(Some(out))
}

/// A photo's sizes (`srcset`) read from its item, as an `<img>`'s srcset
/// says them: `url 1000w, url 2000w`, narrowest first, each a URL the view
/// may load (`url_of`) with nothing in it that would break the list (a
/// comma, a space); none where none reads so.
fn srcset(sizes: &Value, item: &Value, ctx: &Ctx) -> Option<String> {
    let sizes = sizes.as_array()?;
    let mut read: Vec<(u64, String)> = sizes
        .iter()
        .filter_map(|s| {
            let found = value(&s["src"], item, |v| url_of(v, ctx).is_some()).ok()??;
            let url = url_of(found, ctx).filter(|u| !u.contains([',', ' ']))?;
            Some((s["width"].as_u64()?, url))
        })
        .collect();
    read.sort();
    let set: Vec<String> = read.iter().map(|(w, url)| format!("{url} {w}w")).collect();
    (!set.is_empty()).then(|| set.join(", "))
}

/// A gallery's `info` read from one photo's item: each line its parts'
/// words (prefixed and suffixed) joined, those reading nothing left out,
/// and one marked `omitRepeated` where the next part read starts with its
/// first word (a camera's make before a model that names it); a line of
/// none dropped.
fn info(lines: &Value, item: &Value) -> R<Vec<Value>> {
    let first = |s: &str| s.split_whitespace().next().unwrap_or("").to_lowercase();
    let mut out = Vec::new();
    for line in lines.as_array().into_iter().flatten() {
        let mut read = Vec::new();
        for part in line["parts"].as_array().into_iter().flatten() {
            if let Some(text) = text_of(&part["value"], item)?.filter(|t| !t.is_empty()) {
                read.push((part, text));
            }
        }
        let words: Vec<String> = read
            .iter()
            .enumerate()
            .filter(|(i, (part, text))| {
                part["omitRepeated"] != true
                    || read
                        .get(i + 1)
                        .is_none_or(|(_, next)| first(next) != first(text))
            })
            .map(|(_, (part, text))| {
                let (prefix, suffix) = (str_at(part, "prefix"), str_at(part, "suffix"));
                format!("{}{text}{}", prefix.unwrap_or(""), suffix.unwrap_or(""))
            })
            .collect();
        if !words.is_empty() {
            out.push(json!({ "text": words.join(str_at(line, "join").unwrap_or(" ")) }));
        }
    }
    Ok(out)
}

/// `Slides`: each picture full size, and the sizes it comes in (`srcset`)
/// where the view names them, its alt text, shape, when it was
/// posted and where, and the screen it is (`href`, as an Image's: a
/// story's record), which an app's address follows as it shows; with
/// `call`, in a trusted view, the procedure each one calls once it is
/// shown (a story marked watched), its input read from it. Its children
/// over each picture, the picture's item their scope (a ⋯ for it); with
/// none, its `empty` words and its children drawn with the view's scope (a
/// way to add one). With `reverse`, its items are drawn last first: an
/// archive answered newest first plays oldest first, as stories do.
pub(super) fn slides(n: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
    let p = &n["props"];
    let mut drawn = Vec::new();
    // Begun at the item the query was asked to show first (`at`), found at
    // `start` in each.
    let start = p["start"].as_str().and_then(Path::parse);
    let first = ctx.root["at"].as_str();
    let mut begin = None;
    let mut all: Vec<&Value> = items(p, scope)?.iter().collect();
    if p["reverse"] == true {
        all.reverse();
    }
    for item in all {
        if begin.is_none()
            && let (Some(path), Some(first)) = (&start, first)
            && path.get(item).and_then(Value::as_str) == Some(first)
        {
            begin = Some(drawn.len());
        }
        let found = value(&p["src"], item, |v| url_of(v, ctx).is_some())?;
        let ratio = value(&p["aspectRatio"], item, |v| ratio_of(v).is_some())?.and_then(ratio_of);
        let mut slide = json!({
            "src": source_of(found, ctx, false),
            "alt": text_of(&p["alt"], item)?.unwrap_or_default(),
            "ratio": ratio,
        });
        for key in ["time", "place"] {
            if let Some(words) = text_of(&p[key], item)? {
                slide[key] = words.into();
            }
        }
        if let Some(set) = srcset(&p["srcset"], item, ctx) {
            slide["srcset"] = set.into();
        }
        // The screen it is: never opened by a tap, its address the app's
        // while it shows.
        let href = value(&p["href"], item, Value::is_string)?.and_then(Value::as_str);
        if let Some(open) = href.and_then(|h| follow(h, ctx)) {
            slide["open"] = open;
        }
        if p["call"].is_object() {
            match procedure(&p["call"], item, ctx) {
                Ok(call) => slide["call"] = call,
                Err(Fail::Missing) => {}
                Err(fail) => return Err(fail),
            }
        }
        let k = super::children(n, item, ctx);
        if !k.is_empty() {
            slide["k"] = Value::Array(k);
        }
        drawn.push(slide);
    }
    let none = drawn.is_empty();
    let mut out = listing("Slides", p, scope, ctx, drawn);
    if none {
        if let Some(words) = p["empty"].as_str() {
            out["p"]["empty"] = words.into();
        }
        let k = super::children(n, scope, ctx);
        if !k.is_empty() {
            out["k"] = Value::Array(k);
        }
    }
    if let Some(s) = p["seconds"].as_u64() {
        out["p"]["seconds"] = s.into();
    }
    if let Some(at) = begin.filter(|&at| at > 0) {
        out["p"]["start"] = at.into();
    }
    // The Action a double-tap on a picture runs, by its label (a story's ♡).
    if let Some(like) = p["like"].as_str() {
        out["p"]["like"] = like.into();
    }
    // Whose they are, over their top.
    let face = source(&p["face"], scope, ctx, true)?;
    if !face.is_null() {
        out["p"]["face"] = face;
    }
    if let Some(name) = text_of(&p["name"], scope)? {
        out["p"]["name"] = name.into();
    }
    Ok(Some(out))
}

/// The most faces a pile lists, every one it may show expanded.
const PILE: usize = 100;

/// `Faces`: the first three items' pictures, each of the first two with
/// its name, how many there are, its words (`countNoun` as `{ one, many
/// }`), and what a click opens (read from the view's scope). A pile
/// (`style: "pile"`): every item's picture and name (up to `PILE`), how
/// many it draws (`max`, 5 by default) and whether it lists them all
/// (`expand`). Each face with its handle and what it opens (`href`), where
/// the item has them. No items, nothing.
pub(super) fn faces(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
    let all = items(p, scope)?;
    if all.is_empty() {
        return Err(Fail::Missing);
    }
    let pile = p["style"] == "pile";
    let mut faces = Vec::new();
    for (i, item) in all.iter().take(if pile { PILE } else { 3 }).enumerate() {
        let mut face = json!({ "src": picture_at(&p["src"], item, ctx)? });
        if let Some(name) = text_of(&p["name"], item)?.filter(|_| pile || i < 2) {
            face["name"] = name.into();
        }
        if let Some(handle) = text_of(&p["handle"], item)? {
            face["handle"] = handle.into();
        }
        let href = value(&p["href"], item, Value::is_string)?.and_then(Value::as_str);
        if let Some(open) = href.and_then(|h| follow(h, ctx)) {
            face["open"] = open;
        }
        faces.push(face);
    }
    let mut o = Map::new();
    o.insert("faces".into(), Value::Array(faces));
    o.insert("count".into(), all.len().into());
    if let Some(lead) = p["lead"].as_str() {
        o.insert("lead".into(), lead.into());
    }
    if let [one, many] = p["countNoun"].as_array().map_or(&[][..], Vec::as_slice) {
        o.insert("countNoun".into(), json!({ "one": one, "many": many }));
    }
    if let Some(open) = opens(&p["open"], scope, ctx, None)? {
        o.insert("open".into(), open);
    }
    if pile {
        o.insert("style".into(), "pile".into());
        o.insert("max".into(), p["max"].as_u64().unwrap_or(5).into());
        if p["expand"] == true {
            o.insert("expand".into(), true.into());
        }
    }
    Ok(Some(make("Faces", o, vec![])))
}

pub(super) fn covers(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
    let noun = p["countNoun"]
        .as_array()
        .filter(|a| a.len() == 2)
        .and_then(|a| Some((a[0].as_str()?, a[1].as_str()?)));
    let fallback = json!({ "$": "uri" });
    let mut drawn = Vec::new();
    let select = selecting(p, scope, ctx)?;
    let call = select.map(select_call);
    // Its `where` and `limit`, as a List's.
    let (w, limit) = (p["where"].as_object(), p["limit"].as_u64());
    for item in items(p, scope)? {
        if limit.is_some_and(|l| drawn.len() as u64 == l) {
            break;
        }
        if let Some(w) = w
            && !matches(item, w, scope)?
        {
            continue;
        }
        // A number, or an array counted (a gallery's photos).
        let n =
            value(&p["count"], item, |v| v.is_number() || v.is_array())?.and_then(|v| match v {
                Value::Array(a) => Some(a.len() as f64),
                v => v.as_f64(),
            });
        let count = n.map(|n| match noun {
            Some((one, many)) => format!("{} {}", number(n), if n == 1.0 { one } else { many }),
            None => number(n),
        });
        let stat = value(&p["stat"], item, Value::is_number)?.map(|n| {
            let mut s = json!({ "value": n });
            if let Some(icon) = p["statIcon"].as_str() {
                s["icon"] = icon.into();
            }
            s
        });
        let mut o = json!({
            "src": picture_at(&p["src"], item, ctx)?,
            "title": text_of(&p["title"], item)?,
            "count": count,
            "stat": stat,
            "date": text_of(&p["date"], item)?,
            "labels": labels(&p["labels"], item)?,
        });
        // More than one picture, marked so on a tile, which has no words.
        if n.is_some_and(|n| n > 1.0) {
            o["many"] = true.into();
        }
        if let Some(set) = srcset(&p["srcset"], item, ctx) {
            o["srcset"] = set.into();
        }
        if let Some(open) = opens(&p["open"], item, ctx, Some(&fallback))? {
            o["open"] = open;
        }
        if let Some(call) = &call
            && let Some(input) = pick(call, item, ctx)?
        {
            o["pick"] = input;
        }
        drawn.push(o);
    }
    let picked = drawn.iter().any(|o| o.get("pick").is_some());
    let mut out = listing("Covers", p, scope, ctx, drawn);
    if p["style"].as_str() == Some("tiles") {
        out["p"]["style"] = "tiles".into();
    }
    let mut grid = Map::new();
    grid_words(p, &mut grid);
    for (k, v) in grid {
        out["p"][k] = v;
    }
    if let Some(next) = own_next(p, scope, ctx) {
        out["p"]["next"] = next;
    }
    if let (Some(s), Some(call)) = (select.filter(|_| picked), &call) {
        let mut words = json!({
            "label": s.get("label").and_then(Value::as_str).unwrap_or("Select"),
            "action": s["action"], "one": s["noun"][0], "many": s["noun"][1],
            "method": call["method"], "service": call["service"],
        });
        for k in ["confirm", "tone"] {
            if let Some(v) = s.get(k) {
                words[k] = v.clone();
            }
        }
        out["p"]["select"] = words;
    }
    Ok(Some(out))
}

/// Covers' `select`, where it is offered: a trusted view's, where the
/// scope holds the signed-in person's DID at its `mine` (signed out,
/// never).
fn selecting<'a>(p: &'a Value, scope: &Value, ctx: &Ctx) -> R<Option<&'a Map<String, Value>>> {
    let Some(s) = p["select"].as_object().filter(|_| ctx.trusted) else {
        return Ok(None);
    };
    let Some(at) = s.get("mine").and_then(Value::as_str) else {
        return Ok(Some(s));
    };
    let path =
        Path::parse(at).ok_or_else(|| Fail::Bad("select.mine: a path in the scope".into()))?;
    let mine = ctx
        .me
        .is_some_and(|me| path.get(scope).and_then(Value::as_str) == Some(me));
    Ok(mine.then_some(s))
}

/// The call a select makes for each item picked: its `call`, or its
/// `deletes` as one (`call_of`).
fn select_call(s: &Map<String, Value>) -> std::borrow::Cow<'_, Value> {
    let at = |k| s.get(k).unwrap_or(&Value::Null);
    call_of(at("call"), at("deletes"))
}

/// The input a picked item's `call` takes, read from the item; none where
/// the item has not what it reads.
fn pick(call: &Value, item: &Value, ctx: &Ctx) -> R<Option<Value>> {
    match procedure(call, item, ctx) {
        Ok(called) => Ok(Some(called["input"].clone())),
        Err(Fail::Missing) => Ok(None),
        Err(e) => Err(e),
    }
}

pub(super) fn content_warning(n: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
    let shown = labels(&n["props"]["labels"], scope)?;
    let k = children(n, scope, ctx);
    if k.is_empty() && shown.is_empty() {
        return Err(Fail::Missing);
    }
    let mut o = Map::new();
    if !shown.is_empty() {
        let list = json!(shown);
        let hidden = Value::Array(k.clone());
        o.insert("key".into(), key(&[&list, &hidden]).into());
    }
    o.insert("labels".into(), json!(shown));
    Ok(Some(make("ContentWarning", o, k)))
}

pub(super) fn player(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
    let mut drawn = Vec::new();
    for item in items(p, scope)? {
        let src =
            value(&p["src"], item, |v| url_of(v, ctx).is_some())?.and_then(|f| url_of(f, ctx));
        let duration = value(&p["duration"], item, |v| {
            v.as_f64().is_some_and(|d| d >= 0.0)
        })?;
        let mut o = json!({
            "src": src,
            "title": text_of(&p["title"], item)?,
            "subtitle": text_of(&p["subtitle"], item)?,
            "duration": duration,
            "art": picture_at(&p["art"], item, ctx)?,
        });
        if let Some(open) = text_of(&p["subtitleHref"], item)?.and_then(|h| follow(&h, ctx)) {
            o["subtitleOpen"] = open;
        }
        drawn.push(o);
    }
    Ok(Some(listing("Player", p, scope, ctx, drawn)))
}

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

    fn ctx<'a>(root: &'a Value, origins: &'a [String]) -> Ctx<'a> {
        Ctx {
            origins,
            thumbnails: vec![(
                "https://cdn.example/full/".into(),
                "https://cdn.example/thumb/".into(),
            )],
            trusted: true,
            root,
            report: None,
            inline: None,
            lexicon: None,
            handles: None,
            paged: Vec::new(),
            more: More::default(),
            me: None,
            people: None,
        }
    }

    fn blob(name: &str) -> Value {
        json!({ "url": format!("https://cdn.example/full/{name}"), "thumb": format!("https://cdn.example/small/{name}"), "proxy": format!("https://hud.example/blob/{name}") })
    }

    #[test]
    fn a_gallery_draws_blobs_small_and_urls_as_given() {
        let root = json!({});
        let origins = vec!["https://cdn.example".to_string()];
        let c = ctx(&root, &origins);
        let layout = json!({ "component": "Gallery", "props": { "items": { "$": "records" },
            "src": { "$": "photo" }, "aspectRatio": { "$": "size" }, "alt": { "$": "alt" } } });
        let scope = json!({ "records": [
            { "photo": blob("a"), "size": { "width": 2000, "height": 1500 }, "alt": "sea" },
            { "photo": "https://cdn.example/full/b" },
            { "photo": "https://evil.example/c" },
        ] });
        let tree = resolve(&layout, &scope, &c).unwrap();
        check::checked(&tree);
        assert_eq!(tree["p"]["page"], true);
        let items = tree["items"].as_array().unwrap();
        assert_eq!(
            items[0]["src"],
            json!({ "src": "https://cdn.example/small/a", "fallback": "https://hud.example/blob/a" })
        );
        assert_eq!(items[0]["full"], "https://cdn.example/full/a");
        assert_eq!(items[0]["ratio"], json!(2000.0 / 1500.0));
        assert_eq!(
            items[1]["src"]["src"], "https://cdn.example/full/b",
            "no view's thumbnail rule"
        );
        assert_eq!(items[1]["ratio"], Value::Null);
        assert_eq!(items[2]["src"], Value::Null);
        assert_eq!(items[2]["full"], Value::Null);
    }

    #[test]
    fn a_cover_counts_in_its_nouns_reads_self_labels_and_opens_its_record() {
        let root = json!({});
        let c = ctx(&root, &[]);
        let layout = json!({ "component": "Covers", "props": { "items": { "$": "joins.all" },
            "src": { "$": "photo" }, "count": { "$": "n" }, "countNoun": ["photo", "photos"],
            "labels": { "$": "value.labels" }, "stat": { "$": "favs" }, "statIcon": "heart" } });
        let scope = json!({ "joins": { "all": [
            { "uri": "at://did:plc:a/social.grain.gallery/1", "n": 1, "value": { "labels": { "values": [{ "val": "nudity" }] } } },
            { "uri": "at://did:plc:a/social.grain.gallery/2", "n": 16, "favs": 3, "value": { "labels": ["gore", { "nope": 1 }] } },
        ] } });
        let tree = resolve(&layout, &scope, &c).unwrap();
        check::checked(&tree);
        assert!(tree.get("p").is_none(), "not a page's records");
        let items = tree["items"].as_array().unwrap();
        assert_eq!(items[0]["count"], "1 photo");
        assert_eq!(items[0]["labels"], json!(["nudity"]));
        assert_eq!(items[0]["stat"], Value::Null);
        // A gallery opens as getGallery, the tile its feed opens too.
        assert_eq!(
            items[0]["open"]["call"],
            json!({ "name": "query", "args": { "method": "social.grain.gallery.getGallery",
                    "params": { "gallery": "at://did:plc:a/social.grain.gallery/1" } } })
        );
        assert_eq!(items[1]["count"], "16 photos");
        assert_eq!(items[1]["labels"], json!(["gore"]));
        assert_eq!(items[1]["stat"], json!({ "value": 3, "icon": "heart" }));
    }

    #[test]
    fn a_warning_with_no_labels_keeps_nothing_and_one_with_labels_is_keyed_by_what_it_hides() {
        let root = json!({});
        let c = ctx(&root, &[]);
        let layout = json!({ "component": "ContentWarning", "props": { "labels": { "$": "labels" } },
            "children": [{ "component": "Text", "props": { "value": { "$": "t" } } }] });
        let plain = resolve(&layout, &json!({ "t": "hi" }), &c).unwrap();
        check::checked(&plain);
        assert_eq!(plain["p"], json!({ "labels": [] }));
        let a = resolve(&layout, &json!({ "t": "a", "labels": ["porn"] }), &c).unwrap();
        let b = resolve(&layout, &json!({ "t": "b", "labels": ["porn"] }), &c).unwrap();
        check::checked(&a);
        assert_ne!(a["p"]["key"], b["p"]["key"]);
        assert_eq!(a["k"][0]["c"], "Text");
        assert!(
            resolve(&layout, &json!({}), &c).is_none(),
            "nothing to hide, nothing shown"
        );
    }

    #[test]
    fn a_track_off_the_origins_is_not_playable_and_its_artist_opens_their_account() {
        let root = json!({});
        let origins = vec!["https://audio.example".to_string()];
        let c = ctx(&root, &origins);
        let layout = json!({ "component": "Player", "props": { "items": { "$": "records" },
            "src": { "$": ["audioBlob", "audioUrl"] }, "duration": { "$": "d" }, "subtitleHref": { "$": "did" } } });
        let scope = json!({ "records": [
            { "audioBlob": { "url": "https://hud.example/blob/x" }, "d": 579, "did": "did:plc:artist" },
            { "audioUrl": "https://evil.example/y.mp3", "d": -1 },
            { "audioUrl": "https://audio.example/z.mp3" },
        ] });
        let tree = resolve(&layout, &scope, &c).unwrap();
        check::checked(&tree);
        let items = tree["items"].as_array().unwrap();
        assert_eq!(items[0]["src"], "https://hud.example/blob/x");
        assert_eq!(items[0]["duration"], 579);
        assert_eq!(
            items[0]["subtitleOpen"]["call"]["args"]["actor"],
            "did:plc:artist"
        );
        assert_eq!(items[1]["src"], Value::Null);
        assert_eq!(items[1]["duration"], Value::Null);
        assert_eq!(items[2]["src"], "https://audio.example/z.mp3");
    }

    #[test]
    fn a_track_whose_duration_is_no_path_is_an_error() {
        let root = json!({});
        let c = ctx(&root, &[]);
        let layout = json!({ "component": "Player", "props": { "items": { "$": "records" }, "duration": { "$": 5 } } });
        let error = resolve(&layout, &json!({ "records": [{}] }), &c).unwrap();
        check::checked(&error);
        assert_eq!(
            error["p"],
            json!({ "component": "Player", "message": "unknown path syntax 5" })
        );
    }

    #[test]
    fn items_that_are_no_array_are_an_error_and_none_draw_nothing() {
        let root = json!({});
        let c = ctx(&root, &[]);
        for component in ["Gallery", "Covers", "Player"] {
            let layout =
                json!({ "component": component, "props": { "items": { "$": "records" } } });
            let error = resolve(&layout, &json!({ "records": { "a": 1 } }), &c).unwrap();
            check::checked(&error);
            assert_eq!(
                error["p"],
                json!({ "component": component, "message": "items: no array" })
            );
            assert!(resolve(&layout, &json!({}), &c).is_none(), "{component}");
        }
    }

    /// An account's stories: each full size, with when and where, and in a
    /// trusted view the call that marks it watched, read from it.
    #[test]
    fn slides_draw_each_story_full_size_with_the_call_that_marks_it_watched() {
        let root = json!({});
        let origins = vec!["https://cdn.example".to_string()];
        let mut c = ctx(&root, &origins);
        let call = json!({ "method": "com.example.markViewed", "service": "did:web:example.com#appview",
            "input": { "stories": [{ "$": "uri" }] } });
        let layout = json!({ "component": "Slides", "props": { "items": { "$": "stories" },
            "src": { "$": "full" }, "alt": { "$": "alt" }, "aspectRatio": { "$": "size" },
            "time": { "$": "createdAt" }, "place": { "$": "where" }, "seconds": 6, "call": call,
            "face": { "$": "who.avatar" }, "name": { "$": "who.name" } } });
        let scope = json!({ "stories": [
            { "uri": "at://did:plc:a/com.example.story/1", "full": "https://cdn.example/full/1.jpg", "alt": "A dog",
              "size": { "width": 3, "height": 4 }, "createdAt": "2026-11-19T10:00:00Z", "where": "Portland" },
            { "uri": "at://did:plc:a/com.example.story/2", "full": "https://cdn.example/full/2.jpg" },
        ], "who": { "avatar": "https://cdn.example/full/me.jpg", "name": "Alice" } });
        let tree = resolve(&layout, &scope, &c).unwrap();
        check::checked(&tree);
        assert_eq!(tree["p"]["seconds"], 6);
        // A face drawn small: its thumbnail, as the view's thumbnails say.
        assert_eq!(tree["p"]["face"]["src"], "https://cdn.example/thumb/me.jpg");
        assert_eq!(tree["p"]["name"], "Alice");
        assert_eq!(
            tree["items"][0],
            json!({ "src": { "src": "https://cdn.example/full/1.jpg", "fallback": null }, "alt": "A dog", "ratio": 0.75,
                "time": "2026-11-19T10:00:00Z", "place": "Portland",
                "call": { "method": "com.example.markViewed", "service": "did:web:example.com#appview",
                    "input": { "stories": ["at://did:plc:a/com.example.story/1"] } } })
        );
        assert_eq!(tree["items"][1]["alt"], "");
        assert_eq!(tree["items"][1]["ratio"], Value::Null);
        // An untrusted view calls nothing: the stories show, none marked.
        c.trusted = false;
        let tree = resolve(&layout, &scope, &c).unwrap();
        assert!(
            tree["items"]
                .as_array()
                .unwrap()
                .iter()
                .all(|s| s.get("call").is_none())
        );
        // A call naming no service is the view's error.
        c.trusted = true;
        let bad = json!({ "component": "Slides", "props": { "items": { "$": "stories" }, "src": { "$": "full" },
            "call": { "method": "com.example.markViewed" } } });
        let tree = resolve(&bad, &scope, &c).unwrap();
        assert_eq!(tree["c"], "Error");
    }

    /// A story picked from an archive: the open asks its query to show it
    /// first, and the slides begin at it; asked for none, or the first,
    /// they begin at the first.
    #[test]
    fn slides_begin_at_the_story_asked_for() {
        let story = |uri: &str| json!({ "uri": uri, "full": "https://cdn.example.com/a.jpg" });
        let scope = json!({ "stories": [story("at://a/s/1"), story("at://a/s/2")] });
        let layout = json!({ "component": "Slides", "props": { "items": { "$": "stories" }, "src": { "$": "full" },
            "start": "uri" } });
        let origins = ["https://cdn.example.com".to_string()];
        let asked = json!({ "at": "at://a/s/2" });
        let tree = resolve(&layout, &scope, &ctx(&asked, &origins)).unwrap();
        check::checked(&tree);
        assert_eq!(tree["p"]["start"], 1);
        for root in [json!({ "at": "at://a/s/1" }), json!({})] {
            let tree = resolve(&layout, &scope, &ctx(&root, &origins)).unwrap();
            assert!(tree["p"].get("start").is_none());
        }
        // A story's comments, over it.
        let cover = json!({ "component": "List", "props": { "items": { "$": "stories" },
            "open": { "query": "com.example.getArchive", "params": {}, "at": { "$": "uri" }, "sheet": true } },
            "children": [{ "component": "Text", "props": { "value": { "$": "uri" } } }] });
        let tree = resolve(&cover, &scope, &ctx(&json!({}), &origins)).unwrap();
        check::checked(&tree);
        assert_eq!(tree["items"][1]["open"]["call"]["args"]["at"], "at://a/s/2");
        assert_eq!(tree["items"][1]["open"]["sheet"], true);
    }

    /// An archive answered newest first, played oldest first: reversed,
    /// begun at the story asked for where it is now, each picture the
    /// screen of its record, one with no record none.
    #[test]
    fn slides_reversed_begin_where_asked_and_name_each_picture_s_screen() {
        let story = |uri: &str| json!({ "uri": uri, "full": "https://cdn.example.com/a.jpg" });
        let scope = json!({ "stories": [story("at://did:plc:a/com.example.story/3"), story("at://did:plc:a/com.example.story/2"),
            { "full": "https://cdn.example.com/a.jpg" }] });
        let layout = json!({ "component": "Slides", "props": { "items": { "$": "stories" }, "src": { "$": "full" },
            "start": "uri", "href": { "$": "uri" }, "reverse": true } });
        let origins = ["https://cdn.example.com".to_string()];
        let asked = json!({ "at": "at://did:plc:a/com.example.story/3" });
        let tree = resolve(&layout, &scope, &ctx(&asked, &origins)).unwrap();
        check::checked(&tree);
        assert_eq!(tree["p"]["start"], 2);
        assert!(tree["items"][0].get("open").is_none());
        let opens = |i: usize| tree["items"][i]["open"]["call"]["args"]["uri"].clone();
        assert_eq!(opens(1), "at://did:plc:a/com.example.story/2");
        assert_eq!(opens(2), "at://did:plc:a/com.example.story/3");
        assert!(tree["p"].get("reverse").is_none());
    }

    /// No stories: the screen's words, and a way to add one where the
    /// account asked about is one's own.
    #[test]
    fn slides_of_nothing_say_so_and_offer_a_way_to_add_one() {
        let root = json!({});
        let mut c = ctx(&root, &[]);
        c.me = Some("did:plc:me");
        let layout = json!({ "component": "Slides", "props": { "items": { "$": "stories" }, "src": { "$": "full" },
            "empty": "No stories yet" },
            "children": [{ "component": "Stack", "props": { "mine": "actor" },
                "children": [{ "component": "Text", "props": { "value": "Add to your story" } }] }] });
        let mine = resolve(
            &layout,
            &json!({ "stories": [], "actor": "did:plc:me" }),
            &c,
        )
        .unwrap();
        check::checked(&mine);
        assert_eq!(mine["p"]["empty"], "No stories yet");
        assert_eq!(
            mine["k"][0]["k"][0]["p"]["runs"][0]["text"],
            "Add to your story"
        );
        let theirs = resolve(
            &layout,
            &json!({ "stories": [], "actor": "did:plc:else" }),
            &c,
        )
        .unwrap();
        assert_eq!(theirs["k"], Value::Null);
        // With stories, neither.
        let some = resolve(
            &layout,
            &json!({ "stories": [{ "full": "https://cdn.example/a.jpg" }], "actor": "did:plc:me" }),
            &c,
        )
        .unwrap();
        assert_eq!((some["p"].get("empty"), some.get("k")), (None, None));
        // With no words for it, none said.
        let wordless = json!({ "component": "Slides", "props": { "items": { "$": "stories" }, "src": { "$": "full" } } });
        let none = resolve(&wordless, &json!({ "stories": [] }), &c).unwrap();
        assert_eq!(
            (none["p"].get("empty"), none.get("items")),
            (None, Some(&json!([])))
        );
    }

    /// Known followers: three faces, two names and how many, opening the
    /// list; none, nothing.
    #[test]
    fn faces_of_a_few_and_how_many() {
        let root = json!({});
        let origins = vec!["https://cdn.example".to_string()];
        let c = ctx(&root, &origins);
        let layout = json!({ "component": "Faces", "props": { "items": { "$": "known" },
            "src": { "$": "avatar" }, "name": { "$": ["displayName", "handle"] },
            "lead": "Followed by", "countNoun": ["other you follow", "others you follow"],
            "open": { "query": "a.b.getKnownFollowers", "params": { "actor": { "$": "did" } } } } });
        let person = |n: u8| json!({ "handle": format!("p{n}.test"), "avatar": format!("https://cdn.example/full/{n}.jpg") });
        let scope = json!({ "did": "did:plc:a", "known": [person(1), { "displayName": "Two" }, person(3), person(4)] });
        let tree = resolve(&layout, &scope, &c).unwrap();
        check::checked(&tree);
        // The first two named, the third a face alone; the nouns one and many.
        let names: Vec<&Value> = (0..3).map(|i| &tree["p"]["faces"][i]["name"]).collect();
        assert_eq!(names, [&json!("p1.test"), &json!("Two"), &Value::Null]);
        assert_eq!(
            tree["p"]["countNoun"],
            json!({ "one": "other you follow", "many": "others you follow" })
        );
        assert_eq!(tree["p"]["count"], 4);
        assert_eq!(tree["p"]["faces"].as_array().unwrap().len(), 3);
        assert_eq!(tree["p"]["faces"][1]["src"], Value::Null);
        assert_eq!(
            tree["p"]["faces"][0]["src"]["src"],
            "https://cdn.example/full/1.jpg"
        );
        assert_eq!(
            tree["p"]["open"]["call"]["args"]["params"]["actor"],
            "did:plc:a"
        );
        assert_eq!(resolve(&layout, &json!({ "known": [] }), &c), None);
        let bare = json!({ "component": "Faces", "props": { "items": { "$": "known" }, "src": { "$": "avatar" } } });
        let tree = resolve(&bare, &json!({ "known": [{}] }), &c).unwrap();
        assert_eq!((tree["p"].get("lead"), tree["p"].get("open")), (None, None));
    }

    /// A pile, as a notification's favorites: every face, each its name,
    /// handle and account; how many it draws (5 by default) and whether it
    /// lists them all.
    #[test]
    fn a_pile_names_every_face_and_opens_each() {
        let root = json!({});
        let origins = vec!["https://cdn.example".to_string()];
        let c = ctx(&root, &origins);
        let layout = |extra: Value| {
            let mut p = json!({ "style": "pile", "items": { "$": "who" }, "src": { "$": "author.avatar" },
                "name": { "$": ["author.displayName", "author.handle"] }, "handle": { "$": "author.handle" },
                "href": { "$": "author.did" } });
            p.as_object_mut()
                .unwrap()
                .extend(extra.as_object().unwrap().clone());
            json!({ "component": "Faces", "props": p })
        };
        let person = |n: u8| json!({ "author": { "did": format!("did:plc:p{n}"), "handle": format!("p{n}.test") } });
        let scope = json!({ "who": (1..=7).map(person).collect::<Vec<_>>() });
        let tree = resolve(&layout(json!({ "max": 3, "expand": true })), &scope, &c).unwrap();
        check::checked(&tree);
        let faces = tree["p"]["faces"].as_array().unwrap();
        assert_eq!(faces.len(), 7);
        assert_eq!(
            (&faces[6]["name"], &faces[6]["handle"]),
            (&json!("p7.test"), &json!("p7.test"))
        );
        assert_eq!(faces[6]["open"]["call"]["args"]["actor"], "did:plc:p7");
        assert_eq!(
            (
                &tree["p"]["style"],
                &tree["p"]["max"],
                &tree["p"]["expand"],
                &tree["p"]["count"]
            ),
            (&json!("pile"), &json!(3), &json!(true), &json!(7))
        );
        let tree = resolve(&layout(json!({})), &scope, &c).unwrap();
        assert_eq!(
            (&tree["p"]["max"], tree["p"].get("expand")),
            (&json!(5), None)
        );
    }

    /// Each story its ⋯, read from the story itself: its own a Delete.
    #[test]
    fn each_slide_draws_its_children_with_it() {
        let root = json!({});
        let mut c = ctx(&root, &[]);
        c.me = Some("did:plc:me");
        let layout = json!({ "component": "Slides", "props": { "items": { "$": "stories" }, "src": { "$": "full" } },
            "children": [{ "component": "Stack", "props": { "mine": "creator" },
                "children": [{ "component": "Text", "props": { "value": { "$": "uri" } } }] }] });
        let scope = json!({ "stories": [
            { "full": "https://cdn.example/a.jpg", "uri": "at://did:plc:me/s/1", "creator": "did:plc:me" },
            { "full": "https://cdn.example/b.jpg", "uri": "at://did:plc:else/s/2", "creator": "did:plc:else" },
        ] });
        let tree = resolve(&layout, &scope, &c).unwrap();
        check::checked(&tree);
        assert_eq!(
            tree["items"][0]["k"][0]["k"][0]["p"]["runs"][0]["text"],
            "at://did:plc:me/s/1"
        );
        assert_eq!(tree["items"][1].get("k"), None);
    }

    #[test]
    fn a_stacked_gallery_and_tiled_covers_say_their_style() {
        let root = json!({});
        let c = ctx(&root, &[]);
        let gallery = json!({ "component": "Gallery", "props": { "items": { "$": "all" }, "style": "stack" } });
        let tree = resolve(&gallery, &json!({ "all": [] }), &c).unwrap();
        check::checked(&tree);
        assert_eq!(
            tree,
            json!({ "c": "Gallery", "p": { "style": "stack" }, "items": [] })
        );
        // A gallery's screen: one at a time, edge to edge, each photo with
        // alt text marked ALT, a tap opening it to be zoomed.
        let bled = json!({ "component": "Gallery", "props": { "items": { "$": "all" }, "style": "carousel", "bleed": true, "showAlt": true, "zoom": true } });
        let tree = resolve(&bled, &json!({ "all": [] }), &c).unwrap();
        check::checked(&tree);
        assert_eq!(
            tree["p"],
            json!({ "style": "carousel", "bleed": true, "showAlt": true, "zoom": true })
        );
        let covers = json!({ "component": "Covers", "props": { "items": { "$": "all" }, "style": "tiles" } });
        let tree = resolve(&covers, &json!({ "all": [] }), &c).unwrap();
        check::checked(&tree);
        assert_eq!(
            tree,
            json!({ "c": "Covers", "p": { "style": "tiles" }, "items": [] })
        );
        // Its narrowest and most across as given, cards' as tiles'.
        let capped = json!({ "component": "Covers", "props": { "items": { "$": "all" }, "min": "md", "columns": 4 } });
        let tree = resolve(&capped, &json!({ "all": [] }), &c).unwrap();
        check::checked(&tree);
        assert_eq!(tree["p"], json!({ "min": "md", "columns": 4 }));
    }

    /// An account's other galleries: Covers leave out what `where` doesn't
    /// keep, the gallery drawn in `{"$not": …}`, and draw at most `limit`,
    /// six whether the gallery drawn is among the seven or not; a List's
    /// `where` the same.
    #[test]
    fn covers_leave_out_what_where_does_not_keep_and_stop_at_limit() {
        let root = json!({});
        let c = ctx(&root, &[]);
        let covers = json!({ "component": "Covers", "props": { "items": { "$": "more" }, "src": { "$": "thumb" },
            "title": { "$": "title" }, "where": { "uri": { "$not": "gallery.uri" } }, "limit": 6 } });
        let more: Vec<Value> = (1..=7)
            .map(|i| json!({ "uri": format!("at://a/g/{i}"), "title": format!("g{i}") }))
            .collect();
        let titles = |gallery: &str| {
            let scope = json!({ "more": more, "gallery": { "uri": gallery } });
            let tree = resolve(&covers, &scope, &c).unwrap();
            check::checked(&tree);
            tree["items"]
                .as_array()
                .unwrap()
                .iter()
                .map(|i| i["title"].as_str().unwrap().to_string())
                .collect::<Vec<_>>()
        };
        assert_eq!(titles("at://a/g/3"), ["g1", "g2", "g4", "g5", "g6", "g7"]);
        assert_eq!(titles("at://a/g/9"), ["g1", "g2", "g3", "g4", "g5", "g6"]);
        // A literal in `$not`, on a List: all but the one it names.
        let list = json!({ "component": "List", "props": { "items": { "$": "more" },
            "where": { "title": { "$not": { "$is": "g2" } } }, "limit": 2 },
            "children": [{ "component": "Text", "props": { "value": { "$": "title" } } }] });
        let tree = resolve(&list, &json!({ "more": more }), &c).unwrap();
        check::checked(&tree);
        let drawn: Vec<&Value> = tree["items"]
            .as_array()
            .unwrap()
            .iter()
            .map(|i| &i["k"][0]["p"]["runs"][0]["text"])
            .collect();
        assert_eq!(drawn, [&json!("g1"), &json!("g3")]);
    }

    /// A full-width gallery's photos with the sizes they come in, narrowest
    /// first, each a URL the view may load, one that would break the list
    /// (a comma) or reads nothing left out; justified rows, and a photo none
    /// of whose sizes read, with none.
    #[test]
    fn a_full_width_gallery_says_each_photos_sizes() {
        let root = json!({});
        let origins = ["https://cdn.test".to_string()];
        let c = ctx(&root, &origins);
        let sizes = json!([{ "src": { "$": "full" }, "width": 2000 }, { "src": { "$": "thumb" }, "width": 1000 },
                           { "src": { "$": "odd" }, "width": 500 }, { "src": { "$": "none" }, "width": 300 }]);
        let gallery = |style: &str| {
            json!({ "component": "Gallery", "props": { "items": { "$": "all" }, "src": { "$": "full" },
                                                                              "style": style, "srcset": sizes } })
        };
        let photos = json!({ "all": [
            { "full": "https://cdn.test/f.jpg", "thumb": "https://cdn.test/t.jpg", "odd": "https://cdn.test/a,b.jpg" },
            { "full": "https://elsewhere.test/f.jpg" },
        ] });
        let tree = resolve(&gallery("carousel"), &photos, &c).unwrap();
        check::checked(&tree);
        assert_eq!(
            tree["items"][0]["srcset"],
            "https://cdn.test/t.jpg 1000w, https://cdn.test/f.jpg 2000w"
        );
        assert_eq!(tree["items"][1].get("srcset"), None);
        let rows = resolve(&gallery("rows"), &photos, &c).unwrap();
        assert_eq!(rows["items"][0].get("srcset"), None);
        let plain = json!({ "component": "Gallery", "props": { "items": { "$": "all" }, "src": { "$": "full" }, "style": "stack" } });
        assert_eq!(
            resolve(&plain, &photos, &c).unwrap()["items"][0].get("srcset"),
            None
        );
    }

    /// A story's and a cover's pictures with the sizes they come in, as a
    /// gallery's photos: narrowest first, each a URL the view may load; one
    /// none of whose sizes read, and a view naming none, with none.
    #[test]
    fn slides_and_covers_say_each_pictures_sizes() {
        let root = json!({});
        let origins = ["https://cdn.test".to_string()];
        let c = ctx(&root, &origins);
        let sizes = json!([{ "src": { "$": "large" }, "width": 1440 }, { "src": { "$": "small" }, "width": 640 }]);
        let all = json!({ "all": [
            { "uri": "at://a/s/1", "src": "https://cdn.test/s.jpg", "small": "https://cdn.test/s-640.jpg", "large": "https://cdn.test/s-1440.jpg" },
            { "uri": "at://a/s/2", "src": "https://cdn.test/o.jpg", "small": "https://elsewhere.test/o.jpg" },
        ] });
        for name in ["Slides", "Covers"] {
            let sized = json!({ "component": name, "props": { "items": { "$": "all" }, "src": { "$": "src" }, "srcset": sizes } });
            let tree = resolve(&sized, &all, &c).unwrap();
            check::checked(&tree);
            assert_eq!(
                tree["items"][0]["srcset"],
                "https://cdn.test/s-640.jpg 640w, https://cdn.test/s-1440.jpg 1440w",
                "{name}"
            );
            assert_eq!(tree["items"][1].get("srcset"), None, "{name}");
            let plain = json!({ "component": name, "props": { "items": { "$": "all" }, "src": { "$": "src" } } });
            assert_eq!(
                resolve(&plain, &all, &c).unwrap()["items"][0].get("srcset"),
                None,
                "{name}"
            );
        }
    }

    /// Each photo's own camera, read from its item: a line's parts joined,
    /// one reading nothing left out, a make left out before a model that
    /// names it (`omitRepeated`) and kept elsewhere, a line of none
    /// dropped, a photo with none given no info.
    #[test]
    fn each_photo_says_its_own_camera() {
        let root = json!({});
        let c = ctx(&root, &[]);
        let gallery = json!({ "component": "Gallery", "props": { "items": { "$": "photos" }, "src": { "$": "src" },
            "style": "carousel", "info": [
                { "parts": [{ "value": { "$": "exif.make" }, "omitRepeated": true }, { "value": { "$": "exif.model" } }] },
                { "parts": [{ "value": { "$": ["exif.lensModel", "exif.lensMake"] } }] },
                { "parts": [{ "value": { "$": "exif.focalLengthIn35mmFormat" } }, { "value": { "$": "exif.fNumber" } },
                    { "value": { "$": "exif.iSO" }, "prefix": "ISO " }, { "value": { "$": "exif.flash" }, "suffix": " flash" }], "join": " · " },
            ] } });
        let photos = json!({ "photos": [
            { "src": "x", "exif": { "make": "Fujifilm", "model": "X100V", "lensModel": "23mm", "fNumber": "ƒ/2", "iSO": 400, "flash": "" } },
            { "src": "y", "exif": { "make": "Leica", "focalLengthIn35mmFormat": "35mm", "flash": "No" } },
            { "src": "z" },
            { "src": "n", "exif": { "make": "NIKON CORPORATION", "model": "Nikon D750" } },
        ] });
        let tree = resolve(&gallery, &photos, &c).unwrap();
        check::checked(&tree);
        let info: Vec<&Value> = (0..4).map(|i| &tree["items"][i]["info"]).collect();
        assert_eq!(
            info,
            [
                &json!([{ "text": "Fujifilm X100V" }, { "text": "23mm" }, { "text": "ƒ/2 · ISO 400" }]),
                &json!([{ "text": "Leica" }, { "text": "35mm · No flash" }]),
                &Value::Null,
                &json!([{ "text": "Nikon D750" }]),
            ]
        );
    }

    /// With no nouns, a count is its number as JavaScript writes it (an
    /// array's length, a fraction kept); a stat with no icon is its value
    /// alone; an open that is no record opens nothing.
    #[test]
    fn a_cover_without_nouns_counts_bare_and_opens_nothing_it_cannot() {
        let root = json!({});
        let c = ctx(&root, &[]);
        let layout = json!({ "component": "Covers", "props": { "items": { "$": "all" },
            "count": { "$": "n" }, "stat": { "$": "favs" }, "open": false } });
        let scope = json!({ "all": [
            { "uri": "at://did:plc:a/social.grain.gallery/1", "n": ["a", "b", "c"], "favs": 2 },
            { "uri": "at://did:plc:a/social.grain.gallery/2", "n": 2.5 },
        ] });
        let tree = resolve(&layout, &scope, &c).unwrap();
        check::checked(&tree);
        let items = tree["items"].as_array().unwrap();
        assert_eq!(items[0]["count"], "3");
        assert_eq!(items[0]["many"], true);
        assert_eq!(items[0]["stat"], json!({ "value": 2 }));
        assert!(items[0].get("open").is_none());
        assert_eq!(items[1]["count"], "2.5");
        assert!(items[1].get("open").is_none());
    }

    /// Grain's own stories opened at their form (`compose`): with none,
    /// Add to your story opens at once; with some, nothing opens (what is
    /// over each picture is the picture's), and another's opens nothing.
    #[test]
    fn a_story_screen_opens_at_its_add_only_where_it_has_none() {
        let doc: Value = serde_json::from_str(include_str!(
            "../testdata/grain/apps/views/grain-stories.json"
        ))
        .unwrap();
        let drawn = |actor: &str, stories: Value, form: Value| {
            let root = json!({ "params": { "actor": actor }, "me": { "did": "did:plc:me" },
                "response": { "stories": stories.clone() }, "items": stories,
                "joins": { "who": { "did": actor, "handle": "me.test" } } });
            let origins = vec!["https://cdn.grain.social".to_string()];
            let mut c = ctx(&root, &origins);
            c.me = Some("did:plc:me");
            let mut tree = resolve(&doc["query"]["layout"], &root, &c).unwrap();
            let opened = super::super::open_compose(&mut tree, &form);
            check::checked(&tree);
            (opened, tree)
        };
        let (opened, none) = drawn("did:plc:me", json!([]), json!(true));
        assert!(opened);
        let add = &none["k"][0]["k"][0];
        assert_eq!(
            (&add["c"], &add["p"]["label"], &add["p"]["open"]),
            (&json!("Compose"), &json!("Add to your story"), &json!(true))
        );
        // By its label, as a frame's action opens New gallery.
        assert!(drawn("did:plc:me", json!([]), json!("Add to your story")).0);
        assert!(!drawn("did:plc:me", json!([]), json!("New gallery")).0);
        // Another's, with none: nothing to add, nothing opened.
        assert!(!drawn("did:plc:else", json!([]), json!(true)).0);
        let story = json!({ "uri": "at://did:plc:me/social.grain.story/1", "cid": "c",
            "creator": { "did": "did:plc:me", "handle": "me.test" },
            "fullsize": "https://cdn.grain.social/a.jpg", "createdAt": "2026-11-21T00:00:00Z" });
        let (opened, some) = drawn("did:plc:me", json!([story]), json!(true));
        assert!(!opened);
        let over = serde_json::to_string(&some["items"][0]["k"]).unwrap();
        assert!(over.contains("Delete story") && !over.contains("\"open\":true"));
    }

    /// Each Grain story has ♡ over it beside its 💬: a favorite of the
    /// story, holding the one the account made already (`viewer.fav`), so
    /// it starts done and undoes it.
    #[test]
    fn a_story_is_favorited_from_over_its_picture() {
        let doc: Value = serde_json::from_str(include_str!(
            "../testdata/grain/apps/views/grain-stories.json"
        ))
        .unwrap();
        let story = |n: u8, viewer: Value| {
            json!({ "uri": format!("at://did:plc:else/social.grain.story/{n}"), "cid": "c",
                "creator": { "did": "did:plc:else", "handle": "else.test" }, "viewer": viewer,
                "fullsize": "https://cdn.grain.social/a.jpg", "createdAt": "2026-11-21T00:00:00Z" })
        };
        let faved = "at://did:plc:me/social.grain.favorite/3kfav";
        let stories = json!([story(1, json!({})), story(2, json!({ "fav": faved }))]);
        let root = json!({ "params": { "actor": "did:plc:else" }, "me": { "did": "did:plc:me" },
            "response": { "stories": stories.clone() }, "items": stories,
            "joins": { "who": { "did": "did:plc:else", "handle": "else.test" } } });
        let origins = vec!["https://cdn.grain.social".to_string()];
        let mut c = ctx(&root, &origins);
        c.me = Some("did:plc:me");
        let tree = resolve(&doc["query"]["layout"], &root, &c).unwrap();
        check::checked(&tree);
        // A double-tap on the picture runs it, by its label.
        assert_eq!(tree["p"]["like"], "Favorite");
        let heart = |i: usize| {
            let row = &tree["items"][i]["k"][0]["k"];
            assert_eq!(row[0]["p"]["label"], "Comments");
            row[1]["p"].clone()
        };
        let (first, second) = (heart(0), heart(1));
        assert_eq!(
            (&first["icon"], &first["done"]),
            (&json!("heart"), &json!("Favorited"))
        );
        assert_eq!(first["create"]["collection"], "social.grain.favorite");
        assert_eq!(
            first["create"]["record"]["subject"],
            "at://did:plc:else/social.grain.story/1"
        );
        assert!(first.get("existing").is_none());
        assert_eq!(second["existing"], faved);
        assert_ne!(first["key"], second["key"]);
    }
}