~ 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
284 lines · 9.7 KB Raw History
//! A thread's posts around the one it is about, as the web renderer's
//! TreeNode and ChainNode walk them: a `Tree` of replies, each with its own
//! nested under it, and a `Chain` of the posts it replies to, oldest first.

use super::*;

/// A literal path prop: a Tree's `children`, a Chain's `next`.
fn path_prop(p: &Value, key: &str, says: &str) -> R<Path> {
    p[key]
        .as_str()
        .filter(|s| !s.is_empty())
        .and_then(Path::parse)
        .ok_or_else(|| Fail::Bad(format!("{key}: {says}")))
}

/// A `depth` prop: a whole number in `range`, else `fallback`.
fn depth(p: &Value, range: std::ops::RangeInclusive<f64>, fallback: usize) -> usize {
    p["depth"]
        .as_f64()
        .filter(|d| d.fract() == 0.0 && range.contains(d))
        .map_or(fallback, |d| d as usize)
}

/// An item: `{ open?, k, children? }`, the node's children drawn with it as
/// scope, opening what `open` names (nothing without one); None where it
/// draws nothing and has nothing under it, so it takes no room.
fn item(n: &Value, scope: &Value, nested: Vec<Value>, ctx: &Ctx) -> R<Option<Value>> {
    let open = opens(&n["props"]["open"], scope, ctx, None)?;
    let k = children(n, scope, ctx);
    if k.is_empty() && nested.is_empty() {
        return Ok(None);
    }
    let mut o = Map::new();
    if let Some(open) = open {
        o.insert("open".into(), open);
    }
    o.insert("k".into(), Value::Array(k));
    if !nested.is_empty() {
        o.insert("children".into(), Value::Array(nested));
    }
    Ok(Some(Value::Object(o)))
}

/// `{ c, p?, items }`, or nothing where no item draws: `p.line` "face"
/// where the node's thread line runs down its items' face column.
fn drawn(n: &Value, c: &str, items: Vec<Value>) -> R<Option<Value>> {
    if items.is_empty() {
        return Err(Fail::Missing);
    }
    let mut p = Map::new();
    if n["props"]["line"] == "face" {
        p.insert("line".into(), "face".into());
    }
    let mut out = make(c, p, vec![]);
    out["items"] = Value::Array(items);
    Ok(Some(out))
}

/// `Tree`: `items: [{ open?, k, children? }]`, an item's `children` its own
/// (the array at the `children` path) down to `depth` levels (1–8, 6 by
/// default).
pub(super) fn tree(n: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
    let p = &n["props"];
    let items = match value(&p["items"], scope, Value::is_array)? {
        Some(Value::Array(a)) => a,
        _ if value(&p["items"], scope, present)?.is_some() => return bad("items: no array"),
        _ => return Err(Fail::Missing),
    };
    if items.is_empty() {
        return Err(Fail::Missing);
    }
    let below = path_prop(p, "children", "the path to an item's children")?;
    let depth = depth(p, 1.0..=8.0, 6);
    drawn(n, "Tree", branch(n, items, &below, 1, depth, ctx)?)
}

/// One level of a tree, each item with the level under it.
fn branch(
    n: &Value,
    list: &[Value],
    below: &Path,
    level: usize,
    depth: usize,
    ctx: &Ctx,
) -> R<Vec<Value>> {
    let mut out = Vec::new();
    for at in list {
        let nested = match below.get(at) {
            Some(Value::Array(a)) if level < depth && !a.is_empty() => {
                branch(n, a, below, level + 1, depth, ctx)?
            }
            _ => Vec::new(),
        };
        if let Some(drawn) = item(n, at, nested, ctx)? {
            out.push(drawn);
        }
    }
    Ok(out)
}

/// `Chain`: `items: [{ open?, k }]`, from the object `from` names along its
/// `next` path, `depth` in all (1–20, 10 by default), oldest first.
pub(super) fn chain(n: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
    let p = &n["props"];
    let depth = depth(p, 1.0..=20.0, 10);
    let next = path_prop(p, "next", "the path to the next object")?;
    let mut walk = Vec::new();
    let mut at = Some(required("from", &p["from"], scope, Value::is_object)?);
    while let Some(found) = at {
        if !found.is_object() || walk.len() >= depth {
            break;
        }
        walk.push(found);
        at = next.get(found);
    }
    let mut items = Vec::new();
    for found in walk.into_iter().rev() {
        if let Some(drawn) = item(n, found, Vec::new(), ctx)? {
            items.push(drawn);
        }
    }
    drawn(n, "Chain", items)
}

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

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

    fn post(text: &str) -> Value {
        json!({ "post": { "uri": format!("at://did:plc:a/app.bsky.feed.post/{text}"), "text": text } })
    }

    fn template(c: &str, props: Value) -> Value {
        let mut n = json!({ "component": c, "props": props,
            "children": [{ "component": "Text", "props": { "value": { "$": "post.text" } } }] });
        n["props"]["open"] = json!({ "query": "app.bsky.feed.getPostThread",
            "params": { "uri": { "$": "post.uri" } } });
        n
    }

    fn texts(items: &Value) -> Vec<&str> {
        items
            .as_array()
            .unwrap()
            .iter()
            .map(|i| i["k"][0]["p"]["runs"][0]["text"].as_str().unwrap_or(""))
            .collect()
    }

    #[test]
    fn a_chain_walks_its_parents_and_draws_them_oldest_first() {
        let root = json!({});
        let c = ctx(&root);
        let mut thread = post("parent");
        thread["parent"] = post("grandparent");
        thread["parent"]["parent"] = json!({ "uri": "at://gone", "notFound": true });
        thread["parent"]["parent"]["parent"] = post("too far");
        let layout = template(
            "Chain",
            json!({ "from": { "$": "thread" }, "next": "parent", "depth": 4 }),
        );
        let scope = json!({ "thread": thread });
        let tree = resolve(&layout, &scope, &c).unwrap();
        check::checked(&tree);
        assert_eq!(
            texts(&tree["items"]),
            ["too far", "grandparent", "parent"],
            "the post not found takes no room"
        );
        assert_eq!(
            tree["items"][2]["open"]["call"]["args"]["params"]["uri"],
            "at://did:plc:a/app.bsky.feed.post/parent"
        );
        let shallow = template(
            "Chain",
            json!({ "from": { "$": "thread" }, "next": "parent", "depth": 2 }),
        );
        assert_eq!(
            texts(&resolve(&shallow, &scope, &c).unwrap()["items"]),
            ["grandparent", "parent"]
        );
        let top = json!({ "thread": null });
        assert!(resolve(&layout, &top, &c).is_none(), "no parent: nothing");
    }

    #[test]
    fn a_tree_nests_replies_to_its_depth_keeping_a_missing_reply_with_replies() {
        let root = json!({});
        let c = ctx(&root);
        let mut gone = json!({ "uri": "at://gone", "notFound": true });
        gone["replies"] = json!([post("under the gone one")]);
        let mut first = post("first");
        let mut deep = post("deep");
        deep["replies"] = json!([post("too deep")]);
        first["replies"] = json!([deep]);
        let items = json!([first, gone, { "notFound": true }]);
        let layout = template(
            "Tree",
            json!({ "items": { "$": "replies" }, "children": "replies", "depth": 2 }),
        );
        let scope = json!({ "replies": items });
        let tree = resolve(&layout, &scope, &c).unwrap();
        check::checked(&tree);
        let items = &tree["items"];
        assert_eq!(
            items.as_array().unwrap().len(),
            2,
            "a blank leaf is left out"
        );
        assert_eq!(texts(&items[0]["children"]), ["deep"]);
        assert!(
            items[0]["children"][0].get("children").is_none(),
            "past depth: not drawn"
        );
        assert_eq!(items[1]["k"], json!([]));
        assert_eq!(texts(&items[1]["children"]), ["under the gone one"]);
        assert!(items[1].get("open").is_none());
    }

    #[test]
    fn a_tree_with_no_children_path_is_an_error_only_when_it_has_items() {
        let root = json!({});
        let c = ctx(&root);
        let layout = template("Tree", json!({ "items": { "$": "replies" } }));
        assert!(resolve(&layout, &json!({ "replies": [] }), &c).is_none());
        let scope = json!({ "replies": [post("a")] });
        let error = resolve(&layout, &scope, &c).unwrap();
        check::checked(&error);
        assert_eq!(error["c"], "Error");
    }

    #[test]
    fn a_tree_of_no_array_is_an_error_and_of_blank_items_or_none_draws_nothing() {
        let root = json!({});
        let c = ctx(&root);
        let layout = template(
            "Tree",
            json!({ "items": { "$": "replies" }, "children": "replies" }),
        );
        let error = resolve(&layout, &json!({ "replies": "many" }), &c).unwrap();
        check::checked(&error);
        assert_eq!(
            error["p"],
            json!({ "component": "Tree", "message": "items: no array" })
        );
        assert!(resolve(&layout, &json!({}), &c).is_none());
        let blank = json!({ "replies": [{ "notFound": true }] });
        assert!(
            resolve(&layout, &blank, &c).is_none(),
            "items that draw nothing take no room"
        );
    }

    #[test]
    fn a_line_down_the_faces_is_said() {
        let root = json!({});
        let c = ctx(&root);
        let layout = template(
            "Chain",
            json!({ "from": { "$": "thread" }, "next": "parent", "line": "face" }),
        );
        let tree = resolve(&layout, &json!({ "thread": post("one") }), &c).unwrap();
        check::checked(&tree);
        assert_eq!(tree["p"], json!({ "line": "face" }));
        assert_eq!(texts(&tree["items"]), ["one"]);
    }
}