Skip to main content

gpui_component/
message.rs

1use gpui::{
2    AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce,
3    StatefulInteractiveElement as _, StyleRefinement, Styled, Window, prelude::FluentBuilder as _,
4    relative, rems,
5};
6use gpui_base::LogicalStyledExt as _;
7
8use crate::{ActiveTheme as _, RoleOverride, StyledExt as _, bubble::Bubble, h_flex, v_flex};
9
10/// Horizontal alignment for a message and message-owned chat surfaces.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12pub enum MessageAlignment {
13    /// Place the message at the leading edge.
14    #[default]
15    Start,
16    /// Place the message at the trailing edge.
17    End,
18}
19
20impl MessageAlignment {
21    /// Whether this alignment puts the message on the physical right under
22    /// the global layout direction: `End` in LTR, `Start` in RTL.
23    pub(crate) fn is_right(self, cx: &App) -> bool {
24        (self == Self::End) != gpui_base::LayoutDirection::global(cx).is_rtl()
25    }
26}
27
28/// A vertical stack of consecutive messages from the same sender.
29#[derive(IntoElement)]
30pub struct MessageGroup {
31    style: StyleRefinement,
32    children: Vec<AnyElement>,
33}
34
35impl MessageGroup {
36    /// Create an empty message group.
37    pub fn new() -> Self {
38        Self {
39            style: StyleRefinement::default(),
40            children: Vec::new(),
41        }
42    }
43}
44
45impl Default for MessageGroup {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl ParentElement for MessageGroup {
52    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
53        self.children.extend(elements);
54    }
55}
56
57impl Styled for MessageGroup {
58    fn style(&mut self) -> &mut StyleRefinement {
59        &mut self.style
60    }
61}
62
63impl RenderOnce for MessageGroup {
64    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
65        v_flex()
66            .min_w_0()
67            .gap_2()
68            .refine_style(&self.style)
69            .children(self.children)
70    }
71}
72
73/// A composable message row with named avatar, header, content, and footer slots.
74///
75/// Named slots let the message apply its alignment consistently while every
76/// part remains independently styleable.
77#[derive(IntoElement)]
78pub struct Message {
79    id: Option<ElementId>,
80    role: RoleOverride,
81    style: StyleRefinement,
82    stack_style: StyleRefinement,
83    alignment: MessageAlignment,
84    avatar: Option<MessageAvatar>,
85    header: Option<MessageHeader>,
86    content: Option<MessageContent>,
87    footer: Option<MessageFooter>,
88}
89
90impl Message {
91    /// Create a leading-aligned message.
92    pub fn new() -> Self {
93        Self {
94            id: None,
95            role: RoleOverride::default(),
96            style: StyleRefinement::default(),
97            stack_style: StyleRefinement::default(),
98            alignment: MessageAlignment::Start,
99            avatar: None,
100            header: None,
101            content: None,
102            footer: None,
103        }
104    }
105
106    /// Set whether the message is aligned to the leading or trailing edge.
107    pub fn alignment(mut self, alignment: MessageAlignment) -> Self {
108        self.alignment = alignment;
109        self
110    }
111
112    /// Set a stable identity so the message can appear in the accessibility
113    /// tree and keep element state across frames.
114    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
115        self.id = Some(id.into());
116        self
117    }
118
119    /// Set the accessibility role announced for this message.
120    ///
121    /// A message is presentational by default. Give the rows of a transcript
122    /// a role such as [`gpui::Role::ListItem`] so assistive technology can
123    /// move between them. Accessibility nodes need a stable identity, so the
124    /// role takes effect only together with [`Self::id`].
125    pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
126        self.role = role.into();
127        self
128    }
129
130    /// Refine the inner vertical stack that contains the named slots.
131    pub fn with_stack_style(mut self, style: StyleRefinement) -> Self {
132        self.stack_style = style;
133        self
134    }
135
136    /// Set an optional avatar or other sender identity element.
137    pub fn avatar(mut self, avatar: impl IntoElement) -> Self {
138        self.avatar = Some(MessageAvatar::new().child(avatar));
139        self
140    }
141
142    /// Set a fully configured avatar slot.
143    pub fn avatar_slot(mut self, avatar: MessageAvatar) -> Self {
144        self.avatar = Some(avatar);
145        self
146    }
147
148    /// Set the message header.
149    pub fn header(mut self, header: MessageHeader) -> Self {
150        self.header = Some(header);
151        self
152    }
153
154    /// Set the message body.
155    pub fn content(mut self, content: MessageContent) -> Self {
156        self.content = Some(content);
157        self
158    }
159
160    /// Set the message footer.
161    pub fn footer(mut self, footer: MessageFooter) -> Self {
162        self.footer = Some(footer);
163        self
164    }
165}
166
167impl Default for Message {
168    fn default() -> Self {
169        Self::new()
170    }
171}
172
173impl Styled for Message {
174    fn style(&mut self) -> &mut StyleRefinement {
175        &mut self.style
176    }
177}
178
179impl RenderOnce for Message {
180    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
181        let alignment = self.alignment;
182        let is_right = alignment.is_right(cx);
183        let has_avatar = self.avatar.is_some();
184        let has_ghost_bubble = self
185            .content
186            .as_ref()
187            .is_some_and(|content| content.has_ghost_bubble);
188        let stack_style = self.stack_style;
189        let role = self.role;
190
191        // No text size or line height here: the header and footer set their
192        // own, and content typography belongs to the bubble or the caller.
193        let row = v_flex()
194            .relative()
195            .w_full()
196            .min_w_0()
197            .gap(rems(0.625))
198            .map(|this| {
199                if is_right {
200                    this.items_end()
201                } else {
202                    this.items_start()
203                }
204            })
205            .refine_style(&self.style)
206            .child(
207                // The footer lives outside this row so the bottom-anchored
208                // avatar always sits flush with the content's bottom edge,
209                // whatever the footer contains.
210                h_flex()
211                    .w_full()
212                    .min_w_0()
213                    .items_end()
214                    .gap_2()
215                    .when(is_right, |this| this.flex_row_reverse())
216                    .when_some(self.avatar, |this, avatar| this.child(avatar))
217                    .child(
218                        v_flex()
219                            .w_full()
220                            .min_w_0()
221                            .gap(rems(0.625))
222                            .map(|this| {
223                                if is_right {
224                                    this.items_end()
225                                } else {
226                                    this.items_start()
227                                }
228                            })
229                            .refine_style(&stack_style)
230                            .when_some(self.header, |this, header| {
231                                this.child(header.with_inherited_content_inset(!has_ghost_bubble))
232                            })
233                            .when_some(self.content, |this, content| {
234                                this.child(content.aligned(alignment))
235                            }),
236                    ),
237            )
238            .when_some(self.footer, |this, footer| {
239                this.child(
240                    footer
241                        .with_inherited_content_inset(!has_ghost_bubble)
242                        // Align the footer with the content column: the
243                        // avatar's shared `size-8` baseline plus the row gap.
244                        .when(has_avatar && !is_right, |this| this.ml(rems(2.5)))
245                        .when(has_avatar && is_right, |this| this.mr(rems(2.5))),
246                )
247            });
248
249        // `role` lives on the stateful element: accessibility nodes need the
250        // stable identity that only an element id provides.
251        match (self.id, role) {
252            (Some(id), RoleOverride::Role(role)) => row.id(id).role(role).into_any_element(),
253            (Some(id), _) => row.id(id).into_any_element(),
254            (None, _) => row.into_any_element(),
255        }
256    }
257}
258
259/// The sender identity slot rendered beside a [`Message`].
260///
261/// The slot reserves the shared `size-8` baseline; the message row keeps it
262/// flush with the bottom edge of the visible message surface.
263#[derive(IntoElement)]
264pub struct MessageAvatar {
265    style: StyleRefinement,
266    children: Vec<AnyElement>,
267}
268
269impl MessageAvatar {
270    /// Create an empty avatar slot.
271    pub fn new() -> Self {
272        Self {
273            style: StyleRefinement::default(),
274            children: Vec::new(),
275        }
276    }
277}
278
279impl Default for MessageAvatar {
280    fn default() -> Self {
281        Self::new()
282    }
283}
284
285impl ParentElement for MessageAvatar {
286    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
287        self.children.extend(elements);
288    }
289}
290
291impl Styled for MessageAvatar {
292    fn style(&mut self) -> &mut StyleRefinement {
293        &mut self.style
294    }
295}
296
297impl RenderOnce for MessageAvatar {
298    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
299        let tokens = cx.theme().semantic_tokens();
300
301        h_flex()
302            .relative()
303            .min_w_8()
304            .flex_none()
305            .items_center()
306            .justify_center()
307            .self_end()
308            .overflow_hidden()
309            .rounded(cx.theme().radius_full())
310            .bg(tokens.colors.muted)
311            .refine_style(&self.style)
312            .children(self.children)
313    }
314}
315
316/// Header content such as a sender name and timestamp.
317#[derive(IntoElement)]
318pub struct MessageHeader {
319    style: StyleRefinement,
320    content_inset: Option<bool>,
321    children: Vec<AnyElement>,
322}
323
324impl MessageHeader {
325    /// Create an empty message header.
326    pub fn new() -> Self {
327        Self {
328            style: StyleRefinement::default(),
329            content_inset: None,
330            children: Vec::new(),
331        }
332    }
333
334    /// Set whether the header keeps its default horizontal content inset.
335    pub fn content_inset(mut self, content_inset: bool) -> Self {
336        self.content_inset = Some(content_inset);
337        self
338    }
339
340    fn with_inherited_content_inset(mut self, content_inset: bool) -> Self {
341        self.content_inset.get_or_insert(content_inset);
342        self
343    }
344}
345
346impl Default for MessageHeader {
347    fn default() -> Self {
348        Self::new()
349    }
350}
351
352impl ParentElement for MessageHeader {
353    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
354        self.children.extend(elements);
355    }
356}
357
358impl Styled for MessageHeader {
359    fn style(&mut self) -> &mut StyleRefinement {
360        &mut self.style
361    }
362}
363
364impl RenderOnce for MessageHeader {
365    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
366        let tokens = cx.theme().semantic_tokens();
367
368        h_flex()
369            .flex_row_dir(cx)
370            .max_w_full()
371            .min_w_0()
372            .gap_1()
373            .text_xs()
374            .line_height(relative(1.25))
375            .font_medium()
376            .text_color(tokens.colors.muted_foreground)
377            .when(self.content_inset.unwrap_or(true), |this| this.px_3())
378            .refine_style(&self.style)
379            .children(self.children)
380    }
381}
382
383/// The message body slot. It can contain bubbles, images, code, or files.
384#[derive(IntoElement)]
385pub struct MessageContent {
386    style: StyleRefinement,
387    alignment: MessageAlignment,
388    has_ghost_bubble: bool,
389    children: Vec<AnyElement>,
390}
391
392impl MessageContent {
393    /// Create an empty message body.
394    pub fn new() -> Self {
395        Self {
396            style: StyleRefinement::default(),
397            alignment: MessageAlignment::Start,
398            has_ghost_bubble: false,
399            children: Vec::new(),
400        }
401    }
402
403    /// Add a typed bubble and inherit ghost-surface metadata layout.
404    ///
405    /// Ordinary `.child(...)` content remains available for arbitrary elements;
406    /// use this builder when surrounding message slots should react to a
407    /// bubble's variant.
408    pub fn bubble(mut self, bubble: Bubble) -> Self {
409        self.has_ghost_bubble |= bubble.is_ghost();
410        self.children.push(bubble.into_any_element());
411        self
412    }
413
414    fn aligned(mut self, alignment: MessageAlignment) -> Self {
415        self.alignment = alignment;
416        self
417    }
418}
419
420impl Default for MessageContent {
421    fn default() -> Self {
422        Self::new()
423    }
424}
425
426impl ParentElement for MessageContent {
427    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
428        self.children.extend(elements);
429    }
430}
431
432impl Styled for MessageContent {
433    fn style(&mut self) -> &mut StyleRefinement {
434        &mut self.style
435    }
436}
437
438impl RenderOnce for MessageContent {
439    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
440        let is_right = self.alignment.is_right(cx);
441        v_flex()
442            .w_full()
443            .max_w_full()
444            .min_w_0()
445            .gap(rems(0.625))
446            .map(|this| {
447                if is_right {
448                    this.items_end()
449                } else {
450                    this.items_start()
451                }
452            })
453            .refine_style(&self.style)
454            .children(self.children)
455    }
456}
457
458/// Footer content such as delivery state, reactions, or action buttons.
459#[derive(IntoElement)]
460pub struct MessageFooter {
461    style: StyleRefinement,
462    content_inset: Option<bool>,
463    children: Vec<AnyElement>,
464}
465
466impl MessageFooter {
467    /// Create an empty message footer.
468    pub fn new() -> Self {
469        Self {
470            style: StyleRefinement::default(),
471            content_inset: None,
472            children: Vec::new(),
473        }
474    }
475
476    /// Set whether the footer keeps its default horizontal content inset.
477    pub fn content_inset(mut self, content_inset: bool) -> Self {
478        self.content_inset = Some(content_inset);
479        self
480    }
481
482    fn with_inherited_content_inset(mut self, content_inset: bool) -> Self {
483        self.content_inset.get_or_insert(content_inset);
484        self
485    }
486}
487
488impl Default for MessageFooter {
489    fn default() -> Self {
490        Self::new()
491    }
492}
493
494impl ParentElement for MessageFooter {
495    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
496        self.children.extend(elements);
497    }
498}
499
500impl Styled for MessageFooter {
501    fn style(&mut self) -> &mut StyleRefinement {
502        &mut self.style
503    }
504}
505
506impl RenderOnce for MessageFooter {
507    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
508        let tokens = cx.theme().semantic_tokens();
509
510        h_flex()
511            .flex_row_dir(cx)
512            .max_w_full()
513            .min_w_0()
514            .gap_1()
515            .text_xs()
516            .line_height(relative(1.25))
517            .font_medium()
518            .text_color(tokens.colors.muted_foreground)
519            .when(self.content_inset.unwrap_or(true), |this| this.px_3())
520            .refine_style(&self.style)
521            .children(self.children)
522    }
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528
529    #[test]
530    fn test_message_builder() {
531        let stack_style = StyleRefinement::default().gap_1();
532        let message = Message::new()
533            .alignment(MessageAlignment::End)
534            .with_stack_style(stack_style.clone())
535            .avatar_slot(MessageAvatar::new().child(gpui::div()))
536            .header(MessageHeader::new().content_inset(false).child("Alice"))
537            .content(MessageContent::new().child("Hello"))
538            .footer(MessageFooter::new().content_inset(false).child("Delivered"));
539
540        assert_eq!(message.alignment, MessageAlignment::End);
541        assert_eq!(message.stack_style, stack_style);
542        assert!(message.avatar.is_some());
543        assert!(message.header.is_some());
544        assert!(message.content.is_some());
545        assert!(message.footer.is_some());
546        assert_eq!(message.header.as_ref().unwrap().content_inset, Some(false));
547        assert_eq!(message.footer.as_ref().unwrap().content_inset, Some(false));
548        assert!(message.id.is_none());
549        assert_eq!(message.role, RoleOverride::default());
550
551        let row = Message::new().id("message-1").role(gpui::Role::ListItem);
552        assert_eq!(row.id, Some("message-1".into()));
553        assert_eq!(row.role, RoleOverride::Role(gpui::Role::ListItem));
554
555        let group = MessageGroup::new().child("First").child("Second");
556        assert_eq!(group.children.len(), 2);
557
558        let content = MessageContent::new().aligned(MessageAlignment::End);
559        assert_eq!(content.alignment, MessageAlignment::End);
560
561        let avatar = MessageAvatar::new().child("ME");
562        assert_eq!(avatar.children.len(), 1);
563    }
564
565    #[test]
566    fn test_ghost_bubble_inherits_message_slot_insets() {
567        let content = MessageContent::new()
568            .bubble(Bubble::new())
569            .bubble(Bubble::new().with_variant(crate::bubble::BubbleVariant::Ghost));
570
571        assert!(content.has_ghost_bubble);
572        assert_eq!(content.children.len(), 2);
573        assert_eq!(
574            MessageHeader::new()
575                .with_inherited_content_inset(false)
576                .content_inset,
577            Some(false)
578        );
579        assert_eq!(
580            MessageFooter::new()
581                .with_inherited_content_inset(false)
582                .content_inset,
583            Some(false)
584        );
585        assert_eq!(
586            MessageHeader::new()
587                .content_inset(true)
588                .with_inherited_content_inset(false)
589                .content_inset,
590            Some(true)
591        );
592        assert_eq!(
593            MessageFooter::new()
594                .content_inset(true)
595                .with_inherited_content_inset(false)
596                .content_inset,
597            Some(true)
598        );
599    }
600}