~ 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
535 lines · 19.9 KB Raw History
//! A clamped text cut on the server: a `Text`'s or `RichText`'s `clamp`
//! lines read as a budget of characters, so the tree holds the cut and a
//! client draws it as it is, the same on a server, in a browser and in an
//! app, measuring nothing. A text over its budget is given `shownRuns`
//! (markdown, `shownBlocks`): itself cut at a word, an ellipsis after it,
//! drawn with a "Show more" until opened; one within it is given nothing.

use serde_json::Value;
use unicode_segmentation::UnicodeSegmentation;

/// The columns a line holds: about what a line of body text holds in a
/// phone's column (390 points wide, less its margins), less what wrapping
/// at words leaves at a line's end, so a cut text rarely takes more lines
/// than its clamp there. A wider column draws it in fewer.
pub(super) const LINE: usize = 44;

/// A phone's column, in lines of body text (360 pixels of 24): how many
/// lines a picture as wide as it is tall takes.
const COLUMN: f64 = 15.0;

/// A line of body text's height, in CSS pixels: how many lines a picture
/// `width` pixels wide takes.
const LINE_PX: f64 = 24.0;

/// The columns a grapheme takes: two for East Asian wide letters (Hangul,
/// Han, kana, fullwidth forms) and emoji, about twice a Latin letter's
/// width; one for the rest.
fn width(g: &str) -> usize {
    let c = g.chars().next().map_or(0, u32::from);
    let wide = matches!(c,
        0x1100..=0x115F
            | 0x2E80..=0xA4CF
            | 0xAC00..=0xD7A3
            | 0xF900..=0xFAFF
            | 0xFE30..=0xFE4F
            | 0xFF00..=0xFF60
            | 0xFFE0..=0xFFE6
            | 0x1F300..=0x1FAFF
            | 0x20000..=0x3FFFD
    );
    1 + usize::from(wide)
}

/// Where each line of `text` after its first starts, as a column of
/// `LINE` columns wraps it: its byte offset, and whether a line break
/// starts it (else it wrapped). White space a line wraps at takes no
/// column, as a browser hangs it at the end of the line before.
fn breaks(text: &str) -> Vec<(usize, bool)> {
    let mut starts = Vec::new();
    let mut col = 0;
    for (i, g) in text.grapheme_indices(true) {
        if g == "\n" || g == "\r\n" {
            starts.push((i + g.len(), true));
            col = 0;
            continue;
        }
        let w = width(g);
        if col + w > LINE {
            starts.push((i, false));
            col = 0;
            if g.trim().is_empty() {
                continue;
            }
        }
        col += w;
    }
    starts
}

/// The lines `text` takes.
fn lines(text: &str) -> usize {
    breaks(text).len() + 1
}

/// Where `text` is cut to show at most `lines` lines, an ellipsis after
/// it: a byte offset, its trailing white space left off; none when it
/// fits. Past a line break, or a wrap at white space, the cut is there;
/// past a wrap within a word, at the last white space of the last line
/// shown, or within a word that fills the line, a grapheme before the
/// line's end, room for the ellipsis.
fn cut(text: &str, lines: usize) -> Option<usize> {
    let starts = breaks(text);
    let &(at, by_break) = starts.get(lines - 1)?;
    if text[at..].trim().is_empty() {
        return None;
    }
    let end = if by_break || text[at..].starts_with(char::is_whitespace) {
        at
    } else {
        let from = lines.checked_sub(2).map_or(0, |i| starts[i].0);
        match text[from..at].rfind(char::is_whitespace) {
            Some(i) if i > 0 => from + i,
            _ => text[..at]
                .grapheme_indices(true)
                .next_back()
                .map_or(at, |(i, _)| i),
        }
    };
    Some(text[..end].trim_end().len())
}

/// Whether a run is a link, an account or a tag, which a cut leaves whole.
fn marked(run: &Value) -> bool {
    ["link", "actor", "tag"]
        .iter()
        .any(|k| run.get(k).is_some())
}

/// `runs` cut to about `lines` lines, at a word, an ellipsis after them;
/// none when they fit. A link, an account or a tag the cut falls in is
/// left out whole, unless it is the first run, whose words are cut then,
/// what it opens kept.
pub(super) fn runs(runs: &Value, lines: usize) -> Option<Vec<Value>> {
    let end = cut(&joined(runs), lines)?;
    let mut shown = Vec::new();
    let mut at = 0;
    for r in items(runs) {
        let t = r["text"].as_str().unwrap_or_default();
        if at + t.len() > end {
            if end > at && (shown.is_empty() || !marked(r)) {
                let mut part = r.clone();
                part["text"] = t[..end - at].into();
                shown.push(part);
            }
            break;
        }
        shown.push(r.clone());
        at += t.len();
    }
    let last = shown.last_mut().filter(|r| !marked(r));
    match last {
        Some(r) => {
            let t = r["text"].as_str().unwrap_or_default().trim_end();
            r["text"] = format!("{t}…").into();
        }
        None => shown.push(serde_json::json!({ "text": "…" })),
    }
    Some(shown)
}

/// Runs' words, one after another.
fn joined(runs: &Value) -> String {
    items(runs).filter_map(|r| r["text"].as_str()).collect()
}

/// The lines runs take.
fn runs_lines(runs: &Value) -> usize {
    lines(&joined(runs))
}

/// The lines a block takes: its words' (a heading one more, its margins),
/// a code block's lines and its padding, a table's rows and its head, a
/// picture's height across a phone's column (its own width where it is
/// narrower), a list's, a footnote's or a quote's blocks', and a closed
/// disclosure's summary; one for the rest.
fn block_lines(b: &Value) -> usize {
    match b["kind"].as_str().unwrap_or_default() {
        "paragraph" => runs_lines(&b["runs"]),
        "heading" => runs_lines(&b["runs"]) + 1,
        "unsupported" => lines(b["text"].as_str().unwrap_or_default()),
        "code" => b["text"].as_str().unwrap_or_default().lines().count() + 1,
        "table" => b["rows"].as_array().map_or(0, Vec::len) + 1,
        "image" => {
            let wide = b["width"]
                .as_f64()
                .map_or(COLUMN, |w| (w / LINE_PX).min(COLUMN));
            let ratio = b["ratio"].as_f64().filter(|r| *r > 0.0).unwrap_or(1.0);
            ((wide / ratio).ceil() as usize).max(1)
        }
        "list" | "footnotes" => items(&b["items"]).map(|i| blocks_lines(&i["blocks"])).sum(),
        "quote" => blocks_lines(&b["blocks"]),
        "details" if b["expanded"] == true => runs_lines(&b["runs"]) + blocks_lines(&b["blocks"]),
        _ => 1,
    }
}

fn items(v: &Value) -> impl Iterator<Item = &Value> {
    v.as_array().into_iter().flatten()
}

/// The lines blocks take, one between each two, their margin.
fn blocks_lines(blocks: &Value) -> usize {
    items(blocks).map(block_lines).sum::<usize>() + items(blocks).count().saturating_sub(1)
}

/// The blocks that fit in `lines` lines: whole, while they fit, then the
/// one past them cut, where it can be (`cut_block`).
fn fit(blocks: &Value, lines: usize) -> Vec<Value> {
    let mut shown = Vec::new();
    let mut used = 0;
    for b in items(blocks) {
        let gap = usize::from(!shown.is_empty());
        let need = block_lines(b) + gap;
        if used + need > lines {
            let left = lines - used;
            if let Some(part) = left
                .checked_sub(gap)
                .filter(|l| *l > 0)
                .and_then(|l| cut_block(b, l))
            {
                shown.push(part);
            }
            break;
        }
        shown.push(b.clone());
        used += need;
    }
    shown
}

/// A block cut to `lines` lines, or none where nothing of it fits: a
/// paragraph's runs (`runs`), a code block's first lines, a table's first
/// rows, a list's or a footnote's first items, the last cut in its blocks,
/// and a quote's blocks; a heading, a picture and the rest are shown whole
/// or not at all.
fn cut_block(b: &Value, lines: usize) -> Option<Value> {
    let mut part = b.clone();
    match b["kind"].as_str().unwrap_or_default() {
        "paragraph" => part["runs"] = runs(&b["runs"], lines)?.into(),
        "code" if lines > 1 => {
            let text = b["text"].as_str().unwrap_or_default();
            let kept: Vec<&str> = text.lines().take(lines - 1).collect();
            part["text"] = kept.join("\n").into();
        }
        "table" if lines > 1 => {
            let rows = items(&b["rows"]).take(lines - 1).cloned();
            part["rows"] = rows.collect::<Vec<_>>().into();
        }
        "list" | "footnotes" => {
            let mut used = 0;
            let mut kept = Vec::new();
            for item in items(&b["items"]) {
                let need = blocks_lines(&item["blocks"]);
                if used + need > lines {
                    let shown = fit(&item["blocks"], lines - used);
                    if !shown.is_empty() {
                        let mut item = item.clone();
                        item["blocks"] = shown.into();
                        kept.push(item);
                    }
                    break;
                }
                kept.push(item.clone());
                used += need;
            }
            if kept.is_empty() {
                return None;
            }
            part["items"] = kept.into();
        }
        "quote" => {
            let shown = fit(&b["blocks"], lines);
            if shown.is_empty() {
                return None;
            }
            part["blocks"] = shown.into();
        }
        _ => return None,
    }
    Some(part)
}

/// Markdown's `blocks` cut to about `lines` lines, by the same budget as
/// runs, each block's margin a line: whole blocks while they fit, then the
/// next cut where it can be; none when they fit. Where not even the first
/// fits in part, it is shown whole.
pub(super) fn blocks(blocks: &Value, lines: usize) -> Option<Vec<Value>> {
    if blocks_lines(blocks) <= lines {
        return None;
    }
    let shown = fit(blocks, lines);
    if shown.is_empty() {
        let first: Vec<Value> = items(blocks).take(1).cloned().collect();
        return (items(blocks).count() > 1).then_some(first);
    }
    Some(shown)
}

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

    fn plain(text: &str) -> Value {
        json!([{ "text": text }])
    }

    fn p(text: &str) -> Value {
        json!({ "kind": "paragraph", "runs": [{ "text": text }] })
    }

    fn heading(text: &str) -> Value {
        json!({ "kind": "heading", "level": 2, "runs": [{ "text": text }] })
    }

    const FOX: &str = "Pack my box with five dozen liquor jugs ";

    /// Text that fits its lines is left as it is: short, as many lines as
    /// it may take, or more only in white space after its words.
    #[test]
    fn text_that_fits_is_not_cut() {
        assert_eq!(runs(&plain("Hello"), 1), None);
        assert_eq!(runs(&plain("one\ntwo"), 2), None);
        assert_eq!(runs(&plain(&"x".repeat(LINE * 2)), 2), None);
        assert_eq!(runs(&plain("one\n  \n"), 1), None);
        assert_eq!(lines(""), 1);
    }

    /// Past its lines, text is cut at the last word of its last line, an
    /// ellipsis after it; at a line break, the break counting as a line's
    /// end; within a word that fills the line, a grapheme before its end.
    #[test]
    fn text_is_cut_at_a_word_or_a_line_break() {
        assert_eq!(
            runs(&plain(&FOX.repeat(4)), 2),
            Some(vec![
                json!({ "text": "Pack my box with five dozen liquor jugs Pack my box with five dozen liquor jugs Pack my…" })
            ])
        );
        assert_eq!(
            runs(&plain(&FOX.repeat(4)), 1),
            Some(vec![
                json!({ "text": "Pack my box with five dozen liquor jugs Pack…" })
            ])
        );
        assert_eq!(
            runs(&plain("one\ntwo\nthree"), 2),
            Some(vec![json!({ "text": "one\ntwo…" })])
        );
        let word = "x".repeat(100);
        assert_eq!(
            runs(&plain(&word), 1),
            Some(vec![
                json!({ "text": format!("{}…", "x".repeat(LINE - 1)) })
            ])
        );
        // A last line whose only space starts it is one word: cut within it.
        let text = format!("{} {}", "x".repeat(LINE), "y".repeat(60));
        assert_eq!(
            runs(&plain(&text), 2),
            Some(vec![
                json!({ "text": format!("{} {}…", "x".repeat(LINE), "y".repeat(LINE - 1)) })
            ])
        );
        // Nothing but white space before the cut leaves the ellipsis alone.
        assert_eq!(
            runs(&plain("\n\nlater"), 1),
            Some(vec![json!({ "text": "…" })])
        );
    }

    /// Han, kana, Hangul and emoji take two columns, a family of people one
    /// grapheme, never cut apart.
    #[test]
    fn wide_letters_and_emoji_take_two_columns() {
        let half = LINE / 2 - 1;
        assert_eq!(
            runs(&plain(&"漢".repeat(30)), 1),
            Some(vec![json!({ "text": format!("{}…", "漢".repeat(half)) })])
        );
        let family = "👩\u{200d}👩\u{200d}👧";
        assert_eq!(
            runs(&plain(&family.repeat(30)), 1),
            Some(vec![json!({ "text": format!("{}…", family.repeat(half)) })])
        );
        assert_eq!(runs(&plain(&"漢".repeat(LINE / 2)), 1), None);
    }

    /// A link, an account or a tag the cut falls in is left out whole and
    /// the run before it ends the text; a first run cut keeps what it
    /// opens, its ellipsis a run of its own; one the cut falls after stays.
    #[test]
    fn links_mentions_and_tags_stay_whole() {
        let link = format!("{} {}", "a".repeat(20), "b".repeat(30));
        let cut = runs(
            &json!([{ "text": "read " }, { "text": link, "link": "https://a.example" }]),
            1,
        );
        assert_eq!(cut, Some(vec![json!({ "text": "read…" })]));

        let url = format!("https://{}", "x".repeat(60));
        let cut = runs(&json!([{ "text": url, "link": url }]), 1).unwrap();
        assert_eq!(cut[0], json!({ "text": url[..LINE - 1], "link": url }));
        assert_eq!(cut[1], json!({ "text": "…" }));

        let mention = json!([
            { "text": "hi " },
            { "text": "@alice.test", "actor": "did:plc:alice" },
            { "text": "\nmore\nmore" }
        ]);
        assert_eq!(
            runs(&mention, 1),
            Some(vec![
                json!({ "text": "hi " }),
                json!({ "text": "@alice.test", "actor": "did:plc:alice" }),
                json!({ "text": "…" })
            ])
        );
        let tag = json!([{ "text": "one " }, { "text": "#two", "tag": "two" }, { "text": " three\nfour" }]);
        assert_eq!(
            runs(&tag, 1),
            Some(vec![
                json!({ "text": "one " }),
                json!({ "text": "#two", "tag": "two" }),
                json!({ "text": " three…" })
            ])
        );
    }

    /// The lines each block takes: words', a heading's margin, a code
    /// block's and a table's padding, a picture's height in a phone's
    /// column, a list's and a quote's blocks', a closed disclosure's
    /// summary.
    #[test]
    fn blocks_take_their_lines() {
        let long = FOX.repeat(3);
        assert_eq!(block_lines(&p(&long)), 3);
        assert_eq!(block_lines(&heading("Title")), 2);
        assert_eq!(
            block_lines(&json!({ "kind": "unsupported", "text": "<x>" })),
            1
        );
        assert_eq!(block_lines(&json!({ "kind": "code", "text": "a\nb" })), 3);
        assert_eq!(
            block_lines(&json!({ "kind": "table", "head": [], "rows": [[], []] })),
            3
        );
        assert_eq!(
            block_lines(&json!({ "kind": "image", "ratio": 2.0, "width": 240 })),
            5
        );
        assert_eq!(block_lines(&json!({ "kind": "image", "ratio": 0.0 })), 15);
        assert_eq!(block_lines(&json!({ "kind": "image", "ratio": 100.0 })), 1);
        let list = json!({ "kind": "list", "items": [{ "blocks": [p("a"), p("b")] }, { "blocks": [p("c")] }] });
        assert_eq!(block_lines(&list), 4);
        assert_eq!(
            block_lines(&json!({ "kind": "quote", "blocks": [p("a")] })),
            1
        );
        let details =
            json!({ "kind": "details", "runs": [{ "text": "More" }], "blocks": [p("a"), p("b")] });
        assert_eq!(block_lines(&details), 1);
        let mut open = details.clone();
        open["expanded"] = true.into();
        assert_eq!(block_lines(&open), 4);
        assert_eq!(block_lines(&json!({ "kind": "rule" })), 1);
    }

    /// Blocks that fit are left as they are; past their lines, whole blocks
    /// are kept while they fit, each but the first a line more for its
    /// margin, then the next cut: a paragraph at a word, a code block's or
    /// a table's first lines, a list's first items and a quote's blocks;
    /// a heading or a picture not at all.
    #[test]
    fn blocks_are_cut_whole_then_in_part() {
        let blocks = |b: Value, n| super::blocks(&b, n);
        assert_eq!(blocks(json!([p("a"), p("b")]), 3), None);
        assert_eq!(
            blocks(json!([p("a"), p("b"), p("c")]), 1),
            Some(vec![p("a")])
        );
        // A line of it, its words filling it: nine of them.
        let long = "word ".repeat(30);
        let line = &p(&format!("{}…", ["word"; 9].join(" ")));
        assert_eq!(
            blocks(json!([p("a"), p(&long)]), 3),
            Some(vec![p("a"), line.clone()])
        );
        assert_eq!(
            blocks(json!([p("a"), heading("Title"), p("b")]), 2),
            Some(vec![p("a")])
        );

        let code = json!({ "kind": "code", "text": "1\n2\n3\n4", "lang": "sh" });
        assert_eq!(
            blocks(json!([code]), 3),
            Some(vec![
                json!({ "kind": "code", "text": "1\n2", "lang": "sh" })
            ])
        );
        let table = json!({ "kind": "table", "head": [], "rows": [[1], [2], [3], [4], [5]] });
        assert_eq!(
            blocks(json!([table]), 3),
            Some(vec![
                json!({ "kind": "table", "head": [], "rows": [[1], [2]] })
            ])
        );

        let list = json!({ "kind": "list", "ordered": false, "items": [
            { "blocks": [p("one")] }, { "blocks": [p("two")] }, { "blocks": [p(&long)] }
        ] });
        assert_eq!(
            blocks(json!([list]), 3),
            Some(vec![json!({ "kind": "list", "ordered": false, "items": [
                { "blocks": [p("one")] }, { "blocks": [p("two")] }, { "blocks": [line] }
            ] })])
        );
        let list = json!({ "kind": "footnotes", "items": [{ "blocks": [p("a")] }, { "blocks": [heading("h")] }] });
        assert_eq!(
            blocks(json!([list]), 2),
            Some(vec![
                json!({ "kind": "footnotes", "items": [{ "blocks": [p("a")] }] })
            ])
        );
        let quote = json!({ "kind": "quote", "blocks": [p("a"), p(&long)] });
        assert_eq!(
            blocks(json!([quote]), 3),
            Some(vec![json!({ "kind": "quote", "blocks": [p("a"), line] })])
        );
    }

    /// Where not even the first block fits in part, it is shown whole, and
    /// alone it is nothing cut: a heading, a picture, a code block or a
    /// table of one line, a list or a quote whose first block cannot be
    /// cut, a paragraph whose rest is white space.
    #[test]
    fn a_first_block_that_cannot_be_cut_is_shown_whole() {
        let blocks = |b: Value, n| super::blocks(&b, n);
        assert_eq!(
            blocks(json!([heading("Title"), p("b")]), 1),
            Some(vec![heading("Title")])
        );
        assert_eq!(blocks(json!([{ "kind": "image", "ratio": 1.0 }]), 3), None);
        assert_eq!(blocks(json!([{ "kind": "code", "text": "1\n2" }]), 1), None);
        assert_eq!(
            blocks(json!([{ "kind": "table", "head": [], "rows": [[1]] }]), 1),
            None
        );
        let list = json!({ "kind": "list", "items": [{ "blocks": [heading("h")] }] });
        assert_eq!(blocks(json!([list, p("x")]), 1), Some(vec![list]));
        let quote = json!({ "kind": "quote", "blocks": [heading("h")] });
        assert_eq!(blocks(json!([quote, p("x")]), 1), Some(vec![quote]));
        assert_eq!(blocks(json!([p("a\n ")]), 1), None);
    }
}