Skip to main content

arc_ui/data/
chat_thread.rs

1//! Ported from Arc (MIT) Β© 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/chat-thread/chat-thread.tsx` & `.module.css`
3//!
4//! P6 Component #15: `chat-thread`
5//!
6//! - Full chat & support conversation thread:
7//!   - Automatic day separators (`Today`, `Yesterday`, or UTC date) via zero-dependency civil calendar;
8//!   - Consecutive messages by the same author within `group_window_ms` (default 5 min) share a
9//!     group with softened inner corner radii (`6px` vs `18px`), single header, and bottom-aligned
10//!     author avatar;
11//!   - Image & file attachment chips (`format_chat_bytes`);
12//!   - Hoverable reaction trigger with inline emoji picker (`πŸ‘ ❀️ πŸ˜‚ πŸŽ‰ πŸ‘€ πŸ™`), active pill state,
13//!     and count toggling;
14//!   - Delivery status (`Sending` / `Sent` / `Delivered` / `Read` / `Not delivered` + `Retry` button)
15//!     and stacked reader avatars under the latest read message;
16//!   - Animated 3-dot breathing typing indicator;
17//!   - Built-in rounded composer powered by `gpui_kit::component::input::{Input, InputState}` with
18//!     Enter-to-send and active send button morph.
19
20use std::{cell::RefCell, collections::HashMap, rc::Rc};
21
22use arc_motion::{is_reduced_motion, motion_now};
23use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Typography, oklab_mix};
24use gpui_kit::{
25    App, ElementId, Entity, Hsla, IntoElement, KeyDownEvent, MouseButton, ParentElement,
26    PathBuilder, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, canvas,
27    component::input::{Input as KitInput, InputState},
28    div, point,
29    prelude::*,
30    px,
31};
32
33use super::avatar::initials_for;
34
35/// Default quick reaction set matching `chat-thread.tsx`.
36pub const CHAT_DEFAULT_REACTIONS: &[&str] = &["πŸ‘", "❀️", "πŸ˜‚", "πŸŽ‰", "πŸ‘€", "πŸ™"];
37/// Default grouping window: 5 minutes in milliseconds.
38pub const CHAT_DEFAULT_GROUP_WINDOW_MS: i64 = 5 * 60 * 1000;
39
40/// Participant in a [`ChatThread`].
41#[derive(Clone, Debug, Eq, PartialEq)]
42pub struct ChatParticipant {
43    pub id: SharedString,
44    pub name: SharedString,
45}
46
47impl ChatParticipant {
48    pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
49        Self {
50            id: id.into(),
51            name: name.into(),
52        }
53    }
54}
55
56/// Kind of attachment on a [`ChatMessage`].
57#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
58pub enum ChatAttachmentKind {
59    Image,
60    #[default]
61    File,
62}
63
64/// File or image attachment displayed inside a message bubble stack.
65#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct ChatAttachment {
67    pub id: SharedString,
68    pub name: SharedString,
69    pub kind: ChatAttachmentKind,
70    pub size_bytes: Option<u64>,
71}
72
73impl ChatAttachment {
74    pub fn file(
75        id: impl Into<SharedString>,
76        name: impl Into<SharedString>,
77        size_bytes: u64,
78    ) -> Self {
79        Self {
80            id: id.into(),
81            name: name.into(),
82            kind: ChatAttachmentKind::File,
83            size_bytes: Some(size_bytes),
84        }
85    }
86
87    pub fn image(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
88        Self {
89            id: id.into(),
90            name: name.into(),
91            kind: ChatAttachmentKind::Image,
92            size_bytes: None,
93        }
94    }
95}
96
97/// Emoji reaction count under a [`ChatMessage`].
98#[derive(Clone, Debug, Eq, PartialEq)]
99pub struct ChatReaction {
100    pub emoji: SharedString,
101    pub count: usize,
102    pub mine: bool,
103}
104
105impl ChatReaction {
106    pub fn new(emoji: impl Into<SharedString>, count: usize, mine: bool) -> Self {
107        Self {
108            emoji: emoji.into(),
109            count,
110            mine,
111        }
112    }
113}
114
115/// Delivery state of the current user's own message.
116#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
117pub enum ChatMessageStatus {
118    Sending,
119    #[default]
120    Sent,
121    Delivered,
122    Read,
123    Failed,
124}
125
126/// One message in a [`ChatThread`].
127#[derive(Clone, Debug)]
128pub struct ChatMessage {
129    pub id: SharedString,
130    pub author_id: SharedString,
131    pub text: Option<SharedString>,
132    /// Epoch milliseconds.
133    pub created_at_ms: i64,
134    pub attachments: Vec<ChatAttachment>,
135    pub reactions: Vec<ChatReaction>,
136    pub status: ChatMessageStatus,
137}
138
139impl ChatMessage {
140    pub fn new(
141        id: impl Into<SharedString>,
142        author_id: impl Into<SharedString>,
143        text: impl Into<SharedString>,
144        created_at_ms: i64,
145    ) -> Self {
146        Self {
147            id: id.into(),
148            author_id: author_id.into(),
149            text: Some(text.into()),
150            created_at_ms,
151            attachments: Vec::new(),
152            reactions: Vec::new(),
153            status: ChatMessageStatus::Sent,
154        }
155    }
156
157    pub fn attachment(mut self, attachment: ChatAttachment) -> Self {
158        self.attachments.push(attachment);
159        self
160    }
161
162    pub fn reaction(mut self, emoji: impl Into<SharedString>, count: usize, mine: bool) -> Self {
163        self.reactions.push(ChatReaction::new(emoji, count, mine));
164        self
165    }
166
167    pub fn status(mut self, status: ChatMessageStatus) -> Self {
168        self.status = status;
169        self
170    }
171}
172
173/// Flattened render row produced by [`build_chat_rows`].
174#[derive(Clone, Debug, Eq, PartialEq)]
175pub enum ChatRow {
176    Day {
177        key: String,
178        label: String,
179    },
180    Message {
181        index: usize,
182        mine: bool,
183        first: bool,
184        last: bool,
185    },
186}
187
188/// Formats byte sizes matching `chat-thread.tsx` (`B` / `KB` / `MB`).
189pub fn format_chat_bytes(bytes: u64) -> String {
190    if bytes < 1024 {
191        format!("{bytes} B")
192    } else if bytes < 1024 * 1024 {
193        format!("{} KB", ((bytes as f64) / 1024.0).round() as u64)
194    } else {
195        format!("{:.1} MB", (bytes as f64) / (1024.0 * 1024.0))
196    }
197}
198
199fn utc_day_number(ms: i64) -> i64 {
200    ms.div_euclid(86_400_000)
201}
202
203fn civil_from_days(z: i64) -> (i32, u32, u32) {
204    let z = z + 719_468;
205    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
206    let doe = (z - era * 146_097) as u32;
207    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
208    let y = yoe as i64 + era * 400;
209    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
210    let mp = (5 * doy + 2) / 153;
211    let d = doy - (153 * mp + 2) / 5 + 1;
212    let m = if mp < 10 { mp + 3 } else { mp - 9 };
213    let y = y + i64::from(m <= 2);
214    (y as i32, m, d)
215}
216
217fn month_short(month: u32) -> &'static str {
218    match month {
219        1 => "Jan",
220        2 => "Feb",
221        3 => "Mar",
222        4 => "Apr",
223        5 => "May",
224        6 => "Jun",
225        7 => "Jul",
226        8 => "Aug",
227        9 => "Sep",
228        10 => "Oct",
229        11 => "Nov",
230        _ => "Dec",
231    }
232}
233
234/// Formats a day separator label relative to `now_ms`.
235pub fn format_chat_day(ms: i64, now_ms: i64) -> String {
236    let diff = utc_day_number(now_ms) - utc_day_number(ms);
237    if diff == 0 {
238        return "Today".to_string();
239    }
240    if diff == 1 {
241        return "Yesterday".to_string();
242    }
243    let (y, m, d) = civil_from_days(utc_day_number(ms));
244    let (ny, _, _) = civil_from_days(utc_day_number(now_ms));
245    if y == ny {
246        format!("{} {}", month_short(m), d)
247    } else {
248        format!("{} {}, {}", month_short(m), d, y)
249    }
250}
251
252/// Formats `HH:MM` UTC clock time for a message timestamp.
253pub fn format_chat_time(ms: i64) -> String {
254    let secs_in_day = ms.rem_euclid(86_400_000) / 1000;
255    let h = secs_in_day / 3600;
256    let m = (secs_in_day % 3600) / 60;
257    format!("{h:02}:{m:02}")
258}
259
260/// Groups chronological messages into day separators and `first`/`last` author runs.
261pub fn build_chat_rows(
262    messages: &[ChatMessage],
263    current_user_id: &str,
264    group_window_ms: i64,
265    now_ms: i64,
266) -> Vec<ChatRow> {
267    let mut rows = Vec::with_capacity(messages.len() + 4);
268    let mut last_day: Option<i64> = None;
269
270    for (idx, msg) in messages.iter().enumerate() {
271        let day = utc_day_number(msg.created_at_ms);
272        if last_day != Some(day) {
273            rows.push(ChatRow::Day {
274                key: format!("day-{day}"),
275                label: format_chat_day(msg.created_at_ms, now_ms),
276            });
277            last_day = Some(day);
278        }
279        let joins = |other: Option<&ChatMessage>| -> bool {
280            let Some(other) = other else {
281                return false;
282            };
283            other.author_id == msg.author_id
284                && utc_day_number(other.created_at_ms) == day
285                && (other.created_at_ms - msg.created_at_ms).abs() <= group_window_ms
286        };
287        let prev = idx.checked_sub(1).and_then(|i| messages.get(i));
288        let next = messages.get(idx + 1);
289        rows.push(ChatRow::Message {
290            index: idx,
291            mine: msg.author_id.as_ref() == current_user_id,
292            first: !joins(prev),
293            last: !joins(next),
294        });
295    }
296    rows
297}
298
299/// Toggles the current user's reaction on a message's reaction list.
300pub fn toggle_chat_reaction(reactions: &mut Vec<ChatReaction>, emoji: &str) {
301    if let Some(pos) = reactions.iter().position(|r| r.emoji.as_ref() == emoji) {
302        if reactions[pos].mine {
303            reactions[pos].count = reactions[pos].count.saturating_sub(1);
304            reactions[pos].mine = false;
305            if reactions[pos].count == 0 {
306                reactions.remove(pos);
307            }
308        } else {
309            reactions[pos].count += 1;
310            reactions[pos].mine = true;
311        }
312    } else {
313        reactions.push(ChatReaction::new(emoji.to_string(), 1, true));
314    }
315}
316
317fn paint_arrow_up(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
318    let mut pb = PathBuilder::stroke(px(2.0));
319    pb.move_to(point(px(cx), px(cy + 4.5)));
320    pb.line_to(point(px(cx), px(cy - 4.5)));
321    pb.move_to(point(px(cx - 4.0), px(cy - 0.5)));
322    pb.line_to(point(px(cx), px(cy - 4.5)));
323    pb.line_to(point(px(cx + 4.0), px(cy - 0.5)));
324    if let Ok(p) = pb.build() {
325        window.paint_path(p, color);
326    }
327}
328
329fn paint_smile_plus(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
330    // Simple circular smile glyph
331    let mut pb = PathBuilder::stroke(px(1.5));
332    pb.move_to(point(px(cx - 3.5), px(cy + 1.0)));
333    pb.line_to(point(px(cx - 1.5), px(cy + 3.0)));
334    pb.line_to(point(px(cx + 1.5), px(cy + 3.0)));
335    pb.line_to(point(px(cx + 3.5), px(cy + 1.0)));
336    if let Ok(p) = pb.build() {
337        window.paint_path(p, color);
338    }
339    let mut plus = PathBuilder::stroke(px(1.5));
340    plus.move_to(point(px(cx), px(cy - 5.0)));
341    plus.line_to(point(px(cx), px(cy - 1.0)));
342    plus.move_to(point(px(cx - 2.0), px(cy - 3.0)));
343    plus.line_to(point(px(cx + 2.0), px(cy - 3.0)));
344    if let Ok(p) = plus.build() {
345        window.paint_path(p, color);
346    }
347}
348
349type SendCallback = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
350type ReactCallback = Rc<dyn Fn(SharedString, SharedString, &mut Window, &mut App)>;
351type RetryCallback = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
352
353#[derive(Clone)]
354struct ChatThreadInternal {
355    picker_for: Option<SharedString>,
356    input_state: Entity<InputState>,
357    scroll: gpui_kit::ScrollHandle,
358}
359
360/// Arc `ChatThread` β€” grouped chat messages, reactions, read receipts, typing dots, and composer.
361#[derive(IntoElement)]
362pub struct ChatThread {
363    id: ElementId,
364    label: SharedString,
365    participants: Vec<ChatParticipant>,
366    current_user_id: SharedString,
367    messages: Vec<ChatMessage>,
368    typing_ids: Vec<SharedString>,
369    read_by: HashMap<SharedString, SharedString>,
370    reactions: Vec<SharedString>,
371    placeholder: SharedString,
372    composer: bool,
373    group_window_ms: i64,
374    now_ms: i64,
375    height_px: f32,
376    on_send: Option<SendCallback>,
377    on_react: Option<ReactCallback>,
378    on_retry: Option<RetryCallback>,
379}
380
381impl ChatThread {
382    pub fn new(
383        id: impl Into<ElementId>,
384        participants: Vec<ChatParticipant>,
385        current_user_id: impl Into<SharedString>,
386        messages: Vec<ChatMessage>,
387    ) -> Self {
388        Self {
389            id: id.into(),
390            label: "Conversation".into(),
391            participants,
392            current_user_id: current_user_id.into(),
393            messages,
394            typing_ids: Vec::new(),
395            read_by: HashMap::new(),
396            reactions: CHAT_DEFAULT_REACTIONS
397                .iter()
398                .map(|&e| SharedString::from(e))
399                .collect(),
400            placeholder: "Message".into(),
401            composer: true,
402            group_window_ms: CHAT_DEFAULT_GROUP_WINDOW_MS,
403            now_ms: 1_745_000_000_000,
404            height_px: 440.0,
405            on_send: None,
406            on_react: None,
407            on_retry: None,
408        }
409    }
410
411    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
412        self.label = label.into();
413        self
414    }
415
416    pub fn typing(mut self, ids: Vec<SharedString>) -> Self {
417        self.typing_ids = ids;
418        self
419    }
420
421    pub fn read_by(mut self, read_by: HashMap<SharedString, SharedString>) -> Self {
422        self.read_by = read_by;
423        self
424    }
425
426    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
427        self.placeholder = placeholder.into();
428        self
429    }
430
431    pub fn composer(mut self, enabled: bool) -> Self {
432        self.composer = enabled;
433        self
434    }
435
436    pub fn now_ms(mut self, now_ms: i64) -> Self {
437        self.now_ms = now_ms;
438        self
439    }
440
441    pub fn height(mut self, px_height: f32) -> Self {
442        self.height_px = px_height.max(240.0);
443        self
444    }
445
446    pub fn on_send(
447        mut self,
448        handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
449    ) -> Self {
450        self.on_send = Some(Rc::new(handler));
451        self
452    }
453
454    pub fn on_react(
455        mut self,
456        handler: impl Fn(SharedString, SharedString, &mut Window, &mut App) + 'static,
457    ) -> Self {
458        self.on_react = Some(Rc::new(handler));
459        self
460    }
461
462    pub fn on_retry(
463        mut self,
464        handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
465    ) -> Self {
466        self.on_retry = Some(Rc::new(handler));
467        self
468    }
469}
470
471impl RenderOnce for ChatThread {
472    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
473        let theme = cx.arc_theme().clone();
474        let reduced = is_reduced_motion(cx);
475        let placeholder_str = self.placeholder.clone();
476
477        let state = window.use_keyed_state(
478            ElementId::Name(format!("arc-chat-thread-state-{:?}", self.id).into()),
479            cx,
480            |window, cx| {
481                let input_state =
482                    cx.new(|cx| InputState::new(window, cx).placeholder(placeholder_str.clone()));
483                Rc::new(RefCell::new(ChatThreadInternal {
484                    picker_for: None,
485                    input_state,
486                    scroll: gpui_kit::ScrollHandle::new(),
487                }))
488            },
489        );
490        let shared = state.read(cx).clone();
491        let picker_for = shared.borrow().picker_for.clone();
492        let input_state = shared.borrow().input_state.clone();
493        let scroll = shared.borrow().scroll.clone();
494
495        let people: HashMap<SharedString, ChatParticipant> = self
496            .participants
497            .iter()
498            .map(|p| (p.id.clone(), p.clone()))
499            .collect();
500
501        // Build read receipts map: message_id -> Vec<ChatParticipant>
502        let mut receipts: HashMap<SharedString, Vec<ChatParticipant>> = HashMap::new();
503        let mut furthest_read_idx: isize = -1;
504        for (person_id, msg_id) in &self.read_by {
505            if person_id == &self.current_user_id {
506                continue;
507            }
508            let Some(who) = people.get(person_id) else {
509                continue;
510            };
511            if let Some((idx, msg)) = self
512                .messages
513                .iter()
514                .enumerate()
515                .find(|(_, m)| &m.id == msg_id)
516            {
517                if &msg.author_id == person_id {
518                    continue;
519                }
520                furthest_read_idx = furthest_read_idx.max(idx as isize);
521                receipts
522                    .entry(msg_id.clone())
523                    .or_default()
524                    .push(who.clone());
525            }
526        }
527
528        let last_mine_idx = self
529            .messages
530            .iter()
531            .rposition(|m| m.author_id == self.current_user_id);
532
533        let rows = build_chat_rows(
534            &self.messages,
535            self.current_user_id.as_ref(),
536            self.group_window_ms,
537            self.now_ms,
538        );
539
540        let other_bubble_bg = if matches!(theme.mode, arc_tokens::ThemeMode::Dark) {
541            theme.colors.surface_raised
542        } else {
543            theme.colors.surface_muted
544        };
545
546        let mut list = div()
547            .id(ElementId::Name(
548                format!("arc-chat-thread-log-{:?}", self.id).into(),
549            ))
550            .test_support()
551            .role(Role::Log)
552            .aria_label(self.label)
553            .flex_1()
554            .overflow_y_scroll()
555            .track_scroll(&scroll)
556            .on_scroll(arc_motion::scroll_chain_handler(&scroll, false))
557            .px(px(16.0))
558            .py(px(12.0))
559            .flex()
560            .flex_col()
561            .gap(px(2.0));
562
563        for row in rows {
564            match row {
565                ChatRow::Day { key, label } => {
566                    list = list.child(
567                        div()
568                            .id(ElementId::Name(
569                                format!("arc-chat-day-{:?}-{}", self.id, key).into(),
570                            ))
571                            .w_full()
572                            .py(px(8.0))
573                            .flex()
574                            .items_center()
575                            .gap(px(12.0))
576                            .child(div().flex_1().h(px(1.0)).bg(theme.colors.border_subtle))
577                            .child(
578                                div()
579                                    .text_size(Typography::TEXT_XS)
580                                    .text_color(theme.colors.text_muted)
581                                    .child(label),
582                            )
583                            .child(div().flex_1().h(px(1.0)).bg(theme.colors.border_subtle)),
584                    );
585                }
586                ChatRow::Message {
587                    index,
588                    mine,
589                    first,
590                    last,
591                } => {
592                    let msg = &self.messages[index];
593                    let author_name = people
594                        .get(&msg.author_id)
595                        .map(|p| p.name.clone())
596                        .unwrap_or_else(|| SharedString::from("Unknown"));
597                    let msg_id = msg.id.clone();
598                    let is_picker_open = picker_for.as_ref() == Some(&msg_id);
599                    let seen_by = receipts.get(&msg_id).cloned().unwrap_or_default();
600                    let show_status = mine && last_mine_idx == Some(index);
601                    let effective_status = match msg.status {
602                        ChatMessageStatus::Failed => ChatMessageStatus::Failed,
603                        ChatMessageStatus::Sending => ChatMessageStatus::Sending,
604                        _ if furthest_read_idx >= index as isize => ChatMessageStatus::Read,
605                        other => other,
606                    };
607
608                    // Corner radii: inner side tightens to 6px inside a run of messages
609                    let r_full = px(18.0);
610                    let r_tight = px(6.0);
611                    let (r_tl, r_tr, r_bl, r_br) = if mine {
612                        (
613                            r_full,
614                            if first { r_full } else { r_tight },
615                            r_full,
616                            if last { r_full } else { r_tight },
617                        )
618                    } else {
619                        (
620                            if first { r_full } else { r_tight },
621                            r_full,
622                            if last { r_full } else { r_tight },
623                            r_full,
624                        )
625                    };
626
627                    let mut stack = div()
628                        .max_w(px(360.0))
629                        .flex()
630                        .flex_col()
631                        .gap(px(4.0))
632                        .when(mine, |el| el.items_end())
633                        .when(!mine, |el| el.items_start());
634
635                    if first {
636                        let mut meta = div().px(px(10.0)).flex().items_baseline().gap(px(6.0));
637                        if !mine {
638                            meta = meta.child(
639                                div()
640                                    .text_size(Typography::TEXT_XS)
641                                    .text_color(theme.colors.text_secondary)
642                                    .child(author_name.clone()),
643                            );
644                        }
645                        meta = meta.child(
646                            div()
647                                .text_size(Typography::TEXT_XS)
648                                .text_color(theme.colors.text_muted)
649                                .child(format_chat_time(msg.created_at_ms)),
650                        );
651                        stack = stack.child(meta);
652                    }
653
654                    // Bubble + attachments
655                    let mut parts = div()
656                        .flex()
657                        .flex_col()
658                        .gap(px(4.0))
659                        .when(mine, |el| el.items_end())
660                        .when(!mine, |el| el.items_start());
661
662                    for att in &msg.attachments {
663                        let chip = div()
664                            .px(px(12.0))
665                            .py(px(8.0))
666                            .rounded(px(14.0))
667                            .border_1()
668                            .border_color(theme.colors.border)
669                            .bg(theme.colors.surface)
670                            .flex()
671                            .items_center()
672                            .gap(px(8.0))
673                            .child(
674                                div()
675                                    .text_size(Typography::TEXT_XS)
676                                    .text_color(theme.colors.text_muted)
677                                    .child(match att.kind {
678                                        ChatAttachmentKind::Image => "IMG",
679                                        ChatAttachmentKind::File => "FILE",
680                                    }),
681                            )
682                            .child(
683                                div()
684                                    .flex()
685                                    .flex_col()
686                                    .child(
687                                        div()
688                                            .text_size(Typography::TEXT_SM)
689                                            .text_color(theme.colors.foreground)
690                                            .child(att.name.clone()),
691                                    )
692                                    .when_some(att.size_bytes, |el, sz| {
693                                        el.child(
694                                            div()
695                                                .text_size(Typography::TEXT_XS)
696                                                .text_color(theme.colors.text_muted)
697                                                .child(format_chat_bytes(sz)),
698                                        )
699                                    }),
700                            );
701                        parts = parts.child(chip);
702                    }
703
704                    if let Some(text) = &msg.text {
705                        let bubble = div()
706                            .px(px(13.0))
707                            .py(px(8.0))
708                            .rounded_tl(r_tl)
709                            .rounded_tr(r_tr)
710                            .rounded_bl(r_bl)
711                            .rounded_br(r_br)
712                            .bg(if mine {
713                                theme.colors.accent
714                            } else {
715                                other_bubble_bg
716                            })
717                            .text_color(if mine {
718                                theme.colors.accent_foreground
719                            } else {
720                                theme.colors.foreground
721                            })
722                            .text_size(Typography::TEXT_SM)
723                            .opacity(if msg.status == ChatMessageStatus::Failed {
724                                0.6
725                            } else {
726                                1.0
727                            })
728                            .child(text.clone());
729                        parts = parts.child(bubble);
730                    }
731
732                    // Reaction trigger button beside the bubble
733                    let shared_toggle = shared.clone();
734                    let msg_id_toggle = msg_id.clone();
735                    let smile_color = if is_picker_open {
736                        theme.colors.foreground
737                    } else {
738                        theme.colors.text_muted
739                    };
740                    let react_btn = div()
741                        .id(ElementId::Name(
742                            format!("arc-chat-react-btn-{:?}-{}", self.id, msg_id).into(),
743                        ))
744                        .role(Role::Button)
745                        .aria_label("Add reaction")
746                        .w(px(26.0))
747                        .h(px(26.0))
748                        .rounded(Radii::PILL)
749                        .when(is_picker_open, |el| el.bg(theme.colors.surface_muted))
750                        .hover(|s| s.bg(theme.colors.surface_muted))
751                        .cursor_pointer()
752                        .flex()
753                        .items_center()
754                        .justify_center()
755                        .on_mouse_down(MouseButton::Left, move |_, window, _| {
756                            let mut st = shared_toggle.borrow_mut();
757                            if st.picker_for.as_ref() == Some(&msg_id_toggle) {
758                                st.picker_for = None;
759                            } else {
760                                st.picker_for = Some(msg_id_toggle.clone());
761                            }
762                            window.refresh();
763                        })
764                        .child(
765                            canvas(
766                                |b, _, _| b,
767                                move |b, _, window, _| {
768                                    let cx = f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
769                                    let cy = f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
770                                    paint_smile_plus(cx, cy, smile_color, window);
771                                },
772                            )
773                            .w(px(14.0))
774                            .h(px(14.0)),
775                        );
776
777                    let line = if mine {
778                        div()
779                            .flex()
780                            .items_center()
781                            .gap(px(6.0))
782                            .child(react_btn)
783                            .child(parts)
784                    } else {
785                        div()
786                            .flex()
787                            .items_center()
788                            .gap(px(6.0))
789                            .child(parts)
790                            .child(react_btn)
791                    };
792                    stack = stack.child(line);
793
794                    // Inline emoji picker popover strip when open for this message
795                    if is_picker_open {
796                        let mut picker_strip = div()
797                            .p(px(4.0))
798                            .rounded(Radii::PILL)
799                            .border_1()
800                            .border_color(theme.colors.border)
801                            .bg(theme.colors.surface_raised)
802                            .shadow(Shadows::floating(theme.mode))
803                            .flex()
804                            .items_center()
805                            .gap(px(2.0));
806
807                        for emoji in &self.reactions {
808                            let emoji_val = emoji.clone();
809                            let msg_id_pick = msg_id.clone();
810                            let on_react = self.on_react.clone();
811                            let shared_pick = shared.clone();
812                            picker_strip = picker_strip.child(
813                                div()
814                                    .id(ElementId::Name(
815                                        format!("arc-chat-pick-{:?}-{}-{}", self.id, msg_id, emoji)
816                                            .into(),
817                                    ))
818                                    .role(Role::Button)
819                                    .w(px(30.0))
820                                    .h(px(30.0))
821                                    .rounded(Radii::PILL)
822                                    .hover(|s| s.bg(theme.colors.surface_muted))
823                                    .cursor_pointer()
824                                    .flex()
825                                    .items_center()
826                                    .justify_center()
827                                    .text_size(px(16.0))
828                                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
829                                        shared_pick.borrow_mut().picker_for = None;
830                                        if let Some(cb) = &on_react {
831                                            cb(msg_id_pick.clone(), emoji_val.clone(), window, cx);
832                                        }
833                                        window.refresh();
834                                    })
835                                    .child(emoji.clone()),
836                            );
837                        }
838                        stack = stack.child(picker_strip);
839                    }
840
841                    // Existing reaction pills
842                    if !msg.reactions.is_empty() {
843                        let mut reaction_row = div()
844                            .flex()
845                            .flex_wrap()
846                            .gap(px(4.0))
847                            .when(mine, |el| el.justify_end());
848
849                        for reaction in &msg.reactions {
850                            let border_c = if reaction.mine {
851                                oklab_mix(theme.colors.border_subtle, theme.colors.accent, 0.35)
852                            } else {
853                                theme.colors.border_subtle
854                            };
855                            let bg_c = if reaction.mine {
856                                oklab_mix(theme.colors.surface, theme.colors.accent, 0.10)
857                            } else {
858                                theme.colors.surface
859                            };
860                            let on_react = self.on_react.clone();
861                            let msg_id_r = msg_id.clone();
862                            let emoji_r = reaction.emoji.clone();
863                            reaction_row = reaction_row.child(
864                                div()
865                                    .id(ElementId::Name(
866                                        format!(
867                                            "arc-chat-rx-{:?}-{}-{}",
868                                            self.id, msg_id, reaction.emoji
869                                        )
870                                        .into(),
871                                    ))
872                                    .role(Role::Button)
873                                    .h(px(24.0))
874                                    .pl(px(7.0))
875                                    .pr(px(8.0))
876                                    .rounded(Radii::PILL)
877                                    .border_1()
878                                    .border_color(border_c)
879                                    .bg(bg_c)
880                                    .hover(|s| s.border_color(theme.colors.border_strong))
881                                    .cursor_pointer()
882                                    .flex()
883                                    .items_center()
884                                    .gap(px(4.0))
885                                    .text_size(Typography::TEXT_XS)
886                                    .text_color(if reaction.mine {
887                                        theme.colors.foreground
888                                    } else {
889                                        theme.colors.text_secondary
890                                    })
891                                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
892                                        if let Some(cb) = &on_react {
893                                            cb(msg_id_r.clone(), emoji_r.clone(), window, cx);
894                                        }
895                                    })
896                                    .child(reaction.emoji.clone())
897                                    .child(reaction.count.to_string()),
898                            );
899                        }
900                        stack = stack.child(reaction_row);
901                    }
902
903                    // Delivery status & read receipt avatars
904                    if show_status || !seen_by.is_empty() {
905                        let mut receipt_row = div().px(px(6.0)).flex().items_center().gap(px(6.0));
906
907                        if show_status {
908                            let status_label = match effective_status {
909                                ChatMessageStatus::Sending => "Sending",
910                                ChatMessageStatus::Sent => "Sent",
911                                ChatMessageStatus::Delivered => "Delivered",
912                                ChatMessageStatus::Read => "Read",
913                                ChatMessageStatus::Failed => "Not delivered",
914                            };
915                            receipt_row = receipt_row.child(
916                                div()
917                                    .text_size(Typography::TEXT_XS)
918                                    .text_color(if effective_status == ChatMessageStatus::Failed {
919                                        theme.colors.danger
920                                    } else {
921                                        theme.colors.text_muted
922                                    })
923                                    .child(status_label),
924                            );
925                            if effective_status == ChatMessageStatus::Failed
926                                && let Some(on_retry) = self.on_retry.clone()
927                            {
928                                let msg_id_retry = msg_id.clone();
929                                receipt_row = receipt_row.child(
930                                    div()
931                                        .id(ElementId::Name(
932                                            format!("arc-chat-retry-{:?}-{}", self.id, msg_id)
933                                                .into(),
934                                        ))
935                                        .role(Role::Button)
936                                        .px(px(8.0))
937                                        .py(px(2.0))
938                                        .rounded(Radii::PILL)
939                                        .border_1()
940                                        .border_color(theme.colors.border)
941                                        .bg(theme.colors.surface)
942                                        .hover(|s| s.bg(theme.colors.surface_muted))
943                                        .cursor_pointer()
944                                        .text_size(Typography::TEXT_XS)
945                                        .text_color(theme.colors.foreground)
946                                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
947                                            on_retry(msg_id_retry.clone(), window, cx);
948                                        })
949                                        .child("Retry"),
950                                );
951                            }
952                        }
953
954                        if !seen_by.is_empty() {
955                            let mut readers = div().flex().items_center();
956                            for reader in &seen_by {
957                                readers = readers.child(
958                                    div()
959                                        .w(px(16.0))
960                                        .h(px(16.0))
961                                        .rounded(Radii::PILL)
962                                        .bg(theme.colors.surface_muted)
963                                        .border_1()
964                                        .border_color(theme.colors.surface)
965                                        .flex()
966                                        .items_center()
967                                        .justify_center()
968                                        .text_size(px(8.0))
969                                        .text_color(theme.colors.text_secondary)
970                                        .child(initials_for(reader.name.as_ref())),
971                                );
972                            }
973                            receipt_row = receipt_row.child(readers);
974                        }
975
976                        stack = stack.child(receipt_row);
977                    }
978
979                    // Row container with left avatar gutter for other participants
980                    let mut row_el = div()
981                        .w_full()
982                        .mt(px(if first { 12.0 } else { 2.0 }))
983                        .flex()
984                        .items_end()
985                        .gap(px(8.0))
986                        .when(mine, |el| el.justify_end());
987
988                    if !mine {
989                        let gutter = if last {
990                            div()
991                                .w(px(28.0))
992                                .h(px(28.0))
993                                .flex_shrink_0()
994                                .rounded(Radii::PILL)
995                                .bg(theme.colors.surface_muted)
996                                .flex()
997                                .items_center()
998                                .justify_center()
999                                .text_size(px(11.0))
1000                                .text_color(theme.colors.text_secondary)
1001                                .child(initials_for(author_name.as_ref()))
1002                        } else {
1003                            div().w(px(28.0)).flex_shrink_0()
1004                        };
1005                        row_el = row_el.child(gutter);
1006                    }
1007
1008                    row_el = row_el.child(stack);
1009                    list = list.child(row_el);
1010                }
1011            }
1012        }
1013
1014        // Typing indicator row with 3 breathing dots
1015        let typers: Vec<&ChatParticipant> = self
1016            .typing_ids
1017            .iter()
1018            .filter(|id| *id != &self.current_user_id)
1019            .filter_map(|id| people.get(id))
1020            .collect();
1021        if let Some(first_typer) = typers.first() {
1022            let phase_s = motion_now(cx);
1023            if !reduced {
1024                window.request_animation_frame();
1025            }
1026            let mut dots = div().flex().items_center().gap(px(4.0));
1027            for i in 0..3 {
1028                let (alpha, dy) = if reduced {
1029                    (0.6, 0.0)
1030                } else {
1031                    let t = ((phase_s - i as f64 * 0.16).rem_euclid(1.2) / 1.2) as f32;
1032                    let wave = if t < 0.6 {
1033                        (t / 0.6 * std::f32::consts::PI).sin()
1034                    } else {
1035                        0.0
1036                    };
1037                    (0.35 + 0.65 * wave, -3.0 * wave)
1038                };
1039                dots = dots.child(
1040                    div()
1041                        .w(px(6.0))
1042                        .h(px(6.0))
1043                        .mt(px(dy))
1044                        .rounded(Radii::PILL)
1045                        .bg(theme.colors.text_muted)
1046                        .opacity(alpha),
1047                );
1048            }
1049            list = list.child(
1050                div()
1051                    .mt(px(10.0))
1052                    .flex()
1053                    .items_end()
1054                    .gap(px(8.0))
1055                    .child(
1056                        div()
1057                            .w(px(28.0))
1058                            .h(px(28.0))
1059                            .rounded(Radii::PILL)
1060                            .bg(theme.colors.surface_muted)
1061                            .flex()
1062                            .items_center()
1063                            .justify_center()
1064                            .text_size(px(11.0))
1065                            .text_color(theme.colors.text_secondary)
1066                            .child(initials_for(first_typer.name.as_ref())),
1067                    )
1068                    .child(
1069                        div()
1070                            .h(px(34.0))
1071                            .px(px(14.0))
1072                            .rounded(px(18.0))
1073                            .bg(other_bubble_bg)
1074                            .flex()
1075                            .items_center()
1076                            .child(dots),
1077                    ),
1078            );
1079        }
1080
1081        let mut root = div()
1082            .id(self.id.clone())
1083            .w_full()
1084            .h(px(self.height_px))
1085            .rounded(Radii::PANEL)
1086            .border_1()
1087            .border_color(theme.colors.border)
1088            .bg(theme.colors.surface)
1089            .overflow_hidden()
1090            .flex()
1091            .flex_col()
1092            .child(list);
1093
1094        // Composer bar
1095        if self.composer {
1096            let current_text = input_state.read(cx).value().to_string();
1097            let ready = !current_text.trim().is_empty();
1098            let send_action = {
1099                let input_st = input_state.clone();
1100                let on_send = self.on_send.clone();
1101                Rc::new(move |window: &mut Window, cx: &mut App| {
1102                    let raw = input_st.read(cx).value().to_string();
1103                    let trimmed = raw.trim().to_string();
1104                    if trimmed.is_empty() {
1105                        return;
1106                    }
1107                    input_st.update(cx, |state, cx| {
1108                        state.set_value("", window, cx);
1109                    });
1110                    if let Some(cb) = &on_send {
1111                        cb(SharedString::from(trimmed), window, cx);
1112                    }
1113                })
1114            };
1115
1116            let send_on_click = send_action.clone();
1117            let send_on_key = send_action.clone();
1118            let arrow_color = if ready {
1119                theme.colors.accent_foreground
1120            } else {
1121                theme.colors.text_muted
1122            };
1123
1124            let composer_box = div()
1125                .w_full()
1126                .px(px(12.0))
1127                .py(px(10.0))
1128                .border_t_1()
1129                .border_color(theme.colors.border_subtle)
1130                .child(
1131                    div()
1132                        .w_full()
1133                        .min_h(px(36.0))
1134                        .pl(px(12.0))
1135                        .pr(px(5.0))
1136                        .py(px(4.0))
1137                        .rounded(Radii::PANEL)
1138                        .border_1()
1139                        .border_color(theme.colors.border)
1140                        .bg(theme.colors.surface)
1141                        .flex()
1142                        .items_center()
1143                        .gap(px(6.0))
1144                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
1145                            if event.keystroke.key == "enter" && !event.keystroke.modifiers.shift {
1146                                send_on_key(window, cx);
1147                            }
1148                        })
1149                        .child(
1150                            div()
1151                                .flex_1()
1152                                .min_w_0()
1153                                .child(KitInput::new(&input_state).appearance(false)),
1154                        )
1155                        .child(
1156                            div()
1157                                .id(ElementId::Name(
1158                                    format!("arc-chat-send-{:?}", self.id).into(),
1159                                ))
1160                                .role(Role::Button)
1161                                .aria_label("Send")
1162                                .w(px(32.0))
1163                                .h(px(32.0))
1164                                .rounded(Radii::PILL)
1165                                .bg(if ready {
1166                                    theme.colors.accent
1167                                } else {
1168                                    gpui_kit::hsla(0.0, 0.0, 0.0, 0.0)
1169                                })
1170                                .when(ready, |el| el.cursor_pointer())
1171                                .flex()
1172                                .items_center()
1173                                .justify_center()
1174                                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1175                                    send_on_click(window, cx);
1176                                })
1177                                .child(
1178                                    canvas(
1179                                        |b, _, _| b,
1180                                        move |b, _, window, _| {
1181                                            let cx = f32::from(b.origin.x)
1182                                                + f32::from(b.size.width) * 0.5;
1183                                            let cy = f32::from(b.origin.y)
1184                                                + f32::from(b.size.height) * 0.5;
1185                                            paint_arrow_up(cx, cy, arrow_color, window);
1186                                        },
1187                                    )
1188                                    .w(px(16.0))
1189                                    .h(px(16.0)),
1190                                ),
1191                        ),
1192                );
1193            root = root.child(composer_box);
1194        }
1195
1196        root
1197    }
1198}
1199
1200#[cfg(test)]
1201mod tests {
1202    use super::*;
1203
1204    #[test]
1205    fn chat_thread_grouping_bytes_and_reactions() {
1206        assert_eq!(format_chat_bytes(512), "512 B");
1207        assert_eq!(format_chat_bytes(2048), "2 KB");
1208        assert_eq!(format_chat_bytes(2_621_440), "2.5 MB");
1209
1210        let now = 1_745_000_000_000_i64;
1211        let msgs = vec![
1212            ChatMessage::new("m1", "a", "Hello", now - 120_000),
1213            ChatMessage::new("m2", "a", "Second line", now - 60_000),
1214            ChatMessage::new("m3", "me", "Got it", now - 10_000),
1215        ];
1216        let rows = build_chat_rows(&msgs, "me", CHAT_DEFAULT_GROUP_WINDOW_MS, now);
1217        assert_eq!(rows.len(), 4); // 1 day + 3 messages
1218        assert!(matches!(rows[0], ChatRow::Day { .. }));
1219        assert_eq!(
1220            rows[1],
1221            ChatRow::Message {
1222                index: 0,
1223                mine: false,
1224                first: true,
1225                last: false,
1226            }
1227        );
1228        assert_eq!(
1229            rows[2],
1230            ChatRow::Message {
1231                index: 1,
1232                mine: false,
1233                first: false,
1234                last: true,
1235            }
1236        );
1237        assert_eq!(
1238            rows[3],
1239            ChatRow::Message {
1240                index: 2,
1241                mine: true,
1242                first: true,
1243                last: true,
1244            }
1245        );
1246
1247        let mut rx = Vec::new();
1248        toggle_chat_reaction(&mut rx, "πŸ‘");
1249        assert_eq!(rx.len(), 1);
1250        assert_eq!(rx[0].count, 1);
1251        assert!(rx[0].mine);
1252        toggle_chat_reaction(&mut rx, "πŸ‘");
1253        assert!(rx.is_empty());
1254    }
1255}