1use std::cell::RefCell;
2use std::{cell::Cell, cmp::Reverse, ops::Range, rc::Rc};
3
4use fuzzy::{StringMatch, StringMatchCandidate};
5use gpui::{
6 div, px, uniform_list, AnyElement, BackgroundExecutor, Div, FontWeight, ListSizingBehavior,
7 Model, MouseButton, Pixels, ScrollStrategy, SharedString, StrikethroughStyle, StyledText,
8 UniformListScrollHandle, ViewContext, WeakView,
9};
10use language::Buffer;
11use language::{CodeLabel, Documentation};
12use lsp::LanguageServerId;
13use multi_buffer::{Anchor, ExcerptId};
14use ordered_float::OrderedFloat;
15use project::{CodeAction, Completion, TaskSourceKind};
16use task::ResolvedTask;
17use ui::{
18 h_flex, ActiveTheme as _, Color, FluentBuilder as _, InteractiveElement as _, IntoElement,
19 Label, LabelCommon as _, LabelSize, ListItem, ParentElement as _, Popover,
20 StatefulInteractiveElement as _, Styled, StyledExt as _, Toggleable as _,
21};
22use util::ResultExt as _;
23use workspace::Workspace;
24
25use crate::{
26 actions::{ConfirmCodeAction, ConfirmCompletion},
27 display_map::DisplayPoint,
28 render_parsed_markdown, split_words, styled_runs_for_code_label, CodeActionProvider,
29 CompletionId, CompletionProvider, DisplayRow, Editor, EditorStyle, ResolvedTasks,
30};
31
32pub enum CodeContextMenu {
33 Completions(CompletionsMenu),
34 CodeActions(CodeActionsMenu),
35}
36
37impl CodeContextMenu {
38 pub fn select_first(
39 &mut self,
40 provider: Option<&dyn CompletionProvider>,
41 cx: &mut ViewContext<Editor>,
42 ) -> bool {
43 if self.visible() {
44 match self {
45 CodeContextMenu::Completions(menu) => menu.select_first(provider, cx),
46 CodeContextMenu::CodeActions(menu) => menu.select_first(cx),
47 }
48 true
49 } else {
50 false
51 }
52 }
53
54 pub fn select_prev(
55 &mut self,
56 provider: Option<&dyn CompletionProvider>,
57 cx: &mut ViewContext<Editor>,
58 ) -> bool {
59 if self.visible() {
60 match self {
61 CodeContextMenu::Completions(menu) => menu.select_prev(provider, cx),
62 CodeContextMenu::CodeActions(menu) => menu.select_prev(cx),
63 }
64 true
65 } else {
66 false
67 }
68 }
69
70 pub fn select_next(
71 &mut self,
72 provider: Option<&dyn CompletionProvider>,
73 cx: &mut ViewContext<Editor>,
74 ) -> bool {
75 if self.visible() {
76 match self {
77 CodeContextMenu::Completions(menu) => menu.select_next(provider, cx),
78 CodeContextMenu::CodeActions(menu) => menu.select_next(cx),
79 }
80 true
81 } else {
82 false
83 }
84 }
85
86 pub fn select_last(
87 &mut self,
88 provider: Option<&dyn CompletionProvider>,
89 cx: &mut ViewContext<Editor>,
90 ) -> bool {
91 if self.visible() {
92 match self {
93 CodeContextMenu::Completions(menu) => menu.select_last(provider, cx),
94 CodeContextMenu::CodeActions(menu) => menu.select_last(cx),
95 }
96 true
97 } else {
98 false
99 }
100 }
101
102 pub fn visible(&self) -> bool {
103 match self {
104 CodeContextMenu::Completions(menu) => menu.visible(),
105 CodeContextMenu::CodeActions(menu) => menu.visible(),
106 }
107 }
108
109 pub fn render(
110 &self,
111 cursor_position: DisplayPoint,
112 style: &EditorStyle,
113 max_height: Pixels,
114 workspace: Option<WeakView<Workspace>>,
115 cx: &mut ViewContext<Editor>,
116 ) -> (ContextMenuOrigin, AnyElement) {
117 match self {
118 CodeContextMenu::Completions(menu) => (
119 ContextMenuOrigin::EditorPoint(cursor_position),
120 menu.render(style, max_height, workspace, cx),
121 ),
122 CodeContextMenu::CodeActions(menu) => {
123 menu.render(cursor_position, style, max_height, cx)
124 }
125 }
126 }
127}
128
129pub enum ContextMenuOrigin {
130 EditorPoint(DisplayPoint),
131 GutterIndicator(DisplayRow),
132}
133
134#[derive(Clone, Debug)]
135pub struct CompletionsMenu {
136 pub id: CompletionId,
137 sort_completions: bool,
138 pub initial_position: Anchor,
139 pub buffer: Model<Buffer>,
140 pub completions: Rc<RefCell<Box<[Completion]>>>,
141 match_candidates: Rc<[StringMatchCandidate]>,
142 pub matches: Rc<[StringMatch]>,
143 pub selected_item: usize,
144 scroll_handle: UniformListScrollHandle,
145 resolve_completions: bool,
146 pub aside_was_displayed: Cell<bool>,
147 show_completion_documentation: bool,
148}
149
150impl CompletionsMenu {
151 pub fn new(
152 id: CompletionId,
153 sort_completions: bool,
154 show_completion_documentation: bool,
155 initial_position: Anchor,
156 buffer: Model<Buffer>,
157 completions: Box<[Completion]>,
158 aside_was_displayed: bool,
159 ) -> Self {
160 let match_candidates = completions
161 .iter()
162 .enumerate()
163 .map(|(id, completion)| StringMatchCandidate::new(id, &completion.label.filter_text()))
164 .collect();
165
166 Self {
167 id,
168 sort_completions,
169 initial_position,
170 buffer,
171 show_completion_documentation,
172 completions: RefCell::new(completions).into(),
173 match_candidates,
174 matches: Vec::new().into(),
175 selected_item: 0,
176 scroll_handle: UniformListScrollHandle::new(),
177 resolve_completions: true,
178 aside_was_displayed: Cell::new(aside_was_displayed),
179 }
180 }
181
182 pub fn new_snippet_choices(
183 id: CompletionId,
184 sort_completions: bool,
185 choices: &Vec<String>,
186 selection: Range<Anchor>,
187 buffer: Model<Buffer>,
188 ) -> Self {
189 let completions = choices
190 .iter()
191 .map(|choice| Completion {
192 old_range: selection.start.text_anchor..selection.end.text_anchor,
193 new_text: choice.to_string(),
194 label: CodeLabel {
195 text: choice.to_string(),
196 runs: Default::default(),
197 filter_range: Default::default(),
198 },
199 server_id: LanguageServerId(usize::MAX),
200 documentation: None,
201 lsp_completion: Default::default(),
202 confirm: None,
203 })
204 .collect();
205
206 let match_candidates = choices
207 .iter()
208 .enumerate()
209 .map(|(id, completion)| StringMatchCandidate::new(id, &completion))
210 .collect();
211 let matches = choices
212 .iter()
213 .enumerate()
214 .map(|(id, completion)| StringMatch {
215 candidate_id: id,
216 score: 1.,
217 positions: vec![],
218 string: completion.clone(),
219 })
220 .collect();
221 Self {
222 id,
223 sort_completions,
224 initial_position: selection.start,
225 buffer,
226 completions: RefCell::new(completions).into(),
227 match_candidates,
228 matches,
229 selected_item: 0,
230 scroll_handle: UniformListScrollHandle::new(),
231 resolve_completions: false,
232 aside_was_displayed: Cell::new(false),
233 show_completion_documentation: false,
234 }
235 }
236
237 fn select_first(
238 &mut self,
239 provider: Option<&dyn CompletionProvider>,
240 cx: &mut ViewContext<Editor>,
241 ) {
242 self.selected_item = 0;
243 self.scroll_handle
244 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
245 self.resolve_selected_completion(provider, cx);
246 cx.notify();
247 }
248
249 fn select_prev(
250 &mut self,
251 provider: Option<&dyn CompletionProvider>,
252 cx: &mut ViewContext<Editor>,
253 ) {
254 if self.selected_item > 0 {
255 self.selected_item -= 1;
256 } else {
257 self.selected_item = self.matches.len() - 1;
258 }
259 self.scroll_handle
260 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
261 self.resolve_selected_completion(provider, cx);
262 cx.notify();
263 }
264
265 fn select_next(
266 &mut self,
267 provider: Option<&dyn CompletionProvider>,
268 cx: &mut ViewContext<Editor>,
269 ) {
270 if self.selected_item + 1 < self.matches.len() {
271 self.selected_item += 1;
272 } else {
273 self.selected_item = 0;
274 }
275 self.scroll_handle
276 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
277 self.resolve_selected_completion(provider, cx);
278 cx.notify();
279 }
280
281 fn select_last(
282 &mut self,
283 provider: Option<&dyn CompletionProvider>,
284 cx: &mut ViewContext<Editor>,
285 ) {
286 self.selected_item = self.matches.len() - 1;
287 self.scroll_handle
288 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
289 self.resolve_selected_completion(provider, cx);
290 cx.notify();
291 }
292
293 pub fn resolve_selected_completion(
294 &mut self,
295 provider: Option<&dyn CompletionProvider>,
296 cx: &mut ViewContext<Editor>,
297 ) {
298 if !self.resolve_completions {
299 return;
300 }
301 let Some(provider) = provider else {
302 return;
303 };
304
305 let completion_index = self.matches[self.selected_item].candidate_id;
306 let resolve_task = provider.resolve_completions(
307 self.buffer.clone(),
308 vec![completion_index],
309 self.completions.clone(),
310 cx,
311 );
312
313 cx.spawn(move |editor, mut cx| async move {
314 if let Some(true) = resolve_task.await.log_err() {
315 editor.update(&mut cx, |_, cx| cx.notify()).ok();
316 }
317 })
318 .detach();
319 }
320
321 fn visible(&self) -> bool {
322 !self.matches.is_empty()
323 }
324
325 fn render(
326 &self,
327 style: &EditorStyle,
328 max_height: Pixels,
329 workspace: Option<WeakView<Workspace>>,
330 cx: &mut ViewContext<Editor>,
331 ) -> AnyElement {
332 let completions = self.completions.borrow_mut();
333 let show_completion_documentation = self.show_completion_documentation;
334 let widest_completion_ix = self
335 .matches
336 .iter()
337 .enumerate()
338 .max_by_key(|(_, mat)| {
339 let completion = &completions[mat.candidate_id];
340 let documentation = &completion.documentation;
341
342 let mut len = completion.label.text.chars().count();
343 if let Some(Documentation::SingleLine(text)) = documentation {
344 if show_completion_documentation {
345 len += text.chars().count();
346 }
347 }
348
349 len
350 })
351 .map(|(ix, _)| ix);
352
353 let selected_item = self.selected_item;
354 let style = style.clone();
355
356 let multiline_docs = if show_completion_documentation {
357 let mat = &self.matches[selected_item];
358 match &completions[mat.candidate_id].documentation {
359 Some(Documentation::MultiLinePlainText(text)) => {
360 Some(div().child(SharedString::from(text.clone())))
361 }
362 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
363 Some(div().child(render_parsed_markdown(
364 "completions_markdown",
365 parsed,
366 &style,
367 workspace,
368 cx,
369 )))
370 }
371 Some(Documentation::Undocumented) if self.aside_was_displayed.get() => {
372 Some(div().child("No documentation"))
373 }
374 _ => None,
375 }
376 } else {
377 None
378 };
379
380 let aside_contents = if let Some(multiline_docs) = multiline_docs {
381 Some(multiline_docs)
382 } else if self.aside_was_displayed.get() {
383 Some(div().child("Fetching documentation..."))
384 } else {
385 None
386 };
387 self.aside_was_displayed.set(aside_contents.is_some());
388
389 let aside_contents = aside_contents.map(|div| {
390 div.id("multiline_docs")
391 .max_h(max_height)
392 .flex_1()
393 .px_1p5()
394 .py_1()
395 .min_w(px(260.))
396 .max_w(px(640.))
397 .w(px(500.))
398 .overflow_y_scroll()
399 .occlude()
400 });
401
402 drop(completions);
403 let completions = self.completions.clone();
404 let matches = self.matches.clone();
405 let list = uniform_list(
406 cx.view().clone(),
407 "completions",
408 matches.len(),
409 move |_editor, range, cx| {
410 let start_ix = range.start;
411 let completions_guard = completions.borrow_mut();
412
413 matches[range]
414 .iter()
415 .enumerate()
416 .map(|(ix, mat)| {
417 let item_ix = start_ix + ix;
418 let candidate_id = mat.candidate_id;
419 let completion = &completions_guard[candidate_id];
420
421 let documentation = if show_completion_documentation {
422 &completion.documentation
423 } else {
424 &None
425 };
426
427 let filter_start = completion.label.filter_range.start;
428 let highlights = gpui::combine_highlights(
429 mat.ranges().map(|range| {
430 (
431 filter_start + range.start..filter_start + range.end,
432 FontWeight::BOLD.into(),
433 )
434 }),
435 styled_runs_for_code_label(&completion.label, &style.syntax).map(
436 |(range, mut highlight)| {
437 // Ignore font weight for syntax highlighting, as we'll use it
438 // for fuzzy matches.
439 highlight.font_weight = None;
440
441 if completion.lsp_completion.deprecated.unwrap_or(false) {
442 highlight.strikethrough = Some(StrikethroughStyle {
443 thickness: 1.0.into(),
444 ..Default::default()
445 });
446 highlight.color = Some(cx.theme().colors().text_muted);
447 }
448
449 (range, highlight)
450 },
451 ),
452 );
453 let completion_label = StyledText::new(completion.label.text.clone())
454 .with_highlights(&style.text, highlights);
455 let documentation_label =
456 if let Some(Documentation::SingleLine(text)) = documentation {
457 if text.trim().is_empty() {
458 None
459 } else {
460 Some(
461 Label::new(text.clone())
462 .ml_4()
463 .size(LabelSize::Small)
464 .color(Color::Muted),
465 )
466 }
467 } else {
468 None
469 };
470
471 let color_swatch = completion
472 .color()
473 .map(|color| div().size_4().bg(color).rounded_sm());
474
475 div().min_w(px(220.)).max_w(px(540.)).child(
476 ListItem::new(mat.candidate_id)
477 .inset(true)
478 .toggle_state(item_ix == selected_item)
479 .on_click(cx.listener(move |editor, _event, cx| {
480 cx.stop_propagation();
481 if let Some(task) = editor.confirm_completion(
482 &ConfirmCompletion {
483 item_ix: Some(item_ix),
484 },
485 cx,
486 ) {
487 task.detach_and_log_err(cx)
488 }
489 }))
490 .start_slot::<Div>(color_swatch)
491 .child(h_flex().overflow_hidden().child(completion_label))
492 .end_slot::<Label>(documentation_label),
493 )
494 })
495 .collect()
496 },
497 )
498 .occlude()
499 .max_h(max_height)
500 .track_scroll(self.scroll_handle.clone())
501 .with_width_from_item(widest_completion_ix)
502 .with_sizing_behavior(ListSizingBehavior::Infer);
503
504 Popover::new()
505 .child(list)
506 .when_some(aside_contents, |popover, aside_contents| {
507 popover.aside(aside_contents)
508 })
509 .into_any_element()
510 }
511
512 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
513 let mut matches = if let Some(query) = query {
514 fuzzy::match_strings(
515 &self.match_candidates,
516 query,
517 query.chars().any(|c| c.is_uppercase()),
518 100,
519 &Default::default(),
520 executor,
521 )
522 .await
523 } else {
524 self.match_candidates
525 .iter()
526 .enumerate()
527 .map(|(candidate_id, candidate)| StringMatch {
528 candidate_id,
529 score: Default::default(),
530 positions: Default::default(),
531 string: candidate.string.clone(),
532 })
533 .collect()
534 };
535
536 // Remove all candidates where the query's start does not match the start of any word in the candidate
537 if let Some(query) = query {
538 if let Some(query_start) = query.chars().next() {
539 matches.retain(|string_match| {
540 split_words(&string_match.string).any(|word| {
541 // Check that the first codepoint of the word as lowercase matches the first
542 // codepoint of the query as lowercase
543 word.chars()
544 .flat_map(|codepoint| codepoint.to_lowercase())
545 .zip(query_start.to_lowercase())
546 .all(|(word_cp, query_cp)| word_cp == query_cp)
547 })
548 });
549 }
550 }
551
552 let completions = self.completions.borrow_mut();
553 if self.sort_completions {
554 matches.sort_unstable_by_key(|mat| {
555 // We do want to strike a balance here between what the language server tells us
556 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
557 // `Creat` and there is a local variable called `CreateComponent`).
558 // So what we do is: we bucket all matches into two buckets
559 // - Strong matches
560 // - Weak matches
561 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
562 // and the Weak matches are the rest.
563 //
564 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
565 // matches, we prefer language-server sort_text first.
566 //
567 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
568 // Rest of the matches(weak) can be sorted as language-server expects.
569
570 #[derive(PartialEq, Eq, PartialOrd, Ord)]
571 enum MatchScore<'a> {
572 Strong {
573 score: Reverse<OrderedFloat<f64>>,
574 sort_text: Option<&'a str>,
575 sort_key: (usize, &'a str),
576 },
577 Weak {
578 sort_text: Option<&'a str>,
579 score: Reverse<OrderedFloat<f64>>,
580 sort_key: (usize, &'a str),
581 },
582 }
583
584 let completion = &completions[mat.candidate_id];
585 let sort_key = completion.sort_key();
586 let sort_text = completion.lsp_completion.sort_text.as_deref();
587 let score = Reverse(OrderedFloat(mat.score));
588
589 if mat.score >= 0.2 {
590 MatchScore::Strong {
591 score,
592 sort_text,
593 sort_key,
594 }
595 } else {
596 MatchScore::Weak {
597 sort_text,
598 score,
599 sort_key,
600 }
601 }
602 });
603 }
604 drop(completions);
605
606 self.matches = matches.into();
607 self.selected_item = 0;
608 }
609}
610
611#[derive(Clone)]
612pub struct AvailableCodeAction {
613 pub excerpt_id: ExcerptId,
614 pub action: CodeAction,
615 pub provider: Rc<dyn CodeActionProvider>,
616}
617
618#[derive(Clone)]
619pub struct CodeActionContents {
620 pub tasks: Option<Rc<ResolvedTasks>>,
621 pub actions: Option<Rc<[AvailableCodeAction]>>,
622}
623
624impl CodeActionContents {
625 fn len(&self) -> usize {
626 match (&self.tasks, &self.actions) {
627 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
628 (Some(tasks), None) => tasks.templates.len(),
629 (None, Some(actions)) => actions.len(),
630 (None, None) => 0,
631 }
632 }
633
634 fn is_empty(&self) -> bool {
635 match (&self.tasks, &self.actions) {
636 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
637 (Some(tasks), None) => tasks.templates.is_empty(),
638 (None, Some(actions)) => actions.is_empty(),
639 (None, None) => true,
640 }
641 }
642
643 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
644 self.tasks
645 .iter()
646 .flat_map(|tasks| {
647 tasks
648 .templates
649 .iter()
650 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
651 })
652 .chain(self.actions.iter().flat_map(|actions| {
653 actions.iter().map(|available| CodeActionsItem::CodeAction {
654 excerpt_id: available.excerpt_id,
655 action: available.action.clone(),
656 provider: available.provider.clone(),
657 })
658 }))
659 }
660
661 pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
662 match (&self.tasks, &self.actions) {
663 (Some(tasks), Some(actions)) => {
664 if index < tasks.templates.len() {
665 tasks
666 .templates
667 .get(index)
668 .cloned()
669 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
670 } else {
671 actions.get(index - tasks.templates.len()).map(|available| {
672 CodeActionsItem::CodeAction {
673 excerpt_id: available.excerpt_id,
674 action: available.action.clone(),
675 provider: available.provider.clone(),
676 }
677 })
678 }
679 }
680 (Some(tasks), None) => tasks
681 .templates
682 .get(index)
683 .cloned()
684 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
685 (None, Some(actions)) => {
686 actions
687 .get(index)
688 .map(|available| CodeActionsItem::CodeAction {
689 excerpt_id: available.excerpt_id,
690 action: available.action.clone(),
691 provider: available.provider.clone(),
692 })
693 }
694 (None, None) => None,
695 }
696 }
697}
698
699#[allow(clippy::large_enum_variant)]
700#[derive(Clone)]
701pub enum CodeActionsItem {
702 Task(TaskSourceKind, ResolvedTask),
703 CodeAction {
704 excerpt_id: ExcerptId,
705 action: CodeAction,
706 provider: Rc<dyn CodeActionProvider>,
707 },
708}
709
710impl CodeActionsItem {
711 fn as_task(&self) -> Option<&ResolvedTask> {
712 let Self::Task(_, task) = self else {
713 return None;
714 };
715 Some(task)
716 }
717
718 fn as_code_action(&self) -> Option<&CodeAction> {
719 let Self::CodeAction { action, .. } = self else {
720 return None;
721 };
722 Some(action)
723 }
724
725 pub fn label(&self) -> String {
726 match self {
727 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
728 Self::Task(_, task) => task.resolved_label.clone(),
729 }
730 }
731}
732
733pub struct CodeActionsMenu {
734 pub actions: CodeActionContents,
735 pub buffer: Model<Buffer>,
736 pub selected_item: usize,
737 pub scroll_handle: UniformListScrollHandle,
738 pub deployed_from_indicator: Option<DisplayRow>,
739}
740
741impl CodeActionsMenu {
742 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
743 self.selected_item = 0;
744 self.scroll_handle
745 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
746 cx.notify()
747 }
748
749 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
750 if self.selected_item > 0 {
751 self.selected_item -= 1;
752 } else {
753 self.selected_item = self.actions.len() - 1;
754 }
755 self.scroll_handle
756 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
757 cx.notify();
758 }
759
760 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
761 if self.selected_item + 1 < self.actions.len() {
762 self.selected_item += 1;
763 } else {
764 self.selected_item = 0;
765 }
766 self.scroll_handle
767 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
768 cx.notify();
769 }
770
771 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
772 self.selected_item = self.actions.len() - 1;
773 self.scroll_handle
774 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
775 cx.notify()
776 }
777
778 fn visible(&self) -> bool {
779 !self.actions.is_empty()
780 }
781
782 fn render(
783 &self,
784 cursor_position: DisplayPoint,
785 _style: &EditorStyle,
786 max_height: Pixels,
787 cx: &mut ViewContext<Editor>,
788 ) -> (ContextMenuOrigin, AnyElement) {
789 let actions = self.actions.clone();
790 let selected_item = self.selected_item;
791 let element = uniform_list(
792 cx.view().clone(),
793 "code_actions_menu",
794 self.actions.len(),
795 move |_this, range, cx| {
796 actions
797 .iter()
798 .skip(range.start)
799 .take(range.end - range.start)
800 .enumerate()
801 .map(|(ix, action)| {
802 let item_ix = range.start + ix;
803 let selected = selected_item == item_ix;
804 let colors = cx.theme().colors();
805 div()
806 .px_1()
807 .rounded_md()
808 .text_color(colors.text)
809 .when(selected, |style| {
810 style
811 .bg(colors.element_active)
812 .text_color(colors.text_accent)
813 })
814 .hover(|style| {
815 style
816 .bg(colors.element_hover)
817 .text_color(colors.text_accent)
818 })
819 .whitespace_nowrap()
820 .when_some(action.as_code_action(), |this, action| {
821 this.on_mouse_down(
822 MouseButton::Left,
823 cx.listener(move |editor, _, cx| {
824 cx.stop_propagation();
825 if let Some(task) = editor.confirm_code_action(
826 &ConfirmCodeAction {
827 item_ix: Some(item_ix),
828 },
829 cx,
830 ) {
831 task.detach_and_log_err(cx)
832 }
833 }),
834 )
835 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
836 .child(SharedString::from(
837 action.lsp_action.title.replace("\n", ""),
838 ))
839 })
840 .when_some(action.as_task(), |this, task| {
841 this.on_mouse_down(
842 MouseButton::Left,
843 cx.listener(move |editor, _, cx| {
844 cx.stop_propagation();
845 if let Some(task) = editor.confirm_code_action(
846 &ConfirmCodeAction {
847 item_ix: Some(item_ix),
848 },
849 cx,
850 ) {
851 task.detach_and_log_err(cx)
852 }
853 }),
854 )
855 .child(SharedString::from(task.resolved_label.replace("\n", "")))
856 })
857 })
858 .collect()
859 },
860 )
861 .elevation_1(cx)
862 .p_1()
863 .max_h(max_height)
864 .occlude()
865 .track_scroll(self.scroll_handle.clone())
866 .with_width_from_item(
867 self.actions
868 .iter()
869 .enumerate()
870 .max_by_key(|(_, action)| match action {
871 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
872 CodeActionsItem::CodeAction { action, .. } => {
873 action.lsp_action.title.chars().count()
874 }
875 })
876 .map(|(ix, _)| ix),
877 )
878 .with_sizing_behavior(ListSizingBehavior::Infer)
879 .into_any_element();
880
881 let cursor_position = if let Some(row) = self.deployed_from_indicator {
882 ContextMenuOrigin::GutterIndicator(row)
883 } else {
884 ContextMenuOrigin::EditorPoint(cursor_position)
885 };
886
887 (cursor_position, element)
888 }
889}