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, 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}
358
359/// Arc `ChatThread` β€” grouped chat messages, reactions, read receipts, typing dots, and composer.
360#[derive(IntoElement)]
361pub struct ChatThread {
362    id: ElementId,
363    label: SharedString,
364    participants: Vec<ChatParticipant>,
365    current_user_id: SharedString,
366    messages: Vec<ChatMessage>,
367    typing_ids: Vec<SharedString>,
368    read_by: HashMap<SharedString, SharedString>,
369    reactions: Vec<SharedString>,
370    placeholder: SharedString,
371    composer: bool,
372    group_window_ms: i64,
373    now_ms: i64,
374    height_px: f32,
375    on_send: Option<SendCallback>,
376    on_react: Option<ReactCallback>,
377    on_retry: Option<RetryCallback>,
378}
379
380impl ChatThread {
381    pub fn new(
382        id: impl Into<ElementId>,
383        participants: Vec<ChatParticipant>,
384        current_user_id: impl Into<SharedString>,
385        messages: Vec<ChatMessage>,
386    ) -> Self {
387        Self {
388            id: id.into(),
389            label: "Conversation".into(),
390            participants,
391            current_user_id: current_user_id.into(),
392            messages,
393            typing_ids: Vec::new(),
394            read_by: HashMap::new(),
395            reactions: CHAT_DEFAULT_REACTIONS
396                .iter()
397                .map(|&e| SharedString::from(e))
398                .collect(),
399            placeholder: "Message".into(),
400            composer: true,
401            group_window_ms: CHAT_DEFAULT_GROUP_WINDOW_MS,
402            now_ms: 1_745_000_000_000,
403            height_px: 440.0,
404            on_send: None,
405            on_react: None,
406            on_retry: None,
407        }
408    }
409
410    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
411        self.label = label.into();
412        self
413    }
414
415    pub fn typing(mut self, ids: Vec<SharedString>) -> Self {
416        self.typing_ids = ids;
417        self
418    }
419
420    pub fn read_by(mut self, read_by: HashMap<SharedString, SharedString>) -> Self {
421        self.read_by = read_by;
422        self
423    }
424
425    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
426        self.placeholder = placeholder.into();
427        self
428    }
429
430    pub fn composer(mut self, enabled: bool) -> Self {
431        self.composer = enabled;
432        self
433    }
434
435    pub fn now_ms(mut self, now_ms: i64) -> Self {
436        self.now_ms = now_ms;
437        self
438    }
439
440    pub fn height(mut self, px_height: f32) -> Self {
441        self.height_px = px_height.max(240.0);
442        self
443    }
444
445    pub fn on_send(
446        mut self,
447        handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
448    ) -> Self {
449        self.on_send = Some(Rc::new(handler));
450        self
451    }
452
453    pub fn on_react(
454        mut self,
455        handler: impl Fn(SharedString, SharedString, &mut Window, &mut App) + 'static,
456    ) -> Self {
457        self.on_react = Some(Rc::new(handler));
458        self
459    }
460
461    pub fn on_retry(
462        mut self,
463        handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
464    ) -> Self {
465        self.on_retry = Some(Rc::new(handler));
466        self
467    }
468}
469
470impl RenderOnce for ChatThread {
471    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
472        let theme = cx.arc_theme().clone();
473        let reduced = is_reduced_motion(cx);
474        let placeholder_str = self.placeholder.clone();
475
476        let state = window.use_keyed_state(
477            ElementId::Name(format!("arc-chat-thread-state-{:?}", self.id).into()),
478            cx,
479            |window, cx| {
480                let input_state =
481                    cx.new(|cx| InputState::new(window, cx).placeholder(placeholder_str.clone()));
482                Rc::new(RefCell::new(ChatThreadInternal {
483                    picker_for: None,
484                    input_state,
485                }))
486            },
487        );
488        let shared = state.read(cx).clone();
489        let picker_for = shared.borrow().picker_for.clone();
490        let input_state = shared.borrow().input_state.clone();
491
492        let people: HashMap<SharedString, ChatParticipant> = self
493            .participants
494            .iter()
495            .map(|p| (p.id.clone(), p.clone()))
496            .collect();
497
498        // Build read receipts map: message_id -> Vec<ChatParticipant>
499        let mut receipts: HashMap<SharedString, Vec<ChatParticipant>> = HashMap::new();
500        let mut furthest_read_idx: isize = -1;
501        for (person_id, msg_id) in &self.read_by {
502            if person_id == &self.current_user_id {
503                continue;
504            }
505            let Some(who) = people.get(person_id) else {
506                continue;
507            };
508            if let Some((idx, msg)) = self
509                .messages
510                .iter()
511                .enumerate()
512                .find(|(_, m)| &m.id == msg_id)
513            {
514                if &msg.author_id == person_id {
515                    continue;
516                }
517                furthest_read_idx = furthest_read_idx.max(idx as isize);
518                receipts
519                    .entry(msg_id.clone())
520                    .or_default()
521                    .push(who.clone());
522            }
523        }
524
525        let last_mine_idx = self
526            .messages
527            .iter()
528            .rposition(|m| m.author_id == self.current_user_id);
529
530        let rows = build_chat_rows(
531            &self.messages,
532            self.current_user_id.as_ref(),
533            self.group_window_ms,
534            self.now_ms,
535        );
536
537        let other_bubble_bg = if matches!(theme.mode, arc_tokens::ThemeMode::Dark) {
538            theme.colors.surface_raised
539        } else {
540            theme.colors.surface_muted
541        };
542
543        let mut list = div()
544            .id(ElementId::Name(
545                format!("arc-chat-thread-log-{:?}", self.id).into(),
546            ))
547            .role(Role::Log)
548            .aria_label(self.label)
549            .flex_1()
550            .overflow_y_scroll()
551            .px(px(16.0))
552            .py(px(12.0))
553            .flex()
554            .flex_col()
555            .gap(px(2.0));
556
557        for row in rows {
558            match row {
559                ChatRow::Day { key, label } => {
560                    list = list.child(
561                        div()
562                            .id(ElementId::Name(
563                                format!("arc-chat-day-{:?}-{}", self.id, key).into(),
564                            ))
565                            .w_full()
566                            .py(px(8.0))
567                            .flex()
568                            .items_center()
569                            .gap(px(12.0))
570                            .child(div().flex_1().h(px(1.0)).bg(theme.colors.border_subtle))
571                            .child(
572                                div()
573                                    .text_size(Typography::TEXT_XS)
574                                    .text_color(theme.colors.text_muted)
575                                    .child(label),
576                            )
577                            .child(div().flex_1().h(px(1.0)).bg(theme.colors.border_subtle)),
578                    );
579                }
580                ChatRow::Message {
581                    index,
582                    mine,
583                    first,
584                    last,
585                } => {
586                    let msg = &self.messages[index];
587                    let author_name = people
588                        .get(&msg.author_id)
589                        .map(|p| p.name.clone())
590                        .unwrap_or_else(|| SharedString::from("Unknown"));
591                    let msg_id = msg.id.clone();
592                    let is_picker_open = picker_for.as_ref() == Some(&msg_id);
593                    let seen_by = receipts.get(&msg_id).cloned().unwrap_or_default();
594                    let show_status = mine && last_mine_idx == Some(index);
595                    let effective_status = match msg.status {
596                        ChatMessageStatus::Failed => ChatMessageStatus::Failed,
597                        ChatMessageStatus::Sending => ChatMessageStatus::Sending,
598                        _ if furthest_read_idx >= index as isize => ChatMessageStatus::Read,
599                        other => other,
600                    };
601
602                    // Corner radii: inner side tightens to 6px inside a run of messages
603                    let r_full = px(18.0);
604                    let r_tight = px(6.0);
605                    let (r_tl, r_tr, r_bl, r_br) = if mine {
606                        (
607                            r_full,
608                            if first { r_full } else { r_tight },
609                            r_full,
610                            if last { r_full } else { r_tight },
611                        )
612                    } else {
613                        (
614                            if first { r_full } else { r_tight },
615                            r_full,
616                            if last { r_full } else { r_tight },
617                            r_full,
618                        )
619                    };
620
621                    let mut stack = div()
622                        .max_w(px(360.0))
623                        .flex()
624                        .flex_col()
625                        .gap(px(4.0))
626                        .when(mine, |el| el.items_end())
627                        .when(!mine, |el| el.items_start());
628
629                    if first {
630                        let mut meta = div().px(px(10.0)).flex().items_baseline().gap(px(6.0));
631                        if !mine {
632                            meta = meta.child(
633                                div()
634                                    .text_size(Typography::TEXT_XS)
635                                    .text_color(theme.colors.text_secondary)
636                                    .child(author_name.clone()),
637                            );
638                        }
639                        meta = meta.child(
640                            div()
641                                .text_size(Typography::TEXT_XS)
642                                .text_color(theme.colors.text_muted)
643                                .child(format_chat_time(msg.created_at_ms)),
644                        );
645                        stack = stack.child(meta);
646                    }
647
648                    // Bubble + attachments
649                    let mut parts = div()
650                        .flex()
651                        .flex_col()
652                        .gap(px(4.0))
653                        .when(mine, |el| el.items_end())
654                        .when(!mine, |el| el.items_start());
655
656                    for att in &msg.attachments {
657                        let chip = div()
658                            .px(px(12.0))
659                            .py(px(8.0))
660                            .rounded(px(14.0))
661                            .border_1()
662                            .border_color(theme.colors.border)
663                            .bg(theme.colors.surface)
664                            .flex()
665                            .items_center()
666                            .gap(px(8.0))
667                            .child(
668                                div()
669                                    .text_size(Typography::TEXT_XS)
670                                    .text_color(theme.colors.text_muted)
671                                    .child(match att.kind {
672                                        ChatAttachmentKind::Image => "IMG",
673                                        ChatAttachmentKind::File => "FILE",
674                                    }),
675                            )
676                            .child(
677                                div()
678                                    .flex()
679                                    .flex_col()
680                                    .child(
681                                        div()
682                                            .text_size(Typography::TEXT_SM)
683                                            .text_color(theme.colors.foreground)
684                                            .child(att.name.clone()),
685                                    )
686                                    .when_some(att.size_bytes, |el, sz| {
687                                        el.child(
688                                            div()
689                                                .text_size(Typography::TEXT_XS)
690                                                .text_color(theme.colors.text_muted)
691                                                .child(format_chat_bytes(sz)),
692                                        )
693                                    }),
694                            );
695                        parts = parts.child(chip);
696                    }
697
698                    if let Some(text) = &msg.text {
699                        let bubble = div()
700                            .px(px(13.0))
701                            .py(px(8.0))
702                            .rounded_tl(r_tl)
703                            .rounded_tr(r_tr)
704                            .rounded_bl(r_bl)
705                            .rounded_br(r_br)
706                            .bg(if mine {
707                                theme.colors.accent
708                            } else {
709                                other_bubble_bg
710                            })
711                            .text_color(if mine {
712                                theme.colors.accent_foreground
713                            } else {
714                                theme.colors.foreground
715                            })
716                            .text_size(Typography::TEXT_SM)
717                            .opacity(if msg.status == ChatMessageStatus::Failed {
718                                0.6
719                            } else {
720                                1.0
721                            })
722                            .child(text.clone());
723                        parts = parts.child(bubble);
724                    }
725
726                    // Reaction trigger button beside the bubble
727                    let shared_toggle = shared.clone();
728                    let msg_id_toggle = msg_id.clone();
729                    let smile_color = if is_picker_open {
730                        theme.colors.foreground
731                    } else {
732                        theme.colors.text_muted
733                    };
734                    let react_btn = div()
735                        .id(ElementId::Name(
736                            format!("arc-chat-react-btn-{:?}-{}", self.id, msg_id).into(),
737                        ))
738                        .role(Role::Button)
739                        .aria_label("Add reaction")
740                        .w(px(26.0))
741                        .h(px(26.0))
742                        .rounded(Radii::PILL)
743                        .when(is_picker_open, |el| el.bg(theme.colors.surface_muted))
744                        .hover(|s| s.bg(theme.colors.surface_muted))
745                        .cursor_pointer()
746                        .flex()
747                        .items_center()
748                        .justify_center()
749                        .on_mouse_down(MouseButton::Left, move |_, window, _| {
750                            let mut st = shared_toggle.borrow_mut();
751                            if st.picker_for.as_ref() == Some(&msg_id_toggle) {
752                                st.picker_for = None;
753                            } else {
754                                st.picker_for = Some(msg_id_toggle.clone());
755                            }
756                            window.refresh();
757                        })
758                        .child(
759                            canvas(
760                                |b, _, _| b,
761                                move |b, _, window, _| {
762                                    let cx = f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
763                                    let cy = f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
764                                    paint_smile_plus(cx, cy, smile_color, window);
765                                },
766                            )
767                            .w(px(14.0))
768                            .h(px(14.0)),
769                        );
770
771                    let line = if mine {
772                        div()
773                            .flex()
774                            .items_center()
775                            .gap(px(6.0))
776                            .child(react_btn)
777                            .child(parts)
778                    } else {
779                        div()
780                            .flex()
781                            .items_center()
782                            .gap(px(6.0))
783                            .child(parts)
784                            .child(react_btn)
785                    };
786                    stack = stack.child(line);
787
788                    // Inline emoji picker popover strip when open for this message
789                    if is_picker_open {
790                        let mut picker_strip = div()
791                            .p(px(4.0))
792                            .rounded(Radii::PILL)
793                            .border_1()
794                            .border_color(theme.colors.border)
795                            .bg(theme.colors.surface_raised)
796                            .shadow(Shadows::floating(theme.mode))
797                            .flex()
798                            .items_center()
799                            .gap(px(2.0));
800
801                        for emoji in &self.reactions {
802                            let emoji_val = emoji.clone();
803                            let msg_id_pick = msg_id.clone();
804                            let on_react = self.on_react.clone();
805                            let shared_pick = shared.clone();
806                            picker_strip = picker_strip.child(
807                                div()
808                                    .id(ElementId::Name(
809                                        format!("arc-chat-pick-{:?}-{}-{}", self.id, msg_id, emoji)
810                                            .into(),
811                                    ))
812                                    .role(Role::Button)
813                                    .w(px(30.0))
814                                    .h(px(30.0))
815                                    .rounded(Radii::PILL)
816                                    .hover(|s| s.bg(theme.colors.surface_muted))
817                                    .cursor_pointer()
818                                    .flex()
819                                    .items_center()
820                                    .justify_center()
821                                    .text_size(px(16.0))
822                                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
823                                        shared_pick.borrow_mut().picker_for = None;
824                                        if let Some(cb) = &on_react {
825                                            cb(msg_id_pick.clone(), emoji_val.clone(), window, cx);
826                                        }
827                                        window.refresh();
828                                    })
829                                    .child(emoji.clone()),
830                            );
831                        }
832                        stack = stack.child(picker_strip);
833                    }
834
835                    // Existing reaction pills
836                    if !msg.reactions.is_empty() {
837                        let mut reaction_row = div()
838                            .flex()
839                            .flex_wrap()
840                            .gap(px(4.0))
841                            .when(mine, |el| el.justify_end());
842
843                        for reaction in &msg.reactions {
844                            let border_c = if reaction.mine {
845                                oklab_mix(theme.colors.border_subtle, theme.colors.accent, 0.35)
846                            } else {
847                                theme.colors.border_subtle
848                            };
849                            let bg_c = if reaction.mine {
850                                oklab_mix(theme.colors.surface, theme.colors.accent, 0.10)
851                            } else {
852                                theme.colors.surface
853                            };
854                            let on_react = self.on_react.clone();
855                            let msg_id_r = msg_id.clone();
856                            let emoji_r = reaction.emoji.clone();
857                            reaction_row = reaction_row.child(
858                                div()
859                                    .id(ElementId::Name(
860                                        format!(
861                                            "arc-chat-rx-{:?}-{}-{}",
862                                            self.id, msg_id, reaction.emoji
863                                        )
864                                        .into(),
865                                    ))
866                                    .role(Role::Button)
867                                    .h(px(24.0))
868                                    .pl(px(7.0))
869                                    .pr(px(8.0))
870                                    .rounded(Radii::PILL)
871                                    .border_1()
872                                    .border_color(border_c)
873                                    .bg(bg_c)
874                                    .hover(|s| s.border_color(theme.colors.border_strong))
875                                    .cursor_pointer()
876                                    .flex()
877                                    .items_center()
878                                    .gap(px(4.0))
879                                    .text_size(Typography::TEXT_XS)
880                                    .text_color(if reaction.mine {
881                                        theme.colors.foreground
882                                    } else {
883                                        theme.colors.text_secondary
884                                    })
885                                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
886                                        if let Some(cb) = &on_react {
887                                            cb(msg_id_r.clone(), emoji_r.clone(), window, cx);
888                                        }
889                                    })
890                                    .child(reaction.emoji.clone())
891                                    .child(reaction.count.to_string()),
892                            );
893                        }
894                        stack = stack.child(reaction_row);
895                    }
896
897                    // Delivery status & read receipt avatars
898                    if show_status || !seen_by.is_empty() {
899                        let mut receipt_row = div().px(px(6.0)).flex().items_center().gap(px(6.0));
900
901                        if show_status {
902                            let status_label = match effective_status {
903                                ChatMessageStatus::Sending => "Sending",
904                                ChatMessageStatus::Sent => "Sent",
905                                ChatMessageStatus::Delivered => "Delivered",
906                                ChatMessageStatus::Read => "Read",
907                                ChatMessageStatus::Failed => "Not delivered",
908                            };
909                            receipt_row = receipt_row.child(
910                                div()
911                                    .text_size(Typography::TEXT_XS)
912                                    .text_color(if effective_status == ChatMessageStatus::Failed {
913                                        theme.colors.danger
914                                    } else {
915                                        theme.colors.text_muted
916                                    })
917                                    .child(status_label),
918                            );
919                            if effective_status == ChatMessageStatus::Failed
920                                && let Some(on_retry) = self.on_retry.clone()
921                            {
922                                let msg_id_retry = msg_id.clone();
923                                receipt_row = receipt_row.child(
924                                    div()
925                                        .id(ElementId::Name(
926                                            format!("arc-chat-retry-{:?}-{}", self.id, msg_id)
927                                                .into(),
928                                        ))
929                                        .role(Role::Button)
930                                        .px(px(8.0))
931                                        .py(px(2.0))
932                                        .rounded(Radii::PILL)
933                                        .border_1()
934                                        .border_color(theme.colors.border)
935                                        .bg(theme.colors.surface)
936                                        .hover(|s| s.bg(theme.colors.surface_muted))
937                                        .cursor_pointer()
938                                        .text_size(Typography::TEXT_XS)
939                                        .text_color(theme.colors.foreground)
940                                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
941                                            on_retry(msg_id_retry.clone(), window, cx);
942                                        })
943                                        .child("Retry"),
944                                );
945                            }
946                        }
947
948                        if !seen_by.is_empty() {
949                            let mut readers = div().flex().items_center();
950                            for reader in &seen_by {
951                                readers = readers.child(
952                                    div()
953                                        .w(px(16.0))
954                                        .h(px(16.0))
955                                        .rounded(Radii::PILL)
956                                        .bg(theme.colors.surface_muted)
957                                        .border_1()
958                                        .border_color(theme.colors.surface)
959                                        .flex()
960                                        .items_center()
961                                        .justify_center()
962                                        .text_size(px(8.0))
963                                        .text_color(theme.colors.text_secondary)
964                                        .child(initials_for(reader.name.as_ref())),
965                                );
966                            }
967                            receipt_row = receipt_row.child(readers);
968                        }
969
970                        stack = stack.child(receipt_row);
971                    }
972
973                    // Row container with left avatar gutter for other participants
974                    let mut row_el = div()
975                        .w_full()
976                        .mt(px(if first { 12.0 } else { 2.0 }))
977                        .flex()
978                        .items_end()
979                        .gap(px(8.0))
980                        .when(mine, |el| el.justify_end());
981
982                    if !mine {
983                        let gutter = if last {
984                            div()
985                                .w(px(28.0))
986                                .h(px(28.0))
987                                .flex_shrink_0()
988                                .rounded(Radii::PILL)
989                                .bg(theme.colors.surface_muted)
990                                .flex()
991                                .items_center()
992                                .justify_center()
993                                .text_size(px(11.0))
994                                .text_color(theme.colors.text_secondary)
995                                .child(initials_for(author_name.as_ref()))
996                        } else {
997                            div().w(px(28.0)).flex_shrink_0()
998                        };
999                        row_el = row_el.child(gutter);
1000                    }
1001
1002                    row_el = row_el.child(stack);
1003                    list = list.child(row_el);
1004                }
1005            }
1006        }
1007
1008        // Typing indicator row with 3 breathing dots
1009        let typers: Vec<&ChatParticipant> = self
1010            .typing_ids
1011            .iter()
1012            .filter(|id| *id != &self.current_user_id)
1013            .filter_map(|id| people.get(id))
1014            .collect();
1015        if let Some(first_typer) = typers.first() {
1016            let phase_s = motion_now(cx);
1017            if !reduced {
1018                window.request_animation_frame();
1019            }
1020            let mut dots = div().flex().items_center().gap(px(4.0));
1021            for i in 0..3 {
1022                let (alpha, dy) = if reduced {
1023                    (0.6, 0.0)
1024                } else {
1025                    let t = ((phase_s - i as f64 * 0.16).rem_euclid(1.2) / 1.2) as f32;
1026                    let wave = if t < 0.6 {
1027                        (t / 0.6 * std::f32::consts::PI).sin()
1028                    } else {
1029                        0.0
1030                    };
1031                    (0.35 + 0.65 * wave, -3.0 * wave)
1032                };
1033                dots = dots.child(
1034                    div()
1035                        .w(px(6.0))
1036                        .h(px(6.0))
1037                        .mt(px(dy))
1038                        .rounded(Radii::PILL)
1039                        .bg(theme.colors.text_muted)
1040                        .opacity(alpha),
1041                );
1042            }
1043            list = list.child(
1044                div()
1045                    .mt(px(10.0))
1046                    .flex()
1047                    .items_end()
1048                    .gap(px(8.0))
1049                    .child(
1050                        div()
1051                            .w(px(28.0))
1052                            .h(px(28.0))
1053                            .rounded(Radii::PILL)
1054                            .bg(theme.colors.surface_muted)
1055                            .flex()
1056                            .items_center()
1057                            .justify_center()
1058                            .text_size(px(11.0))
1059                            .text_color(theme.colors.text_secondary)
1060                            .child(initials_for(first_typer.name.as_ref())),
1061                    )
1062                    .child(
1063                        div()
1064                            .h(px(34.0))
1065                            .px(px(14.0))
1066                            .rounded(px(18.0))
1067                            .bg(other_bubble_bg)
1068                            .flex()
1069                            .items_center()
1070                            .child(dots),
1071                    ),
1072            );
1073        }
1074
1075        let mut root = div()
1076            .id(self.id.clone())
1077            .w_full()
1078            .h(px(self.height_px))
1079            .rounded(Radii::PANEL)
1080            .border_1()
1081            .border_color(theme.colors.border)
1082            .bg(theme.colors.surface)
1083            .overflow_hidden()
1084            .flex()
1085            .flex_col()
1086            .child(list);
1087
1088        // Composer bar
1089        if self.composer {
1090            let current_text = input_state.read(cx).value().to_string();
1091            let ready = !current_text.trim().is_empty();
1092            let send_action = {
1093                let input_st = input_state.clone();
1094                let on_send = self.on_send.clone();
1095                Rc::new(move |window: &mut Window, cx: &mut App| {
1096                    let raw = input_st.read(cx).value().to_string();
1097                    let trimmed = raw.trim().to_string();
1098                    if trimmed.is_empty() {
1099                        return;
1100                    }
1101                    input_st.update(cx, |state, cx| {
1102                        state.set_value("", window, cx);
1103                    });
1104                    if let Some(cb) = &on_send {
1105                        cb(SharedString::from(trimmed), window, cx);
1106                    }
1107                })
1108            };
1109
1110            let send_on_click = send_action.clone();
1111            let send_on_key = send_action.clone();
1112            let arrow_color = if ready {
1113                theme.colors.accent_foreground
1114            } else {
1115                theme.colors.text_muted
1116            };
1117
1118            let composer_box = div()
1119                .w_full()
1120                .px(px(12.0))
1121                .py(px(10.0))
1122                .border_t_1()
1123                .border_color(theme.colors.border_subtle)
1124                .child(
1125                    div()
1126                        .w_full()
1127                        .min_h(px(36.0))
1128                        .pl(px(12.0))
1129                        .pr(px(5.0))
1130                        .py(px(4.0))
1131                        .rounded(Radii::PANEL)
1132                        .border_1()
1133                        .border_color(theme.colors.border)
1134                        .bg(theme.colors.surface)
1135                        .flex()
1136                        .items_center()
1137                        .gap(px(6.0))
1138                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
1139                            if event.keystroke.key == "enter" && !event.keystroke.modifiers.shift {
1140                                send_on_key(window, cx);
1141                            }
1142                        })
1143                        .child(
1144                            div()
1145                                .flex_1()
1146                                .min_w_0()
1147                                .child(KitInput::new(&input_state).appearance(false)),
1148                        )
1149                        .child(
1150                            div()
1151                                .id(ElementId::Name(
1152                                    format!("arc-chat-send-{:?}", self.id).into(),
1153                                ))
1154                                .role(Role::Button)
1155                                .aria_label("Send")
1156                                .w(px(32.0))
1157                                .h(px(32.0))
1158                                .rounded(Radii::PILL)
1159                                .bg(if ready {
1160                                    theme.colors.accent
1161                                } else {
1162                                    gpui_kit::hsla(0.0, 0.0, 0.0, 0.0)
1163                                })
1164                                .when(ready, |el| el.cursor_pointer())
1165                                .flex()
1166                                .items_center()
1167                                .justify_center()
1168                                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1169                                    send_on_click(window, cx);
1170                                })
1171                                .child(
1172                                    canvas(
1173                                        |b, _, _| b,
1174                                        move |b, _, window, _| {
1175                                            let cx = f32::from(b.origin.x)
1176                                                + f32::from(b.size.width) * 0.5;
1177                                            let cy = f32::from(b.origin.y)
1178                                                + f32::from(b.size.height) * 0.5;
1179                                            paint_arrow_up(cx, cy, arrow_color, window);
1180                                        },
1181                                    )
1182                                    .w(px(16.0))
1183                                    .h(px(16.0)),
1184                                ),
1185                        ),
1186                );
1187            root = root.child(composer_box);
1188        }
1189
1190        root
1191    }
1192}
1193
1194#[cfg(test)]
1195mod tests {
1196    use super::*;
1197
1198    #[test]
1199    fn chat_thread_grouping_bytes_and_reactions() {
1200        assert_eq!(format_chat_bytes(512), "512 B");
1201        assert_eq!(format_chat_bytes(2048), "2 KB");
1202        assert_eq!(format_chat_bytes(2_621_440), "2.5 MB");
1203
1204        let now = 1_745_000_000_000_i64;
1205        let msgs = vec![
1206            ChatMessage::new("m1", "a", "Hello", now - 120_000),
1207            ChatMessage::new("m2", "a", "Second line", now - 60_000),
1208            ChatMessage::new("m3", "me", "Got it", now - 10_000),
1209        ];
1210        let rows = build_chat_rows(&msgs, "me", CHAT_DEFAULT_GROUP_WINDOW_MS, now);
1211        assert_eq!(rows.len(), 4); // 1 day + 3 messages
1212        assert!(matches!(rows[0], ChatRow::Day { .. }));
1213        assert_eq!(
1214            rows[1],
1215            ChatRow::Message {
1216                index: 0,
1217                mine: false,
1218                first: true,
1219                last: false,
1220            }
1221        );
1222        assert_eq!(
1223            rows[2],
1224            ChatRow::Message {
1225                index: 1,
1226                mine: false,
1227                first: false,
1228                last: true,
1229            }
1230        );
1231        assert_eq!(
1232            rows[3],
1233            ChatRow::Message {
1234                index: 2,
1235                mine: true,
1236                first: true,
1237                last: true,
1238            }
1239        );
1240
1241        let mut rx = Vec::new();
1242        toggle_chat_reaction(&mut rx, "πŸ‘");
1243        assert_eq!(rx.len(), 1);
1244        assert_eq!(rx[0].count, 1);
1245        assert!(rx[0].mine);
1246        toggle_chat_reaction(&mut rx, "πŸ‘");
1247        assert!(rx.is_empty());
1248    }
1249}