~ 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
396 lines · 16.1 KB Raw History
//! A map with pins, as the web renderer's MapNode and HUDKit's ResolvedMap
//! draw one.
//!
//! - `Map`: `p: { height, zoom?, bleed?, pins? }`, `items: [{ lat, lng,
//!   label?, count?, open? }]`; `height` `short` (a header) or `tall`; with
//!   `zoom`, the map centred on its pins at that zoom, else fitted to them;
//!   `pins: false`, centred on them so, but none drawn. A pin's place is
//!   its item's `cell`, an H3 cell turned into its centre here, else its
//!   `lat` and `lng`, so the clients get coordinates alone.

use super::*;
use h3o::{CellIndex, LatLng};

/// A coordinate to 6 decimals (about 0.1 m), as much as a pin needs.
fn round(x: f64) -> f64 {
    (x * 1e6).round() / 1e6
}

/// Its items: literal ones each with its `{"$root": path}`s read from the
/// view's scope, else the array a binding (`$` or `$root`) holds.
fn items(p: &Value, scope: &Value, ctx: &Ctx) -> R<Vec<Value>> {
    let found = match &p["items"] {
        Value::Array(a) => return a.iter().map(|item| rooted(item, ctx.root, true)).collect(),
        given if is_root_binding(given) => root_value(given, ctx.root)?,
        given => value(given, scope, present)?,
    };
    match found {
        Some(Value::Array(a)) => Ok(a.clone()),
        Some(_) => bad("items: no array"),
        None => Err(Fail::Missing),
    }
}

/// Where an item's pin is: its H3 cell's centre, else its `lat` and `lng`;
/// none where it gives neither, an error where what it gives is no place.
fn place(p: &Value, item: &Value) -> R<Option<(f64, f64)>> {
    if let Some(cell) = value(&p["cell"], item, Value::is_string)?.and_then(Value::as_str) {
        let Ok(index) = cell.parse::<CellIndex>() else {
            return bad(format!("cell: {cell} is no H3 cell"));
        };
        let centre = LatLng::from(index);
        return Ok(Some((centre.lat(), centre.lng())));
    }
    let lat = value(&p["lat"], item, Value::is_number)?.and_then(Value::as_f64);
    let lng = value(&p["lng"], item, Value::is_number)?.and_then(Value::as_f64);
    match (lat, lng) {
        (Some(lat), Some(lng))
            if (-90.0..=90.0).contains(&lat) && (-180.0..=180.0).contains(&lng) =>
        {
            Ok(Some((lat, lng)))
        }
        (Some(lat), Some(lng)) => bad(format!("lat {lat}, lng {lng}: no place on Earth")),
        _ => Ok(None),
    }
}

/// `Map`: a pin per item that gives a place, each with its label, count
/// and what it opens (a literal item's own `open` in place of the Map's);
/// no pins, nothing.
pub(super) fn map(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
    let literal = p["items"].is_array();
    let fallback = json!({ "$": "uri" });
    let mut pins = Vec::new();
    for item in items(p, scope, ctx)? {
        let Some((lat, lng)) = place(p, &item)? else {
            continue;
        };
        let mut pin = json!({ "lat": round(lat), "lng": round(lng) });
        if let Some(label) = text_of(&p["label"], &item)? {
            pin["label"] = label.into();
        }
        if let Some(n) = value(&p["count"], &item, Value::is_u64)?.and_then(Value::as_u64) {
            pin["count"] = n.into();
        }
        let own = if literal && !item["open"].is_null() {
            &item["open"]
        } else {
            &p["open"]
        };
        if let Some(open) = opens(own, &item, ctx, Some(&fallback))? {
            pin["open"] = open;
        }
        pins.push(pin);
    }
    if pins.is_empty() {
        return Err(Fail::Missing);
    }
    let mut o = Map::new();
    let height = p["height"].as_str().filter(|h| *h == "tall");
    o.insert("height".into(), height.unwrap_or("short").into());
    if let Some(zoom) = p["zoom"].as_u64() {
        o.insert("zoom".into(), zoom.into());
    }
    if p["bleed"] == true {
        o.insert("bleed".into(), true.into());
    }
    if p["pins"] == false {
        o.insert("pins".into(), false.into());
    }
    let mut out = make("Map", o, vec![]);
    out["items"] = Value::Array(pins);
    Ok(Some(out))
}

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

    fn ctx(root: &Value) -> Ctx<'_> {
        Ctx {
            origins: &[],
            thumbnails: Vec::new(),
            trusted: true,
            root,
            report: None,
            inline: None,
            lexicon: None,
            handles: None,
            paged: Vec::new(),
            more: More::default(),
            me: None,
            people: None,
        }
    }

    /// A Grain query's answer as its bundled view draws it, held to the
    /// tree's lexicon.
    fn grain(method: &str, params: Value, response: Value, joins: Value) -> Value {
        let view = crate::view::for_method(method).unwrap();
        let mut answer = json!({ "structuredContent": { "method": method,
                "service": "did:web:grain.social#grain_appview",
                "params": params, "response": response, "joins": joins },
            "_meta": { "view": { "doc": view.doc, "mode": "query", "trusted": true } } });
        crate::tools::resolve_answer(&mut answer, Some("query"), None).unwrap();
        let ui = answer["_meta"]["ui"].take();
        assert_eq!(check(&ui), Ok(()));
        ui
    }

    /// The nodes of component `c` in a tree, in order.
    fn nodes(n: &Value, c: &str) -> Vec<Value> {
        let mut found: Vec<Value> = (n["c"] == c).then(|| n.clone()).into_iter().collect();
        for k in n["k"].as_array().into_iter().flatten() {
            found.extend(nodes(k, c));
        }
        found
    }

    /// The one node of component `c` in a tree, which must hold one.
    fn one(ui: &Value, c: &str) -> Value {
        let mut found = nodes(&ui["root"], c);
        assert_eq!(found.len(), 1, "one {c}: {ui}");
        found.remove(0)
    }

    /// Opening a Grain place's galleries, as its pins and cards do.
    fn place_feed(cell: &str, name: &str) -> Value {
        json!({ "call": { "name": "query", "args": { "method": "social.grain.feed.getFeed",
            "params": { "feed": "at://did:web:grain.social/social.grain.feed.generator/location",
                        "location": cell, "name": name } } } })
    }

    /// Grain's place page, as its bundled view draws it: a plain map of
    /// the place, centred on its cell, no pin drawn, against its galleries
    /// under it, as Grain's web heads a place's page.
    #[test]
    fn grains_place_page_has_a_map_of_the_place() {
        let ui = grain(
            "social.grain.feed.getFeed",
            json!({ "feed": "at://did:web:grain.social/social.grain.feed.generator/location",
                    "location": "8a1969c9b397fff", "name": "Amsterdam, Noord-Holland, NL" }),
            json!({ "items": [{ "uri": "at://did:plc:a/social.grain.gallery/1", "title": "Canals",
                "items": [{ "thumb": "https://cdn.grain.social/a/feed_thumbnail/plain/did:plc:a/b" }] }] }),
            json!({}),
        );
        let map = one(&ui, "Map");
        assert_eq!(
            map["p"],
            json!({ "height": "short", "bleed": true, "pins": false })
        );
        assert_eq!(
            map["items"],
            json!([{ "lat": 52.373031, "lng": 4.892636, "label": "Amsterdam, Noord-Holland, NL" }])
        );
        let header = nodes(&ui["root"], "Stack")
            .into_iter()
            .find(|s| s["k"][0]["c"] == "Map")
            .unwrap();
        assert_eq!(header["p"]["gap"], "none");
        assert_eq!(header["k"][1]["c"], "Stack");
        assert_eq!(header["k"][1]["p"]["gap"], "md");
        assert_eq!(nodes(&header["k"][1], "Covers").len(), 1);
    }

    /// Grain's Locations (getLocations with pins): every place a pin with
    /// its galleries' count, over the top places' cards, each opening the
    /// place's galleries; its Explore (no pins) none of it, but its top
    /// places and cameras as chips, each ending in a See all where there
    /// are more than it shows.
    #[test]
    fn grains_locations_page_maps_every_place_over_the_top_ones() {
        let amsterdam = json!({ "name": "Amsterdam, Noord-Holland, NL", "h3Index": "8a1969c9b397fff",
            "galleryCount": 12 });
        let mut top = amsterdam.clone();
        top["thumbs"] = json!(["https://cdn.grain.social/a/feed_thumbnail/plain/did:plc:a/b"]);
        let ui = grain(
            "social.grain.gallery.getLocations",
            json!({ "pins": true }),
            json!({ "locations": [amsterdam, { "name": "Nowhere", "h3Index": "8a1969c9b397fff", "galleryCount": 1 }] }),
            json!({ "places": { "locations": [top] } }),
        );
        let map = one(&ui, "Map");
        assert_eq!(map["p"], json!({ "height": "tall", "bleed": true }));
        assert_eq!(map["items"].as_array().unwrap().len(), 2);
        assert_eq!(
            map["items"][0],
            json!({ "lat": 52.373031, "lng": 4.892636, "label": "Amsterdam, Noord-Holland, NL",
                "count": 12, "open": place_feed("8a1969c9b397fff", "Amsterdam, Noord-Holland, NL") })
        );
        let cards = one(&ui, "Covers");
        let card = &cards["items"][0];
        assert_eq!(
            (&card["title"], &card["count"], &card["open"]),
            (
                &json!("Amsterdam, Noord-Holland, NL"),
                &json!("12 galleries"),
                &place_feed("8a1969c9b397fff", "Amsterdam, Noord-Holland, NL")
            )
        );
        assert_eq!(nodes(&ui["root"], "Search"), Vec::<Value>::new());
        let cameras: Vec<Value> = (0..11)
            .map(|i| json!({ "camera": format!("Fujifilm X{i}"), "photoCount": 9 }))
            .collect();
        let explore = grain(
            "social.grain.gallery.getLocations",
            json!({}),
            json!({ "locations": vec![top.clone(); 11] }),
            json!({ "cameras": { "cameras": cameras }, "recent": { "items": [] } }),
        );
        assert_eq!(nodes(&explore["root"], "Map"), Vec::<Value>::new());
        let lists = nodes(&explore["root"], "List");
        let titles: Vec<&Value> = lists.iter().map(|l| &l["p"]["title"]).collect();
        assert_eq!(titles, [&json!("Cameras"), &json!("Places")]);
        let all: Vec<Value> = lists
            .iter()
            .map(|l| l["p"]["more"]["open"]["call"]["args"].clone())
            .collect();
        assert_eq!(
            all,
            [
                json!({ "method": "social.grain.gallery.getCameras", "params": {} }),
                json!({ "method": "social.grain.gallery.getLocations", "params": { "pins": true } })
            ]
        );
        assert_eq!(lists[0]["items"].as_array().unwrap().len(), 10);
    }

    /// Grain's Cameras, the Locations page's sibling (Explore's other See
    /// all): a card per camera with its photos' count, opening its galleries.
    #[test]
    fn grains_cameras_page_has_a_card_per_camera() {
        let ui = grain(
            "social.grain.gallery.getCameras",
            json!({}),
            json!({ "cameras": [{ "camera": "Fujifilm X100V", "photoCount": 1,
                "thumbs": ["https://cdn.grain.social/a/feed_thumbnail/plain/did:plc:a/b"] }] }),
            json!({}),
        );
        let cards = one(&ui, "Covers");
        let card = &cards["items"][0];
        assert_eq!(
            (&card["title"], &card["count"], &card["src"]["src"]),
            (
                &json!("Fujifilm X100V"),
                &json!("1 photo"),
                &json!("https://cdn.grain.social/a/feed_thumbnail/plain/did:plc:a/b")
            )
        );
        assert_eq!(
            card["open"]["call"]["args"]["params"],
            json!({ "feed": "at://did:web:grain.social/social.grain.feed.generator/camera",
                    "camera": "Fujifilm X100V" })
        );
    }

    /// Grain's places: each H3 cell its centre's coordinates, as H3's own
    /// docs give 85283473fffffff's, its name and gallery count, opening
    /// its galleries.
    #[test]
    fn a_map_puts_each_cell_at_its_centre_and_opens_its_pin() {
        let root = json!({});
        let c = ctx(&root);
        let layout = json!({ "component": "Map", "props": { "items": { "$": "locations" },
            "cell": { "$": "h3Index" }, "label": { "$": "name" }, "count": { "$": "galleryCount" },
            "height": "tall", "bleed": true,
            "open": { "query": "a.b.getFeed", "params": { "location": { "$": "h3Index" } } } } });
        let scope = json!({ "locations": [
            { "name": "Cupertino", "h3Index": "85283473fffffff", "galleryCount": 3 },
            { "name": "Nowhere" },
        ] });
        let tree = resolve(&layout, &scope, &c).unwrap();
        check::checked(&tree);
        assert_eq!(tree["p"], json!({ "height": "tall", "bleed": true }));
        assert_eq!(
            tree["items"],
            json!([{ "lat": 37.345793, "lng": -121.976376, "label": "Cupertino", "count": 3,
                "open": { "call": { "name": "query", "args": { "method": "a.b.getFeed",
                    "params": { "location": "85283473fffffff" } } } } }]),
            "an item with no place has no pin"
        );
    }

    /// A header's map: one literal item, its cell the view's param, at a
    /// zoom; a pin given as lat and lng; none where the param is not there.
    #[test]
    fn a_literal_item_centres_a_map_on_one_place() {
        let layout = |items: Value| {
            json!({ "component": "Map", "props": { "items": items, "cell": { "$": "cell" },
                "lat": { "$": "lat" }, "lng": { "$": "lng" }, "zoom": 11 } })
        };
        let root = json!({ "params": { "location": "8a1969c9b397fff" } });
        let c = ctx(&root);
        let one = layout(json!([{ "cell": { "$root": "params.location" } }]));
        let tree = resolve(&one, &root, &c).unwrap();
        check::checked(&tree);
        assert_eq!(tree["p"], json!({ "height": "short", "zoom": 11 }));
        let pin = &tree["items"][0];
        let (lat, lng) = (pin["lat"].as_f64().unwrap(), pin["lng"].as_f64().unwrap());
        assert!(
            (lat - 52.37).abs() < 0.05 && (lng - 4.89).abs() < 0.05,
            "Amsterdam: {pin}"
        );
        assert_eq!(pin.get("open"), None);
        let given = layout(json!([{ "lat": 52.5, "lng": 13.4,
            "open": { "query": "a.b.c", "params": {} } }]));
        let tree = resolve(&given, &root, &c).unwrap();
        assert_eq!(
            tree["items"],
            json!([{ "lat": 52.5, "lng": 13.4,
                "open": { "call": { "name": "query", "args": { "method": "a.b.c", "params": {} } } } }])
        );
        let c = ctx(&Value::Null);
        assert_eq!(resolve(&one, &json!({}), &c), None);
    }

    /// Items from the view's scope by `$root`; none there, or not an array,
    /// as a List's.
    #[test]
    fn a_maps_items_are_found_as_a_lists_are() {
        let root = json!({ "places": [{ "lat": 1, "lng": 2, "uri": "at://did:plc:a/a.b.c/1" }], "one": 1 });
        let c = ctx(&root);
        let layout = |items: Value| {
            json!({ "component": "Map", "props": { "items": items,
                "lat": { "$": "lat" }, "lng": { "$": "lng" } } })
        };
        let tree = resolve(&layout(json!({ "$root": "places" })), &json!({}), &c).unwrap();
        assert_eq!(
            tree["items"][0]["open"],
            c.record_call("at://did:plc:a/a.b.c/1")
        );
        assert_eq!(
            resolve(&layout(json!({ "$root": "none" })), &json!({}), &c),
            None
        );
        assert_eq!(resolve(&layout(json!({ "$": "none" })), &root, &c), None);
        assert_eq!(
            resolve(&layout(json!({ "$": "one" })), &root, &c).unwrap()["p"]["message"],
            "items: no array"
        );
    }

    /// What is no place is the view's error: a cell that is no H3 cell,
    /// coordinates off the Earth.
    #[test]
    fn a_bad_place_is_an_error() {
        let root = json!({});
        let c = ctx(&root);
        let error = |props: Value| {
            resolve(&json!({ "component": "Map", "props": props }), &root, &c)
            .unwrap()["p"]["message"]
            .clone()
        };
        assert_eq!(
            error(json!({ "items": [{}], "cell": "not-a-cell" })),
            "cell: not-a-cell is no H3 cell"
        );
        assert_eq!(
            error(json!({ "items": [{}], "lat": 91, "lng": 0 })),
            "lat 91, lng 0: no place on Earth"
        );
        assert_eq!(
            error(json!({ "items": [{}], "lat": 0, "lng": 181 })),
            "lat 0, lng 181: no place on Earth"
        );
    }
}