use std::{
cell::{Cell, RefCell},
collections::{HashMap, HashSet},
rc::Rc,
};
use arc_motion::{
ArcPresence, CubicBezier, arc_spring, arc_spring_with_options, is_reduced_motion, motion_now,
spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, ElementId, Entity, Focusable as _, Hsla, IntoElement, KeyDownEvent,
MouseButton, ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled,
TestSupportExt as _, Window, canvas,
component::input::{Input as KitInput, InputEvent, InputState},
div, point,
prelude::*,
px,
};
use super::avatar::initials_for;
pub const COMMENT_DEFAULT_REACTIONS: &[&str] = &["👍", "❤️", "🎉", "👀", "🚀", "✅"];
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CommentAuthor {
pub id: SharedString,
pub name: SharedString,
}
impl CommentAuthor {
pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
name: name.into(),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CommentReaction {
pub emoji: SharedString,
pub users: Vec<SharedString>,
}
impl CommentReaction {
pub fn new(emoji: impl Into<SharedString>, users: Vec<SharedString>) -> Self {
Self {
emoji: emoji.into(),
users,
}
}
}
#[derive(Clone, Debug)]
pub struct ThreadComment {
pub id: SharedString,
pub author: CommentAuthor,
pub body: SharedString,
pub created_at: SharedString,
pub edited: bool,
pub deleted: bool,
pub reactions: Vec<CommentReaction>,
pub replies: Vec<ThreadComment>,
}
impl ThreadComment {
pub fn new(
id: impl Into<SharedString>,
author: CommentAuthor,
body: impl Into<SharedString>,
created_at: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
author,
body: body.into(),
created_at: created_at.into(),
edited: false,
deleted: false,
reactions: Vec::new(),
replies: Vec::new(),
}
}
pub fn edited(mut self, edited: bool) -> Self {
self.edited = edited;
self
}
pub fn reaction(mut self, emoji: impl Into<SharedString>, users: Vec<&str>) -> Self {
self.reactions.push(CommentReaction::new(
emoji,
users.into_iter().map(SharedString::from).collect(),
));
self
}
pub fn reply(mut self, reply: ThreadComment) -> Self {
self.replies.push(reply);
self
}
}
pub fn count_comment_tree(list: &[ThreadComment]) -> usize {
list.iter()
.map(|c| usize::from(!c.deleted) + count_comment_tree(&c.replies))
.sum()
}
pub fn collect_comment_authors(list: &[ThreadComment]) -> Vec<CommentAuthor> {
let mut seen = HashSet::new();
let mut out = Vec::new();
fn walk(
list: &[ThreadComment],
seen: &mut HashSet<SharedString>,
out: &mut Vec<CommentAuthor>,
) {
for c in list {
if !c.deleted && seen.insert(c.author.id.clone()) {
out.push(c.author.clone());
}
walk(&c.replies, seen, out);
}
}
walk(list, &mut seen, &mut out);
out
}
pub fn path_to_comment(list: &[ThreadComment], target_id: &str) -> Option<Vec<SharedString>> {
for c in list {
if c.id.as_ref() == target_id {
return Some(vec![c.id.clone()]);
}
if let Some(mut child_path) = path_to_comment(&c.replies, target_id) {
let mut full = vec![c.id.clone()];
full.append(&mut child_path);
return Some(full);
}
}
None
}
pub fn append_comment_reply(
list: &[ThreadComment],
reply_to_id: Option<&str>,
max_depth: usize,
reply: ThreadComment,
) -> Vec<ThreadComment> {
let target_parent = reply_to_id.and_then(|rid| {
let path = path_to_comment(list, rid)?;
let idx = path.len().min(max_depth.max(1)).saturating_sub(1);
path.get(idx).cloned()
});
let Some(parent_id) = target_parent else {
let mut next = list.to_vec();
next.push(reply);
return next;
};
fn insert_under(
nodes: &[ThreadComment],
parent_id: &str,
reply: &ThreadComment,
) -> Vec<ThreadComment> {
nodes
.iter()
.map(|c| {
let mut cloned = c.clone();
if c.id.as_ref() == parent_id {
cloned.replies.push(reply.clone());
} else if !c.replies.is_empty() {
cloned.replies = insert_under(&c.replies, parent_id, reply);
}
cloned
})
.collect()
}
insert_under(list, parent_id.as_ref(), &reply)
}
pub fn edit_comment_in_tree(
list: &[ThreadComment],
id: &str,
new_body: SharedString,
) -> Vec<ThreadComment> {
list.iter()
.map(|c| {
let mut cloned = c.clone();
if c.id.as_ref() == id {
cloned.body = new_body.clone();
cloned.edited = true;
} else if !c.replies.is_empty() {
cloned.replies = edit_comment_in_tree(&c.replies, id, new_body.clone());
}
cloned
})
.collect()
}
pub fn delete_comment_in_tree(list: &[ThreadComment], id: &str) -> Vec<ThreadComment> {
let mut out = Vec::with_capacity(list.len());
for c in list {
if c.id.as_ref() == id {
if !c.replies.is_empty() {
let mut tombstone = c.clone();
tombstone.deleted = true;
tombstone.body = SharedString::from("");
tombstone.reactions.clear();
out.push(tombstone);
}
continue;
}
let mut cloned = c.clone();
if !c.replies.is_empty() {
cloned.replies = delete_comment_in_tree(&c.replies, id);
}
out.push(cloned);
}
out
}
pub fn toggle_comment_reaction(
list: &[ThreadComment],
id: &str,
emoji: &str,
user_id: &str,
) -> Vec<ThreadComment> {
list.iter()
.map(|c| {
let mut cloned = c.clone();
if c.id.as_ref() == id {
if let Some(pos) = cloned
.reactions
.iter()
.position(|r| r.emoji.as_ref() == emoji)
{
if let Some(upos) = cloned.reactions[pos]
.users
.iter()
.position(|u| u.as_ref() == user_id)
{
cloned.reactions[pos].users.remove(upos);
if cloned.reactions[pos].users.is_empty() {
cloned.reactions.remove(pos);
}
} else {
cloned.reactions[pos]
.users
.push(SharedString::from(user_id.to_string()));
}
} else {
cloned.reactions.push(CommentReaction::new(
emoji.to_string(),
vec![SharedString::from(user_id.to_string())],
));
}
} else if !c.replies.is_empty() {
cloned.replies = toggle_comment_reaction(&c.replies, id, emoji, user_id);
}
cloned
})
.collect()
}
pub fn split_comment_mentions(text: &str, people: &[CommentAuthor]) -> Vec<(String, bool)> {
if people.is_empty() || !text.contains('@') {
return vec![(text.to_string(), false)];
}
let mut names: Vec<&str> = people.iter().map(|p| p.name.as_ref()).collect();
names.sort_by_key(|name| std::cmp::Reverse(name.len()));
let mut out = Vec::new();
let mut rest = text;
let mut plain_buf = String::new();
while !rest.is_empty() {
if rest.starts_with('@')
&& let Some(matched) = names
.iter()
.find(|&&n| !n.is_empty() && rest[1..].starts_with(n))
{
if !plain_buf.is_empty() {
out.push((std::mem::take(&mut plain_buf), false));
}
let token_len = 1 + matched.len();
out.push((rest[..token_len].to_string(), true));
rest = &rest[token_len..];
continue;
}
let mut chars = rest.chars();
if let Some(ch) = chars.next() {
plain_buf.push(ch);
rest = chars.as_str();
}
}
if !plain_buf.is_empty() {
out.push((plain_buf, false));
}
out
}
fn paint_check(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
let mut pb = PathBuilder::stroke(px(1.75));
pb.move_to(point(px(cx - 4.0), px(cy + 0.2)));
pb.line_to(point(px(cx - 1.0), px(cy + 3.2)));
pb.line_to(point(px(cx + 4.5), px(cy - 3.2)));
if let Ok(p) = pb.build() {
window.paint_path(p, color);
}
}
fn paint_chevron_toggle(cx: f32, cy: f32, degrees: f32, color: Hsla, window: &mut Window) {
let mut pb = PathBuilder::stroke(px(1.5));
let (sin, cos) = degrees.to_radians().sin_cos();
for (i, (x, y)) in [(-1.8, -3.5), (2.2, 0.0), (-1.8, 3.5)]
.into_iter()
.enumerate()
{
let p = point(px(cx + x * cos - y * sin), px(cy + x * sin + y * cos));
if i == 0 {
pb.move_to(p);
} else {
pb.line_to(p);
}
}
if let Ok(p) = pb.build() {
window.paint_path(p, color);
}
}
type CommentsCallback = Rc<dyn Fn(Vec<ThreadComment>, &mut Window, &mut App)>;
type ResolvedCallback = Rc<dyn Fn(bool, &mut Window, &mut App)>;
fn animated_comment_height(
id: ElementId,
present: bool,
content: impl IntoElement,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let theme = cx.arc_theme().clone();
let measured = window
.use_keyed_state(
ElementId::NamedChild(id.clone().into(), "natural-height".into()),
cx,
|_, _| Rc::new(Cell::new(None::<f32>)),
)
.read(cx)
.clone();
let natural_height = measured.get();
let target = if present {
natural_height.unwrap_or(0.0)
} else {
0.0
};
let height_spec = SpringSpec::visual(0.42, 0.0).as_physical();
let height = if natural_height.is_some() {
arc_spring_with_options(
(id.clone(), "height"),
target,
SpringOptions::new(height_spec),
window,
cx,
)
} else {
arc_motion::SpringSample {
value: 0.0,
velocity: 0.0,
settled: true,
}
};
let fade = ArcPresence::new((id.clone(), "fade"), present)
.animate_initial(false)
.enter(theme.motion.duration.standard, theme.motion.ease.enter)
.exit(theme.motion.duration.instant, theme.motion.ease.standard)
.sample(window, cx);
if !present && height.settled && !fade.should_render() {
return div().into_any_element();
}
let probe_height = measured.clone();
let probe = canvas(
move |b, window, _| {
let next = f32::from(b.size.height);
if probe_height
.get()
.is_none_or(|last| (last - next).abs() > 0.1)
{
probe_height.set(Some(next));
window.refresh();
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let mut inner = div()
.relative()
.w_full()
.flex()
.flex_col()
.opacity(fade.progress)
.child(probe)
.child(content);
let mut outer = div()
.id(id)
.test_support()
.relative()
.w_full()
.flex_shrink_0()
.overflow_hidden();
if measured.get().is_some() {
inner = inner.absolute().top_0().left_0();
outer = outer.h(px(height.value.max(0.0)));
}
outer.child(inner).into_any_element()
}
fn animated_comment_swap(
id: ElementId,
phase: &str,
content: impl IntoElement,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let now = motion_now(cx);
let theme = cx.arc_theme().clone();
let state = window.use_keyed_state(
ElementId::NamedChild(id.clone().into(), "face".into()),
cx,
|_, _| (phase.to_string(), None::<f64>),
);
if state.read(cx).0 != phase {
state.update(cx, |s, _| {
s.0 = phase.to_string();
s.1 = Some(now);
});
}
let alpha = if is_reduced_motion(cx) {
1.0
} else if let Some(start) = state.read(cx).1 {
let p = ((now - start) / theme.motion.duration.fast.as_secs_f64()).clamp(0.0, 1.0) as f32;
if p < 1.0 {
window.request_animation_frame();
}
CubicBezier::from_spec(theme.motion.ease.enter).sample(p)
} else {
1.0
};
animated_comment_height(
id,
true,
div().w_full().opacity(alpha).child(content),
window,
cx,
)
}
#[derive(Clone)]
struct CommentThreadInternal {
editing_id: Option<SharedString>,
confirming_id: Option<SharedString>,
picker_id: Option<SharedString>,
reply_to: Option<(SharedString, SharedString)>,
collapsed: HashMap<SharedString, bool>,
composer_state: Entity<InputState>,
edit_state: Entity<InputState>,
next_serial: usize,
focus_handle: gpui_kit::FocusHandle,
_input_observers: Rc<Vec<gpui_kit::Subscription>>,
resolved: bool,
}
#[derive(IntoElement)]
pub struct CommentThread {
id: ElementId,
title: Option<SharedString>,
comments: Vec<ThreadComment>,
current_user: CommentAuthor,
people: Option<Vec<CommentAuthor>>,
resolved: bool,
reactions: Vec<SharedString>,
placeholder: SharedString,
max_depth: usize,
now_label: SharedString,
on_comments_change: Option<CommentsCallback>,
on_resolved_change: Option<ResolvedCallback>,
}
impl CommentThread {
pub fn new(
id: impl Into<ElementId>,
current_user: CommentAuthor,
comments: Vec<ThreadComment>,
) -> Self {
Self {
id: id.into(),
title: None,
comments,
current_user,
people: None,
resolved: false,
reactions: COMMENT_DEFAULT_REACTIONS
.iter()
.map(|&e| SharedString::from(e))
.collect(),
placeholder: "Reply, or @mention someone".into(),
max_depth: 2,
now_label: "Just now".into(),
on_comments_change: None,
on_resolved_change: None,
}
}
pub fn title(mut self, title: impl Into<SharedString>) -> Self {
self.title = Some(title.into());
self
}
pub fn people(mut self, people: Vec<CommentAuthor>) -> Self {
self.people = Some(people);
self
}
pub fn resolved(mut self, resolved: bool) -> Self {
self.resolved = resolved;
self
}
pub fn max_depth(mut self, depth: usize) -> Self {
self.max_depth = depth.max(1);
self
}
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = placeholder.into();
self
}
pub fn on_comments_change(
mut self,
handler: impl Fn(Vec<ThreadComment>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_comments_change = Some(Rc::new(handler));
self
}
pub fn on_resolved_change(
mut self,
handler: impl Fn(bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_resolved_change = Some(Rc::new(handler));
self
}
}
struct RenderCtx<'a> {
root_id: &'a ElementId,
theme: &'a arc_tokens::ArcTheme,
current_user: &'a CommentAuthor,
mentionable: &'a [CommentAuthor],
reactions: &'a [SharedString],
all_comments: &'a [ThreadComment],
shared: &'a Rc<RefCell<CommentThreadInternal>>,
edit_state: &'a Entity<InputState>,
on_comments_change: &'a Option<CommentsCallback>,
}
fn render_avatar_badge(name: &str, size: f32, theme: &arc_tokens::ArcTheme) -> AnyElement {
div()
.w(px(size))
.h(px(size))
.flex_shrink_0()
.rounded(Radii::PILL)
.bg(theme.colors.surface_muted)
.flex()
.items_center()
.justify_center()
.text_size(px((size * 0.38).round()))
.text_color(theme.colors.text_secondary)
.child(initials_for(name))
.into_any_element()
}
fn render_comment_node(
comment: &ThreadComment,
ctx: &RenderCtx<'_>,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let theme = ctx.theme;
let mine = comment.author.id == ctx.current_user.id;
let st = ctx.shared.borrow().clone();
let node_id = ElementId::Name(format!("arc-cm-node-{:?}-{}", ctx.root_id, comment.id).into());
let is_editing = st.editing_id.as_ref() == Some(&comment.id);
let is_confirming = st.confirming_id.as_ref() == Some(&comment.id);
let is_picking = st.picker_id.as_ref() == Some(&comment.id);
let collapsed = st.collapsed.get(&comment.id).copied().unwrap_or(false);
let mut main_col = div().flex_1().min_w_0().flex().flex_col().gap(px(3.0));
if comment.deleted {
main_col = main_col.child(
div()
.pt(px(4.0))
.text_size(Typography::TEXT_SM)
.text_color(theme.colors.text_muted)
.italic()
.child("This comment was deleted"),
);
} else {
let time_text = if comment.edited {
format!("{} · edited", comment.created_at)
} else {
comment.created_at.to_string()
};
main_col = main_col.child(
div()
.flex()
.items_baseline()
.gap(px(8.0))
.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(theme.colors.foreground)
.child(comment.author.name.clone()),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_muted)
.child(time_text),
),
);
if is_editing {
let edit_text = ctx.edit_state.read(cx).value().to_string();
let can_save = !edit_text.trim().is_empty() && edit_text.trim() != comment.body.trim();
let shared_cancel = ctx.shared.clone();
let shared_save = ctx.shared.clone();
let edit_st_save = ctx.edit_state.clone();
let comment_id_save = comment.id.clone();
let comments_snap = ctx.all_comments.to_vec();
let on_change_save = ctx.on_comments_change.clone();
let edit_box = div()
.mt(px(4.0))
.flex()
.flex_col()
.gap(px(6.0))
.child(
div()
.id(ElementId::Name(
format!("arc-cm-edit-field-{:?}-{}", ctx.root_id, comment.id).into(),
))
.test_support()
.px(px(10.0))
.py(px(6.0))
.rounded(px(12.0))
.border_1()
.border_color(theme.colors.border_strong)
.bg(theme.colors.surface)
.child(KitInput::new(ctx.edit_state).appearance(false)),
)
.child(
div()
.flex()
.justify_end()
.gap(px(6.0))
.child(
div()
.id(ElementId::Name(
format!("arc-cm-cancel-{:?}-{}", ctx.root_id, comment.id)
.into(),
))
.test_support()
.role(Role::Button)
.h(px(30.0))
.px(px(12.0))
.rounded(Radii::PILL)
.hover(|s| s.bg(theme.colors.surface_muted))
.cursor_pointer()
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_secondary)
.on_mouse_down(MouseButton::Left, move |_, window, _| {
shared_cancel.borrow_mut().editing_id = None;
window.refresh();
})
.child("Cancel"),
)
.child(
div()
.id(ElementId::Name(
format!("arc-cm-save-{:?}-{}", ctx.root_id, comment.id).into(),
))
.test_support()
.role(Role::Button)
.h(px(30.0))
.px(px(12.0))
.rounded(Radii::PILL)
.bg(theme.colors.foreground)
.text_color(theme.colors.background)
.opacity(if can_save { 1.0 } else { 0.35 })
.when(can_save, |el| el.cursor_pointer())
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let trimmed = edit_st_save.read(cx).value().trim().to_string();
if trimmed.is_empty() {
return;
}
shared_save.borrow_mut().editing_id = None;
let next = edit_comment_in_tree(
&comments_snap,
comment_id_save.as_ref(),
SharedString::from(trimmed),
);
if let Some(cb) = &on_change_save {
cb(next, window, cx);
}
window.refresh();
})
.child("Save"),
),
);
main_col = main_col.child(animated_comment_swap(
ElementId::Name(format!("arc-cm-content-{:?}-{}", ctx.root_id, comment.id).into()),
"edit",
edit_box,
window,
cx,
));
} else {
let segments = split_comment_mentions(comment.body.as_ref(), ctx.mentionable);
let mut body_row = div()
.flex()
.flex_wrap()
.text_size(Typography::TEXT_SM)
.text_color(theme.colors.text_secondary);
for (seg, is_mention) in segments {
if is_mention {
body_row =
body_row.child(div().text_color(theme.colors.accent_strong).child(seg));
} else {
body_row = body_row.child(seg);
}
}
let body_content = div().w_full().flex().flex_col().child(body_row);
let mut footer = div()
.mt(px(4.0))
.flex()
.flex_wrap()
.items_center()
.gap(px(6.0));
for rx in &comment.reactions {
let pressed = rx.users.iter().any(|u| u == &ctx.current_user.id);
let border_c = if pressed {
oklab_mix(theme.colors.border, theme.colors.accent, 0.45)
} else {
theme.colors.border
};
let bg_c = if pressed {
theme.colors.accent_subtle
} else {
theme.colors.surface
};
let comments_snap = ctx.all_comments.to_vec();
let cid = comment.id.clone();
let emoji = rx.emoji.clone();
let uid = ctx.current_user.id.clone();
let on_change = ctx.on_comments_change.clone();
footer = footer.child(
div()
.id(ElementId::Name(
format!("arc-cm-rx-{:?}-{}-{}", ctx.root_id, comment.id, rx.emoji)
.into(),
))
.test_support()
.role(Role::Button)
.h(px(26.0))
.pl(px(7.0))
.pr(px(9.0))
.rounded(Radii::PILL)
.border_1()
.border_color(border_c)
.bg(bg_c)
.hover(|s| s.border_color(theme.colors.border_strong))
.cursor_pointer()
.flex()
.items_center()
.gap(px(4.0))
.text_size(Typography::TEXT_XS)
.text_color(if pressed {
theme.colors.foreground
} else {
theme.colors.text_secondary
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let next = toggle_comment_reaction(
&comments_snap,
cid.as_ref(),
emoji.as_ref(),
uid.as_ref(),
);
if let Some(cb) = &on_change {
cb(next, window, cx);
}
})
.child(rx.emoji.clone())
.child(
crate::AnimatedCounter::new(
ElementId::Name(
format!(
"arc-cm-count-{:?}-{}-{}",
ctx.root_id, comment.id, rx.emoji
)
.into(),
),
rx.users.len() as f64,
)
.text_size(Typography::TEXT_XS),
),
);
}
if is_confirming {
let shared_cancel = ctx.shared.clone();
let shared_del = ctx.shared.clone();
let comments_snap = ctx.all_comments.to_vec();
let cid = comment.id.clone();
let on_change = ctx.on_comments_change.clone();
footer = footer.child(
div()
.flex()
.items_center()
.gap(px(4.0))
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.foreground)
.child("Delete this comment?"),
)
.child(
div()
.id(ElementId::Name(
format!("arc-cm-del-no-{:?}-{}", ctx.root_id, comment.id)
.into(),
))
.test_support()
.role(Role::Button)
.h(px(26.0))
.px(px(8.0))
.rounded(Radii::PILL)
.hover(|s| s.bg(theme.colors.surface_muted))
.cursor_pointer()
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_muted)
.on_mouse_down(MouseButton::Left, move |_, window, _| {
shared_cancel.borrow_mut().confirming_id = None;
window.refresh();
})
.child("Cancel"),
)
.child(
div()
.id(ElementId::Name(
format!("arc-cm-del-yes-{:?}-{}", ctx.root_id, comment.id)
.into(),
))
.test_support()
.role(Role::Button)
.h(px(26.0))
.px(px(8.0))
.rounded(Radii::PILL)
.hover(|s| {
s.bg(oklab_mix(theme.colors.surface, theme.colors.danger, 0.12))
})
.cursor_pointer()
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.danger)
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
shared_del.borrow_mut().confirming_id = None;
let next = delete_comment_in_tree(&comments_snap, cid.as_ref());
if let Some(cb) = &on_change {
cb(next, window, cx);
}
window.refresh();
})
.child("Delete"),
),
);
} else if is_picking {
let mut picker = div().flex().items_center().gap(px(2.0));
for emoji in ctx.reactions {
let comments_snap = ctx.all_comments.to_vec();
let cid = comment.id.clone();
let em = emoji.clone();
let uid = ctx.current_user.id.clone();
let shared_p = ctx.shared.clone();
let on_change = ctx.on_comments_change.clone();
picker = picker.child(
div()
.id(ElementId::Name(
format!("arc-cm-pick-{:?}-{}-{}", ctx.root_id, comment.id, emoji)
.into(),
))
.test_support()
.role(Role::Button)
.w(px(26.0))
.h(px(26.0))
.rounded(Radii::PILL)
.hover(|s| s.bg(theme.colors.surface_muted))
.cursor_pointer()
.flex()
.items_center()
.justify_center()
.text_size(px(14.0))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
shared_p.borrow_mut().picker_id = None;
let next = toggle_comment_reaction(
&comments_snap,
cid.as_ref(),
em.as_ref(),
uid.as_ref(),
);
if let Some(cb) = &on_change {
cb(next, window, cx);
}
window.refresh();
})
.child(emoji.clone()),
);
}
let shared_close = ctx.shared.clone();
picker = picker.child(
div()
.id(ElementId::Name(
format!("arc-cm-pick-close-{:?}-{}", ctx.root_id, comment.id).into(),
))
.test_support()
.role(Role::Button)
.w(px(24.0))
.h(px(24.0))
.rounded(Radii::PILL)
.hover(|s| s.bg(theme.colors.surface_muted))
.cursor_pointer()
.flex()
.items_center()
.justify_center()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_muted)
.on_mouse_down(MouseButton::Left, move |_, window, _| {
shared_close.borrow_mut().picker_id = None;
window.refresh();
})
.child("×"),
);
footer = footer.child(picker);
} else {
let shared_rx = ctx.shared.clone();
let cid_rx = comment.id.clone();
let shared_reply = ctx.shared.clone();
let cid_reply = comment.id.clone();
let author_reply = comment.author.name.clone();
let mut actions = div()
.flex()
.items_center()
.gap(px(2.0))
.child(
div()
.id(ElementId::Name(
format!("arc-cm-act-rx-{:?}-{}", ctx.root_id, comment.id).into(),
))
.test_support()
.role(Role::Button)
.h(px(26.0))
.px(px(8.0))
.rounded(Radii::PILL)
.hover(|s| {
s.bg(theme.colors.surface_muted)
.text_color(theme.colors.foreground)
})
.cursor_pointer()
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_muted)
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
shared_rx.borrow().focus_handle.focus(window, cx);
let mut s = shared_rx.borrow_mut();
s.picker_id = Some(cid_rx.clone());
s.confirming_id = None;
window.refresh();
})
.child("+ React"),
)
.child(
div()
.id(ElementId::Name(
format!("arc-cm-act-reply-{:?}-{}", ctx.root_id, comment.id).into(),
))
.test_support()
.role(Role::Button)
.h(px(26.0))
.px(px(8.0))
.rounded(Radii::PILL)
.hover(|s| {
s.bg(theme.colors.surface_muted)
.text_color(theme.colors.foreground)
})
.cursor_pointer()
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_muted)
.on_mouse_down(MouseButton::Left, move |_, window, _| {
let composer = {
let mut ui = shared_reply.borrow_mut();
ui.reply_to = Some((cid_reply.clone(), author_reply.clone()));
ui.composer_state.clone()
};
window.on_next_frame(move |window, cx| {
composer.focus_handle(cx).focus(window, cx);
});
window.refresh();
})
.child("Reply"),
);
if mine {
let shared_edit = ctx.shared.clone();
let edit_st = ctx.edit_state.clone();
let cid_edit = comment.id.clone();
let body_edit = comment.body.clone();
let shared_del = ctx.shared.clone();
let cid_del = comment.id.clone();
actions = actions
.child(
div()
.id(ElementId::Name(
format!("arc-cm-act-edit-{:?}-{}", ctx.root_id, comment.id)
.into(),
))
.test_support()
.role(Role::Button)
.h(px(26.0))
.px(px(8.0))
.rounded(Radii::PILL)
.hover(|s| {
s.bg(theme.colors.surface_muted)
.text_color(theme.colors.foreground)
})
.cursor_pointer()
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_muted)
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
edit_st.update(cx, |s, cx| {
s.set_value(body_edit.clone(), window, cx);
});
let edit_focus = edit_st.clone();
window.on_next_frame(move |window, cx| {
edit_focus.focus_handle(cx).focus(window, cx);
});
let mut s = shared_edit.borrow_mut();
s.editing_id = Some(cid_edit.clone());
s.confirming_id = None;
s.picker_id = None;
window.refresh();
})
.child("Edit"),
)
.child(
div()
.id(ElementId::Name(
format!("arc-cm-act-del-{:?}-{}", ctx.root_id, comment.id)
.into(),
))
.test_support()
.role(Role::Button)
.h(px(26.0))
.px(px(8.0))
.rounded(Radii::PILL)
.hover(|s| {
s.bg(theme.colors.surface_muted)
.text_color(theme.colors.danger)
})
.cursor_pointer()
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_muted)
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
shared_del.borrow().focus_handle.focus(window, cx);
let mut s = shared_del.borrow_mut();
s.confirming_id = Some(cid_del.clone());
s.editing_id = None;
s.picker_id = None;
window.refresh();
})
.child("Delete"),
);
}
footer = footer.child(actions);
}
main_col = main_col.child(animated_comment_swap(
ElementId::Name(format!("arc-cm-content-{:?}-{}", ctx.root_id, comment.id).into()),
if is_confirming {
"confirm"
} else if is_picking {
"picker"
} else {
"view"
},
body_content.child(footer),
window,
cx,
));
}
}
if !comment.replies.is_empty() {
let reply_count = count_comment_tree(&comment.replies);
let toggle_label = if collapsed {
format!(
"Show {} {}",
reply_count,
if reply_count == 1 { "reply" } else { "replies" }
)
} else {
"Hide replies".to_string()
};
let shared_toggle = ctx.shared.clone();
let cid_toggle = comment.id.clone();
let chevron_color = theme.colors.text_muted;
let chevron_degrees = arc_spring(
(
ElementId::Name(format!("arc-cm-chevron-{:?}-{}", ctx.root_id, comment.id).into()),
"rotation",
),
if collapsed { 0.0 } else { 90.0 },
theme.motion.spring.snappy,
window,
cx,
);
let mut toggle_btn = div()
.id(ElementId::Name(
format!("arc-cm-toggle-{:?}-{}", ctx.root_id, comment.id).into(),
))
.test_support()
.role(Role::Button)
.h(px(26.0))
.px(px(6.0))
.rounded(Radii::PILL)
.hover(|s| s.bg(theme.colors.surface_muted))
.cursor_pointer()
.flex()
.items_center()
.gap(px(5.0))
.on_mouse_down(MouseButton::Left, move |_, window, _| {
let mut s = shared_toggle.borrow_mut();
let next = !s.collapsed.get(&cid_toggle).copied().unwrap_or(false);
s.collapsed.insert(cid_toggle.clone(), next);
window.refresh();
})
.child(
canvas(
|b, _, _| b,
move |b, _, window, _| {
let cx = f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
let cy = f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
paint_chevron_toggle(cx, cy, chevron_degrees, chevron_color, window);
},
)
.w(px(12.0))
.h(px(12.0)),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_secondary)
.child(toggle_label),
);
if collapsed {
let reply_authors = collect_comment_authors(&comment.replies);
let mut stack = div().flex().items_center().pl(px(4.0));
for a in reply_authors.iter().take(3) {
stack = stack.child(render_avatar_badge(a.name.as_ref(), 18.0, theme));
}
toggle_btn = toggle_btn.child(stack);
}
main_col = main_col.child(toggle_btn);
}
let avatar_el = if comment.deleted {
div()
.w(px(28.0))
.h(px(28.0))
.flex_shrink_0()
.rounded(Radii::PILL)
.border_1()
.border_color(theme.colors.border_strong)
.into_any_element()
} else {
render_avatar_badge(comment.author.name.as_ref(), 28.0, theme)
};
let mut wrapper = div()
.id(node_id)
.test_support()
.w_full()
.flex()
.flex_col()
.child(
div()
.w_full()
.p(px(10.0))
.flex()
.items_start()
.gap(px(10.0))
.child(avatar_el)
.child(main_col),
);
if !comment.replies.is_empty() {
let mut replies_col = div()
.ml(px(24.0))
.pl(px(12.0))
.border_l_1()
.border_color(theme.colors.border)
.flex()
.flex_col();
for reply in &comment.replies {
replies_col = replies_col.child(render_comment_node(reply, ctx, window, cx));
}
wrapper = wrapper.child(animated_comment_height(
ElementId::Name(format!("arc-cm-replies-{:?}-{}", ctx.root_id, comment.id).into()),
!collapsed,
replies_col,
window,
cx,
));
}
wrapper.into_any_element()
}
impl RenderOnce for CommentThread {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let placeholder_str = self.placeholder.clone();
let state = window.use_keyed_state(
ElementId::Name(format!("arc-comment-thread-state-{:?}", self.id).into()),
cx,
|window, cx| {
let composer_state =
cx.new(|cx| InputState::new(window, cx).placeholder(placeholder_str.clone()));
let edit_state =
cx.new(|cx| InputState::new(window, cx).placeholder("Edit comment"));
let observers = Rc::new(vec![
window.subscribe(&composer_state, cx, |_, event: &InputEvent, window, _| {
if matches!(event, InputEvent::Change) {
window.refresh();
}
}),
window.subscribe(&edit_state, cx, |_, event: &InputEvent, window, _| {
if matches!(event, InputEvent::Change) {
window.refresh();
}
}),
]);
Rc::new(RefCell::new(CommentThreadInternal {
editing_id: None,
confirming_id: None,
picker_id: None,
reply_to: None,
collapsed: HashMap::new(),
composer_state,
edit_state,
next_serial: 1,
focus_handle: cx.focus_handle(),
_input_observers: observers,
resolved: self.resolved,
}))
},
);
let shared = state.read(cx).clone();
{
let mut ui = shared.borrow_mut();
if ui.resolved != self.resolved {
ui.resolved = self.resolved;
ui.editing_id = None;
ui.confirming_id = None;
ui.picker_id = None;
ui.reply_to = None;
}
}
let composer_state = shared.borrow().composer_state.clone();
let edit_state = shared.borrow().edit_state.clone();
let reply_to = shared.borrow().reply_to.clone();
let total = count_comment_tree(&self.comments);
let participants = collect_comment_authors(&self.comments);
let mentionable = self.people.clone().unwrap_or_else(|| {
let mut list = participants.clone();
if !list.iter().any(|p| p.id == self.current_user.id) {
list.push(self.current_user.clone());
}
list
});
let comment_count_label = format!(
"{} {}",
total,
if total == 1 { "comment" } else { "comments" }
);
let people_count_label = format!(
"{} {}",
participants.len(),
if participants.len() == 1 {
"person"
} else {
"people"
}
);
let root_radius = if self.resolved {
Radii::SURFACE
} else {
Radii::PANEL
};
let focus = shared.borrow().focus_handle.clone();
let escape_ui = shared.clone();
let mut root = div()
.id(self.id.clone())
.test_support()
.role(Role::Region)
.aria_label("Comment thread")
.track_focus(&focus)
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape" {
let mut ui = escape_ui.borrow_mut();
ui.editing_id = None;
ui.confirming_id = None;
ui.picker_id = None;
ui.reply_to = None;
cx.stop_propagation();
window.refresh();
}
})
.w_full()
.rounded(root_radius)
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.surface)
.overflow_hidden();
if self.resolved {
let success_color = theme.colors.success;
let on_resolved = self.on_resolved_change.clone();
let mut title_line = div().flex().items_center().gap(px(4.0)).child(
div()
.text_size(Typography::TEXT_SM)
.text_color(theme.colors.foreground)
.child("Resolved"),
);
if let Some(title) = &self.title {
title_line = title_line.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(theme.colors.text_secondary)
.child(format!("· {title}")),
);
}
let mut avatar_stack = div().flex().items_center().gap(px(2.0));
for author in participants.iter().take(3) {
avatar_stack =
avatar_stack.child(render_avatar_badge(author.name.as_ref(), 22.0, &theme));
}
root = root.child(
div()
.w_full()
.px(px(14.0))
.py(px(10.0))
.flex()
.items_center()
.gap(px(12.0))
.child(
div()
.w(px(24.0))
.h(px(24.0))
.rounded(Radii::PILL)
.bg(oklab_mix(theme.colors.surface, theme.colors.success, 0.14))
.flex()
.items_center()
.justify_center()
.child(
canvas(
|b, _, _| b,
move |b, _, window, _| {
let cx =
f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
let cy =
f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
paint_check(cx, cy, success_color, window);
},
)
.w(px(14.0))
.h(px(14.0)),
),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(title_line)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_muted)
.child(format!("{comment_count_label} · {people_count_label}")),
),
)
.child(avatar_stack)
.child(
div()
.id(ElementId::Name(
format!("arc-cm-reopen-{:?}", self.id).into(),
))
.test_support()
.role(Role::Button)
.h(px(32.0))
.px(px(12.0))
.rounded(Radii::PILL)
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.surface)
.hover(|s| s.bg(theme.colors.surface_muted))
.cursor_pointer()
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.foreground)
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if let Some(cb) = &on_resolved {
cb(false, window, cx);
}
})
.child("Reopen"),
),
);
return animated_comment_swap(
ElementId::NamedChild(self.id.clone().into(), "thread-height".into()),
"resolved",
root,
window,
cx,
);
}
let on_resolve = self.on_resolved_change.clone();
let can_resolve = total > 0;
let success_color = theme.colors.success;
let mut heading = div().flex().flex_col();
if let Some(title) = &self.title {
heading = heading.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(theme.colors.foreground)
.child(title.clone()),
);
}
heading = heading.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_muted)
.child(comment_count_label),
);
let header = div()
.w_full()
.pl(px(18.0))
.pr(px(12.0))
.pt(px(12.0))
.pb(px(8.0))
.flex()
.items_center()
.justify_between()
.gap(px(12.0))
.child(heading)
.child(
div()
.id(ElementId::Name(
format!("arc-cm-resolve-{:?}", self.id).into(),
))
.test_support()
.role(Role::Button)
.h(px(32.0))
.pl(px(10.0))
.pr(px(12.0))
.rounded(Radii::PILL)
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.surface)
.opacity(if can_resolve { 1.0 } else { 0.45 })
.when(can_resolve, |el| {
el.cursor_pointer()
.hover(|s| s.bg(theme.colors.surface_muted))
})
.flex()
.items_center()
.gap(px(6.0))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if can_resolve && let Some(cb) = &on_resolve {
cb(true, window, cx);
}
})
.child(
canvas(
|b, _, _| b,
move |b, _, window, _| {
let cx = f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
let cy = f32::from(b.origin.y) + f32::from(b.size.height) * 0.5;
paint_check(cx, cy, success_color, window);
},
)
.w(px(14.0))
.h(px(14.0)),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.foreground)
.child("Resolve"),
),
);
let rctx = RenderCtx {
root_id: &self.id,
theme: &theme,
current_user: &self.current_user,
mentionable: &mentionable,
reactions: &self.reactions,
all_comments: &self.comments,
shared: &shared,
edit_state: &edit_state,
on_comments_change: &self.on_comments_change,
};
let body_section = if self.comments.is_empty() {
div()
.px(px(18.0))
.py(px(12.0))
.text_size(Typography::TEXT_SM)
.text_color(theme.colors.text_muted)
.child("No comments yet. Start the conversation below.")
.into_any_element()
} else {
let mut list = div().px(px(8.0)).flex().flex_col();
for comment in &self.comments {
list = list.child(render_comment_node(comment, &rctx, window, cx));
}
list.into_any_element()
};
let current_draft = composer_state.read(cx).value().to_string();
let can_send = !current_draft.trim().is_empty();
let active_mention_query = current_draft.rsplit_once('@').and_then(|(before, after)| {
if (before.is_empty() || before.ends_with(char::is_whitespace))
&& !after.contains(char::is_whitespace)
{
Some(after.to_lowercase())
} else {
None
}
});
let mention_matches: Vec<&CommentAuthor> = if let Some(q) = &active_mention_query {
mentionable
.iter()
.filter(|p| {
let lower = p.name.to_lowercase();
lower.starts_with(q.as_str())
|| lower.split_whitespace().any(|w| w.starts_with(q.as_str()))
})
.take(4)
.collect()
} else {
Vec::new()
};
let submit_reply = {
let composer_st = composer_state.clone();
let shared_s = shared.clone();
let comments_snap = self.comments.clone();
let current_user = self.current_user.clone();
let now_label = self.now_label.clone();
let max_depth = self.max_depth;
let on_change = self.on_comments_change.clone();
Rc::new(move |window: &mut Window, cx: &mut App| {
let trimmed = composer_st.read(cx).value().trim().to_string();
if trimmed.is_empty() {
return;
}
let (serial, reply_parent) = {
let mut st = shared_s.borrow_mut();
let s = st.next_serial;
st.next_serial += 1;
let r = st.reply_to.take().map(|(id, _)| id);
if let Some(pid) = &r {
st.collapsed.insert(pid.clone(), false);
}
(s, r)
};
composer_st.update(cx, |state, cx| {
state.set_value("", window, cx);
});
let new_comment = ThreadComment::new(
format!("c-local-{serial}"),
current_user.clone(),
trimmed,
now_label.clone(),
);
let next = append_comment_reply(
&comments_snap,
reply_parent.as_deref(),
max_depth,
new_comment,
);
if let Some(cb) = &on_change {
cb(next, window, cx);
}
window.refresh();
})
};
let submit_click = submit_reply.clone();
let submit_key = submit_reply.clone();
let mut composer_area = div()
.w_full()
.mt(px(4.0))
.px(px(12.0))
.py(px(10.0))
.border_t_1()
.border_color(theme.colors.border_subtle)
.flex()
.flex_col()
.gap(px(8.0));
if let Some((_, target_name)) = &reply_to {
let shared_cancel_reply = shared.clone();
composer_area = composer_area.child(
div()
.pl(px(38.0))
.flex()
.items_center()
.gap(px(6.0))
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_secondary)
.child("Replying to")
.child(
div()
.text_color(theme.colors.foreground)
.child(target_name.clone()),
)
.child(
div()
.id(ElementId::Name(
format!("arc-cm-cancel-reply-{:?}", self.id).into(),
))
.test_support()
.role(Role::Button)
.w(px(20.0))
.h(px(20.0))
.rounded(Radii::PILL)
.hover(|s| s.bg(theme.colors.surface_muted))
.cursor_pointer()
.flex()
.items_center()
.justify_center()
.on_mouse_down(MouseButton::Left, move |_, window, _| {
shared_cancel_reply.borrow_mut().reply_to = None;
window.refresh();
})
.child("×"),
),
);
}
if !mention_matches.is_empty() {
let mut bar = div().pl(px(38.0)).flex().flex_wrap().gap(px(6.0));
for person in mention_matches {
let pname = person.name.clone();
let cst = composer_state.clone();
bar = bar.child(
div()
.id(ElementId::Name(
format!("arc-cm-mention-{:?}-{}", self.id, person.id).into(),
))
.role(Role::ListBoxOption)
.h(px(28.0))
.px(px(8.0))
.rounded(px(10.0))
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.surface_raised)
.hover(|s| s.bg(theme.colors.surface_muted))
.cursor_pointer()
.flex()
.items_center()
.gap(px(6.0))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let cur = cst.read(cx).value().to_string();
let next = if let Some((head, _)) = cur.rsplit_once('@') {
format!("{head}@{pname} ")
} else {
format!("{cur}@{pname} ")
};
cst.update(cx, |s, cx| {
s.set_value(next, window, cx);
});
})
.child(render_avatar_badge(person.name.as_ref(), 18.0, &theme))
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.foreground)
.child(person.name.clone()),
),
);
}
composer_area = composer_area.child(bar);
}
composer_area = composer_area.child(
div()
.w_full()
.flex()
.items_center()
.gap(px(10.0))
.child(render_avatar_badge(
self.current_user.name.as_ref(),
28.0,
&theme,
))
.child(
div()
.id(ElementId::Name(
format!("arc-cm-composer-field-{:?}", self.id).into(),
))
.test_support()
.flex_1()
.min_w_0()
.min_h(px(36.0))
.px(px(12.0))
.py(px(6.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.surface)
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "enter"
&& (event.keystroke.modifiers.control
|| event.keystroke.modifiers.platform)
{
submit_key(window, cx);
}
})
.child(KitInput::new(&composer_state).appearance(false)),
)
.child(
div()
.id(ElementId::Name(format!("arc-cm-send-{:?}", self.id).into()))
.test_support()
.role(Role::Button)
.h(px(36.0))
.px(px(14.0))
.rounded(Radii::PILL)
.bg(theme.colors.foreground)
.text_color(theme.colors.background)
.opacity(if can_send { 1.0 } else { 0.35 })
.when(can_send, |el| el.cursor_pointer())
.flex()
.items_center()
.text_size(Typography::TEXT_SM)
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
submit_click(window, cx);
})
.child("Send"),
),
);
let content = root.child(
div()
.w_full()
.flex()
.flex_col()
.child(header)
.child(body_section)
.child(composer_area),
);
animated_comment_swap(
ElementId::NamedChild(self.id.clone().into(), "thread-height".into()),
"thread",
content,
window,
cx,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
use std::time::Duration;
fn action(name: &str) -> ElementId {
ElementId::Name(format!("arc-cm-{name}-{:?}", ElementId::from("thread-test")).into())
}
fn node_action(name: &str, node: &str) -> ElementId {
ElementId::Name(format!("arc-cm-{name}-{:?}-{node}", ElementId::from("thread-test")).into())
}
struct Host {
comments: Vec<ThreadComment>,
resolved: bool,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let comments_host = cx.entity().clone();
let resolved_host = cx.entity().clone();
div().size_full().flex().flex_col().items_start().child(
CommentThread::new(
"thread-test",
CommentAuthor::new("me", "Alex Rivera"),
self.comments.clone(),
)
.resolved(self.resolved)
.on_comments_change(move |next, _, cx| {
comments_host.update(cx, |this, cx| {
this.comments = next;
cx.notify();
});
})
.on_resolved_change(move |next, _, cx| {
resolved_host.update(cx, |this, cx| {
this.resolved = next;
cx.notify();
});
}),
)
}
}
fn init(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
arc_tokens::install_arc_theme(
arc_tokens::ThemeMode::Light,
arc_tokens::Accent::Neutral,
cx,
);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx);
});
}
fn host() -> Host {
Host {
comments: vec![
ThreadComment::new("c1", CommentAuthor::new("me", "Alex Rivera"), "Root", "now")
.reply(ThreadComment::new(
"c2",
CommentAuthor::new("other", "Clara Wu"),
"Reply",
"now",
)),
],
resolved: false,
}
}
#[gpui_kit::test]
fn comment_thread_collapse_has_intermediate_height(cx: &mut TestAppContext) {
init(cx);
let (_, window) = cx.add_window_view(|_, _| host());
window.update(|w, cx| {
w.render_frame(cx);
w.render_frame(cx);
});
let before = window.update(|w, cx| {
let before = w.find("thread-test").bounds().size.height;
w.click(node_action("toggle", "c1"), cx);
before
});
window.executor().advance_clock(Duration::from_millis(70));
let middle = window.update(|w, cx| {
w.render_frame(cx);
w.find("thread-test").bounds().size.height
});
window.executor().advance_clock(Duration::from_millis(1500));
let after = window.update(|w, cx| {
w.render_frame(cx);
w.render_frame(cx);
w.find("thread-test").bounds().size.height
});
assert!(
before > middle && middle > after,
"collapse must animate: {before:?} > {middle:?} > {after:?}"
);
}
#[gpui_kit::test]
fn comment_thread_controls_edit_reply_react_delete_and_resolve(cx: &mut TestAppContext) {
init(cx);
cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx));
let (view, window) = cx.add_window_view(|_, _| host());
window.update(|w, cx| {
w.render_frame(cx);
w.render_frame(cx);
w.click(node_action("act-rx", "c1"), cx);
assert!(w.try_find(node_action("pick-close", "c1")).is_some());
let emoji = ElementId::Name(
format!(
"arc-cm-pick-{:?}-c1-{}",
ElementId::from("thread-test"),
COMMENT_DEFAULT_REACTIONS[0]
)
.into(),
);
w.click(emoji, cx);
assert_eq!(view.read(cx).comments[0].reactions.len(), 1);
w.click(node_action("act-edit", "c1"), cx);
w.click(node_action("edit-field", "c1"), cx);
w.press("ctrl-a", cx);
w.input("Edited root", cx);
w.render_frame(cx);
w.click(node_action("save", "c1"), cx);
assert_eq!(view.read(cx).comments[0].body.as_ref(), "Edited root");
assert!(view.read(cx).comments[0].edited);
w.click(node_action("act-reply", "c1"), cx);
w.click(action("composer-field"), cx);
w.input("New reply", cx);
w.render_frame(cx);
w.click(action("send"), cx);
assert_eq!(view.read(cx).comments[0].replies.len(), 2);
w.click(action("resolve"), cx);
w.render_frame(cx);
assert!(view.read(cx).resolved);
assert!(w.try_find(action("cancel-reply")).is_none());
w.click(action("reopen"), cx);
w.render_frame(cx);
assert!(!view.read(cx).resolved);
w.click(node_action("act-del", "c1"), cx);
assert!(w.try_find(node_action("del-yes", "c1")).is_some());
w.click(node_action("del-yes", "c1"), cx);
assert!(view.read(cx).comments[0].deleted);
assert_eq!(view.read(cx).comments[0].replies.len(), 2);
});
}
#[gpui_kit::test]
fn comment_thread_resolve_height_and_midflight_reversal(cx: &mut TestAppContext) {
init(cx);
let (_, window) = cx.add_window_view(|_, _| host());
let frame_id = ElementId::NamedChild(
ElementId::from("thread-test").into(),
"thread-height".into(),
);
let before = window.update(|w, cx| {
w.render_frame(cx);
w.render_frame(cx);
w.render_frame(cx);
let before = w.find(frame_id.clone()).bounds().size.height;
w.click(action("resolve"), cx);
before
});
window.executor().advance_clock(Duration::from_millis(80));
let middle = window.update(|w, cx| {
w.render_frame(cx);
w.find(frame_id.clone()).bounds().size.height
});
window.executor().advance_clock(Duration::from_millis(1500));
let after = window.update(|w, cx| {
w.render_frame(cx);
w.render_frame(cx);
let after = w.find(frame_id.clone()).bounds().size.height;
w.click(action("reopen"), cx);
after
});
assert!(
before > middle && middle > after,
"resolve: {before:?} > {middle:?} > {after:?}"
);
window.executor().advance_clock(Duration::from_millis(100));
window.update(|w, cx| {
w.render_frame(cx);
w.click(action("resolve"), cx);
});
window.executor().advance_clock(Duration::from_millis(1500));
window.update(|w, cx| {
w.render_frame(cx);
w.render_frame(cx);
assert!((w.find(frame_id).bounds().size.height - after).abs() < px(1.0));
});
}
#[test]
fn comment_thread_tree_operations_and_mentions() {
let alice = CommentAuthor::new("a", "Alice Chen");
let bob = CommentAuthor::new("b", "Bob Lin");
let root_comment =
ThreadComment::new("c1", alice.clone(), "Ping @Bob Lin on hero copy", "2h")
.reply(ThreadComment::new("c2", bob.clone(), "Looks crisp!", "1h"));
let tree = vec![root_comment];
assert_eq!(count_comment_tree(&tree), 2);
assert_eq!(collect_comment_authors(&tree).len(), 2);
let parts =
split_comment_mentions("Ping @Bob Lin on hero copy", &[alice.clone(), bob.clone()]);
assert_eq!(
parts,
vec![
("Ping ".to_string(), false),
("@Bob Lin".to_string(), true),
(" on hero copy".to_string(), false),
]
);
let r3 = ThreadComment::new("c3", alice.clone(), "Deep reply", "Just now");
let tree = append_comment_reply(&tree, Some("c2"), 2, r3);
assert_eq!(count_comment_tree(&tree), 3);
let tree = delete_comment_in_tree(&tree, "c1");
assert!(tree[0].deleted);
assert_eq!(count_comment_tree(&tree), 2);
let tree = toggle_comment_reaction(&tree, "c2", "👍", "a");
assert_eq!(tree[0].replies[0].reactions.len(), 1);
let tree = toggle_comment_reaction(&tree, "c2", "👍", "a");
assert!(tree[0].replies[0].reactions.is_empty());
}
}