Skip to main content

gpui_deck/
menu.rs

1//! Shared commands, navigation, activation, and semantics for menu triggers.
2
3use gpui::{
4    Anchor, AnyElement, App, AppContext as _, Context, Entity, EventEmitter, FocusHandle,
5    InteractiveElement as _, IntoElement, KeyBinding, KeyDownEvent, ParentElement, Pixels, Point,
6    RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement as _, StyleRefinement,
7    Styled, Subscription, Toggled, WeakEntity, Window, div, prelude::FluentBuilder as _, px,
8};
9
10use crate::{
11    CheckboxState, Direction, ElementExt as _, Popover, PopoverState, Popup, StyledExt as _,
12    TestSupportExt as _,
13    a11y_disabled::A11yDisabledExt as _,
14    actions::{
15        Cancel, Confirm, SelectDown, SelectFirst, SelectLast, SelectLeft, SelectRight, SelectUp,
16    },
17    scroll_area::RevealViewport,
18};
19
20const CONTEXT: &str = "Menu";
21
22pub(crate) fn init(cx: &mut App) {
23    cx.bind_keys([
24        KeyBinding::new("down", SelectDown, Some(CONTEXT)),
25        KeyBinding::new("up", SelectUp, Some(CONTEXT)),
26        KeyBinding::new("home", SelectFirst, Some(CONTEXT)),
27        KeyBinding::new("end", SelectLast, Some(CONTEXT)),
28        KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
29        KeyBinding::new("right", SelectRight, Some(CONTEXT)),
30        KeyBinding::new("escape", Cancel, Some(CONTEXT)),
31        KeyBinding::new("enter", Confirm { secondary: false }, Some(CONTEXT)),
32        KeyBinding::new("space", Confirm { secondary: false }, Some(CONTEXT)),
33    ]);
34}
35
36/// One command in a menu's fixed, ordered collection. Values must be unique.
37#[derive(Clone, Debug)]
38pub struct MenuItem {
39    value: SharedString,
40    label: SharedString,
41    disabled: bool,
42    submenu: Option<Entity<MenuState>>,
43}
44
45impl MenuItem {
46    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
47        Self {
48            value: value.into(),
49            label: label.into(),
50            disabled: false,
51            submenu: None,
52        }
53    }
54
55    pub fn disabled(mut self, disabled: bool) -> Self {
56        self.disabled = disabled;
57        self
58    }
59
60    pub fn value(&self) -> &SharedString {
61        &self.value
62    }
63
64    pub fn label(&self) -> &SharedString {
65        &self.label
66    }
67
68    pub fn is_disabled(&self) -> bool {
69        self.disabled
70    }
71
72    /// Makes this row open a child menu. A child belongs to exactly one parent;
73    /// its leaf command values are emitted by the top-level [`MenuState`].
74    /// Render this row with [`MenuSubmenu`] so its child content stays mounted.
75    pub fn submenu(mut self, submenu: &Entity<MenuState>) -> Self {
76        self.submenu = Some(submenu.clone());
77        self
78    }
79
80    pub fn submenu_state(&self) -> Option<&Entity<MenuState>> {
81        self.submenu.as_ref()
82    }
83}
84
85/// Emitted once by the top-level menu after a leaf command closes the entire
86/// menu chain and restores focus. Submenu trigger rows never emit commands.
87#[derive(Clone, Debug, Eq, PartialEq)]
88pub enum MenuEvent {
89    Action(SharedString),
90}
91
92/// Retained commands and cursor for one non-modal menu in one window.
93///
94/// The nested [`PopoverState`] exclusively owns open, disabled, dismissal, and
95/// focus-restoration behavior. The menu adds enabled-item navigation and command
96/// events. It never stores a selected value: repeated activation of the same
97/// command emits an event each time.
98///
99/// Keep its matching [`crate::DropdownMenu`], [`crate::ContextMenu`],
100/// [`crate::MenubarMenu`] or [`MenuSubmenu`] mounted while closed and host the app
101/// in [`crate::Root`]. Empty and all-disabled collections may open, but cannot
102/// emit commands. Menu options are not individual Tab stops.
103pub struct MenuState {
104    items: Vec<MenuItem>,
105    highlighted: Option<usize>,
106    scroll: ScrollHandle,
107    reveal_highlight: bool,
108    pub(crate) popover: Entity<PopoverState>,
109    position: Option<Point<Pixels>>,
110    focus: FocusHandle,
111    content_focus: FocusHandle,
112    _popover_subscription: Subscription,
113    _submenu_subscriptions: Vec<Subscription>,
114    submenu_focus_subscriptions: Vec<Subscription>,
115    parent: Option<WeakEntity<MenuState>>,
116    direction: Direction,
117}
118
119impl MenuState {
120    pub fn new(items: impl IntoIterator<Item = MenuItem>, cx: &mut Context<Self>) -> Self {
121        let items: Vec<_> = items.into_iter().collect();
122        for (index, item) in items.iter().enumerate() {
123            assert!(
124                items[..index].iter().all(|other| other.value != item.value),
125                "MenuItem values must be unique"
126            );
127        }
128        let content_focus = cx.focus_handle();
129        let popover = cx.new(|cx| PopoverState::new(cx).with_initial_focus(&content_focus));
130        let focus = popover.read(cx).focus_handle().clone();
131        let subscription = cx.observe(&popover, |state, popover, cx| {
132            if popover.read(cx).is_open() {
133                // Native Button activation opens Popover directly. Preserve a
134                // cursor already chosen by ArrowUp/Down on the trigger.
135                if state.highlighted.is_none() {
136                    state.highlighted = state.items.iter().position(|item| !item.disabled);
137                    state.reveal_highlight = true;
138                }
139            } else {
140                state.highlighted = None;
141                state.reveal_highlight = false;
142                state.position = None;
143            }
144            cx.notify();
145        });
146        let parent = cx.weak_entity();
147        let submenu_subscriptions = items
148            .iter()
149            .filter_map(|item| item.submenu.as_ref())
150            .map(|submenu| {
151                submenu.update(cx, |state, _| {
152                    assert!(
153                        state
154                            .parent
155                            .as_ref()
156                            .and_then(WeakEntity::upgrade)
157                            .is_none(),
158                        "A submenu can belong to only one MenuItem"
159                    );
160                    state.parent = Some(parent.clone());
161                });
162                cx.observe(submenu, |_, _, cx| cx.notify())
163            })
164            .collect();
165        Self {
166            items,
167            highlighted: None,
168            scroll: ScrollHandle::new(),
169            reveal_highlight: false,
170            popover,
171            position: None,
172            focus,
173            content_focus,
174            _popover_subscription: subscription,
175            _submenu_subscriptions: submenu_subscriptions,
176            submenu_focus_subscriptions: Vec::new(),
177            parent: None,
178            direction: Direction::Ltr,
179        }
180    }
181
182    pub fn items(&self) -> &[MenuItem] {
183        &self.items
184    }
185
186    pub fn highlighted_index(&self) -> Option<usize> {
187        self.highlighted
188    }
189
190    pub fn is_open(&self, cx: &App) -> bool {
191        self.popover.read(cx).is_open()
192    }
193
194    pub fn is_disabled(&self, cx: &App) -> bool {
195        self.popover.read(cx).is_disabled()
196    }
197
198    /// The button or context target's focus handle.
199    pub fn focus_handle(&self) -> &FocusHandle {
200        &self.focus
201    }
202
203    /// The menu's focus handle; keyboard navigation moves its active descendant.
204    pub fn content_focus_handle(&self) -> &FocusHandle {
205        &self.content_focus
206    }
207
208    fn bind_submenu_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
209        // Native accessibility focus can move to a submenu row independently
210        // of the menu's current active descendant.
211        if !self.submenu_focus_subscriptions.is_empty() {
212            return;
213        }
214        self.submenu_focus_subscriptions = self
215            .items
216            .iter()
217            .enumerate()
218            .filter_map(|(index, item)| {
219                let focus = item.submenu.as_ref()?.read(cx).focus.clone();
220                Some(cx.on_focus(&focus, window, move |_, window, cx| {
221                    cx.defer_in(window, move |state, window, cx| {
222                        if state.items[index]
223                            .submenu
224                            .as_ref()
225                            .is_some_and(|submenu| submenu.read(cx).focus.is_focused(window))
226                        {
227                            state.highlight(index, true, window, cx);
228                        }
229                    });
230                }))
231            })
232            .collect();
233    }
234
235    pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
236        if self.is_disabled(cx) == disabled {
237            return;
238        }
239        if disabled {
240            self.highlighted = None;
241            self.close_descendants(None, window, cx);
242        }
243        self.popover
244            .update(cx, |state, cx| state.set_disabled(disabled, window, cx));
245        cx.notify();
246    }
247
248    /// Opens with the first enabled command highlighted.
249    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
250        self.open_at(false, window, cx);
251    }
252
253    /// Closes and restores the trigger while focus still belongs to the menu.
254    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
255        self.close_descendants(None, window, cx);
256        self.close_local(window, cx);
257    }
258
259    fn close_local(&mut self, window: &mut Window, cx: &mut Context<Self>) {
260        if !self.is_open(cx) {
261            return;
262        }
263        self.highlighted = None;
264        self.position = None;
265        self.popover.update(cx, |state, cx| state.close(window, cx));
266        cx.notify();
267    }
268
269    fn close_descendants(
270        &self,
271        keep: Option<usize>,
272        window: &mut Window,
273        cx: &mut Context<Self>,
274    ) -> bool {
275        let mut closed = false;
276        for (index, item) in self.items.iter().enumerate() {
277            if keep != Some(index)
278                && let Some(submenu) = &item.submenu
279                && submenu.read(cx).is_open(cx)
280            {
281                submenu.update(cx, |menu, cx| menu.close(window, cx));
282                closed = true;
283            }
284        }
285        closed
286    }
287
288    fn open_submenu(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) -> bool {
289        if !self.is_open(cx) || self.is_disabled(cx) {
290            return false;
291        }
292        let Some(item) = self.items.get(index).filter(|item| !item.disabled) else {
293            return false;
294        };
295        let Some(submenu) = item.submenu.clone() else {
296            return false;
297        };
298        if submenu.read(cx).is_disabled(cx) {
299            return false;
300        }
301        self.close_descendants(Some(index), window, cx);
302        self.highlighted = Some(index);
303        submenu.update(cx, |menu, cx| menu.open(window, cx));
304        let focus = submenu.read(cx).content_focus_handle().clone();
305        focus.focus(window, cx);
306        cx.notify();
307        window.refresh();
308        true
309    }
310
311    fn close_to_parent(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
312        let Some(parent) = self.parent.as_ref().and_then(WeakEntity::upgrade) else {
313            return false;
314        };
315        self.close(window, cx);
316        let focus = parent.read(cx).content_focus.clone();
317        focus.focus(window, cx);
318        true
319    }
320
321    fn horizontal(&mut self, expand: bool, window: &mut Window, cx: &mut Context<Self>) {
322        // Nested popups share the dispatch ancestry. Only the focused menu
323        // handles a submenu key; an unhandled root key can reach Menubar.
324        if !self.owns_focus(window, cx) {
325            cx.propagate();
326            return;
327        }
328        let handled = if expand {
329            self.highlighted
330                .is_some_and(|index| self.open_submenu(index, window, cx))
331        } else {
332            self.close_to_parent(window, cx)
333        };
334        if !handled {
335            cx.propagate();
336        }
337    }
338
339    fn cancel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
340        if !self.close_to_parent(window, cx) {
341            self.close(window, cx);
342        }
343    }
344
345    fn tab(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
346        if let Some(parent) = self.parent.as_ref().and_then(WeakEntity::upgrade) {
347            self.close_local(window, cx);
348            parent.update(cx, |menu, cx| menu.tab(forward, window, cx));
349        } else {
350            self.popover
351                .update(cx, |popover, cx| popover.tab(forward, window, cx));
352        }
353    }
354
355    fn complete_action(
356        &mut self,
357        value: SharedString,
358        window: &mut Window,
359        cx: &mut Context<Self>,
360    ) {
361        // The active descendant branch has already closed. Closing just this
362        // level avoids updating the child currently reporting its command.
363        self.close_local(window, cx);
364        if let Some(parent) = self.parent.as_ref().and_then(WeakEntity::upgrade) {
365            parent.update(cx, |menu, cx| menu.complete_action(value, window, cx));
366        } else {
367            cx.emit(MenuEvent::Action(value));
368        }
369    }
370
371    pub(crate) fn open_at(&mut self, last: bool, window: &mut Window, cx: &mut Context<Self>) {
372        if self.is_disabled(cx) || self.is_open(cx) {
373            return;
374        }
375        self.position = None;
376        self.highlighted = self.edge(last);
377        self.reveal_highlight = true;
378        self.popover.update(cx, |state, cx| state.open(window, cx));
379        cx.notify();
380    }
381
382    pub(crate) fn position(&self) -> Option<Point<Pixels>> {
383        self.position
384    }
385
386    // A context request can move an already open menu without toggling it off.
387    pub(crate) fn open_at_position(
388        &mut self,
389        position: Point<Pixels>,
390        window: &mut Window,
391        cx: &mut Context<Self>,
392    ) {
393        if self.is_disabled(cx) {
394            return;
395        }
396        self.close_descendants(None, window, cx);
397        self.position = Some(position);
398        self.highlighted = self.edge(false);
399        self.reveal_highlight = true;
400        self.popover.update(cx, |state, cx| state.open(window, cx));
401        self.content_focus.focus(window, cx);
402        cx.notify();
403        window.refresh();
404    }
405
406    fn edge(&self, last: bool) -> Option<usize> {
407        if last {
408            self.items.iter().rposition(|item| !item.disabled)
409        } else {
410            self.items.iter().position(|item| !item.disabled)
411        }
412    }
413
414    fn move_cursor(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
415        if self.is_disabled(cx) || !self.is_open(cx) || self.items.is_empty() {
416            return;
417        }
418        let count = self.items.len();
419        let start = self
420            .highlighted
421            .unwrap_or(if forward { count - 1 } else { 0 });
422        for distance in 1..=count {
423            let index = if forward {
424                (start + distance) % count
425            } else {
426                (start + count - distance) % count
427            };
428            if !self.items[index].disabled {
429                self.highlight(index, true, window, cx);
430                break;
431            }
432        }
433    }
434
435    fn move_to_edge(&mut self, last: bool, window: &mut Window, cx: &mut Context<Self>) {
436        if let Some(index) = self.edge(last) {
437            self.highlight(index, true, window, cx);
438        }
439    }
440
441    fn highlight(
442        &mut self,
443        index: usize,
444        reveal: bool,
445        window: &mut Window,
446        cx: &mut Context<Self>,
447    ) {
448        if !self.is_open(cx)
449            || self.is_disabled(cx)
450            || self.items.get(index).is_none_or(|item| item.disabled)
451            || (self.highlighted == Some(index) && !reveal)
452        {
453            return;
454        }
455        self.highlighted = Some(index);
456        self.reveal_highlight = reveal;
457        if self.close_descendants(Some(index), window, cx) {
458            self.content_focus.focus(window, cx);
459        }
460        cx.notify();
461        window.refresh();
462    }
463
464    fn typeahead(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
465        if !self.owns_focus(window, cx) {
466            return;
467        }
468        let modifiers = event.keystroke.modifiers;
469        if modifiers.control || modifiers.alt || modifiers.platform || modifiers.function {
470            return;
471        }
472        let text = event
473            .keystroke
474            .key_char
475            .as_deref()
476            .unwrap_or(&event.keystroke.key);
477        let mut characters = text.chars();
478        let Some(character) = characters.next() else {
479            return;
480        };
481        if characters.next().is_some() || character.is_control() || character.is_whitespace() {
482            return;
483        }
484        if !self.is_open(cx) || self.is_disabled(cx) || self.items.is_empty() {
485            return;
486        }
487        let prefix = character.to_lowercase().collect::<String>();
488        let count = self.items.len();
489        let start = self.highlighted.unwrap_or(count - 1);
490        for distance in 1..=count {
491            let index = (start + distance) % count;
492            let item = &self.items[index];
493            if !item.disabled && item.label.to_lowercase().starts_with(&prefix) {
494                self.highlight(index, true, window, cx);
495                cx.stop_propagation();
496                break;
497            }
498        }
499    }
500
501    fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
502        if !self.is_open(cx) || self.is_disabled(cx) {
503            return;
504        }
505        let Some(item) = self.items.get(index).filter(|item| !item.disabled) else {
506            return;
507        };
508        let value = item.value.clone();
509        if item.submenu.is_some() {
510            self.open_submenu(index, window, cx);
511            return;
512        }
513        // Subscribers may immediately focus another view or open a Dialog.
514        // Close first so this menu cannot steal that new focus afterward.
515        self.close_descendants(None, window, cx);
516        self.complete_action(value, window, cx);
517    }
518
519    fn confirm(&mut self, window: &mut Window, cx: &mut Context<Self>) {
520        if let Some(index) = self.highlighted {
521            self.activate(index, window, cx);
522        }
523    }
524
525    fn owns_focus(&self, window: &Window, cx: &App) -> bool {
526        self.content_focus.is_focused(window)
527            || self
528                .items
529                .iter()
530                .filter_map(|item| item.submenu.as_ref())
531                .any(|submenu| submenu.read(cx).focus.is_focused(window))
532    }
533}
534
535impl EventEmitter<MenuEvent> for MenuState {}
536
537pub(crate) fn menu_content(
538    menu: &Entity<MenuState>,
539    label: Option<SharedString>,
540    children: Option<AnyElement>,
541    window: &Window,
542    cx: &mut App,
543) -> impl IntoElement + use<> {
544    menu_content_with_direction(menu, label, children, Direction::current(cx), window, cx)
545}
546
547pub(crate) fn menu_content_with_direction(
548    menu: &Entity<MenuState>,
549    label: Option<SharedString>,
550    children: Option<AnyElement>,
551    direction: Direction,
552    window: &Window,
553    cx: &mut App,
554) -> impl IntoElement + use<> {
555    menu.update(cx, |state, _| state.direction = direction);
556    let state = menu.read(cx);
557    let focus = state.content_focus.clone();
558    let scroll = state.scroll.clone();
559    let up = menu.clone();
560    let down = menu.clone();
561    let first = menu.clone();
562    let last = menu.clone();
563    let confirm = menu.clone();
564    let typeahead = menu.clone();
565    let left = menu.clone();
566    let right = menu.clone();
567    let cancel = menu.clone();
568    let tab = menu.clone();
569    let previous = menu.clone();
570
571    div()
572        .id(("menu", menu.entity_id()))
573        .test_support()
574        .role(Role::Menu)
575        .when_some(label, |this, label| this.aria_label(label))
576        .track_focus(&focus)
577        .key_context(CONTEXT)
578        .on_action(move |_: &SelectUp, window, cx| {
579            up.update(cx, |state, cx| state.move_cursor(false, window, cx));
580        })
581        .on_action(move |_: &SelectDown, window, cx| {
582            down.update(cx, |state, cx| state.move_cursor(true, window, cx));
583        })
584        .on_action(move |_: &SelectFirst, window, cx| {
585            first.update(cx, |state, cx| state.move_to_edge(false, window, cx));
586        })
587        .on_action(move |_: &SelectLast, window, cx| {
588            last.update(cx, |state, cx| state.move_to_edge(true, window, cx));
589        })
590        .on_action(move |_: &Confirm, window, cx| {
591            confirm.update(cx, |state, cx| state.confirm(window, cx));
592        })
593        .on_action(move |_: &SelectLeft, window, cx| {
594            left.update(cx, |state, cx| {
595                state.horizontal(direction.is_rtl(), window, cx)
596            });
597        })
598        .on_action(move |_: &SelectRight, window, cx| {
599            right.update(cx, |state, cx| {
600                state.horizontal(!direction.is_rtl(), window, cx)
601            });
602        })
603        .on_action(move |_: &Cancel, window, cx| {
604            cancel.update(cx, |state, cx| state.cancel(window, cx));
605        })
606        .on_action(move |_: &crate::root::Tab, window, cx| {
607            tab.update(cx, |state, cx| state.tab(true, window, cx));
608        })
609        .on_action(move |_: &crate::root::TabPrev, window, cx| {
610            previous.update(cx, |state, cx| state.tab(false, window, cx));
611        })
612        .on_key_down(move |event, window, cx| {
613            typeahead.update(cx, |state, cx| state.typeahead(event, window, cx));
614        })
615        .child(RevealViewport::popup(
616            "menu-viewport",
617            Popup::available_height(window),
618            scroll,
619            children,
620        ))
621}
622
623/// One command's application-styled surface, with library-owned interaction.
624///
625/// Highlighted options expose the menu's active descendant without becoming
626/// individual Tab stops. Read [`MenuState::highlighted_index`] to style
627/// the keyboard/pointer cursor; disabled state comes from its fixed item.
628#[derive(IntoElement)]
629pub struct MenuOption {
630    state: Entity<MenuState>,
631    index: usize,
632    checked: Option<Toggled>,
633    role: Role,
634    style: StyleRefinement,
635    children: Vec<AnyElement>,
636}
637
638impl MenuOption {
639    pub fn new(state: &Entity<MenuState>, index: usize) -> Self {
640        Self {
641            state: state.clone(),
642            index,
643            checked: None,
644            role: Role::MenuItem,
645            style: StyleRefinement::default(),
646            children: Vec::new(),
647        }
648    }
649
650    /// Presents this command as a checkbox menu item with an application-owned value.
651    ///
652    /// Without this method the option is an ordinary menu item with no checked
653    /// metadata. The value is rendered only; activation still closes the menu,
654    /// restores focus, and emits [`MenuEvent::Action`]. Update application state
655    /// in that handler and render the new value back here. This adds no item
656    /// focus stop and does not change the menu's highlighted cursor.
657    pub fn checked(self, checked: bool) -> Self {
658        self.check_state(if checked {
659            CheckboxState::Checked
660        } else {
661            CheckboxState::Unchecked
662        })
663    }
664
665    /// Exposes a controlled checkbox value, including a mixed selection.
666    pub fn check_state(mut self, state: CheckboxState) -> Self {
667        self.role = Role::MenuItemCheckBox;
668        self.checked = Some(match state {
669            CheckboxState::Unchecked => Toggled::False,
670            CheckboxState::Checked => Toggled::True,
671            CheckboxState::Indeterminate => Toggled::Mixed,
672        });
673        self
674    }
675
676    /// Exposes a radio menu item. Render each peer from one application-owned
677    /// value, for example `option.radio_checked(current == item.value())`, and
678    /// update that value from [`MenuEvent::Action`]. Group related peers in a
679    /// named `Role::Group` surface; this adds no independent focus or selection.
680    pub fn radio_checked(mut self, checked: bool) -> Self {
681        self.role = Role::MenuItemRadio;
682        self.checked = Some(if checked {
683            Toggled::True
684        } else {
685            Toggled::False
686        });
687        self
688    }
689}
690
691impl Styled for MenuOption {
692    fn style(&mut self) -> &mut StyleRefinement {
693        &mut self.style
694    }
695}
696
697impl ParentElement for MenuOption {
698    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
699        self.children.extend(elements);
700    }
701}
702
703impl RenderOnce for MenuOption {
704    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
705        let state = self.state.read(cx);
706        let item = state
707            .items
708            .get(self.index)
709            .expect("MenuOption index is out of bounds");
710        let disabled = state.is_disabled(cx) || item.disabled;
711        let highlighted = state.is_open(cx) && state.highlighted == Some(self.index);
712        let reveal = highlighted && state.reveal_highlight;
713        let label = item.label.clone();
714        let submenu = item.submenu.clone();
715        let submenu_focus = submenu
716            .as_ref()
717            .map(|submenu| submenu.read(cx).focus.clone().tab_stop(false));
718        let expanded = submenu.as_ref().map(|submenu| submenu.read(cx).is_open(cx));
719        let index = self.index;
720        let hover = self.state.clone();
721        let reveal_state = self.state.clone();
722        let activate = self.state.clone();
723        div()
724            .id(("menu-option", index))
725            .test_support()
726            .role(if submenu.is_some() {
727                Role::MenuItem
728            } else {
729                self.role
730            })
731            .aria_label(label)
732            .when_some(
733                self.checked.filter(|_| submenu.is_none()),
734                |this, checked| this.aria_toggled(checked),
735            )
736            .when_some(submenu_focus, |this, focus| this.track_focus(&focus))
737            .when_some(expanded, |this, expanded| this.aria_expanded(expanded))
738            .when(highlighted, |this| this.aria_active_descendant())
739            .when(reveal, |this| {
740                this.on_prepaint(move |bounds, window, cx| {
741                    reveal_state.update(cx, |state, _| state.reveal_highlight = false);
742                    window.request_autoscroll(bounds);
743                })
744            })
745            .when(!disabled, |this| {
746                this.on_hover(move |hovered, window, cx| {
747                    if *hovered {
748                        hover.update(cx, |state, cx| {
749                            state.highlight(index, false, window, cx);
750                            state.open_submenu(index, window, cx);
751                        });
752                    }
753                })
754                .on_click(move |_, window, cx| {
755                    activate.update(cx, |state, cx| state.activate(index, window, cx));
756                })
757            })
758            .children(self.children)
759            .refine_style(&self.style)
760            .a11y_disabled(disabled)
761    }
762}
763
764/// One submenu row and its nested command surface.
765///
766/// The corresponding [`MenuItem`] must declare its child with
767/// [`MenuItem::submenu`]. The trigger is a normal active-descendant menu option;
768/// hovering or activating it opens the child. The expanding horizontal arrow
769/// opens it, and the opposite arrow or Escape returns to the parent's cursor.
770/// A leaf command closes the entire chain before emitting one root event.
771#[derive(IntoElement)]
772pub struct MenuSubmenu {
773    parent: Entity<MenuState>,
774    index: usize,
775    trigger: MenuOption,
776    content: Option<AnyElement>,
777    anchor: Option<Anchor>,
778    offset: Pixels,
779    style: StyleRefinement,
780}
781
782impl MenuSubmenu {
783    pub fn new(parent: &Entity<MenuState>, index: usize) -> Self {
784        Self {
785            parent: parent.clone(),
786            index,
787            trigger: MenuOption::new(parent, index),
788            content: None,
789            anchor: None,
790            offset: px(0.),
791            style: StyleRefinement::default(),
792        }
793    }
794
795    pub fn trigger(mut self, build: impl FnOnce(MenuOption) -> MenuOption) -> Self {
796        self.trigger = build(self.trigger);
797        self
798    }
799
800    pub fn content(mut self, content: impl IntoElement) -> Self {
801        self.content = Some(content.into_any_element());
802        self
803    }
804
805    /// Overrides the default side anchor (right in LTR, left in RTL).
806    pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
807        self.anchor = Some(anchor.into());
808        self
809    }
810
811    pub fn offset(mut self, offset: Pixels) -> Self {
812        self.offset = offset;
813        self
814    }
815}
816
817impl Styled for MenuSubmenu {
818    fn style(&mut self) -> &mut StyleRefinement {
819        &mut self.style
820    }
821}
822
823impl RenderOnce for MenuSubmenu {
824    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
825        self.parent
826            .update(cx, |parent, cx| parent.bind_submenu_focus(window, cx));
827        let parent = self.parent.read(cx);
828        let item = parent
829            .items
830            .get(self.index)
831            .expect("MenuSubmenu index is out of bounds");
832        let submenu = item
833            .submenu
834            .as_ref()
835            .expect("MenuSubmenu requires a MenuItem with a submenu")
836            .clone();
837        let label = item.label.clone();
838        let direction = parent.direction;
839        let popover = submenu.read(cx).popover.clone();
840        let anchor = self.anchor.unwrap_or_else(|| {
841            if direction.is_rtl() {
842                Anchor::RightCenter
843            } else {
844                Anchor::LeftCenter
845            }
846        });
847        Popover::new(("menu-submenu", self.index), &popover)
848            .supplied_trigger(self.trigger)
849            .content_role(None)
850            .anchor(anchor)
851            .offset(self.offset)
852            .content(menu_content_with_direction(
853                &submenu,
854                Some(label),
855                self.content,
856                direction,
857                window,
858                cx,
859            ))
860            .refine_style(&self.style)
861    }
862}