Visual Studio Code, rebuilt in Rust
Rust
//! commentNode.ts and reactionsAction.ts: one comment of a thread widget. The author line carries the
//! `comments/comment/title` inline actions and a "More Actions..." menu of the others; a comment the extension
//! switches to `CommentMode.Editing` shows its text in the input with the `comments/comment/context` buttons; the
//! reactions with a count follow the body and toggle through the controller's reaction handler, whose picker lists
//! the comment's reactions as `reaction.command.<label>` commands.
use gpui::{AnyElement, Context, MouseButton, Window, div, img, prelude::*, px};
use serde_json::{Value, json};
use super::Workbench;
use super::comment_thread_widget::{BODY_LINE, ThreadWidget};
use super::comments::Thread;
use super::hover::{HoverContent, HoverOptions};
use super::markdown_view::MarkdownStyle;
use crate::markdown::{MarkdownString, parse};
use crate::menus::{MenuAction, MenuId, menu_actions};
#[cfg(test)]
mod tests;
/// `languages.CommentMode.Editing`.
const EDITING: u64 = 0;
/// review.css `.comment-reactions`: 8px above the 25px row.
pub(super) const REACTIONS_ROW: f32 = 8. + 25.;
/// review.css `.review-widget .action-item`: each reaction and the picker are action items 4px after the previous.
const ACTION_ITEM_MARGIN: f32 = 4.;
impl Workbench {
/// `CommentNode.update` on a mode change: a comment switched to Editing opens its edit form with its text, one
/// switched back closes it. A comment new to the thread keeps its body (`switchToEditMode` runs on changes only).
pub(super) fn sync_comment_edits(&mut self, controller: u64, thread: u64, before: &[Value], window: &mut Window, cx: &mut Context<Self>) {
let Some(state) = self.comment_thread(controller, thread) else { return };
let mut opened = Vec::new();
let mut closed = Vec::new();
for comment in &state.comments {
let Some(old) = before.iter().find(|old| old["uniqueIdInThread"] == comment["uniqueIdInThread"]) else { continue };
if comment["mode"].is_null() || comment["mode"] == old["mode"] {
continue;
}
let id = comment["uniqueIdInThread"].as_u64().unwrap_or_default();
match comment["mode"].as_u64() == Some(EDITING) {
true => opened.push((id, comment_text(comment))),
false => closed.push(id),
}
}
for id in closed {
if self.close_comment_editor(controller, thread, Some(id)).is_some() {
self.editors_changed(cx);
}
}
for (id, text) in opened {
self.open_comment_editor(controller, thread, Some(id), &text, window, cx);
}
}
/// The context of a comment's menus: the thread's keys and `comment`, its `contextValue`.
fn comment_context(&self, controller: u64, thread: &Thread, comment: &Value, window: &Window) -> std::collections::HashMap<String, Value> {
let mut context = self.comment_thread_context(controller, thread, window);
if let Some(value) = comment["contextValue"].as_str() {
context.insert("comment".into(), json!(value));
}
context
}
/// `commentNodeContext`: the `CommentNode` (`MarshalledId.CommentNode`, 10) and the thread.
fn comment_node_args(controller: u64, thread: u64, comment: &Value) -> Vec<Value> {
let thread = json!({ "$mid": 7, "commentControlHandle": controller, "commentThreadHandle": thread });
vec![json!({ "thread": thread, "commentUniqueId": comment["uniqueIdInThread"], "$mid": 10 }), thread]
}
/// The edit form's `CommentFormActions` run: the command gets the `CommentThreadNode` (`MarshalledId`, 11) with
/// the typed text, then the form closes (`removeCommentEditor`).
fn run_comment_edit_action(&mut self, id: &str, controller: u64, thread: u64, comment: u64, window: &mut Window, cx: &mut Context<Self>) {
let Some(form) = self.comment_form(controller, thread, Some(comment)) else { return };
let text = self.form_text(form);
self.close_comment_editor(controller, thread, Some(comment));
let marshalled = json!({ "$mid": 7, "commentControlHandle": controller, "commentThreadHandle": thread });
let argument = json!({ "thread": marshalled, "commentUniqueId": comment, "text": text, "$mid": 11 });
self.run_code_lens_command(id, vec![argument], window, cx);
self.sync_comment_widgets();
self.editors_changed(cx);
window.focus(&self.editor_focus, cx);
cx.notify();
}
/// `editor.action.submitComment` in an edit form: its first enabled action runs.
pub(super) fn submit_comment_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some((controller, thread_handle, Some(comment_id))) = self.focused_comment_form().map(|form| (form.controller, form.thread, form.comment)) else { return };
let Some(thread) = self.comment_thread(controller, thread_handle) else { return };
let Some(comment) = thread.comments.iter().find(|comment| comment["uniqueIdInThread"].as_u64() == Some(comment_id)) else { return };
let context = self.comment_context(controller, thread, comment, window);
let first = menu_actions(&self.menus, MenuId::CommentActions, &context).into_iter().find_map(|action| match action {
MenuAction::Command { id, enabled: true, .. } => Some(id),
_ => None,
});
if let Some(id) = first {
self.run_comment_edit_action(&id, controller, thread_handle, comment_id, window, cx);
}
}
/// `commentService.toggleReaction`: the controller's reaction handler adds or removes the user's reaction.
fn toggle_comment_reaction(&mut self, controller: u64, thread: u64, comment: &Value, reaction: &Value) {
let Some(resource) = self.comment_thread(controller, thread).map(|thread| thread.resource.clone()) else { return };
drop(self.host.call("ExtHostComments", "$toggleReaction", vec![json!(controller), json!(thread), resource, comment.clone(), reaction.clone()]));
}
/// `CommentNode`: the author, the comment's label and its title actions, then the body (plain text, rendered
/// markdown, or the edit form), then the reactions.
pub(super) fn comment_node(&self, widget: &ThreadWidget, thread: &Thread, index: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
let comment = &thread.comments[index];
let foreground = self.foreground_or("foreground");
let header = div()
.h(px(22.))
.flex()
.items_center()
.child(div().min_w_0().overflow_hidden().text_ellipsis().whitespace_nowrap().font_weight(gpui::FontWeight::BOLD).child(comment["userName"].as_str().unwrap_or_default().to_owned()))
.children(comment["label"].as_str().map(|label| div().mx(px(5.)).px(px(2.)).italic().child(label.to_owned())))
.child(self.comment_title_actions(widget, thread, comment, window, cx));
let editing = comment["uniqueIdInThread"].as_u64().is_some_and(|id| self.comment_form(widget.controller, widget.thread, Some(id)).is_some());
let body = match (&comment["body"], editing) {
(_, true) => self.comment_edit_form(widget, thread, comment, window, cx),
(Value::String(text), false) => div().whitespace_normal().child(text.clone()).into_any_element(),
(markdown, false) => {
let blocks = parse(&MarkdownString::from_value(markdown));
let style = MarkdownStyle { font_size: 13., line_height: BODY_LINE, foreground, action_handler: None, code_foreground: None, code_background: None, selectable: false };
self.markdown_blocks(&format!("comment-{}-{}-{index}", widget.controller, widget.thread), &blocks, style, "", cx).into_any_element()
}
};
let body = match editing {
true => body,
false => div().relative().child(body).child(self.comment_body_measure(widget, comment, cx)).into_any_element(),
};
// The edit container replaces the body and its 4px padding.
let body = div().when(!editing, |body| body.pt(px(4.))).line_height(px(BODY_LINE)).child(body);
let details = div().pl(px(20.)).flex_1().min_w_0().overflow_hidden().child(header).child(body);
// commentNode.ts `setFocus`: the comment the arrows moved to has the focus outline.
let focused = self.comments.focused_thread == Some((widget.controller, widget.thread, Some(index))) && self.comments.thread_focus.is_focused(window);
let context = self.comment_context(widget.controller, thread, comment, window);
let args = Self::comment_node_args(widget.controller, widget.thread, comment);
div()
.relative()
.debug_selector(move || format!("comment-node-{index}"))
// commentNode.ts `onContextMenu`: `comments/commentThread/comment/context` with the `commentNodeContext`.
.on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &gpui::MouseDownEvent, window, cx| {
cx.stop_propagation();
let actions = menu_actions(&workbench.menus, MenuId::CommentThreadCommentContext, &context);
if !actions.is_empty() {
workbench.show_context_menu_actions(actions, &context, gpui::Bounds::new(event.position, Default::default()), args.clone(), window, cx);
}
}))
.pt(px(8.))
.pb(px(8.))
.pl(px(20.))
.pr(px(16.))
.flex()
.child(details.children(self.comment_reactions(widget, comment, cx)))
.when(focused, |node| node.child(self.focus_outline()))
.into_any_element()
}
/// commentThreadZoneWidget.ts `_refresh` on the body's mutations: a drawn height that differs from the recorded
/// one (a wrapped line, a markdown block) is recorded and the zones resize to it.
fn comment_body_measure(&self, widget: &ThreadWidget, comment: &Value, cx: &mut Context<Self>) -> impl IntoElement {
let key = (widget.controller, widget.thread, widget.model_id, comment["uniqueIdInThread"].as_u64().unwrap_or_default());
let recorded = self.comments.body_heights.get(&key).copied();
let entity = cx.entity().downgrade();
let record = move |bounds: gpui::Bounds<gpui::Pixels>, _: &mut Window, cx: &mut gpui::App| {
let height = f32::from(bounds.size.height);
if recorded == Some(height) {
return;
}
cx.defer(move |cx| {
let _ = entity.update(cx, |workbench, cx| {
workbench.comments.body_heights.insert(key, height);
workbench.sync_comment_widgets();
cx.notify();
});
});
};
gpui::canvas(record, |_, _, _, _| ()).absolute().inset_0()
}
/// `createActionsToolbar`: the `inline` group as icons, the others behind "More Actions...".
fn comment_title_actions(&self, widget: &ThreadWidget, thread: &Thread, comment: &Value, window: &Window, cx: &mut Context<Self>) -> AnyElement {
let context = self.comment_context(widget.controller, thread, comment, window);
let args = Self::comment_node_args(widget.controller, widget.thread, comment);
let icon_color = self.foreground_or("icon.foreground");
let mut actions = Vec::new();
let inline: Vec<_> = self.menus.iter().filter(|item| item.menu == MenuId::CommentTitle && item.group.starts_with("inline")).cloned().collect();
for action in menu_actions(&inline, MenuId::CommentTitle, &context) {
let MenuAction::Command { id, title, enabled: true, .. } = action else { continue };
actions.push(self.command_button(&id, title, args.clone(), icon_color, cx).into_any_element());
}
let others: Vec<_> = self.menus.iter().filter(|item| item.menu != MenuId::CommentTitle || !item.group.starts_with("inline")).cloned().collect();
let secondary = menu_actions(&others, MenuId::CommentTitle, &context);
if !secondary.is_empty() {
let more = self
.icon("toolbar-more", 22., 16., icon_color)
.id(gpui::SharedString::from(format!("comment-more-{}-{}-{}", widget.controller, widget.thread, comment["uniqueIdInThread"])))
.rounded(px(4.))
.cursor_pointer()
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
.child(self.hover_target("comment-more-hover", HoverContent::Text("More Actions...".into()), HoverOptions::mouse()))
.on_click(cx.listener(move |workbench, event: &gpui::ClickEvent, window, cx| {
let anchor = gpui::Bounds::new(event.position(), Default::default());
workbench.show_context_menu_actions(secondary.clone(), &context, anchor, args.clone(), window, cx);
}));
actions.push(more.into_any_element());
}
div().ml_auto().h(px(22.)).flex().items_center().children(actions).into_any_element()
}
/// The edit container: the input with the text, then the `comments/comment/context` buttons, the first primary.
fn comment_edit_form(&self, widget: &ThreadWidget, thread: &Thread, comment: &Value, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
let comment_id = comment["uniqueIdInThread"].as_u64().unwrap_or_default();
let (controller, thread_handle) = (widget.controller, widget.thread);
let input = self.comment_editor_box(self.comment_form(controller, thread_handle, Some(comment_id)), None, window, cx);
let context = self.comment_context(controller, thread, comment, window);
let mut buttons = Vec::new();
for (index, action) in menu_actions(&self.menus, MenuId::CommentActions, &context).into_iter().enumerate() {
let MenuAction::Command { id, title, enabled, .. } = action else { continue };
let key = format!("comment-edit-action-{id}");
buttons.push(self.comment_form_button(key, title, enabled, index == 0, move |workbench, window, cx| workbench.run_comment_edit_action(&id, controller, thread_handle, comment_id, window, cx), cx));
}
let editor_actions = self.comment_editor_actions(&context, controller, thread_handle, Some(comment_id), cx);
let actions = div().mt(px(10.)).pt(px(10.)).mb(px(10.)).flex().flex_row_reverse().children(buttons.into_iter().rev()).children(editor_actions);
// review.css: `.edit-textarea` keeps 12px from the right, the form actions do not.
div().mt(px(5.)).child(div().mr(px(12.)).child(input)).child(actions).into_any_element()
}
/// `createReactionsContainer`: each reaction with a count, its icon or label and the count, active when the user
/// reacted; a click toggles it when the controller has a reaction handler.
fn comment_reactions(&self, widget: &ThreadWidget, comment: &Value, cx: &mut Context<Self>) -> Option<AnyElement> {
let handler = self.comments.controllers.iter().any(|controller| controller.handle == widget.controller && controller.reaction_handler);
let reactions: Vec<Value> = comment["commentReactions"].as_array().into_iter().flatten().filter(|reaction| reaction["count"].as_u64().unwrap_or_default() > 0).cloned().collect();
if reactions.is_empty() && !handler {
return None;
}
let mut row = div().mt(px(8.)).min_h(px(25.)).flex().items_center();
for (index, reaction) in reactions.into_iter().enumerate() {
let label = reaction["label"].as_str().unwrap_or_default().to_owned();
let content = match reaction["iconPath"]["path"].as_str() {
Some(path) => div().w(px(14.)).child(img(path.to_owned()).size(px(14.))).into_any_element(),
None => div().mr(px(4.)).line_height(px(20.)).child(label.clone()).into_any_element(),
};
let active = handler && reaction["hasReacted"] == true;
let (controller, thread, comment) = (widget.controller, widget.thread, comment.clone());
let tooltip = reaction_tooltip(&reaction, handler);
let count = reaction["count"].as_u64();
let button = div()
.id(gpui::SharedString::from(format!("comment-reaction-{controller}-{thread}-{}-{index}", comment["uniqueIdInThread"])))
.debug_selector(move || format!("comment-reaction-{index}"))
.ml(px(ACTION_ITEM_MARGIN))
.px(px(4.))
.py(px(1.))
.flex()
.items_center()
.text_size(px(12.))
.whitespace_nowrap()
.border_1()
.border_color(self.color("panel.border"))
.rounded(px(3.))
.when(!handler, |button| button.opacity(0.6))
.when(active, |button| button.hover(|button| button.bg(self.color("statusBarItem.hoverBackground"))))
.when(handler, |button| {
button.cursor_pointer().on_click(cx.listener(move |workbench, _, _, _| workbench.toggle_comment_reaction(controller, thread, &comment, &reaction)))
})
.child(self.hover_target(gpui::SharedString::from(format!("comment-reaction-hover-{index}")), HoverContent::Text(tooltip), HoverOptions::mouse()))
.child(content)
.children(count.map(|count| div().child(count.to_string())));
row = row.child(button);
}
if handler {
let (controller, thread, comment) = (widget.controller, widget.thread, comment.clone());
let picker = self
.icon("reactions", 26., 16., self.foreground_or("icon.foreground"))
.id(gpui::SharedString::from(format!("comment-reaction-picker-{controller}-{thread}-{}", comment["uniqueIdInThread"])))
.debug_selector(|| "comment-reaction-picker".into())
.ml(px(ACTION_ITEM_MARGIN))
.h(px(16.))
.mt(px(3.))
.cursor_pointer()
.child(self.hover_target("comment-reaction-picker-hover", HoverContent::Text("Pick Reactions...".into()), HoverOptions::mouse()))
.on_click(cx.listener(move |workbench, event: &gpui::ClickEvent, window, cx| {
let anchor = gpui::Bounds::new(event.position(), Default::default());
workbench.show_reaction_picker(controller, thread, &comment, anchor, window, cx);
}));
row = row.child(picker);
}
Some(row.into_any_element())
}
/// `createReactionPicker`: the comment's reactions as `reaction.command.<label>` items that toggle them. The
/// previous picker's commands are disposed first.
fn show_reaction_picker(&mut self, controller: u64, thread: u64, comment: &Value, anchor: gpui::Bounds<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
for (id, registration) in std::mem::take(&mut self.comments.reaction_commands) {
self.commands.dispose(&id, registration);
}
let mut actions = Vec::new();
for reaction in comment["commentReactions"].as_array().into_iter().flatten() {
let label = reaction["label"].as_str().unwrap_or_default().to_owned();
let id = format!("reaction.command.{label}");
let (comment, reaction) = (comment.clone(), reaction.clone());
let registration = self.commands.register(id.clone(), move |workbench, _, _, _| {
workbench.toggle_comment_reaction(controller, thread, &comment, &reaction);
crate::commands::Outcome::done()
});
self.comments.reaction_commands.push((id.clone(), registration));
actions.push(MenuAction::Command { id, title: label, enabled: true, checked: false, alt: None });
}
let context = self.key_context(window);
self.show_context_menu_actions(actions, &context, anchor, Vec::new(), window, cx);
}
}
/// `ReactionActionViewItem.getTooltip`: the count, or who reacted, with "Toggle reaction, " when it toggles.
fn reaction_tooltip(reaction: &Value, enabled: bool) -> String {
let toggle = if enabled { "Toggle reaction, " } else { "" };
let label = reaction["label"].as_str().unwrap_or_default();
let count = reaction["count"].as_u64().unwrap_or_default();
let reactors: Vec<&str> = reaction["reactors"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
if reactors.is_empty() {
return match count {
1 => format!("{toggle}1 reaction with {label}"),
_ => format!("{toggle}{count} reactions with {label}"),
};
}
if reactors.len() <= 10 && reactors.len() as u64 == count {
return format!("{toggle}{} reacted with {label}", reactors.join(", "));
}
let shown = &reactors[..reactors.len().min(10)];
format!("{toggle}{} and {} more reacted with {label}", shown.join(", "), count.saturating_sub(shown.len() as u64))
}
/// `commentBodyValue`: the text of a string or markdown body.
pub(super) fn comment_text(comment: &Value) -> String {
comment["body"].as_str().or(comment["body"]["value"].as_str()).unwrap_or_default().to_owned()
}