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

chadtmiller.com/hud

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

0
0

Bios and feed descriptions mark their links, mentions and tags

Merged chadtmiller.com asked to merge into main from chadtmiller.com/hud:richtext/bios
crates/hud-core/src/ui/layout.rs+32−5
@@ -50,16 +50,19 @@ pub(super) fn header(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
Ok(Some(make("Header", o, vec![])))
}
/// `Profile`: `p: { name?, handle?, open?, description?, avatar, banner }`;
/// `Profile`: `p: { name?, handle?, open?, descriptionRuns?, avatar, banner }`;
/// `handle` without its leading `@`, `open` the account it names (as given),
/// `descriptionRuns` its description with its links, @mentions and #tags
/// found as Bluesky's app finds them (a profile's record has no facets),
/// `avatar` drawn small and `banner` large, each null for none. It always
/// draws.
pub(super) fn profile(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let mut o = Map::new();
for key in ["name", "description"] {
if let Some(s) = words(&p[key], scope)? {
o.insert(key.into(), s.into());
}
if let Some(s) = words(&p["name"], scope)? {
o.insert("name".into(), s.into());
}
if let Some(s) = words(&p["description"], scope)? {
o.insert("descriptionRuns".into(), detected_runs(&s, ctx).into());
}
if let Some(handle) = words(&p["handle"], scope)? {
o.insert(
@@ -161,4 +164,28 @@ mod tests {
"a banner is drawn large"
);
}
#[test]
fn a_profiles_description_marks_its_links_mentions_and_tags() {
let root = json!({});
let c = ctx(&root, &[]);
let p = json!({ "description": { "$": "description" }, "avatar": null, "banner": null });
let scope =
json!({ "description": "building @Grain.social, https://a.example/x. #atproto" });
let drawn = profile(&p, &scope, &c).ok().flatten().unwrap();
check::checked(&drawn);
assert_eq!(
drawn["p"]["descriptionRuns"],
json!([
{ "text": "building " },
{ "text": "@Grain.social", "actor": "grain.social" },
{ "text": ", " },
{ "text": "https://a.example/x", "link": "https://a.example/x" },
{ "text": ". " },
{ "text": "#atproto", "tag": "atproto" },
]),
"a mention opens the account by its handle, as the text names no DID"
);
assert!(drawn["p"].get("description").is_none());
}
}
crates/hud-core/src/ui/mod.rs+60−22
@@ -55,7 +55,8 @@
//! `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` of markdown or gfm: `p: { blocks, clamp? }`; `Document`:
//! - `RichText`: `p: { runs | blocks, clamp?, 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
@@ -558,46 +559,77 @@ fn link_runs(text: &str) -> Vec<Value> {
/// 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.
/// A #tag opens what the tree's app searches for it with (`Ctx::tag_call`).
fn facet_runs(text: &str, facets: Option<&Value>, ctx: &Ctx) -> Vec<Value> {
let bytes = text.as_bytes();
let mut marks: Vec<(usize, usize, &Value)> = facets
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;
(s < e && e <= bytes.len()).then_some((s, e, &f["features"]))
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, features) in marks {
for (s, e, kind) in marks {
if s < at {
continue;
}
if s > at {
runs.push(run(&slice(at, s), None));
}
let part = slice(s, e);
let kind =
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,
});
let mut drawn = run(&part, kind);
let mut drawn = run(&slice(s, e), kind);
if let Some(("tag", t)) = kind
&& let Some(open) = ctx.tag_call(t)
{
@@ -669,10 +701,16 @@ fn rich_text(p: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
let facets = value_or_none(&p["facets"], scope, Value::is_array)?;
o.insert("runs".into(), Value::Array(facet_runs(value, facets, ctx)));
}
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());
}
crates/hud-core/src/catalog.rs+7−3
@@ -403,12 +403,16 @@ pub const COMPONENTS: &[Component] = &[
name: "RichText",
props: &[
req("value", Ty::Text),
lit("format", Ty::OneOf(&["plain", "markdown", "gfm", "facets"])),
lit(
"format",
Ty::OneOf(&["plain", "markdown", "gfm", "facets", "detect"]),
),
p("facets", Ty::Any),
lit("clamp", Ty::Int),
lit("style", Ty::OneOf(&["body", "muted"])),
],
children: false,
notes: "Markdown drawn safely (no HTML but <details> and its <summary>, drawn as a disclosure): markdown is CommonMark, gfm GitHub's (tables, task lists, strikethrough, bare links), as a pull's or a README's; or text with Bluesky richtext facets (links, mentions, tags). clamp is about the most lines shown before \"Show more\", as a README's first 20.",
notes: "Markdown drawn safely (no HTML but <details> and its <summary>, drawn as a disclosure): markdown is CommonMark, gfm GitHub's (tables, task lists, strikethrough, bare links), as a pull's or a README's; or text with Bluesky richtext facets (links, mentions, tags); or detect, text written with none (a profile's description), its links, @mentions and #tags found as Bluesky's app finds them. clamp is about the most lines shown before \"Show more\", as a README's first 20. style muted draws its runs smaller and quieter, as Text's muted: a feed's description under its name.",
},
Component {
name: "Time",
@@ -640,7 +644,7 @@ pub const COMPONENTS: &[Component] = &[
p("description", Ty::Text),
],
children: false,
notes: "An account's profile card.",
notes: "An account's profile card; its description's links, @mentions and #tags are found as Bluesky's app finds them.",
},
Component {
name: "Fields",
crates/hud-core/src/tools.rs+6−2
@@ -2595,9 +2595,13 @@ mod tests {
(
&k[0]["p"]["name"],
&k[0]["p"]["handle"],
&k[0]["p"]["description"]
&k[0]["p"]["descriptionRuns"]
),
(&json!("Meri"), &json!("meri.garden"), &json!("bio"))
(
&json!("Meri"),
&json!("meri.garden"),
&json!([{ "text": "bio" }])
)
);
assert_eq!(
k[0]["p"]["avatar"],
docs/app-pages.md+2−0
@@ -64,6 +64,8 @@ Bluesky's page (`bsky-app`) is a profile as Bluesky's app draws one:
A bundled view's drawing names accounts in links, mentions and who reposted. Such an account opens as its page in that view's app, where the app has one (`describe_app { domain, actor }`). So a name in a Bluesky post opens their Bluesky page, and a name in a Grain gallery opens their Grain page. In an app with no page, or from an inline view, it opens as the account's profile across its apps (`describe_repo`).
Posts and galleries carry their facets, but a bio has none. HUD finds a bio's links, @mentions and #tags as Bluesky's app does, and a mention there opens by the handle it names.
The tree says which app (`_meta.ui.people`), for the mentions its clients open.
A tile's header has the way across. Its @handle opens the account's profile. The profile's apps open their pages. Those apps are the ones a bundled view draws something of, either an app page or a section of the profile.
ios/HUDKit/Sources/HUDKit/Parts/ProfileCard.swift+6−42
@@ -2,15 +2,16 @@ import SwiftUI
/// A resolved tree's `Profile`: a banner, an avatar, its name and handle
/// (which opens the account through `open`, when given), and its
/// description, cut to four lines with a "more" that shows the rest.
/// description (its links and mentions opening as a text's do), cut to
/// four lines with a "more" that shows the rest, kept open by `key`.
struct ProfileCard: View {
let name: String?
let handle: String?
let description: String?
let description: AttributedString?
let key: String
let avatar: Source?
let banner: Source?
let open: (@MainActor () -> Void)?
let memory: Memory
var body: some View {
VStack(alignment: .leading, spacing: 0) {
@@ -41,7 +42,8 @@ struct ProfileCard: View {
}
}
if let description {
ClampedDescription(text: description, key: "profile.more:\(handle ?? description)", memory: memory)
Clamped(text: description, lines: 4, more: "more", key: key)
.font(.subheadline)
}
}
.padding([.horizontal, .bottom], Space.s3)
@@ -50,41 +52,3 @@ struct ProfileCard: View {
.hudCard()
}
}
/// Text cut to four lines, line breaks kept, with a "more" that shows the
/// rest when there is more, remembered so it stays shown when drawn again.
private struct ClampedDescription: View {
let text: String
let key: String
let memory: Memory
@State private var open: Bool?
@State private var full: CGFloat = 0
@State private var clamped: CGFloat = 0
var body: some View {
let shown = open ?? memory.get(key, first: { false })
VStack(alignment: .leading, spacing: Space.s1) {
Text(text)
.font(.subheadline)
.lineLimit(shown ? nil : 4)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
.onGeometryChange(for: CGFloat.self) { $0.size.height } action: { clamped = $0 }
.background(alignment: .topLeading) {
// The whole text, unseen, to tell whether the cut leaves any out.
Text(text)
.font(.subheadline)
.fixedSize(horizontal: false, vertical: true)
.hidden()
.onGeometryChange(for: CGFloat.self) { $0.size.height } action: { full = $0 }
}
if !shown && full > clamped + 1 {
LinkButton(label: "more", font: .subheadline) {
memory.set(key, true)
open = true
}
}
}
}
}
ios/HUDKit/Sources/HUDKit/Support/RichText.swift+6−5
@@ -3,15 +3,16 @@ import SwiftUI
// Text with structure, made safe to draw: the runs the server made of a
// view's text (links to http(s) alone, mentions, tags) as one attributed
// string. A mention's link is `hud-actor:<did>`, a tag's that opens
// string. A mention's link is `hud-actor:<did or handle>`, a tag's that opens
// something (a search for it) `hud-open:<its open>`, which the view
// context routes (`ViewContext.route`).
/// A run of text: plain, or a link, a mention (a DID) or a tag.
/// A run of text: plain, or a link, a mention (its account's DID, or the
/// handle a text with no facets names it by) or a tag.
enum Run: Equatable {
case text(String)
case link(String, url: URL)
case mention(String, did: String)
case mention(String, actor: String)
/// A tag; with `open`, a link that opens it (`ViewContext.openURL`).
case tag(String, tag: String, open: URL? = nil)
}
@@ -28,9 +29,9 @@ enum RichText {
var part = AttributedString(s)
part.link = url
out += part
case .mention(let s, let did):
case .mention(let s, let actor):
var part = AttributedString(s)
part.link = ViewContext.actorURL(did)
part.link = ViewContext.actorURL(actor)
out += part
case .tag(let s, _, let open):
var part = AttributedString(s)
ios/HUDKit/Sources/HUDKit/Tree/ResolvedProfile.swift+6−4
@@ -1,7 +1,7 @@
import SwiftUI
// A resolved tree's `Profile`, read on the server (ui/layout.rs's
// `profile`): `{ name?, handle?, open?, description?, avatar, banner }`,
// `profile`): `{ name?, handle?, open?, descriptionRuns?, avatar, banner }`,
// drawn by `ProfileCard`; its handle opens the account through `onCall`.
struct ResolvedProfile: View {
@@ -9,14 +9,16 @@ struct ResolvedProfile: View {
@Environment(\.viewContext) private var view
var body: some View {
let runs = p["descriptionRuns"]
let words = Resolved.plain(runs)
ProfileCard(
name: p.str("name"),
handle: p.str("handle"),
description: p.str("description"),
description: words.isEmpty ? nil : Resolved.text(runs),
key: "profile.more:\(p.str("handle") ?? words)",
avatar: Resolved.source(p["avatar"]),
banner: Resolved.source(p["banner"]),
open: view.opener(tree: p["open"])?.run,
memory: view.memory
open: view.opener(tree: p["open"])?.run
)
}
}
ios/HUDKit/Sources/HUDKit/Tree/TreeView.swift+5−3
@@ -132,8 +132,10 @@ struct ResolvedNode: View {
if let blocks = p["blocks"]?.array {
ResolvedRichBlocks(blocks: blocks, clamp: Clamped.lines(p["clamp"]))
} else {
let muted = p["style"]?.string == "muted"
TextBody(text: Resolved.text(p["runs"]), clamp: Clamped.lines(p["clamp"]), more: "Show more", key: "rich:\(Resolved.plain(p["runs"]))")
.font(.subheadline)
.font(muted ? TextBody.font("muted") : .subheadline)
.foregroundStyle(muted ? .secondary : .primary)
}
case "Time":
TimeText(value: p["value"]?.string ?? "")
@@ -289,8 +291,8 @@ enum Resolved {
let shown: Run
if let url = run["link"]?.string.flatMap(Format.httpURL) {
shown = .link(text, url: url)
} else if let did = run["actor"]?.string {
shown = .mention(text, did: did)
} else if let actor = run["actor"]?.string {
shown = .mention(text, actor: actor)
} else if let tag = run["tag"]?.string {
shown = .tag(text, tag: tag, open: run["open"].flatMap(ViewContext.openURL))
} else {
schemas/place.hud.ui.json+6−4
@@ -76,7 +76,7 @@
"properties": {
"text": { "type": "string" },
"link": { "type": "string", "description": "The http or https page it opens." },
"actor": { "type": "string", "description": "The DID of the account it opens." },
"actor": { "type": "string", "description": "The account it opens: its DID, or the handle a text written with no facets names it by (a profile's description)." },
"tag": { "type": "string", "description": "The tag it names." },
"open": { "type": "ref", "ref": "#open", "description": "With tag: a search for it in the app the tree is in, where that app has one." },
"bold": { "type": "boolean" },
@@ -159,11 +159,12 @@
},
"richTextProps": {
"type": "object",
"description": "Text with its facets (runs), or markdown or GFM read into blocks (blocks).",
"description": "Text with its facets, or with its links, mentions and tags found (runs); or markdown or GFM read into blocks (blocks).",
"properties": {
"runs": { "type": "array", "items": { "type": "ref", "ref": "#run" } },
"blocks": { "type": "array", "items": { "type": "ref", "ref": "#block" } },
"clamp": { "type": "integer", "minimum": 1, "description": "About the most lines shown before more." }
"clamp": { "type": "integer", "minimum": 1, "description": "About the most lines shown before more." },
"style": { "type": "string", "maxLength": 16, "knownValues": ["muted"], "description": "muted: runs smaller and quieter, as Text's; absent: body text." }
}
},
"timeProps": {
@@ -453,7 +454,8 @@
"name": { "type": "string" },
"handle": { "type": "string", "description": "Without its leading @." },
"open": { "type": "ref", "ref": "#open", "description": "The account its handle names." },
"description": { "type": "string" },
"description": { "type": "string", "description": "No longer sent: descriptionRuns." },
"descriptionRuns": { "type": "array", "items": { "type": "ref", "ref": "#run" }, "description": "Its description, its links, @mentions and #tags found as Bluesky's app finds them." },
"avatar": { "type": "ref", "ref": "#picture", "description": "Drawn small." },
"banner": { "type": "ref", "ref": "#picture", "description": "Drawn large." }
}
views/bsky-app.json+5−1
views/bsky-feed-generators.json+1−1
views/bsky-profile.json+1−1
views/grain-app.json+1−1
web/renderer/src/tree/context.ts+2−2
web/renderer/src/tree/Profile.svelte+7−4
web/renderer/src/tree/RichText.svelte+20−6
web/renderer/src/tree/types.ts+3−3
web/renderer/src/view/ProfileView.svelte+10−4
web/renderer/src/ClampedText.svelte+13−4
web/renderer/src/RichRuns.svelte+3−3
web/renderer/src/richtext.ts+3−2