Skip to main content

iced_code_editor/canvas_editor/features/
context_menu.rs

1//! Right-click context menu for editor actions.
2
3use iced::widget::{Space, button, column, container, row, text};
4use iced::{Background, Border, Color, Element, Length, Shadow, Theme, Vector};
5
6use super::actions::{ActionContext, SharedAction};
7use crate::canvas_editor::Message;
8use crate::i18n::Translations;
9
10const MENU_WIDTH: f32 = 224.0;
11
12/// An actionable entry in the editor context menu.
13///
14/// The `id` is what the host receives when the item is selected, so it should
15/// be a stable identifier rather than the display text — renaming or
16/// translating a `label` then never breaks the action.
17///
18/// # Examples
19///
20/// ```
21/// use iced_code_editor::ContextMenuItem;
22///
23/// let item = ContextMenuItem::new("format", "Format Document")
24///     .with_shortcut("Ctrl+Shift+F");
25///
26/// assert_eq!(item.id, "format");
27/// assert_eq!(item.shortcut.as_deref(), Some("Ctrl+Shift+F"));
28/// assert!(item.enabled);
29/// ```
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct ContextMenuItem {
32    /// Stable action identifier emitted when the item is selected.
33    pub id: String,
34    /// Text displayed for the item.
35    pub label: String,
36    /// Optional keyboard shortcut hint displayed beside the label.
37    pub shortcut: Option<String>,
38    /// Whether the item can be selected.
39    pub enabled: bool,
40    /// Current state of a toggle command, `None` for every other command.
41    ///
42    /// Only the command palette reads it, where it is drawn as an On/Off badge
43    /// beside the label; the context menu ignores it. Set it on an entry that
44    /// switches a setting the host owns, and re-register the entries when that
45    /// setting changes so the badge stays truthful.
46    pub status: Option<bool>,
47}
48
49impl ContextMenuItem {
50    /// Creates an enabled context-menu item without a shortcut hint.
51    ///
52    /// # Arguments
53    ///
54    /// * `id` - Stable action identifier emitted when the item is selected
55    /// * `label` - The text shown to the user
56    ///
57    /// # Returns
58    ///
59    /// An enabled item with no shortcut hint
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use iced_code_editor::ContextMenuItem;
65    ///
66    /// let item = ContextMenuItem::new("rename", "Rename Symbol");
67    /// assert_eq!(item.label, "Rename Symbol");
68    /// assert!(item.shortcut.is_none());
69    /// assert!(item.enabled);
70    /// ```
71    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
72        Self {
73            id: id.into(),
74            label: label.into(),
75            shortcut: None,
76            enabled: true,
77            status: None,
78        }
79    }
80
81    /// Sets the keyboard shortcut hint displayed beside this item.
82    ///
83    /// This is only a hint for the user: setting it does not bind the
84    /// shortcut, which the host application is responsible for handling.
85    ///
86    /// # Arguments
87    ///
88    /// * `shortcut` - The shortcut text to display, e.g. `Ctrl+Shift+F`
89    ///
90    /// # Returns
91    ///
92    /// Self for method chaining
93    ///
94    /// # Examples
95    ///
96    /// ```
97    /// use iced_code_editor::ContextMenuItem;
98    ///
99    /// let item = ContextMenuItem::new("format", "Format Document")
100    ///     .with_shortcut("Ctrl+Shift+F");
101    /// assert_eq!(item.shortcut.as_deref(), Some("Ctrl+Shift+F"));
102    /// ```
103    #[must_use]
104    pub fn with_shortcut(mut self, shortcut: impl Into<String>) -> Self {
105        self.shortcut = Some(shortcut.into());
106        self
107    }
108
109    /// Sets whether this item can be selected.
110    ///
111    /// A disabled item is still drawn, dimmed — use this for an action that is
112    /// unavailable right now but should stay visible so the menu does not
113    /// change shape between right-clicks.
114    ///
115    /// # Arguments
116    ///
117    /// * `enabled` - Whether the item can be selected
118    ///
119    /// # Returns
120    ///
121    /// Self for method chaining
122    ///
123    /// # Examples
124    ///
125    /// ```
126    /// use iced_code_editor::ContextMenuItem;
127    ///
128    /// let item = ContextMenuItem::new("rename", "Rename Symbol")
129    ///     .with_enabled(false);
130    /// assert!(!item.enabled);
131    /// ```
132    #[must_use]
133    pub fn with_enabled(mut self, enabled: bool) -> Self {
134        self.enabled = enabled;
135        self
136    }
137
138    /// Marks this item as a toggle currently in state `status`.
139    ///
140    /// The command palette then shows an On/Off badge beside the label, so the
141    /// user can tell what running the command will do without trying it. The
142    /// value is a snapshot: re-register the entries when the setting changes.
143    ///
144    /// # Arguments
145    ///
146    /// * `status` - Whether the setting the item toggles is currently on
147    ///
148    /// # Returns
149    ///
150    /// Self for method chaining
151    ///
152    /// # Examples
153    ///
154    /// ```
155    /// use iced_code_editor::ContextMenuItem;
156    ///
157    /// let item = ContextMenuItem::new("format_on_save", "Toggle Format On Save")
158    ///     .with_status(true);
159    /// assert_eq!(item.status, Some(true));
160    /// ```
161    #[must_use]
162    pub fn with_status(mut self, status: bool) -> Self {
163        self.status = Some(status);
164        self
165    }
166}
167
168/// A custom editor context-menu entry.
169///
170/// Pass a list of these to [`CodeEditor::set_custom_context_menu_entries`] to
171/// extend the menu, or to replace it entirely by also turning off the built-in
172/// actions with [`CodeEditor::set_default_context_menu_enabled`].
173///
174/// # Examples
175///
176/// ```
177/// use iced_code_editor::ContextMenuEntry;
178///
179/// let entries = vec![
180///     ContextMenuEntry::item("format", "Format Document")
181///         .with_shortcut("Ctrl+Shift+F"),
182///     ContextMenuEntry::separator(),
183///     ContextMenuEntry::item("rename", "Rename Symbol").with_enabled(false),
184/// ];
185/// assert_eq!(entries.len(), 3);
186/// ```
187///
188/// [`CodeEditor::set_custom_context_menu_entries`]: crate::CodeEditor::set_custom_context_menu_entries
189/// [`CodeEditor::set_default_context_menu_enabled`]: crate::CodeEditor::set_default_context_menu_enabled
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub enum ContextMenuEntry {
192    /// An actionable menu item.
193    Item(ContextMenuItem),
194    /// A visual separator between groups of items.
195    Separator,
196}
197
198impl ContextMenuEntry {
199    /// Creates an enabled action entry without a shortcut hint.
200    ///
201    /// Shorthand for wrapping [`ContextMenuItem::new`].
202    ///
203    /// # Arguments
204    ///
205    /// * `id` - Stable action identifier emitted when the entry is selected
206    /// * `label` - The text shown to the user
207    ///
208    /// # Returns
209    ///
210    /// An [`ContextMenuEntry::Item`] wrapping a new enabled item
211    ///
212    /// # Examples
213    ///
214    /// ```
215    /// use iced_code_editor::{ContextMenuEntry, ContextMenuItem};
216    ///
217    /// let entry = ContextMenuEntry::item("format", "Format Document");
218    /// assert_eq!(
219    ///     entry,
220    ///     ContextMenuEntry::Item(ContextMenuItem::new("format", "Format Document")),
221    /// );
222    /// ```
223    pub fn item(id: impl Into<String>, label: impl Into<String>) -> Self {
224        Self::Item(ContextMenuItem::new(id, label))
225    }
226
227    /// Creates a separator entry.
228    ///
229    /// # Returns
230    ///
231    /// A [`ContextMenuEntry::Separator`]
232    ///
233    /// # Examples
234    ///
235    /// ```
236    /// use iced_code_editor::ContextMenuEntry;
237    ///
238    /// assert_eq!(ContextMenuEntry::separator(), ContextMenuEntry::Separator);
239    /// ```
240    pub const fn separator() -> Self {
241        Self::Separator
242    }
243
244    /// Sets the keyboard shortcut hint when this is an action entry.
245    ///
246    /// A separator has no shortcut to set, so it is returned unchanged rather
247    /// than erroring — this keeps a chain of builder calls over a mixed list
248    /// of entries free of special cases.
249    ///
250    /// # Arguments
251    ///
252    /// * `shortcut` - The shortcut text to display, e.g. `Ctrl+Shift+F`
253    ///
254    /// # Returns
255    ///
256    /// Self for method chaining
257    ///
258    /// # Examples
259    ///
260    /// ```
261    /// use iced_code_editor::ContextMenuEntry;
262    ///
263    /// let entry = ContextMenuEntry::item("format", "Format Document")
264    ///     .with_shortcut("Ctrl+Shift+F");
265    /// assert!(matches!(entry, ContextMenuEntry::Item(_)));
266    ///
267    /// // A separator is unaffected.
268    /// let separator = ContextMenuEntry::separator().with_shortcut("Ctrl+K");
269    /// assert_eq!(separator, ContextMenuEntry::Separator);
270    /// ```
271    #[must_use]
272    pub fn with_shortcut(self, shortcut: impl Into<String>) -> Self {
273        match self {
274            Self::Item(item) => Self::Item(item.with_shortcut(shortcut)),
275            Self::Separator => Self::Separator,
276        }
277    }
278
279    /// Sets whether this entry can be selected when it is an action.
280    ///
281    /// A separator is returned unchanged, for the same reason as
282    /// [`Self::with_shortcut`].
283    ///
284    /// # Arguments
285    ///
286    /// * `enabled` - Whether the entry can be selected
287    ///
288    /// # Returns
289    ///
290    /// Self for method chaining
291    ///
292    /// # Examples
293    ///
294    /// ```
295    /// use iced_code_editor::{ContextMenuEntry, ContextMenuItem};
296    ///
297    /// let entry = ContextMenuEntry::item("rename", "Rename Symbol")
298    ///     .with_enabled(false);
299    /// assert_eq!(
300    ///     entry,
301    ///     ContextMenuEntry::Item(
302    ///         ContextMenuItem::new("rename", "Rename Symbol").with_enabled(false)
303    ///     ),
304    /// );
305    ///
306    /// // A separator is unaffected.
307    /// let separator = ContextMenuEntry::separator().with_enabled(false);
308    /// assert_eq!(separator, ContextMenuEntry::Separator);
309    /// ```
310    #[must_use]
311    pub fn with_enabled(self, enabled: bool) -> Self {
312        match self {
313            Self::Item(item) => Self::Item(item.with_enabled(enabled)),
314            Self::Separator => Self::Separator,
315        }
316    }
317}
318
319impl From<ContextMenuItem> for ContextMenuEntry {
320    fn from(item: ContextMenuItem) -> Self {
321        Self::Item(item)
322    }
323}
324
325#[derive(Debug, Clone)]
326enum MenuEntry {
327    Item { label: String, shortcut: String, message: Option<Message> },
328    Separator,
329}
330
331impl MenuEntry {
332    #[cfg(test)]
333    fn label(&self) -> Option<&str> {
334        match self {
335            Self::Item { label, .. } => Some(label),
336            Self::Separator => None,
337        }
338    }
339}
340
341fn custom_entries(entries: &[ContextMenuEntry]) -> Vec<MenuEntry> {
342    entries
343        .iter()
344        .map(|entry| match entry {
345            ContextMenuEntry::Item(item) => MenuEntry::Item {
346                label: item.label.clone(),
347                shortcut: item.shortcut.clone().unwrap_or_default(),
348                message: item
349                    .enabled
350                    .then(|| Message::CustomContextMenuAction(item.id.clone())),
351            },
352            ContextMenuEntry::Separator => MenuEntry::Separator,
353        })
354        .collect()
355}
356
357/// Builds the built-in half of the menu, in the order the menu shows it.
358///
359/// Every row's label, shortcut and message come from [`SharedAction`], which
360/// the command palette reads too; what belongs to the menu is the order, the
361/// separators, and the choice to *dim* an unavailable action rather than drop
362/// it. A menu with a fixed shape is what lets muscle memory work, so a row
363/// that cannot be run right now still holds its place.
364fn default_entries(
365    context: ActionContext,
366    translations: &Translations,
367) -> Vec<MenuEntry> {
368    /// Turns a shared action into a menu row, dimmed when unavailable.
369    fn row(
370        action: SharedAction,
371        context: ActionContext,
372        translations: &Translations,
373    ) -> MenuEntry {
374        MenuEntry::Item {
375            label: action.label(translations),
376            shortcut: action.shortcut().to_string(),
377            message: action.is_available(context).then(|| action.message()),
378        }
379    }
380
381    // Reveal sits above everything, separated: it acts on the file rather than
382    // on the text, and it is the only one the host can switch off entirely --
383    // so it is absent, not dimmed, when unavailable.
384    let mut entries = if SharedAction::RevealInFileManager.is_available(context)
385    {
386        vec![
387            row(SharedAction::RevealInFileManager, context, translations),
388            MenuEntry::Separator,
389        ]
390    } else {
391        Vec::new()
392    };
393
394    entries.extend([
395        row(SharedAction::Undo, context, translations),
396        row(SharedAction::Redo, context, translations),
397        MenuEntry::Separator,
398        row(SharedAction::Cut, context, translations),
399        row(SharedAction::Copy, context, translations),
400        row(SharedAction::Paste, context, translations),
401        MenuEntry::Separator,
402        row(SharedAction::SelectAll, context, translations),
403    ]);
404    entries
405}
406
407fn build_entries(
408    custom: &[ContextMenuEntry],
409    default_context_menu_enabled: bool,
410    context: ActionContext,
411    translations: &Translations,
412) -> Vec<MenuEntry> {
413    let mut entries = custom_entries(custom);
414    if default_context_menu_enabled {
415        if !entries.is_empty() {
416            entries.push(MenuEntry::Separator);
417        }
418        entries.extend(default_entries(context, translations));
419    }
420    entries
421}
422
423/// Builds the context-menu contents.
424pub(crate) fn view(
425    custom: &[ContextMenuEntry],
426    default_context_menu_enabled: bool,
427    context: ActionContext,
428    translations: Translations,
429) -> Element<'static, Message> {
430    let items = build_entries(
431        custom,
432        default_context_menu_enabled,
433        context,
434        &translations,
435    )
436    .into_iter()
437    .map(|entry| match entry {
438        MenuEntry::Item { label, shortcut, message } => {
439            menu_item(label, shortcut, message)
440        }
441        MenuEntry::Separator => separator(),
442    })
443    .collect::<Vec<_>>();
444
445    container(column(items).spacing(1).padding(4))
446        .width(Length::Fixed(MENU_WIDTH))
447        .style(|theme: &Theme| {
448            let palette = theme.extended_palette();
449            container::Style {
450                background: Some(Background::Color(
451                    palette.background.weak.color,
452                )),
453                text_color: Some(palette.background.weak.text),
454                border: Border {
455                    color: palette.background.strong.color,
456                    width: 1.0,
457                    radius: 6.0.into(),
458                },
459                shadow: Shadow {
460                    color: Color::BLACK.scale_alpha(0.35),
461                    offset: Vector::new(0.0, 4.0),
462                    blur_radius: 14.0,
463                },
464                ..container::Style::default()
465            }
466        })
467        .into()
468}
469
470fn menu_item(
471    label: String,
472    shortcut: String,
473    message: Option<Message>,
474) -> Element<'static, Message> {
475    let enabled = message.is_some();
476    let content = row![
477        text(label).size(13),
478        Space::new().width(Length::Fill),
479        text(shortcut).size(12),
480    ]
481    .align_y(iced::Alignment::Center);
482
483    button(content)
484        .width(Length::Fill)
485        .padding([6, 9])
486        .on_press_maybe(message)
487        .style(move |theme: &Theme, status| {
488            let palette = theme.extended_palette();
489            let text_color = if enabled {
490                palette.background.weak.text
491            } else {
492                palette.background.weak.text.scale_alpha(0.35)
493            };
494            let background = matches!(
495                status,
496                button::Status::Hovered | button::Status::Pressed
497            )
498            .then_some(Background::Color(palette.background.strong.color));
499
500            button::Style {
501                background,
502                text_color,
503                border: Border { radius: 4.0.into(), ..Border::default() },
504                ..button::Style::default()
505            }
506        })
507        .into()
508}
509
510fn separator() -> Element<'static, Message> {
511    let line =
512        container(Space::new().width(Length::Fill).height(Length::Fixed(1.0)))
513            .style(|theme: &Theme| {
514                let palette = theme.extended_palette();
515                container::Style {
516                    background: Some(Background::Color(
517                        palette.background.strong.color,
518                    )),
519                    ..container::Style::default()
520                }
521            });
522
523    container(line).padding([3, 7]).into()
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529    use crate::canvas_editor::CodeEditor;
530    use crate::canvas_editor::features::actions::SharedAction;
531    use crate::canvas_editor::features::command_palette::PaletteAction;
532    use crate::{ContextMenuEntry, ContextMenuItem, Language, Translations};
533
534    /// An editor in which every shared action is available, so both surfaces
535    /// offer all seven and the two lists can be compared row for row.
536    fn editor_with_everything_available() -> CodeEditor {
537        let mut editor = CodeEditor::new("hello", "rs");
538        editor.set_reveal_in_file_manager_enabled(true);
539        // Paste rather than type: typed characters stay in an open undo
540        // group, so nothing would be undoable yet. Two edits and one undo
541        // leaves both stacks non-empty at once, which is what makes Undo and
542        // Redo simultaneously available.
543        let _ = editor.update(&Message::Paste("a".to_string()));
544        let _ = editor.update(&Message::Paste("b".to_string()));
545        let _ = editor.update(&Message::Undo);
546        let _ = editor.update(&Message::SelectAll);
547
548        let context = editor.action_context();
549        assert!(context.can_undo && context.can_redo);
550        assert!(context.has_selection && context.has_content);
551        assert!(context.reveal_in_file_manager_enabled);
552
553        editor
554    }
555
556    // A missing row or a mismatched binding *is* the failure this test
557    // reports, so `panic!` is the report rather than a bug — the same reason
558    // the LSP protocol tests carry this allow.
559    #[test]
560    #[allow(clippy::panic)]
561    fn test_both_surfaces_render_every_shared_action_from_the_same_binding() {
562        // The drift this exists to prevent: the two surfaces used to spell out
563        // label / shortcut / message separately, so a relabelled action or a
564        // rebound key had to be edited in both, and nothing noticed when only
565        // one was. Reading them from `SharedAction` is what makes them equal;
566        // this walks all seven and checks that they really are.
567        let editor = editor_with_everything_available();
568        let translations = Translations::default();
569        let menu =
570            build_entries(&[], true, editor.action_context(), &translations);
571        let palette = editor.command_palette_entries();
572
573        for action in SharedAction::ALL {
574            let label = action.label(&translations);
575
576            let menu_row = menu
577                .iter()
578                .find_map(|entry| match entry {
579                    MenuEntry::Item { label: found, shortcut, message }
580                        if *found == label =>
581                    {
582                        Some((shortcut, message))
583                    }
584                    _ => None,
585                })
586                .unwrap_or_else(|| panic!("{label:?} missing from the menu"));
587
588            let palette_row = palette
589                .iter()
590                .find(|entry| entry.label == label)
591                .unwrap_or_else(|| {
592                    panic!("{label:?} missing from the palette")
593                });
594
595            assert_eq!(
596                menu_row.0, &palette_row.shortcut,
597                "{label:?}: the two surfaces show different shortcut hints"
598            );
599            assert_eq!(
600                menu_row.0,
601                action.shortcut(),
602                "{label:?}: neither matches `SharedAction::shortcut`"
603            );
604
605            // `Message` is not `PartialEq`; its `Debug` form is enough to tell
606            // two variants -- and two `Paste` payloads -- apart.
607            let expected = format!("{:?}", action.message());
608            assert_eq!(
609                menu_row.1.as_ref().map(|message| format!("{message:?}")),
610                Some(expected.clone()),
611                "{label:?}: the menu sends a different message"
612            );
613            let sent = match &palette_row.action {
614                PaletteAction::Builtin(message) => format!("{message:?}"),
615                other => panic!("{label:?} is not a built-in row: {other:?}"),
616            };
617            assert_eq!(
618                sent, expected,
619                "{label:?}: the palette sends a different message"
620            );
621        }
622    }
623
624    #[test]
625    fn test_an_unavailable_action_is_dimmed_in_the_menu_but_absent_from_the_palette()
626     {
627        // The one thing the two surfaces are *meant* to disagree on. A fresh
628        // editor has nothing to undo, and no file behind it to reveal.
629        let editor = CodeEditor::new("hello", "rs");
630        let translations = Translations::default();
631        let undo = SharedAction::Undo.label(&translations);
632        let reveal = SharedAction::RevealInFileManager.label(&translations);
633
634        let menu =
635            build_entries(&[], true, editor.action_context(), &translations);
636        let palette = editor.command_palette_entries();
637
638        assert!(
639            menu.iter().any(|entry| matches!(
640                entry,
641                MenuEntry::Item { label, message: None, .. } if *label == undo
642            )),
643            "the menu keeps Undo in place, dimmed"
644        );
645        assert!(
646            !palette.iter().any(|entry| entry.label == undo),
647            "the palette drops Undo entirely"
648        );
649
650        // Reveal is the exception: the host switched it off, so it is absent
651        // from both rather than dimmed in one.
652        assert!(!menu.iter().any(|entry| entry.label() == Some(&reveal)));
653        assert!(!palette.iter().any(|entry| entry.label == reveal));
654    }
655
656    #[test]
657    fn test_custom_context_menu_action_message_preserves_id() {
658        let entries = build_entries(
659            &[ContextMenuEntry::Item(ContextMenuItem::new(
660                "refactor.extract",
661                "Extract function",
662            ))],
663            false,
664            ActionContext::default(),
665            &Translations::default(),
666        );
667
668        assert!(matches!(
669            &entries[0],
670            MenuEntry::Item {
671                message: Some(Message::CustomContextMenuAction(id)),
672                ..
673            }
674                if id == "refactor.extract"
675        ));
676    }
677
678    #[test]
679    fn test_custom_entries_precede_default_entries() {
680        let entries = build_entries(
681            &[ContextMenuEntry::item("custom.format", "Format document")],
682            true,
683            ActionContext::default(),
684            &Translations::default(),
685        );
686
687        assert_eq!(entries[0].label(), Some("Format document"));
688        assert!(matches!(entries[1], MenuEntry::Separator));
689        assert_eq!(entries[2].label(), Some("Undo"));
690    }
691
692    #[test]
693    fn test_context_menu_uses_selected_language() {
694        let translations = Translations::new(Language::ChineseSimplified);
695        let entries = default_entries(ActionContext::default(), &translations);
696
697        assert_eq!(entries[0].label(), Some("撤消"));
698        assert_eq!(entries[1].label(), Some("恢复"));
699        assert_eq!(entries[3].label(), Some("剪切"));
700        assert_eq!(entries[4].label(), Some("复制"));
701        assert_eq!(entries[5].label(), Some("粘贴"));
702        assert_eq!(entries[7].label(), Some("选择全部"));
703
704        let custom = custom_entries(&[ContextMenuEntry::item(
705            "custom.format",
706            "Format document",
707        )]);
708        assert_eq!(custom[0].label(), Some("Format document"));
709    }
710
711    #[test]
712    fn test_reveal_in_file_manager_entry_emits_request() {
713        let translations = Translations::new(Language::English);
714        let entries = build_entries(
715            &[],
716            true,
717            ActionContext {
718                reveal_in_file_manager_enabled: true,
719                ..ActionContext::default()
720            },
721            &translations,
722        );
723
724        assert!(matches!(
725            &entries[0],
726            MenuEntry::Item { label, shortcut, message }
727                if label == &translations.context_menu_reveal_in_file_manager()
728                    && shortcut.is_empty()
729                    && matches!(message, Some(Message::RevealInFileManager))
730        ));
731        assert!(matches!(entries[1], MenuEntry::Separator));
732        assert_eq!(entries[2].label(), Some("Undo"));
733    }
734
735    #[test]
736    fn test_reveal_in_file_manager_respects_default_menu_toggle() {
737        let entries = build_entries(
738            &[],
739            false,
740            ActionContext {
741                reveal_in_file_manager_enabled: true,
742                ..ActionContext::default()
743            },
744            &Translations::default(),
745        );
746
747        assert!(entries.is_empty());
748    }
749}