chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.5.0 Latest 5 packages
0
0
//! A view resolved: its layout drawn against its data on the server, as a
//! tree a client draws with nothing left to interpret (`_meta.ui`). Every
//! binding is read here, every URL held to the view's origins, every
//! node whose required data is absent left out, every `open` made the tool
//! call it opens, a Bluesky post's embed and feed context read into what
//! they show. A client draws the components, makes the calls it is handed,
//! and stamps `{"$now": true}` when it writes. The view's own rules
//! (bindings, which URLs load, what is Missing) are read here, once.
//!
//! Every `list_records`, `get_record` and `query` result carries one, a
//! view's or the generic drawing of an answer with none; it is how views
//! are drawn. A record opened from an inline view's drawing opens with
//! that view (`Ctx::record_call`).
//!
//! The tree (`v` 1):
//!
//! - `{ v, trusted, title?, root, next?, report?, head?, hero? }`: `trusted`
//! whether the view is a bundled one (an untrusted view's actions ask
//! before they write); `title` the view's description; `next` the call
//! for the page after, whose tree's `page` list's items go after these;
//! `report` `{ feed, seen }`, for a feed told what is done with its items
//! (`seen`: whether seen items are told, a signed-in call's alone);
//! `head` what a page drawing it says in its HTML head, a trusted view's
//! mode's `head` read (`head::resolve`); `hero` the src of the first
//! picture it draws large (`hero`), which a page loads first.
//! - A node is `{ c, p?, k?, fallback? }`: its component, its props, its
//! children, and what a client that doesn't know its component draws in
//! its place, where its view gave one. `{ c: "Error", p: { component,
//! message } }` stands where a component could not draw. A Stack, Pane
//! or Bar gated on the kit is marked `$kit` (`kit::GATES`) until the tree
//! is fitted to the kit drawing it (`kit::fit`), which no client sees.
//! - An open is `{ call: { name, args } }`, a tool call, or `{ url }`, an
//! http(s) page.
//! - Text is `runs`: `[{ text, link?, actor?, tag?, bold?, italic?, code?,
//! strike?, underline?, highlight? }]`, `link` a page, `actor` a DID to
//! open; each formatting flag present only when true.
//! - A `Text` or `RichText` longer than its `clamp` is cut here (`clamp`):
//! `shownRuns` (markdown's, `shownBlocks`) what it shows until opened,
//! with a "Show more"; absent where it fits.
//! - A picture is `{ src, fallback }`, or null where its value is no usable
//! source (a placeholder is drawn).
//! - `List`: `p: { style, title?, empty?, page? }`, `items: [{ open?,
//! report?, k }]`; `report` the item as its feed is told of it (`{ item,
//! feedContext?, reqId? }`), on a seen and on its open. The page list a
//! page more grows is any node with `p.page` and `items`, whatever its `c`.
//! A literal item's `{"$root": path}` values are read before it is drawn,
//! and its own `open` opens it in place of the List's.
//! - `Tabs`: `p: { items: [{ label, open, selected }] }`, `selected` the
//! one whose call is the one drawn now (`drawn_now`); a client replaces
//! the call it draws with a tab's, in place, never opening another.
//! - `Icon`: `p: { name, tint }`, each one of the catalog's words.
//! - `Stat`: `p: { value, icon?, label?, more? }`, `value` a number or an
//! array's length, `more` (true) where there are more than it counts.
//! - `Action`: `p: { label, done, icon?, key, create?: { collection,
//! record }, delete?: { uri }, interaction?: { event, report }, existing? }`;
//! `key` what it is, for state kept as it is drawn again.
//! - `FeedContext`, `Embed`: what they show, read (see `feed_context`,
//! `embed`); an embed's raw quote of a post is `{ kind: "post", uri,
//! quote?, fallback }`, `quote` the post as a `quote` embed once the tool
//! fetched it (`fill_posts`), else `fallback`, a compact card.
//! - `Header`, `Profile`: their words and pictures, read (see `header`,
//! `profile`); a profile's `open` the account its handle names.
//! - `Tree`, `Chain`: `items: [{ open?, k, children? }]`, a tree's
//! `children` its nested items, a chain's oldest first.
//! - `Fields`: a record's fields read through its lexicon (see `fields`);
//! `Json`: `p: { value, open }`, a value as it is.
//! - `RichText`: `p: { runs | blocks, clamp?, shownRuns? | shownBlocks?,
//! style? }`, blocks for markdown or gfm, `style` only as muted, with
//! runs; `Document`:
//! `p: { look, blocks }`, `look` how its blocks are drawn (leaflet,
//! markdown or plain). Blocks as `document` reads them; in their runs,
//! `alt` marks a picture's alt text; a `bskyPost` block's `quote` the
//! post as `embed` draws a quoted one, once the tool fetched it
//! (`fill_posts`).
//!
//! Its lexicon, `schemas/place.hud.ui.json`, describes all of
//! it, each component's props as `#<component>Props`; `check` holds a tree
//! to it.
use crate::view::Path;
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
mod check;
mod clamp;
mod diff;
mod document;
mod embed;
mod feed;
mod fields;
pub mod head;
mod layout;
mod map;
mod marks;
mod media;
mod thread;
pub use check::check;
pub use fields::record_fields;
/// An app's own page's Markdown as blocks, its links to the app's paths
/// opening them on its site, `https://{site}` (`document::page`).
pub fn page_blocks(markdown: &str, site: &str) -> Vec<Value> {
document::page(markdown, site)
}
/// The tree of an app's own page (`view::Page`): its title in the
/// screen's bar over its text, as `RichText` draws markdown; its head
/// its title on the app's name, its description and its path, the page's
/// canonical URL on the app's site.
pub fn page_tree(page: &crate::view::Page) -> Value {
let mut head = json!({ "title": format!("{} - {}", page.title, page.app),
"canonical": page.path });
if let Some(d) = &page.description {
head["description"] = d.as_str().into();
}
json!({ "v": 1, "trusted": true, "title": page.title, "head": head,
"root": { "c": "Stack", "p": { "gap": "md" }, "k": [
{ "c": "Bar", "p": { "title": page.title } },
{ "c": "RichText", "p": { "blocks": page.blocks } } ] } })
}
/// Whether a node is a Bluesky post left for the tool to fetch: a
/// document's `bskyPost` block, or an embed's raw quote (`post`), each
/// `{ kind, uri, quote?, fallback }`.
fn unfetched_post(o: &Map<String, Value>) -> Option<&str> {
let kind = o.get("kind").and_then(Value::as_str)?;
if (kind != "bskyPost" && kind != "post") || !o.contains_key("fallback") {
return None;
}
o.get("uri").and_then(Value::as_str)
}
/// The at-uris of the Bluesky posts a tree shows unfetched
/// (`unfetched_post`), each once, in the order they show.
pub fn post_uris(tree: &Value) -> Vec<String> {
fn walk(v: &Value, out: &mut Vec<String>) {
match v {
Value::Object(o) => {
if let Some(uri) = unfetched_post(o)
&& !out.iter().any(|u| u == uri)
{
out.push(uri.to_string());
}
o.values().for_each(|v| walk(v, out));
}
Value::Array(a) => a.iter().for_each(|v| walk(v, out)),
_ => {}
}
}
let mut out = Vec::new();
walk(tree, &mut out);
out
}
/// Whether `form` names a form a screen opens at (`compose`): true, its
/// first, or a Compose's label, 1 to 64 characters.
pub fn is_compose(form: &Value) -> bool {
match form {
Value::Bool(b) => *b,
Value::String(s) => (1..=64).contains(&s.chars().count()),
_ => false,
}
}
/// The Compose a screen opens at (`compose`: true for the first, else the
/// one of that label) marked `open`, so the renderers open its form at
/// once: only one drawn as the screen itself, its children's `k` in order,
/// never one over an item (a List's, a Slides' picture's) nor a Menu's
/// row; so a story screen opens its Add only where it has no pictures.
/// Whether one was.
pub fn open_compose(tree: &mut Value, form: &Value) -> bool {
match tree["c"].as_str() {
Some("Compose") if form.as_bool() == Some(true) || tree["p"]["label"] == *form => {
tree["p"]["open"] = true.into();
true
}
Some("Menu") => false,
_ => match tree.get_mut("k").and_then(Value::as_array_mut) {
Some(k) => k.iter_mut().any(|child| open_compose(child, form)),
None => false,
},
}
}
/// How wide a view's answer is drawn (`_meta.ui.measure`): the measure of
/// the first of its `measureWhen` whose `when` the scope holds something at,
/// else its `measure`. So one view of a query draws some answers wide and
/// the rest at the reading width, decided from the call's params: Grain's
/// feed of a camera's galleries wide, a home feed not.
pub fn measure<'a>(doc: &'a Value, scope: &Value) -> Option<&'a str> {
doc["measureWhen"]
.as_array()
.into_iter()
.flatten()
.find(|case| {
case["when"]
.as_str()
.and_then(Path::parse)
.is_some_and(|at| holds(&at, scope))
})
.map_or(&doc["measure"], |case| &case["measure"])
.as_str()
}
/// The first picture a tree draws large, in the order it draws them: what
/// a page loads first (`_meta.ui.hero`). An `Image` but one drawn small (an
/// avatar, an icon, a thumbnail), the first item with a picture of a
/// `Gallery`, `Slides` or `Covers`, or a `Profile`'s banner, else its
/// avatar: its src, and a gallery photo's or a slide's sizes (`srcset`)
/// where it has them, which a page preloads at the tree's width; a cover is
/// drawn a grid's tile, narrower than that, so a cover that is the hero is
/// preloaded and drawn at its src alone. A
/// `List` scrolled sideways (a `strip` or a `shelf`, a photo app's
/// stories over its feed) draws each item small, so nothing in it is the
/// hero. None where it draws none.
pub fn hero(tree: &Value) -> Option<(&str, Option<&str>)> {
fn src(picture: &Value) -> Option<(&str, Option<&str>)> {
picture["src"].as_str().map(|s| (s, None))
}
match tree {
Value::Object(o) => {
let p = &tree["p"];
let small = matches!(
p["size"].as_str(),
Some("avatar" | "face" | "icon" | "thumb")
);
let own = match o.get("c").and_then(Value::as_str) {
Some("List") if matches!(p["style"].as_str(), Some("strip" | "shelf")) => {
return None;
}
Some("Image") if !small => src(&p["src"]),
Some(c @ ("Gallery" | "Slides" | "Covers")) => {
let sized = c != "Covers";
tree["items"].as_array().and_then(|items| {
items.iter().find_map(|i| {
let set = i["srcset"].as_str().filter(|_| sized);
src(&i["src"]).map(|(s, _)| (s, set))
})
})
}
Some("Profile") => src(&p["banner"]).or_else(|| src(&p["avatar"])),
_ => None,
};
own.or_else(|| o.values().find_map(hero))
}
Value::Array(a) => a.iter().find_map(hero),
_ => None,
}
}
/// A tree's `hero` and `heroSrcset` set from its root as it is now
/// (`hero`): none where it draws no picture large.
pub fn set_hero(tree: &mut Value) {
let hero = hero(&tree["root"]).map(|(src, set)| (src.to_string(), set.map(str::to_string)));
let o = tree.as_object_mut().expect("a tree is an object");
o.remove("hero");
o.remove("heroSrcset");
if let Some((src, set)) = hero {
o.insert("hero".into(), src.into());
o.extend(set.map(|set| ("heroSrcset".to_string(), set.into())));
}
}
/// The authority (a DID or a handle) and record key of a post's at-uri.
fn post_parts(uri: &str) -> Option<(&str, &str)> {
let rest = uri.strip_prefix("at://")?;
let (authority, rest) = rest.split_once('/')?;
let rkey = rest.strip_prefix("app.bsky.feed.post/")?;
(!authority.is_empty() && !rkey.is_empty() && !rkey.contains('/')).then_some((authority, rkey))
}
/// The postView among `posts` that a post's at-uri asked for: the AppView
/// names posts by DID, so one asked for by handle is its author's handle
/// and its record key.
fn answered<'a>(uri: &str, posts: &'a [Value]) -> Option<&'a Value> {
let (authority, rkey) = post_parts(uri)?;
posts.iter().find(|post| {
let Some((did, key)) = post["uri"].as_str().and_then(post_parts) else {
return false;
};
let handle = post["author"]["handle"].as_str().unwrap_or("");
key == rkey && (did == authority || handle.eq_ignore_ascii_case(authority))
})
}
/// Each unfetched post of a tree (`unfetched_post`) that is among `posts`
/// (the AppView's postViews, as `answered` finds them) given its `quote`,
/// read as `ctx` reads an embed's quoted post; one not among them keeps
/// its fallback alone.
pub fn fill_posts(tree: &mut Value, posts: &[Value], ctx: &Ctx) {
match tree {
Value::Object(o) => {
if let Some(post) = unfetched_post(o).and_then(|u| answered(u, posts))
&& let Some(quote) = embed::post_quote(post, ctx)
{
o.insert("quote".into(), quote);
}
o.values_mut().for_each(|v| fill_posts(v, posts, ctx));
}
Value::Array(a) => a.iter_mut().for_each(|v| fill_posts(v, posts, ctx)),
_ => {}
}
}
/// What a view's drawing is resolved with.
pub struct Ctx<'a> {
/// The https origins its string URLs may load (a trusted view's).
pub origins: &'a [String],
/// `(from, to)`: a picture drawn small whose URL starts with `from` loads from `to` (a trusted view's).
pub thumbnails: Vec<(String, String)>,
pub trusted: bool,
/// The view's own scope, for `{"$root": path}`.
pub root: &'a Value,
/// The paths in an item to its uri, feedContext and reqId, for a feed
/// told what is done with its items.
pub report: Option<ReportPaths<'a>>,
/// An inline view's collection and document: a record of that
/// collection opens with it, for its record part.
pub inline: Option<(&'a str, &'a Value)>,
/// The lexicon of the records' collection (`{ nsid, doc, refs }`), for `Fields`.
pub lexicon: Option<&'a Value>,
/// The verified handle of each DID the data names, for `Fields`' accounts.
pub handles: Option<&'a Value>,
/// The query joins, by `as`, whose answer is the page's, as the records
/// are: a records view's that read a page's records, an app page's
/// that pages it. A listing of one's answer is the page list (`paged`).
pub paged: Vec<&'a str>,
/// The query joins whose listings page themselves (`own_next`).
pub more: More<'a>,
/// The signed-in person's DID, when the call was made signed in: their
/// own messages are `mine`, and only then may they send.
pub me: Option<&'a str>,
/// The app a bundled view draws, where it has a page (`describe_app`):
/// an account named in its drawing opens there, as the person's page
/// in the app they are being read in; else their profile, all apps.
pub people: Option<String>,
}
/// The query joins whose listings page themselves, apart from the tree's
/// page more: a List or Covers drawing one's answer carries the call for
/// its page after (`p.next`), and grows by what that answers alone.
#[derive(Default)]
pub struct More<'a> {
/// Each such join, by `as`, with the call for its page after: those
/// whose answer has a cursor.
pub next: Vec<(&'a str, Value)>,
/// Drawing one join's page more alone, its `as`: a listing of it draws
/// its items alone (no `first` row, no blocks at places), and says its
/// `next` even where there is none, as null, so the page more is found
/// in the tree (`tools`' `more_ui`).
pub alone: Option<&'a str>,
}
impl Ctx<'_> {
/// The call that opens a record: `get_record`, with the inline view
/// when the record is of the collection it draws; else the query a
/// bundled view draws it as, where that needs only its at-uri (a
/// gallery opened from anywhere is the one tile its feed opens too).
fn record_call(&self, uri: &str) -> Value {
let collection = uri.strip_prefix("at://").and_then(|r| r.split('/').nth(1));
match self.inline {
Some((c, doc)) if collection == Some(c) => {
call("get_record", json!({ "uri": uri, "view": doc }))
}
_ => match crate::view::routed_call(uri) {
Some(args) => call("query", args),
None => call("get_record", json!({ "uri": uri })),
},
}
}
/// The call that opens an account the drawing names: its page in the
/// app being read (`people`), else its profile across apps.
pub(super) fn actor_call(&self, actor: &str) -> Value {
match &self.people {
Some(domain) => call("describe_app", json!({ "domain": domain, "actor": actor })),
None => call("describe_repo", json!({ "actor": actor })),
}
}
/// What a #tag in the tree's text opens: its app's page view's `tag`
/// (a search for it in that app), read from `{ tag, hashtag }` (the
/// word, and the word after a #); none where the app has no page or
/// says nothing of tags.
fn tag_call(&self, tag: &str) -> Option<Value> {
let view = crate::view::for_domain(self.people.as_deref()?)?;
let page = view.page.as_ref()?;
let scope = json!({ "tag": tag, "hashtag": format!("#{tag}") });
opens(page.tag.as_ref()?, &scope, self, None).ok().flatten()
}
}
pub struct ReportPaths<'a> {
pub item: &'a Path,
pub feed_context: Option<&'a Path>,
pub req_id: Option<&'a Path>,
}
/// Why a node draws nothing (its data is absent), or an error in its place.
enum Fail {
Missing,
Bad(String),
}
type R<T> = Result<T, Fail>;
fn bad<T>(m: impl Into<String>) -> R<T> {
Err(Fail::Bad(m.into()))
}
/// The tree of a layout over its scope; None when its top node draws nothing.
pub fn resolve(layout: &Value, scope: &Value, ctx: &Ctx) -> Option<Value> {
match with_fors(layout) {
Some(layout) => node(&layout, scope, ctx),
None => node(layout, scope, ctx),
}
}
/// The components whose children are drawn in their own scope, so a
/// Compose's `for` finds the one it names among them too.
const SAME_SCOPE: &[&str] = &["Stack", "Row", "Split", "Menu", "Bar", "Panes", "Pane"];
/// A Compose `for` another: where it sits (the indexes of the children
/// down to it), the label it names, and the props of the first Compose of
/// that label drawn in its scope, if there is one.
pub type For<'a> = (Vec<usize>, &'a str, Option<&'a Map<String, Value>>);
/// Each Compose `for` another in a layout, with the one it names: the
/// first of that label among the nodes drawn in the same scope, down
/// through those whose children share it (`SAME_SCOPE`); a List's items,
/// and any other node's children, are a scope of their own.
pub fn fors(layout: &Value) -> Vec<For<'_>> {
let mut out = Vec::new();
scope_fors(vec![(Vec::new(), layout)], &mut out);
out
}
/// One scope's nodes, read for `fors`, and the scopes below them.
fn scope_fors<'a>(nodes: Vec<(Vec<usize>, &'a Value)>, out: &mut Vec<For<'a>>) {
let mut named = Vec::new();
let mut wanting = Vec::new();
let mut inner = Vec::new();
for (at, n) in nodes {
gather_fors(n, at, &mut named, &mut wanting, &mut inner);
}
for (at, label) in wanting {
let form = named.iter().find(|(l, _)| *l == label).map(|(_, p)| *p);
out.push((at, label, form));
}
for nodes in inner {
scope_fors(nodes, out);
}
}
/// A node of a scope: a Compose named by its label (the first of each)
/// or `for` another; its children in the same scope where it shares it,
/// else one of their own.
#[allow(clippy::type_complexity)]
fn gather_fors<'a>(
n: &'a Value,
at: Vec<usize>,
named: &mut Vec<(&'a str, &'a Map<String, Value>)>,
wanting: &mut Vec<(Vec<usize>, &'a str)>,
inner: &mut Vec<Vec<(Vec<usize>, &'a Value)>>,
) {
let c = n["component"].as_str().unwrap_or("");
let p = &n["props"];
if c == "Compose" {
match (p["for"].as_str(), p["label"].as_str(), p.as_object()) {
(Some(label), _, _) => wanting.push((at.clone(), label)),
(None, Some(label), Some(props)) if !named.iter().any(|(l, _)| *l == label) => {
named.push((label, props));
}
_ => {}
}
}
let children: Vec<_> = n["children"]
.as_array()
.into_iter()
.flatten()
.enumerate()
.map(|(i, child)| ([at.as_slice(), &[i]].concat(), child))
.collect();
if SAME_SCOPE.contains(&c) {
for (at, child) in children {
gather_fors(child, at, named, wanting, inner);
}
} else if !children.is_empty() {
inner.push(children);
}
}
/// Whether a layout has a Compose `for` another anywhere.
fn has_for(n: &Value) -> bool {
(n["component"] == "Compose" && n["props"]["for"].is_string())
|| n["children"]
.as_array()
.is_some_and(|k| k.iter().any(has_for))
}
/// The layout with each Compose `for` another made that one, drawn as
/// its own `style`, with its own `signIn`, its own label its words
/// (`prompt`): the same form, its draft kept by the same key. None where
/// it has none, drawn as it is. One naming none in its scope is left, and
/// draws nothing.
fn with_fors(layout: &Value) -> Option<Value> {
if !has_for(layout) {
return None;
}
let mut out = layout.clone();
for (at, _, form) in fors(layout) {
let Some(form) = form else { continue };
let n = at.iter().fold(&mut out, |n, i| &mut n["children"][*i]);
let own = n["props"].take();
let mut p = form.clone();
p.remove("style");
p.remove("signIn");
p.insert("prompt".into(), own["label"].clone());
p.extend(
["style", "signIn"]
.into_iter()
.filter_map(|k| own.get(k).map(|v| (k.to_string(), v.clone()))),
);
n["props"] = Value::Object(p);
}
Some(out)
}
/// A node drawn, an error in its place, or nothing.
fn node(n: &Value, scope: &Value, ctx: &Ctx) -> Option<Value> {
let c = n["component"].as_str().unwrap_or("");
let p = &n["props"];
let drawn = match c {
"Stack" => gated(p, scope, ctx.me).map(|on| {
on.then(|| container(n, scope, ctx, &[("gap", "md")]))
.flatten()
}),
"Row" => Ok(container(n, scope, ctx, &[("gap", "sm")])),
"Text" => text(p, scope),
"RichText" => rich_text(p, scope, ctx),
"Time" => time(p, scope),
"Image" => image(p, scope, ctx),
"Link" => link(p, scope, ctx),
"Stat" => stat(p, scope),
"Tabs" => tabs(p, scope, ctx),
"Search" => search(p, scope, ctx),
"Toggle" => toggle(p, scope, ctx),
"Choice" => choice(p, scope, ctx),
"Menu" => Ok(menu(n, scope, ctx)),
"Bar" => bar(n, scope, ctx),
"Panes" => Ok(panes(n, scope, ctx)),
"Accounts" => Ok(Some(make("Accounts", Map::new(), children(n, scope, ctx)))),
"Split" => Ok(split(n, scope, ctx)),
"Pane" => gated(p, scope, ctx.me).map(|on| on.then(|| pane(n, scope, ctx)).flatten()),
"Icon" => marks::icon(p, scope),
"List" => list(n, scope, ctx),
"Messages" => messages(n, scope, ctx),
"Action" => action(p, scope, ctx),
"Compose" => compose(p, scope, ctx),
"FeedContext" => feed::feed_context(n, scope, ctx),
"Embed" => embed::embed_node(p, scope, ctx),
"State" => marks::state(p, scope),
"Badge" => marks::badge(p, scope),
"Label" => marks::label(p, scope),
"Diff" => diff::diff(p, scope),
"Fields" => fields::fields_node(p, scope, ctx),
"Json" => fields::json_node(p, scope),
"Header" => layout::header(p, scope, ctx),
"Profile" => layout::profile(p, scope, ctx),
"Tree" => thread::tree(n, scope, ctx),
"Chain" => thread::chain(n, scope, ctx),
"Gallery" => media::gallery(p, scope, ctx),
"Slides" => media::slides(n, scope, ctx),
"Covers" => media::covers(p, scope, ctx),
"Faces" => media::faces(p, scope, ctx),
"ContentWarning" => media::content_warning(n, scope, ctx),
"Player" => media::player(p, scope, ctx),
"Map" => map::map(p, scope, ctx),
"Document" => document::document(p, scope, ctx),
other => bad(format!("{other} is not resolved")),
};
match drawn {
Ok(Some(mut v)) => {
marked(&mut v, n, scope, ctx);
Some(v)
}
Ok(None) | Err(Fail::Missing) => None,
Err(Fail::Bad(message)) => {
Some(json!({ "c": "Error", "p": { "component": c, "message": message } }))
}
}
}
/// A node drawn, marked for the kit that will draw it (`kit::fit`): a
/// Stack's, Pane's or Bar's gates on the kit (`kit::gates`), and its
/// layout's `fallback`, drawn over the same scope, where that draws.
fn marked(v: &mut Value, n: &Value, scope: &Value, ctx: &Ctx) {
let gates = match n["component"].as_str() {
Some("Stack" | "Pane" | "Bar") => crate::kit::gates(&n["props"]),
_ => Vec::new(),
};
if !gates.is_empty() {
v[crate::kit::GATES] = gates.into();
}
if let Some(fallback) = n.get("fallback").and_then(|f| node(f, scope, ctx)) {
v["fallback"] = fallback;
}
}
/// A node's children drawn against a scope, those that draw nothing left out.
fn children(n: &Value, scope: &Value, ctx: &Ctx) -> Vec<Value> {
n["children"]
.as_array()
.map(|k| k.iter().filter_map(|c| node(c, scope, ctx)).collect())
.unwrap_or_default()
}
/// `{c, p, k}`, without an empty `p` or `k`.
fn make(c: &str, p: Map<String, Value>, k: Vec<Value>) -> Value {
let mut o = Map::new();
o.insert("c".into(), c.into());
if !p.is_empty() {
o.insert("p".into(), Value::Object(p));
}
if !k.is_empty() {
o.insert("k".into(), Value::Array(k));
}
Value::Object(o)
}
/// Stack and Row: their words as given (gap, align, wrap, a Stack's
/// measure), their children
/// drawn; one whose children all draw nothing is left out.
fn container(n: &Value, scope: &Value, ctx: &Ctx, defaults: &[(&str, &str)]) -> Option<Value> {
let k = children(n, scope, ctx);
if k.is_empty() {
return None;
}
let mut p = Map::new();
for (key, fallback) in defaults {
p.insert(
(*key).into(),
n["props"][*key].as_str().unwrap_or(fallback).into(),
);
}
for key in ["align", "wrap", "measure"] {
if let Some(w) = n["props"][key].as_str() {
p.insert(key.into(), w.into());
}
}
Some(make(n["component"].as_str().unwrap_or("Stack"), p, k))
}
/// `Bar`, where its gate holds: its buttons, and the screen's title, its
/// words one after another (none where one of them resolves to nothing,
/// so a hashtag's title is never a bare #); a bar with neither draws
/// nothing.
fn bar(n: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
if !gated(&n["props"], scope, ctx.me)? {
return Ok(None);
}
let mut title = Some(String::new());
for part in n["props"]["title"].as_array().into_iter().flatten() {
let found = text_of(part, scope)?;
title = title.zip(found).map(|(t, s)| t + &s);
}
let title = title.filter(|t| !t.is_empty());
let k = children(n, scope, ctx);
if k.is_empty() && title.is_none() {
return Ok(None);
}
let mut p = Map::new();
if let Some(t) = title {
p.insert("title".into(), t.into());
}
Ok(Some(make("Bar", p, k)))
}
/// `Menu`: its rows; a Stack among them, however deep, drawn where its gate
/// holds (one's own gallery's Delete, someone else's Report, Mute where
/// they are not muted), gives its rows in its place, each gated on the kit
/// as it was and as every Stack around it was (`kit::GATES`), so a kit that
/// draws a menu's rows alone (iOS's, Android's) has them all.
fn menu(n: &Value, scope: &Value, ctx: &Ctx) -> Option<Value> {
let mut out = container(n, scope, ctx, &[("label", "More")])?;
let mut rows = Vec::new();
for row in out["k"].as_array().into_iter().flatten() {
menu_rows(row, &[], &mut rows);
}
out["k"] = Value::Array(rows);
Some(out)
}
/// A menu's row, or a Stack's rows through every Stack in it, each gated on
/// the kit as it was and as the Stacks around it were (`gates`).
fn menu_rows(row: &Value, gates: &[Value], rows: &mut Vec<Value>) {
let mut all = row[crate::kit::GATES]
.as_array()
.cloned()
.unwrap_or_default();
all.extend(gates.iter().cloned());
if row["c"] == "Stack" {
for r in row["k"].as_array().into_iter().flatten() {
menu_rows(r, &all, rows);
}
return;
}
let mut r = row.clone();
if !all.is_empty() {
r[crate::kit::GATES] = all.into();
}
rows.push(r);
}
/// `Split`: its two children and its words (side where it is start, main
/// and aside as given); one child drawing nothing leaves the other alone,
/// both nothing.
fn split(n: &Value, scope: &Value, ctx: &Ctx) -> Option<Value> {
let mut k = children(n, scope, ctx);
if k.len() < 2 {
return k.pop();
}
let mut p = Map::new();
if n["props"]["side"] == "start" {
p.insert("side".into(), "start".into());
}
for key in ["main", "aside"] {
if let Some(w) = n["props"][key].as_str() {
p.insert(key.into(), w.into());
}
}
Some(make("Split", p, k))
}
/// A grid's words, as given: the narrowest its tiles go and the most across.
fn grid_words(p: &Value, o: &mut Map<String, Value>) {
if let Some(min) = p["min"].as_str() {
o.insert("min".into(), min.into());
}
if let Some(columns) = p["columns"].as_u64() {
o.insert("columns".into(), columns.into());
}
}
/// `Panes`: the Panes among its children drawn (those whose gate holds and
/// that have something to show); none, nothing.
fn panes(n: &Value, scope: &Value, ctx: &Ctx) -> Option<Value> {
let k: Vec<Value> = children(n, scope, ctx)
.into_iter()
.filter(|c| c["c"] == "Pane")
.collect();
(!k.is_empty()).then(|| make("Panes", Map::new(), k))
}
/// `Pane`: its label, icon and children; with no children, nothing.
fn pane(n: &Value, scope: &Value, ctx: &Ctx) -> Option<Value> {
let k = children(n, scope, ctx);
if k.is_empty() {
return None;
}
let p = &n["props"];
let mut o = Map::new();
o.insert("label".into(), str_at(p, "label").unwrap_or("More").into());
if let Some(icon) = p["icon"].as_str() {
o.insert("icon".into(), icon.into());
}
Some(make("Pane", o, k))
}
// Bindings, as bind.ts reads them.
fn is_binding(v: &Value) -> bool {
v.as_object()
.is_some_and(|o| o.len() == 1 && o.contains_key("$"))
}
fn is_root_binding(v: &Value) -> bool {
v.as_object()
.is_some_and(|o| o.len() == 1 && o.contains_key("$root"))
}
/// Whether a listing's items are the page's, which a page more grows: bound
/// to `items` or `records`, or to the answer of a query join that is the
/// page's (`ctx.paged`).
fn paged(p: &Value, scope: &Value, ctx: &Ctx) -> bool {
let bound = p["items"]["$"].as_str();
if matches!(bound, Some("items" | "records")) {
return true;
}
joined(p, scope, ctx).is_some_and(|name| ctx.paged.contains(&name))
}
/// The query join whose answer a listing's items are, by `as`: bound by
/// `{"$root": "joins.<as>…"}` or, in the root scope itself, `{"$":
/// "joins.<as>…"}`.
fn joined<'p>(p: &'p Value, scope: &Value, ctx: &Ctx) -> Option<&'p str> {
let path = match p["items"]["$root"].as_str() {
Some(path) => path,
None => p["items"]["$"]
.as_str()
.filter(|_| std::ptr::eq(scope, ctx.root))?,
};
let rest = path.strip_prefix("joins.")?;
rest.split('.').next()
}
/// The call for the page after a listing's own items, where they are a
/// query join's answer that pages itself (`ctx.more`) and no `limit` cuts
/// them: null at its end, in that join's page more (`More::alone`).
fn own_next(p: &Value, scope: &Value, ctx: &Ctx) -> Option<Value> {
if p.get("limit").is_some() {
return None;
}
let name = joined(p, scope, ctx)?;
match ctx.more.next.iter().find(|(n, _)| *n == name) {
Some((_, call)) => Some(call.clone()),
None => (ctx.more.alone == Some(name)).then_some(Value::Null),
}
}
fn paths(b: &Value) -> R<Vec<Path>> {
let list: Vec<&Value> = match &b["$"] {
Value::Array(a) => a.iter().collect(),
v => vec![v],
};
list.into_iter()
.map(|p| {
p.as_str()
.and_then(Path::parse)
.ok_or_else(|| Fail::Bad(format!("unknown path syntax {p}")))
})
.collect()
}
fn present(v: &Value) -> bool {
!v.is_null()
}
/// A prop's value: a literal as it is, a binding as the first of its paths
/// that holds something `usable` says yes to.
fn value<'a>(
prop: &'a Value,
scope: &'a Value,
usable: impl Fn(&Value) -> bool,
) -> R<Option<&'a Value>> {
if prop.is_null() {
return Ok(None);
}
if !is_binding(prop) {
return Ok(usable(prop).then_some(prop));
}
Ok(paths(prop)?
.iter()
.find_map(|p| p.get(scope).filter(|v| usable(v))))
}
/// A required prop: nothing there is Missing, something unusable an error.
fn required<'a>(
name: &str,
prop: &'a Value,
scope: &'a Value,
usable: impl Fn(&Value) -> bool,
) -> R<&'a Value> {
if let Some(v) = value(prop, scope, &usable)? {
return Ok(v);
}
if value(prop, scope, present)?.is_some() {
return bad(format!("{name}: not usable"));
}
Err(Fail::Missing)
}
/// A prop as text: a string, or a number written out.
fn text_of(prop: &Value, scope: &Value) -> R<Option<String>> {
Ok(value(prop, scope, |v| v.is_string() || v.is_number())?.map(write))
}
/// A string as it is, a number or a boolean written out, anything else as
/// nothing.
fn write(v: &Value) -> String {
match v {
Value::Number(_) | Value::Bool(_) => v.to_string(),
_ => v.as_str().unwrap_or_default().to_string(),
}
}
/// A non-empty string field.
fn str_at<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
v[key].as_str().filter(|s| !s.is_empty())
}
/// An account as Bluesky names it: its display name, else its handle.
fn name_of(actor: &Value) -> Option<&str> {
str_at(actor, "displayName").or_else(|| str_at(actor, "handle"))
}
/// The URL a value stands for: a blob's `url`, or an https URL on the origins.
fn url_of(found: &Value, ctx: &Ctx) -> Option<String> {
if found.is_object() {
return found["url"].as_str().map(str::to_string);
}
let s = found.as_str()?;
let u = url::Url::parse(s).ok().filter(|u| u.scheme() == "https")?;
let origin = u.origin().ascii_serialization();
ctx.origins.contains(&origin).then(|| s.to_string())
}
/// The picture a value stands for, drawn small or large: a blob's `url`
/// (its `thumb` small, its `proxy` the fallback), or an allowed URL (a
/// thumbnail's small).
fn source_of(found: Option<&Value>, ctx: &Ctx, small: bool) -> Value {
let Some(found) = found else {
return Value::Null;
};
if found.is_object() {
let Some(url) = found["url"].as_str() else {
return Value::Null;
};
let src = if small {
found["thumb"].as_str().unwrap_or(url)
} else {
url
};
let fallback = found["proxy"].as_str().filter(|p| *p != src);
return json!({ "src": src, "fallback": fallback });
}
let Some(at) = url_of(found, ctx) else {
return Value::Null;
};
let rule = small
.then(|| {
ctx.thumbnails
.iter()
.find(|(from, _)| at.starts_with(from.as_str()))
})
.flatten();
let src = match rule {
Some((from, to)) => format!("{to}{}", &at[from.len()..]),
None => at,
};
json!({ "src": src, "fallback": null })
}
fn source(prop: &Value, scope: &Value, ctx: &Ctx, small: bool) -> R<Value> {
let found = value(prop, scope, |v| url_of(v, ctx).is_some())?;
Ok(source_of(found, ctx, small))
}
fn ratio_of(v: &Value) -> Option<f64> {
let w = v["width"].as_f64()?;
let h = v["height"].as_f64()?;
(w > 0.0 && h > 0.0).then(|| w / h)
}
/// A whole number of at least 1.
fn whole(v: &Value) -> Option<u64> {
v.as_u64().filter(|n| *n >= 1)
}
fn http_url(s: &str) -> bool {
url::Url::parse(s).is_ok_and(|u| matches!(u.scheme(), "http" | "https") && u.host().is_some())
}
// Text.
/// A run of text: plain, or a link, an account or a tag.
fn run(text: &str, kind: Option<(&str, &str)>) -> Value {
let mut o = Map::new();
o.insert("text".into(), text.into());
if let Some((k, v)) = kind {
o.insert(k.into(), v.into());
}
Value::Object(o)
}
/// Plain text cut into runs at its http(s) URLs: after the start, a space or
/// a `(`, up to the next space; one trailing `.,;:!?` and an unopened `)` left off.
fn link_runs(text: &str) -> Vec<Value> {
let mut runs = Vec::new();
let lower = text.to_ascii_lowercase();
let mut at = 0;
let mut from = 0;
while let Some(found) = ["http://", "https://"]
.iter()
.filter_map(|p| lower[from..].find(p).map(|i| i + from))
.min()
{
let before = text[..found].chars().next_back();
if !before.is_none_or(|c| c.is_whitespace() || c == '(') {
from = found + 1;
continue;
}
let end = text[found..]
.find(char::is_whitespace)
.map_or(text.len(), |i| i + found);
let mut url = &text[found..end];
if url.ends_with(['.', ',', ';', ':', '!', '?']) {
url = &url[..url.len() - 1];
}
if url.ends_with(')') && !url.contains('(') {
url = &url[..url.len() - 1];
}
if !http_url(url) {
from = end.max(found + 1);
continue;
}
if found > at {
runs.push(run(&text[at..found], None));
}
runs.push(run(url, Some(("link", url))));
at = found + url.len();
from = at;
}
if at < text.len() {
runs.push(run(&text[at..], None));
}
runs
}
/// Text cut into runs by its facets, whose `index` counts UTF-8 bytes;
/// those out of range or overlapping an earlier one leave their text plain.
fn facet_runs(text: &str, facets: Option<&Value>, ctx: &Ctx) -> Vec<Value> {
let marks = facets
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|f| {
let s = f["index"]["byteStart"].as_u64()? as usize;
let e = f["index"]["byteEnd"].as_u64()? as usize;
let kind =
f["features"]
.as_array()
.into_iter()
.flatten()
.find_map(|f| match f["$type"].as_str()? {
"app.bsky.richtext.facet#link" => f["uri"]
.as_str()
.filter(|u| http_url(u))
.map(|u| ("link", u)),
"app.bsky.richtext.facet#mention" => {
f["did"].as_str().map(|d| ("actor", d))
}
"app.bsky.richtext.facet#tag" => f["tag"].as_str().map(|t| ("tag", t)),
_ => None,
});
Some((s, e, kind))
})
.collect();
marked_runs(text, marks, ctx)
}
/// Text written with no facets (a profile's description) cut into runs at
/// what Bluesky's app finds in it (`richtext::marks`): its links, its
/// @mentions, each opening the account by the handle it names, and its tags.
fn detected_runs(text: &str, ctx: &Ctx) -> Vec<Value> {
let found = crate::richtext::marks(text);
let marks = found
.iter()
.map(|m| {
let kind = match &m.kind {
crate::richtext::Kind::Link(u) => ("link", u.as_str()),
crate::richtext::Kind::Mention(h) => ("actor", h.as_str()),
crate::richtext::Kind::Tag(t) => ("tag", t.as_str()),
};
(m.start, m.end, Some(kind))
})
.collect();
marked_runs(text, marks, ctx)
}
/// A part of a text to mark: its UTF-8 byte range, and the run's kind and
/// value (a link, an account or a tag), or none for plain.
type Marked<'a> = (usize, usize, Option<(&'a str, &'a str)>);
/// Text cut into runs at its marks; one out of range or overlapping an
/// earlier one leaves its text plain. A #tag opens what the tree's app
/// searches for it with (`Ctx::tag_call`).
fn marked_runs(text: &str, mut marks: Vec<Marked>, ctx: &Ctx) -> Vec<Value> {
let bytes = text.as_bytes();
marks.retain(|&(s, e, _)| s < e && e <= bytes.len());
marks.sort_by_key(|m| m.0);
let slice = |a: usize, b: usize| String::from_utf8_lossy(&bytes[a..b]).into_owned();
let mut runs = Vec::new();
let mut at = 0;
for (s, e, kind) in marks {
if s < at {
continue;
}
if s > at {
runs.push(run(&slice(at, s), None));
}
let mut drawn = run(&slice(s, e), kind);
if let Some(("tag", t)) = kind
&& let Some(open) = ctx.tag_call(t)
{
drawn["open"] = open;
}
runs.push(drawn);
at = e;
}
if at < bytes.len() {
runs.push(run(&slice(at, bytes.len()), None));
}
runs
}
/// A whole number of 10,000 or more, as a count reads (`67,519`): its
/// thousands grouped. Smaller ones (a year, a pull's number) and any with
/// a fraction stay as they are.
fn grouped(v: &Value) -> Option<String> {
let n = v.as_u64().filter(|n| *n >= 10_000)?;
let digits = n.to_string();
let mut out = String::new();
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i) % 3 == 0 {
out.push(',');
}
out.push(c);
}
Some(out)
}
fn text(p: &Value, scope: &Value) -> R<Option<Value>> {
let found = required("value", &p["value"], scope, present)?;
let raw = match found {
Value::String(_) | Value::Number(_) | Value::Bool(_) => write(found),
_ => return bad("value: not text"),
};
let shown = match p["words"][raw.as_str()].as_str() {
Some(w) => w.to_string(),
None if p["prefix"].is_null() => grouped(found).unwrap_or(raw.clone()),
None => raw.clone(),
};
let shown = match whole(&p["chars"]) {
Some(n) => shown.chars().take(n as usize).collect(),
None => shown,
};
// A number followed by its noun, the singular after 1 (1 other, 3 others).
let noun = p["countNoun"][usize::from(found.as_f64() != Some(1.0))].as_str();
let shown = match noun.filter(|_| found.is_number()) {
Some(noun) => format!("{shown} {noun}"),
None => shown,
};
let value = format!("{}{shown}", p["prefix"].as_str().unwrap_or(""));
let mut o = Map::new();
o.insert("runs".into(), Value::Array(link_runs(&value)));
let style = p["style"].as_str().unwrap_or("body");
o.insert("style".into(), style.into());
if let Some(n) = whole(&p["clamp"]) {
o.insert("clamp".into(), n.into());
// A quote is one line, cut short by the client: nothing to show more of.
if let Some(cut) = clamp::runs(&o["runs"], n as usize).filter(|_| style != "quote") {
o.insert("shownRuns".into(), cut.into());
}
}
Ok(Some(make("Text", o, vec![])))
}
fn rich_text(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let Some(value) = required("value", &p["value"], scope, present)?.as_str() else {
return bad("value: not text");
};
let mut o = Map::new();
match p["format"].as_str() {
Some(format @ ("markdown" | "gfm")) => {
let pictures = value_or_none(&p["pictures"], scope, Value::is_array)?;
let pictures = document::Picture::all(pictures, ctx);
let blocks = document::pictured(value, format == "gfm", &pictures);
o.insert("blocks".into(), Value::Array(blocks));
}
Some("facets") => {
// A record written with no facets at all (another client's, or one
// made before facets were written) has its links, @mentions and
// #tags found as `detect` finds them, as Grain's apps do; facets
// given, even none, are taken as they are.
let runs = match value_or_none(&p["facets"], scope, Value::is_array)? {
Some(facets) => facet_runs(value, Some(facets), ctx),
None => detected_runs(value, ctx),
};
o.insert("runs".into(), Value::Array(runs));
}
Some("detect") => {
o.insert("runs".into(), Value::Array(detected_runs(value, ctx)));
}
_ => {
o.insert("runs".into(), Value::Array(vec![run(value, None)]));
}
}
if p["style"].as_str() == Some("muted") && o.contains_key("runs") {
o.insert("style".into(), "muted".into());
}
if let Some(n) = whole(&p["clamp"]) {
o.insert("clamp".into(), n.into());
let lines = n as usize;
let cut = match o.get("blocks") {
Some(blocks) => clamp::blocks(blocks, lines).map(|c| ("shownBlocks", c)),
None => clamp::runs(&o["runs"], lines).map(|c| ("shownRuns", c)),
};
if let Some((key, c)) = cut {
o.insert(key.into(), c.into());
}
}
Ok(Some(make("RichText", o, vec![])))
}
fn value_or_none<'a>(
prop: &'a Value,
scope: &'a Value,
usable: impl Fn(&Value) -> bool,
) -> R<Option<&'a Value>> {
value(prop, scope, usable)
}
fn time(p: &Value, scope: &Value) -> R<Option<Value>> {
let Some(v) = required("value", &p["value"], scope, present)?.as_str() else {
return bad("value: not a timestamp");
};
Ok(Some(json!({ "c": "Time", "p": { "value": v } })))
}
fn image(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let size = p["size"]
.as_str()
.filter(|s| matches!(*s, "avatar" | "face" | "large" | "icon" | "thumb"));
// One with a size (an account's picture) holds its place with a
// placeholder where it has none, as apps draw a missing avatar; any
// other, and a thumb (a notification's gallery), is left out.
if size.is_none_or(|s| s == "thumb") {
required("src", &p["src"], scope, present)?;
}
// A large one (a profile's own, 80 points) is drawn from the picture
// whole: a thumbnail is too small for it.
let small = matches!(size, Some("avatar" | "face" | "thumb"));
let src = source(&p["src"], scope, ctx, small)?;
let alt = text_of(&p["alt"], scope)?.unwrap_or_default();
let ratio = match size {
Some(_) => 1.0,
None => value(&p["aspectRatio"], scope, |v| ratio_of(v).is_some())?
.and_then(ratio_of)
.unwrap_or(4.0 / 3.0),
};
let mut o = Map::new();
if p["showAlt"] == true && !alt.is_empty() {
o.insert("showAlt".into(), true.into());
}
if p["bleed"] == true {
o.insert("bleed".into(), true.into());
}
for k in ["ring", "plus"] {
if let Some(at) = p[k].as_str() {
let path =
Path::parse(at).ok_or_else(|| Fail::Bad(format!("{k}: a path in the scope")))?;
if holds(&path, scope) {
o.insert(k.into(), true.into());
}
}
}
o.insert("src".into(), src);
o.insert("alt".into(), alt.into());
o.insert("ratio".into(), json!(ratio));
if let Some(s) = size {
o.insert("size".into(), s.into());
}
if p["fit"].as_str() == Some("contain") {
o.insert("fit".into(), "contain".into());
}
// Tapped, it opens what href says (an author's profile) rather than
// what holds it.
let href = value(&p["href"], scope, Value::is_string)?.and_then(Value::as_str);
if let Some(open) = href.and_then(|h| follow(h, ctx)) {
o.insert("open".into(), open);
}
Ok(Some(make("Image", o, vec![])))
}
/// `Stat`: a number, or the length of an array the value binds; `more`
/// where its binding holds anything (a cursor: there are more).
fn stat(p: &Value, scope: &Value) -> R<Option<Value>> {
let n = match value(&p["value"], scope, |v| v.is_number() || v.is_array())? {
Some(Value::Array(a)) => json!(a.len()),
Some(n) => n.clone(),
None => return Err(Fail::Missing),
};
let mut o = Map::new();
o.insert("value".into(), n);
for key in ["icon", "label"] {
if let Some(s) = p[key].as_str() {
o.insert(key.into(), s.into());
}
}
if value(&p["more"], scope, present)?.is_some() {
o.insert("more".into(), true.into());
}
Ok(Some(make("Stat", o, vec![])))
}
// Opening.
fn call(name: &str, args: Value) -> Value {
json!({ "call": { "name": name, "args": args } })
}
/// What following an href opens: a record, an account, a page; nothing for text.
fn follow(href: &str, ctx: &Ctx) -> Option<Value> {
if href.starts_with("at://") {
return Some(ctx.record_call(href));
}
if href.starts_with("https://") {
return http_url(href).then(|| json!({ "url": href }));
}
let handle = href.split('.').count() >= 2
&& href
.split('.')
.all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'));
(href.starts_with("did:") || handle).then(|| ctx.actor_call(href))
}
fn root_value<'a>(prop: &Value, root: &'a Value) -> R<Option<&'a Value>> {
let Some(path) = prop["$root"].as_str().and_then(Path::parse) else {
return bad("unknown path syntax");
};
Ok(path.get(root).filter(|v| !v.is_null()))
}
/// An `open` query's param, as the item and the view's scope resolve it.
fn param(prop: &Value, scope: &Value, ctx: &Ctx, top: bool) -> R<Option<Value>> {
if is_binding(prop) {
return Ok(value(prop, scope, present)?.cloned());
}
if is_root_binding(prop) {
return Ok(root_value(prop, ctx.root)?.cloned());
}
if let Some(parts) = prop
.as_object()
.filter(|o| o.len() == 1)
.and_then(|o| o.get("$atUri"))
{
let Some(parts) = parts.as_array().filter(|a| a.len() == 3) else {
return bad("$atUri: [authority, collection, rkey]");
};
let mut found = Vec::new();
for part in parts {
let v = if part.is_string() {
Some(part.clone())
} else {
param(part, scope, ctx, false)?
};
match v.as_ref().and_then(Value::as_str) {
Some(s) if !s.is_empty() && !s.contains('/') => found.push(s.to_string()),
_ => return Ok(None),
}
}
return Ok(Some(format!("at://{}", found.join("/")).into()));
}
// What a string holds after a prefix (a pinned feed's `camera:` id's
// camera), none where it doesn't start so.
if let Some(args) = op(prop, "$after") {
let (Some(of), Some(prefix)) = (args.first(), args.get(1).and_then(Value::as_str)) else {
return bad("$after: [value, prefix]");
};
let found = param(of, scope, ctx, false)?;
let rest = found
.as_ref()
.and_then(Value::as_str)
.and_then(|s| s.strip_prefix(prefix));
return Ok(rest.filter(|r| !r.is_empty()).map(Value::from));
}
if top && let Some(list) = prop.as_array() {
let mut found = Vec::new();
for item in list {
match param(item, scope, ctx, false)? {
Some(v) => found.push(v),
None => return Ok(None),
}
}
return Ok(Some(Value::Array(found)));
}
Ok(Some(prop.clone()))
}
/// Where an `open` prop says an item opens, as a tool call: a query, or a
/// binding to an at-uri (its record) or a DID (its account, as a Link's
/// href opens it); without one, `fallback` (the item's own `uri` for a List).
/// A page (`url`) or what the host does itself (`host`) is as written.
fn opens(prop: &Value, scope: &Value, ctx: &Ctx, fallback: Option<&Value>) -> R<Option<Value>> {
let given = if prop.is_null() { fallback } else { Some(prop) };
let Some(given) = given.filter(|g| !g.is_null()) else {
return Ok(None);
};
if given.get("url").or_else(|| given.get("host")).is_some() {
return Ok(Some(given.clone()));
}
if given.is_object()
&& !is_binding(given)
&& let Some(method) = given["query"].as_str()
{
let mut params = Map::new();
if let Some(raw) = given["params"].as_object() {
for (name, p) in raw {
match param(p, scope, ctx, true)? {
Some(v) => params.insert(name.clone(), v),
None => return Ok(None),
};
}
}
let mut args = json!({ "method": method, "params": params });
if let Some(s) = given["service"].as_str() {
args["service"] = s.into();
}
// What its answer shows first, where one at a time (a story).
if let Some(Value::String(first)) = param(&given["at"], scope, ctx, false)? {
args["at"] = first.into();
}
// Its screen opened at a form (Add to your story), unless the scope
// holds something at `unless` (one's own stories): then as it is.
let held = given["unless"]
.as_str()
.and_then(Path::parse)
.is_some_and(|u| holds(&u, scope));
if is_compose(&given["compose"]) && !held {
args["compose"] = given["compose"].clone();
}
let mut open = call("query", args);
// Its screen over what is open, as a story's comments are.
if given["sheet"] == true {
open["sheet"] = true.into();
}
return Ok(Some(open));
}
let found = value(given, scope, |v| {
v.as_str()
.is_some_and(|s| s.starts_with("at://") || s.starts_with("did:"))
})?;
Ok(found
.and_then(Value::as_str)
.map(|to| match to.starts_with("did:") {
true => ctx.actor_call(to),
false => ctx.record_call(to),
}))
}
fn thread_call(uri: &str) -> Value {
call(
"query",
json!({ "method": "app.bsky.feed.getPostThread", "params": { "uri": uri } }),
)
}
fn link(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let mut o = Map::new();
if let Some(style @ ("button" | "name" | "muted")) = p["style"].as_str() {
o.insert("style".into(), style.into());
}
if let Some(icon) = p["icon"].as_str() {
o.insert("icon".into(), icon.into());
}
if !p["open"].is_null() {
let Some(label) = text_of(&p["label"], scope)? else {
return Err(Fail::Missing);
};
let target = opens(&p["open"], scope, ctx, None)?;
o.insert("label".into(), label.into());
if let Some(t) = &target {
if drawn_now(t, ctx.root) {
o.insert("current".into(), true.into());
} else {
o.insert("open".into(), t.clone());
}
}
return Ok(Some(make("Link", o, vec![])));
}
let Some(href) = required("href", &p["href"], scope, present)?.as_str() else {
return bad("href: not a link");
};
let label = text_of(&p["label"], scope)?.unwrap_or_else(|| href.to_string());
o.insert("label".into(), label.into());
// Shared rather than opened: the address `share` begins, href's value
// its end (a profile's page on its app's site).
if let Some(prefix) = p["share"].as_str() {
let address = format!("{prefix}{href}");
if !http_url(&address) {
return bad("share: an https address that href's value ends");
}
o.insert("share".into(), address.into());
return Ok(Some(make("Link", o, vec![])));
}
// Copied as plain text rather than opened: `copy` before href's value
// (a profile's handle, "@" before it).
if let Some(prefix) = p["copy"].as_str() {
o.insert("copy".into(), format!("{prefix}{href}").into());
return Ok(Some(make("Link", o, vec![])));
}
// An address naming two accounts in its fragment (Germ's messageMeUrl):
// the DID at `fragment`, then `+` and the signed-in person's where one is.
let mut href = href.to_string();
if let Some(at) = p["fragment"].as_str() {
let did = Path::parse(at)
.and_then(|path| path.get(scope))
.and_then(Value::as_str);
let Some(did) = did.filter(|d| d.starts_with("did:")) else {
return Err(Fail::Missing);
};
if !href.starts_with("https://") || href.contains('#') {
return bad("fragment: on an https address with no fragment of its own");
}
href = match ctx.me {
Some(me) => format!("{href}#{did}+{me}"),
None => format!("{href}#{did}"),
};
}
if let Some(open) = follow(&href, ctx) {
o.insert("open".into(), open);
}
Ok(Some(make("Link", o, vec![])))
}
/// `Tabs`: each tab whose open resolves (`items`, or one for each element
/// of `from` that `where` keeps, labelled by its `label`, opening `open` or
/// the first of `opens` it matches), its call, and `selected` on the one
/// whose call is drawn now: of those `drawn_now` holds, the one naming the
/// most params (an Open tab, not an All tab with no state). Fewer than two
/// tabs, or none drawn now, draw nothing.
fn tabs(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let mut drawn: Vec<(String, Value)> = Vec::new();
if let Some(elements) = value(&p["from"], scope, Value::is_array)?.and_then(Value::as_array) {
let Some(label) = p["label"].as_str().and_then(Path::parse) else {
return bad("label: a path within each element");
};
for element in elements {
if let Some(w) = p["where"].as_object()
&& !matches(element, w, scope)?
{
continue;
}
let Some(name) = label.get(element).and_then(Value::as_str) else {
continue;
};
let open = match p["opens"].as_array() {
Some(cases) => case(cases, element, scope)?,
None => &p["open"],
};
if let Some(open) = opens(open, element, ctx, None)? {
drawn.push((name.to_string(), open));
}
}
drawn.truncate(crate::catalog::MAX_LITERAL_ITEMS);
} else {
for tab in p["items"].as_array().into_iter().flatten() {
let Some(label) = str_at(tab, "label") else {
continue;
};
if let Some(open) = opens(&tab["open"], scope, ctx, None)? {
drawn.push((label.to_string(), open));
}
}
}
if drawn.len() < 2 {
return Err(Fail::Missing);
}
let named = |open: &Value| {
open["call"]["args"]["params"]
.as_object()
.map_or(0, Map::len)
};
let mut selected: Option<usize> = None;
for (i, (_, open)) in drawn.iter().enumerate() {
if drawn_now(open, ctx.root) && selected.is_none_or(|s| named(open) > named(&drawn[s].1)) {
selected = Some(i);
}
}
if selected.is_none() {
return Err(Fail::Missing);
}
let items: Vec<Value> = drawn
.into_iter()
.enumerate()
.map(|(i, (label, open))| {
json!({ "label": label, "open": open, "selected": selected == Some(i) })
})
.collect();
let mut o = Map::new();
o.insert("items".into(), Value::Array(items));
if p["style"] == "strip" {
o.insert("style".into(), "strip".into());
}
Ok(Some(make("Tabs", o, vec![])))
}
/// The open of the first of a Tabs' `opens` whose `where` an element matches
/// (one with no where, any), as a pinned camera's opens its camera's feed.
fn case<'a>(cases: &'a [Value], element: &Value, scope: &Value) -> R<&'a Value> {
for c in cases {
if c["where"]
.as_object()
.map_or(Ok(true), |w| matches(element, w, scope))?
{
return Ok(&c["open"]);
}
}
Ok(&Value::Null)
}
/// `Toggle`: its label, about, whether it is on now (its binding's
/// boolean, else `default`), and the call a flip sends, its `{"$on": true}`
/// left for the client; a trusted view's alone, as a call is.
fn toggle(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let call = procedure(&p["call"], scope, ctx)?;
let label = str_at(p, "label").unwrap_or("On");
let on = value(&p["on"], scope, Value::is_boolean)?
.and_then(Value::as_bool)
.unwrap_or(p["default"] == true);
let mut o = Map::new();
o.insert("label".into(), label.into());
if let Some(about) = text_of(&p["about"], scope)? {
o.insert("about".into(), about.into());
}
o.insert("on".into(), on.into());
o.insert("key".into(), key(&[&label.into(), &p["call"]]).into());
o.insert("call".into(), call);
Ok(Some(make("Toggle", o, vec![])))
}
/// `Choice`: its label, about, options, which is chosen now (its binding's
/// value where an option has it, else `default`; none where neither is
/// one), and the call a choice sends, its `{"$on": true}` left for the
/// client; a trusted view's alone, as a call is.
fn choice(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let call = procedure(&p["call"], scope, ctx)?;
let label = str_at(p, "label").unwrap_or("Choice");
let options = p["options"].as_array().map_or(&[][..], Vec::as_slice);
let offered = |v: &Value| options.iter().any(|o| o["value"] == *v);
let on = value(&p["on"], scope, offered)?.or(Some(&p["default"]).filter(|d| offered(d)));
let mut o = Map::new();
o.insert("label".into(), label.into());
if let Some(about) = text_of(&p["about"], scope)? {
o.insert("about".into(), about.into());
}
o.insert("options".into(), Value::Array(options.to_vec()));
if let Some(on) = on {
o.insert("on".into(), on.clone());
}
o.insert("key".into(), key(&[&label.into(), &p["call"]]).into());
o.insert("call".into(), call);
Ok(Some(make("Choice", o, vec![])))
}
/// `Search`: a field whose words fill `param` of the query `open` names,
/// with `value`, the words searched already, and `current` where that query
/// is the one drawn now (searching again draws in place, as a tab does).
/// One whose open is a record, or opens nothing, draws nothing.
fn search(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let open = opens(&p["open"], scope, ctx, None)?.filter(|o| o["call"]["name"] == "query");
let Some(open) = open else {
return Err(Fail::Missing);
};
let mut o = Map::new();
if drawn_now(&open, ctx.root) {
o.insert("current".into(), true.into());
}
o.insert("open".into(), open);
o.insert("param".into(), p["param"].clone());
for (key, given) in [
("placeholder", p["placeholder"].as_str().map(str::to_string)),
("value", text_of(&p["value"], scope)?),
] {
if let Some(words) = given {
o.insert(key.into(), words.into());
}
}
Ok(Some(make("Search", o, vec![])))
}
/// Whether an open is the query the view draws now: its method, and each
/// param it names as the view was asked.
fn drawn_now(open: &Value, root: &Value) -> bool {
let args = &open["call"]["args"];
open["call"]["name"] == "query"
&& args["method"] == root["method"]
&& args["params"]
.as_object()
.is_some_and(|p| p.iter().all(|(k, v)| root["params"][k] == *v))
}
// Lists.
/// What an item's feed is told of it: its uri, feedContext and reqId.
fn report(item: &Value, ctx: &Ctx) -> Option<Value> {
let paths = ctx.report.as_ref()?;
let uri = paths
.item
.get(item)?
.as_str()
.filter(|u| u.starts_with("at://"))?;
let mut o = Map::new();
o.insert("item".into(), uri.into());
for (key, path) in [("feedContext", paths.feed_context), ("reqId", paths.req_id)] {
if let Some(s) = path
.and_then(|p| p.get(item))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
{
o.insert(key.into(), s.into());
}
}
Some(Value::Object(o))
}
/// A literal item's values with each `{"$root": path}` read from the view's
/// own scope (null where it holds nothing), its `open` left for `opens`.
fn rooted(v: &Value, root: &Value, top: bool) -> R<Value> {
if is_root_binding(v) {
return Ok(root_value(v, root)?.cloned().unwrap_or(Value::Null));
}
Ok(match v {
Value::Object(o) => {
let mut out = Map::new();
for (k, x) in o {
let kept = if top && k == "open" {
x.clone()
} else {
rooted(x, root, false)?
};
out.insert(k.clone(), kept);
}
Value::Object(out)
}
Value::Array(a) => {
Value::Array(a.iter().map(|x| rooted(x, root, false)).collect::<R<_>>()?)
}
_ => v.clone(),
})
}
fn list(n: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let p = &n["props"];
let literal = p["items"].is_array();
let all: Vec<Value> = if literal {
p["items"]
.as_array()
.into_iter()
.flatten()
.map(|item| rooted(item, ctx.root, true))
.collect::<R<_>>()?
} else if is_root_binding(&p["items"]) {
match root_value(&p["items"], ctx.root)? {
None => return Err(Fail::Missing),
Some(Value::Array(a)) => a.clone(),
Some(_) => return bad("items: no array"),
}
} else {
match value(&p["items"], scope, Value::is_array)? {
Some(Value::Array(a)) => a.clone(),
_ if value(&p["items"], scope, present)?.is_some() => return bad("items: no array"),
_ => return Err(Fail::Missing),
}
};
let items = match p["where"].as_object() {
Some(w) => {
let mut kept = Vec::new();
for element in all {
if matches(&element, w, scope)? {
kept.push(element);
}
}
kept
}
None => all,
};
let items = whose(p, items, ctx.me)?;
let (items, cut) = kept(p, items)?;
let items = groups(&p["group"], items);
// `first`, a literal row before the items (oneself before who has
// stories), where `needs` keeps it; never in a join's page more.
let first = if p["first"].is_object() && ctx.more.alone.is_none() {
kept(p, vec![rooted(&p["first"], ctx.root, true)?])?.0
} else {
Vec::new()
};
let bound = p["items"]["$"].as_str();
let page = paged(p, scope, ctx);
let fallback = json!({ "$": "uri" });
// A Stack with `at` among the children is drawn once, with the List's
// scope, after that many items (suggestions after a feed's fifth); the
// rest are each item's.
let (slots, each): (Vec<&Value>, Vec<&Value>) = n["children"]
.as_array()
.into_iter()
.flatten()
.partition(|c| c["component"] == "Stack" && c["props"]["at"].is_u64());
let template = json!({ "children": each });
let mut drawn = Vec::new();
let rows = first.iter().map(|row| (row, true));
for (item, row) in rows.chain(items.iter().map(|item| (item, literal))) {
let mut o = Map::new();
// A literal row's own open, in place of the List's.
let own = if row && !item["open"].is_null() {
&item["open"]
} else {
&p["open"]
};
if let Some(open) = opens(own, item, ctx, Some(&fallback)).unwrap_or(None) {
o.insert("open".into(), open);
}
if let Some(r) = report(item, ctx) {
o.insert("report".into(), r);
}
o.insert("k".into(), Value::Array(children(&template, item, ctx)));
drawn.push(Value::Object(o));
}
let mut slots: Vec<(usize, &Value)> = slots
.into_iter()
.map(|s| (s["props"]["at"].as_u64().unwrap_or(0) as usize, s))
.collect();
slots.sort_by_key(|(at, _)| std::cmp::Reverse(*at));
// On the first page alone: a page more (a cursor asked, or a join's
// page more) gets none again.
let first_page = ctx.root["params"]["cursor"].is_null() && ctx.more.alone.is_none();
for (at, slot) in slots {
if first_page
&& at <= drawn.len()
&& let Some(block) = node(slot, scope, ctx)
{
drawn.insert(at, json!({ "k": [block] }));
}
}
let mut o = Map::new();
o.insert("style".into(), p["style"].as_str().unwrap_or("rows").into());
grid_words(p, &mut o);
// A title heads items: with none, only `empty` says so.
if let Some(t) = str_at(p, "title").filter(|_| !drawn.is_empty()) {
o.insert("title".into(), t.into());
}
match str_at(p, "empty") {
Some(e) => {
o.insert("empty".into(), e.into());
}
None if bound == Some("records") => {
o.insert("empty".into(), "Nothing here yet.".into());
}
None => {}
}
if page {
o.insert("page".into(), true.into());
}
if let Some(next) = own_next(p, scope, ctx) {
o.insert("next".into(), next);
}
if p["pages"] == true {
o.insert("pages".into(), true.into());
}
// Rows that open pages of their own, each ending in a chevron.
if p["chevrons"] == true && o["style"] == "rows" {
o.insert("chevrons".into(), true.into());
}
// Chips' one more, after the items, where `limit` left some out (See all).
if cut
&& o["style"] == "chips"
&& let Some(label) = str_at(&p["more"], "label")
&& let Some(open) = opens(&p["more"]["open"], scope, ctx, None).unwrap_or(None)
{
o.insert("more".into(), json!({ "label": label, "open": open }));
}
// What is called once it is first shown (notifications marked seen).
if p["shown"].is_object() {
match procedure(&p["shown"], scope, ctx) {
Ok(call) => {
o.insert("shown".into(), call);
}
Err(Fail::Missing) => {}
Err(fail) => return Err(fail),
}
}
let mut out = make("List", o, vec![]);
out["items"] = Value::Array(drawn);
Ok(Some(out))
}
/// Whether an element holds, at each of `where`'s paths, what the scope
/// holds at the path paired with it, or the literal of an `{"$is": …}`;
/// where it is in `{"$not": …}`, anything else (nothing there too).
fn matches(element: &Value, w: &Map<String, Value>, scope: &Value) -> R<bool> {
for (at, want) in w {
let Some(at) = Path::parse(at) else {
return bad("where: paths within the element to paths in the scope");
};
let (want, negated) = crate::catalog::negated(want);
let want = if crate::catalog::is_literal(want) {
Some(&want["$is"])
} else {
let Some(path) = want.as_str().and_then(Path::parse) else {
return bad("where: paths within the element to paths in the scope");
};
path.get(scope).filter(|v| !v.is_null())
};
let same = want.is_some_and(|want| at.get(element) == Some(want));
if same == negated {
return Ok(false);
}
}
Ok(true)
}
/// Whether a scope holds something at `path`: a value but null, false, 0,
/// "", [] or {}.
fn holds(path: &Path, scope: &Value) -> bool {
match path.get(scope) {
None | Some(Value::Null | Value::Bool(false)) => false,
Some(Value::Number(n)) => n.as_f64() != Some(0.0),
Some(Value::String(s)) => !s.is_empty(),
Some(Value::Array(a)) => !a.is_empty(),
Some(Value::Object(o)) => !o.is_empty(),
Some(_) => true,
}
}
/// Whether a Stack is drawn: its scope holding something at `when`, and
/// nothing at `unless`; the signed-in person's DID at `mine`, and anything
/// else at `others` (signed out, `mine` is never drawn, `others` always);
/// at each of `where`'s paths, what `matches` asks of an element.
fn gated(p: &Value, scope: &Value, me: Option<&str>) -> R<bool> {
let path = |key: &str| -> R<Option<Path>> {
match p[key].as_str() {
None => Ok(None),
Some(s) => Path::parse(s)
.map(Some)
.ok_or_else(|| Fail::Bad(format!("{key}: a path in the scope"))),
}
};
let is_me = |at: &Path| me.is_some_and(|me| at.get(scope).and_then(Value::as_str) == Some(me));
let kept = match p["where"].as_object() {
Some(w) => matches(scope, w, scope)?,
None => true,
};
Ok(kept
&& path("when")?.is_none_or(|w| holds(&w, scope))
&& path("unless")?.is_none_or(|u| !holds(&u, scope))
&& path("mine")?.is_none_or(|m| is_me(&m))
&& path("others")?.is_none_or(|o| !is_me(&o)))
}
/// A List's items as `mine` and `others` keep them: those whose DID at
/// `mine` is the signed-in person's; those whose DID at `others` is not.
/// Signed out, no one is the person: `mine` keeps none, `others` all.
fn whose(p: &Value, mut items: Vec<Value>, me: Option<&str>) -> R<Vec<Value>> {
for (key, keep_mine) in [("mine", true), ("others", false)] {
let Some(at) = p[key].as_str() else { continue };
let Some(path) = Path::parse(at) else {
return bad(format!("{key}: a path within each item"));
};
items.retain(|item| {
let is_me = me.is_some_and(|me| path.get(item).and_then(Value::as_str) == Some(me));
is_me == keep_mine
});
}
Ok(items)
}
/// A List's items as its `needs`, `distinct` and `limit` keep them: those
/// holding something at `needs`, each value at `distinct` once (its first
/// item; one with nothing there left out), at most `limit`; and whether
/// `limit` left any out.
fn kept(p: &Value, mut items: Vec<Value>) -> R<(Vec<Value>, bool)> {
let path = |key: &str| -> R<Option<Path>> {
match p[key].as_str() {
None => Ok(None),
Some(s) => Path::parse(s)
.map(Some)
.ok_or_else(|| Fail::Bad(format!("{key}: a path within each item"))),
}
};
let there = |v: Option<&Value>| v.is_some_and(|v| !v.is_null());
if let Some(needs) = path("needs")? {
items.retain(|item| there(needs.get(item)));
}
if let Some(distinct) = path("distinct")? {
let mut seen: Vec<Value> = Vec::new();
items.retain(|item| match distinct.get(item).filter(|v| !v.is_null()) {
Some(v) if !seen.contains(v) => {
seen.push(v.clone());
true
}
_ => false,
});
}
let limit = p["limit"].as_u64().map_or(usize::MAX, |l| l as usize);
let cut = items.len() > limit;
items.truncate(limit);
Ok((items, cut))
}
/// A List's items as its `group` draws them (as a photo app groups the
/// favorites of one gallery): each item joins the first group before it
/// whose first item holds what it holds at every `by` path (nothing there
/// alike) and whose time, at `time`, is less than `hours` from its own;
/// one that holds nothing at `time`, or nothing `only` names at its paths,
/// starts a group of its own. One whose value at `distinct` its group holds
/// already is left out. Each group's first item is drawn, `as` holding the
/// group: `{ items, count, others? }`, `others` how many there are past the
/// first, where there are. With no `group`, the items as they are.
fn groups(g: &Value, items: Vec<Value>) -> Vec<Value> {
let Some(name) = g["as"].as_str() else {
return items;
};
let path = |v: &Value| v.as_str().and_then(Path::parse);
let by: Vec<Path> = g["by"]
.as_array()
.into_iter()
.flatten()
.filter_map(path)
.collect();
let only: Vec<(Path, &Vec<Value>)> = g["only"]
.as_object()
.into_iter()
.flatten()
.filter_map(|(at, values)| Some((Path::parse(at)?, values.as_array()?)))
.collect();
let time = path(&g["time"]);
let distinct = path(&g["distinct"]);
let window = g["hours"].as_i64().unwrap_or(0) * 3_600_000;
// What an item is grouped by, and when it was (milliseconds): none
// where it is never grouped.
type Key = (Vec<Value>, i64);
let key = |item: &Value| -> Option<Key> {
let when = time
.as_ref()
.and_then(|t| t.get(item))
.and_then(Value::as_str)
.and_then(crate::tools::datetime_millis);
let named = only
.iter()
.all(|(at, values)| at.get(item).is_some_and(|v| values.contains(v)));
let held = by
.iter()
.map(|at| at.get(item).cloned().unwrap_or(Value::Null));
when.filter(|_| named).map(|w| (held.collect(), w))
};
let distinct = distinct.as_ref();
fn unique<'a>(distinct: Option<&Path>, item: &'a Value) -> Option<&'a Value> {
distinct?.get(item).filter(|v| !v.is_null())
}
// Each group: its items' places, and its first's key.
let mut groups: Vec<(Vec<usize>, Option<Key>)> = Vec::new();
for (i, item) in items.iter().enumerate() {
let mine = key(item);
let joined = mine.as_ref().and_then(|(held, when)| {
groups.iter_mut().find(|(_, first)| {
first
.as_ref()
.is_some_and(|(h, w)| h == held && (w - when).abs() < window)
})
});
match joined {
Some((members, _)) => {
let again = unique(distinct, item).is_some_and(|v| {
members
.iter()
.any(|&m| unique(distinct, &items[m]) == Some(v))
});
if !again {
members.push(i);
}
}
None => groups.push((vec![i], mine)),
}
}
// The group's first is drawn and listed in it too: the one copy made.
let mut items = items;
let mut drawn = Vec::with_capacity(groups.len());
for (members, _) in groups {
let count = members.len();
let all: Vec<Value> = members
.iter()
.map(|&m| std::mem::take(&mut items[m]))
.collect();
let mut first = all[0].clone();
let mut group = json!({ "count": count, "items": all });
if count > 1 {
group["others"] = (count - 1).into();
}
if let Some(o) = first.as_object_mut() {
o.insert(name.to_string(), group);
}
drawn.push(first);
}
drawn
}
// Actions.
fn is_now(v: &Value) -> bool {
v.as_object()
.is_some_and(|o| o.len() == 1 && o.get("$now") == Some(&Value::Bool(true)))
}
/// A template with its bindings resolved: `{"$": path}`, `{"$root": path}`
/// read from the view's own scope, `{"$strongRef": path}` as `{uri, cid}`,
/// `{"$rkey": path}` as the record key of the at-uri there,
/// `{"$first": [values]}` as the first that resolves, `{"$join": [values]}`
/// as their strings joined, and an array's edits (`edit`); `{"$now": true}`
/// and `{"$text": true}` (what the person writes) stay, for the client.
fn record(v: &Value, scope: &Value, root: &Value) -> R<Value> {
if is_binding(v) {
return required("record", v, scope, present).cloned();
}
if is_root_binding(v) {
return root_value(v, root)?.cloned().ok_or(Fail::Missing);
}
if is_filled(v) {
return Ok(v.clone());
}
if let Some(firsts) = v
.as_object()
.filter(|o| o.len() == 1)
.and_then(|o| o.get("$first"))
.and_then(Value::as_array)
{
for first in firsts {
match record(first, scope, root) {
Err(Fail::Missing) => continue,
found => return found,
}
}
return Err(Fail::Missing);
}
if let Some(parts) = op(v, "$join") {
let mut joined = String::new();
for part in parts {
let Value::String(s) = record(part, scope, root)? else {
return Err(Fail::Missing);
};
joined.push_str(&s);
}
return Ok(joined.into());
}
if let Some((name, args)) = EDITS.iter().find_map(|&n| op(v, n).map(|a| (n, a))) {
return edit(name, args, scope, root);
}
if let Some(o) = v.as_object()
&& o.len() == 1
&& let Some(path) = o.get("$strongRef").and_then(Value::as_str)
{
let binding = json!({ "$": path });
let found = required("record", &binding, scope, |r| {
r["uri"].as_str().is_some_and(|u| u.starts_with("at://")) && str_at(r, "cid").is_some()
})?;
return Ok(json!({ "uri": found["uri"], "cid": found["cid"] }));
}
if let Some(o) = v.as_object()
&& o.len() == 1
&& let Some(path) = o.get("$rkey").and_then(Value::as_str)
{
let binding = json!({ "$": path });
let found = required("record", &binding, scope, |u| {
u.as_str()
.is_some_and(|u| u.starts_with("at://") && u.matches('/').count() == 4)
})?;
return Ok(found
.as_str()
.and_then(|u| u.rsplit('/').next())
.unwrap_or_default()
.into());
}
if is_now(v) {
return Ok(v.clone());
}
match v {
Value::Array(a) => a
.iter()
.map(|x| record(x, scope, root))
.collect::<R<Vec<_>>>()
.map(Value::Array),
Value::Object(o) => {
let mut out = Map::new();
for (k, x) in o {
out.insert(k.clone(), record(x, scope, root)?);
}
Ok(Value::Object(out))
}
_ => Ok(v.clone()),
}
}
/// An op's arguments: `{"<name>": [args]}`, its key alone.
fn op<'a>(v: &'a Value, name: &str) -> Option<&'a [Value]> {
v.as_object()
.filter(|o| o.len() == 1)
.and_then(|o| o.get(name))
.and_then(Value::as_array)
.map(Vec::as_slice)
}
/// The edits of an array a template makes.
const EDITS: &[&str] = &["$with", "$without", "$move"];
/// An array read from the scope, edited: `{"$with": [array, key, element]}`
/// with the element added at its end, `{"$without": [array, key, value]}`
/// less the elements whose `key` (a path within each) holds the value, and
/// `{"$move": [array, key, value, by]}` with the element whose key holds it
/// moved `by` places (-1 one earlier). None where it would do nothing (the
/// array has one of that key already, none to take out, a move past an
/// end), so a button that would send it draws nothing: a feed's Pin where
/// it is pinned, a first row's Move up.
fn edit(name: &str, args: &[Value], scope: &Value, root: &Value) -> R<Value> {
let key = args.get(1).and_then(Value::as_str).and_then(Path::parse);
let (Some(array), Some(key), Some(given)) = (args.first(), key, args.get(2)) else {
return bad(format!("{name}: [array, key, value]"));
};
let Value::Array(mut items) = record(array, scope, root)? else {
return Err(Fail::Missing);
};
let given = record(given, scope, root)?;
let want = match name {
"$with" => key.get(&given).cloned().unwrap_or(Value::Null),
_ => given.clone(),
};
let holds = |e: &Value| !want.is_null() && key.get(e) == Some(&want);
let at = items.iter().position(holds);
match (name, at) {
("$with", None) if !want.is_null() => items.push(given),
("$without", Some(_)) => items.retain(|e| !holds(e)),
("$move", Some(i)) => {
let by = args.get(3).and_then(Value::as_i64).unwrap_or(0);
let to = i
.checked_add_signed(by as isize)
.filter(|&to| to != i && to < items.len());
let Some(to) = to else {
return Err(Fail::Missing);
};
let moved = items.remove(i);
items.insert(to, moved);
}
_ => return Err(Fail::Missing),
}
Ok(Value::Array(items))
}
/// A mark the client fills with the person's own value: what they wrote
/// (`{"$text": true}`), what they switched to (`{"$on": true}`).
fn is_filled(v: &Value) -> bool {
v.as_object().is_some_and(|o| {
o.len() == 1
&& ["$text", "$on"]
.iter()
.any(|m| o.get(*m) == Some(&Value::Bool(true)))
})
}
/// A procedure call (`Action`'s `call`, `Messages`' `send`) with its input
/// resolved, a trusted view's alone: `{ method, service, input }`.
fn procedure(c: &Value, scope: &Value, ctx: &Ctx) -> R<Value> {
if !ctx.trusted {
return Err(Fail::Missing);
}
let (Some(method), Some(service)) = (str_at(c, "method"), str_at(c, "service")) else {
return bad("call: names a method and a service");
};
let input = match &c["input"] {
Value::Null => json!({}),
i => record(i, scope, ctx.root)?,
};
Ok(json!({ "method": method, "service": service, "input": input }))
}
/// The call an Action or a select makes: its `call`, or its `deletes` as
/// one, the deletion plan's query and its params as the input, which
/// `call_procedure` asks and commits.
pub(super) fn call_of<'a>(call: &'a Value, deletes: &Value) -> std::borrow::Cow<'a, Value> {
match deletes.as_object() {
Some(d) => std::borrow::Cow::Owned(
json!({ "method": d.get("method"), "service": d.get("service"),
"input": d.get("params") }),
),
None => std::borrow::Cow::Borrowed(call),
}
}
fn key(parts: &[&Value]) -> String {
let mut h = Sha256::new();
for p in parts {
h.update(p.to_string().as_bytes());
}
h.finalize()[..8]
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn action(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let label = str_at(p, "label").unwrap_or("Do it");
// Closed, as a post whose author takes no replies: its count alone.
if value(&p["closed"], scope, |v| v == &Value::Bool(true))?.is_some() {
return stat(
&json!({ "value": p["count"], "icon": p["icon"], "label": label }),
scope,
);
}
let mut o = Map::new();
o.insert("label".into(), label.into());
o.insert("done".into(), str_at(p, "done").unwrap_or(label).into());
// Done, the tree is read again (a deleted comment gone), or the screen it
// is on closes (a deleted thing's).
if p["reload"] == true {
o.insert("reload".into(), true.into());
}
if p["leave"] == true {
o.insert("leave".into(), true.into());
}
if let Some(i) = p["icon"].as_str() {
o.insert("icon".into(), i.into());
}
if let Some(style @ ("button" | "row")) = p["style"].as_str() {
o.insert("style".into(), style.into());
}
if let Some(question) = text_of(&p["confirm"], scope)? {
o.insert("confirm".into(), question.into());
// The handle typed to confirm, as deleting an account asks.
if let Some(handle) = text_of(&p["handle"], scope)? {
o.insert("handle".into(), handle.into());
}
}
if p["signOut"] == true {
o.insert("signOut".into(), true.into());
}
if p["tone"].as_str() == Some("danger") {
o.insert("tone".into(), "danger".into());
}
if let Some(n) = value(&p["count"], scope, |v| v.as_u64().is_some())? {
o.insert("count".into(), n.clone());
}
if let Some(create) = p["create"].as_object() {
let (Some(collection), Some(template)) = (
create.get("collection").and_then(Value::as_str),
create.get("record").filter(|r| r.is_object()),
) else {
return bad("create: names a collection and a record");
};
let made = record(template, scope, ctx.root)?;
o.insert(
"key".into(),
key(&[&p["label"], &collection.into(), &made]).into(),
);
o.insert(
"create".into(),
json!({ "collection": collection, "record": made }),
);
if let Some(e) = value(&p["existing"], scope, |v| {
v.as_str().is_some_and(|s| s.starts_with("at://"))
})? {
o.insert("existing".into(), e.clone());
}
} else if let Some(delete) = p["delete"].as_object() {
let uri = required(
"delete.uri",
delete.get("uri").unwrap_or(&Value::Null),
scope,
|v| v.as_str().is_some_and(|s| s.starts_with("at://")),
)?;
o.insert("key".into(), key(&[&p["label"], uri]).into());
o.insert("delete".into(), json!({ "uri": uri }));
} else if let Some(i) = p["interaction"].as_object() {
let Some(event) = i
.get("event")
.and_then(Value::as_str)
.filter(|e| !e.is_empty())
else {
return bad("interaction: names an event");
};
// Only a trusted view's, for an item its feed can be told of.
let Some(r) = ctx.trusted.then(|| report(scope, ctx)).flatten() else {
return Err(Fail::Missing);
};
o.insert("key".into(), key(&[&event.into(), &r]).into());
o.insert("interaction".into(), json!({ "event": event, "report": r }));
} else if p["call"].is_object() || p["deletes"].is_object() {
// A deletion plan is asked and committed through the call the
// clients make already: `call_procedure` knows it a trusted view's.
let called = procedure(&call_of(&p["call"], &p["deletes"]), scope, ctx)?;
o.insert("key".into(), key(&[&p["label"], &called]).into());
o.insert("call".into(), called);
// One that repeats is called again until nothing is left (an
// account's data); what it calls after stays HUD's (`view::Plan`).
if p["deletes"]["repeat"] == true {
o.insert("repeat".into(), true.into());
}
} else {
return bad("names none of create, delete, interaction, call and deletes");
}
Ok(Some(make("Action", o, vec![])))
}
/// A form to write (`Compose`): its button's words, icon and count (closed,
/// its count alone, as an Action's); what heads the form; its fields and
/// writes as the view gives them, for the client to ask and `apply_writes`
/// to fill, each field's `value` read here (`prefilled`) and a text's or
/// line's limits its record's lexicon's (`compose::limited`); its given values
/// resolved here (a reply's root and parent): one that does not resolve
/// draws nothing. Its key names what it opens holding too, so a draft kept
/// of a form since saved is not opened again. Drawn as a field (`style`),
/// its words (`prompt`) are its own label where it is `for` another
/// (`with_fors`), else its first text or line field's placeholder, else
/// its label; one `for` another that names none draws nothing.
fn compose(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
if p["for"].is_string() {
return Err(Fail::Missing);
}
let label = str_at(p, "label").unwrap_or("Write");
if value(&p["closed"], scope, |v| v == &Value::Bool(true))?.is_some() {
return stat(
&json!({ "value": p["count"], "icon": p["icon"], "label": label }),
scope,
);
}
let mut given = Map::new();
for (k, v) in p["given"].as_object().into_iter().flatten() {
given.insert(k.clone(), record(v, scope, ctx.root)?);
}
let mut o = Map::new();
o.insert("label".into(), label.into());
o.insert("send".into(), str_at(p, "send").unwrap_or(label).into());
if let Some(i) = p["icon"].as_str() {
o.insert("icon".into(), i.into());
}
if let Some(style @ ("button" | "field")) = p["style"].as_str() {
o.insert("style".into(), style.into());
}
if p["style"] == "field" {
let placeholder = p["fields"]
.as_array()
.into_iter()
.flatten()
.find(|f| matches!(f["kind"].as_str(), Some("text" | "line")))
.and_then(|f| f["placeholder"].as_str());
let prompt = str_at(p, "prompt").or(placeholder).unwrap_or(label);
o.insert("prompt".into(), prompt.into());
}
if let Some(words) = str_at(p, "signIn") {
o.insert("signIn".into(), words.into());
}
if p["form"].as_str() == Some("photo") {
o.insert("form".into(), "photo".into());
}
if let Some(n) = value(&p["count"], scope, |v| v.as_u64().is_some())? {
o.insert("count".into(), n.clone());
}
if let Some(t) = text_of(&p["title"], scope)? {
o.insert("title".into(), t.into());
}
// What it answers, as one short line: a post's text cut to 300.
if let Some(a) = text_of(&p["about"], scope)? {
o.insert("about".into(), crate::summary::one_line(&a, 300).into());
}
let given = Value::Object(given);
let mut fields = Vec::new();
for f in p["fields"].as_array().into_iter().flatten() {
let f = crate::compose::limited(prefilled(f, scope, ctx)?, &p["writes"]);
fields.push(f);
}
let fields = Value::Array(fields);
o.insert(
"key".into(),
key(&[&label.into(), &p["writes"], &p["call"], &given, &fields]).into(),
);
o.insert("fields".into(), fields);
o.insert("given".into(), given);
// What it writes, or the procedure it calls (a report) in their place.
if p["call"].is_object() {
o.insert("call".into(), procedure(&p["call"], scope, ctx)?);
o.insert("writes".into(), json!([]));
} else {
o.insert("writes".into(), p["writes"].clone());
}
Ok(Some(make("Compose", o, vec![])))
}
/// A composer's field as the form asks it, its `value` (a binding) read:
/// what it opens holding, a text's words (`value`), or a photo's picture
/// (`picture`, `{ src, fallback }`, shown and kept unless another is
/// picked); left out where the binding holds nothing. A photos field's
/// `exif` and a place's `locate`, bound to an account's preference, are
/// read as on unless it holds false; a place not to be located is filled
/// from no photo (its `from` left out), and `locate` goes no further.
fn prefilled(f: &Value, scope: &Value, ctx: &Ctx) -> R<Value> {
let mut f = f.clone();
for k in ["exif", "locate"] {
let bound = f.get(k).filter(|v| is_binding(v)).cloned();
if let Some(b) = bound {
let off = value(&b, scope, |v| *v == Value::Bool(false))?.is_some();
f[k] = Value::Bool(!off);
}
}
let locate = f.as_object_mut().and_then(|o| o.remove("locate"));
if locate == Some(Value::Bool(false))
&& let Some(o) = f.as_object_mut()
{
o.remove("from");
}
let Some(bound) = f.as_object_mut().and_then(|o| o.remove("value")) else {
return Ok(f);
};
let (key, found) = match f["kind"].as_str() {
Some("photos") => ("picture", source(&bound, scope, ctx, false)?),
_ => (
"value",
joined_text(&bound, scope)?.map_or(Value::Null, Value::from),
),
};
if !found.is_null() {
f[key] = found;
}
Ok(f)
}
/// A text's words from a binding, or `{"$join": [parts]}` (strings and
/// bindings) joined: nothing where a part holds nothing.
fn joined_text(bound: &Value, scope: &Value) -> R<Option<String>> {
let Some(parts) = op(bound, "$join") else {
return text_of(bound, scope);
};
let mut joined = String::new();
for part in parts {
let Some(s) = text_of(part, scope)? else {
return Ok(None);
};
joined.push_str(&s);
}
Ok(Some(joined))
}
/// A conversation (`Messages`), the layout's top node: its items in the
/// answer's order (`order` says which way that is; the client draws the
/// oldest at the top), each its bubble's children, its sender (`from`),
/// whether that is the signed-in person (`mine`), its time (`at`) and the
/// sender's name and face from `people` (`who`); an item its template
/// draws nothing of (a message deleted) is left out. `group` where more
/// than two people are in it, `page` where its items are the page's, and
/// `send`, a trusted view's, the call the client sends what is written as.
fn messages(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),
};
let people: Vec<&Value> = match &p["people"] {
Value::Null => None,
r if is_root_binding(r) => root_value(r, ctx.root)?,
b => value(b, scope, Value::is_array)?,
}
.and_then(Value::as_array)
.map(|a| a.iter().filter(|x| x.is_object()).collect())
.unwrap_or_default();
let path = |key: &str| -> R<Option<Path>> {
match p[key].as_str() {
None => Ok(None),
Some(s) => Path::parse(s)
.map(Some)
.ok_or_else(|| Fail::Bad(format!("{key}: a path within each item"))),
}
};
let (from, sent) = (path("from")?, path("sent")?);
let mut drawn = Vec::new();
for item in items {
let k = children(n, item, ctx);
if k.is_empty() {
continue;
}
let mut o = Map::new();
let sender = from
.as_ref()
.and_then(|f| f.get(item))
.and_then(Value::as_str)
.filter(|s| !s.is_empty());
if let Some(did) = sender {
o.insert("from".into(), did.into());
o.insert("mine".into(), (ctx.me == Some(did)).into());
if let Some(person) = people.iter().find(|x| x["did"] == did) {
let mut who = Map::new();
if let Some(name) = name_of(person) {
who.insert("name".into(), name.into());
}
let face = source_of(person.get("avatar"), ctx, true);
if !face.is_null() {
who.insert("avatar".into(), face);
}
o.insert("who".into(), Value::Object(who));
}
}
if let Some(at) = sent
.as_ref()
.and_then(|s| s.get(item))
.and_then(Value::as_str)
{
o.insert("at".into(), at.into());
}
o.insert("k".into(), Value::Array(k));
drawn.push(Value::Object(o));
}
let mut o = Map::new();
if let Some(order) = str_at(p, "order") {
o.insert("order".into(), order.into());
}
if let Some(e) = str_at(p, "empty") {
o.insert("empty".into(), e.into());
}
let many = people
.iter()
.filter_map(|x| x["did"].as_str())
.collect::<std::collections::BTreeSet<_>>()
.len()
> 2;
o.insert("group".into(), many.into());
if paged(p, scope, ctx) {
o.insert("page".into(), true.into());
}
if p["send"].is_object() && ctx.me.is_some() {
match procedure(&p["send"], scope, ctx) {
Ok(called) => {
o.insert("send".into(), called);
}
Err(Fail::Missing) => {}
Err(e) => return Err(e),
}
}
let mut out = make("Messages", o, vec![]);
out["items"] = Value::Array(drawn);
Ok(Some(out))
}
#[cfg(test)]
mod tests {
use super::*;
fn ctx<'a>(root: &'a Value, origins: &'a [String]) -> Ctx<'a> {
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,
}
}
/// A screen opened at a form: its first Compose drawn as the screen,
/// or the one of a label, marked open; never a Menu's row nor one over
/// an item. An open query carries `compose` to the call it makes.
#[test]
fn a_screen_opens_at_the_form_it_is_asked_for() {
let compose = |label: &str| json!({ "c": "Compose", "p": { "label": label } });
let screen = || {
json!({ "c": "Stack", "k": [
{ "c": "Menu", "k": [compose("Edit")] },
{ "c": "List", "items": [{ "k": [compose("Reply")] }] },
{ "c": "Bar", "k": [compose("New gallery"), compose("Edit")] },
] })
};
let mut first = screen();
assert!(open_compose(&mut first, &json!(true)));
assert_eq!(first["k"][2]["k"][0]["p"]["open"], true);
assert_eq!(first["k"][0]["k"][0]["p"].get("open"), None);
let mut named = screen();
assert!(open_compose(&mut named, &json!("Edit")));
assert_eq!(named["k"][2]["k"][1]["p"]["open"], true);
assert_eq!(named["k"][2]["k"][0]["p"].get("open"), None);
assert!(!open_compose(&mut screen(), &json!("Reply")));
let root = json!({});
let list = |compose: Value| {
json!({ "component": "List", "props": { "items": { "$": "rows" },
"open": { "query": "a.b.getStories", "params": { "actor": { "$": "did" } }, "compose": compose } },
"children": [{ "component": "Text", "props": { "value": { "$": "did" } } }] })
};
let scope = json!({ "rows": [{ "did": "did:plc:me" }] });
let opened = |compose: Value| {
resolve(&list(compose), &scope, &ctx(&root, &[])).unwrap()["items"][0]["open"]["call"]
["args"]["compose"]
.clone()
};
assert_eq!(opened(json!(true)), true);
assert_eq!(opened(json!("New story")), "New story");
assert_eq!(opened(json!(false)), Value::Null);
// Your story: at its form with none of one's own, as it is with some.
let yours = |stories: Value| {
let strip = json!({ "component": "List", "props": { "items": { "$": "rows" }, "style": "strip",
"first": { "did": "did:plc:me", "stories": stories,
"open": { "query": "a.b.getStories", "params": { "actor": { "$": "did" } },
"compose": true, "unless": "stories" } },
"children": [{ "component": "Text", "props": { "value": { "$": "did" } } }] } });
resolve(&strip, &json!({ "rows": [] }), &ctx(&root, &[])).unwrap()["items"][0]["open"]["call"]["args"]
.clone()
};
assert_eq!(yours(json!([]))["compose"], true);
assert_eq!(yours(json!([{ "uri": "at://s" }]))["compose"], Value::Null);
assert_eq!(
yours(json!([{ "uri": "at://s" }]))["params"]["actor"],
"did:plc:me"
);
}
/// The hero: the first picture drawn large, in drawing order, past
/// pictures drawn small and lists scrolled sideways (stories over a
/// feed), with a gallery photo's or a slide's sizes, a cover's alone
/// (a tile, narrower than the page); a profile's banner, else its
/// avatar; none where nothing is drawn large.
#[test]
fn a_tree_names_its_hero() {
let image = |size: Option<&str>, src: &str| json!({ "c": "Image", "p": { "src": { "src": src, "fallback": null }, "size": size } });
let items = |c: &str| json!({ "c": c, "items": [{ "src": null }, { "src": { "src": "g1" }, "srcset": "g0 1000w, g1 2000w" }, { "src": { "src": "g2" } }] });
let stack = |k: Value| json!({ "c": "Stack", "k": k });
let card = json!({ "k": [image(Some("face"), "avatar"), image(None, "photo")] });
let feed = stack(json!([{ "c": "List", "items": [card] }]));
let alone = |s| Some((s, None));
assert_eq!(hero(&feed), alone("photo"));
let sideways = |style: &str| json!({ "c": "List", "p": { "style": style }, "items": [{ "k": [image(Some("large"), "story")] }] });
for style in ["strip", "shelf"] {
assert_eq!(hero(&stack(json!([sideways(style), feed]))), alone("photo"));
assert_eq!(hero(&sideways(style)), None);
}
let sized = Some(("g1", Some("g0 1000w, g1 2000w")));
assert_eq!(
hero(&stack(json!([image(Some("thumb"), "t"), items("Gallery")]))),
sized
);
assert_eq!(hero(&items("Slides")), sized);
assert_eq!(
hero(&stack(json!([items("Covers"), image(Some("large"), "l")]))),
alone("g1")
);
assert_eq!(hero(&json!({ "c": "Slides" })), None);
let profile = |p: Value| json!({ "c": "Profile", "p": p });
assert_eq!(
hero(&profile(
json!({ "banner": { "src": "b" }, "avatar": { "src": "a" } })
)),
alone("b")
);
assert_eq!(
hero(&profile(
json!({ "banner": null, "avatar": { "src": "a" } })
)),
alone("a")
);
assert_eq!(
hero(&stack(json!([
image(Some("large"), "l"),
image(Some("avatar"), "a")
]))),
alone("l")
);
assert_eq!(
hero(&stack(
json!([image(Some("icon"), "i"), { "c": "Text", "p": { "runs": [] } }])
)),
None
);
}
/// A chat's row: its other members' names, but a group's own name where
/// it has one; "You:" before the last message only when one sent it;
/// what is unread only when there is some. Signed out, no one is mine.
#[test]
fn stacks_gate_and_lists_keep_mine_or_others() {
let root = json!({});
let origins: Vec<String> = vec![];
let mut c = ctx(&root, &origins);
c.me = Some("did:plc:me");
let text = |v: Value| json!({ "component": "Text", "props": { "value": v } });
let layout = json!({ "component": "Stack", "children": [
{ "component": "Stack", "props": { "unless": "kind.name" }, "children": [
{ "component": "List", "props": { "items": { "$": "members" }, "others": "did", "style": "inline", "open": false },
"children": [text(json!({ "$": "handle" }))] } ] },
text(json!({ "$": "kind.name" })),
{ "component": "Stack", "props": { "mine": "lastMessage.sender.did" }, "children": [text(json!("You:"))] },
{ "component": "Stack", "props": { "others": "lastMessage.sender.did" }, "children": [text(json!("Them:"))] },
{ "component": "List", "props": { "items": { "$": "members" }, "mine": "did", "style": "inline", "open": false },
"children": [text(json!({ "$": "did" }))] },
{ "component": "Stack", "props": { "when": "unreadCount" }, "children": [text(json!("unread"))] },
] });
let texts = |tree: &Value| -> Vec<String> {
let mut out = Vec::new();
fn walk(n: &Value, out: &mut Vec<String>) {
if n["c"] == "Text" {
out.push(
n["p"]["runs"][0]["text"]
.as_str()
.unwrap_or_default()
.to_string(),
);
}
for k in n["k"]
.as_array()
.into_iter()
.flatten()
.chain(n["items"].as_array().into_iter().flatten())
{
walk(k, out);
}
}
walk(tree, &mut out);
out
};
let members = json!([{ "did": "did:plc:me", "handle": "me.test" }, { "did": "did:plc:you", "handle": "you.test" }]);
let direct = json!({ "members": members, "lastMessage": { "sender": { "did": "did:plc:me" } }, "unreadCount": 0 });
let tree = resolve(&layout, &direct, &c).unwrap();
assert_eq!(texts(&tree), ["you.test", "You:", "did:plc:me"]);
let group = json!({ "members": members, "kind": { "name": "Pals" },
"lastMessage": { "sender": { "did": "did:plc:you" } }, "unreadCount": 2 });
let tree = resolve(&layout, &group, &c).unwrap();
assert_eq!(texts(&tree), ["Pals", "Them:", "did:plc:me", "unread"]);
c.me = None;
let tree = resolve(&layout, &direct, &c).unwrap();
assert_eq!(texts(&tree), ["me.test", "you.test", "Them:"]);
}
/// A count reads with its thousands grouped; a year, a number with a
/// prefix or a fraction stays as it is.
#[test]
fn counts_group_their_thousands() {
let drawn = |value: Value, prefix: Option<&str>| {
let p = json!({ "value": value, "prefix": prefix });
text(&p, &json!({})).ok().flatten().unwrap()["p"]["runs"][0]["text"].clone()
};
assert_eq!(drawn(json!(67519), None), "67,519");
assert_eq!(drawn(json!(1234567), None), "1,234,567");
assert_eq!(drawn(json!(2026), None), "2026");
assert_eq!(drawn(json!(12345), Some("#")), "#12345");
assert_eq!(drawn(json!(12345.5), None), "12345.5");
}
#[test]
fn facets_count_utf8_bytes_and_drop_unsafe_links() {
let text = "héllo 🦋 @bob.test";
let at = "héllo 🦋 ".len() as u64;
let facets = json!([
{ "index": { "byteStart": at, "byteEnd": at + 9 }, "features": [{ "$type": "app.bsky.richtext.facet#mention", "did": "did:plc:bob" }] },
{ "index": { "byteStart": 0, "byteEnd": 3 }, "features": [{ "$type": "app.bsky.richtext.facet#link", "uri": "javascript:alert(1)" }] },
]);
assert_eq!(
Value::Array(facet_runs(text, Some(&facets), &ctx(&json!({}), &[]))),
json!([{ "text": "hé" }, { "text": "llo 🦋 " }, { "text": "@bob.test", "actor": "did:plc:bob" }])
);
}
/// A #tag opens a search for it in the app the tree is in, as that
/// app's page view says; elsewhere it is drawn as words alone.
#[test]
fn a_tag_opens_its_apps_search() {
let text = "shot on #film";
let facets = json!([{ "index": { "byteStart": 8, "byteEnd": 13 },
"features": [{ "$type": "app.bsky.richtext.facet#tag", "tag": "film" }] }]);
let root = json!({});
let mut c = ctx(&root, &[]);
assert_eq!(
facet_runs(text, Some(&facets), &c)[1],
json!({ "text": "#film", "tag": "film" })
);
c.people = Some("grain.social".into());
let open = &facet_runs(text, Some(&facets), &c)[1]["open"];
assert_eq!(open["call"]["args"]["method"], "social.grain.feed.getFeed");
assert_eq!(open["call"]["args"]["params"]["tag"], "film");
c.people = Some("bsky.app".into());
let open = &facet_runs(text, Some(&facets), &c)[1]["open"];
assert_eq!(open["call"]["args"]["method"], "app.bsky.feed.searchPosts");
assert_eq!(open["call"]["args"]["params"]["q"], "#film");
}
/// A conversation: each message its bubble, its sender's name and face
/// from the people, the person's own `mine`, one its template draws
/// nothing of left out; its box's call resolved but for the text, and
/// only for someone signed in in a trusted view. An Action's call alike.
#[test]
fn a_conversation_and_its_calls_are_resolved_but_for_the_text() {
let root = json!({ "params": { "convoId": "c1" }, "response": { "relatedProfiles": [
{ "did": "did:plc:me", "handle": "me.test" },
{ "did": "did:plc:you", "handle": "you.test", "displayName": "You", "avatar": "https://cdn.bsky.app/img/avatar/plain/you@jpeg" },
] } });
let origins = vec!["https://cdn.bsky.app".to_string()];
let send = json!({ "method": "chat.bsky.convo.sendMessage", "service": "did:web:api.bsky.chat#bsky_chat",
"input": { "convoId": { "$root": "params.convoId" }, "message": { "text": { "$text": true } } } });
let layout = json!({ "component": "Messages", "props": { "items": { "$": "items" }, "from": "sender.did",
"sent": "sentAt", "people": { "$root": "response.relatedProfiles" }, "order": "newest-first", "send": send },
"children": [
{ "component": "Text", "props": { "value": { "$": "text" } } },
{ "component": "Action", "props": { "label": "Read", "call": { "method": "chat.bsky.convo.updateRead",
"service": "did:web:api.bsky.chat#bsky_chat", "input": { "convoId": { "$root": "params.convoId" }, "messageId": { "$": "id" } } } } },
] });
let scope = json!({ "items": [
{ "id": "m2", "text": "hi", "sender": { "did": "did:plc:you" }, "sentAt": "2026-11-16T09:01:00Z" },
{ "id": "m1", "sender": { "did": "did:plc:you" }, "sentAt": "2026-11-16T09:00:00Z" },
{ "id": "m0", "text": "hello", "sender": { "did": "did:plc:me" }, "sentAt": "2026-11-16T08:59:00Z" },
] });
let mut c = ctx(&root, &origins);
c.me = Some("did:plc:me");
let tree = resolve(&layout, &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(tree["p"]["order"], "newest-first");
assert_eq!(tree["p"]["page"], true);
assert_eq!(tree["p"]["group"], false);
assert_eq!(
tree["p"]["send"]["input"],
json!({ "convoId": "c1", "message": { "text": { "$text": true } } })
);
let items = tree["items"].as_array().unwrap();
// The message with no text still draws its Read action.
assert_eq!(items.len(), 3);
assert_eq!(items[0]["mine"], false);
assert_eq!(items[0]["who"]["name"], "You");
assert_eq!(
items[0]["who"]["avatar"]["src"],
"https://cdn.bsky.app/img/avatar/plain/you@jpeg"
);
assert_eq!(items[0]["at"], "2026-11-16T09:01:00Z");
assert_eq!(items[2]["mine"], true);
assert_eq!(items[2]["who"], json!({ "name": "me.test" }));
assert_eq!(
items[0]["k"][1]["p"]["call"]["input"],
json!({ "convoId": "c1", "messageId": "m2" })
);
// A message its template draws nothing of is left out.
let bare = json!({ "component": "Messages", "props": { "items": { "$": "items" }, "from": "sender.did" },
"children": [{ "component": "Text", "props": { "value": { "$": "text" } } }] });
assert_eq!(
resolve(&bare, &scope, &c).unwrap()["items"]
.as_array()
.unwrap()
.len(),
2
);
// Signed out, no box; untrusted, no call at all.
c.me = None;
assert!(
resolve(&layout, &scope, &c).unwrap()["p"]
.get("send")
.is_none()
);
c.trusted = false;
c.me = Some("did:plc:me");
let untrusted = resolve(&layout, &scope, &c).unwrap();
assert!(untrusted["p"].get("send").is_none());
assert_eq!(untrusted["items"][0]["k"].as_array().unwrap().len(), 1);
}
#[test]
fn plain_links_lose_trailing_punctuation() {
assert_eq!(
Value::Array(link_runs(
"see (https://a.example/x), then https://b.example/y."
)),
json!([
{ "text": "see (" }, { "text": "https://a.example/x", "link": "https://a.example/x" },
{ "text": "), then " }, { "text": "https://b.example/y", "link": "https://b.example/y" }, { "text": "." },
])
);
}
#[test]
fn urls_off_the_origins_never_load_and_absent_data_draws_nothing() {
let root = json!({});
let origins = vec!["https://cdn.bsky.app".to_string()];
let c = ctx(&root, &origins);
let layout = json!({ "component": "Stack", "children": [
{ "component": "Image", "props": { "src": { "$": "good" } } },
{ "component": "Image", "props": { "src": { "$": "evil" } } },
{ "component": "Image", "props": { "src": { "$": "none" } } },
{ "component": "Text", "props": { "value": { "$": "nested" } } },
] });
let scope = json!({ "good": "https://cdn.bsky.app/a.jpg", "evil": "https://evil.example/a.jpg", "nested": { "a": 1 } });
let tree = resolve(&layout, &scope, &c).unwrap();
check::checked(&tree);
let k = tree["k"].as_array().unwrap();
assert_eq!(k.len(), 3, "the image with no value draws nothing");
assert_eq!(k[0]["p"]["src"]["src"], "https://cdn.bsky.app/a.jpg");
assert_eq!(k[1]["p"]["src"], Value::Null);
assert_eq!(k[2]["c"], "Error");
}
#[test]
fn an_item_opens_its_query_and_a_like_is_resolved_but_not_stamped() {
let root = json!({ "method": "app.bsky.feed.getFeed", "params": {} });
let c = ctx(&root, &[]);
let layout = json!({ "component": "List", "props": { "items": { "$": "items" },
"open": { "query": "app.bsky.feed.getPostThread", "params": { "uri": { "$": "post.uri" } } } },
"children": [{ "component": "Action", "props": { "label": "Like",
"create": { "collection": "app.bsky.feed.like", "record": { "subject": { "$strongRef": "post" }, "createdAt": { "$now": true } } },
"existing": { "$": "post.viewer.like" }, "count": { "$": "post.likeCount" } } }] });
let scope = json!({ "items": [{ "post": { "uri": "at://did:plc:a/app.bsky.feed.post/1", "cid": "bafy", "likeCount": 7 } }] });
let tree = resolve(&layout, &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(tree["p"]["page"], true);
let item = &tree["items"][0];
assert_eq!(
item["open"]["call"]["args"]["params"]["uri"],
"at://did:plc:a/app.bsky.feed.post/1"
);
let like = &item["k"][0]["p"];
assert_eq!(
like["create"]["record"]["subject"],
json!({ "uri": "at://did:plc:a/app.bsky.feed.post/1", "cid": "bafy" })
);
assert_eq!(
like["create"]["record"]["createdAt"],
json!({ "$now": true })
);
assert!(like.get("existing").is_none());
assert_eq!(like["count"], 7);
}
/// A reply's composer: its given values resolved (the root the first
/// that resolves: the thread's root for a reply, else the post itself;
/// the view's own scope read), its fields and writes sent as written,
/// for the client to fill; closed, its count alone, as a Stat.
#[test]
fn a_reply_composer_resolves_its_given_values() {
let root = json!({ "response": { "gallery": { "uri": "at://did:plc:g/social.grain.gallery/1" } } });
let c = ctx(&root, &[]);
let fields = json!([{ "name": "text", "kind": "text", "placeholder": "Write your reply", "max": 300, "facets": true, "required": true }]);
let writes = json!([{ "collection": "app.bsky.feed.post", "record": {
"text": { "$value": "text" }, "facets": { "$facets": "text" }, "createdAt": { "$now": true },
"reply": { "root": { "$value": "root" }, "parent": { "$value": "parent" } } } }]);
let layout = json!({ "component": "Compose", "props": { "label": "Reply", "icon": "reply", "send": "Reply",
"count": { "$": "post.replyCount" }, "closed": { "$": "post.viewer.replyDisabled" },
"about": { "$": "post.record.text" },
"given": { "root": { "$first": [{ "$": "post.record.reply.root" }, { "$strongRef": "post" }] },
"parent": { "$strongRef": "post" }, "gallery": { "$root": "response.gallery.uri" } },
"fields": fields, "writes": writes } });
let post = |reply: Option<Value>| {
let mut p = json!({ "uri": "at://did:plc:a/app.bsky.feed.post/2", "cid": "bafy2", "replyCount": 0,
"record": { "text": "hello" } });
if let Some(r) = reply {
p["record"]["reply"] = r;
}
json!({ "post": p })
};
let top = resolve(&layout, &post(None), &c).unwrap();
check::checked(&top);
let p = &top["p"];
let own = json!({ "uri": "at://did:plc:a/app.bsky.feed.post/2", "cid": "bafy2" });
assert_eq!(
p["given"],
json!({ "root": own, "parent": own, "gallery": "at://did:plc:g/social.grain.gallery/1" })
);
// Its text field carries its post's lexicon's bytes beside its graphemes.
let mut limited = fields.clone();
limited[0]["maxBytes"] = json!(3000);
assert_eq!((&p["fields"], &p["writes"]), (&limited, &writes));
assert_eq!(
(&p["about"], &p["count"], &p["send"]),
(&json!("hello"), &json!(0), &json!("Reply"))
);
let thread = json!({ "uri": "at://did:plc:r/app.bsky.feed.post/1", "cid": "bafy1" });
let deep = resolve(
&layout,
&post(Some(json!({ "root": thread, "parent": thread }))),
&c,
)
.unwrap();
assert_eq!(deep["p"]["given"]["root"], thread);
// Its author takes no replies: its count alone, as a Stat.
let mut closed = post(None);
closed["post"]["viewer"] = json!({ "replyDisabled": true });
let stat = resolve(&layout, &closed, &c).unwrap();
check::checked(&stat);
assert_eq!(
stat,
json!({ "c": "Stat", "p": { "value": 0, "icon": "reply", "label": "Reply" } })
);
}
/// Grain's settings run as Grain's own do: the account (who is signed
/// in, opening their page; Delete account, by a plan its handle typed
/// confirms, signing out after; Sign out, which the host does), its
/// look, its feeds (My feeds, the settings opened at them),
/// notifications, moderation, upload defaults, then Grain's policies,
/// pages on grain.social.
#[test]
fn grains_settings_are_grains_sections() {
let doc: Value = serde_json::from_str(include_str!(
"../testdata/grain/apps/views/grain-settings.json"
))
.unwrap();
let root = json!({ "me": { "did": "did:plc:me", "handle": "me.test" },
"response": { "preferences": [] },
"joins": { "me": { "did": "did:plc:me", "handle": "me.test", "displayName": "Me",
"avatar": "https://cdn.grain.social/a.jpg" } } });
let origins = vec!["https://cdn.grain.social".to_string()];
let mut c = ctx(&root, &origins);
c.people = Some("grain.social".into());
let tree = resolve(&doc["query"]["layout"], &root, &c).unwrap();
check::checked(&tree);
// Not opened at feeds: the settings, and no My feeds.
assert_eq!(tree["k"].as_array().map(Vec::len), Some(1));
let k = tree["k"][0]["k"].as_array().unwrap();
let headings: Vec<&Value> = k
.iter()
.filter(|n| n["c"] == "Text" && n["p"]["style"] == "heading")
.map(|n| &n["p"]["runs"][0]["text"])
.collect();
assert_eq!(
headings,
[
"Account",
"Appearance",
"Feeds",
"Notifications",
"Moderation",
"Upload defaults",
"About"
]
);
let opens: Vec<Vec<&Value>> = k
.iter()
.filter(|n| n["c"] == "List")
.map(|n| {
let items = n["items"].as_array().unwrap();
items.iter().map(|i| &i["open"]).collect()
})
.collect();
assert_eq!(opens[0], [&c.actor_call("did:plc:me")]);
assert_eq!(opens[1], [&json!({ "host": "signOut" })]);
let delete = k.iter().find(|n| n["c"] == "Action").unwrap();
let p = &delete["p"];
assert_eq!(
(&p["label"], &p["tone"], &p["handle"], &p["signOut"]),
(
&json!("Delete account"),
&json!("danger"),
&json!("me.test"),
&json!(true)
)
);
assert!(
p["confirm"]
.as_str()
.unwrap()
.starts_with("Delete your Grain account?\n\n")
);
assert_eq!(
(&p["call"], &p["repeat"]),
(
&json!({ "method": "social.grain.server.getAccountDeletionPlan",
"service": "did:web:grain.social#grain_appview", "input": {} }),
&json!(true)
)
);
assert_eq!(
opens[2][0]["call"]["args"]["method"],
"social.grain.actor.getPreferences"
);
assert_eq!(opens[2][0]["call"]["args"]["at"], "feeds");
assert_eq!(opens[3].len(), 2, "muted and blocked");
assert_eq!(opens[4].len(), 5, "Grain's policies");
assert!(opens[4].iter().all(|o| {
o["url"]
.as_str()
.is_some_and(|u| u.starts_with("https://grain.social/support/"))
}));
// Who is signed in: their picture, name and handle.
let me = tree.to_string();
assert!(me.contains("https://cdn.grain.social/a.jpg") && me.contains("\"Me\""));
}
/// Grain's settings opened at feeds are My feeds alone: a row for each
/// feed pinned, in its order, with Move up but on the first, Move down
/// but on the last, and Unpin, each sending the whole preference; with
/// none pinned, Grain's own three, which pinning keeps.
#[test]
fn grains_my_feeds_move_and_unpin_the_feeds_pinned() {
let doc: Value = serde_json::from_str(include_str!(
"../testdata/grain/apps/views/grain-settings.json"
))
.unwrap();
let feed = |id: &str, label: &str, kind: &str, path: &str| json!({ "id": id, "label": label, "type": kind, "path": path });
let recent = feed("recent", "Recent", "feed", "/feeds/recent");
let fuji = feed(
"camera:Fuji X100V",
"Fuji X100V",
"camera",
"/camera/Fuji X100V",
);
let film = feed("hashtag:film", "film", "hashtag", "/hashtags/film");
let root = json!({ "at": "feeds", "response": { "preferences": [
{ "$type": "social.grain.actor.defs#themePref", "theme": "dark" },
{ "$type": "social.grain.actor.defs#pinnedFeedsPref", "items": [recent, fuji, film] },
] } });
let rows = |root: &Value| {
let tree = resolve(&doc["query"]["layout"], root, &ctx(root, &[])).unwrap();
check::checked(&tree);
assert_eq!(
tree["k"].as_array().map(Vec::len),
Some(1),
"My feeds alone"
);
let mut found = Vec::new();
fn lists(v: &Value, out: &mut Vec<Value>) {
match v {
Value::Object(o) if o.get("c") == Some(&json!("List")) => out.push(v.clone()),
Value::Object(o) => o.values().for_each(|c| lists(c, out)),
Value::Array(a) => a.iter().for_each(|c| lists(c, out)),
_ => {}
}
}
lists(&tree, &mut found);
assert_eq!(found.len(), 1);
let mut rows: Vec<Vec<(String, Value)>> = Vec::new();
for item in found[0]["items"].as_array().unwrap() {
let mut actions = Vec::new();
fn each(v: &Value, out: &mut Vec<(String, Value)>) {
match v {
Value::Object(o) if o.get("c") == Some(&json!("Action")) => out.push((
o["p"]["label"].as_str().unwrap().to_string(),
o["p"]["call"]["input"]["preference"]["items"].clone(),
)),
Value::Object(o) => o.values().for_each(|c| each(c, out)),
Value::Array(a) => a.iter().for_each(|c| each(c, out)),
_ => {}
}
}
each(item, &mut actions);
rows.push(actions);
}
rows
};
let ids = |items: &Value| -> Vec<String> {
items
.as_array()
.unwrap()
.iter()
.map(|i| i["id"].as_str().unwrap().to_string())
.collect()
};
let pinned = rows(&root);
let shape: Vec<Vec<&str>> = pinned
.iter()
.map(|r| r.iter().map(|(l, _)| l.as_str()).collect())
.collect();
assert_eq!(
shape,
[
vec!["Move down", "Unpin"],
vec!["Move up", "Move down", "Unpin"],
vec!["Move up", "Unpin"]
]
);
assert_eq!(
pinned[1][0].1,
json!([fuji, recent, film]),
"the whole feeds, moved"
);
assert_eq!(
ids(&pinned[1][1].1),
["recent", "hashtag:film", "camera:Fuji X100V"]
);
assert_eq!(ids(&pinned[1][2].1), ["recent", "hashtag:film"]);
// None pinned: Grain's three, as the strip has them.
let unset = json!({ "at": "feeds", "response": { "preferences": [] } });
let defaults = rows(&unset);
assert_eq!(defaults.len(), 3);
assert_eq!(ids(&defaults[0][1].1), ["following", "foryou"]);
assert_eq!(ids(&defaults[2][0].1), ["recent", "foryou", "following"]);
}
/// Grain's camera, place and hashtag feeds have Pin feed where they are
/// not pinned and Unpin feed where they are, in the screen's bar (a pin,
/// and a pin filled), each the whole preference with the feed added at
/// its end or taken out, and signed out a bar of its title alone; the
/// strip over a pinned one has it chosen, its feed opened with its
/// camera, place or tag.
#[test]
fn grains_feeds_pin_and_unpin_and_the_strip_opens_them() {
let doc: Value =
serde_json::from_str(include_str!("../testdata/grain/apps/views/grain-feed.json"))
.unwrap();
let generator =
|rkey: &str| format!("at://did:web:grain.social/social.grain.feed.generator/{rkey}");
let recent =
json!({ "id": "recent", "label": "Recent", "type": "feed", "path": "/feeds/recent" });
let page = |params: Value, items: Option<Value>| {
let mut prefs =
vec![json!({ "$type": "social.grain.actor.defs#themePref", "theme": "dark" })];
if let Some(items) = items {
prefs.push(
json!({ "$type": "social.grain.actor.defs#pinnedFeedsPref", "items": items }),
);
}
json!({ "method": "social.grain.feed.getFeed", "params": params, "me": { "did": "did:plc:me" },
"response": { "items": [] }, "items": [], "joins": { "prefs": { "preferences": prefs } } })
};
let drawn = |root: &Value| {
let tree = resolve(&doc["query"]["layout"], root, &ctx(root, &[])).unwrap();
check::checked(&tree);
let mut found = Vec::new();
fn walk(v: &Value, out: &mut Vec<Value>) {
match v {
Value::Object(o)
if ["Action", "Tabs", "Bar"]
.iter()
.any(|c| o.get("c") == Some(&json!(c))) =>
{
out.push(v.clone());
o.get("k").into_iter().for_each(|k| walk(k, out));
}
Value::Object(o) => o.values().for_each(|c| walk(c, out)),
Value::Array(a) => a.iter().for_each(|c| walk(c, out)),
_ => {}
}
}
walk(&tree, &mut found);
found
};
let pin = |nodes: &[Value]| -> Vec<(String, Value)> {
nodes
.iter()
.filter(|n| n["c"] == "Action")
.map(|n| {
(
n["p"]["label"].as_str().unwrap().to_string(),
n["p"]["call"]["input"].clone(),
)
})
.collect()
};
let fuji = json!({ "id": "camera:Fuji X100V", "label": "Fuji X100V", "type": "camera",
"path": "/camera/Fuji X100V" });
let camera = json!({ "feed": generator("camera"), "camera": "Fuji X100V" });
// Not pinned, never set: Pin adds it to Grain's three.
let nodes = drawn(&page(camera.clone(), None));
let actions = pin(&nodes);
assert_eq!(actions.len(), 1);
assert_eq!(actions[0].0, "Pin feed");
let bar = |nodes: &[Value]| nodes.iter().find(|n| n["c"] == "Bar").unwrap().clone();
let icons = |bar: &Value| -> Vec<Value> {
bar["k"]
.as_array()
.into_iter()
.flatten()
.map(|a| a["p"]["icon"].clone())
.collect()
};
assert_eq!(bar(&nodes)["p"]["title"], "Fuji X100V");
assert_eq!(icons(&bar(&nodes)), [json!("pin")]);
// Signed out: the bar's title alone.
let mut out = page(camera.clone(), None);
out.as_object_mut().unwrap().remove("me");
let nodes = drawn(&out);
assert!(pin(&nodes).is_empty());
assert_eq!(bar(&nodes)["p"]["title"], "Fuji X100V");
assert_eq!(icons(&bar(&nodes)), Vec::<Value>::new());
let items = &actions[0].1["preference"]["items"];
assert_eq!(
actions[0].1["preference"]["$type"],
"social.grain.actor.defs#pinnedFeedsPref"
);
assert_eq!(items.as_array().map(Vec::len), Some(4));
assert_eq!(items[3], fuji);
// Pinned: Unpin takes it out, the strip has it chosen; a kind of
// feed the strip can't open (a group) has no tab, and stays pinned.
let group = json!({ "id": "group:did:plc:g", "label": "Friends", "type": "group", "path": "/groups/g" });
let nodes = drawn(&page(camera.clone(), Some(json!([recent, fuji, group]))));
assert_eq!(
pin(&nodes),
[(
"Unpin feed".to_string(),
json!({ "preference": {
"$type": "social.grain.actor.defs#pinnedFeedsPref", "items": [recent, group] } })
)]
);
assert_eq!(icons(&bar(&nodes)), [json!("pinned")]);
let tabs = nodes.iter().find(|n| n["c"] == "Tabs").unwrap();
assert_eq!(tabs["p"]["items"].as_array().map(Vec::len), Some(2));
assert_eq!(tabs["p"]["items"][1]["selected"], true);
assert_eq!(
tabs["p"]["items"][1]["open"]["call"]["args"]["params"],
camera
);
// A place and a hashtag pinned so: their ids, labels and paths.
let place = json!({ "feed": generator("location"), "location": "8a2a1072b59ffff", "name": "Brooklyn" });
let added = pin(&drawn(&page(place.clone(), Some(json!([recent])))));
assert_eq!(
added[0].1["preference"]["items"][1],
json!({ "id": "location:8a2a1072b59ffff", "label": "Brooklyn", "type": "location",
"path": "/location/8a2a1072b59ffff" })
);
let tag = json!({ "feed": generator("hashtag"), "tag": "film" });
let added = pin(&drawn(&page(tag.clone(), Some(json!([recent])))));
assert_eq!(
added[0].1["preference"]["items"][1],
json!({ "id": "hashtag:film", "label": "film", "type": "hashtag", "path": "/hashtags/film" })
);
// A camera's, a place's and a hashtag's galleries drawn wide; the home feeds at the reading width.
for params in [camera, place, tag] {
assert_eq!(measure(&doc, &page(params, None)), Some("wide"));
}
let home = json!({ "feed": generator("foryou") });
assert_eq!(measure(&doc, &page(home, None)), None);
}
/// Grain's settings choose a theme and, for each kind of notification,
/// from whom: each as stored, else its default, each call keeping what
/// the others are.
#[test]
fn grains_settings_choose_a_theme_and_from_whom() {
let doc: Value = serde_json::from_str(include_str!(
"../testdata/grain/apps/views/grain-settings.json"
))
.unwrap();
let root = json!({ "response": { "preferences": [
{ "$type": "social.grain.actor.defs#themePref", "theme": "dark" },
{ "$type": "social.grain.actor.defs#notificationsPref",
"favorites": { "push": false, "inApp": true, "from": "follows" } },
] } });
let tree = resolve(&doc["query"]["layout"], &root, &ctx(&root, &[])).unwrap();
check::checked(&tree);
fn choices(v: &Value, out: &mut Vec<Value>) {
match v {
Value::Object(o) if o.get("c") == Some(&json!("Choice")) => {
out.push(o["p"].clone())
}
Value::Object(o) => o.values().for_each(|x| choices(x, out)),
Value::Array(a) => a.iter().for_each(|x| choices(x, out)),
_ => {}
}
}
let mut found = Vec::new();
choices(&tree, &mut found);
let said: Vec<(&Value, &Value)> = found.iter().map(|c| (&c["label"], &c["on"])).collect();
assert_eq!(
said,
[
(&json!("Theme"), &json!("dark")),
(&json!("From"), &json!("follows")),
(&json!("From"), &json!("all")),
(&json!("From"), &json!("all")),
(&json!("From"), &json!("all")),
]
);
// Favorites' from chosen anew: its push and the other kinds as they are.
let pref = &found[1]["call"]["input"]["preference"];
assert_eq!(
pref["favorites"],
json!({ "push": false, "inApp": true, "from": { "$on": true } })
);
assert_eq!(
pref["follows"],
json!({ "push": true, "inApp": true, "from": "all" })
);
}
/// Grain's New gallery keeps to the account's upload defaults
/// (`#photoMetadataPref`): each photo's camera details read, and
/// written as `social.grain.photo.exif`, unless includeExif is false;
/// the place filled from the first located photo unless
/// includeLocation is false; both on where the account set neither,
/// or no preferences were read (signed out).
#[test]
fn grains_new_gallery_keeps_to_upload_defaults() {
let doc: Value =
serde_json::from_str(include_str!("../testdata/grain/apps/views/grain-feed.json"))
.unwrap();
fn find(v: &Value) -> Option<&Value> {
match v {
Value::Object(o)
if o.get("component") == Some(&json!("Compose"))
&& o["props"]["label"] == "New gallery" =>
{
Some(v)
}
Value::Object(o) => o.values().find_map(find),
Value::Array(a) => a.iter().find_map(find),
_ => None,
}
}
let node = find(&doc["query"]["layout"]).expect("New gallery");
let root = json!({});
let c = ctx(&root, &[]);
let prefs = |pref: Value| {
let mut pref = pref;
pref["$type"] = json!("social.grain.actor.defs#photoMetadataPref");
json!({ "joins": { "prefs": { "preferences": [
{ "$type": "social.grain.actor.defs#pinnedFeedsPref", "items": [] }, pref ] } } })
};
for (scope, exif, located) in [
(json!({ "joins": { "prefs": null } }), true, true),
(prefs(json!({})), true, true),
(
prefs(json!({ "includeExif": false, "includeLocation": true })),
false,
true,
),
(
prefs(json!({ "includeExif": true, "includeLocation": false })),
true,
false,
),
] {
let tree = resolve(node, &scope, &c).unwrap();
check::checked(&tree);
let fields = &tree["p"]["fields"];
assert_eq!(fields[0]["exif"], exif, "{scope}");
let from = if located {
json!("photos")
} else {
Value::Null
};
assert_eq!(fields[3]["from"], from, "{scope}");
assert!(fields[3].get("locate").is_none());
// What the form sends: a photo's camera details only where it
// reads them, and the writes make their record only then.
let mut photo = json!({ "blob": { "$type": "blob", "ref": { "$link": "bafy" }, "mimeType": "image/jpeg", "size": 9 },
"alt": "", "aspectRatio": { "width": 3, "height": 2 } });
if exif {
photo["exif"] = json!({ "make": "Fujifilm" });
}
let values = json!({ "photos": [photo], "title": "Lisbon" });
let mut n = 0;
let made = crate::compose::expand(
&tree["p"]["writes"],
values.as_object().unwrap(),
&[],
"did:plc:me",
"2026-11-20T00:00:00.000Z",
|| {
n += 1;
format!("3kaaaaaaaaa{n:02}")
},
)
.unwrap();
let exifs = made
.iter()
.filter(|m| m.collection == "social.grain.photo.exif")
.count();
assert_eq!((made.len(), exifs), (3 + exifs, usize::from(exif)));
}
}
/// Grain's stories strip rings one's own Your story, as Grain does,
/// where one has a story of the last day (the `mine` join's stories);
/// with none, or none read, it is drawn unringed, its + to add one. It
/// opens one's stories at Add to your story (`compose`), which opens
/// only where there are none.
#[test]
fn grains_your_story_is_ringed_with_a_story_of_the_last_day() {
let doc: Value =
serde_json::from_str(include_str!("../testdata/grain/apps/views/grain-feed.json"))
.unwrap();
fn find(v: &Value) -> Option<&Value> {
match v {
Value::Object(o)
if o.get("component") == Some(&json!("List"))
&& o["props"]["first"]["label"] == "Your story" =>
{
Some(v)
}
Value::Object(o) => o.values().find_map(find),
Value::Array(a) => a.iter().find_map(find),
_ => None,
}
}
let strip = find(&doc["query"]["layout"]).expect("the stories strip");
let yours = |mine: Value| {
// The strip reads who has stories from the view's scope; none
// but oneself here.
let root = json!({ "me": { "did": "did:plc:me" }, "joins": {
"me": { "did": "did:plc:me", "handle": "me.test" }, "mine": mine,
"stories": { "authors": [] } } });
let tree = resolve(strip, &root, &ctx(&root, &[])).unwrap();
check::checked(&tree);
let first = tree["items"][0]["k"][0]["p"].clone();
assert_eq!(first["plus"], true);
let args = &tree["items"][0]["open"]["call"]["args"];
assert_eq!(
(&args["params"]["actor"], &args["compose"]),
(&json!("did:plc:me"), &json!(true))
);
first.get("ring").cloned()
};
let story = json!({ "stories": [{ "uri": "at://did:plc:me/social.grain.story/3k" }] });
assert_eq!(yours(story), Some(json!(true)));
assert_eq!(yours(json!({ "stories": [] })), None);
assert_eq!(yours(Value::Null), None);
}
/// Grain's Add to your story starts from the camera (its one photo's
/// `camera`, the library beside it) and is drawn as Grain's review of
/// the photo (`form: photo`): full-bleed, the place it was taken a chip
/// over it.
#[test]
fn grains_new_story_takes_a_photo_and_reviews_it() {
let doc: Value = serde_json::from_str(include_str!(
"../testdata/grain/apps/views/grain-stories.json"
))
.unwrap();
fn find(v: &Value) -> Option<&Value> {
match v {
Value::Object(o)
if o.get("component") == Some(&json!("Compose"))
&& o["props"]["label"] == "Add to your story" =>
{
Some(v)
}
Value::Object(o) => o.values().find_map(find),
Value::Array(a) => a.iter().find_map(find),
_ => None,
}
}
let node = find(&doc["query"]["layout"]).expect("Add to your story");
let root = json!({});
let scope = json!({ "joins": { "prefs": null } });
let tree = resolve(node, &scope, &ctx(&root, &[])).unwrap();
check::checked(&tree);
let p = &tree["p"];
assert_eq!(p["form"], "photo");
assert_eq!(
(
&p["fields"][0]["kind"],
&p["fields"][0]["max"],
&p["fields"][0]["camera"]
),
(&json!("photos"), &json!(1), &json!(true))
);
assert_eq!(p["fields"][1]["from"], "photos");
}
/// A Grain gallery double-tapped favorites it, as Grain's apps do: its
/// photos name their ♡ (`like`), which a feed card holds in the same
/// item as them and a gallery's page outside any list.
#[test]
fn a_grain_gallery_is_favorited_from_over_its_photos() {
fn find<'a>(v: &'a Value, hit: &dyn Fn(&Value) -> bool, out: &mut Vec<&'a Value>) {
if hit(v) {
out.push(v);
}
match v {
Value::Object(o) => o.values().for_each(|c| find(c, hit, out)),
Value::Array(a) => a.iter().for_each(|c| find(c, hit, out)),
_ => {}
}
}
let all = |v: &Value, c: &str| {
let mut out = Vec::new();
find(v, &|n| n["c"] == c, &mut out);
out.into_iter().cloned().collect::<Vec<_>>()
};
let favorite = |v: &Value| {
all(v, "Action")
.iter()
.filter(|a| a["p"]["label"] == "Favorite")
.count()
};
let photo = json!({ "thumb": "https://cdn.test/a.jpg", "fullsize": "https://cdn.test/a.jpg",
"alt": "", "aspectRatio": { "width": 3, "height": 2 } });
let gallery = json!({ "uri": "at://did:plc:a/social.grain.gallery/3kgallery", "cid": "bafy",
"title": "Lisbon", "creator": { "did": "did:plc:a", "handle": "a.test" }, "items": [photo],
"favCount": 0, "viewer": {}, "record": { "title": "Lisbon", "createdAt": "2026-01-01T00:00:00Z" } });
// A feed card: the gallery and its ♡ in one item.
let doc: Value =
serde_json::from_str(include_str!("../testdata/grain/apps/views/grain-feed.json"))
.unwrap();
let mut cards = Vec::new();
find(
&doc["query"]["layout"],
&|n| {
n["component"] == "List"
&& n["props"]["open"]["query"] == "social.grain.gallery.getGallery"
},
&mut cards,
);
let root = json!({ "items": [gallery.clone()] });
let mut c = ctx(&root, &[]);
c.me = Some("did:plc:me");
let tree = resolve(cards[0], &root, &c).unwrap();
check::checked(&tree);
let card = &tree["items"][0];
assert_eq!(all(card, "Gallery")[0]["p"]["like"], "Favorite");
assert_eq!(favorite(card), 1);
// A gallery's page: its ♡ in no list, the comments' own in theirs.
let doc: Value = serde_json::from_str(include_str!(
"../testdata/grain/apps/views/grain-gallery-view.json"
))
.unwrap();
let root = json!({ "response": { "gallery": gallery } });
let mut c = ctx(&root, &[]);
c.me = Some("did:plc:me");
let tree = resolve(&doc["query"]["layout"], &root, &c).unwrap();
check::checked(&tree);
assert_eq!(all(&tree, "Gallery")[0]["p"]["like"], "Favorite");
let listed: usize = all(&tree, "List").iter().map(favorite).sum();
assert_eq!(favorite(&tree) - listed, 1);
}
/// A gallery's description drawn with its facets, which Grain's
/// appview gives in the gallery's record alone, as the feed reads them.
#[test]
fn a_gallerys_description_draws_its_facets() {
let doc: Value = serde_json::from_str(include_str!(
"../testdata/grain/apps/views/grain-gallery-view.json"
))
.unwrap();
let tag = json!([{ "index": { "byteStart": 5, "byteEnd": 12 },
"features": [{ "$type": "app.bsky.richtext.facet#tag", "tag": "portra" }] }]);
let root = json!({ "response": { "gallery": {
"uri": "at://did:plc:a/social.grain.gallery/3kgallery", "cid": "bafy", "title": "Lisbon",
"description": "film #portra", "creator": { "did": "did:plc:a", "handle": "a.test" }, "items": [],
"record": { "title": "Lisbon", "description": "film #portra", "facets": tag,
"createdAt": "2026-01-01T00:00:00Z" } } } });
let tree = resolve(&doc["query"]["layout"], &root, &ctx(&root, &[])).unwrap();
check::checked(&tree);
fn find(v: &Value) -> Option<&Value> {
match v {
Value::Object(o)
if o.get("c") == Some(&json!("RichText"))
&& o["p"].to_string().contains("portra") =>
{
Some(v)
}
Value::Object(o) => o.values().find_map(find),
Value::Array(a) => a.iter().find_map(find),
_ => None,
}
}
assert_eq!(
find(&tree).expect("the description")["p"]["runs"],
json!([{ "text": "film " }, { "text": "#portra", "tag": "portra" }])
);
}
/// A comment, under a gallery or in the comments sheet, opens nothing
/// itself (its author, reply and ⋯ do), and draws its text with the
/// facets Grain's appview gives on the comment's view.
#[test]
fn a_comment_opens_nothing_and_draws_its_facets() {
let comment = json!({ "uri": "at://did:plc:b/social.grain.comment/3kc", "cid": "bafyc",
"author": { "did": "did:plc:b", "handle": "b.test" }, "text": "hi @a.test",
"facets": [{ "index": { "byteStart": 3, "byteEnd": 10 },
"features": [{ "$type": "app.bsky.richtext.facet#mention", "did": "did:plc:a" }] }],
"createdAt": "2026-01-01T00:00:00Z", "favCount": 0 });
let gallery = json!({ "response": { "gallery": {
"uri": "at://did:plc:a/social.grain.gallery/3kgallery", "cid": "bafy", "title": "Lisbon",
"creator": { "did": "did:plc:a", "handle": "a.test" }, "items": [],
"record": { "title": "Lisbon", "createdAt": "2026-01-01T00:00:00Z" } } },
"joins": { "comments": { "comments": [comment.clone()] } } });
let sheet = json!({ "items": [comment], "params": { "subject": "at://did:plc:a/social.grain.gallery/3kgallery" } });
fn comments(v: &Value) -> Option<&Value> {
match v {
Value::Object(o)
if o.get("c") == Some(&json!("List"))
&& o["items"].to_string().contains("hi @a.test") =>
{
Some(v)
}
Value::Object(o) => o.values().find_map(comments),
Value::Array(a) => a.iter().find_map(comments),
_ => None,
}
}
for (view, root) in [
(
include_str!("../testdata/grain/apps/views/grain-gallery-view.json"),
gallery,
),
(
include_str!("../testdata/grain/apps/views/grain-comments.json"),
sheet,
),
] {
let doc: Value = serde_json::from_str(view).unwrap();
let tree = resolve(&doc["query"]["layout"], &root, &ctx(&root, &[])).unwrap();
check::checked(&tree);
let list = comments(&tree).expect("the comments");
let item = &list["items"][0];
assert!(item.get("open").is_none(), "{item}");
assert!(
item.to_string()
.contains(&json!({ "text": "@a.test", "actor": "did:plc:a" }).to_string()),
"{item}"
);
}
}
/// One's own gallery's ⋯ offers Edit gallery, holding its title and
/// description, the gallery's record key given for its update.
#[test]
fn ones_own_gallery_offers_edit_gallery_holding_its_words() {
let doc: Value = serde_json::from_str(include_str!(
"../testdata/grain/apps/views/grain-gallery-view.json"
))
.unwrap();
let root = json!({ "response": { "gallery": {
"uri": "at://did:plc:me/social.grain.gallery/3kgallery", "cid": "bafy", "title": "Lisbon",
"description": "film #portra", "creator": { "did": "did:plc:me", "handle": "me.test" }, "items": [] } } });
let mut c = ctx(&root, &[]);
c.me = Some("did:plc:me");
let tree = resolve(&doc["query"]["layout"], &root, &c).unwrap();
check::checked(&tree);
fn find<'a>(v: &'a Value, label: &str) -> Option<&'a Value> {
match v {
Value::Object(o)
if o.get("c") == Some(&json!("Compose")) && o["p"]["label"] == label =>
{
Some(v)
}
Value::Object(o) => o.values().find_map(|x| find(x, label)),
Value::Array(a) => a.iter().find_map(|x| find(x, label)),
_ => None,
}
}
let edit = &find(&tree, "Edit gallery").expect("Edit gallery")["p"];
assert_eq!(edit["given"], json!({ "rkey": "3kgallery" }));
let values: Vec<&Value> = edit["fields"]
.as_array()
.unwrap()
.iter()
.map(|f| &f["value"])
.collect();
assert_eq!(values, [&json!("Lisbon"), &json!("film #portra")]);
assert_eq!(edit["writes"][0]["update"], json!({ "$value": "rkey" }));
// Someone else's: none.
c.me = Some("did:plc:else");
assert!(
find(
&resolve(&doc["query"]["layout"], &root, &c).unwrap(),
"Edit gallery"
)
.is_none()
);
}
/// An Edit profile form opens holding what the profile says: each
/// field's `value` read, a text's words, the avatar's picture (an
/// allowed URL, drawn whole); left out where it holds nothing. Its key
/// changes with them, so a draft kept before a save is not opened.
#[test]
fn an_edit_composer_opens_holding_what_is_there() {
let origins = vec!["https://cdn.example.com".to_string()];
let layout = json!({ "component": "Compose", "props": { "label": "Edit profile", "send": "Save", "style": "button",
"fields": [
{ "name": "avatar", "kind": "photos", "max": 1, "maxBytes": 1000000, "maxSide": 1000, "value": { "$": "profile.avatar" } },
{ "name": "name", "kind": "line", "max": 64, "value": { "$": "profile.displayName" } },
{ "name": "description", "kind": "text", "max": 256, "facets": true, "value": { "$": "profile.description" } },
{ "name": "note", "kind": "line", "max": 64 }],
"writes": [{ "collection": "a.b.c", "update": "self", "record": { "x": { "$value": "name" } } }] } });
let draw = |profile: Value| {
let root = json!({ "profile": profile });
let top = resolve(&layout, &root, &ctx(&root, &origins)).unwrap();
check::checked(&top);
top["p"].clone()
};
let full = draw(
json!({ "displayName": "Ana", "description": "photos @bob.test",
"avatar": "https://cdn.example.com/avatar/ana@jpeg" }),
);
let values: Vec<(&Value, &Value)> = full["fields"]
.as_array()
.unwrap()
.iter()
.map(|f| (&f["value"], &f["picture"]))
.collect();
let none = &Value::Null;
assert_eq!(
values,
[
(
none,
&json!({ "src": "https://cdn.example.com/avatar/ana@jpeg", "fallback": null })
),
(&json!("Ana"), none),
(&json!("photos @bob.test"), none),
(none, none)
]
);
// None there, or a picture from elsewhere: left out.
let bare = draw(json!({ "avatar": "https://elsewhere.example/a.jpg" }));
assert!(
bare["fields"]
.as_array()
.unwrap()
.iter()
.all(|f| f.get("value").is_none() && f.get("picture").is_none()),
"{bare}"
);
assert_ne!(full["key"], bare["key"]);
assert_eq!(full["writes"], layout["props"]["writes"]);
}
/// A reply opens holding the mention of whom it answers: its text's
/// `value` words joined, strings and bindings; left out where a part
/// holds nothing.
#[test]
fn a_reply_opens_holding_its_mention() {
let layout = json!({ "component": "Compose", "props": { "label": "Reply", "send": "Post",
"fields": [{ "name": "text", "kind": "text", "max": 300, "facets": true,
"value": { "$join": ["@", { "$": "author.handle" }, " "] } }],
"writes": [{ "collection": "a.b.c", "record": { "text": { "$value": "text" } } }] } });
let draw = |root: Value| {
let top = resolve(&layout, &root, &ctx(&root, &[])).unwrap();
check::checked(&top);
top["p"]["fields"][0].clone()
};
assert_eq!(
draw(json!({ "author": { "handle": "bob.test" } }))["value"],
"@bob.test "
);
assert!(draw(json!({})).get("value").is_none());
}
#[test]
fn the_tab_drawn_now_is_selected_and_the_most_specific_wins() {
let root = json!({ "method": "com.example.listIssues", "params": { "repo": "did:plc:r", "state": "closed" } });
let c = ctx(&root, &[]);
let tab = |label: &str, state: Option<&str>| {
let mut params = json!({ "repo": { "$root": "params.repo" } });
if let Some(s) = state {
params["state"] = s.into();
}
json!({ "label": label, "open": { "query": "com.example.listIssues", "params": params } })
};
let layout = json!({ "component": "Tabs", "props": { "items": [
tab("All", None), tab("Open", Some("open")), tab("Closed", Some("closed")),
{ "label": "Unread", "open": { "query": "com.example.listIssues", "params": { "x": { "$": "absent" } } } },
] } });
let tree = resolve(&layout, &json!({}), &c).unwrap();
check::checked(&tree);
let items = tree["p"]["items"].as_array().unwrap();
// The one whose params do not resolve is left out.
assert_eq!(items.len(), 3);
let selected: Vec<bool> = items.iter().map(|t| t["selected"] == true).collect();
assert_eq!(selected, [false, false, true]);
assert_eq!(
items[1]["open"],
json!({ "call": { "name": "query", "args": { "method": "com.example.listIssues",
"params": { "repo": "did:plc:r", "state": "open" } } } })
);
// Drawn from elsewhere, none is, and the tabs are not drawn; one tab
// alone draws nothing.
let other = json!({ "method": "com.example.getRepo", "params": { "repo": "did:plc:r" } });
assert!(resolve(&layout, &json!({}), &ctx(&other, &[])).is_none());
let one = json!({ "component": "Tabs", "props": { "items": [
tab("All", None),
{ "label": "Gone", "open": { "query": "com.example.listIssues", "params": { "x": { "$": "absent" } } } },
] } });
assert!(resolve(&one, &json!({}), &c).is_none());
}
/// A tab for each feed a person pinned, of those `where` keeps, drawn
/// as a strip; with none pinned, the view's own; a label that is no
/// path is the view's error.
#[test]
fn tabs_from_the_data_each_open_their_element() {
let root = json!({ "method": "a.b.getFeed", "params": { "feed": "at://did:web:a/a.b.generator/following" } });
let c = ctx(&root, &[]);
let tabs = |from: Value, label: &str| {
json!({ "component": "Tabs", "props": {
"from": from, "label": label, "where": { "type": { "$is": "feed" } }, "style": "strip",
"open": { "query": "a.b.getFeed", "params": { "feed": { "$atUri": ["did:web:a", "a.b.generator", { "$": "id" }] } } },
"items": [
{ "label": "Recent", "open": { "query": "a.b.getFeed", "params": { "feed": "at://did:web:a/a.b.generator/recent" } } },
{ "label": "Following", "open": { "query": "a.b.getFeed", "params": { "feed": "at://did:web:a/a.b.generator/following" } } },
] } })
};
let scope = json!({ "pinned": [
{ "id": "foryou", "label": "For You", "type": "feed" },
{ "id": "camera:Fuji", "label": "Fuji", "type": "camera" },
{ "id": "following", "label": "Following", "type": "feed" },
{ "id": "unnamed", "type": "feed" },
] });
let tree = resolve(&tabs(json!({ "$": "pinned" }), "label"), &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(tree["p"]["style"], "strip");
let drawn: Vec<(&Value, &Value)> = tree["p"]["items"]
.as_array()
.unwrap()
.iter()
.map(|t| (&t["label"], &t["selected"]))
.collect();
assert_eq!(
drawn,
[
(&json!("For You"), &json!(false)),
(&json!("Following"), &json!(true))
]
);
// None pinned: the view's own tabs.
let tree = resolve(&tabs(json!({ "$": "pinned" }), "label"), &json!({}), &c).unwrap();
assert_eq!(tree["p"]["items"][0]["label"], "Recent");
assert_eq!(
resolve(&tabs(json!({ "$": "pinned" }), "a..b"), &scope, &c).unwrap()["p"],
json!({ "component": "Tabs", "message": "label: a path within each element" })
);
}
/// A profile's panes: its galleries for anyone, its favorites on one's
/// own alone, and none with nothing in it; none drawn, no Panes.
#[test]
fn panes_hold_the_panes_with_something_to_show() {
let root = json!({});
let mut c = ctx(&root, &[]);
c.me = Some("did:plc:me");
let text = |path: &str| json!({ "component": "Text", "props": { "value": { "$": path } } });
let panes = json!({ "component": "Panes", "children": [
{ "component": "Pane", "props": { "label": "Galleries", "icon": "grid" }, "children": [text("galleries")] },
{ "component": "Pane", "props": { "label": "Favorites", "icon": "heart", "mine": "did" }, "children": [text("favorites")] },
{ "component": "Pane", "props": { "label": "Stories" }, "children": [text("stories")] },
text("galleries"),
] });
let mine = json!({ "did": "did:plc:me", "galleries": "G", "favorites": "F" });
let tree = resolve(&panes, &mine, &c).unwrap();
check::checked(&tree);
let labels: Vec<&Value> = tree["k"]
.as_array()
.unwrap()
.iter()
.map(|p| &p["p"]["label"])
.collect();
assert_eq!(labels, [&json!("Galleries"), &json!("Favorites")]);
assert_eq!(tree["k"][0]["p"]["icon"], "grid");
// A pane named with no icon of its own is drawn without one.
let all =
json!({ "did": "did:plc:me", "galleries": "G", "favorites": "F", "stories": "S" });
let stories = &resolve(&panes, &all, &c).unwrap()["k"][2]["p"];
assert_eq!(
(&stories["label"], stories.get("icon")),
(&json!("Stories"), None)
);
let theirs = json!({ "did": "did:plc:else", "galleries": "G", "favorites": "F" });
assert_eq!(
resolve(&panes, &theirs, &c).unwrap()["k"]
.as_array()
.unwrap()
.len(),
1
);
assert_eq!(resolve(&panes, &json!({ "did": "did:plc:else" }), &c), None);
}
/// The host's accounts: drawn whatever its children draw, as the host
/// draws them from what it keeps; its children, its stand-in where the
/// host keeps none, resolved against the view's data.
#[test]
fn accounts_stand_for_the_hosts_with_their_children() {
let root = json!({});
let c = ctx(&root, &[]);
let own = json!({ "component": "Accounts", "children": [
{ "component": "Text", "props": { "value": { "$": "handle" } } },
{ "component": "Text", "props": { "value": { "$": "missing" } } },
] });
let tree = resolve(&own, &json!({ "handle": "alice.test" }), &c).unwrap();
check::checked(&tree);
assert_eq!(tree["c"], "Accounts");
assert_eq!(tree.get("p"), None);
assert_eq!(tree["k"].as_array().unwrap().len(), 1);
assert_eq!(tree["k"][0]["p"]["runs"][0]["text"], "alice.test");
let bare = resolve(&json!({ "component": "Accounts" }), &root, &c).unwrap();
check::checked(&bare);
assert_eq!(bare, json!({ "c": "Accounts" }));
}
/// A split's two sides and its words; one side drawing nothing leaves
/// the other as it is, both nothing.
#[test]
fn a_split_draws_its_two_sides() {
let root = json!({});
let c = ctx(&root, &[]);
let text = |path: &str| json!({ "component": "Text", "props": { "value": { "$": path } } });
let split = |props: Value| json!({ "component": "Split", "props": props, "children": [text("a"), text("b")] });
let both = json!({ "a": "A", "b": "B" });
let tree = resolve(
&split(json!({ "side": "start", "main": "lg", "aside": "sm" })),
&both,
&c,
)
.unwrap();
check::checked(&tree);
assert_eq!(tree["c"], "Split");
assert_eq!(
tree["p"],
json!({ "side": "start", "main": "lg", "aside": "sm" })
);
assert_eq!(tree["k"][1]["p"]["runs"][0]["text"], "B");
// The end is the default, unsaid, as are minimums not given.
let plain = resolve(&split(json!({ "side": "end" })), &both, &c).unwrap();
assert_eq!((plain["c"].as_str(), plain.get("p")), (Some("Split"), None));
let one = resolve(&split(json!({})), &json!({ "b": "B" }), &c).unwrap();
assert_eq!(
(&one["c"], &one["p"]["runs"][0]["text"]),
(&json!("Text"), &json!("B"))
);
assert_eq!(resolve(&split(json!({})), &json!({}), &c), None);
}
/// A Stack held to reading width says so in its tree, its gap as ever;
/// one that says nothing, nothing.
#[test]
fn a_stack_keeps_its_measure() {
let root = json!({});
let c = ctx(&root, &[]);
let stack = |props: Value| json!({ "component": "Stack", "props": props, "children": [{ "component": "Text", "props": { "value": "a" } }] });
let held = resolve(&stack(json!({ "measure": "content" })), &root, &c).unwrap();
check::checked(&held);
assert_eq!(held["p"], json!({ "gap": "md", "measure": "content" }));
let plain = resolve(&stack(json!({})), &root, &c).unwrap();
assert_eq!(plain["p"], json!({ "gap": "md" }));
}
/// A grid's narrowest tile and most across reach the tree as given; a
/// list without them, none.
#[test]
fn a_grid_keeps_its_min_and_columns() {
let root = json!({});
let c = ctx(&root, &[]);
let list = |props: Value| {
let mut p = json!({ "items": { "$": "all" }, "style": "grid" });
p.as_object_mut()
.unwrap()
.extend(props.as_object().unwrap().clone());
json!({ "component": "List", "props": p, "children": [
{ "component": "Text", "props": { "value": { "$": "t" } } }] })
};
let scope = json!({ "all": [{ "t": "a" }, { "t": "b" }] });
let tree = resolve(&list(json!({ "min": "sm", "columns": 3 })), &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(
(&tree["p"]["min"], &tree["p"]["columns"]),
(&json!("sm"), &json!(3))
);
let plain = resolve(&list(json!({})), &scope, &c).unwrap();
assert_eq!(plain["p"], json!({ "style": "grid" }));
}
/// Rows keep `chevrons`, each ending in one; other styles draw none.
#[test]
fn rows_keep_their_chevrons() {
let root = json!({});
let c = ctx(&root, &[]);
let list = |style: &str| {
json!({ "component": "List", "props": { "items": { "$": "all" }, "style": style, "chevrons": true },
"children": [{ "component": "Text", "props": { "value": { "$": "t" } } }] })
};
let scope = json!({ "all": [{ "t": "a" }] });
let rows = resolve(&list("rows"), &scope, &c).unwrap();
check::checked(&rows);
assert_eq!(rows["p"], json!({ "style": "rows", "chevrons": true }));
let cards = resolve(&list("cards"), &scope, &c).unwrap();
assert_eq!(cards["p"], json!({ "style": "cards" }));
}
/// Chips end with their `more` where `limit` left items out, and only then.
#[test]
fn chips_end_with_more_where_some_are_left_out() {
let root = json!({});
let c = ctx(&root, &[]);
let list = |style: &str, limit: u64| {
json!({ "component": "List", "props": { "items": { "$": "all" }, "style": style, "limit": limit,
"more": { "label": "See all", "open": { "query": "a.b.getAll" } } },
"children": [{ "component": "Text", "props": { "value": { "$": "t" } } }] })
};
let scope = json!({ "all": [{ "t": "a" }, { "t": "b" }] });
let cut = resolve(&list("chips", 1), &scope, &c).unwrap();
check::checked(&cut);
assert_eq!(cut["p"]["more"]["label"], "See all");
assert_eq!(
cut["p"]["more"]["open"]["call"]["args"]["method"],
"a.b.getAll"
);
assert!(
resolve(&list("chips", 2), &scope, &c).unwrap()["p"]
.get("more")
.is_none()
);
assert!(
resolve(&list("inline", 1), &scope, &c).unwrap()["p"]
.get("more")
.is_none()
);
}
/// A bar holds its buttons, a Link's icon with it; a bar of nothing is
/// not drawn.
#[test]
fn a_bar_holds_its_buttons() {
let root = json!({});
let c = ctx(&root, &[]);
let bar = |label: Value| {
json!({ "component": "Bar", "children": [{ "component": "Link",
"props": { "label": label, "icon": "settings", "open": { "query": "a.b.getPreferences" } } }] })
};
let tree = resolve(&bar(json!("Settings")), &json!({}), &c).unwrap();
check::checked(&tree);
assert_eq!(tree["k"][0]["p"]["icon"], "settings");
assert_eq!(
resolve(&bar(json!({ "$": "absent" })), &json!({}), &c),
None
);
// Gated as a Stack is: on someone else's profile, no gear.
let mut mine = bar(json!("Settings"));
mine["props"] = json!({ "mine": "did" });
assert_eq!(resolve(&mine, &json!({ "did": "did:plc:else" }), &c), None);
}
/// A bar's title is the screen's, its words one after another: a
/// bar of a title alone draws, and one whose words are not all there
/// has none, so a hashtag's is never a bare #.
#[test]
fn a_bars_title_is_its_words_one_after_another() {
let root = json!({});
let c = ctx(&root, &[]);
let bar = |title: Value| json!({ "component": "Bar", "props": { "title": title } });
let tag = json!(["#", { "$": "params.tag" }]);
let tree = resolve(
&bar(tag.clone()),
&json!({ "params": { "tag": "film" } }),
&c,
)
.unwrap();
check::checked(&tree);
assert_eq!(tree, json!({ "c": "Bar", "p": { "title": "#film" } }));
assert_eq!(resolve(&bar(tag), &json!({ "params": {} }), &c), None);
assert_eq!(resolve(&bar(json!([""])), &json!({}), &c), None);
// With buttons, the title beside them; without one, the buttons alone.
let mut both = bar(json!(["Followers"]));
both["children"] = json!([{ "component": "Link", "props": { "label": "Settings", "icon": "settings", "open": { "query": "a.b.getPreferences" } } }]);
let tree = resolve(&both, &json!({}), &c).unwrap();
assert_eq!(tree["p"], json!({ "title": "Followers" }));
assert_eq!(tree["k"][0]["c"], "Link");
both["props"]["title"] = json!([{ "$": "absent" }]);
assert_eq!(resolve(&both, &json!({}), &c).unwrap().get("p"), None);
// A gate that is no path is an error in its place.
let gate = json!({ "component": "Bar", "props": { "when": "", "title": ["x"] } });
assert_eq!(resolve(&gate, &json!({}), &c).unwrap()["c"], "Error");
}
/// A feed's events cut to the threads they touch: those with a title,
/// each subject once (its newest, the first), at most `limit`.
#[test]
fn a_list_keeps_what_it_needs_each_thing_once_and_at_most_its_limit() {
let root = json!({});
let c = ctx(&root, &[]);
let event = |subject: Option<&str>, title: Option<&str>| json!({ "action": { "subject": subject, "title": title } });
let events = json!([
event(Some("at://a/issue/1"), Some("first")),
event(None, None), // a push
event(Some("at://a/repo/r"), None), // a star
event(Some("at://a/issue/1"), Some("again")), // a comment on the first
event(Some("at://a/pull/2"), Some("second")),
event(Some("at://a/issue/3"), Some("third")),
]);
let layout = |limit: u64| {
json!({ "component": "List", "props": { "items": { "$": "events" },
"needs": "action.title", "distinct": "action.subject", "limit": limit, "open": false },
"children": [{ "component": "Text", "props": { "value": { "$": "action.title" } } }] })
};
let titles = |tree: &Value| -> Vec<String> {
tree["items"]
.as_array()
.unwrap()
.iter()
.map(|i| {
i["k"][0]["p"]["runs"][0]["text"]
.as_str()
.unwrap()
.to_string()
})
.collect()
};
let scope = json!({ "events": events });
let tree = resolve(&layout(8), &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(titles(&tree), ["first", "second", "third"]);
assert_eq!(
titles(&resolve(&layout(2), &scope, &c).unwrap()),
["first", "second"]
);
}
#[test]
fn a_stat_counts_an_array_and_says_there_are_more() {
let root = json!({});
let c = ctx(&root, &[]);
let layout = json!({ "component": "Stat", "props": { "value": { "$": "items" }, "more": { "$": "cursor" } } });
let drawn = |scope: Value| resolve(&layout, &scope, &c);
let more = drawn(json!({ "items": [1, 2, 3], "cursor": "abc" })).unwrap();
check::checked(&more);
assert_eq!(more["p"], json!({ "value": 3, "more": true }));
assert_eq!(
drawn(json!({ "items": [], "cursor": null })).unwrap()["p"],
json!({ "value": 0 })
);
assert_eq!(
drawn(json!({ "items": 12 })).unwrap()["p"],
json!({ "value": 12 })
);
assert!(drawn(json!({ "items": "many" })).is_none());
}
#[test]
fn literal_rows_read_the_root_and_open_their_own() {
let root = json!({ "me": { "did": "did:plc:me" }, "joins": { "issues": { "items": [1, 2], "cursor": "c" } } });
let c = ctx(&root, &[]);
let layout = json!({ "component": "List", "props": {
"items": [
{ "label": "Issues", "icon": "issue", "tint": "green",
"count": { "$root": "joins.issues.items" }, "more": { "$root": "joins.issues.cursor" },
"open": { "query": "com.example.listIssues", "params": { "actor": { "$root": "me.did" } } } },
{ "label": "Pulls", "icon": "pull", "tint": "purple", "count": { "$root": "joins.pulls.items" } },
],
"open": { "query": "com.example.listAll", "params": { "label": { "$": "label" } } } },
"children": [{ "component": "Row", "children": [
{ "component": "Icon", "props": { "name": { "$": "icon" }, "tint": { "$": "tint" } } },
{ "component": "Text", "props": { "value": { "$": "label" } } },
{ "component": "Stat", "props": { "value": { "$": "count" }, "more": { "$": "more" } } },
] }] });
let tree = resolve(&layout, &json!({}), &c).unwrap();
check::checked(&tree);
let items = tree["items"].as_array().unwrap();
assert_eq!(items.len(), 2);
assert_eq!(
items[0]["open"]["call"]["args"],
json!({ "method": "com.example.listIssues", "params": { "actor": "did:plc:me" } })
);
assert_eq!(
items[1]["open"]["call"]["args"],
json!({ "method": "com.example.listAll", "params": { "label": "Pulls" } })
);
let row = &items[0]["k"][0]["k"];
assert_eq!(
row[0],
json!({ "c": "Icon", "p": { "name": "issue", "tint": "green" } })
);
assert_eq!(row[2]["p"], json!({ "value": 2, "more": true }));
// A root path that holds nothing reads as null: no count drawn.
assert_eq!(items[1]["k"][0]["k"].as_array().unwrap().len(), 2);
assert!(tree["p"].get("page").is_none());
}
#[test]
fn a_reply_whose_root_is_its_parent_shows_the_parent_alone() {
let root = json!({});
let c = ctx(&root, &[]);
let parent = json!({ "$type": feed::POST, "uri": "at://p", "author": { "did": "did:plc:p", "handle": "p.test" }, "record": {} });
let item = json!({ "post": { "uri": "at://c", "record": { "reply": { "parent": { "uri": "at://p" } } } },
"reply": { "root": parent, "parent": parent } });
let layout = json!({ "component": "FeedContext", "props": { "item": { "$": "." } },
"children": [{ "component": "Text", "props": { "value": { "$": "post.author.handle" } } }] });
let tree = resolve(&layout, &item, &c).unwrap();
check::checked(&tree);
let thread = &tree["p"]["thread"];
assert!(thread.get("top").is_none() && thread.get("gap").is_none());
assert_eq!(thread["parent"]["k"][0]["p"]["runs"][0]["text"], "p.test");
}
/// The node of the unfetched post at `uri` (`unfetched_post`), wherever
/// it is in the tree.
fn post_at<'a>(tree: &'a Value, uri: &str) -> Option<&'a Value> {
match tree {
Value::Object(o) if unfetched_post(o) == Some(uri) => Some(tree),
Value::Object(o) => o.values().find_map(|v| post_at(v, uri)),
Value::Array(a) => a.iter().find_map(|v| post_at(v, uri)),
_ => None,
}
}
#[test]
fn posts_are_filled_from_the_appview_by_did_or_by_handle_and_rkey() {
let root = json!({});
let origins = vec!["https://cdn.bsky.app".to_string()];
let c = ctx(&root, &origins);
let (a, gone) = (
"at://did:plc:alice/app.bsky.feed.post/a1",
"at://did:plc:gone/app.bsky.feed.post/x",
);
let (b_by_handle, b) = (
"at://bob.test/app.bsky.feed.post/b1",
"at://did:plc:bob/app.bsky.feed.post/b1",
);
let (cee, f) = (
"at://did:plc:carol/app.bsky.feed.post/c1",
"at://did:plc:fay/app.bsky.feed.post/f1",
);
let block = |uri: &str| json!({ "block": { "$type": "pub.leaflet.blocks.bskyPost", "postRef": { "uri": uri, "cid": "bafy" } } });
let scope = json!({
"doc": { "$type": "pub.leaflet.content", "pages": [{ "blocks": [block(a), block(gone)] }] },
"raw": { "$type": "app.bsky.embed.record", "record": { "uri": b_by_handle, "cid": "bafyb" } },
"media": { "$type": "app.bsky.embed.recordWithMedia",
"media": { "$type": "app.bsky.embed.images", "images": [{ "image": "https://cdn.bsky.app/m.jpg", "alt": "m" }] },
"record": { "$type": "app.bsky.embed.record", "record": { "uri": cee, "cid": "bafyc" } } },
"view": { "$type": "app.bsky.embed.record#view", "record": {
"$type": "app.bsky.embed.record#viewRecord", "uri": "at://did:plc:erin/app.bsky.feed.post/e0",
"author": { "did": "did:plc:erin", "handle": "erin.test" }, "value": { "text": "look" },
"embeds": [{ "uri": f, "cid": "bafyf" }] } },
});
let embed = |at: &str| json!({ "component": "Embed", "props": { "value": { "$": at } } });
let layout = json!({ "component": "Stack", "children": [
{ "component": "Document", "props": { "value": { "$": "doc" } } },
embed("raw"), embed("media"), embed("view"),
] });
let mut tree = resolve(&layout, &scope, &c).unwrap();
assert_eq!(post_uris(&tree), [a, gone, b_by_handle, cee, f]);
check::checked(&tree);
let missing = post_at(&tree, gone).unwrap().clone();
// getPosts' answer: posts by DID, in no particular order, with a
// post of the same rkey by someone else and another of Bob's
// before Bob's own.
let zed = json!({ "$type": "app.bsky.embed.record#viewRecord", "uri": "at://did:plc:zed/app.bsky.feed.post/z",
"author": { "did": "did:plc:zed", "handle": "zed.test" }, "value": { "text": "deep" } });
let post = |uri: &str, did: &str, handle: &str, text: &str| {
json!({ "uri": uri, "cid": "bafy", "author": { "did": did, "handle": handle },
"record": { "$type": "app.bsky.feed.post", "text": text, "createdAt": "2026-01-01T00:00:00Z" },
"indexedAt": "2026-01-01T00:00:00Z" })
};
let mut alice = post(a, "did:plc:alice", "alice.test", "from alice");
alice["author"]["displayName"] = "Alice".into();
alice["author"]["avatar"] = "https://cdn.bsky.app/img/avatar/alice.jpg".into();
alice["embed"] = json!({ "$type": "app.bsky.embed.recordWithMedia#view",
"media": { "$type": "app.bsky.embed.images#view", "images": [
{ "thumb": "https://cdn.bsky.app/t/1.jpg", "fullsize": "https://cdn.bsky.app/f/1.jpg", "alt": "one" },
{ "thumb": "https://evil.example/2.jpg", "fullsize": "https://evil.example/2.jpg", "alt": "two" },
] },
"record": { "$type": "app.bsky.embed.record#view", "record": zed } });
let mut bob = post(b, "did:plc:bob", "bob.test", "from bob");
bob["author"]["avatar"] = "https://evil.example/bob.jpg".into();
let mut carol = post(cee, "did:plc:carol", "carol.test", "from carol");
carol["embed"] = json!({ "$type": "app.bsky.embed.record#view", "record": zed });
let answer = json!({ "posts": [
post("at://did:plc:carol/app.bsky.feed.post/b1", "did:plc:carol", "carol.test", "same rkey, not bob"),
post("at://did:plc:bob/app.bsky.feed.post/b2", "did:plc:bob", "bob.test", "bob, another post"),
carol, bob, alice,
post(f, "did:plc:fay", "fay.test", "from fay"),
] });
fill_posts(&mut tree, answer["posts"].as_array().unwrap(), &c);
check::checked(&tree);
// The document's block, by DID: its pictures held to the origins,
// its own embed drawn a level down (no quote in it).
let filled = post_at(&tree, a).unwrap();
assert_eq!(filled["kind"], "bskyPost");
assert_eq!(filled["fallback"]["kind"], "card");
let q = &filled["quote"];
assert_eq!(q["kind"], "quote");
assert_eq!(q["author"]["name"], "Alice");
assert_eq!(q["author"]["handle"], "alice.test");
assert_eq!(
q["author"]["avatar"]["src"],
"https://cdn.bsky.app/img/avatar/alice.jpg"
);
assert_eq!(q["runs"][0]["text"], "from alice");
assert_eq!(q["open"]["call"]["args"]["params"]["uri"], a);
assert_eq!(q["embed"]["kind"], "recordWithMedia");
assert_eq!(
q["embed"]["record"],
Value::Null,
"a filled post's quote of a post is past its depth"
);
let images = &q["embed"]["media"]["images"];
assert_eq!(images[0]["src"]["src"], "https://cdn.bsky.app/t/1.jpg");
assert_eq!(images[1]["src"], Value::Null, "a picture off the origins");
// The one the AppView has no post for: its fallback alone.
assert_eq!(post_at(&tree, gone).unwrap(), &missing);
assert!(missing.get("quote").is_none());
// The raw embed asked for by handle: Bob's post of that rkey.
let filled = &tree["k"][1]["p"];
assert_eq!(filled["uri"], b_by_handle);
assert_eq!(filled["quote"]["runs"][0]["text"], "from bob");
assert_eq!(filled["quote"]["open"]["call"]["args"]["params"]["uri"], b);
assert_eq!(filled["quote"]["author"]["avatar"], Value::Null);
assert_eq!(filled["fallback"]["compact"], true);
// In recordWithMedia: its record filled, its media as it was.
let shown = &tree["k"][2]["p"];
assert_eq!(shown["kind"], "recordWithMedia");
assert_eq!(
shown["media"]["images"][0]["src"]["src"],
"https://cdn.bsky.app/m.jpg"
);
assert_eq!(shown["record"]["uri"], cee);
assert_eq!(shown["record"]["quote"]["runs"][0]["text"], "from carol");
assert_eq!(shown["record"]["quote"]["embed"], Value::Null);
// Inside a quote's embed: filled, the quote around it left as it is.
let shown = &tree["k"][3]["p"];
assert_eq!(shown["kind"], "quote");
assert!(shown.get("quote").is_none());
assert_eq!(shown["embed"]["uri"], f);
assert_eq!(shown["embed"]["quote"]["runs"][0]["text"], "from fay");
}
/// A post the AppView names by something that is no post's at-uri
/// answers nothing: the post keeps its fallback alone.
#[test]
fn a_post_answered_under_no_post_uri_fills_nothing() {
let root = json!({});
let c = ctx(&root, &[]);
let unfetched =
json!({ "kind": "post", "uri": "at://did:plc:a/app.bsky.feed.post/1", "fallback": {} });
let mut tree = unfetched.clone();
fill_posts(&mut tree, &[json!({ "uri": "https://a.example/1" })], &c);
assert_eq!(tree, unfetched);
}
#[test]
fn what_no_component_draws_is_an_error_and_an_empty_container_nothing() {
let root = json!({});
let c = ctx(&root, &[]);
let layout = json!({ "component": "Stack", "children": [
{ "component": "Sparkle" },
{ "component": "Row", "children": [{ "component": "Text", "props": { "value": { "$": "none" } } }] },
{ "component": "Text", "props": { "value": { "$": 5 } } },
] });
let tree = resolve(&layout, &json!({}), &c).unwrap();
check::checked(&tree);
assert_eq!(
tree["k"],
json!([
{ "c": "Error", "p": { "component": "Sparkle", "message": "Sparkle is not resolved" } },
{ "c": "Error", "p": { "component": "Text", "message": "unknown path syntax 5" } },
])
);
}
#[test]
fn text_is_worded_cut_and_written_out() {
let root = json!({});
let c = ctx(&root, &[]);
let drawn = |p: Value, scope: Value| {
let n = resolve(&json!({ "component": "Text", "props": p }), &scope, &c).unwrap();
check::checked(&n);
n["p"]["runs"].clone()
};
assert_eq!(
drawn(json!({ "value": { "$": "on" } }), json!({ "on": true })),
json!([{ "text": "true" }])
);
assert_eq!(
drawn(
json!({ "value": "open", "words": { "open": "Open now" } }),
json!({})
),
json!([{ "text": "Open now" }])
);
assert_eq!(
drawn(json!({ "value": "abcdef", "chars": 3 }), json!({})),
json!([{ "text": "abc" }])
);
}
/// A URL that starts inside a word, or is no URL at all, stays words.
#[test]
fn only_whole_urls_after_a_space_are_links() {
let text = "mail:https://a.example and https:// b";
assert_eq!(Value::Array(link_runs(text)), json!([{ "text": text }]));
}
#[test]
fn a_facet_overlapping_an_earlier_one_or_of_no_kind_is_plain() {
let facets = json!([
{ "index": { "byteStart": 2, "byteEnd": 7 }, "features": [{ "$type": "app.bsky.richtext.facet#link", "uri": "https://a.example" }] },
{ "index": { "byteStart": 0, "byteEnd": 5 }, "features": [{ "$type": "app.bsky.richtext.facet#bold" }] },
]);
assert_eq!(
Value::Array(facet_runs(
"hello world",
Some(&facets),
&ctx(&json!({}), &[])
)),
json!([{ "text": "hello" }, { "text": " world" }])
);
}
/// Rich text as markdown is blocks, its pictures those it is given;
/// with no format its words as they are (no links read), detected its
/// links found in them, and with facets where a record has none, found
/// as detected; a value that is no text is an error, as a time's that is
/// no timestamp is.
#[test]
fn rich_text_reads_its_format_and_times_their_timestamp() {
let root = json!({});
let origins = vec!["https://cdn.bsky.app".to_string()];
let c = ctx(&root, &origins);
let rich = |p: Value| json!({ "component": "RichText", "props": p });
let layout = json!({ "component": "Stack", "children": [
rich(json!({ "value": "# Hi", "format": "markdown", "clamp": 3 })),
rich(json!({ "value": "see https://a.example" })),
rich(json!({ "value": { "$": "n" } })),
{ "component": "Time", "props": { "value": { "$": "n" } } },
{ "component": "Image", "props": { "src": "https://cdn.bsky.app/a.jpg", "fit": "contain" } },
rich(json!({ "value": "see https://a.example", "format": "detect" })),
rich(json!({ "value": "", "format": "gfm", "pictures": { "$": "pics" } })),
rich(json!({ "value": "see https://a.example #tag", "format": "facets", "facets": { "$": "none" } })),
rich(json!({ "value": "see https://a.example", "format": "facets", "facets": { "$": "empty" } })),
] });
let scope = json!({ "n": 1, "empty": [], "pics": [{ "cid": "bafa", "url": "https://cdn.bsky.app/p", "width": 10, "height": 5 }] });
let tree = resolve(&layout, &scope, &c).unwrap();
check::checked(&tree);
let k = &tree["k"];
assert_eq!(
k[0]["p"],
json!({ "blocks": document::markdown("# Hi", false), "clamp": 3 })
);
assert_eq!(
k[1]["p"],
json!({ "runs": [{ "text": "see https://a.example" }] })
);
assert_eq!(
k[2]["p"],
json!({ "component": "RichText", "message": "value: not text" })
);
assert_eq!(
k[3]["p"],
json!({ "component": "Time", "message": "value: not a timestamp" })
);
assert_eq!(k[4]["p"]["fit"], "contain");
assert_eq!(
k[5]["p"],
json!({ "runs": [{ "text": "see " }, { "text": "https://a.example", "link": "https://a.example" }] })
);
assert_eq!(
k[6]["p"]["blocks"],
json!([{ "kind": "image", "src": { "src": "https://cdn.bsky.app/p", "fallback": null }, "alt": "a", "ratio": 2.0, "width": 10 }])
);
// A record written with no facets: its link and tag found as `detect`
// finds them; one written with none, its facets an empty list, plain.
let found = &k[7]["p"]["runs"];
assert_eq!(
found[1],
json!({ "text": "https://a.example", "link": "https://a.example" })
);
assert_eq!(found[3], json!({ "text": "#tag", "tag": "tag" }));
assert_eq!(
k[8]["p"],
json!({ "runs": [{ "text": "see https://a.example" }] })
);
}
/// A clamped text longer than its clamp is given what it shows until
/// opened, cut on the server (`clamp`): a Text's and a RichText's runs
/// as `shownRuns`, markdown's blocks as `shownBlocks`; one that fits,
/// and a quote, drawn on one line, nothing.
#[test]
fn clamped_text_is_cut_on_the_server() {
let root = json!({});
let c = ctx(&root, &[]);
let long = "word ".repeat(40);
let node = |c: &str, p: Value| json!({ "component": c, "props": p });
let layout = json!({ "component": "Stack", "children": [
node("Text", json!({ "value": long, "clamp": 1 })),
node("Text", json!({ "value": long, "style": "quote", "clamp": 1 })),
node("Text", json!({ "value": "short", "clamp": 1 })),
node("RichText", json!({ "value": long, "format": "detect", "clamp": 2 })),
node("RichText", json!({ "value": format!("# Hi\n\n{long}"), "format": "markdown", "clamp": 3 })),
] });
let tree = resolve(&layout, &json!({}), &c).unwrap();
check::checked(&tree);
let k = &tree["k"];
let words = |n: usize| format!("{}…", ["word"; 40][..n].join(" "));
assert_eq!(k[0]["p"]["shownRuns"], json!([{ "text": words(9) }]));
assert_eq!(k[1]["p"].get("shownRuns"), None);
assert_eq!(k[2]["p"].get("shownRuns"), None);
assert_eq!(k[3]["p"]["shownRuns"], json!([{ "text": words(18) }]));
assert_eq!(
k[4]["p"]["shownBlocks"],
json!([{ "kind": "heading", "level": 1, "runs": [{ "text": "Hi" }] }])
);
}
/// An href opens a record (with the inline view, of its collection), a
/// page, an account, or nothing for words; an `open` the query drawn
/// now is `current`, its `$atUri` and list params resolved, one that
/// does not resolve opening nothing.
#[test]
fn links_open_what_their_href_or_open_names() {
let root = json!({ "method": "com.example.get", "params": { "id": "1" } });
let doc = json!({ "id": "an.inline.view" });
let mut c = ctx(&root, &[]);
c.inline = Some(("app.test.thing", &doc));
let href = |h: Value| json!({ "component": "Link", "props": { "href": h } });
let open = |label: Value, open: Value| json!({ "component": "Link", "props": { "label": label, "open": open } });
let query = |params: Value| json!({ "query": "com.example.get", "params": params });
let layout = json!({ "component": "Stack", "children": [
href(json!("at://did:plc:a/app.test.thing/1")),
{ "component": "Link", "props": { "href": "https://a.example/x", "style": "button" } },
href(json!("https://")),
href(json!("alice.test")),
href(json!("just words")),
href(json!({ "$": "n" })),
open(json!({ "$": "none" }), query(json!({ "id": "1" }))),
open(json!("Here"), query(json!({ "id": "1" }))),
open(json!("There"), query(json!({ "id": "2" }))),
open(json!("Bad"), query(json!({ "uri": { "$atUri": ["a"] } }))),
open(json!("Gone"), query(json!({ "uri": { "$atUri": [{ "$": "none" }, "app.test.thing", "1"] } }))),
open(json!("Many"), json!({ "query": "com.example.list", "service": "did:web:a.example#svc",
"params": { "uris": [{ "$": "did" }, "lit"] } })),
open(json!("Fewer"), json!({ "query": "com.example.list", "params": { "uris": [{ "$": "none" }] } })),
open(json!("Odd"), json!({ "$": 5 })),
] });
let tree = resolve(&layout, &json!({ "n": 3, "did": "did:plc:a" }), &c).unwrap();
check::checked(&tree);
let k = tree["k"].as_array().unwrap();
let p: Vec<&Value> = k.iter().map(|n| &n["p"]).collect();
assert_eq!(k.len(), 13, "the open with no label draws nothing");
assert_eq!(
p[0]["open"],
call(
"get_record",
json!({ "uri": "at://did:plc:a/app.test.thing/1", "view": doc })
)
);
assert_eq!(
*p[1],
json!({ "style": "button", "label": "https://a.example/x", "open": { "url": "https://a.example/x" } })
);
assert_eq!(*p[2], json!({ "label": "https://" }));
assert_eq!(
p[3]["open"],
call("describe_repo", json!({ "actor": "alice.test" }))
);
assert_eq!(*p[4], json!({ "label": "just words" }));
assert_eq!(
*p[5],
json!({ "component": "Link", "message": "href: not a link" })
);
assert_eq!(*p[6], json!({ "label": "Here", "current": true }));
assert_eq!(
p[7]["open"],
call(
"query",
json!({ "method": "com.example.get", "params": { "id": "2" } })
)
);
assert_eq!(
*p[8],
json!({ "component": "Link", "message": "$atUri: [authority, collection, rkey]" })
);
assert_eq!(*p[9], json!({ "label": "Gone" }));
assert_eq!(
p[10]["open"],
call(
"query",
json!({ "method": "com.example.list", "params": { "uris": ["did:plc:a", "lit"] },
"service": "did:web:a.example#svc" })
)
);
assert_eq!(*p[11], json!({ "label": "Fewer" }));
assert_eq!(
*p[12],
json!({ "component": "Link", "message": "unknown path syntax 5" })
);
}
/// A page (`url`) and what the host does itself (`host`) open as
/// written, from a Link and from a menu's rows alike.
#[test]
fn a_page_or_the_hosts_own_opens_as_written() {
let root = json!({});
let c = ctx(&root, &[]);
let page = json!({ "url": "https://grain.social/settings/import" });
let host = json!({ "host": "signOut" });
let layout = json!({ "component": "Stack", "children": [
{ "component": "Link", "props": { "label": "Sign out", "open": host } },
{ "component": "List", "props": { "style": "rows", "items": [
{ "label": "Import", "open": page }, { "label": "Sign out", "open": host }] },
"children": [{ "component": "Text", "props": { "value": { "$": "label" } } }] },
] });
let tree = resolve(&layout, &root, &c).unwrap();
check::checked(&tree);
assert_eq!(
tree["k"][0]["p"],
json!({ "label": "Sign out", "open": host })
);
let items = &tree["k"][1]["items"];
assert_eq!(items[0]["open"], page);
assert_eq!(items[1]["open"], host);
}
#[test]
fn an_image_takes_its_ratio_from_its_data_else_four_to_three() {
let root = json!({});
let origins = vec!["https://cdn.bsky.app".to_string()];
let c = ctx(&root, &origins);
let layout = json!({ "component": "Image", "props": { "src": "https://cdn.bsky.app/a.jpg", "aspectRatio": { "$": "size" } } });
let ratio = |scope: Value| {
let drawn = resolve(&layout, &scope, &c).unwrap();
check::checked(&drawn);
drawn["p"]["ratio"].clone()
};
assert_eq!(ratio(json!({ "size": { "width": 2, "height": 1 } })), 2.0);
assert_eq!(
ratio(json!({ "size": { "width": 0, "height": 1 } })),
4.0 / 3.0
);
}
#[test]
fn a_photo_bleeds_and_offers_its_alt_and_a_face_without_a_picture_holds_its_place() {
let root = json!({});
let origins = vec!["https://cdn.bsky.app".to_string()];
let c = ctx(&root, &origins);
let image = |p: Value| json!({ "component": "Image", "props": p });
let layout = json!({ "component": "Stack", "children": [
image(json!({ "src": "https://cdn.bsky.app/a.jpg", "alt": "A dog", "bleed": true, "showAlt": true })),
image(json!({ "src": "https://cdn.bsky.app/a.jpg", "showAlt": true })),
image(json!({ "src": { "$": "none" }, "size": "face" })),
image(json!({ "src": { "$": "none" } })),
{ "component": "Link", "props": { "href": "https://a.example", "label": "Alice", "style": "name" } },
] });
let tree = resolve(&layout, &json!({}), &c).unwrap();
check::checked(&tree);
let k = tree["k"].as_array().unwrap();
// The picture with no size and no source is left out.
assert_eq!(k.len(), 4);
assert_eq!(k[0]["p"]["bleed"], true);
assert_eq!(k[0]["p"]["showAlt"], true);
// With no alt text there is nothing to mark ALT.
assert_eq!(k[1]["p"].get("showAlt"), None);
assert_eq!(k[1]["p"].get("bleed"), None);
assert_eq!(k[2]["p"]["src"], Value::Null);
assert_eq!(k[2]["p"]["size"], "face");
assert_eq!(k[3]["p"]["style"], "name");
}
/// A gallery's header: its author's picture opens their profile, not
/// the gallery; its location a muted link to the location's feed, its
/// words alone where the gallery has no place to open.
#[test]
fn an_authors_picture_opens_them_and_a_location_is_a_muted_link() {
let root = json!({});
let origins = vec!["https://cdn.bsky.app".to_string()];
let c = ctx(&root, &origins);
let face = |href: Value| {
json!({ "component": "Image", "props": {
"src": "https://cdn.bsky.app/a.jpg", "alt": "Alice", "size": "avatar", "href": href } })
};
let place = json!({ "component": "Link", "props": { "label": { "$": "locationDisplay" }, "style": "muted",
"open": { "query": "social.grain.feed.getFeed", "params": { "location": { "$": "location.value" } } } } });
let layout = json!({ "component": "Stack", "children": [
face(json!({ "$": "creator.did" })), face(json!("just words")), face(json!({ "$": "none" })), place,
] });
let scope = json!({ "creator": { "did": "did:plc:alice" }, "locationDisplay": "Lisbon",
"location": { "value": "8a2a1072b59ffff" } });
let tree = resolve(&layout, &scope, &c).unwrap();
check::checked(&tree);
let k = tree["k"].as_array().unwrap();
assert_eq!(k[0]["p"]["open"], c.actor_call("did:plc:alice"));
assert_eq!(k[1]["p"].get("open"), None);
assert_eq!(k[2]["p"].get("open"), None);
assert_eq!(k[3]["p"]["style"], "muted");
assert_eq!(
k[3]["p"]["open"]["call"]["args"]["params"]["location"],
"8a2a1072b59ffff"
);
// No place to open: its words alone, never a dead link.
let nowhere = json!({ "creator": { "did": "did:plc:alice" }, "locationDisplay": "Lisbon" });
let tree = resolve(&layout, &nowhere, &c).unwrap();
let k = tree["k"].as_array().unwrap();
assert_eq!(k[3]["p"]["label"], "Lisbon");
assert_eq!(k[3]["p"].get("open"), None);
}
/// A profile's Share: its page on its app's site, made of the address
/// share begins and href's value, offered to share, opening nothing.
#[test]
fn a_link_shares_the_address_it_makes() {
let root = json!({});
let c = ctx(&root, &[]);
let layout = json!({ "component": "Link", "props": { "label": "Share profile",
"href": { "$": "handle" }, "share": "https://grain.social/profile/" } });
let tree = resolve(&layout, &json!({ "handle": "alice.test" }), &c).unwrap();
check::checked(&tree);
assert_eq!(
tree["p"],
json!({ "label": "Share profile", "share": "https://grain.social/profile/alice.test" })
);
let bad = json!({ "component": "Link", "props": { "label": "Share",
"href": { "$": "handle" }, "share": "grain.social/" } });
assert_eq!(
resolve(&bad, &json!({ "handle": "alice.test" }), &c).unwrap()["c"],
"Error"
);
}
/// A profile's Copy handle: the text copy begins and href's value,
/// offered to copy, opening nothing.
#[test]
fn a_link_copies_the_text_it_makes() {
let root = json!({});
let c = ctx(&root, &[]);
let layout = json!({ "component": "Link", "props": { "label": "Copy handle",
"href": { "$": "handle" }, "copy": "@" } });
let tree = resolve(&layout, &json!({ "handle": "alice.test" }), &c).unwrap();
check::checked(&tree);
assert_eq!(
tree["p"],
json!({ "label": "Copy handle", "copy": "@alice.test" })
);
}
/// Germ's Message: its messageMeUrl opened with the account's DID as its
/// fragment, then + and the reader's; signed out, the account's alone. No
/// DID there draws nothing; an address that is not https, or has a
/// fragment already, is the view's mistake.
#[test]
fn a_link_fills_its_fragment_with_two_accounts() {
let root = json!({});
let mut c = ctx(&root, &[]);
let germ = |href: &str, at: &str| {
json!({ "component": "Link", "props": { "label": "Message on Germ",
"href": href, "fragment": at } })
};
let scope = json!({ "did": "did:plc:bob", "handle": "bob.test" });
let url = "https://landing.ger.mx/newUser";
let signed_out = resolve(&germ(url, "did"), &scope, &c).unwrap();
assert_eq!(
signed_out["p"]["open"],
json!({ "url": format!("{url}#did:plc:bob") })
);
c.me = Some("did:plc:me");
let tree = resolve(&germ(url, "did"), &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(
tree["p"],
json!({ "label": "Message on Germ",
"open": { "url": format!("{url}#did:plc:bob+did:plc:me") } })
);
assert_eq!(resolve(&germ(url, "handle"), &scope, &c), None);
assert_eq!(resolve(&germ(url, "nope"), &scope, &c), None);
for bad in [
"https://landing.ger.mx/newUser#x",
"at://did:plc:bob/a.b.c/1",
] {
assert_eq!(
resolve(&germ(bad, "did"), &scope, &c).unwrap()["c"],
"Error"
);
}
}
/// A Stack with where is drawn only where its scope holds there what
/// the path paired with it holds, or the literal of an $is: Germ's
/// button, for everyone or for those its account follows.
#[test]
fn a_stack_is_drawn_where_its_scope_matches() {
let root = json!({});
let c = ctx(&root, &[]);
let stack = |w: Value| {
json!({ "component": "Stack", "props": { "where": w },
"children": [{ "component": "Text", "props": { "value": "Message" } }] })
};
let scope = json!({ "policy": "everyone", "same": "everyone" });
let everyone = stack(json!({ "policy": { "$is": "everyone" } }));
assert_eq!(resolve(&everyone, &scope, &c).unwrap()["c"], "Stack");
assert_eq!(
resolve(&everyone, &json!({ "policy": "usersIFollow" }), &c),
None
);
assert_eq!(resolve(&everyone, &json!({}), &c), None);
assert!(resolve(&stack(json!({ "policy": "same" })), &scope, &c).is_some());
let bad = resolve(&stack(json!({ "a..b": { "$is": 1 } })), &scope, &c).unwrap();
assert_eq!(bad["c"], "Error");
}
/// An item whose open binds a DID opens that account, as a Link's href
/// does: a suggested account's card.
#[test]
fn an_item_opens_the_account_its_did_names() {
let root = json!({});
let c = ctx(&root, &[]);
let layout = json!({ "component": "List", "props": { "items": { "$": "people" }, "open": { "$": "did" } },
"children": [{ "component": "Text", "props": { "value": { "$": "did" } } }] });
let tree = resolve(&layout, &json!({ "people": [{ "did": "did:plc:a" }] }), &c).unwrap();
check::checked(&tree);
assert_eq!(
tree["items"][0]["open"],
json!({ "call": { "name": "describe_repo", "args": { "actor": "did:plc:a" } } })
);
}
/// Notifications marked seen once shown: the call, its input read from
/// the view's scope, in a trusted tree alone.
#[test]
fn a_list_says_what_to_call_once_it_is_shown() {
let root = json!({});
let mut c = ctx(&root, &[]);
let layout = json!({ "component": "List", "props": { "items": { "$": "items" }, "open": false,
"shown": { "method": "com.example.updateSeen", "service": "did:web:example.com#svc",
"input": { "seenAt": { "$": "at" } } } },
"children": [{ "component": "Text", "props": { "value": { "$": "t" } } }] });
let scope = json!({ "at": "2026-01-01T00:00:00Z", "items": [{ "t": "a" }] });
let tree = resolve(&layout, &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(
tree["p"]["shown"],
json!({ "method": "com.example.updateSeen", "service": "did:web:example.com#svc",
"input": { "seenAt": "2026-01-01T00:00:00Z" } })
);
c.trusted = false;
assert!(
resolve(&layout, &scope, &c).unwrap()["p"]
.get("shown")
.is_none()
);
// A call naming no service is the view's error.
c.trusted = true;
let bad = json!({ "component": "List", "props": { "items": { "$": "items" },
"shown": { "method": "com.example.updateSeen" } }, "children": [] });
assert_eq!(resolve(&bad, &scope, &c).unwrap()["c"], "Error");
}
/// Suggestions once after a feed's second item, read from the view's
/// scope; not past the items there are, nor on a page more.
#[test]
fn a_stack_with_at_is_drawn_once_among_the_items() {
let root = json!({ "params": {} });
let c = ctx(&root, &[]);
let layout = json!({ "component": "List", "props": { "items": { "$": "feed" }, "open": false },
"children": [
{ "component": "Text", "props": { "value": { "$": "title" } } },
{ "component": "Stack", "props": { "at": 2 }, "children": [
{ "component": "Text", "props": { "value": { "$": "suggested" } } }] }] });
let item = |t: &str| json!({ "title": t });
let scope =
json!({ "suggested": "Suggested for you", "feed": [item("a"), item("b"), item("c")] });
let tree = resolve(&layout, &scope, &c).unwrap();
check::checked(&tree);
let texts: Vec<&Value> = tree["items"]
.as_array()
.unwrap()
.iter()
.map(|i| &i["k"][0]["k"].as_array().map_or(&i["k"][0], |k| &k[0])["p"]["runs"][0]["text"])
.collect();
assert_eq!(
texts,
[
&json!("a"),
&json!("b"),
&json!("Suggested for you"),
&json!("c")
]
);
// One item: not past it.
let short = json!({ "suggested": "S", "feed": [item("a")] });
assert_eq!(
resolve(&layout, &short, &c).unwrap()["items"]
.as_array()
.unwrap()
.len(),
1
);
// A page more: none again.
let later = json!({ "params": { "cursor": "next" } });
let tree = resolve(&layout, &scope, &ctx(&later, &[])).unwrap();
assert_eq!(tree["items"].as_array().unwrap().len(), 3);
// Two, each after its own count of items, whatever order written in.
let two = json!({ "component": "List", "props": { "items": { "$": "feed" }, "open": false },
"children": [
{ "component": "Text", "props": { "value": { "$": "title" } } },
{ "component": "Stack", "props": { "at": 2 }, "children": [
{ "component": "Text", "props": { "value": "second" } }] },
{ "component": "Stack", "props": { "at": 1 }, "children": [
{ "component": "Text", "props": { "value": "first" } }] }] });
let tree = resolve(&two, &scope, &c).unwrap();
let texts: Vec<&Value> = tree["items"]
.as_array()
.unwrap()
.iter()
.map(|i| &i["k"][0]["k"].as_array().map_or(&i["k"][0], |k| &k[0])["p"]["runs"][0]["text"])
.collect();
assert_eq!(
texts,
[
&json!("a"),
&json!("first"),
&json!("b"),
&json!("second"),
&json!("c")
]
);
}
/// Oneself before who has stories, opening one's own; signed out, no one.
#[test]
fn a_strip_draws_its_first_row_before_its_items_where_needs_keeps_it() {
let layout = json!({ "component": "List", "props": { "items": { "$": "authors" }, "style": "strip", "needs": "did", "pages": true,
"first": { "did": { "$root": "me.did" }, "label": "Your story",
"open": { "query": "com.example.getStories", "params": { "actor": { "$": "did" } } } },
"open": { "query": "com.example.getStories", "params": { "actor": { "$": "did" }, "seen": true } } },
"children": [{ "component": "Text", "props": { "value": { "$": ["label", "did"] } } }] });
let scope = json!({ "authors": [{ "did": "did:plc:b" }] });
let root = json!({ "me": { "did": "did:plc:me" } });
let tree = resolve(&layout, &scope, &ctx(&root, &[])).unwrap();
check::checked(&tree);
let items = tree["items"].as_array().unwrap();
assert_eq!(items.len(), 2);
assert_eq!(items[0]["k"][0]["p"]["runs"][0]["text"], "Your story");
// Opening one pages through them all.
assert_eq!(tree["p"]["pages"], true);
// The first row opens its own; the rest the List's.
assert_eq!(
items[0]["open"]["call"]["args"]["params"],
json!({ "actor": "did:plc:me" })
);
assert_eq!(
items[1]["open"]["call"]["args"]["params"],
json!({ "actor": "did:plc:b", "seen": true })
);
let signed_out = json!({ "me": null });
let tree = resolve(&layout, &scope, &ctx(&signed_out, &[])).unwrap();
assert_eq!(tree["items"].as_array().unwrap().len(), 1);
}
/// An account with stories not yet seen is ringed; one caught up is not.
#[test]
fn a_face_is_ringed_where_its_scope_holds_something_at_ring() {
let root = json!({});
let origins = vec!["https://cdn.bsky.app".to_string()];
let c = ctx(&root, &origins);
let face = |ring: &str| json!({ "component": "Image", "props": { "src": "https://cdn.bsky.app/a.jpg", "size": "face", "ring": ring } });
let ringed = |ring: &str, unseen: u64| {
resolve(&face(ring), &json!({ "unseen": unseen }), &c).unwrap()
};
let tree = ringed("unseen", 2);
check::checked(&tree);
assert_eq!(tree["p"]["ring"], true);
assert_eq!(ringed("unseen", 0)["p"].get("ring"), None);
assert_eq!(
ringed("not a path", 2)["p"],
json!({ "component": "Image", "message": "ring: a path in the scope" })
);
// One's own, first in a strip of stories, has a + to add to it.
let own = json!({ "component": "Image", "props": { "src": "https://cdn.bsky.app/a.jpg", "size": "large", "plus": "add" } });
let tree = resolve(&own, &json!({ "add": true }), &c).unwrap();
check::checked(&tree);
assert_eq!(tree["p"]["plus"], true);
assert_eq!(
resolve(&own, &json!({}), &c).unwrap()["p"].get("plus"),
None
);
let bad = json!({ "component": "Image", "props": { "src": "https://cdn.bsky.app/a.jpg", "plus": "not a path" } });
assert_eq!(
resolve(&bad, &json!({}), &c).unwrap()["p"],
json!({ "component": "Image", "message": "plus: a path in the scope" })
);
}
/// One's own covers may be picked: Covers' select offered where the
/// scope's DID at `mine` is the signed-in person's, in a trusted view,
/// each item its call's input read from it (none where it can't be
/// read), and nothing offered where none can be picked.
#[test]
fn ones_own_covers_may_be_picked_and_each_called_for() {
let root = json!({});
let origins = vec!["https://cdn.grain.social".to_string()];
let mut c = ctx(&root, &origins);
c.me = Some("did:plc:me");
let call = json!({ "method": "social.grain.unspecced.deleteGallery", "service": "did:web:grain.social#grain_appview",
"input": { "rkey": { "$rkey": "uri" } } });
let covers = |select: Value| {
json!({ "component": "Covers", "props": { "items": { "$": "items" }, "src": { "$": "thumb" },
"style": "tiles", "select": select } })
};
let select = json!({ "mine": "actor.did", "action": "Delete", "noun": ["gallery", "galleries"],
"confirm": "Gone for good.", "tone": "danger", "call": call });
let scope = |did: &str| {
json!({ "actor": { "did": did }, "items": [
{ "uri": "at://did:plc:me/social.grain.gallery/3kone", "thumb": "https://cdn.grain.social/1.jpg" },
{ "thumb": "https://cdn.grain.social/2.jpg" },
] })
};
let tree = resolve(&covers(select.clone()), &scope("did:plc:me"), &c).unwrap();
check::checked(&tree);
assert_eq!(
tree["p"]["select"],
json!({ "label": "Select", "action": "Delete", "one": "gallery", "many": "galleries",
"confirm": "Gone for good.", "tone": "danger",
"method": "social.grain.unspecced.deleteGallery", "service": "did:web:grain.social#grain_appview" })
);
assert_eq!(tree["items"][0]["pick"], json!({ "rkey": "3kone" }));
assert!(tree["items"][1].get("pick").is_none());
// Its own words where it gives them; no mine, offered to anyone signed in.
let mut plain = select.clone();
plain.as_object_mut().unwrap().remove("mine");
plain.as_object_mut().unwrap().remove("confirm");
plain["label"] = json!("Choose");
let tree = resolve(&covers(plain), &scope("did:plc:else"), &c).unwrap();
assert_eq!(tree["p"]["select"]["label"], "Choose");
assert!(tree["p"]["select"].get("confirm").is_none());
let offered = |tree: Value| {
tree["p"].get("select").is_some() || tree["items"][0].get("pick").is_some()
};
// Someone else's, signed out, or an untrusted view's: none.
assert!(!offered(
resolve(&covers(select.clone()), &scope("did:plc:else"), &c).unwrap()
));
c.me = None;
assert!(!offered(
resolve(&covers(select.clone()), &scope("did:plc:me"), &c).unwrap()
));
c.me = Some("did:plc:me");
c.trusted = false;
assert!(!offered(
resolve(&covers(select.clone()), &scope("did:plc:me"), &c).unwrap()
));
c.trusted = true;
// None that can be picked: nothing offered.
let none = json!({ "actor": { "did": "did:plc:me" }, "items": [{ "thumb": "https://cdn.grain.social/2.jpg" }] });
assert!(!offered(
resolve(&covers(select.clone()), &none, &c).unwrap()
));
// A mine that is no path, or a call that names no method: the view's error.
let mut bad = select.clone();
bad["mine"] = json!("a..b");
assert_eq!(
resolve(&covers(bad), &scope("did:plc:me"), &c).unwrap()["p"]["message"],
"select.mine: a path in the scope"
);
let mut bad = select.clone();
bad["call"] = json!({ "service": "did:web:grain.social#grain_appview" });
assert_eq!(
resolve(&covers(bad), &scope("did:plc:me"), &c).unwrap()["p"]["message"],
"call: names a method and a service"
);
// Deleting what a query plans: the call its method and service,
// each item's input the query's params read from it.
let mut planned = select;
planned.as_object_mut().unwrap().remove("call");
planned["deletes"] = json!({ "method": "social.grain.gallery.getDeletionPlan",
"service": "did:web:grain.social#grain_appview", "params": { "gallery": { "$": "uri" } } });
let tree = resolve(&covers(planned), &scope("did:plc:me"), &c).unwrap();
check::checked(&tree);
assert_eq!(
(
&tree["p"]["select"]["method"],
&tree["p"]["select"]["service"]
),
(
&json!("social.grain.gallery.getDeletionPlan"),
&json!("did:web:grain.social#grain_appview")
)
);
assert_eq!(
tree["items"][0]["pick"],
json!({ "gallery": "at://did:plc:me/social.grain.gallery/3kone" })
);
assert!(tree["items"][1].get("pick").is_none());
}
/// An Action that deletes what a query plans is drawn as the call the
/// clients make (`call_procedure`): the query, its params as the input.
#[test]
fn an_action_deleting_as_planned_is_drawn_as_its_call() {
let root = json!({});
let c = ctx(&root, &[]);
let action = json!({ "component": "Action", "props": { "label": "Delete gallery",
"tone": "danger", "leave": true, "deletes": {
"method": "social.grain.gallery.getDeletionPlan",
"service": "did:web:grain.social#grain_appview",
"params": { "gallery": { "$": "gallery.uri" } } } } });
let scope = json!({ "gallery": { "uri": "at://did:plc:me/social.grain.gallery/3kone" } });
let tree = resolve(&action, &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(
tree["p"]["call"],
json!({ "method": "social.grain.gallery.getDeletionPlan",
"service": "did:web:grain.social#grain_appview",
"input": { "gallery": "at://did:plc:me/social.grain.gallery/3kone" } })
);
assert_eq!(tree["p"]["leave"], true);
}
#[test]
fn a_search_opens_its_query_with_the_words_or_searches_again_in_place() {
let search = json!({ "component": "Search", "props": {
"open": { "query": "com.example.searchPosts", "params": { "limit": 20 } },
"param": "q", "placeholder": "Search posts", "value": { "$": "params.q" },
} });
// Where a search starts: it opens the query, with nothing searched yet.
let start = json!({ "method": "com.example.getExplore", "params": {} });
let tree = resolve(&search, &json!({}), &ctx(&start, &[])).unwrap();
check::checked(&tree);
assert_eq!(
tree["p"],
json!({ "open": { "call": { "name": "query", "args": { "method": "com.example.searchPosts", "params": { "limit": 20 } } } },
"param": "q", "placeholder": "Search posts" })
);
// Over its answer: the words searched, and searching again in place.
let results =
json!({ "method": "com.example.searchPosts", "params": { "q": "dogs", "limit": 20 } });
let scope = json!({ "params": { "q": "dogs" } });
let tree = resolve(&search, &scope, &ctx(&results, &[])).unwrap();
check::checked(&tree);
assert_eq!(tree["p"]["value"], "dogs");
assert_eq!(tree["p"]["current"], true);
// One that opens a record searches nothing, and draws nothing.
let record =
json!({ "component": "Search", "props": { "open": { "$": "uri" }, "param": "q" } });
let scope = json!({ "uri": "at://did:plc:a/com.example.post/1" });
assert_eq!(resolve(&record, &scope, &ctx(&results, &[])), None);
}
#[test]
fn a_tab_with_no_label_is_left_out() {
let root = json!({ "method": "com.example.get", "params": { "id": "1" } });
let c = ctx(&root, &[]);
let tab = |label: Option<&str>, id: &str| json!({ "label": label, "open": { "query": "com.example.get", "params": { "id": id } } });
let layout = json!({ "component": "Tabs", "props": { "items": [
tab(Some("One"), "1"), tab(None, "2"), tab(Some("Three"), "3"),
] } });
let tree = resolve(&layout, &json!({}), &c).unwrap();
check::checked(&tree);
let labels: Vec<&Value> = tree["p"]["items"]
.as_array()
.unwrap()
.iter()
.map(|t| &t["label"])
.collect();
assert_eq!(labels, [&json!("One"), &json!("Three")]);
}
/// A feed's items each tell it their uri, feedContext and reqId (those
/// there); one whose uri is no record tells nothing, and its
/// interaction draws nothing. An interaction is a trusted view's alone.
#[test]
fn items_report_to_their_feed_and_interactions_carry_the_report() {
let root = json!({});
let mut c = ctx(&root, &[]);
let (item, feed_context, req_id) = (
Path::parse("post.uri").unwrap(),
Path::parse("feedContext").unwrap(),
Path::parse("reqId").unwrap(),
);
c.report = Some(ReportPaths {
item: &item,
feed_context: Some(&feed_context),
req_id: Some(&req_id),
});
let layout = |interaction: Value| {
json!({ "component": "List", "props": { "items": { "$": "items" }, "open": false },
"children": [{ "component": "Action", "props": { "label": "Less like this", "interaction": interaction } }] })
};
let less = layout(json!({ "event": "app.bsky.feed.defs#requestLess" }));
let (one, two) = (
"at://did:plc:a/app.bsky.feed.post/1",
"at://did:plc:a/app.bsky.feed.post/2",
);
let scope = json!({ "items": [
{ "post": { "uri": one }, "feedContext": "fc", "reqId": "r1" },
{ "post": { "uri": two }, "feedContext": "" },
{ "post": { "uri": "https://a.example/3" } },
{ "feedContext": "fc" },
] });
let tree = resolve(&less, &scope, &c).unwrap();
check::checked(&tree);
let items = tree["items"].as_array().unwrap();
let told = json!({ "item": one, "feedContext": "fc", "reqId": "r1" });
assert_eq!(items[0]["report"], told);
assert_eq!(
items[0]["k"][0]["p"]["interaction"],
json!({ "event": "app.bsky.feed.defs#requestLess", "report": told })
);
assert!(items[0]["k"][0]["p"]["key"].is_string());
assert_eq!(items[1]["report"], json!({ "item": two }));
assert!(items[2].get("report").is_none());
assert!(items[3].get("report").is_none());
assert_eq!(items[2]["k"], json!([]));
let nameless = resolve(&layout(json!({ "event": "" })), &scope, &c).unwrap();
assert_eq!(
nameless["items"][0]["k"][0]["p"],
json!({ "component": "Action", "message": "interaction: names an event" })
);
c.trusted = false;
let untrusted = resolve(&less, &scope, &c).unwrap();
assert_eq!(untrusted["items"][0]["k"], json!([]));
}
/// A list's items from the view's own scope: a literal row's `$root`
/// values, in arrays too; a root path's array, a page's where its join
/// reads the page's records; nothing there draws nothing, something
/// not an array or a path that is none an error.
#[test]
fn a_list_reads_its_items_from_the_root() {
let root = json!({ "me": { "did": "did:plc:me" }, "joins": { "recent": [{ "t": "a" }], "bad": 5 } });
let mut c = ctx(&root, &[]);
c.paged = vec!["recent"];
let list = |items: Value, value: &str| {
json!({ "component": "List", "props": { "items": items, "open": false },
"children": [{ "component": "Text", "props": { "value": { "$": value } } }] })
};
let drawn = |layout: Value| resolve(&layout, &json!({}), &c);
let literal = drawn(list(
json!([{ "tags": [{ "$root": "me.did" }, "x"] }]),
"tags.0",
))
.unwrap();
check::checked(&literal);
assert_eq!(
literal["items"][0]["k"][0]["p"]["runs"][0]["text"],
"did:plc:me"
);
let joined = drawn(list(json!({ "$root": "joins.recent" }), "t")).unwrap();
check::checked(&joined);
assert_eq!(joined["p"]["page"], true);
assert_eq!(joined["items"][0]["k"][0]["p"]["runs"][0]["text"], "a");
assert!(drawn(list(json!({ "$root": "joins.none" }), "t")).is_none());
for (items, message) in [
(json!({ "$root": "joins.bad" }), "items: no array"),
(json!({ "$root": "a..b" }), "unknown path syntax"),
(json!([{ "x": { "$root": 5 } }]), "unknown path syntax"),
] {
let error = drawn(list(items, "t")).unwrap();
check::checked(&error);
assert_eq!(
error["p"],
json!({ "component": "List", "message": message })
);
}
}
/// A List or Covers of a join that pages itself carries the call for
/// its page after; one a `limit` cuts, none. In that join's page more
/// alone, a List draws its items alone (no first row, no block at a
/// place), and says its next null at the end; another join's, none.
#[test]
fn a_listing_of_a_join_that_pages_itself_says_its_next() {
let root = json!({ "joins": { "recent": { "items": [{ "t": "a" }, { "t": "b" }] } } });
let next = json!({ "name": "query", "args": { "more": "m" } });
let mut c = ctx(&root, &[]);
c.more.next = vec![("recent", next.clone())];
let items = json!({ "$": "joins.recent.items" });
let list = |props: Value| {
json!({ "component": "List", "props": props, "children": [
{ "component": "Text", "props": { "value": { "$": "t" } } },
{ "component": "Stack", "props": { "at": 1 },
"children": [{ "component": "Text", "props": { "value": "between" } }] },
] })
};
let first = json!({ "items": items, "first": { "t": "me" }, "open": false });
let drawn = |layout: &Value, c: &Ctx| resolve(layout, &root, c).unwrap();
let rows = drawn(&list(first.clone()), &c);
check::checked(&rows);
assert_eq!(rows["p"]["next"], next);
assert_eq!(rows["items"].as_array().map(Vec::len), Some(4));
let covers =
json!({ "component": "Covers", "props": { "items": items, "title": { "$": "t" } } });
let covers = drawn(&covers, &c);
check::checked(&covers);
assert_eq!(covers["p"]["next"], next);
let cut = drawn(&list(json!({ "items": items, "limit": 5 })), &c);
assert!(cut["p"].get("next").is_none());
c.more = More {
next: Vec::new(),
alone: Some("recent"),
};
let more = drawn(&list(first.clone()), &c);
assert_eq!(more["p"]["next"], Value::Null);
assert_eq!(more["items"].as_array().map(Vec::len), Some(2));
c.more.alone = Some("other");
assert!(drawn(&list(first), &c)["p"].get("next").is_none());
}
/// A list with nothing in it says its own `empty`; `where`, `mine`,
/// `needs` and a Stack's `when` that are no paths are errors.
#[test]
fn a_list_says_it_is_empty_and_paths_that_are_none_are_errors() {
let root = json!({});
let c = ctx(&root, &[]);
let list = |props: Value| {
let mut p = json!({ "items": { "$": "things" }, "open": false });
p.as_object_mut()
.unwrap()
.extend(props.as_object().unwrap().clone());
json!({ "component": "List", "props": p })
};
let scope = json!({ "things": [{ "a": 1 }] });
let empty = resolve(
&list(json!({ "empty": "Nothing yet" })),
&json!({ "things": [] }),
&c,
)
.unwrap();
check::checked(&empty);
assert_eq!(
empty["p"],
json!({ "style": "rows", "empty": "Nothing yet" })
);
for (props, message) in [
(
json!({ "where": { "a..b": "x" } }),
"where: paths within the element to paths in the scope",
),
(
json!({ "where": { "a": "x..y" } }),
"where: paths within the element to paths in the scope",
),
(json!({ "mine": "a..b" }), "mine: a path within each item"),
(json!({ "needs": "a..b" }), "needs: a path within each item"),
] {
let error = resolve(&list(props), &scope, &c).unwrap();
assert_eq!(
error["p"],
json!({ "component": "List", "message": message })
);
}
let gate = json!({ "component": "Stack", "props": { "when": "a..b" },
"children": [{ "component": "Text", "props": { "value": "x" } }] });
assert_eq!(
resolve(&gate, &scope, &c).unwrap()["p"],
json!({ "component": "Stack", "message": "when: a path in the scope" })
);
}
/// A Stack's, Pane's or Bar's gate on the kit is left marked for
/// `kit::fit`, beside any gate on its scope; a Menu's rows keep their
/// Stack's, and every Stack's around it however deep; a node's fallback
/// is drawn over the same scope, and fitted away with nothing marked left.
#[test]
fn gates_on_the_kit_and_fallbacks_are_marked_for_the_kit() {
let root = json!({});
let c = ctx(&root, &[]);
let text = |v: &str| json!({ "component": "Text", "props": { "value": v } });
let kit = json!({ "$kit": ">=0.3.0" });
let layout = json!({ "component": "Stack", "children": [
{ "component": "Stack", "props": { "when": kit, "unless": "off" }, "children": [text("new")] },
{ "component": "Bar", "props": { "unless": kit, "title": ["Old"] } },
{ "component": "Menu", "children": [
{ "component": "Stack", "props": { "when": kit }, "children": [text("row")] },
{ "component": "Stack", "children": [text("plain")] },
{ "component": "Stack", "props": { "unless": kit }, "children": [
{ "component": "Stack", "children": [
{ "component": "Stack", "props": { "when": { "$kit": ">=0.1.0" } }, "children": [text("deep")] }] }] }] },
{ "component": "Text", "props": { "value": "x" },
"fallback": { "component": "Text", "props": { "value": { "$": "name" } } } },
{ "component": "Text", "props": { "value": "y" },
"fallback": { "component": "Text", "props": { "value": { "$": "missing" } } } },
] });
let drawn = resolve(&layout, &json!({ "name": "fell back", "off": false }), &c).unwrap();
let k = &drawn["k"];
assert_eq!(k[0]["$kit"], json!([{ "when": ">=0.3.0" }]));
assert_eq!(k[1]["$kit"], json!([{ "unless": ">=0.3.0" }]));
assert_eq!(k[2]["k"][0]["$kit"], json!([{ "when": ">=0.3.0" }]));
assert_eq!(k[2]["k"][1].get("$kit"), None);
assert_eq!(k[2]["k"][2]["c"], "Text");
assert_eq!(
k[2]["k"][2]["$kit"],
json!([{ "when": ">=0.1.0" }, { "unless": ">=0.3.0" }])
);
assert_eq!(k[3]["fallback"]["p"]["runs"][0]["text"], "fell back");
assert_eq!(
k[4].get("fallback"),
None,
"a fallback drawing nothing is none"
);
let mut meta = json!({ "ui": { "v": 1, "trusted": true, "root": drawn } });
crate::kit::fit(&mut meta, &crate::kit::Kit::oldest());
let fitted = meta["ui"].to_string();
assert!(!fitted.contains("$kit"), "{fitted}");
assert_eq!(check(&meta["ui"]), Ok(()));
for (word, there) in [
("new", false),
("row", false),
("Old", true),
("plain", true),
("deep", true),
] {
assert_eq!(
fitted.contains(&format!("\"{word}\"")),
there,
"{word}: {fitted}"
);
}
}
/// A Stack's `when` holds for a list or an object with something in
/// it, and for true; not for an empty one.
#[test]
fn a_stack_is_drawn_when_its_scope_holds_something() {
let root = json!({});
let c = ctx(&root, &[]);
let gate = |when: &str| {
json!({ "component": "Stack", "props": { "when": when },
"children": [{ "component": "Text", "props": { "value": when } }] })
};
let scope =
json!({ "list": [1], "none": [], "object": { "a": 1 }, "empty": {}, "flag": true });
let drawn: Vec<&str> = ["list", "none", "object", "empty", "flag"]
.into_iter()
.filter(|w| resolve(&gate(w), &scope, &c).is_some())
.collect();
assert_eq!(drawn, ["list", "object", "flag"]);
}
/// Closed, an Action is its count; else it creates (its template's
/// arrays and literals resolved, the record it made already named as
/// `existing`), deletes, or calls; one that names none of them, or
/// names them wrongly, is an error; one whose `$first` finds nothing
/// draws nothing.
#[test]
fn actions_create_delete_and_call_or_say_what_is_wrong() {
let root = json!({});
let c = ctx(&root, &[]);
let action = |props: Value| json!({ "component": "Action", "props": props });
let layout = json!({ "component": "Stack", "children": [
action(json!({ "label": "Reply", "icon": "reply", "count": { "$": "n" }, "closed": { "$": "off" },
"create": { "collection": "app.test.reply", "record": {} } })),
action(json!({ "create": { "record": {} } })),
action(json!({ "create": { "collection": "app.test.like", "record": { "subject": { "$first": [{ "$": "a" }, { "$": "b" }] } } } })),
action(json!({ "label": "Tag", "create": { "collection": "app.test.tag", "record": { "langs": ["en", { "$": "lang" }], "n": 1 } },
"existing": { "$": "mine" } })),
action(json!({ "label": "Delete", "delete": { "uri": { "$": "mine" } } })),
action(json!({ "label": "Delete", "delete": { "uri": { "$": "lang" } } })),
action(json!({ "label": "Nothing" })),
action(json!({ "label": "Call", "call": { "method": "com.example.do" } })),
action(json!({ "label": "Call", "call": { "method": "com.example.do", "service": "did:web:a.example#svc" } })),
action(json!({ "create": { "collection": "app.test.like", "record": { "subject": { "$strongRef": "post" } } } })),
action(json!({ "create": { "collection": "app.test.like", "record": {} }, "existing": { "$": 5 } })),
] });
let mine = "at://did:plc:me/app.test.tag/1";
let scope =
json!({ "n": 4, "off": true, "lang": "fr", "mine": mine, "post": { "uri": mine } });
let tree = resolve(&layout, &scope, &c).unwrap();
check::checked(&tree);
let k = tree["k"].as_array().unwrap();
assert_eq!(k.len(), 10, "the $first that finds nothing draws nothing");
assert_eq!(
k[0],
json!({ "c": "Stat", "p": { "value": 4, "icon": "reply", "label": "Reply" } })
);
assert_eq!(
k[1]["p"],
json!({ "component": "Action", "message": "create: names a collection and a record" })
);
assert_eq!(
k[2]["p"]["create"],
json!({ "collection": "app.test.tag", "record": { "langs": ["en", "fr"], "n": 1 } })
);
assert_eq!(k[2]["p"]["existing"], mine);
assert_eq!(k[3]["p"]["delete"], json!({ "uri": mine }));
assert!(k[3]["p"]["key"].is_string());
assert_eq!(
k[4]["p"],
json!({ "component": "Action", "message": "delete.uri: not usable" })
);
assert_eq!(
k[5]["p"],
json!({ "component": "Action", "message": "names none of create, delete, interaction, call and deletes" })
);
assert_eq!(
k[6]["p"],
json!({ "component": "Action", "message": "call: names a method and a service" })
);
assert_eq!(
k[7]["p"]["call"],
json!({ "method": "com.example.do", "service": "did:web:a.example#svc", "input": {} })
);
assert_eq!(
k[8]["p"],
json!({ "component": "Action", "message": "record: not usable" })
);
assert_eq!(
k[9]["p"],
json!({ "component": "Action", "message": "unknown path syntax 5" })
);
}
/// A profile's Follow is a button of its own; a like stays compact.
#[test]
fn an_action_drawn_as_a_button_says_so() {
let root = json!({});
let c = ctx(&root, &[]);
let follow = |style: Option<&str>| {
let mut p = json!({ "label": "Follow", "create": { "collection": "app.test.follow", "record": {} } });
if let Some(s) = style {
p["style"] = s.into();
}
resolve(
&json!({ "component": "Action", "props": p }),
&json!({}),
&c,
)
.unwrap()
};
let tree = follow(Some("button"));
check::checked(&tree);
assert_eq!(tree["p"]["style"], "button");
assert_eq!(follow(None)["p"].get("style"), None);
}
/// A setting as it stands, a default where it was never set, and its
/// call left with `$on` for the client; none in an untrusted view.
#[test]
fn a_toggle_says_whether_it_is_on_and_what_a_flip_sends() {
let root = json!({});
let mut c = ctx(&root, &[]);
let toggle = |on: &str| {
json!({ "component": "Toggle", "props": { "label": "Keep EXIF", "about": "Camera data",
"on": { "$": on }, "default": true,
"call": { "method": "a.b.setPreference", "service": "did:web:a.example#svc",
"input": { "preference": { "exif": { "$on": true }, "place": { "$first": [{ "$": "prefs.@photoPref.place" }, true] } } } } } })
};
let scope =
json!({ "prefs": [{ "$type": "a.b.defs#photoPref", "exif": false, "place": false }] });
let tree = resolve(&toggle("prefs.@photoPref.exif"), &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(tree["p"]["on"], false);
assert_eq!(tree["p"]["about"], "Camera data");
assert_eq!(
tree["p"]["call"]["input"],
json!({ "preference": { "exif": { "$on": true }, "place": false } })
);
// Never set: its default, and the other field's.
let tree = resolve(
&toggle("prefs.@photoPref.exif"),
&json!({ "prefs": [] }),
&c,
)
.unwrap();
assert_eq!(tree["p"]["on"], true);
assert_eq!(tree["p"]["call"]["input"]["preference"]["place"], true);
c.trusted = false;
assert_eq!(resolve(&toggle("prefs.@photoPref.exif"), &scope, &c), None);
}
/// A feed pinned, unpinned and moved as its whole preference: the array
/// read from the scope with the feed added at its end, taken out, or
/// moved, the rest as they were, and nothing of the other preferences
/// (the call sets one). A button that would change nothing (Pin where it
/// is pinned, Unpin where it is not, the first row's Up, the last's
/// Down), or whose parts can't be read, is not drawn; a malformed edit is
/// the view's error.
#[test]
fn template_edits_pin_unpin_and_move_a_preferences_feeds() {
let root = json!({});
let c = ctx(&root, &[]);
let action = |label: &str, items: Value| {
json!({ "component": "Action", "props": { "label": label, "reload": true,
"call": { "method": "a.b.setPreference", "service": "did:web:a.example#svc",
"input": { "preference": { "$type": "a.b.defs#pinnedFeedsPref", "items": items } } } } })
};
let recent = json!({ "id": "recent", "label": "Recent", "type": "feed", "path": "/" });
let following = json!({ "id": "following", "label": "Following", "type": "feed", "path": "/feeds/following" });
let fuji = json!({ "id": "camera:Fuji X100V", "label": "Fuji X100V", "type": "camera",
"path": "/camera/Fuji X100V" });
let pinned = json!({ "$first": [{ "$": "prefs.@pinnedFeedsPref.items" }, [recent]] });
let id = json!({ "$join": ["camera:", { "$": "params.camera" }] });
let pin = action(
"Pin",
json!({ "$with": [pinned, "id", { "id": id, "label": { "$": "params.camera" }, "type": "camera",
"path": { "$join": ["/camera/", { "$": "params.camera" }] } }] }),
);
let unpin = action("Unpin", json!({ "$without": [pinned, "id", id] }));
let items = |tree: Option<Value>| {
tree.map(|t| t["p"]["call"]["input"]["preference"]["items"].clone())
};
let prefs = |items: Value| {
json!({ "params": { "camera": "Fuji X100V" }, "prefs": [
{ "$type": "a.b.defs#themePref", "theme": "dark" },
{ "$type": "a.b.defs#pinnedFeedsPref", "items": items }] })
};
// Not pinned: Pin adds it at the end; no Unpin.
let scope = prefs(json!([recent, following]));
let tree = resolve(&pin, &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(
tree["p"]["call"]["input"],
json!({ "preference": { "$type": "a.b.defs#pinnedFeedsPref", "items": [recent, following, fuji] } })
);
assert_eq!(resolve(&unpin, &scope, &c), None);
// Pinned: Unpin takes it out, the rest in their order; no Pin.
let scope = prefs(json!([recent, fuji, following]));
assert_eq!(
items(resolve(&unpin, &scope, &c)),
Some(json!([recent, following]))
);
assert_eq!(resolve(&pin, &scope, &c), None);
// Never set: the feed added to the defaults.
let unset = json!({ "params": { "camera": "Fuji X100V" }, "prefs": [] });
assert_eq!(
items(resolve(&pin, &unset, &c)),
Some(json!([recent, fuji]))
);
// A row's own feed moved by its id, read from the view's scope.
let moved = |by: i64| {
action(
"Move",
json!({ "$move": [{ "$root": "prefs.@pinnedFeedsPref.items" }, "id", { "$": "id" }, by] }),
)
};
let root = prefs(json!([recent, fuji, following]));
let c = ctx(&root, &[]);
assert_eq!(
items(resolve(&moved(-1), &fuji, &c)),
Some(json!([fuji, recent, following]))
);
assert_eq!(
items(resolve(&moved(1), &fuji, &c)),
Some(json!([recent, following, fuji]))
);
assert_eq!(
items(resolve(&moved(2), &recent, &c)),
Some(json!([fuji, following, recent]))
);
for (by, row) in [
(-1, &recent),
(1, &following),
(1, &json!({ "id": "foryou" })),
] {
assert_eq!(resolve(&moved(by), row, &c), None, "{by} {row}");
}
// What can't be read: an element with no key, a part that is no
// string, an array that is none.
let scope = json!({ "params": { "camera": 5 }, "prefs": [] });
for template in [
json!({ "$with": [pinned, "id", { "label": "No id" }] }),
json!({ "$with": [pinned, "id", { "id": { "$join": ["camera:", { "$": "params.camera" }] } }] }),
json!({ "$without": [{ "$": "params.camera" }, "id", "recent"] }),
] {
assert_eq!(
resolve(&action("Go", template.clone()), &scope, &c),
None,
"{template}"
);
}
assert_eq!(
resolve(&action("Go", json!({ "$move": [pinned] })), &scope, &c).unwrap()["p"],
json!({ "component": "Action", "message": "$move: [array, key, value]" })
);
}
/// Tabs from the data, each element opening the first of `opens` whose
/// `where` it matches (one with none, any), its params read from it, a
/// `$after` its id's rest; an element none of whose opens resolves (an
/// id without its prefix, or with nothing after it) has no tab.
#[test]
fn tabs_open_each_element_by_its_case() {
let root = json!({ "method": "a.b.getFeed",
"params": { "feed": "at://did:web:a/a.b.generator/camera", "camera": "Fuji X100V" } });
let c = ctx(&root, &[]);
let feed = |rkey: &str, param: &str, prefix: &str| {
json!({ "query": "a.b.getFeed", "params": { "feed": format!("at://did:web:a/a.b.generator/{rkey}"),
param: { "$after": [{ "$": "id" }, prefix] } } })
};
let mut location = feed("location", "location", "location:");
location["params"]["name"] = json!({ "$": "label" });
let tabs = |after: Value| {
json!({ "component": "Tabs", "props": { "from": { "$": "pinned" }, "label": "label", "style": "strip",
"opens": [
{ "where": { "type": { "$is": "camera" } }, "open": feed("camera", "camera", "camera:") },
{ "where": { "type": { "$is": "location" } }, "open": location },
{ "where": { "type": { "$is": "feed" } }, "open": { "query": "a.b.getFeed",
"params": { "feed": { "$atUri": ["did:web:a", "a.b.generator", { "$": "id" }] } } } },
{ "open": { "query": "a.b.getFeed", "params": { "feed": "at://did:web:a/a.b.generator/hashtag",
"tag": after } } },
] } })
};
let scope = json!({ "pinned": [
{ "id": "recent", "label": "Recent", "type": "feed" },
{ "id": "camera:Fuji X100V", "label": "Fuji X100V", "type": "camera" },
{ "id": "location:8a2a1072b59ffff", "label": "Brooklyn", "type": "location" },
{ "id": "hashtag:film", "label": "film", "type": "hashtag" },
{ "id": "camera:", "label": "Nothing after", "type": "camera" },
{ "id": "Fuji", "label": "No prefix", "type": "camera" },
{ "id": "group:x", "label": "Group", "type": "group" },
] });
let tree = resolve(
&tabs(json!({ "$after": [{ "$": "id" }, "hashtag:"] })),
&scope,
&c,
)
.unwrap();
check::checked(&tree);
let drawn: Vec<(&Value, &Value)> = tree["p"]["items"]
.as_array()
.unwrap()
.iter()
.map(|t| (&t["label"], &t["selected"]))
.collect();
assert_eq!(
drawn,
[
(&json!("Recent"), &json!(false)),
(&json!("Fuji X100V"), &json!(true)),
(&json!("Brooklyn"), &json!(false)),
(&json!("film"), &json!(false)),
]
);
assert_eq!(
tree["p"]["items"][2]["open"]["call"]["args"]["params"],
json!({ "feed": "at://did:web:a/a.b.generator/location", "location": "8a2a1072b59ffff", "name": "Brooklyn" })
);
assert_eq!(
tree["p"]["items"][3]["open"]["call"]["args"]["params"]["tag"],
"film"
);
assert_eq!(
resolve(&tabs(json!({ "$after": ["x"] })), &scope, &c).unwrap()["p"],
json!({ "component": "Tabs", "message": "$after: [value, prefix]" })
);
}
/// A choice says which option is chosen now: the data's where it is an
/// option's, else its default, else none; its call left with `$on` for
/// the client; none in an untrusted view.
#[test]
fn a_choice_says_which_is_chosen_and_what_a_choice_sends() {
let root = json!({});
let mut c = ctx(&root, &[]);
let options = json!([{ "label": "System", "value": "system" }, { "label": "Light", "value": "light" },
{ "label": "Dark", "value": "dark" }]);
let choice = |default: Value| {
let mut props = json!({ "label": "Theme", "about": "How Grain looks", "options": options,
"on": { "$": "prefs.@themePref.theme" },
"call": { "method": "a.b.setPreference", "service": "did:web:a.example#svc",
"input": { "preference": { "$type": "a.b.defs#themePref", "theme": { "$on": true } } } } });
if !default.is_null() {
props["default"] = default;
}
json!({ "component": "Choice", "props": props })
};
let theme = |t: &str| json!({ "prefs": [{ "$type": "a.b.defs#themePref", "theme": t }] });
let tree = resolve(&choice(json!("system")), &theme("dark"), &c).unwrap();
check::checked(&tree);
assert_eq!(
(&tree["p"]["on"], &tree["p"]["about"], &tree["p"]["options"]),
(&json!("dark"), &json!("How Grain looks"), &options)
);
assert_eq!(
tree["p"]["call"]["input"]["preference"]["theme"],
json!({ "$on": true })
);
// Never set, or none of its options: its default; with none, nothing chosen.
for scope in [json!({ "prefs": [] }), theme("sepia")] {
let tree = resolve(&choice(json!("system")), &scope, &c).unwrap();
assert_eq!(tree["p"]["on"], "system");
}
let tree = resolve(&choice(Value::Null), &json!({ "prefs": [] }), &c).unwrap();
check::checked(&tree);
assert_eq!(tree["p"].get("on"), None);
c.trusted = false;
assert_eq!(resolve(&choice(json!("system")), &theme("dark"), &c), None);
}
/// A profile's ⋯: Block asked first and red, Report a form that calls
/// the moderation service; a menu of nothing is not drawn.
#[test]
fn a_menu_holds_its_rows_a_block_asks_first_and_a_report_calls() {
let root = json!({});
let c = ctx(&root, &[]);
let block = json!({ "component": "Action", "props": { "label": "Block", "tone": "danger",
"confirm": { "$": "ask" }, "create": { "collection": "app.test.block", "record": { "subject": { "$": "did" } } } } });
let report = json!({ "component": "Compose", "props": { "label": "Report", "fields": [],
"call": { "method": "com.example.createReport", "service": "did:web:a.example#svc",
"input": { "reasonType": "other", "subject": { "did": { "$": "did" } } } } } });
let menu = json!({ "component": "Menu", "children": [block, report] });
let scope = json!({ "did": "did:plc:a", "ask": "Block @a?" });
let tree = resolve(&menu, &scope, &c).unwrap();
check::checked(&tree);
assert_eq!(tree["p"]["label"], "More");
let (b, r) = (&tree["k"][0]["p"], &tree["k"][1]["p"]);
assert_eq!(
(&b["confirm"], &b["tone"]),
(&json!("Block @a?"), &json!("danger"))
);
assert_eq!(r["call"]["input"]["subject"]["did"], "did:plc:a");
assert_eq!(r["writes"], json!([]));
let empty = json!({ "component": "Menu", "props": { "label": "More" }, "children": [] });
assert_eq!(resolve(&empty, &scope, &c), None);
}
/// An Action's look: a button of its own, or a row as a List's rows
/// are (Settings' Delete account); any other word is dropped.
#[test]
fn an_action_is_drawn_as_a_button_or_a_row() {
let root = json!({});
let c = ctx(&root, &[]);
let action = |style: &str| {
json!({ "component": "Action", "props": { "label": "Delete account", "tone": "danger", "style": style,
"create": { "collection": "app.test.thing", "record": { "a": 1 } } } })
};
for style in ["button", "row"] {
let tree = resolve(&action(style), &json!({}), &c).unwrap();
check::checked(&tree);
assert_eq!(tree["p"]["style"], style);
}
let other = resolve(&action("pill"), &json!({}), &c).unwrap();
assert!(other["p"].get("style").is_none());
}
/// A gallery's ⋯: Delete on one's own, its rkey read from its uri, the
/// screen left once done; Report on another's.
#[test]
fn a_menu_gives_the_rows_its_stacks_keep() {
let root = json!({});
let mut c = ctx(&root, &[]);
c.me = Some("did:plc:me");
let delete = json!({ "component": "Action", "props": { "label": "Delete", "tone": "danger", "leave": true,
"call": { "method": "com.example.deleteGallery", "service": "did:web:a.example#svc",
"input": { "rkey": { "$rkey": "uri" } } } } });
let report = json!({ "component": "Action", "props": { "label": "Report", "reload": true,
"create": { "collection": "app.test.report", "record": { "subject": { "$": "uri" } } } } });
let menu = json!({ "component": "Menu", "children": [
{ "component": "Stack", "props": { "mine": "did" }, "children": [delete] },
{ "component": "Stack", "props": { "others": "did" }, "children": [report] }] });
let mine =
json!({ "did": "did:plc:me", "uri": "at://did:plc:me/com.example.gallery/3abc" });
let tree = resolve(&menu, &mine, &c).unwrap();
check::checked(&tree);
let rows: Vec<&Value> = tree["k"]
.as_array()
.unwrap()
.iter()
.map(|r| &r["p"]["label"])
.collect();
assert_eq!(rows, [&json!("Delete")]);
assert_eq!(tree["k"][0]["p"]["leave"], true);
assert_eq!(
tree["k"][0]["p"]["call"]["input"],
json!({ "rkey": "3abc" })
);
let theirs =
json!({ "did": "did:plc:else", "uri": "at://did:plc:else/com.example.gallery/3abc" });
let tree = resolve(&menu, &theirs, &c).unwrap();
assert_eq!(tree["k"][0]["p"]["label"], "Report");
assert_eq!(tree["k"][0]["p"]["reload"], true);
assert_eq!(tree["k"].as_array().unwrap().len(), 1);
// A uri that is no record's has no rkey: the view's error, where the Delete was.
let odd = json!({ "did": "did:plc:me", "uri": "at://did:plc:me" });
let tree = resolve(&menu, &odd, &c).unwrap();
assert_eq!(tree["k"][0]["p"]["message"], "record: not usable");
}
/// Grain's profile ⋯: Share profile and Copy handle, then on someone
/// else's Mute or Unmute (each in a Stack of its own, in the Stack of
/// someone else's), Block and Report, every row the Menu's own however
/// deep its Stack, so a kit drawing a menu's rows alone (iOS's, Android's)
/// has them all; on one's own the first two. The rows for someone not
/// muted are the kits' fixture (`ui-menu.json`), as the server gives them.
#[test]
fn grains_profile_menu_gives_its_rows_through_every_stack() {
let doc: Value =
serde_json::from_str(include_str!("../testdata/grain/apps/views/grain-app.json"))
.unwrap();
let menu = &doc["page"]["layout"]["children"][1]["children"][1];
assert_eq!(menu["component"], "Menu");
let root = json!({});
let mut c = ctx(&root, &[]);
c.me = Some("did:plc:me");
let scope = |did: &str, muted: bool| {
json!({ "actor": { "did": did, "handle": "alice.test" },
"joins": { "profile": { "viewer": { "muted": muted } } } })
};
let labels = |tree: &Value| -> Vec<String> {
let rows = tree["k"].as_array().unwrap();
rows.iter()
.map(|r| {
format!(
"{} {}",
r["c"].as_str().unwrap(),
r["p"]["label"].as_str().unwrap_or_default()
)
})
.collect()
};
let theirs = resolve(menu, &scope("did:plc:alice", false), &c).unwrap();
check::checked(&theirs);
assert_eq!(
labels(&theirs),
[
"Link Share profile",
"Link Copy handle",
"Action Mute",
"Action Block",
"Compose Report"
]
);
let fixture: Value = serde_json::from_str(include_str!(
"../../../../ios/HUDKit/Tests/HUDKitTests/Fixtures/ui-menu.json"
))
.unwrap();
assert_eq!(
theirs, fixture,
"the kits' fixture is the menu as resolved here"
);
let muted = resolve(menu, &scope("did:plc:alice", true), &c).unwrap();
assert_eq!(labels(&muted)[2], "Action Unmute");
let mine = resolve(menu, &scope("did:plc:me", false), &c).unwrap();
assert_eq!(labels(&mine), ["Link Share profile", "Link Copy handle"]);
}
#[test]
fn a_composer_with_no_icon_or_about_says_neither() {
let root = json!({});
let c = ctx(&root, &[]);
let layout = json!({ "component": "Compose", "props": { "fields": [], "writes": [] } });
let tree = resolve(&layout, &json!({}), &c).unwrap();
check::checked(&tree);
let p = &tree["p"];
assert_eq!(
(&p["label"], &p["send"]),
(&json!("Write"), &json!("Write"))
);
assert!(p.get("icon").is_none() && p.get("about").is_none() && p.get("style").is_none());
// A profile's New gallery: a button of its own.
let button = json!({ "component": "Compose", "props": { "fields": [], "writes": [], "style": "button" } });
let tree = resolve(&button, &json!({}), &c).unwrap();
check::checked(&tree);
assert_eq!(tree["p"]["style"], "button");
}
/// A Compose drawn as a field holds its prompt: its first text or line
/// field's placeholder, else its label; signIn is its words signed out.
/// One `for` another is that one (its form, key and words but its own
/// label, style and signIn), found in its scope: through a Row or a
/// Menu, the first of the label; never one of a List's items, nor one
/// that is `for` another; naming none, it draws nothing.
#[test]
fn a_compose_for_another_opens_its_form_as_a_field() {
let root = json!({});
let c = ctx(&root, &[]);
let field = |fields: Value| {
let layout = json!({ "component": "Compose", "props": { "label": "Comment", "fields": fields, "writes": [], "style": "field", "signIn": "Sign in to comment" } });
let tree = resolve(&layout, &json!({}), &c).unwrap();
check::checked(&tree);
tree["p"].clone()
};
let p = field(json!([
{ "name": "l", "kind": "langs", "max": 1 },
{ "name": "t", "kind": "text", "max": 300, "placeholder": "Add a comment" }
]));
assert_eq!(
(&p["style"], &p["prompt"], &p["signIn"]),
(
&json!("field"),
&json!("Add a comment"),
&json!("Sign in to comment")
)
);
assert_eq!(
field(json!([{ "name": "t", "kind": "line", "max": 30 }]))["prompt"],
"Comment"
);
let comment = |label: &str, extra: Value| {
let mut props = json!({ "label": label, "icon": "comment", "style": "button", "signIn": "theirs", "send": "Send",
"given": { "subject": { "$": "uri" } },
"fields": [{ "name": "text", "kind": "text", "max": 300, "placeholder": "Add a comment" }],
"writes": [{ "collection": "a.b.c", "record": { "subject": { "$value": "subject" }, "text": { "$value": "text" } } }] });
props
.as_object_mut()
.unwrap()
.extend(extra.as_object().unwrap().clone());
json!({ "component": "Compose", "props": props })
};
let prompt = |label: &str, extra: Value| {
let mut props = json!({ "for": label, "label": "Add a comment…" });
props
.as_object_mut()
.unwrap()
.extend(extra.as_object().unwrap().clone());
json!({ "component": "Compose", "props": props })
};
let layout = json!({ "component": "Stack", "children": [
{ "component": "Row", "children": [comment("Comment", json!({})), comment("Comment", json!({ "send": "Other" }))] },
{ "component": "Menu", "children": [comment("Report", json!({}))] },
prompt("Comment", json!({ "style": "field", "signIn": "Sign in to comment" })),
prompt("Report", json!({})),
prompt("Nothing", json!({})),
prompt("Item", json!({})),
prompt("Add a comment…", json!({})),
{ "component": "List", "props": { "items": { "$": "items" } },
"children": [comment("Item", json!({ "given": {} })), prompt("Item", json!({ "style": "field" }))] }
] });
let tree = resolve(&layout, &json!({ "uri": "at://x", "items": [{}] }), &c).unwrap();
check::checked(&tree);
let k = tree["k"].as_array().unwrap();
let icon = &k[0]["k"][0]["p"];
let drawn = &k[2]["p"];
assert_eq!(
(
&drawn["key"],
&drawn["send"],
&drawn["given"],
&drawn["label"]
),
(
&icon["key"],
&json!("Send"),
&json!({ "subject": "at://x" }),
&json!("Comment")
)
);
assert_eq!(
(&drawn["style"], &drawn["prompt"], &drawn["signIn"]),
(
&json!("field"),
&json!("Add a comment…"),
&json!("Sign in to comment")
)
);
// Report, from the Menu, drawn as a button: neither the other's style nor its signIn.
assert_eq!(
(
&k[3]["p"]["label"],
k[3]["p"].get("style"),
k[3]["p"].get("signIn")
),
(&json!("Report"), None, None)
);
// Nothing, the Item of a List's items, and one naming another for: none found.
assert_eq!((k.len(), &k[4]["c"]), (5, &json!("List")));
let item = &k[4]["items"][0]["k"];
assert_eq!(item.as_array().map(Vec::len), Some(2));
assert_eq!(item[1]["p"]["prompt"], "Add a comment…");
}
/// A conversation of no array is an error, of none nothing; its people
/// bound in its scope, one with no name or usable face named by
/// nothing, a sender not among them by none; not a page's where its
/// items are not; its own `empty`; a `from` that is no path, or a
/// `send` that names no service, an error.
#[test]
fn a_conversation_reads_its_people_and_says_what_is_wrong() {
let root = json!({});
let mut c = ctx(&root, &[]);
c.me = Some("did:plc:me");
let messages = |props: Value| {
json!({ "component": "Messages", "props": props,
"children": [{ "component": "Text", "props": { "value": { "$": "text" } } }] })
};
let scope = json!({
"msgs": [
{ "from": "did:plc:a", "text": "hi" },
{ "from": "did:plc:b", "text": "yo" },
],
"people": [{ "did": "did:plc:a", "avatar": { "thumb": "https://cdn.bsky.app/a.jpg" } }],
});
let tree = resolve(
&messages(json!({ "items": { "$": "msgs" }, "from": "from", "people": { "$": "people" }, "empty": "No messages" })),
&scope,
&c,
)
.unwrap();
check::checked(&tree);
assert_eq!(tree["p"], json!({ "empty": "No messages", "group": false }));
let items = tree["items"].as_array().unwrap();
assert_eq!(items[0]["who"], json!({}));
assert!(items[1].get("who").is_none());
assert!(resolve(&messages(json!({ "items": { "$": "none" } })), &scope, &c).is_none());
for (props, message) in [
(json!({ "items": { "$": "people.0" } }), "items: no array"),
(
json!({ "items": { "$": "msgs" }, "from": "a..b" }),
"from: a path within each item",
),
(
json!({ "items": { "$": "msgs" }, "send": { "method": "com.example.send" } }),
"call: names a method and a service",
),
] {
let error = resolve(&messages(props), &scope, &c).unwrap();
check::checked(&error);
assert_eq!(
error["p"],
json!({ "component": "Messages", "message": message })
);
}
}
/// A List's group, as Grain groups favorites and follows: those alike
/// at `by`, of a reason `only` names, less than `hours` from their
/// group's first, drawn as that first with the group; an author twice
/// in one counted once; a reason not named, an item with no time, one
/// too long after, and what is no object each a group of their own.
#[test]
fn a_list_groups_items_alike_and_near_in_time() {
let root = json!({});
let c = ctx(&root, &[]);
let layout = json!({ "component": "List", "props": { "items": { "$": "items" }, "open": false,
"group": { "as": "group", "by": ["reason", "subject"], "time": "at", "hours": 48,
"only": { "reason": ["fav", "follow"] }, "distinct": "who" } },
"children": [{ "component": "Text", "props": { "value": { "$": "who" } } },
{ "component": "Text", "props": { "value": { "$": "group.others" }, "prefix": "and ", "countNoun": ["other", "others"] } }] });
let item = |who: &str, reason: &str, subject: &str, at: &str| json!({ "who": who, "reason": reason, "subject": subject, "at": at });
let scope = json!({ "items": [
item("a", "fav", "g1", "2026-11-16T12:00:00Z"),
item("b", "fav", "g1", "2026-11-16T11:00:00Z"),
item("c", "comment", "g1", "2026-11-16T10:30:00Z"),
item("c", "comment", "g1", "2026-11-16T10:00:00Z"),
item("a", "fav", "g1", "2026-11-16T09:00:00Z"),
item("d", "fav", "g2", "2026-11-16T08:00:00Z"),
item("e", "follow", "", "2026-11-16T07:00:00Z"),
item("f", "follow", "", "2026-11-16T06:00:00Z"),
item("g", "fav", "g1", "2026-11-13T10:00:00Z"),
{ "who": "h", "reason": "fav", "subject": "g1" },
"plain",
] });
let tree = resolve(&layout, &scope, &c).unwrap();
check::checked(&tree);
let rows: Vec<String> = tree["items"]
.as_array()
.unwrap()
.iter()
.map(|i| {
let k = i["k"].as_array().unwrap();
k.iter()
.map(|t| t["p"]["runs"][0]["text"].as_str().unwrap())
.collect::<Vec<_>>()
.join(" ")
})
.collect();
assert_eq!(
rows,
[
"a and 1 other",
"c",
"c",
"d",
"e and 1 other",
"g",
"h",
""
]
);
// The group: its items in order, how many, and how many past the first.
let grouped = groups(&scope["items"]["$"], vec![]);
assert!(grouped.is_empty());
let g = &layout["props"]["group"];
let drawn = groups(g, scope["items"].as_array().unwrap().clone());
assert_eq!(drawn[0]["group"]["count"], 2);
assert_eq!(drawn[0]["group"]["others"], 1);
assert_eq!(drawn[0]["group"]["items"][1]["who"], "b");
assert_eq!(
drawn[1]["group"],
json!({ "count": 1, "items": [scope["items"][2]] })
);
assert_eq!(drawn[7], "plain");
}
/// A number with its noun: the singular after 1, the plural else; a
/// word, or a Text with no countNoun, as it is.
#[test]
fn a_count_takes_its_noun() {
let root = json!({});
let c = ctx(&root, &[]);
let said = |value: Value, noun: Value| {
let layout =
json!({ "component": "Text", "props": { "value": value, "countNoun": noun } });
resolve(&layout, &json!({}), &c).unwrap()["p"]["runs"][0]["text"].clone()
};
let noun = json!(["other", "others"]);
assert_eq!(said(json!(1), noun.clone()), "1 other");
assert_eq!(said(json!(3), noun.clone()), "3 others");
assert_eq!(said(json!("many"), noun), "many");
assert_eq!(said(json!(3), Value::Null), "3");
}
/// A thumb, a notification's gallery: drawn small and square where it
/// has a picture, left out where it has none.
#[test]
fn a_thumb_is_left_out_without_a_picture() {
let root = json!({});
let origins = vec!["https://cdn.example".to_string()];
let mut c = ctx(&root, &origins);
c.thumbnails = vec![(
"https://cdn.example/full/".into(),
"https://cdn.example/small/".into(),
)];
let layout =
json!({ "component": "Image", "props": { "src": { "$": "thumb" }, "size": "thumb" } });
let tree = resolve(
&layout,
&json!({ "thumb": "https://cdn.example/full/a.jpg" }),
&c,
)
.unwrap();
check::checked(&tree);
assert_eq!(tree["p"]["size"], "thumb");
assert_eq!(tree["p"]["src"]["src"], "https://cdn.example/small/a.jpg");
assert_eq!(tree["p"]["ratio"], 1.0);
assert_eq!(resolve(&layout, &json!({}), &c), None);
}
}