~ 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

Markdown's <details> opens to what it hides under its summary

Merged chadtmiller.com asked to merge into main from chadtmiller.com/hud:markdown/details
crates/hud-core/src/ui/document.rs+266−20
@@ -3,9 +3,9 @@
//! links and footnotes), and a long-form document's content for `Document`
//! (Leaflet's pages of blocks, markpub's markdown, else its plain text as
//! paragraphs, else the content itself as JSON), as the web renderer's
//! Markdown and document/ components read them. Markdown's HTML stays text,
//! its pictures show their alt text and load nothing, and its links open
//! only pages (http or https).
//! Markdown and document/ components read them. Markdown's HTML stays text
//! but for `<details>` and its `<summary>`, its pictures show their alt text
//! and load nothing, and its links open only pages (http or https).
//!
//! A block is `{ kind, … }`, any of them with `align` (center, right or
//! justify, a Leaflet block's own):
@@ -18,6 +18,8 @@
//! - `code { text, lang? }`, `quote { blocks }`, `rule`, `table { head:
//! [runs], rows: [[runs]] }`, `footnotes { items: [{ blocks }] }`, in the
//! order they are first referred to (a reference reads `[n]`).
//! - `details { runs, blocks, expanded? }`: markdown's `<details>`, `runs`
//! its summary, `blocks` what it hides, `expanded` where it starts open.
//! - `image { src, alt, ratio }`, `gallery { images: [{ src, alt, ratio }] }`.
//! - `card { kicker, title, description?, image, open? }`, a link to
//! something outside the text; `button { label, open? }`.
@@ -109,6 +111,14 @@ enum Open {
label: String,
blocks: Vec<Value>,
},
/// A `<details>`: whether it starts open, its summary, whether the
/// summary is still being read, and what it hides.
Details {
expanded: bool,
summary: Vec<Value>,
in_summary: bool,
blocks: Vec<Value>,
},
}
#[derive(Default)]
@@ -298,7 +308,7 @@ impl Reader {
self.push(json!({ "kind": "heading", "level": level as u8, "runs": runs }));
}
TagEnd::BlockQuote(_) => {
self.settle();
self.close_details();
if let Some(Open::Quote(blocks)) = self.open.pop() {
self.push(json!({ "kind": "quote", "blocks": blocks }));
}
@@ -316,17 +326,8 @@ impl Reader {
}
}
TagEnd::HtmlBlock => {
// Drawn as the text it is, its lines run together as a paragraph's.
if let Some(html) = self.html.take() {
let text = html
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.collect::<Vec<_>>()
.join(" ");
if !text.is_empty() {
self.push(paragraph(vec![run(&text, None)]));
}
self.html_block(&html);
}
}
TagEnd::List(_) => {
@@ -348,7 +349,7 @@ impl Reader {
}
}
TagEnd::Item => {
self.settle();
self.close_details();
if let Some(Open::Item { check, blocks }) = self.open.pop() {
let mut item = json!({ "blocks": blocks });
if let Some(c) = check {
@@ -360,7 +361,7 @@ impl Reader {
}
}
TagEnd::FootnoteDefinition => {
self.settle();
self.close_details();
if let Some(Open::Note { label, blocks }) = self.open.pop() {
self.notes.push((label, blocks));
}
@@ -497,16 +498,121 @@ impl Reader {
std::mem::take(&mut self.runs)
}
/// A block into what holds it.
/// A block into what holds it; a paragraph or heading in a summary
/// being read, its runs.
fn push(&mut self, b: Value) {
match self.open.last_mut() {
Some(Open::Quote(blocks) | Open::Item { blocks, .. } | Open::Note { blocks, .. }) => {
blocks.push(b);
Some(Open::Details {
in_summary: true,
summary,
..
}) => {
if let Some(Value::Array(runs)) = b.get("runs") {
if !summary.is_empty() {
summary.push(run(" ", None));
}
summary.extend(runs.iter().cloned());
}
}
crates/hud-core/src/ui/document.rslines 505 to 516
review.knotless.dev

Inside a summary, a block with no runs (a list, a code block, a quote, a table between <summary> and </summary>) is dropped without a trace, along with everything in it. That's rare in practice, but if you want nothing lost, fall back to its text, or push it into blocks. Optional.

Some(
Open::Quote(blocks)
| Open::Item { blocks, .. }
| Open::Note { blocks, .. }
| Open::Details { blocks, .. },
) => blocks.push(b),
Some(Open::List { .. }) | None => self.blocks.push(b),
}
}
/// An HTML block: `<details>`, `<summary>` and their ends open and
/// close a details block, whose summary may hold markdown read before
/// `</summary>`; the rest is drawn as the text it is.
fn html_block(&mut self, html: &str) {
let mut rest = html;
while let Some((at, len, tag)) = details_tag(rest) {
self.loose_html(&rest[..at]);
rest = &rest[at + len..];
match tag {
DetailsTag::Open { expanded } => {
self.settle();
self.open.push(Open::Details {
expanded,
summary: Vec::new(),
in_summary: false,
blocks: Vec::new(),
});
}
DetailsTag::Summary | DetailsTag::EndSummary => {
self.settle();
if let Some(Open::Details { in_summary, .. }) = self.open.last_mut() {
*in_summary = matches!(tag, DetailsTag::Summary);
}
}
DetailsTag::Close => {
self.close_detail();
}
}
}
self.loose_html(rest);
}
/// HTML outside the tags a details block is made of: in a summary its
/// text, else drawn as it is, its lines run together as a paragraph's.
fn loose_html(&mut self, html: &str) {
if let Some(Open::Details {
in_summary: true,
summary,
..
}) = self.open.last_mut()
{
let text = html_text(html);
if !text.is_empty() {
if !summary.is_empty() {
summary.push(run(" ", None));
}
summary.push(run(&text, None));
}
return;
}
let text = html
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.collect::<Vec<_>>()
.join(" ");
if !text.is_empty() {
self.push(paragraph(vec![run(&text, None)]));
}
}
/// The details block open innermost closed into what holds it, if it
/// is innermost: one markdown opened inside it never closes it.
fn close_detail(&mut self) -> bool {
self.settle();
if !matches!(self.open.last(), Some(Open::Details { .. })) {
return false;
}
if let Some(Open::Details {
expanded,
summary,
blocks,
..
}) = self.open.pop()
{
let mut b = json!({ "kind": "details", "runs": summary, "blocks": blocks });
if expanded {
b["expanded"] = true.into();
}
self.push(b);
}
true
}
/// Details blocks left open where what holds them ends, closed.
fn close_details(&mut self) {
while self.close_detail() {}
}
/// Text left outside a paragraph (a tight list item's) made one.
fn settle(&mut self) {
let runs = self.take_runs();
@@ -516,7 +622,7 @@ impl Reader {
}
fn finish(mut self) -> Vec<Value> {
self.settle();
self.close_details();
let mut items = Vec::new();
for label in std::mem::take(&mut self.refs) {
if let Some(i) = self
@@ -536,6 +642,118 @@ impl Reader {
}
}
/// A tag a details block is made of.
enum DetailsTag {
Open { expanded: bool },
Close,
Summary,
EndSummary,
}
/// The first `<details>`, `<summary>` or end of one in HTML, any case: where
/// it starts, how long it is, and which; `<details open>` starts expanded.
fn details_tag(html: &str) -> Option<(usize, usize, DetailsTag)> {
let mut from = 0;
while let Some(at) = html[from..].find('<').map(|i| from + i) {
from = at + 1;
let (end, named) = match html[from..].strip_prefix('/') {
Some(t) => (true, t),
None => (false, &html[from..]),
};
for name in ["details", "summary"] {
let Some(after) = named
.get(..name.len())
.filter(|n| n.eq_ignore_ascii_case(name))
.map(|_| &named[name.len()..])
else {
continue;
};
let Some(gt) = after.find('>') else { continue };
let attrs = &after[..gt];
// `<detailsx>` is no details; an end tag has no attributes.
let named_alone = if end {
attrs.trim().is_empty()
} else {
attrs.is_empty() || attrs.starts_with(char::is_whitespace)
};
if !named_alone {
continue;
}
let len = html.len() - after.len() + gt + 1 - at;
let tag = match (name, end) {
("details", false) => DetailsTag::Open {
expanded: attrs.split_whitespace().any(|a| {
let key = a.split('=').next().unwrap_or(a);
key.eq_ignore_ascii_case("open")
}),
},
("details", true) => DetailsTag::Close,
(_, false) => DetailsTag::Summary,
(_, true) => DetailsTag::EndSummary,
};
return Some((at, len, tag));
}
}
None
}
/// HTML's text: its tags left out, its whitespace one space, and its
/// character references (`&amp;`, `&#183;`, a few others by name) read.
fn html_text(html: &str) -> String {
let mut text = String::with_capacity(html.len());
let mut chars = html.chars().peekable();
while let Some(c) = chars.next() {
if c == '<'
&& chars
.peek()
.is_some_and(|n| n.is_ascii_alphabetic() || *n == '/')
{
chars.by_ref().find(|&c| c == '>');
} else {
text.push(c);
}
}
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
let mut out = String::with_capacity(text.len());
let mut rest = text.as_str();
while let Some(i) = rest.find('&') {
out.push_str(&rest[..i]);
rest = &rest[i..];
let read = rest[1..].find(';').filter(|&e| e <= 8).and_then(|e| {
let c = match &rest[1..=e] {
"amp" => '&',
"lt" => '<',
"gt" => '>',
"quot" => '"',
"apos" => '\'',
"nbsp" => ' ',
"middot" => '·',
n => {
let n = n.strip_prefix('#')?;
let code = match n.strip_prefix(['x', 'X']) {
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
None => n.parse().ok()?,
};
char::from_u32(code).filter(|&c| c != '\0')?
}
};
Some((c, e + 2))
});
match read {
Some((c, len)) => {
out.push(c);
rest = &rest[len..];
}
None => {
out.push('&');
rest = &rest[1..];
}
}
}
out.push_str(rest);
out
}
/// Plain text cut at the links GFM finds bare in it: an http(s) URL, or
/// one starting `www.` (an http page), after the start, a space or one of
/// `(*_~`, up to a space or a `<`; trailing `?!.,:*_~'"` and a `)` it never
@@ -1082,6 +1300,34 @@ mod tests {
assert_eq!(blocks[1]["items"][1]["blocks"][0]["runs"][0]["text"], "A");
}
#[test]
fn details_hide_their_markdown_under_their_summary() {
let source = "<details>\n<summary>Claude Opus 5.5 &middot; <b>high</b></summary>\n\n**a**\n\n- b\n\n</details>\n\n<DETAILS open><summary>\n\n*one*\n\n</summary>\nloose <i>html</i>\n</details>\n\n> <details><summary>q</summary>\n>\n> c\n\nafter";
let blocks = markdown(source, true);
checked_markdown(&blocks);
assert_eq!(
Value::Array(blocks),
json!([
{ "kind": "details", "runs": [{ "text": "Claude Opus 5.5 · high" }], "blocks": [
{ "kind": "paragraph", "runs": [{ "text": "a", "bold": true }] },
{ "kind": "list", "ordered": false, "tight": true, "items": [
{ "blocks": [{ "kind": "paragraph", "runs": [{ "text": "b" }] }] },
] },
] },
{ "kind": "details", "expanded": true, "runs": [{ "text": "one", "italic": true }], "blocks": [
{ "kind": "paragraph", "runs": [{ "text": "loose <i>html</i>" }] },
] },
// One left open closes where its quote ends.
{ "kind": "quote", "blocks": [
{ "kind": "details", "runs": [{ "text": "q" }], "blocks": [
{ "kind": "paragraph", "runs": [{ "text": "c" }] },
] },
] },
{ "kind": "paragraph", "runs": [{ "text": "after" }] },
])
);
}
#[test]
fn leaflet_facets_overlap_and_links_open_pages_or_accounts_alone() {
let text = "héllo world";
crates/hud-core/src/catalog.rs+1−1
@@ -408,7 +408,7 @@ pub const COMPONENTS: &[Component] = &[
lit("clamp", Ty::Int),
],
children: false,
notes: "Markdown drawn safely (no HTML): 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). clamp is about the most lines shown before \"Show more\", as a README's first 20.",
},
Component {
name: "Time",
ios/HUDKit/Sources/HUDKit/Tree/ResolvedBlocks.swift+46−1
@@ -9,7 +9,8 @@ import UIKit
// Paragraphs and headings are their runs in their formatting; lists are
// bulleted, numbered or checked, nested; code is monospaced, scrolling
// sideways, under its language; quotes are set off by a bar; tables scroll
// sideways in a grid; footnotes follow a rule. A Leaflet picture or gallery
// sideways in a grid; footnotes follow a rule; details show their summary
// and open, as a person left them, to what they hide. A Leaflet picture or gallery
// loads from the sources the server gave, a card or button opens its call
// or page, and a Bluesky post is drawn as the quote the server resolved it
// to, else its fallback.
@@ -158,6 +159,8 @@ struct ResolvedBlock: View {
TableBlock(head: block["head"]?.array ?? [], rows: block["rows"]?.array ?? [])
case "footnotes":
Footnotes(items: block["items"]?.array ?? [], look: look)
case "details":
DetailsBlock(block: block, look: look)
case "image":
EmbedFrame(ratio: block["ratio"]?.number ?? 4 / 3, maxHeight: 560) {
Picture(source: Resolved.source(block["src"]), alt: block["alt"]?.string ?? "", fit: .fit, side: 1000)
@@ -342,6 +345,48 @@ private struct Footnotes: View {
}
}
/// Markdown's `<details>`: its summary beside a chevron, a tap showing or
/// hiding its blocks; opened or closed, it stays so when drawn again.
private struct DetailsBlock: View {
let block: JSON
let look: BlockLook
@Environment(\.viewContext) private var view
@State private var open = false
private var key: String { "details:\(block.hashValue)" }
var body: some View {
let runs = block["runs"]?.array ?? []
VStack(alignment: .leading, spacing: Space.s2) {
Button {
open.toggle()
view.memory.set(key, open)
} label: {
HStack(alignment: .firstTextBaseline, spacing: Space.s2) {
Image(systemName: "chevron.right")
.font(.caption.weight(.semibold))
.foregroundStyle(.secondary)
.rotationEffect(.degrees(open ? 90 : 0))
.accessibilityHidden(true)
if runs.isEmpty {
Text("Details")
} else {
Text(Resolved.text(block["runs"]))
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(.rect)
}
.buttonStyle(.plain)
.accessibilityValue(open ? "Expanded" : "Collapsed")
if open {
ResolvedBlocks(blocks: block["blocks"]?.array ?? [], look: look)
}
}
.onAppear { open = view.memory.get(key) { block["expanded"] == .bool(true) } }
}
}
/// A link to something outside the text, as a card: its preview picture
/// across the top, then what it is (a site's host, "Bluesky post"), its
/// title and description. A tap opens it; with nowhere to go it only shows.
schemas/place.hud.ui.json+3−2
@@ -511,17 +511,18 @@
},
"block": {
"type": "object",
"description": "A block of text with structure, by kind: paragraph { runs }; heading { level, runs }; list { ordered, start?, tight?, items }; code { text, lang? }; quote { blocks }; rule; table { head, rows }; footnotes { items }, in the order they are first referred to; image { src, alt, ratio }; gallery { images }; card { kicker, title, description?, image, open? }; button { label, open? }; bskyPost { uri, quote?, fallback }; gap; unsupported { text }; json { value }. An image's ratio, width over height, is a number with a fraction, and a json block's value anything at all, so neither is declared here.",
"description": "A block of text with structure, by kind: paragraph { runs }; heading { level, runs }; list { ordered, start?, tight?, items }; code { text, lang? }; quote { blocks }; rule; table { head, rows }; footnotes { items }, in the order they are first referred to; details { runs, blocks, expanded? }, markdown's <details>, its summary's runs and the blocks it hides; image { src, alt, ratio }; gallery { images }; card { kicker, title, description?, image, open? }; button { label, open? }; bskyPost { uri, quote?, fallback }; gap; unsupported { text }; json { value }. An image's ratio, width over height, is a number with a fraction, and a json block's value anything at all, so neither is declared here.",
"required": ["kind"],
"nullable": ["src", "image"],
"properties": {
"kind": { "type": "string", "knownValues": ["paragraph", "heading", "list", "code", "quote", "rule", "table", "footnotes", "image", "gallery", "card", "button", "bskyPost", "gap", "unsupported", "json"] },
"kind": { "type": "string", "knownValues": ["paragraph", "heading", "list", "code", "quote", "rule", "table", "footnotes", "details", "image", "gallery", "card", "button", "bskyPost", "gap", "unsupported", "json"] },
"align": { "type": "string", "knownValues": ["center", "right", "justify"], "description": "A Leaflet block's own alignment." },
"runs": { "type": "array", "items": { "type": "ref", "ref": "#run" } },
"level": { "type": "integer", "minimum": 1, "maximum": 6 },
"ordered": { "type": "boolean" },
"start": { "type": "integer", "minimum": 0, "description": "Where an ordered list starts, where that is not 1." },
"tight": { "type": "boolean", "description": "Its items' paragraphs are drawn without their space." },
"expanded": { "type": "boolean", "description": "Details' own: it starts open." },
"items": { "type": "array", "items": { "type": "ref", "ref": "#blockItem" }, "description": "A list's items, or the footnotes." },
"text": { "type": "string" },
"lang": { "type": "string", "description": "The language its fence names." },
web/renderer/src/tree/Blocks.svelte+14−1
@@ -1,9 +1,15 @@
<script lang="ts" module>
/** Where a details block keeps whether it was opened, by its block. */
const EXPANDED = {};
</script>
<script lang="ts">
import LinkCard from '../document/LinkCard.svelte';
import Gallery from '../Gallery.svelte';
import JsonTree from '../JsonTree.svelte';
import Picture from '../Picture.svelte';
import RichRuns from '../RichRuns.svelte';
import { remembered } from '../view/remember.svelte';
import Blocks from './Blocks.svelte';
import Embed from './Embed.svelte';
import { getTreeContext, openActor, opener, runsOf } from './context';
@@ -14,7 +20,8 @@
// around them (MarkdownProse for markdown, DocumentView for a document)
// styles them: paragraphs, headings, lists (a tight
// one's paragraphs `bare`, a task's checkbox first), code, quotes,
// rules, tables, footnotes, pictures and galleries, cards, buttons, a
// rules, tables, footnotes, details (opened as a person left them),
// pictures and galleries, cards, buttons, a
// Bluesky post the server resolved, as a quote (its fallback when it
// could not), a gap, a block not drawn, JSON. A Leaflet page's blocks (`top`)
// are each in a `div.block` in its alignment.
@@ -103,6 +110,12 @@
{/each}
</ol>
</section>
{:else if b.kind === 'details'}
{@const expanded = remembered(b, EXPANDED, () => b.expanded === true)}
<details open={expanded.value} ontoggle={(e) => (expanded.value = e.currentTarget.open)}>
<summary>{#if b.runs.length > 0}{@render runs(b.runs)}{:else}Details{/if}</summary>
<Blocks blocks={b.blocks} {look} />
</details>
{:else if b.kind === 'image'}
<figure class="image" style:--ratio={b.ratio}><Picture src={b.src} alt={b.alt} fit="contain" /></figure>
{:else if b.kind === 'gallery'}
web/renderer/src/tree/types.ts+1−0
@@ -117,6 +117,7 @@ export type UiBlock = (
| { kind: 'rule' }
| { kind: 'table'; head: UiRun[][]; rows: UiRun[][][] }
| { kind: 'footnotes'; items: { blocks: UiBlock[] }[] }
| { kind: 'details'; runs: UiRun[]; blocks: UiBlock[]; expanded?: boolean }
| { kind: 'image'; src: Source | null; alt: string; ratio: number }
| { kind: 'gallery'; images: { src: Source | null; alt: string | null; ratio: number | null }[] }
| { kind: 'card'; kicker: string; title: string; description?: string; image: Source | null; open?: UiOpen }
web/renderer/src/MarkdownProse.svelte+14−2
@@ -3,7 +3,7 @@
// Markdown's look, as GitHub draws a README or a pull's body: headings,
// paragraphs, lists and task lists, quotes, code, rules, tables,
// footnotes and a picture's alt text in its place, in the app's type.
// footnotes, details and a picture's alt text in its place, in the app's type.
// A resolved tree's `Blocks` draw their elements in it; `element` is the box, for what listens to its clicks.
let { element = $bindable(), children }: { element?: HTMLElement; children: Snippet } = $props();
</script>
@@ -24,7 +24,7 @@
margin-bottom: 0;
}
.markdown :global(:is(p, ul, ol, blockquote, pre, table)) {
.markdown :global(:is(p, ul, ol, blockquote, pre, table, details)) {
margin: 0 0 1em;
}
@@ -142,6 +142,18 @@
font-size: 0.9em;
}
.markdown :global(summary) {
cursor: pointer;
}
.markdown :global(details[open] > summary) {
margin-bottom: 0.5em;
}
.markdown :global(details > :last-child) {
margin-bottom: 0;
}
.markdown :global(.sr-only) {
position: absolute;
width: 1px;