1use iced::widget::{Space, button, column, container, row, text};
4use iced::{Background, Border, Color, Element, Length, Shadow, Theme, Vector};
5
6use crate::canvas_editor::Message;
7use crate::i18n::Translations;
8
9const MENU_WIDTH: f32 = 224.0;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ContextMenuItem {
31 pub id: String,
33 pub label: String,
35 pub shortcut: Option<String>,
37 pub enabled: bool,
39}
40
41impl ContextMenuItem {
42 pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
64 Self {
65 id: id.into(),
66 label: label.into(),
67 shortcut: None,
68 enabled: true,
69 }
70 }
71
72 #[must_use]
95 pub fn with_shortcut(mut self, shortcut: impl Into<String>) -> Self {
96 self.shortcut = Some(shortcut.into());
97 self
98 }
99
100 #[must_use]
124 pub fn with_enabled(mut self, enabled: bool) -> Self {
125 self.enabled = enabled;
126 self
127 }
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
153pub enum ContextMenuEntry {
154 Item(ContextMenuItem),
156 Separator,
158}
159
160impl ContextMenuEntry {
161 pub fn item(id: impl Into<String>, label: impl Into<String>) -> Self {
186 Self::Item(ContextMenuItem::new(id, label))
187 }
188
189 pub const fn separator() -> Self {
203 Self::Separator
204 }
205
206 #[must_use]
234 pub fn with_shortcut(self, shortcut: impl Into<String>) -> Self {
235 match self {
236 Self::Item(item) => Self::Item(item.with_shortcut(shortcut)),
237 Self::Separator => Self::Separator,
238 }
239 }
240
241 #[must_use]
273 pub fn with_enabled(self, enabled: bool) -> Self {
274 match self {
275 Self::Item(item) => Self::Item(item.with_enabled(enabled)),
276 Self::Separator => Self::Separator,
277 }
278 }
279}
280
281impl From<ContextMenuItem> for ContextMenuEntry {
282 fn from(item: ContextMenuItem) -> Self {
283 Self::Item(item)
284 }
285}
286
287#[cfg(target_os = "macos")]
288const UNDO_SHORTCUT: &str = "⌘Z";
289#[cfg(not(target_os = "macos"))]
290const UNDO_SHORTCUT: &str = "Ctrl+Z";
291
292#[cfg(target_os = "macos")]
293const REDO_SHORTCUT: &str = "⇧⌘Z";
294#[cfg(not(target_os = "macos"))]
295const REDO_SHORTCUT: &str = "Ctrl+Y";
296
297#[cfg(target_os = "macos")]
298const CUT_SHORTCUT: &str = "⌘X";
299#[cfg(not(target_os = "macos"))]
300const CUT_SHORTCUT: &str = "Ctrl+X";
301
302#[cfg(target_os = "macos")]
303const COPY_SHORTCUT: &str = "⌘C";
304#[cfg(not(target_os = "macos"))]
305const COPY_SHORTCUT: &str = "Ctrl+C";
306
307#[cfg(target_os = "macos")]
308const PASTE_SHORTCUT: &str = "⌘V";
309#[cfg(not(target_os = "macos"))]
310const PASTE_SHORTCUT: &str = "Ctrl+V";
311
312#[cfg(target_os = "macos")]
313const SELECT_ALL_SHORTCUT: &str = "⌘A";
314#[cfg(not(target_os = "macos"))]
315const SELECT_ALL_SHORTCUT: &str = "Ctrl+A";
316
317#[derive(Debug, Clone, Copy, Default)]
318pub(crate) struct MenuState {
319 pub(crate) can_undo: bool,
320 pub(crate) can_redo: bool,
321 pub(crate) has_selection: bool,
322 pub(crate) has_content: bool,
323 pub(crate) reveal_in_file_manager_enabled: bool,
324}
325
326#[derive(Debug, Clone)]
327enum MenuEntry {
328 Item { label: String, shortcut: String, message: Option<Message> },
329 Separator,
330}
331
332impl MenuEntry {
333 #[cfg(test)]
334 fn label(&self) -> Option<&str> {
335 match self {
336 Self::Item { label, .. } => Some(label),
337 Self::Separator => None,
338 }
339 }
340}
341
342fn custom_entries(entries: &[ContextMenuEntry]) -> Vec<MenuEntry> {
343 entries
344 .iter()
345 .map(|entry| match entry {
346 ContextMenuEntry::Item(item) => MenuEntry::Item {
347 label: item.label.clone(),
348 shortcut: item.shortcut.clone().unwrap_or_default(),
349 message: item
350 .enabled
351 .then(|| Message::CustomContextMenuAction(item.id.clone())),
352 },
353 ContextMenuEntry::Separator => MenuEntry::Separator,
354 })
355 .collect()
356}
357
358fn default_entries(
359 state: MenuState,
360 translations: &Translations,
361) -> Vec<MenuEntry> {
362 let mut entries = if state.reveal_in_file_manager_enabled {
363 vec![
364 MenuEntry::Item {
365 label: translations.context_menu_reveal_in_file_manager(),
366 shortcut: String::new(),
367 message: Some(Message::RevealInFileManager),
368 },
369 MenuEntry::Separator,
370 ]
371 } else {
372 Vec::new()
373 };
374 entries.extend([
375 MenuEntry::Item {
376 label: translations.context_menu_undo(),
377 shortcut: UNDO_SHORTCUT.to_string(),
378 message: state.can_undo.then_some(Message::Undo),
379 },
380 MenuEntry::Item {
381 label: translations.context_menu_redo(),
382 shortcut: REDO_SHORTCUT.to_string(),
383 message: state.can_redo.then_some(Message::Redo),
384 },
385 MenuEntry::Separator,
386 MenuEntry::Item {
387 label: translations.context_menu_cut(),
388 shortcut: CUT_SHORTCUT.to_string(),
389 message: state.has_selection.then_some(Message::Cut),
390 },
391 MenuEntry::Item {
392 label: translations.context_menu_copy(),
393 shortcut: COPY_SHORTCUT.to_string(),
394 message: state.has_selection.then_some(Message::Copy),
395 },
396 MenuEntry::Item {
397 label: translations.context_menu_paste(),
398 shortcut: PASTE_SHORTCUT.to_string(),
399 message: Some(Message::Paste(String::new())),
400 },
401 MenuEntry::Separator,
402 MenuEntry::Item {
403 label: translations.context_menu_select_all(),
404 shortcut: SELECT_ALL_SHORTCUT.to_string(),
405 message: state.has_content.then_some(Message::SelectAll),
406 },
407 ]);
408 entries
409}
410
411fn build_entries(
412 custom: &[ContextMenuEntry],
413 default_context_menu_enabled: bool,
414 state: MenuState,
415 translations: &Translations,
416) -> Vec<MenuEntry> {
417 let mut entries = custom_entries(custom);
418 if default_context_menu_enabled {
419 if !entries.is_empty() {
420 entries.push(MenuEntry::Separator);
421 }
422 entries.extend(default_entries(state, translations));
423 }
424 entries
425}
426
427pub(crate) fn view(
429 custom: &[ContextMenuEntry],
430 default_context_menu_enabled: bool,
431 state: MenuState,
432 translations: Translations,
433) -> Element<'static, Message> {
434 let items = build_entries(
435 custom,
436 default_context_menu_enabled,
437 state,
438 &translations,
439 )
440 .into_iter()
441 .map(|entry| match entry {
442 MenuEntry::Item { label, shortcut, message } => {
443 menu_item(label, shortcut, message)
444 }
445 MenuEntry::Separator => separator(),
446 })
447 .collect::<Vec<_>>();
448
449 container(column(items).spacing(1).padding(4))
450 .width(Length::Fixed(MENU_WIDTH))
451 .style(|theme: &Theme| {
452 let palette = theme.extended_palette();
453 container::Style {
454 background: Some(Background::Color(
455 palette.background.weak.color,
456 )),
457 text_color: Some(palette.background.weak.text),
458 border: Border {
459 color: palette.background.strong.color,
460 width: 1.0,
461 radius: 6.0.into(),
462 },
463 shadow: Shadow {
464 color: Color::BLACK.scale_alpha(0.35),
465 offset: Vector::new(0.0, 4.0),
466 blur_radius: 14.0,
467 },
468 ..container::Style::default()
469 }
470 })
471 .into()
472}
473
474fn menu_item(
475 label: String,
476 shortcut: String,
477 message: Option<Message>,
478) -> Element<'static, Message> {
479 let enabled = message.is_some();
480 let content = row![
481 text(label).size(13),
482 Space::new().width(Length::Fill),
483 text(shortcut).size(12),
484 ]
485 .align_y(iced::Alignment::Center);
486
487 button(content)
488 .width(Length::Fill)
489 .padding([6, 9])
490 .on_press_maybe(message)
491 .style(move |theme: &Theme, status| {
492 let palette = theme.extended_palette();
493 let text_color = if enabled {
494 palette.background.weak.text
495 } else {
496 palette.background.weak.text.scale_alpha(0.35)
497 };
498 let background = matches!(
499 status,
500 button::Status::Hovered | button::Status::Pressed
501 )
502 .then_some(Background::Color(palette.background.strong.color));
503
504 button::Style {
505 background,
506 text_color,
507 border: Border { radius: 4.0.into(), ..Border::default() },
508 ..button::Style::default()
509 }
510 })
511 .into()
512}
513
514fn separator() -> Element<'static, Message> {
515 let line =
516 container(Space::new().width(Length::Fill).height(Length::Fixed(1.0)))
517 .style(|theme: &Theme| {
518 let palette = theme.extended_palette();
519 container::Style {
520 background: Some(Background::Color(
521 palette.background.strong.color,
522 )),
523 ..container::Style::default()
524 }
525 });
526
527 container(line).padding([3, 7]).into()
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533 use crate::{ContextMenuEntry, ContextMenuItem, Language, Translations};
534
535 #[test]
536 fn test_custom_context_menu_action_message_preserves_id() {
537 let entries = build_entries(
538 &[ContextMenuEntry::Item(ContextMenuItem::new(
539 "refactor.extract",
540 "Extract function",
541 ))],
542 false,
543 MenuState::default(),
544 &Translations::default(),
545 );
546
547 assert!(matches!(
548 &entries[0],
549 MenuEntry::Item {
550 message: Some(Message::CustomContextMenuAction(id)),
551 ..
552 }
553 if id == "refactor.extract"
554 ));
555 }
556
557 #[test]
558 fn test_custom_entries_precede_default_entries() {
559 let entries = build_entries(
560 &[ContextMenuEntry::item("custom.format", "Format document")],
561 true,
562 MenuState::default(),
563 &Translations::default(),
564 );
565
566 assert_eq!(entries[0].label(), Some("Format document"));
567 assert!(matches!(entries[1], MenuEntry::Separator));
568 assert_eq!(entries[2].label(), Some("Undo"));
569 }
570
571 #[test]
572 fn test_context_menu_uses_selected_language() {
573 let translations = Translations::new(Language::ChineseSimplified);
574 let entries = default_entries(MenuState::default(), &translations);
575
576 assert_eq!(entries[0].label(), Some("撤消"));
577 assert_eq!(entries[1].label(), Some("恢复"));
578 assert_eq!(entries[3].label(), Some("剪切"));
579 assert_eq!(entries[4].label(), Some("复制"));
580 assert_eq!(entries[5].label(), Some("粘贴"));
581 assert_eq!(entries[7].label(), Some("选择全部"));
582
583 let custom = custom_entries(&[ContextMenuEntry::item(
584 "custom.format",
585 "Format document",
586 )]);
587 assert_eq!(custom[0].label(), Some("Format document"));
588 }
589
590 #[test]
591 fn test_reveal_in_file_manager_entry_emits_request() {
592 let translations = Translations::new(Language::English);
593 let entries = build_entries(
594 &[],
595 true,
596 MenuState {
597 reveal_in_file_manager_enabled: true,
598 ..MenuState::default()
599 },
600 &translations,
601 );
602
603 assert!(matches!(
604 &entries[0],
605 MenuEntry::Item { label, shortcut, message }
606 if label == &translations.context_menu_reveal_in_file_manager()
607 && shortcut.is_empty()
608 && matches!(message, Some(Message::RevealInFileManager))
609 ));
610 assert!(matches!(entries[1], MenuEntry::Separator));
611 assert_eq!(entries[2].label(), Some("Undo"));
612 }
613
614 #[test]
615 fn test_reveal_in_file_manager_respects_default_menu_toggle() {
616 let entries = build_entries(
617 &[],
618 false,
619 MenuState {
620 reveal_in_file_manager_enabled: true,
621 ..MenuState::default()
622 },
623 &Translations::default(),
624 );
625
626 assert!(entries.is_empty());
627 }
628}