use iced::widget::{Space, button, column, container, row, text};
use iced::{Background, Border, Color, Element, Length, Shadow, Theme, Vector};
use super::actions::{ActionContext, SharedAction};
use crate::canvas_editor::Message;
use crate::i18n::Translations;
const MENU_WIDTH: f32 = 224.0;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextMenuItem {
pub id: String,
pub label: String,
pub shortcut: Option<String>,
pub enabled: bool,
pub status: Option<bool>,
}
impl ContextMenuItem {
pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
Self {
id: id.into(),
label: label.into(),
shortcut: None,
enabled: true,
status: None,
}
}
#[must_use]
pub fn with_shortcut(mut self, shortcut: impl Into<String>) -> Self {
self.shortcut = Some(shortcut.into());
self
}
#[must_use]
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
#[must_use]
pub fn with_status(mut self, status: bool) -> Self {
self.status = Some(status);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContextMenuEntry {
Item(ContextMenuItem),
Separator,
}
impl ContextMenuEntry {
pub fn item(id: impl Into<String>, label: impl Into<String>) -> Self {
Self::Item(ContextMenuItem::new(id, label))
}
pub const fn separator() -> Self {
Self::Separator
}
#[must_use]
pub fn with_shortcut(self, shortcut: impl Into<String>) -> Self {
match self {
Self::Item(item) => Self::Item(item.with_shortcut(shortcut)),
Self::Separator => Self::Separator,
}
}
#[must_use]
pub fn with_enabled(self, enabled: bool) -> Self {
match self {
Self::Item(item) => Self::Item(item.with_enabled(enabled)),
Self::Separator => Self::Separator,
}
}
}
impl From<ContextMenuItem> for ContextMenuEntry {
fn from(item: ContextMenuItem) -> Self {
Self::Item(item)
}
}
#[derive(Debug, Clone)]
enum MenuEntry {
Item { label: String, shortcut: String, message: Option<Message> },
Separator,
}
impl MenuEntry {
#[cfg(test)]
fn label(&self) -> Option<&str> {
match self {
Self::Item { label, .. } => Some(label),
Self::Separator => None,
}
}
}
fn custom_entries(entries: &[ContextMenuEntry]) -> Vec<MenuEntry> {
entries
.iter()
.map(|entry| match entry {
ContextMenuEntry::Item(item) => MenuEntry::Item {
label: item.label.clone(),
shortcut: item.shortcut.clone().unwrap_or_default(),
message: item
.enabled
.then(|| Message::CustomContextMenuAction(item.id.clone())),
},
ContextMenuEntry::Separator => MenuEntry::Separator,
})
.collect()
}
fn default_entries(
context: ActionContext,
translations: &Translations,
) -> Vec<MenuEntry> {
fn row(
action: SharedAction,
context: ActionContext,
translations: &Translations,
) -> MenuEntry {
MenuEntry::Item {
label: action.label(translations),
shortcut: action.shortcut().to_string(),
message: action.is_available(context).then(|| action.message()),
}
}
let mut entries = if SharedAction::RevealInFileManager.is_available(context)
{
vec![
row(SharedAction::RevealInFileManager, context, translations),
MenuEntry::Separator,
]
} else {
Vec::new()
};
entries.extend([
row(SharedAction::Undo, context, translations),
row(SharedAction::Redo, context, translations),
MenuEntry::Separator,
row(SharedAction::Cut, context, translations),
row(SharedAction::Copy, context, translations),
row(SharedAction::Paste, context, translations),
MenuEntry::Separator,
row(SharedAction::SelectAll, context, translations),
]);
entries
}
fn build_entries(
custom: &[ContextMenuEntry],
default_context_menu_enabled: bool,
context: ActionContext,
translations: &Translations,
) -> Vec<MenuEntry> {
let mut entries = custom_entries(custom);
if default_context_menu_enabled {
if !entries.is_empty() {
entries.push(MenuEntry::Separator);
}
entries.extend(default_entries(context, translations));
}
entries
}
pub(crate) fn view(
custom: &[ContextMenuEntry],
default_context_menu_enabled: bool,
context: ActionContext,
translations: Translations,
) -> Element<'static, Message> {
let items = build_entries(
custom,
default_context_menu_enabled,
context,
&translations,
)
.into_iter()
.map(|entry| match entry {
MenuEntry::Item { label, shortcut, message } => {
menu_item(label, shortcut, message)
}
MenuEntry::Separator => separator(),
})
.collect::<Vec<_>>();
container(column(items).spacing(1).padding(4))
.width(Length::Fixed(MENU_WIDTH))
.style(|theme: &Theme| {
let palette = theme.extended_palette();
container::Style {
background: Some(Background::Color(
palette.background.weak.color,
)),
text_color: Some(palette.background.weak.text),
border: Border {
color: palette.background.strong.color,
width: 1.0,
radius: 6.0.into(),
},
shadow: Shadow {
color: Color::BLACK.scale_alpha(0.35),
offset: Vector::new(0.0, 4.0),
blur_radius: 14.0,
},
..container::Style::default()
}
})
.into()
}
fn menu_item(
label: String,
shortcut: String,
message: Option<Message>,
) -> Element<'static, Message> {
let enabled = message.is_some();
let content = row![
text(label).size(13),
Space::new().width(Length::Fill),
text(shortcut).size(12),
]
.align_y(iced::Alignment::Center);
button(content)
.width(Length::Fill)
.padding([6, 9])
.on_press_maybe(message)
.style(move |theme: &Theme, status| {
let palette = theme.extended_palette();
let text_color = if enabled {
palette.background.weak.text
} else {
palette.background.weak.text.scale_alpha(0.35)
};
let highlight_alpha = match status {
button::Status::Hovered => {
if palette.is_dark {
0.18
} else {
0.10
}
}
button::Status::Pressed => {
if palette.is_dark {
0.28
} else {
0.18
}
}
button::Status::Active | button::Status::Disabled => 0.0,
};
let background = (enabled && highlight_alpha > 0.0).then_some(
Background::Color(
palette.primary.base.color.scale_alpha(highlight_alpha),
),
);
button::Style {
background,
text_color,
border: Border { radius: 6.0.into(), ..Border::default() },
..button::Style::default()
}
})
.into()
}
fn separator() -> Element<'static, Message> {
let line =
container(Space::new().width(Length::Fill).height(Length::Fixed(1.0)))
.style(|theme: &Theme| {
let palette = theme.extended_palette();
container::Style {
background: Some(Background::Color(
palette.background.strong.color,
)),
..container::Style::default()
}
});
container(line).padding([3, 7]).into()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::canvas_editor::CodeEditor;
use crate::canvas_editor::features::actions::SharedAction;
use crate::canvas_editor::features::command_palette::PaletteAction;
use crate::{ContextMenuEntry, ContextMenuItem, Language, Translations};
fn editor_with_everything_available() -> CodeEditor {
let mut editor = CodeEditor::new("hello", "rs");
editor.set_reveal_in_file_manager_enabled(true);
let _ = editor.update(&Message::Paste("a".to_string()));
let _ = editor.update(&Message::Paste("b".to_string()));
let _ = editor.update(&Message::Undo);
let _ = editor.update(&Message::SelectAll);
let context = editor.action_context();
assert!(context.can_undo && context.can_redo);
assert!(context.has_selection && context.has_content);
assert!(context.reveal_in_file_manager_enabled);
editor
}
#[test]
#[allow(clippy::panic)]
fn test_both_surfaces_render_every_shared_action_from_the_same_binding() {
let editor = editor_with_everything_available();
let translations = Translations::default();
let menu =
build_entries(&[], true, editor.action_context(), &translations);
let palette = editor.command_palette_entries();
for action in SharedAction::ALL {
let label = action.label(&translations);
let menu_row = menu
.iter()
.find_map(|entry| match entry {
MenuEntry::Item { label: found, shortcut, message }
if *found == label =>
{
Some((shortcut, message))
}
_ => None,
})
.unwrap_or_else(|| panic!("{label:?} missing from the menu"));
let palette_row = palette
.iter()
.find(|entry| entry.label == label)
.unwrap_or_else(|| {
panic!("{label:?} missing from the palette")
});
assert_eq!(
menu_row.0, &palette_row.shortcut,
"{label:?}: the two surfaces show different shortcut hints"
);
assert_eq!(
menu_row.0,
action.shortcut(),
"{label:?}: neither matches `SharedAction::shortcut`"
);
let expected = format!("{:?}", action.message());
assert_eq!(
menu_row.1.as_ref().map(|message| format!("{message:?}")),
Some(expected.clone()),
"{label:?}: the menu sends a different message"
);
let sent = match &palette_row.action {
PaletteAction::Builtin(message) => format!("{message:?}"),
other => panic!("{label:?} is not a built-in row: {other:?}"),
};
assert_eq!(
sent, expected,
"{label:?}: the palette sends a different message"
);
}
}
#[test]
fn test_an_unavailable_action_is_dimmed_in_the_menu_but_absent_from_the_palette()
{
let editor = CodeEditor::new("hello", "rs");
let translations = Translations::default();
let undo = SharedAction::Undo.label(&translations);
let reveal = SharedAction::RevealInFileManager.label(&translations);
let menu =
build_entries(&[], true, editor.action_context(), &translations);
let palette = editor.command_palette_entries();
assert!(
menu.iter().any(|entry| matches!(
entry,
MenuEntry::Item { label, message: None, .. } if *label == undo
)),
"the menu keeps Undo in place, dimmed"
);
assert!(
!palette.iter().any(|entry| entry.label == undo),
"the palette drops Undo entirely"
);
assert!(!menu.iter().any(|entry| entry.label() == Some(&reveal)));
assert!(!palette.iter().any(|entry| entry.label == reveal));
}
#[test]
fn test_custom_context_menu_action_message_preserves_id() {
let entries = build_entries(
&[ContextMenuEntry::Item(ContextMenuItem::new(
"refactor.extract",
"Extract function",
))],
false,
ActionContext::default(),
&Translations::default(),
);
assert!(matches!(
&entries[0],
MenuEntry::Item {
message: Some(Message::CustomContextMenuAction(id)),
..
}
if id == "refactor.extract"
));
}
#[test]
fn test_custom_entries_precede_default_entries() {
let entries = build_entries(
&[ContextMenuEntry::item("custom.format", "Format document")],
true,
ActionContext::default(),
&Translations::default(),
);
assert_eq!(entries[0].label(), Some("Format document"));
assert!(matches!(entries[1], MenuEntry::Separator));
assert_eq!(entries[2].label(), Some("Undo"));
}
#[test]
fn test_context_menu_uses_selected_language() {
let translations = Translations::new(Language::ChineseSimplified);
let entries = default_entries(ActionContext::default(), &translations);
assert_eq!(entries[0].label(), Some("撤消"));
assert_eq!(entries[1].label(), Some("恢复"));
assert_eq!(entries[3].label(), Some("剪切"));
assert_eq!(entries[4].label(), Some("复制"));
assert_eq!(entries[5].label(), Some("粘贴"));
assert_eq!(entries[7].label(), Some("选择全部"));
let custom = custom_entries(&[ContextMenuEntry::item(
"custom.format",
"Format document",
)]);
assert_eq!(custom[0].label(), Some("Format document"));
}
#[test]
fn test_reveal_in_file_manager_entry_emits_request() {
let translations = Translations::new(Language::English);
let entries = build_entries(
&[],
true,
ActionContext {
reveal_in_file_manager_enabled: true,
..ActionContext::default()
},
&translations,
);
assert!(matches!(
&entries[0],
MenuEntry::Item { label, shortcut, message }
if label == &translations.context_menu_reveal_in_file_manager()
&& shortcut.is_empty()
&& matches!(message, Some(Message::RevealInFileManager))
));
assert!(matches!(entries[1], MenuEntry::Separator));
assert_eq!(entries[2].label(), Some("Undo"));
}
#[test]
fn test_reveal_in_file_manager_respects_default_menu_toggle() {
let entries = build_entries(
&[],
false,
ActionContext {
reveal_in_file_manager_enabled: true,
..ActionContext::default()
},
&Translations::default(),
);
assert!(entries.is_empty());
}
}