1use std::{
16 cell::{Cell, RefCell},
17 collections::{HashMap, HashSet},
18 rc::Rc,
19};
20
21use arc_motion::{
22 ArcPresence, CubicBezier, arc_spring, arc_spring_with_options, is_reduced_motion, motion_now,
23 spring::SpringOptions,
24};
25use arc_tokens::{ActiveArcTheme as _, Radii, SpringSpec, Typography, oklab_mix};
26use gpui_kit::{
27 AnyElement, App, ElementId, Entity, Focusable as _, Hsla, IntoElement, KeyDownEvent,
28 MouseButton, ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled,
29 TestSupportExt as _, Window, canvas,
30 component::input::{Input as KitInput, InputEvent, InputState},
31 div, point,
32 prelude::*,
33 px,
34};
35
36use super::avatar::initials_for;
37
38pub const COMMENT_DEFAULT_REACTIONS: &[&str] = &["👍", "❤️", "🎉", "👀", "🚀", "✅"];
40
41#[derive(Clone, Debug, Eq, PartialEq)]
43pub struct CommentAuthor {
44 pub id: SharedString,
45 pub name: SharedString,
46}
47
48impl CommentAuthor {
49 pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
50 Self {
51 id: id.into(),
52 name: name.into(),
53 }
54 }
55}
56
57#[derive(Clone, Debug, Eq, PartialEq)]
59pub struct CommentReaction {
60 pub emoji: SharedString,
61 pub users: Vec<SharedString>,
62}
63
64impl CommentReaction {
65 pub fn new(emoji: impl Into<SharedString>, users: Vec<SharedString>) -> Self {
66 Self {
67 emoji: emoji.into(),
68 users,
69 }
70 }
71}
72
73#[derive(Clone, Debug)]
75pub struct ThreadComment {
76 pub id: SharedString,
77 pub author: CommentAuthor,
78 pub body: SharedString,
79 pub created_at: SharedString,
80 pub edited: bool,
81 pub deleted: bool,
82 pub reactions: Vec<CommentReaction>,
83 pub replies: Vec<ThreadComment>,
84}
85
86impl ThreadComment {
87 pub fn new(
88 id: impl Into<SharedString>,
89 author: CommentAuthor,
90 body: impl Into<SharedString>,
91 created_at: impl Into<SharedString>,
92 ) -> Self {
93 Self {
94 id: id.into(),
95 author,
96 body: body.into(),
97 created_at: created_at.into(),
98 edited: false,
99 deleted: false,
100 reactions: Vec::new(),
101 replies: Vec::new(),
102 }
103 }
104
105 pub fn edited(mut self, edited: bool) -> Self {
106 self.edited = edited;
107 self
108 }
109
110 pub fn reaction(mut self, emoji: impl Into<SharedString>, users: Vec<&str>) -> Self {
111 self.reactions.push(CommentReaction::new(
112 emoji,
113 users.into_iter().map(SharedString::from).collect(),
114 ));
115 self
116 }
117
118 pub fn reply(mut self, reply: ThreadComment) -> Self {
119 self.replies.push(reply);
120 self
121 }
122}
123
124pub fn count_comment_tree(list: &[ThreadComment]) -> usize {
126 list.iter()
127 .map(|c| usize::from(!c.deleted) + count_comment_tree(&c.replies))
128 .sum()
129}
130
131pub fn collect_comment_authors(list: &[ThreadComment]) -> Vec<CommentAuthor> {
133 let mut seen = HashSet::new();
134 let mut out = Vec::new();
135 fn walk(
136 list: &[ThreadComment],
137 seen: &mut HashSet<SharedString>,
138 out: &mut Vec<CommentAuthor>,
139 ) {
140 for c in list {
141 if !c.deleted && seen.insert(c.author.id.clone()) {
142 out.push(c.author.clone());
143 }
144 walk(&c.replies, seen, out);
145 }
146 }
147 walk(list, &mut seen, &mut out);
148 out
149}
150
151pub fn path_to_comment(list: &[ThreadComment], target_id: &str) -> Option<Vec<SharedString>> {
153 for c in list {
154 if c.id.as_ref() == target_id {
155 return Some(vec![c.id.clone()]);
156 }
157 if let Some(mut child_path) = path_to_comment(&c.replies, target_id) {
158 let mut full = vec![c.id.clone()];
159 full.append(&mut child_path);
160 return Some(full);
161 }
162 }
163 None
164}
165
166pub fn append_comment_reply(
168 list: &[ThreadComment],
169 reply_to_id: Option<&str>,
170 max_depth: usize,
171 reply: ThreadComment,
172) -> Vec<ThreadComment> {
173 let target_parent = reply_to_id.and_then(|rid| {
174 let path = path_to_comment(list, rid)?;
175 let idx = path.len().min(max_depth.max(1)).saturating_sub(1);
176 path.get(idx).cloned()
177 });
178 let Some(parent_id) = target_parent else {
179 let mut next = list.to_vec();
180 next.push(reply);
181 return next;
182 };
183 fn insert_under(
184 nodes: &[ThreadComment],
185 parent_id: &str,
186 reply: &ThreadComment,
187 ) -> Vec<ThreadComment> {
188 nodes
189 .iter()
190 .map(|c| {
191 let mut cloned = c.clone();
192 if c.id.as_ref() == parent_id {
193 cloned.replies.push(reply.clone());
194 } else if !c.replies.is_empty() {
195 cloned.replies = insert_under(&c.replies, parent_id, reply);
196 }
197 cloned
198 })
199 .collect()
200 }
201 insert_under(list, parent_id.as_ref(), &reply)
202}
203
204pub fn edit_comment_in_tree(
206 list: &[ThreadComment],
207 id: &str,
208 new_body: SharedString,
209) -> Vec<ThreadComment> {
210 list.iter()
211 .map(|c| {
212 let mut cloned = c.clone();
213 if c.id.as_ref() == id {
214 cloned.body = new_body.clone();
215 cloned.edited = true;
216 } else if !c.replies.is_empty() {
217 cloned.replies = edit_comment_in_tree(&c.replies, id, new_body.clone());
218 }
219 cloned
220 })
221 .collect()
222}
223
224pub fn delete_comment_in_tree(list: &[ThreadComment], id: &str) -> Vec<ThreadComment> {
226 let mut out = Vec::with_capacity(list.len());
227 for c in list {
228 if c.id.as_ref() == id {
229 if !c.replies.is_empty() {
230 let mut tombstone = c.clone();
231 tombstone.deleted = true;
232 tombstone.body = SharedString::from("");
233 tombstone.reactions.clear();
234 out.push(tombstone);
235 }
236 continue;
237 }
238 let mut cloned = c.clone();
239 if !c.replies.is_empty() {
240 cloned.replies = delete_comment_in_tree(&c.replies, id);
241 }
242 out.push(cloned);
243 }
244 out
245}
246
247pub fn toggle_comment_reaction(
249 list: &[ThreadComment],
250 id: &str,
251 emoji: &str,
252 user_id: &str,
253) -> Vec<ThreadComment> {
254 list.iter()
255 .map(|c| {
256 let mut cloned = c.clone();
257 if c.id.as_ref() == id {
258 if let Some(pos) = cloned
259 .reactions
260 .iter()
261 .position(|r| r.emoji.as_ref() == emoji)
262 {
263 if let Some(upos) = cloned.reactions[pos]
264 .users
265 .iter()
266 .position(|u| u.as_ref() == user_id)
267 {
268 cloned.reactions[pos].users.remove(upos);
269 if cloned.reactions[pos].users.is_empty() {
270 cloned.reactions.remove(pos);
271 }
272 } else {
273 cloned.reactions[pos]
274 .users
275 .push(SharedString::from(user_id.to_string()));
276 }
277 } else {
278 cloned.reactions.push(CommentReaction::new(
279 emoji.to_string(),
280 vec![SharedString::from(user_id.to_string())],
281 ));
282 }
283 } else if !c.replies.is_empty() {
284 cloned.replies = toggle_comment_reaction(&c.replies, id, emoji, user_id);
285 }
286 cloned
287 })
288 .collect()
289}
290
291pub fn split_comment_mentions(text: &str, people: &[CommentAuthor]) -> Vec<(String, bool)> {
293 if people.is_empty() || !text.contains('@') {
294 return vec![(text.to_string(), false)];
295 }
296 let mut names: Vec<&str> = people.iter().map(|p| p.name.as_ref()).collect();
297 names.sort_by_key(|name| std::cmp::Reverse(name.len()));
298 let mut out = Vec::new();
299 let mut rest = text;
300 let mut plain_buf = String::new();
301
302 while !rest.is_empty() {
303 if rest.starts_with('@')
304 && let Some(matched) = names
305 .iter()
306 .find(|&&n| !n.is_empty() && rest[1..].starts_with(n))
307 {
308 if !plain_buf.is_empty() {
309 out.push((std::mem::take(&mut plain_buf), false));
310 }
311 let token_len = 1 + matched.len();
312 out.push((rest[..token_len].to_string(), true));
313 rest = &rest[token_len..];
314 continue;
315 }
316 let mut chars = rest.chars();
317 if let Some(ch) = chars.next() {
318 plain_buf.push(ch);
319 rest = chars.as_str();
320 }
321 }
322 if !plain_buf.is_empty() {
323 out.push((plain_buf, false));
324 }
325 out
326}
327
328fn paint_check(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
329 let mut pb = PathBuilder::stroke(px(1.75));
330 pb.move_to(point(px(cx - 4.0), px(cy + 0.2)));
331 pb.line_to(point(px(cx - 1.0), px(cy + 3.2)));
332 pb.line_to(point(px(cx + 4.5), px(cy - 3.2)));
333 if let Ok(p) = pb.build() {
334 window.paint_path(p, color);
335 }
336}
337
338fn paint_chevron_toggle(cx: f32, cy: f32, degrees: f32, color: Hsla, window: &mut Window) {
339 let mut pb = PathBuilder::stroke(px(1.5));
340 let (sin, cos) = degrees.to_radians().sin_cos();
341 for (i, (x, y)) in [(-1.8, -3.5), (2.2, 0.0), (-1.8, 3.5)]
342 .into_iter()
343 .enumerate()
344 {
345 let p = point(px(cx + x * cos - y * sin), px(cy + x * sin + y * cos));
346 if i == 0 {
347 pb.move_to(p);
348 } else {
349 pb.line_to(p);
350 }
351 }
352 if let Ok(p) = pb.build() {
353 window.paint_path(p, color);
354 }
355}
356
357type CommentsCallback = Rc<dyn Fn(Vec<ThreadComment>, &mut Window, &mut App)>;
358type ResolvedCallback = Rc<dyn Fn(bool, &mut Window, &mut App)>;
359
360fn animated_comment_height(
363 id: ElementId,
364 present: bool,
365 content: impl IntoElement,
366 window: &mut Window,
367 cx: &mut App,
368) -> AnyElement {
369 let theme = cx.arc_theme().clone();
370 let measured = window
371 .use_keyed_state(
372 ElementId::NamedChild(id.clone().into(), "natural-height".into()),
373 cx,
374 |_, _| Rc::new(Cell::new(None::<f32>)),
375 )
376 .read(cx)
377 .clone();
378 let natural_height = measured.get();
379 let target = if present {
380 natural_height.unwrap_or(0.0)
381 } else {
382 0.0
383 };
384 let height_spec = SpringSpec::visual(0.42, 0.0).as_physical();
386 let height = if natural_height.is_some() {
387 arc_spring_with_options(
388 (id.clone(), "height"),
389 target,
390 SpringOptions::new(height_spec),
391 window,
392 cx,
393 )
394 } else {
395 arc_motion::SpringSample {
396 value: 0.0,
397 velocity: 0.0,
398 settled: true,
399 }
400 };
401 let fade = ArcPresence::new((id.clone(), "fade"), present)
402 .animate_initial(false)
403 .enter(theme.motion.duration.standard, theme.motion.ease.enter)
404 .exit(theme.motion.duration.instant, theme.motion.ease.standard)
405 .sample(window, cx);
406 if !present && height.settled && !fade.should_render() {
407 return div().into_any_element();
408 }
409 let probe_height = measured.clone();
410 let probe = canvas(
411 move |b, window, _| {
412 let next = f32::from(b.size.height);
413 if probe_height
414 .get()
415 .is_none_or(|last| (last - next).abs() > 0.1)
416 {
417 probe_height.set(Some(next));
418 window.refresh();
419 }
420 },
421 |_, _, _, _| {},
422 )
423 .absolute()
424 .inset_0();
425 let mut inner = div()
426 .relative()
427 .w_full()
428 .flex()
429 .flex_col()
430 .opacity(fade.progress)
431 .child(probe)
432 .child(content);
433 let mut outer = div()
434 .id(id)
435 .test_support()
436 .relative()
437 .w_full()
438 .flex_shrink_0()
439 .overflow_hidden();
440 if measured.get().is_some() {
441 inner = inner.absolute().top_0().left_0();
442 outer = outer.h(px(height.value.max(0.0)));
443 }
444 outer.child(inner).into_any_element()
445}
446
447fn animated_comment_swap(
448 id: ElementId,
449 phase: &str,
450 content: impl IntoElement,
451 window: &mut Window,
452 cx: &mut App,
453) -> AnyElement {
454 let now = motion_now(cx);
455 let theme = cx.arc_theme().clone();
456 let state = window.use_keyed_state(
457 ElementId::NamedChild(id.clone().into(), "face".into()),
458 cx,
459 |_, _| (phase.to_string(), None::<f64>),
460 );
461 if state.read(cx).0 != phase {
462 state.update(cx, |s, _| {
463 s.0 = phase.to_string();
464 s.1 = Some(now);
465 });
466 }
467 let alpha = if is_reduced_motion(cx) {
468 1.0
469 } else if let Some(start) = state.read(cx).1 {
470 let p = ((now - start) / theme.motion.duration.fast.as_secs_f64()).clamp(0.0, 1.0) as f32;
471 if p < 1.0 {
472 window.request_animation_frame();
473 }
474 CubicBezier::from_spec(theme.motion.ease.enter).sample(p)
475 } else {
476 1.0
477 };
478 animated_comment_height(
479 id,
480 true,
481 div().w_full().opacity(alpha).child(content),
482 window,
483 cx,
484 )
485}
486
487#[derive(Clone)]
488struct CommentThreadInternal {
489 editing_id: Option<SharedString>,
490 confirming_id: Option<SharedString>,
491 picker_id: Option<SharedString>,
492 reply_to: Option<(SharedString, SharedString)>,
493 collapsed: HashMap<SharedString, bool>,
494 composer_state: Entity<InputState>,
495 edit_state: Entity<InputState>,
496 next_serial: usize,
497 focus_handle: gpui_kit::FocusHandle,
498 _input_observers: Rc<Vec<gpui_kit::Subscription>>,
499 resolved: bool,
500}
501
502#[derive(IntoElement)]
504pub struct CommentThread {
505 id: ElementId,
506 title: Option<SharedString>,
507 comments: Vec<ThreadComment>,
508 current_user: CommentAuthor,
509 people: Option<Vec<CommentAuthor>>,
510 resolved: bool,
511 reactions: Vec<SharedString>,
512 placeholder: SharedString,
513 max_depth: usize,
514 now_label: SharedString,
515 on_comments_change: Option<CommentsCallback>,
516 on_resolved_change: Option<ResolvedCallback>,
517}
518
519impl CommentThread {
520 pub fn new(
521 id: impl Into<ElementId>,
522 current_user: CommentAuthor,
523 comments: Vec<ThreadComment>,
524 ) -> Self {
525 Self {
526 id: id.into(),
527 title: None,
528 comments,
529 current_user,
530 people: None,
531 resolved: false,
532 reactions: COMMENT_DEFAULT_REACTIONS
533 .iter()
534 .map(|&e| SharedString::from(e))
535 .collect(),
536 placeholder: "Reply, or @mention someone".into(),
537 max_depth: 2,
538 now_label: "Just now".into(),
539 on_comments_change: None,
540 on_resolved_change: None,
541 }
542 }
543
544 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
545 self.title = Some(title.into());
546 self
547 }
548
549 pub fn people(mut self, people: Vec<CommentAuthor>) -> Self {
550 self.people = Some(people);
551 self
552 }
553
554 pub fn resolved(mut self, resolved: bool) -> Self {
555 self.resolved = resolved;
556 self
557 }
558
559 pub fn max_depth(mut self, depth: usize) -> Self {
560 self.max_depth = depth.max(1);
561 self
562 }
563
564 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
565 self.placeholder = placeholder.into();
566 self
567 }
568
569 pub fn on_comments_change(
570 mut self,
571 handler: impl Fn(Vec<ThreadComment>, &mut Window, &mut App) + 'static,
572 ) -> Self {
573 self.on_comments_change = Some(Rc::new(handler));
574 self
575 }
576
577 pub fn on_resolved_change(
578 mut self,
579 handler: impl Fn(bool, &mut Window, &mut App) + 'static,
580 ) -> Self {
581 self.on_resolved_change = Some(Rc::new(handler));
582 self
583 }
584}
585
586struct RenderCtx<'a> {
587 root_id: &'a ElementId,
588 theme: &'a arc_tokens::ArcTheme,
589 current_user: &'a CommentAuthor,
590 mentionable: &'a [CommentAuthor],
591 reactions: &'a [SharedString],
592 all_comments: &'a [ThreadComment],
593 shared: &'a Rc<RefCell<CommentThreadInternal>>,
594 edit_state: &'a Entity<InputState>,
595 on_comments_change: &'a Option<CommentsCallback>,
596}
597
598fn render_avatar_badge(name: &str, size: f32, theme: &arc_tokens::ArcTheme) -> AnyElement {
599 div()
600 .w(px(size))
601 .h(px(size))
602 .flex_shrink_0()
603 .rounded(Radii::PILL)
604 .bg(theme.colors.surface_muted)
605 .flex()
606 .items_center()
607 .justify_center()
608 .text_size(px((size * 0.38).round()))
609 .text_color(theme.colors.text_secondary)
610 .child(initials_for(name))
611 .into_any_element()
612}
613
614fn render_comment_node(
615 comment: &ThreadComment,
616 ctx: &RenderCtx<'_>,
617 window: &mut Window,
618 cx: &mut App,
619) -> AnyElement {
620 let theme = ctx.theme;
621 let mine = comment.author.id == ctx.current_user.id;
622 let st = ctx.shared.borrow().clone();
623 let node_id = ElementId::Name(format!("arc-cm-node-{:?}-{}", ctx.root_id, comment.id).into());
624 let is_editing = st.editing_id.as_ref() == Some(&comment.id);
625 let is_confirming = st.confirming_id.as_ref() == Some(&comment.id);
626 let is_picking = st.picker_id.as_ref() == Some(&comment.id);
627 let collapsed = st.collapsed.get(&comment.id).copied().unwrap_or(false);
628
629 let mut main_col = div().flex_1().min_w_0().flex().flex_col().gap(px(3.0));
630
631 if comment.deleted {
632 main_col = main_col.child(
633 div()
634 .pt(px(4.0))
635 .text_size(Typography::TEXT_SM)
636 .text_color(theme.colors.text_muted)
637 .italic()
638 .child("This comment was deleted"),
639 );
640 } else {
641 let time_text = if comment.edited {
643 format!("{} · edited", comment.created_at)
644 } else {
645 comment.created_at.to_string()
646 };
647 main_col = main_col.child(
648 div()
649 .flex()
650 .items_baseline()
651 .gap(px(8.0))
652 .child(
653 div()
654 .text_size(Typography::TEXT_SM)
655 .text_color(theme.colors.foreground)
656 .child(comment.author.name.clone()),
657 )
658 .child(
659 div()
660 .text_size(Typography::TEXT_XS)
661 .text_color(theme.colors.text_muted)
662 .child(time_text),
663 ),
664 );
665
666 if is_editing {
667 let edit_text = ctx.edit_state.read(cx).value().to_string();
668 let can_save = !edit_text.trim().is_empty() && edit_text.trim() != comment.body.trim();
669 let shared_cancel = ctx.shared.clone();
670 let shared_save = ctx.shared.clone();
671 let edit_st_save = ctx.edit_state.clone();
672 let comment_id_save = comment.id.clone();
673 let comments_snap = ctx.all_comments.to_vec();
674 let on_change_save = ctx.on_comments_change.clone();
675
676 let edit_box = div()
677 .mt(px(4.0))
678 .flex()
679 .flex_col()
680 .gap(px(6.0))
681 .child(
682 div()
683 .id(ElementId::Name(
684 format!("arc-cm-edit-field-{:?}-{}", ctx.root_id, comment.id).into(),
685 ))
686 .test_support()
687 .px(px(10.0))
688 .py(px(6.0))
689 .rounded(px(12.0))
690 .border_1()
691 .border_color(theme.colors.border_strong)
692 .bg(theme.colors.surface)
693 .child(KitInput::new(ctx.edit_state).appearance(false)),
694 )
695 .child(
696 div()
697 .flex()
698 .justify_end()
699 .gap(px(6.0))
700 .child(
701 div()
702 .id(ElementId::Name(
703 format!("arc-cm-cancel-{:?}-{}", ctx.root_id, comment.id)
704 .into(),
705 ))
706 .test_support()
707 .role(Role::Button)
708 .h(px(30.0))
709 .px(px(12.0))
710 .rounded(Radii::PILL)
711 .hover(|s| s.bg(theme.colors.surface_muted))
712 .cursor_pointer()
713 .flex()
714 .items_center()
715 .text_size(Typography::TEXT_XS)
716 .text_color(theme.colors.text_secondary)
717 .on_mouse_down(MouseButton::Left, move |_, window, _| {
718 shared_cancel.borrow_mut().editing_id = None;
719 window.refresh();
720 })
721 .child("Cancel"),
722 )
723 .child(
724 div()
725 .id(ElementId::Name(
726 format!("arc-cm-save-{:?}-{}", ctx.root_id, comment.id).into(),
727 ))
728 .test_support()
729 .role(Role::Button)
730 .h(px(30.0))
731 .px(px(12.0))
732 .rounded(Radii::PILL)
733 .bg(theme.colors.foreground)
734 .text_color(theme.colors.background)
735 .opacity(if can_save { 1.0 } else { 0.35 })
736 .when(can_save, |el| el.cursor_pointer())
737 .flex()
738 .items_center()
739 .text_size(Typography::TEXT_XS)
740 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
741 let trimmed = edit_st_save.read(cx).value().trim().to_string();
742 if trimmed.is_empty() {
743 return;
744 }
745 shared_save.borrow_mut().editing_id = None;
746 let next = edit_comment_in_tree(
747 &comments_snap,
748 comment_id_save.as_ref(),
749 SharedString::from(trimmed),
750 );
751 if let Some(cb) = &on_change_save {
752 cb(next, window, cx);
753 }
754 window.refresh();
755 })
756 .child("Save"),
757 ),
758 );
759 main_col = main_col.child(animated_comment_swap(
760 ElementId::Name(format!("arc-cm-content-{:?}-{}", ctx.root_id, comment.id).into()),
761 "edit",
762 edit_box,
763 window,
764 cx,
765 ));
766 } else {
767 let segments = split_comment_mentions(comment.body.as_ref(), ctx.mentionable);
769 let mut body_row = div()
770 .flex()
771 .flex_wrap()
772 .text_size(Typography::TEXT_SM)
773 .text_color(theme.colors.text_secondary);
774 for (seg, is_mention) in segments {
775 if is_mention {
776 body_row =
777 body_row.child(div().text_color(theme.colors.accent_strong).child(seg));
778 } else {
779 body_row = body_row.child(seg);
780 }
781 }
782 let body_content = div().w_full().flex().flex_col().child(body_row);
783
784 let mut footer = div()
786 .mt(px(4.0))
787 .flex()
788 .flex_wrap()
789 .items_center()
790 .gap(px(6.0));
791
792 for rx in &comment.reactions {
793 let pressed = rx.users.iter().any(|u| u == &ctx.current_user.id);
794 let border_c = if pressed {
795 oklab_mix(theme.colors.border, theme.colors.accent, 0.45)
796 } else {
797 theme.colors.border
798 };
799 let bg_c = if pressed {
800 theme.colors.accent_subtle
801 } else {
802 theme.colors.surface
803 };
804 let comments_snap = ctx.all_comments.to_vec();
805 let cid = comment.id.clone();
806 let emoji = rx.emoji.clone();
807 let uid = ctx.current_user.id.clone();
808 let on_change = ctx.on_comments_change.clone();
809
810 footer = footer.child(
811 div()
812 .id(ElementId::Name(
813 format!("arc-cm-rx-{:?}-{}-{}", ctx.root_id, comment.id, rx.emoji)
814 .into(),
815 ))
816 .test_support()
817 .role(Role::Button)
818 .h(px(26.0))
819 .pl(px(7.0))
820 .pr(px(9.0))
821 .rounded(Radii::PILL)
822 .border_1()
823 .border_color(border_c)
824 .bg(bg_c)
825 .hover(|s| s.border_color(theme.colors.border_strong))
826 .cursor_pointer()
827 .flex()
828 .items_center()
829 .gap(px(4.0))
830 .text_size(Typography::TEXT_XS)
831 .text_color(if pressed {
832 theme.colors.foreground
833 } else {
834 theme.colors.text_secondary
835 })
836 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
837 let next = toggle_comment_reaction(
838 &comments_snap,
839 cid.as_ref(),
840 emoji.as_ref(),
841 uid.as_ref(),
842 );
843 if let Some(cb) = &on_change {
844 cb(next, window, cx);
845 }
846 })
847 .child(rx.emoji.clone())
848 .child(
849 crate::AnimatedCounter::new(
850 ElementId::Name(
851 format!(
852 "arc-cm-count-{:?}-{}-{}",
853 ctx.root_id, comment.id, rx.emoji
854 )
855 .into(),
856 ),
857 rx.users.len() as f64,
858 )
859 .text_size(Typography::TEXT_XS),
860 ),
861 );
862 }
863
864 if is_confirming {
865 let shared_cancel = ctx.shared.clone();
866 let shared_del = ctx.shared.clone();
867 let comments_snap = ctx.all_comments.to_vec();
868 let cid = comment.id.clone();
869 let on_change = ctx.on_comments_change.clone();
870 footer = footer.child(
871 div()
872 .flex()
873 .items_center()
874 .gap(px(4.0))
875 .child(
876 div()
877 .text_size(Typography::TEXT_XS)
878 .text_color(theme.colors.foreground)
879 .child("Delete this comment?"),
880 )
881 .child(
882 div()
883 .id(ElementId::Name(
884 format!("arc-cm-del-no-{:?}-{}", ctx.root_id, comment.id)
885 .into(),
886 ))
887 .test_support()
888 .role(Role::Button)
889 .h(px(26.0))
890 .px(px(8.0))
891 .rounded(Radii::PILL)
892 .hover(|s| s.bg(theme.colors.surface_muted))
893 .cursor_pointer()
894 .flex()
895 .items_center()
896 .text_size(Typography::TEXT_XS)
897 .text_color(theme.colors.text_muted)
898 .on_mouse_down(MouseButton::Left, move |_, window, _| {
899 shared_cancel.borrow_mut().confirming_id = None;
900 window.refresh();
901 })
902 .child("Cancel"),
903 )
904 .child(
905 div()
906 .id(ElementId::Name(
907 format!("arc-cm-del-yes-{:?}-{}", ctx.root_id, comment.id)
908 .into(),
909 ))
910 .test_support()
911 .role(Role::Button)
912 .h(px(26.0))
913 .px(px(8.0))
914 .rounded(Radii::PILL)
915 .hover(|s| {
916 s.bg(oklab_mix(theme.colors.surface, theme.colors.danger, 0.12))
917 })
918 .cursor_pointer()
919 .flex()
920 .items_center()
921 .text_size(Typography::TEXT_XS)
922 .text_color(theme.colors.danger)
923 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
924 shared_del.borrow_mut().confirming_id = None;
925 let next = delete_comment_in_tree(&comments_snap, cid.as_ref());
926 if let Some(cb) = &on_change {
927 cb(next, window, cx);
928 }
929 window.refresh();
930 })
931 .child("Delete"),
932 ),
933 );
934 } else if is_picking {
935 let mut picker = div().flex().items_center().gap(px(2.0));
936 for emoji in ctx.reactions {
937 let comments_snap = ctx.all_comments.to_vec();
938 let cid = comment.id.clone();
939 let em = emoji.clone();
940 let uid = ctx.current_user.id.clone();
941 let shared_p = ctx.shared.clone();
942 let on_change = ctx.on_comments_change.clone();
943 picker = picker.child(
944 div()
945 .id(ElementId::Name(
946 format!("arc-cm-pick-{:?}-{}-{}", ctx.root_id, comment.id, emoji)
947 .into(),
948 ))
949 .test_support()
950 .role(Role::Button)
951 .w(px(26.0))
952 .h(px(26.0))
953 .rounded(Radii::PILL)
954 .hover(|s| s.bg(theme.colors.surface_muted))
955 .cursor_pointer()
956 .flex()
957 .items_center()
958 .justify_center()
959 .text_size(px(14.0))
960 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
961 shared_p.borrow_mut().picker_id = None;
962 let next = toggle_comment_reaction(
963 &comments_snap,
964 cid.as_ref(),
965 em.as_ref(),
966 uid.as_ref(),
967 );
968 if let Some(cb) = &on_change {
969 cb(next, window, cx);
970 }
971 window.refresh();
972 })
973 .child(emoji.clone()),
974 );
975 }
976 let shared_close = ctx.shared.clone();
977 picker = picker.child(
978 div()
979 .id(ElementId::Name(
980 format!("arc-cm-pick-close-{:?}-{}", ctx.root_id, comment.id).into(),
981 ))
982 .test_support()
983 .role(Role::Button)
984 .w(px(24.0))
985 .h(px(24.0))
986 .rounded(Radii::PILL)
987 .hover(|s| s.bg(theme.colors.surface_muted))
988 .cursor_pointer()
989 .flex()
990 .items_center()
991 .justify_center()
992 .text_size(Typography::TEXT_XS)
993 .text_color(theme.colors.text_muted)
994 .on_mouse_down(MouseButton::Left, move |_, window, _| {
995 shared_close.borrow_mut().picker_id = None;
996 window.refresh();
997 })
998 .child("×"),
999 );
1000 footer = footer.child(picker);
1001 } else {
1002 let shared_rx = ctx.shared.clone();
1003 let cid_rx = comment.id.clone();
1004 let shared_reply = ctx.shared.clone();
1005 let cid_reply = comment.id.clone();
1006 let author_reply = comment.author.name.clone();
1007
1008 let mut actions = div()
1009 .flex()
1010 .items_center()
1011 .gap(px(2.0))
1012 .child(
1013 div()
1014 .id(ElementId::Name(
1015 format!("arc-cm-act-rx-{:?}-{}", ctx.root_id, comment.id).into(),
1016 ))
1017 .test_support()
1018 .role(Role::Button)
1019 .h(px(26.0))
1020 .px(px(8.0))
1021 .rounded(Radii::PILL)
1022 .hover(|s| {
1023 s.bg(theme.colors.surface_muted)
1024 .text_color(theme.colors.foreground)
1025 })
1026 .cursor_pointer()
1027 .flex()
1028 .items_center()
1029 .text_size(Typography::TEXT_XS)
1030 .text_color(theme.colors.text_muted)
1031 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1032 shared_rx.borrow().focus_handle.focus(window, cx);
1033 let mut s = shared_rx.borrow_mut();
1034 s.picker_id = Some(cid_rx.clone());
1035 s.confirming_id = None;
1036 window.refresh();
1037 })
1038 .child("+ React"),
1039 )
1040 .child(
1041 div()
1042 .id(ElementId::Name(
1043 format!("arc-cm-act-reply-{:?}-{}", ctx.root_id, comment.id).into(),
1044 ))
1045 .test_support()
1046 .role(Role::Button)
1047 .h(px(26.0))
1048 .px(px(8.0))
1049 .rounded(Radii::PILL)
1050 .hover(|s| {
1051 s.bg(theme.colors.surface_muted)
1052 .text_color(theme.colors.foreground)
1053 })
1054 .cursor_pointer()
1055 .flex()
1056 .items_center()
1057 .text_size(Typography::TEXT_XS)
1058 .text_color(theme.colors.text_muted)
1059 .on_mouse_down(MouseButton::Left, move |_, window, _| {
1060 let composer = {
1061 let mut ui = shared_reply.borrow_mut();
1062 ui.reply_to = Some((cid_reply.clone(), author_reply.clone()));
1063 ui.composer_state.clone()
1064 };
1065 window.on_next_frame(move |window, cx| {
1067 composer.focus_handle(cx).focus(window, cx);
1068 });
1069 window.refresh();
1070 })
1071 .child("Reply"),
1072 );
1073
1074 if mine {
1075 let shared_edit = ctx.shared.clone();
1076 let edit_st = ctx.edit_state.clone();
1077 let cid_edit = comment.id.clone();
1078 let body_edit = comment.body.clone();
1079 let shared_del = ctx.shared.clone();
1080 let cid_del = comment.id.clone();
1081
1082 actions = actions
1083 .child(
1084 div()
1085 .id(ElementId::Name(
1086 format!("arc-cm-act-edit-{:?}-{}", ctx.root_id, comment.id)
1087 .into(),
1088 ))
1089 .test_support()
1090 .role(Role::Button)
1091 .h(px(26.0))
1092 .px(px(8.0))
1093 .rounded(Radii::PILL)
1094 .hover(|s| {
1095 s.bg(theme.colors.surface_muted)
1096 .text_color(theme.colors.foreground)
1097 })
1098 .cursor_pointer()
1099 .flex()
1100 .items_center()
1101 .text_size(Typography::TEXT_XS)
1102 .text_color(theme.colors.text_muted)
1103 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1104 edit_st.update(cx, |s, cx| {
1105 s.set_value(body_edit.clone(), window, cx);
1106 });
1107 let edit_focus = edit_st.clone();
1108 window.on_next_frame(move |window, cx| {
1109 edit_focus.focus_handle(cx).focus(window, cx);
1110 });
1111 let mut s = shared_edit.borrow_mut();
1112 s.editing_id = Some(cid_edit.clone());
1113 s.confirming_id = None;
1114 s.picker_id = None;
1115 window.refresh();
1116 })
1117 .child("Edit"),
1118 )
1119 .child(
1120 div()
1121 .id(ElementId::Name(
1122 format!("arc-cm-act-del-{:?}-{}", ctx.root_id, comment.id)
1123 .into(),
1124 ))
1125 .test_support()
1126 .role(Role::Button)
1127 .h(px(26.0))
1128 .px(px(8.0))
1129 .rounded(Radii::PILL)
1130 .hover(|s| {
1131 s.bg(theme.colors.surface_muted)
1132 .text_color(theme.colors.danger)
1133 })
1134 .cursor_pointer()
1135 .flex()
1136 .items_center()
1137 .text_size(Typography::TEXT_XS)
1138 .text_color(theme.colors.text_muted)
1139 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1140 shared_del.borrow().focus_handle.focus(window, cx);
1141 let mut s = shared_del.borrow_mut();
1142 s.confirming_id = Some(cid_del.clone());
1143 s.editing_id = None;
1144 s.picker_id = None;
1145 window.refresh();
1146 })
1147 .child("Delete"),
1148 );
1149 }
1150 footer = footer.child(actions);
1151 }
1152
1153 main_col = main_col.child(animated_comment_swap(
1154 ElementId::Name(format!("arc-cm-content-{:?}-{}", ctx.root_id, comment.id).into()),
1155 if is_confirming {
1156 "confirm"
1157 } else if is_picking {
1158 "picker"
1159 } else {
1160 "view"
1161 },
1162 body_content.child(footer),
1163 window,
1164 cx,
1165 ));
1166 }
1167 }
1168
1169 if !comment.replies.is_empty() {
1171 let reply_count = count_comment_tree(&comment.replies);
1172 let toggle_label = if collapsed {
1173 format!(
1174 "Show {} {}",
1175 reply_count,
1176 if reply_count == 1 { "reply" } else { "replies" }
1177 )
1178 } else {
1179 "Hide replies".to_string()
1180 };
1181 let shared_toggle = ctx.shared.clone();
1182 let cid_toggle = comment.id.clone();
1183 let chevron_color = theme.colors.text_muted;
1184 let chevron_degrees = arc_spring(
1185 (
1186 ElementId::Name(format!("arc-cm-chevron-{:?}-{}", ctx.root_id, comment.id).into()),
1187 "rotation",
1188 ),
1189 if collapsed { 0.0 } else { 90.0 },
1190 theme.motion.spring.snappy,
1191 window,
1192 cx,
1193 );
1194
1195 let mut toggle_btn = div()
1196 .id(ElementId::Name(
1197 format!("arc-cm-toggle-{:?}-{}", ctx.root_id, comment.id).into(),
1198 ))
1199 .test_support()
1200 .role(Role::Button)
1201 .h(px(26.0))
1202 .px(px(6.0))
1203 .rounded(Radii::PILL)
1204 .hover(|s| s.bg(theme.colors.surface_muted))
1205 .cursor_pointer()
1206 .flex()
1207 .items_center()
1208 .gap(px(5.0))
1209 .on_mouse_down(MouseButton::Left, move |_, window, _| {
1210 let mut s = shared_toggle.borrow_mut();
1211 let next = !s.collapsed.get(&cid_toggle).copied().unwrap_or(false);
1212 s.collapsed.insert(cid_toggle.clone(), next);
1213 window.refresh();
1214 })
1215 .child(
1216 canvas(
1217 |b, _, _| b,
1218 move |b, _, window, _| {
1219 let cx = f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
1220 let cy = f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
1221 paint_chevron_toggle(cx, cy, chevron_degrees, chevron_color, window);
1222 },
1223 )
1224 .w(px(12.0))
1225 .h(px(12.0)),
1226 )
1227 .child(
1228 div()
1229 .text_size(Typography::TEXT_XS)
1230 .text_color(theme.colors.text_secondary)
1231 .child(toggle_label),
1232 );
1233
1234 if collapsed {
1235 let reply_authors = collect_comment_authors(&comment.replies);
1236 let mut stack = div().flex().items_center().pl(px(4.0));
1237 for a in reply_authors.iter().take(3) {
1238 stack = stack.child(render_avatar_badge(a.name.as_ref(), 18.0, theme));
1239 }
1240 toggle_btn = toggle_btn.child(stack);
1241 }
1242
1243 main_col = main_col.child(toggle_btn);
1244 }
1245
1246 let avatar_el = if comment.deleted {
1248 div()
1249 .w(px(28.0))
1250 .h(px(28.0))
1251 .flex_shrink_0()
1252 .rounded(Radii::PILL)
1253 .border_1()
1254 .border_color(theme.colors.border_strong)
1255 .into_any_element()
1256 } else {
1257 render_avatar_badge(comment.author.name.as_ref(), 28.0, theme)
1258 };
1259
1260 let mut wrapper = div()
1261 .id(node_id)
1262 .test_support()
1263 .w_full()
1264 .flex()
1265 .flex_col()
1266 .child(
1267 div()
1268 .w_full()
1269 .p(px(10.0))
1270 .flex()
1271 .items_start()
1272 .gap(px(10.0))
1273 .child(avatar_el)
1274 .child(main_col),
1275 );
1276
1277 if !comment.replies.is_empty() {
1278 let mut replies_col = div()
1279 .ml(px(24.0))
1280 .pl(px(12.0))
1281 .border_l_1()
1282 .border_color(theme.colors.border)
1283 .flex()
1284 .flex_col();
1285 for reply in &comment.replies {
1286 replies_col = replies_col.child(render_comment_node(reply, ctx, window, cx));
1287 }
1288 wrapper = wrapper.child(animated_comment_height(
1289 ElementId::Name(format!("arc-cm-replies-{:?}-{}", ctx.root_id, comment.id).into()),
1290 !collapsed,
1291 replies_col,
1292 window,
1293 cx,
1294 ));
1295 }
1296
1297 wrapper.into_any_element()
1298}
1299
1300impl RenderOnce for CommentThread {
1301 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1302 let theme = cx.arc_theme().clone();
1303 let placeholder_str = self.placeholder.clone();
1304
1305 let state = window.use_keyed_state(
1306 ElementId::Name(format!("arc-comment-thread-state-{:?}", self.id).into()),
1307 cx,
1308 |window, cx| {
1309 let composer_state =
1310 cx.new(|cx| InputState::new(window, cx).placeholder(placeholder_str.clone()));
1311 let edit_state =
1312 cx.new(|cx| InputState::new(window, cx).placeholder("Edit comment"));
1313 let observers = Rc::new(vec![
1315 window.subscribe(&composer_state, cx, |_, event: &InputEvent, window, _| {
1316 if matches!(event, InputEvent::Change) {
1317 window.refresh();
1318 }
1319 }),
1320 window.subscribe(&edit_state, cx, |_, event: &InputEvent, window, _| {
1321 if matches!(event, InputEvent::Change) {
1322 window.refresh();
1323 }
1324 }),
1325 ]);
1326 Rc::new(RefCell::new(CommentThreadInternal {
1327 editing_id: None,
1328 confirming_id: None,
1329 picker_id: None,
1330 reply_to: None,
1331 collapsed: HashMap::new(),
1332 composer_state,
1333 edit_state,
1334 next_serial: 1,
1335 focus_handle: cx.focus_handle(),
1336 _input_observers: observers,
1337 resolved: self.resolved,
1338 }))
1339 },
1340 );
1341 let shared = state.read(cx).clone();
1342 {
1343 let mut ui = shared.borrow_mut();
1344 if ui.resolved != self.resolved {
1345 ui.resolved = self.resolved;
1346 ui.editing_id = None;
1347 ui.confirming_id = None;
1348 ui.picker_id = None;
1349 ui.reply_to = None;
1350 }
1351 }
1352 let composer_state = shared.borrow().composer_state.clone();
1353 let edit_state = shared.borrow().edit_state.clone();
1354 let reply_to = shared.borrow().reply_to.clone();
1355
1356 let total = count_comment_tree(&self.comments);
1357 let participants = collect_comment_authors(&self.comments);
1358 let mentionable = self.people.clone().unwrap_or_else(|| {
1359 let mut list = participants.clone();
1360 if !list.iter().any(|p| p.id == self.current_user.id) {
1361 list.push(self.current_user.clone());
1362 }
1363 list
1364 });
1365
1366 let comment_count_label = format!(
1367 "{} {}",
1368 total,
1369 if total == 1 { "comment" } else { "comments" }
1370 );
1371 let people_count_label = format!(
1372 "{} {}",
1373 participants.len(),
1374 if participants.len() == 1 {
1375 "person"
1376 } else {
1377 "people"
1378 }
1379 );
1380
1381 let root_radius = if self.resolved {
1382 Radii::SURFACE
1383 } else {
1384 Radii::PANEL
1385 };
1386 let focus = shared.borrow().focus_handle.clone();
1387 let escape_ui = shared.clone();
1388 let mut root = div()
1389 .id(self.id.clone())
1390 .test_support()
1391 .role(Role::Region)
1392 .aria_label("Comment thread")
1393 .track_focus(&focus)
1394 .on_key_down(move |event: &KeyDownEvent, window, cx| {
1395 if event.keystroke.key == "escape" {
1396 let mut ui = escape_ui.borrow_mut();
1397 ui.editing_id = None;
1398 ui.confirming_id = None;
1399 ui.picker_id = None;
1400 ui.reply_to = None;
1401 cx.stop_propagation();
1402 window.refresh();
1403 }
1404 })
1405 .w_full()
1406 .rounded(root_radius)
1407 .border_1()
1408 .border_color(theme.colors.border)
1409 .bg(theme.colors.surface)
1410 .overflow_hidden();
1411
1412 if self.resolved {
1413 let success_color = theme.colors.success;
1414 let on_resolved = self.on_resolved_change.clone();
1415 let mut title_line = div().flex().items_center().gap(px(4.0)).child(
1416 div()
1417 .text_size(Typography::TEXT_SM)
1418 .text_color(theme.colors.foreground)
1419 .child("Resolved"),
1420 );
1421 if let Some(title) = &self.title {
1422 title_line = title_line.child(
1423 div()
1424 .text_size(Typography::TEXT_SM)
1425 .text_color(theme.colors.text_secondary)
1426 .child(format!("· {title}")),
1427 );
1428 }
1429
1430 let mut avatar_stack = div().flex().items_center().gap(px(2.0));
1431 for author in participants.iter().take(3) {
1432 avatar_stack =
1433 avatar_stack.child(render_avatar_badge(author.name.as_ref(), 22.0, &theme));
1434 }
1435
1436 root = root.child(
1437 div()
1438 .w_full()
1439 .px(px(14.0))
1440 .py(px(10.0))
1441 .flex()
1442 .items_center()
1443 .gap(px(12.0))
1444 .child(
1445 div()
1446 .w(px(24.0))
1447 .h(px(24.0))
1448 .rounded(Radii::PILL)
1449 .bg(oklab_mix(theme.colors.surface, theme.colors.success, 0.14))
1450 .flex()
1451 .items_center()
1452 .justify_center()
1453 .child(
1454 canvas(
1455 |b, _, _| b,
1456 move |b, _, window, _| {
1457 let cx =
1458 f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
1459 let cy =
1460 f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
1461 paint_check(cx, cy, success_color, window);
1462 },
1463 )
1464 .w(px(14.0))
1465 .h(px(14.0)),
1466 ),
1467 )
1468 .child(
1469 div()
1470 .flex_1()
1471 .min_w_0()
1472 .flex()
1473 .flex_col()
1474 .child(title_line)
1475 .child(
1476 div()
1477 .text_size(Typography::TEXT_XS)
1478 .text_color(theme.colors.text_muted)
1479 .child(format!("{comment_count_label} · {people_count_label}")),
1480 ),
1481 )
1482 .child(avatar_stack)
1483 .child(
1484 div()
1485 .id(ElementId::Name(
1486 format!("arc-cm-reopen-{:?}", self.id).into(),
1487 ))
1488 .test_support()
1489 .role(Role::Button)
1490 .h(px(32.0))
1491 .px(px(12.0))
1492 .rounded(Radii::PILL)
1493 .border_1()
1494 .border_color(theme.colors.border)
1495 .bg(theme.colors.surface)
1496 .hover(|s| s.bg(theme.colors.surface_muted))
1497 .cursor_pointer()
1498 .flex()
1499 .items_center()
1500 .text_size(Typography::TEXT_XS)
1501 .text_color(theme.colors.foreground)
1502 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1503 if let Some(cb) = &on_resolved {
1504 cb(false, window, cx);
1505 }
1506 })
1507 .child("Reopen"),
1508 ),
1509 );
1510 return animated_comment_swap(
1511 ElementId::NamedChild(self.id.clone().into(), "thread-height".into()),
1512 "resolved",
1513 root,
1514 window,
1515 cx,
1516 );
1517 }
1518
1519 let on_resolve = self.on_resolved_change.clone();
1521 let can_resolve = total > 0;
1522 let success_color = theme.colors.success;
1523 let mut heading = div().flex().flex_col();
1524 if let Some(title) = &self.title {
1525 heading = heading.child(
1526 div()
1527 .text_size(Typography::TEXT_SM)
1528 .text_color(theme.colors.foreground)
1529 .child(title.clone()),
1530 );
1531 }
1532 heading = heading.child(
1533 div()
1534 .text_size(Typography::TEXT_XS)
1535 .text_color(theme.colors.text_muted)
1536 .child(comment_count_label),
1537 );
1538
1539 let header = div()
1540 .w_full()
1541 .pl(px(18.0))
1542 .pr(px(12.0))
1543 .pt(px(12.0))
1544 .pb(px(8.0))
1545 .flex()
1546 .items_center()
1547 .justify_between()
1548 .gap(px(12.0))
1549 .child(heading)
1550 .child(
1551 div()
1552 .id(ElementId::Name(
1553 format!("arc-cm-resolve-{:?}", self.id).into(),
1554 ))
1555 .test_support()
1556 .role(Role::Button)
1557 .h(px(32.0))
1558 .pl(px(10.0))
1559 .pr(px(12.0))
1560 .rounded(Radii::PILL)
1561 .border_1()
1562 .border_color(theme.colors.border)
1563 .bg(theme.colors.surface)
1564 .opacity(if can_resolve { 1.0 } else { 0.45 })
1565 .when(can_resolve, |el| {
1566 el.cursor_pointer()
1567 .hover(|s| s.bg(theme.colors.surface_muted))
1568 })
1569 .flex()
1570 .items_center()
1571 .gap(px(6.0))
1572 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1573 if can_resolve && let Some(cb) = &on_resolve {
1574 cb(true, window, cx);
1575 }
1576 })
1577 .child(
1578 canvas(
1579 |b, _, _| b,
1580 move |b, _, window, _| {
1581 let cx = f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
1582 let cy = f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
1583 paint_check(cx, cy, success_color, window);
1584 },
1585 )
1586 .w(px(14.0))
1587 .h(px(14.0)),
1588 )
1589 .child(
1590 div()
1591 .text_size(Typography::TEXT_XS)
1592 .text_color(theme.colors.foreground)
1593 .child("Resolve"),
1594 ),
1595 );
1596
1597 let rctx = RenderCtx {
1599 root_id: &self.id,
1600 theme: &theme,
1601 current_user: &self.current_user,
1602 mentionable: &mentionable,
1603 reactions: &self.reactions,
1604 all_comments: &self.comments,
1605 shared: &shared,
1606 edit_state: &edit_state,
1607 on_comments_change: &self.on_comments_change,
1608 };
1609
1610 let body_section = if self.comments.is_empty() {
1611 div()
1612 .px(px(18.0))
1613 .py(px(12.0))
1614 .text_size(Typography::TEXT_SM)
1615 .text_color(theme.colors.text_muted)
1616 .child("No comments yet. Start the conversation below.")
1617 .into_any_element()
1618 } else {
1619 let mut list = div().px(px(8.0)).flex().flex_col();
1620 for comment in &self.comments {
1621 list = list.child(render_comment_node(comment, &rctx, window, cx));
1622 }
1623 list.into_any_element()
1624 };
1625
1626 let current_draft = composer_state.read(cx).value().to_string();
1628 let can_send = !current_draft.trim().is_empty();
1629
1630 let active_mention_query = current_draft.rsplit_once('@').and_then(|(before, after)| {
1632 if (before.is_empty() || before.ends_with(char::is_whitespace))
1633 && !after.contains(char::is_whitespace)
1634 {
1635 Some(after.to_lowercase())
1636 } else {
1637 None
1638 }
1639 });
1640 let mention_matches: Vec<&CommentAuthor> = if let Some(q) = &active_mention_query {
1641 mentionable
1642 .iter()
1643 .filter(|p| {
1644 let lower = p.name.to_lowercase();
1645 lower.starts_with(q.as_str())
1646 || lower.split_whitespace().any(|w| w.starts_with(q.as_str()))
1647 })
1648 .take(4)
1649 .collect()
1650 } else {
1651 Vec::new()
1652 };
1653
1654 let submit_reply = {
1655 let composer_st = composer_state.clone();
1656 let shared_s = shared.clone();
1657 let comments_snap = self.comments.clone();
1658 let current_user = self.current_user.clone();
1659 let now_label = self.now_label.clone();
1660 let max_depth = self.max_depth;
1661 let on_change = self.on_comments_change.clone();
1662
1663 Rc::new(move |window: &mut Window, cx: &mut App| {
1664 let trimmed = composer_st.read(cx).value().trim().to_string();
1665 if trimmed.is_empty() {
1666 return;
1667 }
1668 let (serial, reply_parent) = {
1669 let mut st = shared_s.borrow_mut();
1670 let s = st.next_serial;
1671 st.next_serial += 1;
1672 let r = st.reply_to.take().map(|(id, _)| id);
1673 if let Some(pid) = &r {
1674 st.collapsed.insert(pid.clone(), false);
1675 }
1676 (s, r)
1677 };
1678 composer_st.update(cx, |state, cx| {
1679 state.set_value("", window, cx);
1680 });
1681 let new_comment = ThreadComment::new(
1682 format!("c-local-{serial}"),
1683 current_user.clone(),
1684 trimmed,
1685 now_label.clone(),
1686 );
1687 let next = append_comment_reply(
1688 &comments_snap,
1689 reply_parent.as_deref(),
1690 max_depth,
1691 new_comment,
1692 );
1693 if let Some(cb) = &on_change {
1694 cb(next, window, cx);
1695 }
1696 window.refresh();
1697 })
1698 };
1699
1700 let submit_click = submit_reply.clone();
1701 let submit_key = submit_reply.clone();
1702
1703 let mut composer_area = div()
1704 .w_full()
1705 .mt(px(4.0))
1706 .px(px(12.0))
1707 .py(px(10.0))
1708 .border_t_1()
1709 .border_color(theme.colors.border_subtle)
1710 .flex()
1711 .flex_col()
1712 .gap(px(8.0));
1713
1714 if let Some((_, target_name)) = &reply_to {
1715 let shared_cancel_reply = shared.clone();
1716 composer_area = composer_area.child(
1717 div()
1718 .pl(px(38.0))
1719 .flex()
1720 .items_center()
1721 .gap(px(6.0))
1722 .text_size(Typography::TEXT_XS)
1723 .text_color(theme.colors.text_secondary)
1724 .child("Replying to")
1725 .child(
1726 div()
1727 .text_color(theme.colors.foreground)
1728 .child(target_name.clone()),
1729 )
1730 .child(
1731 div()
1732 .id(ElementId::Name(
1733 format!("arc-cm-cancel-reply-{:?}", self.id).into(),
1734 ))
1735 .test_support()
1736 .role(Role::Button)
1737 .w(px(20.0))
1738 .h(px(20.0))
1739 .rounded(Radii::PILL)
1740 .hover(|s| s.bg(theme.colors.surface_muted))
1741 .cursor_pointer()
1742 .flex()
1743 .items_center()
1744 .justify_center()
1745 .on_mouse_down(MouseButton::Left, move |_, window, _| {
1746 shared_cancel_reply.borrow_mut().reply_to = None;
1747 window.refresh();
1748 })
1749 .child("×"),
1750 ),
1751 );
1752 }
1753
1754 if !mention_matches.is_empty() {
1755 let mut bar = div().pl(px(38.0)).flex().flex_wrap().gap(px(6.0));
1756 for person in mention_matches {
1757 let pname = person.name.clone();
1758 let cst = composer_state.clone();
1759 bar = bar.child(
1760 div()
1761 .id(ElementId::Name(
1762 format!("arc-cm-mention-{:?}-{}", self.id, person.id).into(),
1763 ))
1764 .role(Role::ListBoxOption)
1765 .h(px(28.0))
1766 .px(px(8.0))
1767 .rounded(px(10.0))
1768 .border_1()
1769 .border_color(theme.colors.border)
1770 .bg(theme.colors.surface_raised)
1771 .hover(|s| s.bg(theme.colors.surface_muted))
1772 .cursor_pointer()
1773 .flex()
1774 .items_center()
1775 .gap(px(6.0))
1776 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1777 let cur = cst.read(cx).value().to_string();
1778 let next = if let Some((head, _)) = cur.rsplit_once('@') {
1779 format!("{head}@{pname} ")
1780 } else {
1781 format!("{cur}@{pname} ")
1782 };
1783 cst.update(cx, |s, cx| {
1784 s.set_value(next, window, cx);
1785 });
1786 })
1787 .child(render_avatar_badge(person.name.as_ref(), 18.0, &theme))
1788 .child(
1789 div()
1790 .text_size(Typography::TEXT_XS)
1791 .text_color(theme.colors.foreground)
1792 .child(person.name.clone()),
1793 ),
1794 );
1795 }
1796 composer_area = composer_area.child(bar);
1797 }
1798
1799 composer_area = composer_area.child(
1800 div()
1801 .w_full()
1802 .flex()
1803 .items_center()
1804 .gap(px(10.0))
1805 .child(render_avatar_badge(
1806 self.current_user.name.as_ref(),
1807 28.0,
1808 &theme,
1809 ))
1810 .child(
1811 div()
1812 .id(ElementId::Name(
1813 format!("arc-cm-composer-field-{:?}", self.id).into(),
1814 ))
1815 .test_support()
1816 .flex_1()
1817 .min_w_0()
1818 .min_h(px(36.0))
1819 .px(px(12.0))
1820 .py(px(6.0))
1821 .rounded(Radii::CONTROL)
1822 .border_1()
1823 .border_color(theme.colors.border)
1824 .bg(theme.colors.surface)
1825 .on_key_down(move |event: &KeyDownEvent, window, cx| {
1826 if event.keystroke.key == "enter"
1827 && (event.keystroke.modifiers.control
1828 || event.keystroke.modifiers.platform)
1829 {
1830 submit_key(window, cx);
1831 }
1832 })
1833 .child(KitInput::new(&composer_state).appearance(false)),
1834 )
1835 .child(
1836 div()
1837 .id(ElementId::Name(format!("arc-cm-send-{:?}", self.id).into()))
1838 .test_support()
1839 .role(Role::Button)
1840 .h(px(36.0))
1841 .px(px(14.0))
1842 .rounded(Radii::PILL)
1843 .bg(theme.colors.foreground)
1844 .text_color(theme.colors.background)
1845 .opacity(if can_send { 1.0 } else { 0.35 })
1846 .when(can_send, |el| el.cursor_pointer())
1847 .flex()
1848 .items_center()
1849 .text_size(Typography::TEXT_SM)
1850 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1851 submit_click(window, cx);
1852 })
1853 .child("Send"),
1854 ),
1855 );
1856
1857 let content = root.child(
1858 div()
1859 .w_full()
1860 .flex()
1861 .flex_col()
1862 .child(header)
1863 .child(body_section)
1864 .child(composer_area),
1865 );
1866 animated_comment_swap(
1867 ElementId::NamedChild(self.id.clone().into(), "thread-height".into()),
1868 "thread",
1869 content,
1870 window,
1871 cx,
1872 )
1873 }
1874}
1875
1876#[cfg(test)]
1877mod tests {
1878 use super::*;
1879 use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
1880 use std::time::Duration;
1881
1882 fn action(name: &str) -> ElementId {
1883 ElementId::Name(format!("arc-cm-{name}-{:?}", ElementId::from("thread-test")).into())
1884 }
1885
1886 fn node_action(name: &str, node: &str) -> ElementId {
1887 ElementId::Name(format!("arc-cm-{name}-{:?}-{node}", ElementId::from("thread-test")).into())
1888 }
1889
1890 struct Host {
1891 comments: Vec<ThreadComment>,
1892 resolved: bool,
1893 }
1894
1895 impl Render for Host {
1896 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1897 let comments_host = cx.entity().clone();
1898 let resolved_host = cx.entity().clone();
1899 div().size_full().flex().flex_col().items_start().child(
1900 CommentThread::new(
1901 "thread-test",
1902 CommentAuthor::new("me", "Alex Rivera"),
1903 self.comments.clone(),
1904 )
1905 .resolved(self.resolved)
1906 .on_comments_change(move |next, _, cx| {
1907 comments_host.update(cx, |this, cx| {
1908 this.comments = next;
1909 cx.notify();
1910 });
1911 })
1912 .on_resolved_change(move |next, _, cx| {
1913 resolved_host.update(cx, |this, cx| {
1914 this.resolved = next;
1915 cx.notify();
1916 });
1917 }),
1918 )
1919 }
1920 }
1921
1922 fn init(cx: &mut TestAppContext) {
1923 cx.update(|cx| {
1924 gpui_kit::init(cx);
1925 arc_tokens::install_arc_theme(
1926 arc_tokens::ThemeMode::Light,
1927 arc_tokens::Accent::Neutral,
1928 cx,
1929 );
1930 arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx);
1931 });
1932 }
1933
1934 fn host() -> Host {
1935 Host {
1936 comments: vec![
1937 ThreadComment::new("c1", CommentAuthor::new("me", "Alex Rivera"), "Root", "now")
1938 .reply(ThreadComment::new(
1939 "c2",
1940 CommentAuthor::new("other", "Clara Wu"),
1941 "Reply",
1942 "now",
1943 )),
1944 ],
1945 resolved: false,
1946 }
1947 }
1948
1949 #[gpui_kit::test]
1950 fn comment_thread_collapse_has_intermediate_height(cx: &mut TestAppContext) {
1951 init(cx);
1952 let (_, window) = cx.add_window_view(|_, _| host());
1953 window.update(|w, cx| {
1954 w.render_frame(cx);
1955 w.render_frame(cx);
1956 });
1957 let before = window.update(|w, cx| {
1958 let before = w.find("thread-test").bounds().size.height;
1959 w.click(node_action("toggle", "c1"), cx);
1960 before
1961 });
1962 window.executor().advance_clock(Duration::from_millis(70));
1963 let middle = window.update(|w, cx| {
1964 w.render_frame(cx);
1965 w.find("thread-test").bounds().size.height
1966 });
1967 window.executor().advance_clock(Duration::from_millis(1500));
1968 let after = window.update(|w, cx| {
1969 w.render_frame(cx);
1970 w.render_frame(cx);
1971 w.find("thread-test").bounds().size.height
1972 });
1973 assert!(
1974 before > middle && middle > after,
1975 "collapse must animate: {before:?} > {middle:?} > {after:?}"
1976 );
1977 }
1978
1979 #[gpui_kit::test]
1980 fn comment_thread_controls_edit_reply_react_delete_and_resolve(cx: &mut TestAppContext) {
1981 init(cx);
1982 cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx));
1983 let (view, window) = cx.add_window_view(|_, _| host());
1984 window.update(|w, cx| {
1985 w.render_frame(cx);
1986 w.render_frame(cx);
1987 w.click(node_action("act-rx", "c1"), cx);
1988 assert!(w.try_find(node_action("pick-close", "c1")).is_some());
1989 let emoji = ElementId::Name(
1990 format!(
1991 "arc-cm-pick-{:?}-c1-{}",
1992 ElementId::from("thread-test"),
1993 COMMENT_DEFAULT_REACTIONS[0]
1994 )
1995 .into(),
1996 );
1997 w.click(emoji, cx);
1998 assert_eq!(view.read(cx).comments[0].reactions.len(), 1);
1999 w.click(node_action("act-edit", "c1"), cx);
2000 w.click(node_action("edit-field", "c1"), cx);
2001 w.press("ctrl-a", cx);
2002 w.input("Edited root", cx);
2003 w.render_frame(cx);
2004 w.click(node_action("save", "c1"), cx);
2005 assert_eq!(view.read(cx).comments[0].body.as_ref(), "Edited root");
2006 assert!(view.read(cx).comments[0].edited);
2007 w.click(node_action("act-reply", "c1"), cx);
2008 w.click(action("composer-field"), cx);
2009 w.input("New reply", cx);
2010 w.render_frame(cx);
2011 w.click(action("send"), cx);
2012 assert_eq!(view.read(cx).comments[0].replies.len(), 2);
2013 w.click(action("resolve"), cx);
2014 w.render_frame(cx);
2015 assert!(view.read(cx).resolved);
2016 assert!(w.try_find(action("cancel-reply")).is_none());
2017 w.click(action("reopen"), cx);
2018 w.render_frame(cx);
2019 assert!(!view.read(cx).resolved);
2020 w.click(node_action("act-del", "c1"), cx);
2021 assert!(w.try_find(node_action("del-yes", "c1")).is_some());
2022 w.click(node_action("del-yes", "c1"), cx);
2023 assert!(view.read(cx).comments[0].deleted);
2024 assert_eq!(view.read(cx).comments[0].replies.len(), 2);
2025 });
2026 }
2027
2028 #[gpui_kit::test]
2029 fn comment_thread_resolve_height_and_midflight_reversal(cx: &mut TestAppContext) {
2030 init(cx);
2031 let (_, window) = cx.add_window_view(|_, _| host());
2032 let frame_id = ElementId::NamedChild(
2033 ElementId::from("thread-test").into(),
2034 "thread-height".into(),
2035 );
2036 let before = window.update(|w, cx| {
2037 w.render_frame(cx);
2038 w.render_frame(cx);
2039 w.render_frame(cx);
2040 let before = w.find(frame_id.clone()).bounds().size.height;
2041 w.click(action("resolve"), cx);
2042 before
2043 });
2044 window.executor().advance_clock(Duration::from_millis(80));
2045 let middle = window.update(|w, cx| {
2046 w.render_frame(cx);
2047 w.find(frame_id.clone()).bounds().size.height
2048 });
2049 window.executor().advance_clock(Duration::from_millis(1500));
2050 let after = window.update(|w, cx| {
2051 w.render_frame(cx);
2052 w.render_frame(cx);
2053 let after = w.find(frame_id.clone()).bounds().size.height;
2054 w.click(action("reopen"), cx);
2055 after
2056 });
2057 assert!(
2058 before > middle && middle > after,
2059 "resolve: {before:?} > {middle:?} > {after:?}"
2060 );
2061 window.executor().advance_clock(Duration::from_millis(100));
2062 window.update(|w, cx| {
2063 w.render_frame(cx);
2064 w.click(action("resolve"), cx);
2066 });
2067 window.executor().advance_clock(Duration::from_millis(1500));
2068 window.update(|w, cx| {
2069 w.render_frame(cx);
2070 w.render_frame(cx);
2071 assert!((w.find(frame_id).bounds().size.height - after).abs() < px(1.0));
2072 });
2073 }
2074
2075 #[test]
2076 fn comment_thread_tree_operations_and_mentions() {
2077 let alice = CommentAuthor::new("a", "Alice Chen");
2078 let bob = CommentAuthor::new("b", "Bob Lin");
2079 let root_comment =
2080 ThreadComment::new("c1", alice.clone(), "Ping @Bob Lin on hero copy", "2h")
2081 .reply(ThreadComment::new("c2", bob.clone(), "Looks crisp!", "1h"));
2082
2083 let tree = vec![root_comment];
2084 assert_eq!(count_comment_tree(&tree), 2);
2085 assert_eq!(collect_comment_authors(&tree).len(), 2);
2086
2087 let parts =
2089 split_comment_mentions("Ping @Bob Lin on hero copy", &[alice.clone(), bob.clone()]);
2090 assert_eq!(
2091 parts,
2092 vec![
2093 ("Ping ".to_string(), false),
2094 ("@Bob Lin".to_string(), true),
2095 (" on hero copy".to_string(), false),
2096 ]
2097 );
2098
2099 let r3 = ThreadComment::new("c3", alice.clone(), "Deep reply", "Just now");
2101 let tree = append_comment_reply(&tree, Some("c2"), 2, r3);
2102 assert_eq!(count_comment_tree(&tree), 3);
2103
2104 let tree = delete_comment_in_tree(&tree, "c1");
2106 assert!(tree[0].deleted);
2107 assert_eq!(count_comment_tree(&tree), 2);
2108
2109 let tree = toggle_comment_reaction(&tree, "c2", "👍", "a");
2111 assert_eq!(tree[0].replies[0].reactions.len(), 1);
2112 let tree = toggle_comment_reaction(&tree, "c2", "👍", "a");
2113 assert!(tree[0].replies[0].reactions.is_empty());
2114 }
2115}