Skip to main content

gpui_component/
bubble.rs

1use gpui::{
2    AnyElement, App, IntoElement, ParentElement, RenderOnce, StyleRefinement, Styled, Window, div,
3    prelude::FluentBuilder as _, relative, rems,
4};
5
6use crate::{
7    ActiveTheme as _, Colorize as _, StyledExt as _, button::Button, message::MessageAlignment,
8    v_flex,
9};
10
11/// Visual treatment for a chat bubble.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13pub enum BubbleVariant {
14    /// A filled primary surface.
15    #[default]
16    Filled,
17    /// A neutral secondary surface.
18    Secondary,
19    /// A lower-emphasis surface.
20    Muted,
21    /// A subtle primary-tinted surface.
22    Tinted,
23    /// A background surface with a visible border.
24    Outline,
25    /// No surface, padding, or border.
26    Ghost,
27    /// A destructive surface for failed or invalid content.
28    Destructive,
29}
30
31/// Edge on which reaction feedback is attached.
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33pub enum BubbleReactionSide {
34    /// Attach reactions above the bubble.
35    Top,
36    /// Attach reactions below the bubble.
37    #[default]
38    Bottom,
39}
40
41/// A chat bubble layout that owns alignment, width, and reaction positioning.
42///
43/// The visible surface is rendered by [`BubbleContent`]. Direct children are
44/// added to that content slot as a convenience.
45#[derive(IntoElement)]
46pub struct Bubble {
47    style: StyleRefinement,
48    alignment: Option<MessageAlignment>,
49    variant: BubbleVariant,
50    content: BubbleContent,
51    reactions: Option<BubbleReactions>,
52}
53
54impl Bubble {
55    /// Create a filled bubble that can inherit alignment from its parent.
56    pub fn new() -> Self {
57        Self {
58            style: StyleRefinement::default(),
59            alignment: None,
60            variant: BubbleVariant::Filled,
61            content: BubbleContent::new(),
62            reactions: None,
63        }
64    }
65
66    /// Set the bubble alignment.
67    pub fn alignment(mut self, alignment: MessageAlignment) -> Self {
68        self.alignment = Some(alignment);
69        self
70    }
71
72    /// Set the visual treatment.
73    pub fn with_variant(mut self, variant: BubbleVariant) -> Self {
74        self.variant = variant;
75        self
76    }
77
78    pub(crate) fn is_ghost(&self) -> bool {
79        self.variant == BubbleVariant::Ghost
80    }
81
82    /// Replace the visible content surface.
83    ///
84    /// Children already added directly to the bubble move into the new
85    /// surface, in front of its own children, so `.child(...)` composes the
86    /// same way on either side of this call.
87    pub fn content(mut self, mut content: BubbleContent) -> Self {
88        let mut children = std::mem::take(&mut self.content.children);
89        children.append(&mut content.children);
90        content.children = children;
91        self.content = content;
92        self
93    }
94
95    /// Set an optional reaction region anchored to the bubble edge.
96    pub fn reactions(mut self, reactions: BubbleReactions) -> Self {
97        self.reactions = Some(reactions);
98        self
99    }
100}
101
102impl Default for Bubble {
103    fn default() -> Self {
104        Self::new()
105    }
106}
107
108impl ParentElement for Bubble {
109    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
110        self.content.children.extend(elements);
111    }
112}
113
114impl Styled for Bubble {
115    fn style(&mut self) -> &mut StyleRefinement {
116        &mut self.style
117    }
118}
119
120impl RenderOnce for Bubble {
121    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
122        let variant = self.variant;
123        let mut content = self.content;
124        content.variant = variant;
125        content.alignment = self.alignment;
126
127        div()
128            .relative()
129            .flex()
130            .min_w_0()
131            .flex_col()
132            .flex_none()
133            .gap_1()
134            .max_w(relative(0.8))
135            .when(variant == BubbleVariant::Ghost, |this| {
136                this.w_full().max_w_full()
137            })
138            .when_some(self.alignment, |this, alignment| {
139                if alignment.is_right(cx) {
140                    this.self_end().ml_auto()
141                } else {
142                    this.self_start().mr_auto()
143                }
144            })
145            .refine_style(&self.style)
146            .child(content)
147            .when_some(self.reactions, |this, reactions| this.child(reactions))
148    }
149}
150
151/// The visible surface inside a [`Bubble`].
152///
153/// This part owns padding, radius, border, typography, and semantic colors so
154/// callers can refine the surface without changing the bubble's row layout.
155#[derive(IntoElement)]
156pub struct BubbleContent {
157    style: StyleRefinement,
158    variant: BubbleVariant,
159    alignment: Option<MessageAlignment>,
160    children: Vec<AnyElement>,
161}
162
163impl BubbleContent {
164    /// Create an empty bubble content surface.
165    pub fn new() -> Self {
166        Self {
167            style: StyleRefinement::default(),
168            variant: BubbleVariant::default(),
169            alignment: None,
170            children: Vec::new(),
171        }
172    }
173}
174
175impl Default for BubbleContent {
176    fn default() -> Self {
177        Self::new()
178    }
179}
180
181impl ParentElement for BubbleContent {
182    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
183        self.children.extend(elements);
184    }
185}
186
187impl Styled for BubbleContent {
188    fn style(&mut self) -> &mut StyleRefinement {
189        &mut self.style
190    }
191}
192
193impl RenderOnce for BubbleContent {
194    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
195        let tokens = cx.theme().semantic_tokens();
196
197        div()
198            .min_w_0()
199            .max_w_full()
200            // A ghost bubble has no surface to clip against; clipping would
201            // only cut the shadows and overhanging controls of rich content.
202            .when(self.variant != BubbleVariant::Ghost, |this| {
203                this.overflow_hidden()
204            })
205            .rounded(cx.theme().radius_2xl())
206            .border_1()
207            .border_color(cx.theme().transparent)
208            .px_3()
209            .py_2()
210            .text_sm()
211            .line_height(relative(1.625))
212            .when_some(self.alignment, |this, alignment| {
213                if alignment.is_right(cx) {
214                    this.self_end()
215                } else {
216                    this.self_start()
217                }
218            })
219            .map(|this| match self.variant {
220                BubbleVariant::Filled => this
221                    .bg(tokens.colors.primary)
222                    .text_color(tokens.colors.primary_foreground),
223                // The theme's `secondary` role is tuned for buttons and sits a
224                // tier darker than shadcn's conversation secondary; the
225                // near-background `muted` tier matches shadcn's value in both
226                // light and dark themes.
227                BubbleVariant::Secondary => this
228                    .bg(tokens.colors.muted)
229                    .text_color(tokens.colors.secondary_foreground),
230                BubbleVariant::Muted => this
231                    .bg(tokens.colors.muted)
232                    .text_color(tokens.colors.foreground),
233                BubbleVariant::Tinted => this
234                    .bg(tokens.colors.primary.mix_oklab(
235                        tokens.colors.background,
236                        if cx.theme().is_dark() { 0.24 } else { 0.12 },
237                    ))
238                    .text_color(tokens.colors.foreground),
239                BubbleVariant::Outline => this
240                    .border_color(tokens.colors.border)
241                    .bg(tokens.colors.background)
242                    .text_color(tokens.colors.foreground),
243                BubbleVariant::Ghost => this
244                    .rounded(tokens.radius.none)
245                    .border_0()
246                    .bg(cx.theme().transparent)
247                    .text_color(tokens.colors.foreground)
248                    .p_0(),
249                BubbleVariant::Destructive => this
250                    .bg(tokens.colors.destructive.opacity(if cx.theme().is_dark() {
251                        0.2
252                    } else {
253                        0.1
254                    }))
255                    .text_color(tokens.colors.destructive),
256            })
257            .refine_style(&self.style)
258            .children(self.children)
259    }
260}
261
262/// A vertical stack of consecutive bubbles from one sender.
263#[derive(IntoElement)]
264pub struct BubbleGroup {
265    style: StyleRefinement,
266    children: Vec<AnyElement>,
267}
268
269impl BubbleGroup {
270    /// Create an empty bubble group.
271    pub fn new() -> Self {
272        Self {
273            style: StyleRefinement::default(),
274            children: Vec::new(),
275        }
276    }
277}
278
279impl Default for BubbleGroup {
280    fn default() -> Self {
281        Self::new()
282    }
283}
284
285impl ParentElement for BubbleGroup {
286    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
287        self.children.extend(elements);
288    }
289}
290
291impl Styled for BubbleGroup {
292    fn style(&mut self) -> &mut StyleRefinement {
293        &mut self.style
294    }
295}
296
297impl RenderOnce for BubbleGroup {
298    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
299        v_flex()
300            .min_w_0()
301            .gap_2()
302            .refine_style(&self.style)
303            .children(self.children)
304    }
305}
306
307enum BubbleReactionChild {
308    Action(Box<Button>),
309    Element(AnyElement),
310}
311
312/// A styleable reaction region positioned on a bubble edge.
313///
314/// Compose existing [`crate::button::Button`] values inside this region to
315/// preserve button semantics and keyboard behavior.
316#[derive(IntoElement)]
317pub struct BubbleReactions {
318    style: StyleRefinement,
319    side: BubbleReactionSide,
320    alignment: MessageAlignment,
321    children: Vec<BubbleReactionChild>,
322}
323
324impl BubbleReactions {
325    /// Create a trailing-aligned reaction region on the lower edge.
326    pub fn new() -> Self {
327        Self {
328            style: StyleRefinement::default(),
329            side: BubbleReactionSide::Bottom,
330            alignment: MessageAlignment::End,
331            children: Vec::new(),
332        }
333    }
334
335    /// Set the edge on which reactions are positioned.
336    pub fn side(mut self, side: BubbleReactionSide) -> Self {
337        self.side = side;
338        self
339    }
340
341    /// Set the reaction region alignment along the bubble edge.
342    pub fn alignment(mut self, alignment: MessageAlignment) -> Self {
343        self.alignment = alignment;
344        self
345    }
346
347    /// Add an interactive action that shares the reaction surface.
348    ///
349    /// Typed actions remove the reaction region's decorative content padding
350    /// and use the theme's full radius so the button reads as part of one
351    /// surface. The typed action owns that pill geometry; use `.child(...)`
352    /// for emoji, labels, and arbitrary elements when the child should retain
353    /// its own styling, including a custom button radius.
354    pub fn action(mut self, action: Button) -> Self {
355        self.children
356            .push(BubbleReactionChild::Action(Box::new(action)));
357        self
358    }
359}
360
361impl Default for BubbleReactions {
362    fn default() -> Self {
363        Self::new()
364    }
365}
366
367impl ParentElement for BubbleReactions {
368    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
369        self.children
370            .extend(elements.into_iter().map(BubbleReactionChild::Element));
371    }
372}
373
374impl Styled for BubbleReactions {
375    fn style(&mut self) -> &mut StyleRefinement {
376        &mut self.style
377    }
378}
379
380impl RenderOnce for BubbleReactions {
381    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
382        let tokens = cx.theme().semantic_tokens();
383        let has_action = self
384            .children
385            .iter()
386            .any(|child| matches!(child, BubbleReactionChild::Action(_)));
387        let action_radius = cx.theme().radius_full();
388        let children = self.children.into_iter().map(move |child| match child {
389            BubbleReactionChild::Action(action) => {
390                (*action).rounded(action_radius).into_any_element()
391            }
392            BubbleReactionChild::Element(element) => element,
393        });
394
395        div()
396            .absolute()
397            .flex()
398            .flex_none()
399            .items_center()
400            .justify_center()
401            .gap_1()
402            .rounded(cx.theme().radius_full())
403            .border_3()
404            .border_color(tokens.colors.background)
405            .bg(tokens.colors.muted)
406            .text_color(tokens.colors.foreground)
407            .when(!has_action, |this| this.px_1p5().py_0p5())
408            .text_sm()
409            // Approximates shadcn's `translate-y-3/4`: GPUI cannot offset by a
410            // fraction of the pill's own height, so this fixed value leaves
411            // about three quarters of the default pill outside the bubble.
412            .when(self.side == BubbleReactionSide::Top, |this| {
413                this.top(-rems(1.25))
414            })
415            .when(self.side == BubbleReactionSide::Bottom, |this| {
416                this.bottom(-rems(1.25))
417            })
418            .map(|this| {
419                if self.alignment.is_right(cx) {
420                    this.right_3()
421                } else {
422                    this.left_3()
423                }
424            })
425            .refine_style(&self.style)
426            .children(children)
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    #[test]
435    fn test_bubble_builder() {
436        let bubble = Bubble::new()
437            .alignment(MessageAlignment::End)
438            .with_variant(BubbleVariant::Outline)
439            .content(BubbleContent::new().child("Hello"))
440            .reactions(BubbleReactions::new().child("👍"));
441
442        assert_eq!(bubble.alignment, Some(MessageAlignment::End));
443        assert_eq!(bubble.variant, BubbleVariant::Outline);
444        assert_eq!(bubble.content.children.len(), 1);
445        assert!(bubble.reactions.is_some());
446
447        // Direct children survive a later `content(...)` call and stay in
448        // front of the new surface's own children.
449        let reordered = Bubble::new()
450            .child("Existing")
451            .content(BubbleContent::new().child("Configured"));
452        assert_eq!(reordered.content.children.len(), 2);
453
454        let group = BubbleGroup::new().child("First").child("Second");
455        assert_eq!(group.children.len(), 2);
456
457        let reactions = BubbleReactions::new()
458            .side(BubbleReactionSide::Top)
459            .alignment(MessageAlignment::Start)
460            .child("👍 2");
461
462        assert_eq!(reactions.side, BubbleReactionSide::Top);
463        assert_eq!(reactions.alignment, MessageAlignment::Start);
464        assert_eq!(reactions.children.len(), 1);
465
466        let reactions = BubbleReactions::new()
467            .action(Button::new("reaction-action"))
468            .child("👍");
469        assert_eq!(reactions.children.len(), 2);
470        assert!(matches!(
471            reactions.children.first(),
472            Some(BubbleReactionChild::Action(_))
473        ));
474        assert!(matches!(
475            reactions.children.get(1),
476            Some(BubbleReactionChild::Element(_))
477        ));
478    }
479}