One turn. The person's message, and the agent's reply with its actions.
Loading GPUI…
use std::time::Duration;
use gpui::{
div, prelude::*, px, AnyElement, App, ClipboardItem, Context, Font, FontWeight, Hsla, Pixels, SharedString, Task,
TextRun, Window,
};
use crate::icons::{icon, CHECK, COPY, PENCIL, REFRESH_CCW, THUMBS_DOWN, THUMBS_DOWN_FILLED, THUMBS_UP, THUMBS_UP_FILLED};
use crate::theme::{ActiveTheme, Theme};
use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
use crate::ui::message::{Message, MessageAlign};
use crate::ui::tooltip::Tooltip;
const MONO: &str = "Geist Mono";
/// How long Copy shows its check, like the demo's 2000ms timeout.
const COPIED: Duration = Duration::from_millis(2000);
const QUESTION: &str = "How do I add a settings dialog? It should open from the gear icon in the header.";
/// The reply's markdown source, for the clipboard.
const REPLY: &str = "Install Dialog, then open it from the gear button in `site-header.tsx`.\n\n\
```bash\nnpx shadcn@latest add dialog\n```\n\n\
Wrap the button in a `DialogTrigger` and put the settings form in `DialogContent`. Focus moves \
into the dialog when it opens, and **Esc** closes it.";
const INSTALL: &str = "Install Dialog, then open it from the gear button in `site-header.tsx`.";
const WRAP: &str = "Wrap the button in a `DialogTrigger` and put the settings form in `DialogContent`. Focus moves into the dialog when it opens, and **Esc** closes it.";
/// shiki's github themes, which the docs' code blocks use.
#[derive(Clone, Copy)]
enum Token {
Plain,
Function,
String,
}
const COMMAND: [(&str, Token); 7] = [
("npx", Token::Function),
(" ", Token::Plain),
("shadcn@latest", Token::String),
(" ", Token::Plain),
("add", Token::String),
(" ", Token::Plain),
("dialog", Token::String),
];
fn token_color(token: Token, theme: &Theme) -> Hsla {
let dark = theme.background.l < 0.5;
let hex = match (token, dark) {
(Token::Plain, false) => 0x24292e,
(Token::Function, false) => 0x6f42c1,
(Token::String, false) => 0x032f62,
(Token::Plain, true) => 0xe1e4e8,
(Token::Function, true) => 0xb392f0,
(Token::String, true) => 0x9ecbff,
};
gpui::rgb(hex).into()
}
#[derive(Clone, Copy, PartialEq)]
enum Feedback {
Like,
Dislike,
}
#[derive(Default)]
pub struct MessagePattern {
copied: bool,
code_copied: bool,
feedback: Option<Feedback>,
/// Replacing a countdown restarts it, so a second copy keeps the check up.
copy_reset: Option<Task<()>>,
code_reset: Option<Task<()>>,
}
impl MessagePattern {
fn copy(&mut self, code: bool, cx: &mut Context<Self>) {
let text = if code { "npx shadcn@latest add dialog" } else { REPLY };
cx.write_to_clipboard(ClipboardItem::new_string(text.to_string()));
let reset = cx.spawn(async move |this, cx| {
cx.background_executor().timer(COPIED).await;
this.update(cx, |this, cx| {
if code {
this.code_copied = false;
} else {
this.copied = false;
}
cx.notify();
})
.ok();
});
if code {
self.code_copied = true;
self.code_reset = Some(reset);
} else {
self.copied = true;
self.copy_reset = Some(reset);
}
cx.notify();
}
}
/// One wrappable unit of a paragraph: words glued together with no space between them, such
/// as an inline code span and the comma after it.
#[derive(Clone, Copy, PartialEq)]
enum Style {
Plain,
Bold,
Code,
}
/// Lays out one line of markdown (`code` and **bold** only) like a browser paragraph: words
/// wrap as units, and inline code is a padded chip that doesn't grow the line.
fn paragraph(source: &str, window: &Window, cx: &App) -> AnyElement {
let theme = cx.theme();
let (fg, muted) = (theme.foreground, theme.muted);
// GPUI rounds each text element's width up to a whole pixel, so a line of one-word
// elements drifts wider than the browser's and wraps early. Each unit gets its exact
// shaped width instead.
let base = window.text_style().font();
let measure = |text: &str, style: Style| -> Pixels {
let (font, size) = match style {
Style::Plain => (base.clone(), px(14.0)),
Style::Bold => (Font { weight: FontWeight::SEMIBOLD, ..base.clone() }, px(14.0)),
Style::Code => (gpui::font(MONO), px(12.6)),
};
let run = TextRun { len: text.len(), font, color: fg, background_color: None, underline: None, strikethrough: None };
let width = window.text_system().shape_line(SharedString::from(text.to_string()), size, &[run], None).width;
if style == Style::Code { width + px(8.0) } else { width }
};
// Split into styled runs, then into words that keep their trailing space.
let mut atoms: Vec<(Style, String)> = Vec::new();
let mut style = Style::Plain;
let mut rest = source;
while !rest.is_empty() {
let next = [rest.find('`'), rest.find("**")].into_iter().flatten().min();
let end = next.unwrap_or(rest.len());
let run = &rest[..end];
if style == Style::Code {
if !run.is_empty() {
atoms.push((Style::Code, run.to_string()));
}
} else {
atoms.extend(run.split_inclusive(' ').map(|word| (style, word.to_string())));
}
rest = &rest[end..];
if let Some(stripped) = rest.strip_prefix('`') {
style = if style == Style::Code { Style::Plain } else { Style::Code };
rest = stripped;
} else if let Some(stripped) = rest.strip_prefix("**") {
if style != Style::Code {
style = if style == Style::Bold { Style::Plain } else { Style::Bold };
}
rest = stripped;
}
}
// A word only starts a new unit after whitespace.
let mut units: Vec<Vec<(Style, String)>> = Vec::new();
for atom in atoms {
let after_space = units
.last()
.and_then(|unit| unit.last())
.is_none_or(|(_, text)| text.ends_with(' '));
if atom.1.trim().is_empty() {
match units.last_mut() {
Some(unit) => unit.push(atom),
None => units.push(vec![atom]),
}
} else if after_space {
units.push(vec![atom]);
} else if let Some(unit) = units.last_mut() {
unit.push(atom);
}
}
div()
.flex()
.flex_wrap()
.w_full()
.line_height(px(20.0))
.text_color(fg)
.children(units.into_iter().map(|unit| {
let width: Pixels = unit.iter().map(|(style, text)| measure(text, *style)).fold(px(0.0), |sum, w| sum + w);
div().flex().flex_none().w(width).children(unit.into_iter().map(|(style, text)| match style {
// shadcn's inline code: 12.6px mono, 2px/4px padding, 6px corners. Its 21px box
// hangs below the 20px line rather than growing it.
Style::Code => div()
.relative()
.h(px(20.0))
.px(px(4.0))
.flex()
.items_center()
.font_family(MONO)
.text_size(px(12.6))
.child(div().absolute().top_0().left_0().right_0().h(px(21.0)).rounded(px(6.0)).bg(muted))
.child(div().relative().whitespace_nowrap().child(text))
.into_any_element(),
Style::Bold => div()
.whitespace_nowrap()
.font_weight(FontWeight::SEMIBOLD)
.child(text)
.into_any_element(),
Style::Plain => div().whitespace_nowrap().child(text).into_any_element(),
}))
}))
.into_any_element()
}
impl Render for MessagePattern {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (fg, muted_fg, muted) = (theme.foreground, theme.muted_foreground, theme.muted);
// shadcn's ghost button at size icon-sm. Each one has a tooltip naming it.
let action = |id: &'static str, data: &'static [u8]| {
div()
.id(id)
.flex()
.flex_none()
.items_center()
.justify_center()
.size(px(28.0))
.rounded_full()
.cursor_pointer()
.hover(move |style| style.bg(muted))
.active(|style| style.top(px(1.0)))
.child(icon(data).size(px(16.0)).text_color(muted_fg))
};
let tip = |id: &'static str, label: &'static str, trigger: gpui::Stateful<gpui::Div>| {
Tooltip::new((id, 1usize), label).trigger(trigger)
};
let code_block = div()
.w_full()
.flex()
.flex_col()
.rounded(px(18.0))
.bg(muted)
// shadcn draws a 1px ring of foreground at 5%.
.border_1()
.border_color(fg.opacity(0.05))
.child(
div()
.flex()
.items_center()
.gap_2()
.pt(px(15.0))
.px(px(15.0))
.child(div().flex_1().text_sm().font_weight(FontWeight::MEDIUM).text_color(fg).child("bash"))
.child(
Tooltip::new("code-copy-tip", if self.code_copied { "Copied" } else { "Copy" }).trigger(
div()
.id("code-copy")
.flex()
.items_center()
.justify_center()
.size(px(24.0))
.mr(px(-6.0))
// Like shadcn's `-my-1`, the button doesn't make the header taller.
.my(px(-4.0))
.rounded_full()
.cursor_pointer()
.hover(move |style| style.bg(fg.opacity(0.05)))
.on_click(cx.listener(|this, _, _, cx| this.copy(true, cx)))
.child(
icon(if self.code_copied { CHECK } else { COPY })
.size(px(12.0))
.text_color(muted_fg),
),
),
),
)
.child(
div()
.flex()
.gap_3()
.pt_2()
.pb(px(15.0))
.px(px(15.0))
.font_family(MONO)
.text_sm()
.line_height(px(22.75))
.child(div().w(px(24.0)).flex().justify_end().text_color(muted_fg).child("1"))
.child(div().flex().children(COMMAND.map(|(text, token)| {
div().whitespace_nowrap().text_color(token_color(token, theme)).child(text)
}))),
);
let liked = self.feedback == Some(Feedback::Like);
let disliked = self.feedback == Some(Feedback::Dislike);
let reply_actions = div()
.flex()
.items_center()
.child(tip(
"copy",
if self.copied { "Copied" } else { "Copy" },
action("copy", if self.copied { CHECK } else { COPY })
.on_click(cx.listener(|this, _, _, cx| this.copy(false, cx))),
))
.child(tip(
"like",
"Good response",
action("like", if liked { THUMBS_UP_FILLED } else { THUMBS_UP }).on_click(cx.listener(
|this, _, _, cx| {
this.feedback = (this.feedback != Some(Feedback::Like)).then_some(Feedback::Like);
cx.notify();
},
)),
))
.child(tip(
"dislike",
"Bad response",
action("dislike", if disliked { THUMBS_DOWN_FILLED } else { THUMBS_DOWN }).on_click(cx.listener(
|this, _, _, cx| {
this.feedback = (this.feedback != Some(Feedback::Dislike)).then_some(Feedback::Dislike);
cx.notify();
},
)),
))
.child(tip("retry", "Retry", action("retry", REFRESH_CCW)));
div()
.w(px(448.0))
.flex()
.flex_col()
.gap_8()
.py_6()
.text_sm()
// shadcn's text-sm: 14px on a 20px line.
.line_height(px(20.0))
.child(
Message::new()
.align(MessageAlign::End)
.gap(px(8.0))
.child(Bubble::new("question").align(BubbleAlign::End).variant(BubbleVariant::Muted).child(QUESTION))
.footer(
div()
.flex()
.child(tip("ask-copy", "Copy", action("ask-copy", COPY)))
.child(tip("edit", "Edit", action("edit", PENCIL))),
),
)
.child(
// The reply has no bubble, so its actions line up with the text (`px-0`).
Message::new()
.gap(px(8.0))
.flush()
.child(
div()
.w_full()
.flex()
.flex_col()
.gap_4()
.child(paragraph(INSTALL, window, cx))
.child(code_block)
.child(paragraph(WRAP, window, cx)),
)
.footer(reply_actions),
)
}
}Installation
Add the components
$ cargo hyuskui add bubble message tooltip iconsCopy the pattern
Paste the code into
src/ai/message.rsand declare the module. The demo plays scripted data on a timer; drive it from your agent's events instead.src/ai/message.rs use std::time::Duration; use gpui::{ div, prelude::*, px, AnyElement, App, ClipboardItem, Context, Font, FontWeight, Hsla, Pixels, SharedString, Task, TextRun, Window, }; use crate::icons::{icon, CHECK, COPY, PENCIL, REFRESH_CCW, THUMBS_DOWN, THUMBS_DOWN_FILLED, THUMBS_UP, THUMBS_UP_FILLED}; use crate::theme::{ActiveTheme, Theme}; use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant}; use crate::ui::message::{Message, MessageAlign}; use crate::ui::tooltip::Tooltip; const MONO: &str = "Geist Mono"; /// How long Copy shows its check, like the demo's 2000ms timeout. const COPIED: Duration = Duration::from_millis(2000); const QUESTION: &str = "How do I add a settings dialog? It should open from the gear icon in the header."; /// The reply's markdown source, for the clipboard. const REPLY: &str = "Install Dialog, then open it from the gear button in `site-header.tsx`.\n\n\ ```bash\nnpx shadcn@latest add dialog\n```\n\n\ Wrap the button in a `DialogTrigger` and put the settings form in `DialogContent`. Focus moves \ into the dialog when it opens, and **Esc** closes it."; const INSTALL: &str = "Install Dialog, then open it from the gear button in `site-header.tsx`."; const WRAP: &str = "Wrap the button in a `DialogTrigger` and put the settings form in `DialogContent`. Focus moves into the dialog when it opens, and **Esc** closes it."; /// shiki's github themes, which the docs' code blocks use. #[derive(Clone, Copy)] enum Token { Plain, Function, String, } const COMMAND: [(&str, Token); 7] = [ ("npx", Token::Function), (" ", Token::Plain), ("shadcn@latest", Token::String), (" ", Token::Plain), ("add", Token::String), (" ", Token::Plain), ("dialog", Token::String), ]; fn token_color(token: Token, theme: &Theme) -> Hsla { let dark = theme.background.l < 0.5; let hex = match (token, dark) { (Token::Plain, false) => 0x24292e, (Token::Function, false) => 0x6f42c1, (Token::String, false) => 0x032f62, (Token::Plain, true) => 0xe1e4e8, (Token::Function, true) => 0xb392f0, (Token::String, true) => 0x9ecbff, }; gpui::rgb(hex).into() } #[derive(Clone, Copy, PartialEq)] enum Feedback { Like, Dislike, } #[derive(Default)] pub struct MessagePattern { copied: bool, code_copied: bool, feedback: Option<Feedback>, /// Replacing a countdown restarts it, so a second copy keeps the check up. copy_reset: Option<Task<()>>, code_reset: Option<Task<()>>, } impl MessagePattern { fn copy(&mut self, code: bool, cx: &mut Context<Self>) { let text = if code { "npx shadcn@latest add dialog" } else { REPLY }; cx.write_to_clipboard(ClipboardItem::new_string(text.to_string())); let reset = cx.spawn(async move |this, cx| { cx.background_executor().timer(COPIED).await; this.update(cx, |this, cx| { if code { this.code_copied = false; } else { this.copied = false; } cx.notify(); }) .ok(); }); if code { self.code_copied = true; self.code_reset = Some(reset); } else { self.copied = true; self.copy_reset = Some(reset); } cx.notify(); } } /// One wrappable unit of a paragraph: words glued together with no space between them, such /// as an inline code span and the comma after it. #[derive(Clone, Copy, PartialEq)] enum Style { Plain, Bold, Code, } /// Lays out one line of markdown (`code` and **bold** only) like a browser paragraph: words /// wrap as units, and inline code is a padded chip that doesn't grow the line. fn paragraph(source: &str, window: &Window, cx: &App) -> AnyElement { let theme = cx.theme(); let (fg, muted) = (theme.foreground, theme.muted); // GPUI rounds each text element's width up to a whole pixel, so a line of one-word // elements drifts wider than the browser's and wraps early. Each unit gets its exact // shaped width instead. let base = window.text_style().font(); let measure = |text: &str, style: Style| -> Pixels { let (font, size) = match style { Style::Plain => (base.clone(), px(14.0)), Style::Bold => (Font { weight: FontWeight::SEMIBOLD, ..base.clone() }, px(14.0)), Style::Code => (gpui::font(MONO), px(12.6)), }; let run = TextRun { len: text.len(), font, color: fg, background_color: None, underline: None, strikethrough: None }; let width = window.text_system().shape_line(SharedString::from(text.to_string()), size, &[run], None).width; if style == Style::Code { width + px(8.0) } else { width } }; // Split into styled runs, then into words that keep their trailing space. let mut atoms: Vec<(Style, String)> = Vec::new(); let mut style = Style::Plain; let mut rest = source; while !rest.is_empty() { let next = [rest.find('`'), rest.find("**")].into_iter().flatten().min(); let end = next.unwrap_or(rest.len()); let run = &rest[..end]; if style == Style::Code { if !run.is_empty() { atoms.push((Style::Code, run.to_string())); } } else { atoms.extend(run.split_inclusive(' ').map(|word| (style, word.to_string()))); } rest = &rest[end..]; if let Some(stripped) = rest.strip_prefix('`') { style = if style == Style::Code { Style::Plain } else { Style::Code }; rest = stripped; } else if let Some(stripped) = rest.strip_prefix("**") { if style != Style::Code { style = if style == Style::Bold { Style::Plain } else { Style::Bold }; } rest = stripped; } } // A word only starts a new unit after whitespace. let mut units: Vec<Vec<(Style, String)>> = Vec::new(); for atom in atoms { let after_space = units .last() .and_then(|unit| unit.last()) .is_none_or(|(_, text)| text.ends_with(' ')); if atom.1.trim().is_empty() { match units.last_mut() { Some(unit) => unit.push(atom), None => units.push(vec![atom]), } } else if after_space { units.push(vec![atom]); } else if let Some(unit) = units.last_mut() { unit.push(atom); } } div() .flex() .flex_wrap() .w_full() .line_height(px(20.0)) .text_color(fg) .children(units.into_iter().map(|unit| { let width: Pixels = unit.iter().map(|(style, text)| measure(text, *style)).fold(px(0.0), |sum, w| sum + w); div().flex().flex_none().w(width).children(unit.into_iter().map(|(style, text)| match style { // shadcn's inline code: 12.6px mono, 2px/4px padding, 6px corners. Its 21px box // hangs below the 20px line rather than growing it. Style::Code => div() .relative() .h(px(20.0)) .px(px(4.0)) .flex() .items_center() .font_family(MONO) .text_size(px(12.6)) .child(div().absolute().top_0().left_0().right_0().h(px(21.0)).rounded(px(6.0)).bg(muted)) .child(div().relative().whitespace_nowrap().child(text)) .into_any_element(), Style::Bold => div() .whitespace_nowrap() .font_weight(FontWeight::SEMIBOLD) .child(text) .into_any_element(), Style::Plain => div().whitespace_nowrap().child(text).into_any_element(), })) })) .into_any_element() } impl Render for MessagePattern { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let theme = cx.theme(); let (fg, muted_fg, muted) = (theme.foreground, theme.muted_foreground, theme.muted); // shadcn's ghost button at size icon-sm. Each one has a tooltip naming it. let action = |id: &'static str, data: &'static [u8]| { div() .id(id) .flex() .flex_none() .items_center() .justify_center() .size(px(28.0)) .rounded_full() .cursor_pointer() .hover(move |style| style.bg(muted)) .active(|style| style.top(px(1.0))) .child(icon(data).size(px(16.0)).text_color(muted_fg)) }; let tip = |id: &'static str, label: &'static str, trigger: gpui::Stateful<gpui::Div>| { Tooltip::new((id, 1usize), label).trigger(trigger) }; let code_block = div() .w_full() .flex() .flex_col() .rounded(px(18.0)) .bg(muted) // shadcn draws a 1px ring of foreground at 5%. .border_1() .border_color(fg.opacity(0.05)) .child( div() .flex() .items_center() .gap_2() .pt(px(15.0)) .px(px(15.0)) .child(div().flex_1().text_sm().font_weight(FontWeight::MEDIUM).text_color(fg).child("bash")) .child( Tooltip::new("code-copy-tip", if self.code_copied { "Copied" } else { "Copy" }).trigger( div() .id("code-copy") .flex() .items_center() .justify_center() .size(px(24.0)) .mr(px(-6.0)) // Like shadcn's `-my-1`, the button doesn't make the header taller. .my(px(-4.0)) .rounded_full() .cursor_pointer() .hover(move |style| style.bg(fg.opacity(0.05))) .on_click(cx.listener(|this, _, _, cx| this.copy(true, cx))) .child( icon(if self.code_copied { CHECK } else { COPY }) .size(px(12.0)) .text_color(muted_fg), ), ), ), ) .child( div() .flex() .gap_3() .pt_2() .pb(px(15.0)) .px(px(15.0)) .font_family(MONO) .text_sm() .line_height(px(22.75)) .child(div().w(px(24.0)).flex().justify_end().text_color(muted_fg).child("1")) .child(div().flex().children(COMMAND.map(|(text, token)| { div().whitespace_nowrap().text_color(token_color(token, theme)).child(text) }))), ); let liked = self.feedback == Some(Feedback::Like); let disliked = self.feedback == Some(Feedback::Dislike); let reply_actions = div() .flex() .items_center() .child(tip( "copy", if self.copied { "Copied" } else { "Copy" }, action("copy", if self.copied { CHECK } else { COPY }) .on_click(cx.listener(|this, _, _, cx| this.copy(false, cx))), )) .child(tip( "like", "Good response", action("like", if liked { THUMBS_UP_FILLED } else { THUMBS_UP }).on_click(cx.listener( |this, _, _, cx| { this.feedback = (this.feedback != Some(Feedback::Like)).then_some(Feedback::Like); cx.notify(); }, )), )) .child(tip( "dislike", "Bad response", action("dislike", if disliked { THUMBS_DOWN_FILLED } else { THUMBS_DOWN }).on_click(cx.listener( |this, _, _, cx| { this.feedback = (this.feedback != Some(Feedback::Dislike)).then_some(Feedback::Dislike); cx.notify(); }, )), )) .child(tip("retry", "Retry", action("retry", REFRESH_CCW))); div() .w(px(448.0)) .flex() .flex_col() .gap_8() .py_6() .text_sm() // shadcn's text-sm: 14px on a 20px line. .line_height(px(20.0)) .child( Message::new() .align(MessageAlign::End) .gap(px(8.0)) .child(Bubble::new("question").align(BubbleAlign::End).variant(BubbleVariant::Muted).child(QUESTION)) .footer( div() .flex() .child(tip("ask-copy", "Copy", action("ask-copy", COPY))) .child(tip("edit", "Edit", action("edit", PENCIL))), ), ) .child( // The reply has no bubble, so its actions line up with the text (`px-0`). Message::new() .gap(px(8.0)) .flush() .child( div() .w_full() .flex() .flex_col() .gap_4() .child(paragraph(INSTALL, window, cx)) .child(code_block) .child(paragraph(WRAP, window, cx)), ) .footer(reply_actions), ) } }