hyuskui

Suggestion

A short prompt you can send to the agent in one click.

Loading GPUI…
use gpui::{
    div, linear_color_stop, linear_gradient, prelude::*, px, Context, Entity,
    KeyDownEvent, ScrollHandle, Subscription, Window,
};

use crate::icons::{icon, ARROW_UP, PLUS};
use crate::theme::ActiveTheme;
use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::input::{InputEvent, TextInput};
use crate::ui::message::{Message, MessageAlign};
use crate::ui::textarea::Textarea;

const SUGGESTIONS: [&str; 6] = [
    "Add a dark mode toggle",
    "Fix the failing build",
    "Write tests for the form",
    "Upgrade to Next.js 16",
    "Add a loading state",
    "Find unused dependencies",
];

const REPLIES: [&str; 6] = [
    "Added a ModeToggle to the site header. It calls setTheme from next-themes.",
    "The build failed on a missing import in app/page.tsx. I added it and the build passes.",
    "Added four tests in signup-form.test.tsx. They cover the empty, invalid and valid states.",
    "Ran the codemod and bumped next to 16. Two routes needed async params, so I updated them.",
    "Added a loading.tsx to the dashboard route. It shows skeletons while the data loads.",
    "Three packages are not imported anywhere: lodash, moment and classnames. Should I remove them?",
];

const FALLBACK: &str = "This demo only knows the suggestions. Pick one.";

/// shadcn's `scroll-fade-x`: the row fades out over `min(12%, 40px)` on whichever side has
/// more to scroll to.
const FADE: f32 = 40.0;

#[derive(Default)]
pub struct SuggestionPattern {
    composer: Option<Entity<TextInput>>,
    _change: Option<Subscription>,
    /// The prompt and reply on screen. Each send replaces the last one.
    turn: Option<(String, &'static str)>,
    chips: ScrollHandle,
    /// The row's scroll extent is only known after its first layout.
    measured: bool,
}

impl SuggestionPattern {
    fn send(&mut self, prompt: String, window: &mut Window, cx: &mut Context<Self>) {
        let reply = SUGGESTIONS
            .iter()
            .position(|suggestion| *suggestion == prompt)
            .map_or(FALLBACK, |ix| REPLIES[ix]);
        self.turn = Some((prompt, reply));
        if let Some(composer) = &self.composer {
            composer.update(cx, |input, cx| input.set_text("", window, cx));
        }
        cx.notify();
    }

    fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let Some(composer) = &self.composer else {
            return;
        };
        let text = composer.read(cx).text().trim().to_string();
        if !text.is_empty() {
            self.send(text, window, cx);
        }
    }
}

impl Render for SuggestionPattern {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        if !self.measured {
            self.measured = true;
            window.request_animation_frame();
        }
        if self.composer.is_none() {
            let composer = cx.new(|cx| {
                Textarea::new(cx)
                    .multi_line(1)
                    .placeholder("Ask the agent to change your code...")
                    .bare()
            });
            // The send button's state follows the text, so re-render on every edit.
            self._change = Some(cx.subscribe(&composer, |_, _, _: &InputEvent, cx| cx.notify()));
            self.composer = Some(composer);
        }
        let Some(composer) = self.composer.clone() else {
            return div();
        };

        let theme = cx.theme();
        let (fg, muted_fg, bg, primary_fg) =
            (theme.foreground, theme.muted_foreground, theme.background, theme.primary_foreground);
        let can_send = !composer.read(cx).text().trim().is_empty();

        // shadcn's outline button at size sm: 28px tall, a pill at its 18px radius.
        let chips = SUGGESTIONS.into_iter().enumerate().map(|(ix, prompt)| {
            div().flex_none().child(
                Button::new(("suggestion", ix), prompt)
                    .variant(ButtonVariant::Outline)
                    .size(ButtonSize::Compact)
                    .rounded_full()
                    .on_click(cx.listener(move |this, _, window, cx| this.send(prompt.to_string(), window, cx))),
            )
        });

        // The fade follows the scroll position: none on a side that is already at its end.
        let offset = -self.chips.offset().x;
        let max = self.chips.max_offset().x;
        let fade = |angle: f32| {
            div()
                .absolute()
                .top_0()
                .bottom_0()
                .w(px(FADE))
                .bg(linear_gradient(angle, linear_color_stop(bg.opacity(0.0), 0.0), linear_color_stop(bg, 1.0)))
        };
        let row = div()
            .relative()
            .w_full()
            .child(
                div()
                    .id("suggestions")
                    .track_scroll(&self.chips)
                    .overflow_x_scroll()
                    .on_scroll(cx.listener(|_, _, _, cx| cx.notify()))
                    .flex()
                    .gap_2()
                    .children(chips),
            )
            .when(offset > px(0.5), |this| this.child(fade(270.0).left_0()))
            .when(offset < max - px(0.5), |this| this.child(fade(90.0).right_0()));

        let attach = Button::new("attach", "")
            .variant(ButtonVariant::Outline)
            .size(ButtonSize::Sm)
            .icon_only()
            .rounded_full()
            .leading(icon(PLUS).size(px(16.0)).text_color(muted_fg));
        let send = Button::new("send", "")
            .size(ButtonSize::Sm)
            .icon_only()
            .rounded_full()
            .disabled(!can_send)
            .leading(icon(ARROW_UP).size(px(16.0)).text_color(primary_fg))
            .on_click(cx.listener(|this, _, window, cx| this.submit(window, cx)));

        // shadcn's prompt `InputGroup`: input/50 fill, 18px corners, the addon row under the text.
        let composer_box = div()
            .w_full()
            .flex()
            .flex_col()
            .rounded(px(18.0))
            .border_1()
            .border_color(gpui::transparent_black())
            .bg(theme.input.opacity(0.5))
            // Enter sends and Shift+Enter breaks the line, like the form's `onKeyDown`.
            .capture_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| {
                let keystroke = &event.keystroke;
                if keystroke.key == "enter" && !keystroke.modifiers.shift {
                    cx.stop_propagation();
                    this.submit(window, cx);
                }
            }))
            .child(div().min_h(px(64.0)).p_3().child(composer))
            .child(
                div()
                    .flex()
                    .items_center()
                    .gap_2()
                    .px(px(10.0))
                    .pt(px(6.0))
                    .pb_2()
                    .child(attach)
                    .child(div().flex_1())
                    .child(send),
            );

        div()
            .w(px(512.0))
            .flex()
            .flex_col()
            .gap_6()
            .py_6()
            .text_sm()
            // shadcn's text-sm: 14px on a 20px line.
            .line_height(px(20.0))
            .when_some(self.turn.clone(), |this, (prompt, reply)| {
                this.child(
                    div()
                        .flex()
                        .flex_col()
                        .gap_4()
                        .child(
                            Message::new().align(MessageAlign::End).child(
                                Bubble::new("prompt")
                                    .align(BubbleAlign::End)
                                    .variant(BubbleVariant::Muted)
                                    .child(prompt),
                            ),
                        )
                        .child(Message::new().child(div().w_full().text_color(fg).child(reply))),
                )
            })
            .child(div().flex().flex_col().gap_2().child(row).child(composer_box))
    }
}

Installation

  1. Add the components

    $ cargo hyuskui add bubble button input message textarea icons

    Uses Bubble, Button, Input, Message and Textarea.

  2. Copy the pattern

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

    src/ai/suggestion.rs
    use gpui::{
        div, linear_color_stop, linear_gradient, prelude::*, px, Context, Entity,
        KeyDownEvent, ScrollHandle, Subscription, Window,
    };
    
    use crate::icons::{icon, ARROW_UP, PLUS};
    use crate::theme::ActiveTheme;
    use crate::ui::bubble::{Bubble, BubbleAlign, BubbleVariant};
    use crate::ui::button::{Button, ButtonSize, ButtonVariant};
    use crate::ui::input::{InputEvent, TextInput};
    use crate::ui::message::{Message, MessageAlign};
    use crate::ui::textarea::Textarea;
    
    const SUGGESTIONS: [&str; 6] = [
        "Add a dark mode toggle",
        "Fix the failing build",
        "Write tests for the form",
        "Upgrade to Next.js 16",
        "Add a loading state",
        "Find unused dependencies",
    ];
    
    const REPLIES: [&str; 6] = [
        "Added a ModeToggle to the site header. It calls setTheme from next-themes.",
        "The build failed on a missing import in app/page.tsx. I added it and the build passes.",
        "Added four tests in signup-form.test.tsx. They cover the empty, invalid and valid states.",
        "Ran the codemod and bumped next to 16. Two routes needed async params, so I updated them.",
        "Added a loading.tsx to the dashboard route. It shows skeletons while the data loads.",
        "Three packages are not imported anywhere: lodash, moment and classnames. Should I remove them?",
    ];
    
    const FALLBACK: &str = "This demo only knows the suggestions. Pick one.";
    
    /// shadcn's `scroll-fade-x`: the row fades out over `min(12%, 40px)` on whichever side has
    /// more to scroll to.
    const FADE: f32 = 40.0;
    
    #[derive(Default)]
    pub struct SuggestionPattern {
        composer: Option<Entity<TextInput>>,
        _change: Option<Subscription>,
        /// The prompt and reply on screen. Each send replaces the last one.
        turn: Option<(String, &'static str)>,
        chips: ScrollHandle,
        /// The row's scroll extent is only known after its first layout.
        measured: bool,
    }
    
    impl SuggestionPattern {
        fn send(&mut self, prompt: String, window: &mut Window, cx: &mut Context<Self>) {
            let reply = SUGGESTIONS
                .iter()
                .position(|suggestion| *suggestion == prompt)
                .map_or(FALLBACK, |ix| REPLIES[ix]);
            self.turn = Some((prompt, reply));
            if let Some(composer) = &self.composer {
                composer.update(cx, |input, cx| input.set_text("", window, cx));
            }
            cx.notify();
        }
    
        fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
            let Some(composer) = &self.composer else {
                return;
            };
            let text = composer.read(cx).text().trim().to_string();
            if !text.is_empty() {
                self.send(text, window, cx);
            }
        }
    }
    
    impl Render for SuggestionPattern {
        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            if !self.measured {
                self.measured = true;
                window.request_animation_frame();
            }
            if self.composer.is_none() {
                let composer = cx.new(|cx| {
                    Textarea::new(cx)
                        .multi_line(1)
                        .placeholder("Ask the agent to change your code...")
                        .bare()
                });
                // The send button's state follows the text, so re-render on every edit.
                self._change = Some(cx.subscribe(&composer, |_, _, _: &InputEvent, cx| cx.notify()));
                self.composer = Some(composer);
            }
            let Some(composer) = self.composer.clone() else {
                return div();
            };
    
            let theme = cx.theme();
            let (fg, muted_fg, bg, primary_fg) =
                (theme.foreground, theme.muted_foreground, theme.background, theme.primary_foreground);
            let can_send = !composer.read(cx).text().trim().is_empty();
    
            // shadcn's outline button at size sm: 28px tall, a pill at its 18px radius.
            let chips = SUGGESTIONS.into_iter().enumerate().map(|(ix, prompt)| {
                div().flex_none().child(
                    Button::new(("suggestion", ix), prompt)
                        .variant(ButtonVariant::Outline)
                        .size(ButtonSize::Compact)
                        .rounded_full()
                        .on_click(cx.listener(move |this, _, window, cx| this.send(prompt.to_string(), window, cx))),
                )
            });
    
            // The fade follows the scroll position: none on a side that is already at its end.
            let offset = -self.chips.offset().x;
            let max = self.chips.max_offset().x;
            let fade = |angle: f32| {
                div()
                    .absolute()
                    .top_0()
                    .bottom_0()
                    .w(px(FADE))
                    .bg(linear_gradient(angle, linear_color_stop(bg.opacity(0.0), 0.0), linear_color_stop(bg, 1.0)))
            };
            let row = div()
                .relative()
                .w_full()
                .child(
                    div()
                        .id("suggestions")
                        .track_scroll(&self.chips)
                        .overflow_x_scroll()
                        .on_scroll(cx.listener(|_, _, _, cx| cx.notify()))
                        .flex()
                        .gap_2()
                        .children(chips),
                )
                .when(offset > px(0.5), |this| this.child(fade(270.0).left_0()))
                .when(offset < max - px(0.5), |this| this.child(fade(90.0).right_0()));
    
            let attach = Button::new("attach", "")
                .variant(ButtonVariant::Outline)
                .size(ButtonSize::Sm)
                .icon_only()
                .rounded_full()
                .leading(icon(PLUS).size(px(16.0)).text_color(muted_fg));
            let send = Button::new("send", "")
                .size(ButtonSize::Sm)
                .icon_only()
                .rounded_full()
                .disabled(!can_send)
                .leading(icon(ARROW_UP).size(px(16.0)).text_color(primary_fg))
                .on_click(cx.listener(|this, _, window, cx| this.submit(window, cx)));
    
            // shadcn's prompt `InputGroup`: input/50 fill, 18px corners, the addon row under the text.
            let composer_box = div()
                .w_full()
                .flex()
                .flex_col()
                .rounded(px(18.0))
                .border_1()
                .border_color(gpui::transparent_black())
                .bg(theme.input.opacity(0.5))
                // Enter sends and Shift+Enter breaks the line, like the form's `onKeyDown`.
                .capture_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| {
                    let keystroke = &event.keystroke;
                    if keystroke.key == "enter" && !keystroke.modifiers.shift {
                        cx.stop_propagation();
                        this.submit(window, cx);
                    }
                }))
                .child(div().min_h(px(64.0)).p_3().child(composer))
                .child(
                    div()
                        .flex()
                        .items_center()
                        .gap_2()
                        .px(px(10.0))
                        .pt(px(6.0))
                        .pb_2()
                        .child(attach)
                        .child(div().flex_1())
                        .child(send),
                );
    
            div()
                .w(px(512.0))
                .flex()
                .flex_col()
                .gap_6()
                .py_6()
                .text_sm()
                // shadcn's text-sm: 14px on a 20px line.
                .line_height(px(20.0))
                .when_some(self.turn.clone(), |this, (prompt, reply)| {
                    this.child(
                        div()
                            .flex()
                            .flex_col()
                            .gap_4()
                            .child(
                                Message::new().align(MessageAlign::End).child(
                                    Bubble::new("prompt")
                                        .align(BubbleAlign::End)
                                        .variant(BubbleVariant::Muted)
                                        .child(prompt),
                                ),
                            )
                            .child(Message::new().child(div().w_full().text_color(fg).child(reply))),
                    )
                })
                .child(div().flex().flex_col().gap_2().child(row).child(composer_box))
        }
    }