hyuskui

Inline Citation

Sources cited right where a claim is made. Each pill names the source's site; resting on it shows the page's title and what it covers.

Loading GPUI…
use std::time::Duration;

use gpui::{div, prelude::*, px, AnyElement, App, Context, FontWeight, Window};

use crate::theme::ActiveTheme;
use crate::ui::hover_card::{HoverCard, HoverCardVariant};

/// shadcn's trigger delays: the card opens almost at once and survives a brief exit.
const OPEN_DELAY: Duration = Duration::from_millis(10);
const CLOSE_DELAY: Duration = Duration::from_millis(100);
/// Tailwind's `leading-relaxed` on 14px text.
const LINE: f32 = 22.75;
/// The advance of a space in 14px Geist.
const SPACE: f32 = 3.5;

struct Source {
    url: &'static str,
    title: &'static str,
    description: &'static str,
}

const STREAMING: Source = Source {
    url: "https://nextjs.org/docs/app/getting-started/linking-and-navigating#streaming",
    title: "Linking and Navigating",
    description: "How the App Router streams a route to the browser.",
};
const SUSPENSE: Source = Source {
    url: "https://react.dev/reference/react/Suspense",
    title: "<Suspense>",
    description: "Display a fallback until its children have finished loading.",
};
const SERVER_COMPONENTS: Source = Source {
    url: "https://react.dev/reference/rsc/server-components",
    title: "Server Components",
    description: "Components that render ahead of time, on the server.",
};
const LOADING: Source = Source {
    url: "https://nextjs.org/docs/app/api-reference/file-conventions/loading",
    title: "loading.js",
    description: "Show an instant loading state for a route segment.",
};
const CHUNKED: Source = Source {
    url: "https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Transfer-Encoding",
    title: "Transfer-Encoding",
    description: "Send a response as a series of chunks.",
};

enum Part {
    Text(&'static str),
    Cite(&'static Source),
}

const PARAGRAPHS: [&[Part]; 3] = [
    &[
        Part::Text("Next.js streams a route in chunks, so the page shows up before every request finishes."),
        Part::Cite(&STREAMING),
    ],
    &[
        Part::Text(
            "Wrap a slow part of the page in a Suspense boundary and React sends the fallback first. \
             When the data resolves, the finished HTML streams into the same response and replaces \
             the fallback, with no extra request from the browser.",
        ),
        Part::Cite(&SUSPENSE),
        Part::Text("Server Components help here, because their code never ships to the browser."),
        Part::Cite(&SERVER_COMPONENTS),
    ],
    &[
        Part::Text("A loading.tsx file does the same for a whole route segment."),
        Part::Cite(&LOADING),
        Part::Text("It all runs over chunked transfer encoding, so there is nothing extra to set up."),
        Part::Cite(&CHUNKED),
    ],
];

#[derive(Default)]
pub struct InlineCitationPattern;

impl Render for InlineCitationPattern {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let mut cite = 0;
        let paragraphs = PARAGRAPHS.iter().map(|parts| {
            // GPUI has no inline layout, so a paragraph is a wrapping row with one item per word
            // and pill, a space apart. A gap, unlike a trailing space, costs nothing at a line's
            // end, so lines break where the browser breaks them.
            let items: Vec<AnyElement> = parts
                .iter()
                .flat_map(|part| -> Vec<AnyElement> {
                    match part {
                        Part::Text(text) => text
                            .split_whitespace()
                            .map(|word| div().child(word.to_string()).into_any_element())
                            .collect(),
                        Part::Cite(source) => {
                            cite += 1;
                            vec![citation(cite, source, cx)]
                        }
                    }
                })
                .collect();
            div().flex().flex_wrap().items_start().gap_x(px(SPACE)).children(items)
        });

        div()
            .w(px(384.0))
            .flex()
            .flex_col()
            .gap_3()
            .py_6()
            .text_sm()
            .line_height(px(LINE))
            .text_color(cx.theme().foreground)
            .children(paragraphs)
    }
}

fn hostname(url: &str) -> &str {
    let host = url.split("://").nth(1).unwrap_or(url);
    let host = host.split('/').next().unwrap_or(host);
    host.strip_prefix("www.").unwrap_or(host)
}

/// shadcn's secondary button at size xs, with the source's card on hover.
fn citation(ix: usize, source: &'static Source, cx: &App) -> AnyElement {
    let theme = cx.theme();
    let host = hostname(source.url);
    // Measured on shadcn: the pill darkens on hover in light mode and lightens in dark mode.
    let hover = if theme.background.l > 0.5 {
        theme.border
    } else {
        theme.secondary.blend(theme.foreground.opacity(0.13))
    };

    let pill = div()
        .id(("pill", ix))
        .flex()
        .items_center()
        .h(px(24.0))
        // 10px of padding inside the button's transparent 1px border.
        .px(px(11.0))
        .rounded_full()
        .bg(theme.secondary)
        .text_xs()
        .line_height(px(16.0))
        .font_weight(FontWeight::MEDIUM)
        .text_color(theme.secondary_foreground)
        .cursor_pointer()
        .hover(move |this| this.bg(hover))
        .child(host);

    let card = div()
        .flex()
        .flex_col()
        .gap_1()
        .line_height(px(20.0))
        .child(div().font_weight(FontWeight::MEDIUM).child(source.title))
        .child(div().text_color(theme.muted_foreground).child(source.description))
        .child(
            div()
                .id(("link", ix))
                .text_xs()
                .line_height(px(16.0))
                .text_color(theme.muted_foreground)
                .cursor_pointer()
                .hover(|this| this.underline())
                .on_click(move |_, _, cx| cx.open_url(source.url))
                .child(host),
        );

    let card = HoverCard::new(("citation", ix))
        .variant(HoverCardVariant::Rhea)
        .width(px(256.0))
        .open_delay(OPEN_DELAY)
        .close_delay(CLOSE_DELAY)
        .trigger(pill)
        .child(card);

    // Baseline alignment, as measured on shadcn: the pill's 12px text and the paragraph's
    // 14px text share a baseline, which puts the pill's top 0.375px below the top of the
    // words' 22.75px line boxes. GPUI can't align leaf text by baseline, so the row aligns
    // tops and the pill is nudged down.
    div().pt(px(0.375)).child(card).into_any_element()
}

Installation

  1. Add the components

    $ cargo hyuskui add hover-card

    Uses Hover Card.

  2. Copy the pattern

    Paste the code into src/ai/inline_citation.rs and declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.

    src/ai/inline_citation.rs
    use std::time::Duration;
    
    use gpui::{div, prelude::*, px, AnyElement, App, Context, FontWeight, Window};
    
    use crate::theme::ActiveTheme;
    use crate::ui::hover_card::{HoverCard, HoverCardVariant};
    
    /// shadcn's trigger delays: the card opens almost at once and survives a brief exit.
    const OPEN_DELAY: Duration = Duration::from_millis(10);
    const CLOSE_DELAY: Duration = Duration::from_millis(100);
    /// Tailwind's `leading-relaxed` on 14px text.
    const LINE: f32 = 22.75;
    /// The advance of a space in 14px Geist.
    const SPACE: f32 = 3.5;
    
    struct Source {
        url: &'static str,
        title: &'static str,
        description: &'static str,
    }
    
    const STREAMING: Source = Source {
        url: "https://nextjs.org/docs/app/getting-started/linking-and-navigating#streaming",
        title: "Linking and Navigating",
        description: "How the App Router streams a route to the browser.",
    };
    const SUSPENSE: Source = Source {
        url: "https://react.dev/reference/react/Suspense",
        title: "<Suspense>",
        description: "Display a fallback until its children have finished loading.",
    };
    const SERVER_COMPONENTS: Source = Source {
        url: "https://react.dev/reference/rsc/server-components",
        title: "Server Components",
        description: "Components that render ahead of time, on the server.",
    };
    const LOADING: Source = Source {
        url: "https://nextjs.org/docs/app/api-reference/file-conventions/loading",
        title: "loading.js",
        description: "Show an instant loading state for a route segment.",
    };
    const CHUNKED: Source = Source {
        url: "https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Transfer-Encoding",
        title: "Transfer-Encoding",
        description: "Send a response as a series of chunks.",
    };
    
    enum Part {
        Text(&'static str),
        Cite(&'static Source),
    }
    
    const PARAGRAPHS: [&[Part]; 3] = [
        &[
            Part::Text("Next.js streams a route in chunks, so the page shows up before every request finishes."),
            Part::Cite(&STREAMING),
        ],
        &[
            Part::Text(
                "Wrap a slow part of the page in a Suspense boundary and React sends the fallback first. \
                 When the data resolves, the finished HTML streams into the same response and replaces \
                 the fallback, with no extra request from the browser.",
            ),
            Part::Cite(&SUSPENSE),
            Part::Text("Server Components help here, because their code never ships to the browser."),
            Part::Cite(&SERVER_COMPONENTS),
        ],
        &[
            Part::Text("A loading.tsx file does the same for a whole route segment."),
            Part::Cite(&LOADING),
            Part::Text("It all runs over chunked transfer encoding, so there is nothing extra to set up."),
            Part::Cite(&CHUNKED),
        ],
    ];
    
    #[derive(Default)]
    pub struct InlineCitationPattern;
    
    impl Render for InlineCitationPattern {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let mut cite = 0;
            let paragraphs = PARAGRAPHS.iter().map(|parts| {
                // GPUI has no inline layout, so a paragraph is a wrapping row with one item per word
                // and pill, a space apart. A gap, unlike a trailing space, costs nothing at a line's
                // end, so lines break where the browser breaks them.
                let items: Vec<AnyElement> = parts
                    .iter()
                    .flat_map(|part| -> Vec<AnyElement> {
                        match part {
                            Part::Text(text) => text
                                .split_whitespace()
                                .map(|word| div().child(word.to_string()).into_any_element())
                                .collect(),
                            Part::Cite(source) => {
                                cite += 1;
                                vec![citation(cite, source, cx)]
                            }
                        }
                    })
                    .collect();
                div().flex().flex_wrap().items_start().gap_x(px(SPACE)).children(items)
            });
    
            div()
                .w(px(384.0))
                .flex()
                .flex_col()
                .gap_3()
                .py_6()
                .text_sm()
                .line_height(px(LINE))
                .text_color(cx.theme().foreground)
                .children(paragraphs)
        }
    }
    
    fn hostname(url: &str) -> &str {
        let host = url.split("://").nth(1).unwrap_or(url);
        let host = host.split('/').next().unwrap_or(host);
        host.strip_prefix("www.").unwrap_or(host)
    }
    
    /// shadcn's secondary button at size xs, with the source's card on hover.
    fn citation(ix: usize, source: &'static Source, cx: &App) -> AnyElement {
        let theme = cx.theme();
        let host = hostname(source.url);
        // Measured on shadcn: the pill darkens on hover in light mode and lightens in dark mode.
        let hover = if theme.background.l > 0.5 {
            theme.border
        } else {
            theme.secondary.blend(theme.foreground.opacity(0.13))
        };
    
        let pill = div()
            .id(("pill", ix))
            .flex()
            .items_center()
            .h(px(24.0))
            // 10px of padding inside the button's transparent 1px border.
            .px(px(11.0))
            .rounded_full()
            .bg(theme.secondary)
            .text_xs()
            .line_height(px(16.0))
            .font_weight(FontWeight::MEDIUM)
            .text_color(theme.secondary_foreground)
            .cursor_pointer()
            .hover(move |this| this.bg(hover))
            .child(host);
    
        let card = div()
            .flex()
            .flex_col()
            .gap_1()
            .line_height(px(20.0))
            .child(div().font_weight(FontWeight::MEDIUM).child(source.title))
            .child(div().text_color(theme.muted_foreground).child(source.description))
            .child(
                div()
                    .id(("link", ix))
                    .text_xs()
                    .line_height(px(16.0))
                    .text_color(theme.muted_foreground)
                    .cursor_pointer()
                    .hover(|this| this.underline())
                    .on_click(move |_, _, cx| cx.open_url(source.url))
                    .child(host),
            );
    
        let card = HoverCard::new(("citation", ix))
            .variant(HoverCardVariant::Rhea)
            .width(px(256.0))
            .open_delay(OPEN_DELAY)
            .close_delay(CLOSE_DELAY)
            .trigger(pill)
            .child(card);
    
        // Baseline alignment, as measured on shadcn: the pill's 12px text and the paragraph's
        // 14px text share a baseline, which puts the pill's top 0.375px below the top of the
        // words' 22.75px line boxes. GPUI can't align leaf text by baseline, so the row aligns
        // tops and the pill is nudged down.
        div().pt(px(0.375)).child(card).into_any_element()
    }