Visual Studio Code, rebuilt in Rust
Rust
//! commentThreadZoneWidget.ts, commentThreadWidget.ts, commentNode.ts and commentReply.ts: an expanded thread as a
//! zone below its range's last line. The frame and arrow take the thread state's color, the head shows the label
//! and the `comments/commentThread/title` actions, then each comment, then the reply form whose buttons are the
//! `comments/commentThread/context` items; each comment is drawn by comment_node.rs. The reply and edit forms are
//! code editors on a `comment` model; every thread's reply and every comment's edit has its own.
use std::collections::HashMap;
use gpui::{AnyElement, Context, MouseButton, PathBuilder, Rgba, Window, canvas, div, point, prelude::*, px};
use serde_json::{Value, json};
use super::Workbench;
use super::comment_node::{REACTIONS_ROW, comment_text};
use super::comment_thread_floating::{Floating, FloatingHost};
use super::comments::{INPUT_SCHEME, Thread};
use super::hover::{HoverContent, HoverOptions};
use super::peek_view::UI_FONT;
use crate::editor::{OpenEditor, Position, Selection, VERTICAL_SCROLLBAR_WIDTH, column_x};
use crate::menus::{MenuAction, MenuId, menu_actions};
#[cfg(test)]
mod tests;
/// `CommentThreadCollapsibleState.Expanded`.
pub(super) const EXPANDED: u64 = 1;
/// review.css `.review-comment`: 8px above and below, the 22px author line and the body's 4px top padding.
pub(super) const COMMENT_CHROME: f32 = 8. + 22. + 4. + 8.;
/// review.css `.comment-body` line-height; a body not drawn yet counts its lines at it.
pub(super) const BODY_LINE: f32 = 18.;
/// `.comment-form-container` 8px margins around the 32px "Reply..." button.
pub(super) const REPLY_BUTTON_FORM: f32 = 8. + 32. + 8.;
/// The expanded form without its comment editor: the editor's 12px padding, then the 22px small buttons in 10px
/// margins; the last margin collapses with the container's 8px.
const MIN_EDITOR_HEIGHT: f32 = 5. * 18.;
const MAX_EDITOR_HEIGHT: f32 = 25. * 18.;
pub(super) const REPLY_EDITOR_FORM: f32 = 8. + 12. + 10. + 22. + 10.;
/// `.edit-container` without its comment editor: 5px above the editor's 12px padding, then the buttons in 10px margins
/// and 10px padding; it replaces the body and its 4px padding.
pub(super) const EDIT_FORM: f32 = 5. + 12. + 10. + 10. + 22. + 10. - 4.;
/// An expanded thread shown in an editor.
pub(super) struct ThreadWidget {
pub controller: u64,
pub thread: u64,
pub model_id: u32,
pub place: Place,
}
/// `comments.thread.experimental.style`: a zone between the lines (`inline`), or a window over them (`floating`).
pub(super) enum Place {
Zone(u32),
Floating(Box<Floating>),
}
/// The reply being written in a thread (`.comment-form-container.expand`), or the text of the comment being edited.
pub(super) struct Reply {
pub controller: u64,
pub thread: u64,
/// The edited comment's `uniqueIdInThread`; None for a reply.
pub comment: Option<u64>,
/// Its editor's model, of the `comment` scheme.
pub path: std::path::PathBuf,
}
impl Workbench {
/// Every expanded thread gets a zone in each open editor of its resource, sized to its comments, or a floating
/// widget; a collapsed or gone thread loses them, and a style change replaces them.
pub(super) fn sync_comment_widgets(&mut self) {
let line_height = self.editors.viewport.line_height;
let floating = self.floating_comment_threads();
let mut wanted = Vec::new();
// `removeCommentWidgetsAndStoreCache` while commenting is off.
let controllers = if self.comments.commenting_disabled { &[][..] } else { &self.comments.controllers[..] };
for controller in controllers {
for thread in controller.threads.iter().filter(|thread| thread.zone_shown()) {
let Some(range) = thread.range.as_ref() else { continue };
let forms: Vec<(Option<u64>, f32)> = self.comments.forms.iter().filter(|form| form.controller == controller.handle && form.thread == thread.handle).map(|form| (form.comment, self.comment_editor_height(form))).collect();
for editor in self.editors.code_editors().filter(|editor| same_resource(&editor.document().uri(), &thread.resource)) {
let drawn_body = |id| self.comments.body_heights.get(&(controller.handle, thread.handle, editor.model_id, id)).copied();
let additional = self.comments.additional_heights.get(&(controller.handle, thread.handle, editor.model_id)).copied().unwrap_or_default();
let height = widget_height(thread, &forms, drawn_body, controller.reaction_handler, additional, line_height);
wanted.push((controller.handle, thread.handle, editor.model_id, arrow_position(range), height));
}
}
}
let mut kept = Vec::new();
for widget in std::mem::take(&mut self.comments.widgets) {
let Some(editor) = self.editors.code_editor_mut(widget.model_id) else { continue };
let want = wanted.iter().position(|(controller, thread, model_id, ..)| (*controller, *thread, *model_id) == (widget.controller, widget.thread, widget.model_id));
let zone_id = match widget.place {
Place::Zone(zone_id) => Some(zone_id),
Place::Floating(_) => None,
};
let (Some(index), true) = (want, zone_id.is_none() == floating) else {
if let Some(zone_id) = zone_id {
editor.remove_view_zone(zone_id);
}
continue;
};
let Some(zone_id) = zone_id else {
wanted.remove(index);
kept.push(widget);
continue;
};
let (.., anchor, height) = wanted.remove(index);
match editor.view_zones.iter_mut().find(|zone| zone.id == zone_id) {
Some(zone) => {
zone.anchor = Some(anchor);
zone.height = height;
kept.push(widget);
}
None => wanted.push((widget.controller, widget.thread, widget.model_id, anchor, height)),
}
}
for (controller, thread, model_id, anchor, height) in wanted {
if floating {
// `display(range, shouldReveal)`: a new template is revealed.
let reveal = self.comment_thread(controller, thread).is_some_and(|thread| thread.revealed);
kept.push(ThreadWidget { controller, thread, model_id, place: Place::Floating(Box::new(Floating::new(reveal))) });
continue;
}
let Some(editor) = self.editors.code_editor_mut(model_id) else { continue };
let zone_id = editor.add_view_zone(Some(anchor), height);
kept.push(ThreadWidget { controller, thread, model_id, place: Place::Zone(zone_id) });
}
self.comments.widgets = kept;
}
/// commentThreadRangeDecorator.ts on one line (zIndex 20, over the other inline decorations): the range of every
/// shown thread on `editorCommentsWidget.rangeBackground`, the thread under the pointer or with the focus once more on
/// `rangeActiveBackground`. Inline threads fill a line broken by the range to the editor's edge; floating ones end
/// with the code, and a floating thread's empty range highlights its line's text (commentThreadFloatingWidget.ts).
pub(super) fn comment_range_highlights(&self, editor: &OpenEditor, index: usize, char_width: f32, window: &Window) -> Vec<gpui::Div> {
if self.comments.commenting_disabled {
return Vec::new();
}
let floating = self.floating_comment_threads();
let focused = self.focused_comment_form().filter(|_| self.comment_editor_focused(window)).map(|form| (form.controller, form.thread));
let current = self.comments.hovered.or(focused);
let uri = editor.document().uri();
let text = &editor.document().lines[index];
let layout = editor.line_layout(index);
let (background, active) = (self.color("editorCommentsWidget.rangeBackground"), self.color("editorCommentsWidget.rangeActiveBackground"));
let mut highlights = Vec::new();
for controller in &self.comments.controllers {
for thread in controller.threads.iter().filter(|thread| thread.zone_shown() && same_resource(&uri, &thread.resource)) {
let Some(range) = thread.range.as_ref() else { continue };
let number = |key: &str| (range[key].as_u64().unwrap_or(1) as usize).max(1) - 1;
let (start, end) = (Position::new(number("startLineNumber"), number("startColumn")), Position::new(number("endLineNumber"), number("endColumn")));
let columns = match (start == end, floating) {
(false, _) => super::editor_view::selected_columns(Selection { anchor: start, head: end }, index, text),
(true, true) if index == start.line => Some((0, text.chars().count(), false)),
(true, _) => None,
};
let Some((first, last, line_break)) = columns else { continue };
let (left, right) = layout.range(first, last);
// decorations.ts gives a decoration past the rendered line 1000000px (`outsideRenderedLine`).
let right = if line_break && !floating { 1_000_000. } else { right * char_width };
let box_for = |color: Rgba| div().absolute().top_0().h_full().left(px(left * char_width)).w(px(right - left * char_width)).bg(color);
highlights.push(box_for(background));
// `updateCurrent` leaves empty ranges out.
if start != end && current == Some((controller.handle, thread.handle)) {
highlights.push(box_for(active));
}
}
}
highlights
}
/// commentThreadWidget.ts `updateCurrentThread`: the pointer over a thread's widget makes it the current thread.
pub(super) fn comment_thread_hover(&self, controller: u64, thread: u64, cx: &mut Context<Self>) -> impl Fn(&bool, &mut Window, &mut gpui::App) + 'static {
cx.listener(move |workbench, hovered: &bool, _, cx| {
let key = Some((controller, thread));
if *hovered {
workbench.comments.hovered = key;
} else if workbench.comments.hovered == key {
workbench.comments.hovered = None;
}
cx.notify();
})
}
/// `toggleExpand` from the gutter glyph: a shown zone collapses, a hidden one expands.
pub(super) fn toggle_comment_thread(&mut self, controller: u64, thread: u64, cx: &mut Context<Self>) {
let Some(thread) = self.comment_thread_mut(controller, thread) else { return };
thread.set_collapse_state(if thread.zone_shown() { 0 } else { EXPANDED });
self.sync_comment_widgets();
cx.notify();
}
pub(super) fn comment_thread_mut(&mut self, controller: u64, thread: u64) -> Option<&mut Thread> {
let controller = self.comments.controllers.iter_mut().find(|candidate| candidate.handle == controller)?;
controller.threads.iter_mut().find(|candidate| candidate.handle == thread)
}
pub(super) fn comment_thread(&self, controller: u64, thread: u64) -> Option<&Thread> {
let controller = self.comments.controllers.iter().find(|candidate| candidate.handle == controller)?;
controller.threads.iter().find(|candidate| candidate.handle == thread)
}
/// `expandReplyArea`: the reply's editor shows, focused.
pub(super) fn expand_comment_reply(&mut self, controller: u64, thread: u64, window: &mut Window, cx: &mut Context<Self>) {
self.open_comment_editor(controller, thread, None, "", window, cx);
}
/// commentReply.ts `initialize` and commentNode.ts `createCommentEditor`: a markdown model of the `comment` scheme
/// with `text` and the cursor at its end, whose code editor (simpleCommentEditor.ts) takes the focus.
pub(super) fn open_comment_editor(&mut self, controller: u64, thread: u64, comment: Option<u64>, text: &str, window: &mut Window, cx: &mut Context<Self>) {
if let Some(model_id) = self.comment_form(controller, thread, comment).and_then(|form| self.form_editor(form)).map(|editor| editor.model_id) {
self.focus_code_editor(model_id, window, cx);
return;
}
let path = match comment {
Some(id) => {
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_millis());
format!("/commentinput-{id}-{now}.md")
}
None => {
let owner = self.comments.controllers.iter().find(|candidate| candidate.handle == controller);
let state = self.comment_thread(controller, thread);
let mode = match state.filter(|state| !state.comments.is_empty()) {
Some(state) => state.thread_id.clone(),
None => {
self.comments.input_models += 1;
self.comments.input_models.to_string()
}
};
let (id, extension) = owner.map(|owner| (owner.id.as_str(), owner.extension_id.as_str())).unwrap_or_default();
format!("//{id}/{extension}/commentinput-{}-{mode}.md", crate::debug::generate_uuid())
}
};
let path = std::path::PathBuf::from(path);
let document = crate::editor::TextDocument::from_text(INPUT_SCHEME, &path, text, "utf8".into(), Some("markdown"), &self.languages, &self.settings.lock().unwrap());
let index = self.editors.open_model(document);
self.editors.models[index].move_to_document_edge(true, false);
self.comments.forms.push(Reply { controller, thread, comment, path });
self.sync_comment_widgets();
self.editors_changed(cx);
let model_id = self.editors.models[index].model_id;
self.focus_code_editor(model_id, window, cx);
}
/// A form's editor or the references peek's preview takes the focus for `model_id`, or another code editor does,
/// which blurs the form's.
pub(super) fn zone_editor_focus_moved(&mut self, model_id: u32, window: &Window, cx: &mut Context<Self>) -> bool {
let blurred = self.focused_comment_form().map(|form| (form.controller, form.thread, form.comment));
if let Some((controller, thread, comment)) = blurred
&& self.editors.zone_editor.is_some_and(|(_, id)| id != model_id)
{
self.editors.zone_editor = None;
self.comment_editor_blurred(controller, thread, comment, window, cx);
}
let form = self.comments.forms.iter().any(|form| self.form_editor(form).is_some_and(|editor| editor.model_id == model_id));
let peek = self.editors.peek_editors.iter().any(|peek| peek.editor.model_id == model_id);
let tab = self.editors.active_tab().map(|tab| tab.model_id).filter(|_| peek || form);
self.editors.zone_editor = tab.map(|tab| (tab, model_id));
tab.is_some()
}
/// The form whose editor last took the keyboard and has not lost it to another code editor.
pub(super) fn focused_comment_form(&self) -> Option<&Reply> {
let (_, model_id) = self.editors.zone_editor?;
self.comments.forms.iter().find(|form| self.form_editor(form).is_some_and(|editor| editor.model_id == model_id))
}
/// simpleCommentEditor.ts `ctxCommentEditorFocused`.
pub(super) fn comment_editor_focused(&self, window: &Window) -> bool {
self.focused_comment_form().is_some() && self.editor_focus.is_focused(window)
}
/// The focused form's editor.
pub(super) fn comment_editor(&self) -> Option<&OpenEditor> {
self.form_editor(self.focused_comment_form()?)
}
pub(super) fn comment_editor_text(&self) -> String {
self.focused_comment_form().map(|form| self.form_text(form)).unwrap_or_default()
}
/// The reply form of `thread` (`comment` None), or the edit form of its comment `comment`.
pub(super) fn comment_form(&self, controller: u64, thread: u64, comment: Option<u64>) -> Option<&Reply> {
self.comments.forms.iter().find(|form| (form.controller, form.thread, form.comment) == (controller, thread, comment))
}
pub(super) fn form_editor(&self, form: &Reply) -> Option<&OpenEditor> {
self.editors.model(INPUT_SCHEME, &form.path)
}
pub(super) fn form_text(&self, form: &Reply) -> String {
self.form_editor(form).map(|editor| editor.document().lines.join(editor.document().eol)).unwrap_or_default()
}
/// A reply or edit form closes with its editor and model (`commentEditor.dispose`).
pub(super) fn close_comment_editor(&mut self, controller: u64, thread: u64, comment: Option<u64>) -> Option<Reply> {
let index = self.comments.forms.iter().position(|form| (form.controller, form.thread, form.comment) == (controller, thread, comment))?;
let model_id = self.form_editor(&self.comments.forms[index]).map(|editor| editor.model_id);
if model_id.is_some() && self.editors.zone_editor.map(|(_, id)| id) == model_id {
self.editors.zone_editor = None;
}
let form = self.comments.forms.remove(index);
self.editors.models.retain(|model| !model.document().is(INPUT_SCHEME, &form.path));
if let Some(model_id) = model_id {
self.drop_code_editor(model_id);
}
Some(form)
}
/// commentReply.ts `onDidBlurEditorWidget`: an empty reply to a thread with comments goes back to its button.
/// GPUI reports a window deactivation as a blur; the DOM keeps the focus there.
fn comment_editor_blurred(&mut self, controller: u64, thread: u64, comment: Option<u64>, window: &Window, cx: &mut Context<Self>) {
let Some(form) = self.comment_form(controller, thread, comment) else { return };
let is_reply = self.comment_thread(controller, thread).is_some_and(|thread| !thread.comments.is_empty());
if window.is_window_active() && comment.is_none() && self.form_text(form).is_empty() && is_reply {
self.close_comment_editor(controller, thread, comment);
self.sync_comment_widgets();
self.editors_changed(cx);
}
}
/// The focused form's editor loses the keyboard to another part of the window.
pub fn watch_comment_reply_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let focus = self.editor_focus.clone();
cx.on_blur(&focus, window, |workbench, window, cx| {
if let Some((controller, thread, comment)) = workbench.focused_comment_form().map(|form| (form.controller, form.thread, form.comment)) {
workbench.comment_editor_blurred(controller, thread, comment, window, cx);
cx.notify();
}
})
.detach();
}
/// `hideReplyArea`: the form's text is dropped and the reply button shows again.
pub(super) fn hide_comment_reply(&mut self, controller: u64, thread: u64, comment: Option<u64>, window: &mut Window, cx: &mut Context<Self>) {
if self.close_comment_editor(controller, thread, comment).is_none() {
return;
}
// commentThreadZoneWidget.ts `collapse`: a thread without comments is deleted.
if self.comment_thread(controller, thread).is_some_and(|thread| thread.comments.is_empty()) {
self.delete_comment_thread(controller, thread, cx);
}
self.sync_comment_widgets();
self.editors_changed(cx);
window.focus(&self.editor_focus, cx);
cx.notify();
}
/// The context the thread's menus see: `commentController`, `commentThread`, `commentThreadIsEmpty` and, in the
/// reply form, `commentIsEmpty`.
pub(super) fn comment_thread_context(&self, controller: u64, thread: &Thread, window: &Window) -> HashMap<String, Value> {
let mut context = self.key_context(window);
let reply = self.comment_form(controller, thread.handle, None);
context.insert("commentIsEmpty".into(), json!(reply.is_none_or(|form| self.form_text(form).is_empty())));
let controller = self.comments.controllers.iter().find(|candidate| candidate.handle == controller);
if let Some(value) = controller.and_then(|controller| controller.context_value.as_ref()) {
context.insert("commentController".into(), json!(value));
}
if let Some(value) = &thread.context_value {
context.insert("commentThread".into(), json!(value));
}
context.insert("commentThreadIsEmpty".into(), json!(thread.comments.is_empty()));
context
}
/// `CommentFormActions` run: the command gets the `CommentReply` (`MarshalledId.CommentThreadReply`, 9) with the
/// thread (`MarshalledId.CommentThread`, 7) and the typed text, then the form hides.
fn run_comment_reply_action(&mut self, id: &str, controller: u64, thread: u64, window: &mut Window, cx: &mut Context<Self>) {
let text = self.comment_form(controller, thread, None).map(|form| self.form_text(form)).unwrap_or_default();
let marshalled = json!({ "$mid": 7, "commentControlHandle": controller, "commentThreadHandle": thread });
let argument = json!({ "thread": marshalled, "text": text, "$mid": 9 });
self.run_code_lens_command(id, vec![argument], window, cx);
self.hide_comment_reply(controller, thread, None, window, cx);
}
/// `editor.action.submitComment` (Cmd+Enter in the reply's editor): a typed reply runs the first form action.
pub(super) fn submit_comment_reply(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some((controller, thread)) = self.focused_comment_form().filter(|form| form.comment.is_none()).map(|form| (form.controller, form.thread)) else { return };
if self.comment_editor_text().is_empty() {
return;
}
let Some(state) = self.comment_thread(controller, thread) else { return };
let context = self.comment_thread_context(controller, state, window);
let first = menu_actions(&self.menus, MenuId::CommentThreadActions, &context).into_iter().find_map(|action| match action {
MenuAction::Command { id, enabled: true, .. } => Some(id),
_ => None,
});
if let Some(id) = first {
self.run_comment_reply_action(&id, controller, thread, window, cx);
}
}
pub(super) fn comment_thread_widgets(&self, editor: &OpenEditor, content_left: f32, char_width: f32, window: &mut Window, cx: &mut Context<Self>) -> Vec<AnyElement> {
let widgets = self.comments.widgets.iter().filter(|widget| widget.model_id == editor.model_id);
let viewport = self.editors.viewport;
let width = content_left + viewport.width - VERTICAL_SCROLLBAR_WIDTH;
let mut elements = Vec::new();
for widget in widgets {
let Place::Zone(zone_id) = widget.place else { continue };
let Some(top) = editor.view_zone_top(zone_id, viewport) else { continue };
elements.extend(self.comment_thread_zone(widget, editor, top - editor.scroll.top, width, content_left, char_width, window, cx));
}
// A multi diff file side's floating widgets are laid out in the list (`multi_diff_floating_hosts`).
if self.editors.multi_diff_side(editor.model_id).is_none() {
elements.extend(self.floating_comment_widgets(&FloatingHost::of(editor, viewport), content_left, window, cx));
}
elements
}
/// The zone widget of `widget` at `top` in its editor's view, `width` wide.
pub(super) fn comment_thread_zone(&self, widget: &ThreadWidget, editor: &OpenEditor, top: f32, width: f32, content_left: f32, char_width: f32, window: &mut Window, cx: &mut Context<Self>) -> Option<AnyElement> {
let Place::Zone(zone_id) = widget.place else { return None };
let thread = self.comment_thread(widget.controller, widget.thread)?;
let zone = editor.view_zone(zone_id)?;
let line_height = self.editors.viewport.line_height;
let arrow_height = (line_height / 3.).round();
let frame_width = (line_height / 9.).round();
let state_color = self.comment_thread_state_color(thread);
let state_styled = thread.state_styled_in.contains(&editor.model_id);
let anchor = zone.anchor?;
let line = &editor.document().lines[anchor.line];
// zoneWidget.ts `show`: the arrow is not pretty at column 1 and moves to column 2.
let arrow_column = anchor.column.max(1).min(line.chars().count().max(1));
let arrow_x = content_left + column_x(line, arrow_column, editor.document().indentation.tab_size) * char_width - editor.scroll.left;
let arrow = canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let (x, y) = (bounds.origin.x, bounds.origin.y);
let mut path = PathBuilder::fill();
path.move_to(point(x, y + px(arrow_height)));
path.line_to(point(x + px(2. * arrow_height), y + px(arrow_height)));
path.line_to(point(x + px(arrow_height), y));
path.close();
if let Ok(path) = path.build() {
window.paint_path(path, state_color);
}
},
)
.absolute()
.top_0()
.left(px(arrow_x - arrow_height))
.w(px(2. * arrow_height))
.h(px(arrow_height));
let head_height = (line_height * 1.2).ceil();
let body = self.comment_thread_body(widget, thread, window, cx);
let container = div()
.absolute()
.top(px(arrow_height))
.left_0()
.right_0()
.border_t(px(frame_width))
.border_b(px(frame_width))
.border_color(state_color)
.bg(self.color("peekViewResult.background"))
.child(self.comment_thread_head(widget, thread, head_height, state_styled.then_some(state_color), false, window, cx))
.child(div().when(state_styled, |body| body.border_t_1().border_color(state_color)).child(body));
let element = div()
.id(gpui::SharedString::from(format!("comment-thread-{}-{}", widget.controller, widget.thread)))
.absolute()
.left_0()
.top(px(top))
.w(px(width))
.h(px(zone.height))
.on_hover(self.comment_thread_hover(widget.controller, widget.thread, cx))
.cursor_default()
.occlude()
.font_family(UI_FONT)
.text_size(px(13.))
.text_color(self.foreground_or("foreground"))
.child(container)
.child(arrow);
Some(element.into_any_element())
}
/// commentColors.ts `getCommentThreadWidgetStateColor`.
pub(super) fn comment_thread_state_color(&self, thread: &Thread) -> Rgba {
match thread.state {
Some(0) => self.color("editorCommentsWidget.unresolvedBorder"),
Some(1) => self.color("editorCommentsWidget.resolvedBorder"),
_ => self.color("editorCommentsWidget.rangeBorder"),
}
}
/// `CommentThreadHeader`: the label ("Start discussion" for a thread without comments), the title actions and
/// Collapse (Delete for a thread without comments; a floating widget's `collapseAction` is Close), on
/// `state_color` at 10% when given.
pub(super) fn comment_thread_head(&self, widget: &ThreadWidget, thread: &Thread, height: f32, state_color: Option<Rgba>, floating: bool, window: &Window, cx: &mut Context<Self>) -> AnyElement {
let label = match (&thread.label, thread.comments.is_empty()) {
(Some(label), _) => label.clone(),
(None, true) => "Start discussion".to_owned(),
(None, false) => String::new(),
};
let icon_color = self.foreground_or("icon.foreground");
let (controller, thread_handle) = (widget.controller, widget.thread);
let context = self.comment_thread_context(controller, thread, window);
let mut actions = Vec::new();
for action in menu_actions(&self.menus, MenuId::CommentThreadTitle, &context) {
let MenuAction::Command { id, title, enabled: true, .. } = action else { continue };
let marshalled = json!({ "$mid": 7, "commentControlHandle": controller, "commentThreadHandle": thread_handle });
actions.push(self.command_button(&id, title, vec![marshalled], icon_color, cx).ml(px(4.)).into_any_element());
}
let empty = thread.comments.is_empty();
let (collapse_icon, collapse_title) = match (empty, floating) {
(true, false) => ("trash", "Delete"),
(true, true) => ("trash", "Close"),
(false, false) => ("chevron-up", "Collapse"),
(false, true) => ("close", "Close"),
};
let collapse = self
.icon(collapse_icon, 22., 16., icon_color)
.id("comment-thread-collapse")
.ml(px(4.))
.rounded(px(4.))
.cursor_pointer()
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
.child(self.hover_target("comment-thread-collapse-hover", HoverContent::Text(collapse_title.into()), HoverOptions::mouse()))
.on_click(cx.listener(move |workbench, _, _, cx| match empty {
true => workbench.delete_comment_thread(controller, thread_handle, cx),
false => workbench.toggle_comment_thread(controller, thread_handle, cx),
}));
actions.push(collapse.into_any_element());
div()
.h(px(height))
.line_height(px(height))
.flex()
.items_center()
.when_some(state_color, |head, color| head.bg(Rgba { a: color.a * 0.1, ..color }))
.debug_selector(|| "comment-thread-head".into())
.on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &gpui::MouseDownEvent, window, cx| {
cx.stop_propagation();
workbench.show_comment_thread_title_context_menu(controller, thread_handle, event.position, window, cx);
}))
.child(div().ml(px(20.)).flex_1().min_w_0().overflow_hidden().text_ellipsis().whitespace_nowrap().child(label))
// The actions take their own clicks: a floating widget's title drags from everywhere else.
.child(div().flex_none().flex().items_center().pr(px(2.)).children(actions).on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()))
.into_any_element()
}
/// commentThreadHeader.ts `onContextMenu`: the `comments/commentThread/title/context` actions without their
/// groups' separators, run with the thread; nothing without actions.
fn show_comment_thread_title_context_menu(&mut self, controller: u64, thread_handle: u64, position: gpui::Point<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
let Some(thread) = self.comment_thread(controller, thread_handle) else { return };
let context = self.comment_thread_context(controller, thread, window);
let actions: Vec<_> = menu_actions(&self.menus, MenuId::CommentThreadTitleContext, &context).into_iter().filter(|action| !matches!(action, MenuAction::Separator)).collect();
if actions.is_empty() {
return;
}
let marshalled = json!({ "$mid": 7, "commentControlHandle": controller, "commentThreadHandle": thread_handle });
self.show_context_menu_actions(actions, &context, gpui::Bounds::new(position, Default::default()), vec![marshalled], window, cx);
}
/// `CommentThreadBody` and the reply form.
fn comment_thread_body(&self, widget: &ThreadWidget, thread: &Thread, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
let mut comments = div().relative().flex().flex_col();
for index in 0..thread.comments.len() {
comments = comments.child(self.comment_node(widget, thread, index, window, cx));
}
let mut body = div().flex().flex_col().child(self.focusable_comments(widget, thread.comments.len(), comments, window, cx));
if thread.can_reply != false {
body = body.child(self.comment_reply_form(widget, thread, window, cx));
}
body.children(self.comment_thread_additional_actions(widget, thread, window, cx)).into_any_element()
}
/// commentThreadBody.ts `.comments-container`: the comments of the focused thread in the active editor carry the
/// thread focus, outlined while no comment is singled out; Up and Down move between the comments (`_setFocusedComment`).
pub(super) fn focusable_comments(&self, widget: &ThreadWidget, count: usize, comments: gpui::Div, window: &Window, cx: &mut Context<Self>) -> gpui::Div {
let Some((controller, thread, comment)) = self.comments.focused_thread else { return comments };
let active = self.editors.active().is_some_and(|editor| editor.model_id == widget.model_id);
if (controller, thread) != (widget.controller, widget.thread) || !active || self.editor_groups.drawing_inactive {
return comments;
}
let outlined = comment.is_none() && self.comments.thread_focus.is_focused(window);
comments
.track_focus(&self.comments.thread_focus)
.on_key_down(cx.listener(move |workbench, event: &gpui::KeyDownEvent, _, cx| {
let step: isize = match (event.keystroke.key.as_str(), event.keystroke.modifiers.modified()) {
("up", false) => -1,
("down", false) => 1,
_ => return,
};
let Some(focused) = workbench.comments.focused_thread.as_mut().filter(|_| count > 0) else { return };
cx.stop_propagation();
focused.2 = Some(match focused.2 {
None if step > 0 => 0,
None => count - 1,
Some(index) => index.saturating_add_signed(step).min(count - 1),
});
cx.notify();
}))
.when(outlined, |comments| comments.child(self.focus_outline()))
}
/// `CommentReply`: the "Reply..." button, or the input with the `comments/commentThread/context` buttons, the
/// first one primary.
pub(super) fn comment_reply_form(&self, widget: &ThreadWidget, thread: &Thread, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
let (controller, thread_handle) = (widget.controller, widget.thread);
let reply = self.comment_form(controller, thread_handle, None);
let replying = reply.is_some();
let prompt = if thread.comments.is_empty() { "Type a new comment" } else { "Reply..." };
let form = div().mx(px(20.)).mt(px(8.)).when(!replying, |form| form.mb(px(8.)));
if !replying {
// review.css: `outline-color: var(--vscode-contrastBorder)`, which falls back to the text color without one.
let outline = self.theme.color("contrastBorder").unwrap_or(self.foreground_or("editor.foreground"));
let button = div()
.id("comment-reply-button")
.h(px(32.))
.border_1()
.border_color(outline)
.px(px(12.))
.flex()
.items_center()
.font_family("Menlo")
// review.css asks 600; the reference draws Menlo, which has no semibold, at its regular weight.
.font_weight(gpui::FontWeight::MEDIUM)
.whitespace_nowrap()
.bg(self.color("editorCommentsWidget.replyInputBackground"))
.text_color(self.foreground_or("editor.foreground"))
.cursor_text()
.on_click(cx.listener(move |workbench, _, window, cx| workbench.expand_comment_reply(controller, thread_handle, window, cx)))
.child(prompt);
return form.child(button).into_any_element();
}
let input = self.comment_editor_box(reply, Some(prompt), window, cx);
let context = self.comment_thread_context(controller, thread, window);
let mut buttons = Vec::new();
for (index, action) in menu_actions(&self.menus, MenuId::CommentThreadActions, &context).into_iter().enumerate() {
let MenuAction::Command { id, title, enabled, .. } = action else { continue };
let key = format!("comment-reply-action-{id}");
buttons.push(self.comment_form_button(key, title, enabled, index == 0, move |workbench, window, cx| workbench.run_comment_reply_action(&id, controller, thread_handle, window, cx), cx));
}
let editor_actions = self.comment_editor_actions(&context, controller, thread_handle, None, cx);
form.child(input).child(div().my(px(10.)).flex().flex_row_reverse().children(buttons.into_iter().rev()).children(editor_actions)).into_any_element()
}
/// commentThreadAdditionalActions.ts: a separator and the `comments/commentThread/additionalActions` buttons under
/// the body, every one secondary, a submenu as a `ButtonWithDropdown` running its first action; None while no
/// action is enabled. A zone records its height, which sizes it (the reference observes the DOM).
pub(super) fn comment_thread_additional_actions(&self, widget: &ThreadWidget, thread: &Thread, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
let context = self.comment_thread_context(widget.controller, thread, window);
let actions = additional_actions(menu_actions(&self.menus, MenuId::CommentThreadAdditionalActions, &context));
let key = (widget.controller, widget.thread, widget.model_id);
let height = if actions.is_empty() { 0. } else { additional_actions_height(thread, self.comment_form(widget.controller, widget.thread, None).is_some()) };
if matches!(widget.place, Place::Zone(_)) && self.comments.additional_heights.get(&key).copied().unwrap_or_default() != height {
let entity = cx.entity().downgrade();
cx.defer(move |cx| {
let _ = entity.update(cx, |workbench, cx| {
workbench.comments.additional_heights.insert(key, height);
workbench.sync_comment_widgets();
cx.notify();
});
});
}
if actions.is_empty() {
return None;
}
let marshalled = json!({ "$mid": 7, "commentControlHandle": widget.controller, "commentThreadHandle": widget.thread });
let argument = json!({ "thread": marshalled, "$mid": 8 });
let mut buttons = Vec::new();
for action in actions {
match action {
MenuAction::Command { id, title, enabled, .. } => {
let args = vec![argument.clone()];
let button = self.comment_form_button(format!("comment-additional-action-{id}"), title, enabled, false, move |workbench, window, cx| workbench.run_code_lens_command(&id, args.clone(), window, cx), cx);
buttons.push(button.ml(px(0.)).mr(px(10.)).into_any_element());
}
MenuAction::Submenu { actions, .. } => buttons.extend(self.comment_button_with_dropdown(actions, &context, argument.clone(), cx)),
MenuAction::Separator => {}
}
}
let bar = div()
.debug_selector(|| "comment-additional-actions".into())
.mx(px(20.))
.pt(px(height - (1. + 14. + 22. + 10.)))
.pb(px(10.))
.child(div().h(px(1.)).bg(self.color("menu.separatorBackground")))
.child(div().mt(px(14.)).flex().whitespace_nowrap().children(buttons));
Some(bar.into_any_element())
}
/// button.ts `ButtonWithDropdown` in the secondary colors: the submenu's first action as a small text button, a
/// separator, and a chevron that opens all its actions below it.
fn comment_button_with_dropdown(&self, actions: Vec<MenuAction>, context: &HashMap<String, Value>, argument: Value, cx: &mut Context<Self>) -> Option<AnyElement> {
let Some(MenuAction::Command { id, title, enabled, .. }) = actions.first().cloned() else { return None };
let args = vec![argument.clone()];
let primary = self
.comment_form_button(format!("comment-additional-action-{id}"), title, enabled, false, move |workbench, window, cx| workbench.run_code_lens_command(&id, args.clone(), window, cx), cx)
.ml(px(0.))
.rounded_r(px(0.))
.border_r_0();
let border = self.theme.color("button.secondaryBorder").or(self.theme.color("button.border"));
let separator = div()
.py(px(4.))
.bg(self.color("button.secondaryBackground"))
.when_some(border, |separator, border| separator.border_t_1().border_b_1().border_color(border))
.child(div().w(px(1.)).h_full().bg(self.color("button.separator")));
let bounds = std::rc::Rc::new(std::cell::Cell::new(gpui::Bounds::default()));
let measured = bounds.clone();
let context = context.clone();
let dropdown = div()
.id("comment-additional-dropdown")
.debug_selector(|| "comment-additional-dropdown".into())
.relative()
.px(px(4.))
.flex()
.items_center()
.rounded_r(px(4.))
.bg(self.color("button.secondaryBackground"))
.when_some(border, |button, border| button.border_1().border_l_0().border_color(border))
.cursor_pointer()
.hover(|button| button.bg(self.color("button.secondaryHoverBackground")))
.child(self.icon("drop-down-button", 16., 16., self.color("button.secondaryForeground")))
.child(self.hover_target("comment-additional-dropdown-hover", HoverContent::Text("More Actions...".into()), HoverOptions::mouse()))
.child(canvas(move |element, _, _| measured.set(element), |_, _, _, _| ()).absolute().inset_0())
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |workbench, _, window, cx| workbench.show_context_menu_actions(actions.clone(), &context, bounds.get(), vec![argument.clone()], window, cx)));
Some(div().flex().mr(px(10.)).child(primary).child(separator).child(dropdown).into_any_element())
}
/// commentFormActions.ts: a `small` text button (button.css `.monaco-text-button.small`) in the primary or the
/// secondary button colors with button.ts's 1px border when the theme has one, at 0.4 opacity while disabled.
pub(super) fn comment_form_button(&self, key: String, title: String, enabled: bool, primary: bool, on_click: impl Fn(&mut Self, &mut Window, &mut Context<Self>) + 'static, cx: &mut Context<Self>) -> gpui::Stateful<gpui::Div> {
let (background, foreground, hover, border) = match primary {
true => ("button.background", "button.foreground", "button.hoverBackground", "button.border"),
false => ("button.secondaryBackground", "button.secondaryForeground", "button.secondaryHoverBackground", "button.secondaryBorder"),
};
div()
.id(gpui::SharedString::from(key.clone()))
.debug_selector(|| key)
.h(px(22.))
.ml(px(5.))
.px(px(6.))
.text_size(px(11.))
.line_height(px(14.))
.flex()
.items_center()
.rounded(px(4.))
.bg(self.color(background))
.text_color(self.color(foreground))
.when_some(self.theme.color(border), |button, border| button.border_1().border_color(border))
.when(!enabled, |button| button.opacity(0.4))
.when(enabled, |button| {
button
.cursor_pointer()
.hover(|button| button.bg(self.color(hover)))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |workbench, _, window, cx| on_click(workbench, window, cx)))
})
.child(title)
}
/// `createCommentWidgetEditorActions`: the `comments/comment/editorActions` buttons, all secondary, floated right
/// after the form's own actions so they sit left of them, the first rightmost; `comment` is the edited comment.
pub(super) fn comment_editor_actions(&self, context: &HashMap<String, Value>, controller: u64, thread: u64, comment: Option<u64>, cx: &mut Context<Self>) -> Vec<gpui::Stateful<gpui::Div>> {
let mut buttons = Vec::new();
for action in menu_actions(&self.menus, MenuId::CommentEditorActions, context) {
let MenuAction::Command { id, title, enabled, .. } = action else { continue };
let key = match comment {
Some(comment) => format!("comment-edit-editor-action-{comment}-{id}"),
None => format!("comment-reply-editor-action-{id}"),
};
buttons.push(self.comment_form_button(key, title, enabled, false, move |workbench, window, cx| workbench.run_comment_editor_action(&id, controller, thread, comment, window, cx), cx));
}
buttons
}
/// The editor actions' run: the command gets the reply (`MarshalledId.CommentThreadReply`, 9) or the edited
/// comment (`CommentThreadNode`, 11) with the typed text; the form stays open and its editor takes the focus.
fn run_comment_editor_action(&mut self, id: &str, controller: u64, thread: u64, comment: Option<u64>, window: &mut Window, cx: &mut Context<Self>) {
let Some(form) = self.comment_form(controller, thread, comment) else { return };
let text = self.form_text(form);
let model_id = self.form_editor(form).map(|editor| editor.model_id);
let marshalled = json!({ "$mid": 7, "commentControlHandle": controller, "commentThreadHandle": thread });
let argument = match comment {
Some(comment) => json!({ "thread": marshalled, "commentUniqueId": comment, "text": text, "$mid": 11 }),
None => json!({ "thread": marshalled, "text": text, "$mid": 9 }),
};
self.run_code_lens_command(id, vec![argument], window, cx);
if let Some(model_id) = model_id {
self.focus_code_editor(model_id, window, cx);
}
}
/// review.css `.comment-form .monaco-editor`: the reply or edit editor, 90px in 6px and 12px padding on
/// `editorCommentsWidget.replyInputBackground`, outlined in `focusBorder` while it has the keyboard; an empty one
/// shows `placeholder` (placeholderTextContribution.ts).
/// simpleCommentEditor.ts `calculateEditorHeight`: the comment editor's lines, 5 to 25 of 18px and 90px less than
/// the editor it is in.
pub(super) fn comment_editor_height(&self, form: &Reply) -> f32 {
let Some(editor) = self.form_editor(form) else { return MIN_EDITOR_HEIGHT };
let parent = self.pane_editor_viewport();
let content = editor.view_line_count() as f32 * parent.line_height;
let max = (parent.height - 90.).clamp(MIN_EDITOR_HEIGHT, MAX_EDITOR_HEIGHT);
content.clamp(MIN_EDITOR_HEIGHT, max)
}
pub(super) fn comment_editor_box(&self, form: Option<&Reply>, placeholder: Option<&str>, window: &mut Window, cx: &mut Context<Self>) -> gpui::Div {
let editor = form.and_then(|form| self.form_editor(form));
let focused = editor.is_some_and(|editor| self.editors.zone_editor.is_some_and(|(_, id)| id == editor.model_id)) && self.editor_focus.is_focused(window);
let outline = if focused { self.color("focusBorder") } else { self.theme.color("contrastBorder").unwrap_or(self.foreground_or("editor.foreground")) };
let input = div()
.h(px(form.map_or(MIN_EDITOR_HEIGHT, |form| self.comment_editor_height(form)) + 12.))
.pl(px(12.))
// review.css draws a 1px outline outside the 6px padding; this border sits inside, so the bottom gives it back.
.pt(px(6.))
.pb(px(4.))
.rounded(px(3.))
.border_1()
.border_color(outline)
.bg(self.color("editorCommentsWidget.replyInputBackground"))
.relative()
.flex()
// The editor keeps its press; the zone would blur it.
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation());
let Some(editor) = editor else { return input };
let empty = matches!(editor.document().lines.as_slice(), [line] if line.is_empty());
let placeholder = placeholder.filter(|_| empty).map(|text| {
let metrics = self.editor_metrics(editor, window);
div()
.absolute()
.top(px(6.))
.left(px(12. + metrics.content_left()))
.whitespace_nowrap()
.font_family(super::editor_view::EDITOR_FONT)
.text_size(px(metrics.font_size))
.line_height(px(metrics.line_height))
.text_color(self.color("editor.placeholder.foreground"))
.child(text.to_owned())
});
input.child(self.embedded_code_editor(editor, window, cx)).children(placeholder)
}
}
/// `arrowPosition`: the end line, at the range's middle for a one-line range, else at its start.
fn arrow_position(range: &Value) -> Position {
let number = |key: &str| range[key].as_u64().unwrap_or(1) as usize;
let end_line = number("endLineNumber");
let column = if end_line == number("startLineNumber") { (number("startColumn") + number("endColumn") + 1) / 2 } else { 1 };
Position::new(end_line.max(1) - 1, column - 1)
}
/// `CommentFormActions.setActions` with `maxActions` 4 and dropdowns, and `_enableDisableMenu`: the commands and
/// submenus up to 4, none while neither one nor a submenu's action is enabled.
pub(super) fn additional_actions(actions: Vec<MenuAction>) -> Vec<MenuAction> {
let enabled = |action: &MenuAction| matches!(action, MenuAction::Command { enabled: true, .. });
let shown = actions.iter().any(|action| match action {
MenuAction::Submenu { actions, .. } => actions.iter().any(enabled),
action => enabled(action),
});
if !shown {
return Vec::new();
}
actions.into_iter().filter(|action| !matches!(action, MenuAction::Separator)).take(4).collect()
}
/// review.css `.comment-additional-actions`: its 10px top margin and the separator's collapse with the reply form's
/// bottom margin (8px under the "Reply..." button, 10px under the form's buttons); then the 1px separator, 14px, the
/// 22px small buttons and the 10px bottom margin.
pub(super) fn additional_actions_height(thread: &Thread, replying: bool) -> f32 {
let gap = match (thread.can_reply != false, replying) {
(false, _) => 10.,
(true, false) => 2.,
(true, true) => 0.,
};
gap + 1. + 14. + 22. + 10.
}
/// `_refresh`: the head (1.2 lines), the comments and the form, the arrow, the frame and 8px, in whole lines.
/// `forms` are the thread's open forms with their editor heights: None the reply, Some(id) the edit of comment `id`;
/// `drawn_body` the drawn height of comment `id`'s body (the reference measures the DOM). With a reaction handler
/// every comment has a reactions row, for the picker. `additional` is the additional actions' height.
fn widget_height(thread: &Thread, forms: &[(Option<u64>, f32)], drawn_body: impl Fn(u64) -> Option<f32>, reaction_handler: bool, additional: f32, line_height: f32) -> f32 {
let form_height = |comment: Option<u64>| forms.iter().find(|(id, _)| *id == comment).map(|(_, height)| *height);
let mut body = 1.;
for comment in &thread.comments {
let lines = comment_text(comment).lines().filter(|line| !line.trim().is_empty()).count().max(1);
let id = comment["uniqueIdInThread"].as_u64();
body += COMMENT_CHROME + match id.and_then(|id| form_height(Some(id))) {
Some(input_height) => EDIT_FORM + input_height,
None => id.and_then(&drawn_body).unwrap_or(lines as f32 * BODY_LINE),
};
if reaction_handler || comment["commentReactions"].as_array().into_iter().flatten().any(|reaction| reaction["count"].as_u64().unwrap_or_default() > 0) {
body += REACTIONS_ROW;
}
}
if thread.can_reply != false {
body += form_height(None).map_or(REPLY_BUTTON_FORM, |input_height| REPLY_EDITOR_FORM + input_height);
}
body += additional;
let head = (line_height * 1.2).ceil();
let arrow = (line_height / 3.).round();
let frame = (line_height / 9.).round() * 2.;
((head + body + arrow + frame + 8.) / line_height).ceil() * line_height
}
fn same_resource(uri: &Value, resource: &Value) -> bool {
uri["path"] == resource["path"] && uri["scheme"] == resource["scheme"]
}