Skip to main content

arc_ui/data/
comment_thread.rs

1//! Ported from Arc (MIT) Β© 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/comment-thread/comment-thread.tsx` & `.module.css`
3//!
4//! P6 Component #16: `comment-thread`
5//!
6//! - Nested threaded discussion panel:
7//!   - Recursive replies capped at `max_depth` (default `2`) hanging from a left rail;
8//!   - Collapsible reply branches showing reply count and stacked participant avatars when folded;
9//!   - Inline `@Full Name` mention highlighting for known participants (`split_comment_mentions`);
10//!   - Reaction pills + inline reaction picker;
11//!   - Author-only inline edit (swaps body for edit composer) and two-step delete confirmation
12//!     (soft-deletes to a quiet placeholder if replies exist, or removes leaf comments cleanly);
13//!   - Thread-level Resolve / Reopen morphing the full thread into a compact resolved chip.
14
15use std::{
16    cell::RefCell,
17    collections::{HashMap, HashSet},
18    rc::Rc,
19};
20
21use arc_tokens::{ActiveArcTheme as _, Radii, Typography, oklab_mix};
22use gpui_kit::{
23    AnyElement, App, ElementId, Entity, Hsla, IntoElement, KeyDownEvent, MouseButton,
24    ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window, canvas,
25    component::input::{Input as KitInput, InputState},
26    div, point,
27    prelude::*,
28    px,
29};
30
31use super::avatar::initials_for;
32
33/// Default emoji options in the comment reaction picker (`comment-thread.tsx`).
34pub const COMMENT_DEFAULT_REACTIONS: &[&str] = &["πŸ‘", "❀️", "πŸŽ‰", "πŸ‘€", "πŸš€", "βœ…"];
35
36/// Author metadata for a comment or current user.
37#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct CommentAuthor {
39    pub id: SharedString,
40    pub name: SharedString,
41}
42
43impl CommentAuthor {
44    pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
45        Self {
46            id: id.into(),
47            name: name.into(),
48        }
49    }
50}
51
52/// Emoji reaction carrying the user ids who reacted.
53#[derive(Clone, Debug, Eq, PartialEq)]
54pub struct CommentReaction {
55    pub emoji: SharedString,
56    pub users: Vec<SharedString>,
57}
58
59impl CommentReaction {
60    pub fn new(emoji: impl Into<SharedString>, users: Vec<SharedString>) -> Self {
61        Self {
62            emoji: emoji.into(),
63            users,
64        }
65    }
66}
67
68/// One node in the comment tree.
69#[derive(Clone, Debug)]
70pub struct ThreadComment {
71    pub id: SharedString,
72    pub author: CommentAuthor,
73    pub body: SharedString,
74    pub created_at: SharedString,
75    pub edited: bool,
76    pub deleted: bool,
77    pub reactions: Vec<CommentReaction>,
78    pub replies: Vec<ThreadComment>,
79}
80
81impl ThreadComment {
82    pub fn new(
83        id: impl Into<SharedString>,
84        author: CommentAuthor,
85        body: impl Into<SharedString>,
86        created_at: impl Into<SharedString>,
87    ) -> Self {
88        Self {
89            id: id.into(),
90            author,
91            body: body.into(),
92            created_at: created_at.into(),
93            edited: false,
94            deleted: false,
95            reactions: Vec::new(),
96            replies: Vec::new(),
97        }
98    }
99
100    pub fn edited(mut self, edited: bool) -> Self {
101        self.edited = edited;
102        self
103    }
104
105    pub fn reaction(mut self, emoji: impl Into<SharedString>, users: Vec<&str>) -> Self {
106        self.reactions.push(CommentReaction::new(
107            emoji,
108            users.into_iter().map(SharedString::from).collect(),
109        ));
110        self
111    }
112
113    pub fn reply(mut self, reply: ThreadComment) -> Self {
114        self.replies.push(reply);
115        self
116    }
117}
118
119/// Pure helper: counts all non-deleted comments in the tree.
120pub fn count_comment_tree(list: &[ThreadComment]) -> usize {
121    list.iter()
122        .map(|c| usize::from(!c.deleted) + count_comment_tree(&c.replies))
123        .sum()
124}
125
126/// Pure helper: collects unique non-deleted authors in appearance order.
127pub fn collect_comment_authors(list: &[ThreadComment]) -> Vec<CommentAuthor> {
128    let mut seen = HashSet::new();
129    let mut out = Vec::new();
130    fn walk(
131        list: &[ThreadComment],
132        seen: &mut HashSet<SharedString>,
133        out: &mut Vec<CommentAuthor>,
134    ) {
135        for c in list {
136            if !c.deleted && seen.insert(c.author.id.clone()) {
137                out.push(c.author.clone());
138            }
139            walk(&c.replies, seen, out);
140        }
141    }
142    walk(list, &mut seen, &mut out);
143    out
144}
145
146/// Pure helper: finds the path of comment IDs from root to `target_id`.
147pub fn path_to_comment(list: &[ThreadComment], target_id: &str) -> Option<Vec<SharedString>> {
148    for c in list {
149        if c.id.as_ref() == target_id {
150            return Some(vec![c.id.clone()]);
151        }
152        if let Some(mut child_path) = path_to_comment(&c.replies, target_id) {
153            let mut full = vec![c.id.clone()];
154            full.append(&mut child_path);
155            return Some(full);
156        }
157    }
158    None
159}
160
161/// Pure helper: attaches `reply` under `reply_to_id` clamped to `max_depth` (or root if `None`).
162pub fn append_comment_reply(
163    list: &[ThreadComment],
164    reply_to_id: Option<&str>,
165    max_depth: usize,
166    reply: ThreadComment,
167) -> Vec<ThreadComment> {
168    let target_parent = reply_to_id.and_then(|rid| {
169        let path = path_to_comment(list, rid)?;
170        let idx = path.len().min(max_depth.max(1)).saturating_sub(1);
171        path.get(idx).cloned()
172    });
173    let Some(parent_id) = target_parent else {
174        let mut next = list.to_vec();
175        next.push(reply);
176        return next;
177    };
178    fn insert_under(
179        nodes: &[ThreadComment],
180        parent_id: &str,
181        reply: &ThreadComment,
182    ) -> Vec<ThreadComment> {
183        nodes
184            .iter()
185            .map(|c| {
186                let mut cloned = c.clone();
187                if c.id.as_ref() == parent_id {
188                    cloned.replies.push(reply.clone());
189                } else if !c.replies.is_empty() {
190                    cloned.replies = insert_under(&c.replies, parent_id, reply);
191                }
192                cloned
193            })
194            .collect()
195    }
196    insert_under(list, parent_id.as_ref(), &reply)
197}
198
199/// Pure helper: edits one comment body in place and marks `edited = true`.
200pub fn edit_comment_in_tree(
201    list: &[ThreadComment],
202    id: &str,
203    new_body: SharedString,
204) -> Vec<ThreadComment> {
205    list.iter()
206        .map(|c| {
207            let mut cloned = c.clone();
208            if c.id.as_ref() == id {
209                cloned.body = new_body.clone();
210                cloned.edited = true;
211            } else if !c.replies.is_empty() {
212                cloned.replies = edit_comment_in_tree(&c.replies, id, new_body.clone());
213            }
214            cloned
215        })
216        .collect()
217}
218
219/// Pure helper: deletes a leaf comment, or soft-deletes a comment that still has replies.
220pub fn delete_comment_in_tree(list: &[ThreadComment], id: &str) -> Vec<ThreadComment> {
221    let mut out = Vec::with_capacity(list.len());
222    for c in list {
223        if c.id.as_ref() == id {
224            if !c.replies.is_empty() {
225                let mut tombstone = c.clone();
226                tombstone.deleted = true;
227                tombstone.body = SharedString::from("");
228                tombstone.reactions.clear();
229                out.push(tombstone);
230            }
231            continue;
232        }
233        let mut cloned = c.clone();
234        if !c.replies.is_empty() {
235            cloned.replies = delete_comment_in_tree(&c.replies, id);
236        }
237        out.push(cloned);
238    }
239    out
240}
241
242/// Pure helper: toggles `user_id`'s `emoji` reaction on comment `id`.
243pub fn toggle_comment_reaction(
244    list: &[ThreadComment],
245    id: &str,
246    emoji: &str,
247    user_id: &str,
248) -> Vec<ThreadComment> {
249    list.iter()
250        .map(|c| {
251            let mut cloned = c.clone();
252            if c.id.as_ref() == id {
253                if let Some(pos) = cloned
254                    .reactions
255                    .iter()
256                    .position(|r| r.emoji.as_ref() == emoji)
257                {
258                    if let Some(upos) = cloned.reactions[pos]
259                        .users
260                        .iter()
261                        .position(|u| u.as_ref() == user_id)
262                    {
263                        cloned.reactions[pos].users.remove(upos);
264                        if cloned.reactions[pos].users.is_empty() {
265                            cloned.reactions.remove(pos);
266                        }
267                    } else {
268                        cloned.reactions[pos]
269                            .users
270                            .push(SharedString::from(user_id.to_string()));
271                    }
272                } else {
273                    cloned.reactions.push(CommentReaction::new(
274                        emoji.to_string(),
275                        vec![SharedString::from(user_id.to_string())],
276                    ));
277                }
278            } else if !c.replies.is_empty() {
279                cloned.replies = toggle_comment_reaction(&c.replies, id, emoji, user_id);
280            }
281            cloned
282        })
283        .collect()
284}
285
286/// Splits body text into `(segment, is_mention)` slices matching `@Full Name` of known authors.
287pub fn split_comment_mentions(text: &str, people: &[CommentAuthor]) -> Vec<(String, bool)> {
288    if people.is_empty() || !text.contains('@') {
289        return vec![(text.to_string(), false)];
290    }
291    let mut names: Vec<&str> = people.iter().map(|p| p.name.as_ref()).collect();
292    names.sort_by_key(|name| std::cmp::Reverse(name.len()));
293    let mut out = Vec::new();
294    let mut rest = text;
295    let mut plain_buf = String::new();
296
297    while !rest.is_empty() {
298        if rest.starts_with('@')
299            && let Some(matched) = names
300                .iter()
301                .find(|&&n| !n.is_empty() && rest[1..].starts_with(n))
302        {
303            if !plain_buf.is_empty() {
304                out.push((std::mem::take(&mut plain_buf), false));
305            }
306            let token_len = 1 + matched.len();
307            out.push((rest[..token_len].to_string(), true));
308            rest = &rest[token_len..];
309            continue;
310        }
311        let mut chars = rest.chars();
312        if let Some(ch) = chars.next() {
313            plain_buf.push(ch);
314            rest = chars.as_str();
315        }
316    }
317    if !plain_buf.is_empty() {
318        out.push((plain_buf, false));
319    }
320    out
321}
322
323fn paint_check(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
324    let mut pb = PathBuilder::stroke(px(1.75));
325    pb.move_to(point(px(cx - 4.0), px(cy + 0.2)));
326    pb.line_to(point(px(cx - 1.0), px(cy + 3.2)));
327    pb.line_to(point(px(cx + 4.5), px(cy - 3.2)));
328    if let Ok(p) = pb.build() {
329        window.paint_path(p, color);
330    }
331}
332
333fn paint_chevron_toggle(cx: f32, cy: f32, expanded: bool, color: Hsla, window: &mut Window) {
334    let mut pb = PathBuilder::stroke(px(1.5));
335    if expanded {
336        pb.move_to(point(px(cx - 3.5), px(cy - 1.8)));
337        pb.line_to(point(px(cx), px(cy + 2.2)));
338        pb.line_to(point(px(cx + 3.5), px(cy - 1.8)));
339    } else {
340        pb.move_to(point(px(cx - 1.8), px(cy - 3.5)));
341        pb.line_to(point(px(cx + 2.2), px(cy)));
342        pb.line_to(point(px(cx - 1.8), px(cy + 3.5)));
343    }
344    if let Ok(p) = pb.build() {
345        window.paint_path(p, color);
346    }
347}
348
349type CommentsCallback = Rc<dyn Fn(Vec<ThreadComment>, &mut Window, &mut App)>;
350type ResolvedCallback = Rc<dyn Fn(bool, &mut Window, &mut App)>;
351
352#[derive(Clone)]
353struct CommentThreadInternal {
354    editing_id: Option<SharedString>,
355    confirming_id: Option<SharedString>,
356    picker_id: Option<SharedString>,
357    reply_to: Option<(SharedString, SharedString)>,
358    collapsed: HashMap<SharedString, bool>,
359    composer_state: Entity<InputState>,
360    edit_state: Entity<InputState>,
361    next_serial: usize,
362}
363
364/// Arc `CommentThread` β€” nested replies, `@mention` highlighting, inline edit/delete, and resolve chip.
365#[derive(IntoElement)]
366pub struct CommentThread {
367    id: ElementId,
368    title: Option<SharedString>,
369    comments: Vec<ThreadComment>,
370    current_user: CommentAuthor,
371    people: Option<Vec<CommentAuthor>>,
372    resolved: bool,
373    reactions: Vec<SharedString>,
374    placeholder: SharedString,
375    max_depth: usize,
376    now_label: SharedString,
377    on_comments_change: Option<CommentsCallback>,
378    on_resolved_change: Option<ResolvedCallback>,
379}
380
381impl CommentThread {
382    pub fn new(
383        id: impl Into<ElementId>,
384        current_user: CommentAuthor,
385        comments: Vec<ThreadComment>,
386    ) -> Self {
387        Self {
388            id: id.into(),
389            title: None,
390            comments,
391            current_user,
392            people: None,
393            resolved: false,
394            reactions: COMMENT_DEFAULT_REACTIONS
395                .iter()
396                .map(|&e| SharedString::from(e))
397                .collect(),
398            placeholder: "Reply, or @mention someone".into(),
399            max_depth: 2,
400            now_label: "Just now".into(),
401            on_comments_change: None,
402            on_resolved_change: None,
403        }
404    }
405
406    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
407        self.title = Some(title.into());
408        self
409    }
410
411    pub fn people(mut self, people: Vec<CommentAuthor>) -> Self {
412        self.people = Some(people);
413        self
414    }
415
416    pub fn resolved(mut self, resolved: bool) -> Self {
417        self.resolved = resolved;
418        self
419    }
420
421    pub fn max_depth(mut self, depth: usize) -> Self {
422        self.max_depth = depth.max(1);
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 on_comments_change(
432        mut self,
433        handler: impl Fn(Vec<ThreadComment>, &mut Window, &mut App) + 'static,
434    ) -> Self {
435        self.on_comments_change = Some(Rc::new(handler));
436        self
437    }
438
439    pub fn on_resolved_change(
440        mut self,
441        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
442    ) -> Self {
443        self.on_resolved_change = Some(Rc::new(handler));
444        self
445    }
446}
447
448struct RenderCtx<'a> {
449    root_id: &'a ElementId,
450    theme: &'a arc_tokens::ArcTheme,
451    current_user: &'a CommentAuthor,
452    mentionable: &'a [CommentAuthor],
453    reactions: &'a [SharedString],
454    all_comments: &'a [ThreadComment],
455    shared: &'a Rc<RefCell<CommentThreadInternal>>,
456    edit_state: &'a Entity<InputState>,
457    on_comments_change: &'a Option<CommentsCallback>,
458}
459
460fn render_avatar_badge(name: &str, size: f32, theme: &arc_tokens::ArcTheme) -> AnyElement {
461    div()
462        .w(px(size))
463        .h(px(size))
464        .flex_shrink_0()
465        .rounded(Radii::PILL)
466        .bg(theme.colors.surface_muted)
467        .flex()
468        .items_center()
469        .justify_center()
470        .text_size(px((size * 0.38).round()))
471        .text_color(theme.colors.text_secondary)
472        .child(initials_for(name))
473        .into_any_element()
474}
475
476fn render_comment_node(comment: &ThreadComment, ctx: &RenderCtx<'_>, cx: &App) -> AnyElement {
477    let theme = ctx.theme;
478    let mine = comment.author.id == ctx.current_user.id;
479    let st = ctx.shared.borrow().clone();
480    let is_editing = st.editing_id.as_ref() == Some(&comment.id);
481    let is_confirming = st.confirming_id.as_ref() == Some(&comment.id);
482    let is_picking = st.picker_id.as_ref() == Some(&comment.id);
483    let collapsed = st.collapsed.get(&comment.id).copied().unwrap_or(false);
484
485    let mut main_col = div().flex_1().min_w_0().flex().flex_col().gap(px(3.0));
486
487    if comment.deleted {
488        main_col = main_col.child(
489            div()
490                .pt(px(4.0))
491                .text_size(Typography::TEXT_SM)
492                .text_color(theme.colors.text_muted)
493                .italic()
494                .child("This comment was deleted"),
495        );
496    } else {
497        // Meta header: author name + time + optional edited mark
498        let time_text = if comment.edited {
499            format!("{} Β· edited", comment.created_at)
500        } else {
501            comment.created_at.to_string()
502        };
503        main_col = main_col.child(
504            div()
505                .flex()
506                .items_baseline()
507                .gap(px(8.0))
508                .child(
509                    div()
510                        .text_size(Typography::TEXT_SM)
511                        .text_color(theme.colors.foreground)
512                        .child(comment.author.name.clone()),
513                )
514                .child(
515                    div()
516                        .text_size(Typography::TEXT_XS)
517                        .text_color(theme.colors.text_muted)
518                        .child(time_text),
519                ),
520        );
521
522        if is_editing {
523            let edit_text = ctx.edit_state.read(cx).value().to_string();
524            let can_save = !edit_text.trim().is_empty() && edit_text.trim() != comment.body.trim();
525            let shared_cancel = ctx.shared.clone();
526            let shared_save = ctx.shared.clone();
527            let edit_st_save = ctx.edit_state.clone();
528            let comment_id_save = comment.id.clone();
529            let comments_snap = ctx.all_comments.to_vec();
530            let on_change_save = ctx.on_comments_change.clone();
531
532            let edit_box = div()
533                .mt(px(4.0))
534                .flex()
535                .flex_col()
536                .gap(px(6.0))
537                .child(
538                    div()
539                        .px(px(10.0))
540                        .py(px(6.0))
541                        .rounded(px(12.0))
542                        .border_1()
543                        .border_color(theme.colors.border_strong)
544                        .bg(theme.colors.surface)
545                        .child(KitInput::new(ctx.edit_state).appearance(false)),
546                )
547                .child(
548                    div()
549                        .flex()
550                        .justify_end()
551                        .gap(px(6.0))
552                        .child(
553                            div()
554                                .id(ElementId::Name(
555                                    format!("arc-cm-cancel-{:?}-{}", ctx.root_id, comment.id)
556                                        .into(),
557                                ))
558                                .role(Role::Button)
559                                .h(px(30.0))
560                                .px(px(12.0))
561                                .rounded(Radii::PILL)
562                                .hover(|s| s.bg(theme.colors.surface_muted))
563                                .cursor_pointer()
564                                .flex()
565                                .items_center()
566                                .text_size(Typography::TEXT_XS)
567                                .text_color(theme.colors.text_secondary)
568                                .on_mouse_down(MouseButton::Left, move |_, window, _| {
569                                    shared_cancel.borrow_mut().editing_id = None;
570                                    window.refresh();
571                                })
572                                .child("Cancel"),
573                        )
574                        .child(
575                            div()
576                                .id(ElementId::Name(
577                                    format!("arc-cm-save-{:?}-{}", ctx.root_id, comment.id).into(),
578                                ))
579                                .role(Role::Button)
580                                .h(px(30.0))
581                                .px(px(12.0))
582                                .rounded(Radii::PILL)
583                                .bg(theme.colors.foreground)
584                                .text_color(theme.colors.background)
585                                .opacity(if can_save { 1.0 } else { 0.35 })
586                                .when(can_save, |el| el.cursor_pointer())
587                                .flex()
588                                .items_center()
589                                .text_size(Typography::TEXT_XS)
590                                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
591                                    let trimmed = edit_st_save.read(cx).value().trim().to_string();
592                                    if trimmed.is_empty() {
593                                        return;
594                                    }
595                                    shared_save.borrow_mut().editing_id = None;
596                                    let next = edit_comment_in_tree(
597                                        &comments_snap,
598                                        comment_id_save.as_ref(),
599                                        SharedString::from(trimmed),
600                                    );
601                                    if let Some(cb) = &on_change_save {
602                                        cb(next, window, cx);
603                                    }
604                                    window.refresh();
605                                })
606                                .child("Save"),
607                        ),
608                );
609            main_col = main_col.child(edit_box);
610        } else {
611            // Body with @mention spans highlighted in accent_strong
612            let segments = split_comment_mentions(comment.body.as_ref(), ctx.mentionable);
613            let mut body_row = div()
614                .flex()
615                .flex_wrap()
616                .text_size(Typography::TEXT_SM)
617                .text_color(theme.colors.text_secondary);
618            for (seg, is_mention) in segments {
619                if is_mention {
620                    body_row =
621                        body_row.child(div().text_color(theme.colors.accent_strong).child(seg));
622                } else {
623                    body_row = body_row.child(seg);
624                }
625            }
626            main_col = main_col.child(body_row);
627
628            // Footer: reaction pills + contextual actions / confirm / emoji picker
629            let mut footer = div()
630                .mt(px(4.0))
631                .flex()
632                .flex_wrap()
633                .items_center()
634                .gap(px(6.0));
635
636            for rx in &comment.reactions {
637                let pressed = rx.users.iter().any(|u| u == &ctx.current_user.id);
638                let border_c = if pressed {
639                    oklab_mix(theme.colors.border, theme.colors.accent, 0.45)
640                } else {
641                    theme.colors.border
642                };
643                let bg_c = if pressed {
644                    theme.colors.accent_subtle
645                } else {
646                    theme.colors.surface
647                };
648                let comments_snap = ctx.all_comments.to_vec();
649                let cid = comment.id.clone();
650                let emoji = rx.emoji.clone();
651                let uid = ctx.current_user.id.clone();
652                let on_change = ctx.on_comments_change.clone();
653
654                footer = footer.child(
655                    div()
656                        .id(ElementId::Name(
657                            format!("arc-cm-rx-{:?}-{}-{}", ctx.root_id, comment.id, rx.emoji)
658                                .into(),
659                        ))
660                        .role(Role::Button)
661                        .h(px(26.0))
662                        .pl(px(7.0))
663                        .pr(px(9.0))
664                        .rounded(Radii::PILL)
665                        .border_1()
666                        .border_color(border_c)
667                        .bg(bg_c)
668                        .hover(|s| s.border_color(theme.colors.border_strong))
669                        .cursor_pointer()
670                        .flex()
671                        .items_center()
672                        .gap(px(4.0))
673                        .text_size(Typography::TEXT_XS)
674                        .text_color(if pressed {
675                            theme.colors.foreground
676                        } else {
677                            theme.colors.text_secondary
678                        })
679                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
680                            let next = toggle_comment_reaction(
681                                &comments_snap,
682                                cid.as_ref(),
683                                emoji.as_ref(),
684                                uid.as_ref(),
685                            );
686                            if let Some(cb) = &on_change {
687                                cb(next, window, cx);
688                            }
689                        })
690                        .child(rx.emoji.clone())
691                        .child(rx.users.len().to_string()),
692                );
693            }
694
695            if is_confirming {
696                let shared_cancel = ctx.shared.clone();
697                let shared_del = ctx.shared.clone();
698                let comments_snap = ctx.all_comments.to_vec();
699                let cid = comment.id.clone();
700                let on_change = ctx.on_comments_change.clone();
701                footer = footer.child(
702                    div()
703                        .flex()
704                        .items_center()
705                        .gap(px(4.0))
706                        .child(
707                            div()
708                                .text_size(Typography::TEXT_XS)
709                                .text_color(theme.colors.foreground)
710                                .child("Delete this comment?"),
711                        )
712                        .child(
713                            div()
714                                .id(ElementId::Name(
715                                    format!("arc-cm-del-no-{:?}-{}", ctx.root_id, comment.id)
716                                        .into(),
717                                ))
718                                .role(Role::Button)
719                                .h(px(26.0))
720                                .px(px(8.0))
721                                .rounded(Radii::PILL)
722                                .hover(|s| s.bg(theme.colors.surface_muted))
723                                .cursor_pointer()
724                                .flex()
725                                .items_center()
726                                .text_size(Typography::TEXT_XS)
727                                .text_color(theme.colors.text_muted)
728                                .on_mouse_down(MouseButton::Left, move |_, window, _| {
729                                    shared_cancel.borrow_mut().confirming_id = None;
730                                    window.refresh();
731                                })
732                                .child("Cancel"),
733                        )
734                        .child(
735                            div()
736                                .id(ElementId::Name(
737                                    format!("arc-cm-del-yes-{:?}-{}", ctx.root_id, comment.id)
738                                        .into(),
739                                ))
740                                .role(Role::Button)
741                                .h(px(26.0))
742                                .px(px(8.0))
743                                .rounded(Radii::PILL)
744                                .hover(|s| {
745                                    s.bg(oklab_mix(theme.colors.surface, theme.colors.danger, 0.12))
746                                })
747                                .cursor_pointer()
748                                .flex()
749                                .items_center()
750                                .text_size(Typography::TEXT_XS)
751                                .text_color(theme.colors.danger)
752                                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
753                                    shared_del.borrow_mut().confirming_id = None;
754                                    let next = delete_comment_in_tree(&comments_snap, cid.as_ref());
755                                    if let Some(cb) = &on_change {
756                                        cb(next, window, cx);
757                                    }
758                                    window.refresh();
759                                })
760                                .child("Delete"),
761                        ),
762                );
763            } else if is_picking {
764                let mut picker = div().flex().items_center().gap(px(2.0));
765                for emoji in ctx.reactions {
766                    let comments_snap = ctx.all_comments.to_vec();
767                    let cid = comment.id.clone();
768                    let em = emoji.clone();
769                    let uid = ctx.current_user.id.clone();
770                    let shared_p = ctx.shared.clone();
771                    let on_change = ctx.on_comments_change.clone();
772                    picker = picker.child(
773                        div()
774                            .id(ElementId::Name(
775                                format!("arc-cm-pick-{:?}-{}-{}", ctx.root_id, comment.id, emoji)
776                                    .into(),
777                            ))
778                            .role(Role::Button)
779                            .w(px(26.0))
780                            .h(px(26.0))
781                            .rounded(Radii::PILL)
782                            .hover(|s| s.bg(theme.colors.surface_muted))
783                            .cursor_pointer()
784                            .flex()
785                            .items_center()
786                            .justify_center()
787                            .text_size(px(14.0))
788                            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
789                                shared_p.borrow_mut().picker_id = None;
790                                let next = toggle_comment_reaction(
791                                    &comments_snap,
792                                    cid.as_ref(),
793                                    em.as_ref(),
794                                    uid.as_ref(),
795                                );
796                                if let Some(cb) = &on_change {
797                                    cb(next, window, cx);
798                                }
799                                window.refresh();
800                            })
801                            .child(emoji.clone()),
802                    );
803                }
804                let shared_close = ctx.shared.clone();
805                picker = picker.child(
806                    div()
807                        .id(ElementId::Name(
808                            format!("arc-cm-pick-close-{:?}-{}", ctx.root_id, comment.id).into(),
809                        ))
810                        .role(Role::Button)
811                        .w(px(24.0))
812                        .h(px(24.0))
813                        .rounded(Radii::PILL)
814                        .hover(|s| s.bg(theme.colors.surface_muted))
815                        .cursor_pointer()
816                        .flex()
817                        .items_center()
818                        .justify_center()
819                        .text_size(Typography::TEXT_XS)
820                        .text_color(theme.colors.text_muted)
821                        .on_mouse_down(MouseButton::Left, move |_, window, _| {
822                            shared_close.borrow_mut().picker_id = None;
823                            window.refresh();
824                        })
825                        .child("Γ—"),
826                );
827                footer = footer.child(picker);
828            } else {
829                let shared_rx = ctx.shared.clone();
830                let cid_rx = comment.id.clone();
831                let shared_reply = ctx.shared.clone();
832                let cid_reply = comment.id.clone();
833                let author_reply = comment.author.name.clone();
834
835                let mut actions = div()
836                    .flex()
837                    .items_center()
838                    .gap(px(2.0))
839                    .child(
840                        div()
841                            .id(ElementId::Name(
842                                format!("arc-cm-act-rx-{:?}-{}", ctx.root_id, comment.id).into(),
843                            ))
844                            .role(Role::Button)
845                            .h(px(26.0))
846                            .px(px(8.0))
847                            .rounded(Radii::PILL)
848                            .hover(|s| {
849                                s.bg(theme.colors.surface_muted)
850                                    .text_color(theme.colors.foreground)
851                            })
852                            .cursor_pointer()
853                            .flex()
854                            .items_center()
855                            .text_size(Typography::TEXT_XS)
856                            .text_color(theme.colors.text_muted)
857                            .on_mouse_down(MouseButton::Left, move |_, window, _| {
858                                let mut s = shared_rx.borrow_mut();
859                                s.picker_id = Some(cid_rx.clone());
860                                s.confirming_id = None;
861                                window.refresh();
862                            })
863                            .child("+ React"),
864                    )
865                    .child(
866                        div()
867                            .id(ElementId::Name(
868                                format!("arc-cm-act-reply-{:?}-{}", ctx.root_id, comment.id).into(),
869                            ))
870                            .role(Role::Button)
871                            .h(px(26.0))
872                            .px(px(8.0))
873                            .rounded(Radii::PILL)
874                            .hover(|s| {
875                                s.bg(theme.colors.surface_muted)
876                                    .text_color(theme.colors.foreground)
877                            })
878                            .cursor_pointer()
879                            .flex()
880                            .items_center()
881                            .text_size(Typography::TEXT_XS)
882                            .text_color(theme.colors.text_muted)
883                            .on_mouse_down(MouseButton::Left, move |_, window, _| {
884                                shared_reply.borrow_mut().reply_to =
885                                    Some((cid_reply.clone(), author_reply.clone()));
886                                window.refresh();
887                            })
888                            .child("Reply"),
889                    );
890
891                if mine {
892                    let shared_edit = ctx.shared.clone();
893                    let edit_st = ctx.edit_state.clone();
894                    let cid_edit = comment.id.clone();
895                    let body_edit = comment.body.clone();
896                    let shared_del = ctx.shared.clone();
897                    let cid_del = comment.id.clone();
898
899                    actions = actions
900                        .child(
901                            div()
902                                .id(ElementId::Name(
903                                    format!("arc-cm-act-edit-{:?}-{}", ctx.root_id, comment.id)
904                                        .into(),
905                                ))
906                                .role(Role::Button)
907                                .h(px(26.0))
908                                .px(px(8.0))
909                                .rounded(Radii::PILL)
910                                .hover(|s| {
911                                    s.bg(theme.colors.surface_muted)
912                                        .text_color(theme.colors.foreground)
913                                })
914                                .cursor_pointer()
915                                .flex()
916                                .items_center()
917                                .text_size(Typography::TEXT_XS)
918                                .text_color(theme.colors.text_muted)
919                                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
920                                    edit_st.update(cx, |s, cx| {
921                                        s.set_value(body_edit.clone(), window, cx);
922                                    });
923                                    let mut s = shared_edit.borrow_mut();
924                                    s.editing_id = Some(cid_edit.clone());
925                                    s.confirming_id = None;
926                                    s.picker_id = None;
927                                    window.refresh();
928                                })
929                                .child("Edit"),
930                        )
931                        .child(
932                            div()
933                                .id(ElementId::Name(
934                                    format!("arc-cm-act-del-{:?}-{}", ctx.root_id, comment.id)
935                                        .into(),
936                                ))
937                                .role(Role::Button)
938                                .h(px(26.0))
939                                .px(px(8.0))
940                                .rounded(Radii::PILL)
941                                .hover(|s| {
942                                    s.bg(theme.colors.surface_muted)
943                                        .text_color(theme.colors.danger)
944                                })
945                                .cursor_pointer()
946                                .flex()
947                                .items_center()
948                                .text_size(Typography::TEXT_XS)
949                                .text_color(theme.colors.text_muted)
950                                .on_mouse_down(MouseButton::Left, move |_, window, _| {
951                                    let mut s = shared_del.borrow_mut();
952                                    s.confirming_id = Some(cid_del.clone());
953                                    s.editing_id = None;
954                                    s.picker_id = None;
955                                    window.refresh();
956                                })
957                                .child("Delete"),
958                        );
959                }
960                footer = footer.child(actions);
961            }
962
963            main_col = main_col.child(footer);
964        }
965    }
966
967    // Collapse / expand replies toggle
968    if !comment.replies.is_empty() {
969        let reply_count = count_comment_tree(&comment.replies);
970        let toggle_label = if collapsed {
971            format!(
972                "Show {} {}",
973                reply_count,
974                if reply_count == 1 { "reply" } else { "replies" }
975            )
976        } else {
977            "Hide replies".to_string()
978        };
979        let shared_toggle = ctx.shared.clone();
980        let cid_toggle = comment.id.clone();
981        let chevron_color = theme.colors.text_muted;
982
983        let mut toggle_btn = div()
984            .id(ElementId::Name(
985                format!("arc-cm-toggle-{:?}-{}", ctx.root_id, comment.id).into(),
986            ))
987            .role(Role::Button)
988            .h(px(26.0))
989            .px(px(6.0))
990            .rounded(Radii::PILL)
991            .hover(|s| s.bg(theme.colors.surface_muted))
992            .cursor_pointer()
993            .flex()
994            .items_center()
995            .gap(px(5.0))
996            .on_mouse_down(MouseButton::Left, move |_, window, _| {
997                let mut s = shared_toggle.borrow_mut();
998                let next = !s.collapsed.get(&cid_toggle).copied().unwrap_or(false);
999                s.collapsed.insert(cid_toggle.clone(), next);
1000                window.refresh();
1001            })
1002            .child(
1003                canvas(
1004                    |b, _, _| b,
1005                    move |b, _, window, _| {
1006                        let cx = f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
1007                        let cy = f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
1008                        paint_chevron_toggle(cx, cy, !collapsed, chevron_color, window);
1009                    },
1010                )
1011                .w(px(12.0))
1012                .h(px(12.0)),
1013            )
1014            .child(
1015                div()
1016                    .text_size(Typography::TEXT_XS)
1017                    .text_color(theme.colors.text_secondary)
1018                    .child(toggle_label),
1019            );
1020
1021        if collapsed {
1022            let reply_authors = collect_comment_authors(&comment.replies);
1023            let mut stack = div().flex().items_center().pl(px(4.0));
1024            for a in reply_authors.iter().take(3) {
1025                stack = stack.child(render_avatar_badge(a.name.as_ref(), 18.0, theme));
1026            }
1027            toggle_btn = toggle_btn.child(stack);
1028        }
1029
1030        main_col = main_col.child(toggle_btn);
1031    }
1032
1033    // Comment header + body row
1034    let avatar_el = if comment.deleted {
1035        div()
1036            .w(px(28.0))
1037            .h(px(28.0))
1038            .flex_shrink_0()
1039            .rounded(Radii::PILL)
1040            .border_1()
1041            .border_color(theme.colors.border_strong)
1042            .into_any_element()
1043    } else {
1044        render_avatar_badge(comment.author.name.as_ref(), 28.0, theme)
1045    };
1046
1047    let mut wrapper = div().w_full().flex().flex_col().child(
1048        div()
1049            .w_full()
1050            .p(px(10.0))
1051            .flex()
1052            .items_start()
1053            .gap(px(10.0))
1054            .child(avatar_el)
1055            .child(main_col),
1056    );
1057
1058    if !comment.replies.is_empty() && !collapsed {
1059        let mut replies_col = div()
1060            .ml(px(24.0))
1061            .pl(px(12.0))
1062            .border_l_1()
1063            .border_color(theme.colors.border)
1064            .flex()
1065            .flex_col();
1066        for reply in &comment.replies {
1067            replies_col = replies_col.child(render_comment_node(reply, ctx, cx));
1068        }
1069        wrapper = wrapper.child(replies_col);
1070    }
1071
1072    wrapper.into_any_element()
1073}
1074
1075impl RenderOnce for CommentThread {
1076    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1077        let theme = cx.arc_theme().clone();
1078        let placeholder_str = self.placeholder.clone();
1079
1080        let state = window.use_keyed_state(
1081            ElementId::Name(format!("arc-comment-thread-state-{:?}", self.id).into()),
1082            cx,
1083            |window, cx| {
1084                let composer_state =
1085                    cx.new(|cx| InputState::new(window, cx).placeholder(placeholder_str.clone()));
1086                let edit_state =
1087                    cx.new(|cx| InputState::new(window, cx).placeholder("Edit comment"));
1088                Rc::new(RefCell::new(CommentThreadInternal {
1089                    editing_id: None,
1090                    confirming_id: None,
1091                    picker_id: None,
1092                    reply_to: None,
1093                    collapsed: HashMap::new(),
1094                    composer_state,
1095                    edit_state,
1096                    next_serial: 1,
1097                }))
1098            },
1099        );
1100        let shared = state.read(cx).clone();
1101        let composer_state = shared.borrow().composer_state.clone();
1102        let edit_state = shared.borrow().edit_state.clone();
1103        let reply_to = shared.borrow().reply_to.clone();
1104
1105        let total = count_comment_tree(&self.comments);
1106        let participants = collect_comment_authors(&self.comments);
1107        let mentionable = self.people.clone().unwrap_or_else(|| {
1108            let mut list = participants.clone();
1109            if !list.iter().any(|p| p.id == self.current_user.id) {
1110                list.push(self.current_user.clone());
1111            }
1112            list
1113        });
1114
1115        let comment_count_label = format!(
1116            "{} {}",
1117            total,
1118            if total == 1 { "comment" } else { "comments" }
1119        );
1120        let people_count_label = format!(
1121            "{} {}",
1122            participants.len(),
1123            if participants.len() == 1 {
1124                "person"
1125            } else {
1126                "people"
1127            }
1128        );
1129
1130        let root_radius = if self.resolved {
1131            Radii::SURFACE
1132        } else {
1133            Radii::PANEL
1134        };
1135        let mut root = div()
1136            .id(self.id.clone())
1137            .role(Role::Region)
1138            .aria_label("Comment thread")
1139            .w_full()
1140            .rounded(root_radius)
1141            .border_1()
1142            .border_color(theme.colors.border)
1143            .bg(theme.colors.surface)
1144            .overflow_hidden();
1145
1146        if self.resolved {
1147            let success_color = theme.colors.success;
1148            let on_resolved = self.on_resolved_change.clone();
1149            let mut title_line = div().flex().items_center().gap(px(4.0)).child(
1150                div()
1151                    .text_size(Typography::TEXT_SM)
1152                    .text_color(theme.colors.foreground)
1153                    .child("Resolved"),
1154            );
1155            if let Some(title) = &self.title {
1156                title_line = title_line.child(
1157                    div()
1158                        .text_size(Typography::TEXT_SM)
1159                        .text_color(theme.colors.text_secondary)
1160                        .child(format!("Β· {title}")),
1161                );
1162            }
1163
1164            let mut avatar_stack = div().flex().items_center().gap(px(2.0));
1165            for author in participants.iter().take(3) {
1166                avatar_stack =
1167                    avatar_stack.child(render_avatar_badge(author.name.as_ref(), 22.0, &theme));
1168            }
1169
1170            root = root.child(
1171                div()
1172                    .w_full()
1173                    .px(px(14.0))
1174                    .py(px(10.0))
1175                    .flex()
1176                    .items_center()
1177                    .gap(px(12.0))
1178                    .child(
1179                        div()
1180                            .w(px(24.0))
1181                            .h(px(24.0))
1182                            .rounded(Radii::PILL)
1183                            .bg(oklab_mix(theme.colors.surface, theme.colors.success, 0.14))
1184                            .flex()
1185                            .items_center()
1186                            .justify_center()
1187                            .child(
1188                                canvas(
1189                                    |b, _, _| b,
1190                                    move |b, _, window, _| {
1191                                        let cx =
1192                                            f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
1193                                        let cy =
1194                                            f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
1195                                        paint_check(cx, cy, success_color, window);
1196                                    },
1197                                )
1198                                .w(px(14.0))
1199                                .h(px(14.0)),
1200                            ),
1201                    )
1202                    .child(
1203                        div()
1204                            .flex_1()
1205                            .min_w_0()
1206                            .flex()
1207                            .flex_col()
1208                            .child(title_line)
1209                            .child(
1210                                div()
1211                                    .text_size(Typography::TEXT_XS)
1212                                    .text_color(theme.colors.text_muted)
1213                                    .child(format!("{comment_count_label} Β· {people_count_label}")),
1214                            ),
1215                    )
1216                    .child(avatar_stack)
1217                    .child(
1218                        div()
1219                            .id(ElementId::Name(
1220                                format!("arc-cm-reopen-{:?}", self.id).into(),
1221                            ))
1222                            .role(Role::Button)
1223                            .h(px(32.0))
1224                            .px(px(12.0))
1225                            .rounded(Radii::PILL)
1226                            .border_1()
1227                            .border_color(theme.colors.border)
1228                            .bg(theme.colors.surface)
1229                            .hover(|s| s.bg(theme.colors.surface_muted))
1230                            .cursor_pointer()
1231                            .flex()
1232                            .items_center()
1233                            .text_size(Typography::TEXT_XS)
1234                            .text_color(theme.colors.foreground)
1235                            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1236                                if let Some(cb) = &on_resolved {
1237                                    cb(false, window, cx);
1238                                }
1239                            })
1240                            .child("Reopen"),
1241                    ),
1242            );
1243            return root;
1244        }
1245
1246        // Open thread header
1247        let on_resolve = self.on_resolved_change.clone();
1248        let can_resolve = total > 0;
1249        let success_color = theme.colors.success;
1250        let mut heading = div().flex().flex_col();
1251        if let Some(title) = &self.title {
1252            heading = heading.child(
1253                div()
1254                    .text_size(Typography::TEXT_SM)
1255                    .text_color(theme.colors.foreground)
1256                    .child(title.clone()),
1257            );
1258        }
1259        heading = heading.child(
1260            div()
1261                .text_size(Typography::TEXT_XS)
1262                .text_color(theme.colors.text_muted)
1263                .child(comment_count_label),
1264        );
1265
1266        let header = div()
1267            .w_full()
1268            .pl(px(18.0))
1269            .pr(px(12.0))
1270            .pt(px(12.0))
1271            .pb(px(8.0))
1272            .flex()
1273            .items_center()
1274            .justify_between()
1275            .gap(px(12.0))
1276            .child(heading)
1277            .child(
1278                div()
1279                    .id(ElementId::Name(
1280                        format!("arc-cm-resolve-{:?}", self.id).into(),
1281                    ))
1282                    .role(Role::Button)
1283                    .h(px(32.0))
1284                    .pl(px(10.0))
1285                    .pr(px(12.0))
1286                    .rounded(Radii::PILL)
1287                    .border_1()
1288                    .border_color(theme.colors.border)
1289                    .bg(theme.colors.surface)
1290                    .opacity(if can_resolve { 1.0 } else { 0.45 })
1291                    .when(can_resolve, |el| {
1292                        el.cursor_pointer()
1293                            .hover(|s| s.bg(theme.colors.surface_muted))
1294                    })
1295                    .flex()
1296                    .items_center()
1297                    .gap(px(6.0))
1298                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1299                        if can_resolve && let Some(cb) = &on_resolve {
1300                            cb(true, window, cx);
1301                        }
1302                    })
1303                    .child(
1304                        canvas(
1305                            |b, _, _| b,
1306                            move |b, _, window, _| {
1307                                let cx = f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
1308                                let cy = f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
1309                                paint_check(cx, cy, success_color, window);
1310                            },
1311                        )
1312                        .w(px(14.0))
1313                        .h(px(14.0)),
1314                    )
1315                    .child(
1316                        div()
1317                            .text_size(Typography::TEXT_XS)
1318                            .text_color(theme.colors.foreground)
1319                            .child("Resolve"),
1320                    ),
1321            );
1322
1323        // Comment tree body
1324        let rctx = RenderCtx {
1325            root_id: &self.id,
1326            theme: &theme,
1327            current_user: &self.current_user,
1328            mentionable: &mentionable,
1329            reactions: &self.reactions,
1330            all_comments: &self.comments,
1331            shared: &shared,
1332            edit_state: &edit_state,
1333            on_comments_change: &self.on_comments_change,
1334        };
1335
1336        let body_section = if self.comments.is_empty() {
1337            div()
1338                .px(px(18.0))
1339                .py(px(12.0))
1340                .text_size(Typography::TEXT_SM)
1341                .text_color(theme.colors.text_muted)
1342                .child("No comments yet. Start the conversation below.")
1343                .into_any_element()
1344        } else {
1345            let mut list = div().px(px(8.0)).flex().flex_col();
1346            for comment in &self.comments {
1347                list = list.child(render_comment_node(comment, &rctx, cx));
1348            }
1349            list.into_any_element()
1350        };
1351
1352        // Bottom composer with optional "Replying to X" banner & @mention quick chips
1353        let current_draft = composer_state.read(cx).value().to_string();
1354        let can_send = !current_draft.trim().is_empty();
1355
1356        // Detect trailing `@query` for lightweight mention autocomplete bar
1357        let active_mention_query = current_draft.rsplit_once('@').and_then(|(before, after)| {
1358            if (before.is_empty() || before.ends_with(char::is_whitespace))
1359                && !after.contains(char::is_whitespace)
1360            {
1361                Some(after.to_lowercase())
1362            } else {
1363                None
1364            }
1365        });
1366        let mention_matches: Vec<&CommentAuthor> = if let Some(q) = &active_mention_query {
1367            mentionable
1368                .iter()
1369                .filter(|p| {
1370                    let lower = p.name.to_lowercase();
1371                    lower.starts_with(q.as_str())
1372                        || lower.split_whitespace().any(|w| w.starts_with(q.as_str()))
1373                })
1374                .take(4)
1375                .collect()
1376        } else {
1377            Vec::new()
1378        };
1379
1380        let submit_reply = {
1381            let composer_st = composer_state.clone();
1382            let shared_s = shared.clone();
1383            let comments_snap = self.comments.clone();
1384            let current_user = self.current_user.clone();
1385            let now_label = self.now_label.clone();
1386            let max_depth = self.max_depth;
1387            let on_change = self.on_comments_change.clone();
1388
1389            Rc::new(move |window: &mut Window, cx: &mut App| {
1390                let trimmed = composer_st.read(cx).value().trim().to_string();
1391                if trimmed.is_empty() {
1392                    return;
1393                }
1394                let (serial, reply_parent) = {
1395                    let mut st = shared_s.borrow_mut();
1396                    let s = st.next_serial;
1397                    st.next_serial += 1;
1398                    let r = st.reply_to.take().map(|(id, _)| id);
1399                    if let Some(pid) = &r {
1400                        st.collapsed.insert(pid.clone(), false);
1401                    }
1402                    (s, r)
1403                };
1404                composer_st.update(cx, |state, cx| {
1405                    state.set_value("", window, cx);
1406                });
1407                let new_comment = ThreadComment::new(
1408                    format!("c-local-{serial}"),
1409                    current_user.clone(),
1410                    trimmed,
1411                    now_label.clone(),
1412                );
1413                let next = append_comment_reply(
1414                    &comments_snap,
1415                    reply_parent.as_deref(),
1416                    max_depth,
1417                    new_comment,
1418                );
1419                if let Some(cb) = &on_change {
1420                    cb(next, window, cx);
1421                }
1422                window.refresh();
1423            })
1424        };
1425
1426        let submit_click = submit_reply.clone();
1427        let submit_key = submit_reply.clone();
1428
1429        let mut composer_area = div()
1430            .w_full()
1431            .mt(px(4.0))
1432            .px(px(12.0))
1433            .py(px(10.0))
1434            .border_t_1()
1435            .border_color(theme.colors.border_subtle)
1436            .flex()
1437            .flex_col()
1438            .gap(px(8.0));
1439
1440        if let Some((_, target_name)) = &reply_to {
1441            let shared_cancel_reply = shared.clone();
1442            composer_area = composer_area.child(
1443                div()
1444                    .pl(px(38.0))
1445                    .flex()
1446                    .items_center()
1447                    .gap(px(6.0))
1448                    .text_size(Typography::TEXT_XS)
1449                    .text_color(theme.colors.text_secondary)
1450                    .child("Replying to")
1451                    .child(
1452                        div()
1453                            .text_color(theme.colors.foreground)
1454                            .child(target_name.clone()),
1455                    )
1456                    .child(
1457                        div()
1458                            .id(ElementId::Name(
1459                                format!("arc-cm-cancel-reply-{:?}", self.id).into(),
1460                            ))
1461                            .role(Role::Button)
1462                            .w(px(20.0))
1463                            .h(px(20.0))
1464                            .rounded(Radii::PILL)
1465                            .hover(|s| s.bg(theme.colors.surface_muted))
1466                            .cursor_pointer()
1467                            .flex()
1468                            .items_center()
1469                            .justify_center()
1470                            .on_mouse_down(MouseButton::Left, move |_, window, _| {
1471                                shared_cancel_reply.borrow_mut().reply_to = None;
1472                                window.refresh();
1473                            })
1474                            .child("Γ—"),
1475                    ),
1476            );
1477        }
1478
1479        if !mention_matches.is_empty() {
1480            let mut bar = div().pl(px(38.0)).flex().flex_wrap().gap(px(6.0));
1481            for person in mention_matches {
1482                let pname = person.name.clone();
1483                let cst = composer_state.clone();
1484                bar = bar.child(
1485                    div()
1486                        .id(ElementId::Name(
1487                            format!("arc-cm-mention-{:?}-{}", self.id, person.id).into(),
1488                        ))
1489                        .role(Role::ListBoxOption)
1490                        .h(px(28.0))
1491                        .px(px(8.0))
1492                        .rounded(px(10.0))
1493                        .border_1()
1494                        .border_color(theme.colors.border)
1495                        .bg(theme.colors.surface_raised)
1496                        .hover(|s| s.bg(theme.colors.surface_muted))
1497                        .cursor_pointer()
1498                        .flex()
1499                        .items_center()
1500                        .gap(px(6.0))
1501                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1502                            let cur = cst.read(cx).value().to_string();
1503                            let next = if let Some((head, _)) = cur.rsplit_once('@') {
1504                                format!("{head}@{pname} ")
1505                            } else {
1506                                format!("{cur}@{pname} ")
1507                            };
1508                            cst.update(cx, |s, cx| {
1509                                s.set_value(next, window, cx);
1510                            });
1511                        })
1512                        .child(render_avatar_badge(person.name.as_ref(), 18.0, &theme))
1513                        .child(
1514                            div()
1515                                .text_size(Typography::TEXT_XS)
1516                                .text_color(theme.colors.foreground)
1517                                .child(person.name.clone()),
1518                        ),
1519                );
1520            }
1521            composer_area = composer_area.child(bar);
1522        }
1523
1524        composer_area = composer_area.child(
1525            div()
1526                .w_full()
1527                .flex()
1528                .items_center()
1529                .gap(px(10.0))
1530                .child(render_avatar_badge(
1531                    self.current_user.name.as_ref(),
1532                    28.0,
1533                    &theme,
1534                ))
1535                .child(
1536                    div()
1537                        .flex_1()
1538                        .min_w_0()
1539                        .min_h(px(36.0))
1540                        .px(px(12.0))
1541                        .py(px(6.0))
1542                        .rounded(Radii::CONTROL)
1543                        .border_1()
1544                        .border_color(theme.colors.border)
1545                        .bg(theme.colors.surface)
1546                        .on_key_down(move |event: &KeyDownEvent, window, cx| {
1547                            if event.keystroke.key == "enter"
1548                                && (event.keystroke.modifiers.control
1549                                    || event.keystroke.modifiers.platform)
1550                            {
1551                                submit_key(window, cx);
1552                            }
1553                        })
1554                        .child(KitInput::new(&composer_state).appearance(false)),
1555                )
1556                .child(
1557                    div()
1558                        .id(ElementId::Name(format!("arc-cm-send-{:?}", self.id).into()))
1559                        .role(Role::Button)
1560                        .h(px(36.0))
1561                        .px(px(14.0))
1562                        .rounded(Radii::PILL)
1563                        .bg(theme.colors.foreground)
1564                        .text_color(theme.colors.background)
1565                        .opacity(if can_send { 1.0 } else { 0.35 })
1566                        .when(can_send, |el| el.cursor_pointer())
1567                        .flex()
1568                        .items_center()
1569                        .text_size(Typography::TEXT_SM)
1570                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1571                            submit_click(window, cx);
1572                        })
1573                        .child("Send"),
1574                ),
1575        );
1576
1577        root.child(
1578            div()
1579                .w_full()
1580                .flex()
1581                .flex_col()
1582                .child(header)
1583                .child(body_section)
1584                .child(composer_area),
1585        )
1586    }
1587}
1588
1589#[cfg(test)]
1590mod tests {
1591    use super::*;
1592
1593    #[test]
1594    fn comment_thread_tree_operations_and_mentions() {
1595        let alice = CommentAuthor::new("a", "Alice Chen");
1596        let bob = CommentAuthor::new("b", "Bob Lin");
1597        let root_comment =
1598            ThreadComment::new("c1", alice.clone(), "Ping @Bob Lin on hero copy", "2h")
1599                .reply(ThreadComment::new("c2", bob.clone(), "Looks crisp!", "1h"));
1600
1601        let tree = vec![root_comment];
1602        assert_eq!(count_comment_tree(&tree), 2);
1603        assert_eq!(collect_comment_authors(&tree).len(), 2);
1604
1605        // Mention splitting highlights @Bob Lin
1606        let parts =
1607            split_comment_mentions("Ping @Bob Lin on hero copy", &[alice.clone(), bob.clone()]);
1608        assert_eq!(
1609            parts,
1610            vec![
1611                ("Ping ".to_string(), false),
1612                ("@Bob Lin".to_string(), true),
1613                (" on hero copy".to_string(), false),
1614            ]
1615        );
1616
1617        // Reply deeper than max_depth=2 attaches to depth-2 parent (c2)
1618        let r3 = ThreadComment::new("c3", alice.clone(), "Deep reply", "Just now");
1619        let tree = append_comment_reply(&tree, Some("c2"), 2, r3);
1620        assert_eq!(count_comment_tree(&tree), 3);
1621
1622        // Soft-delete c1 because it has replies; leaf c3 deletes completely
1623        let tree = delete_comment_in_tree(&tree, "c1");
1624        assert!(tree[0].deleted);
1625        assert_eq!(count_comment_tree(&tree), 2);
1626
1627        // Reaction toggle adds then removes
1628        let tree = toggle_comment_reaction(&tree, "c2", "πŸ‘", "a");
1629        assert_eq!(tree[0].replies[0].reactions.len(), 1);
1630        let tree = toggle_comment_reaction(&tree, "c2", "πŸ‘", "a");
1631        assert!(tree[0].replies[0].reactions.is_empty());
1632    }
1633}