Skip to main content

zaxis/components/
context_menu.rs

1//! Pointer-anchored menus built on the shared popup layer.
2use std::hash::Hash;
3
4use super::{Popup, Response, ScrollArea, Ui};
5use crate::winit::keyboard::KeyCode;
6use crate::{
7    context::{HitAction, HitRegion},
8    Id, Padding, Rect, Vec2,
9};
10
11mod access;
12mod actions;
13mod cache;
14pub(in crate::components) mod paint;
15
16/// A stable action ID is independent of its visible label. Separators have no ID.
17#[derive(Clone, Debug, PartialEq)]
18pub struct ContextMenuItem {
19    pub id: Option<Id>,
20    pub text: String,
21    pub icon: String,
22    pub icon_shapes: Vec<crate::Shape>,
23    pub left_text: String,
24    pub right_text: String,
25    pub enabled: bool,
26    /// Draws a check mark in the icon column.
27    pub checked: bool,
28    /// Draws a chevron; set by cascading menus whose item opens a submenu.
29    pub(crate) submenu: bool,
30    /// Bound to a registered action: see [`ContextMenuItem::action`].
31    pub(crate) action: bool,
32}
33
34impl ContextMenuItem {
35    pub fn new(id: impl Hash, text: impl Into<String>) -> Self {
36        Self {
37            id: Some(Id::new(id)),
38            text: text.into(),
39            icon: String::new(),
40            icon_shapes: Vec::new(),
41            left_text: String::new(),
42            right_text: String::new(),
43            enabled: true,
44            checked: false,
45            submenu: false,
46            action: false,
47        }
48    }
49    /// A row that runs a registered action. Its caption, shortcut, enabled and checked
50    /// state come from the registry on every pass; choosing it raises the action's event
51    /// (`ui.actions().triggered(id)`) and is not reported as `selected`. Pass the value the
52    /// action was declared with.
53    pub fn action(id: impl Hash) -> Self {
54        let mut item = Self::new("", "");
55        item.id = Some(crate::actions::action_id(id));
56        item.action = true;
57        item
58    }
59    pub fn separator() -> Self {
60        Self {
61            id: None,
62            text: String::new(),
63            icon: String::new(),
64            icon_shapes: Vec::new(),
65            left_text: String::new(),
66            right_text: String::new(),
67            enabled: false,
68            checked: false,
69            submenu: false,
70            action: false,
71        }
72    }
73    /// A font glyph or short symbol, in a dedicated aligned icon column.
74    pub fn icon(mut self, icon: impl Into<String>) -> Self {
75        self.icon = icon.into();
76        self.icon_shapes.clear();
77        self
78    }
79    /// Vector icon drawn in an 18 × 18 logical-pixel box, with local coordinates.
80    pub fn icon_shapes(mut self, shapes: impl IntoIterator<Item = crate::Shape>) -> Self {
81        self.icon_shapes = shapes.into_iter().collect();
82        self.icon.clear();
83        self
84    }
85    pub fn left_text(mut self, text: impl Into<String>) -> Self {
86        self.left_text = text.into();
87        self
88    }
89    pub fn right_text(mut self, text: impl Into<String>) -> Self {
90        self.right_text = text.into();
91        self
92    }
93    pub fn enabled(mut self, enabled: bool) -> Self {
94        self.enabled = enabled;
95        self
96    }
97    pub fn checked(mut self, checked: bool) -> Self {
98        self.checked = checked;
99        self
100    }
101}
102
103/// Colors inherit the current UI theme; these overrides control menu proportions
104/// and reuse the existing popup and control appearance styles.
105#[derive(Clone, Debug)]
106pub struct ContextMenuStyle {
107    pub min_width: f32,
108    pub row_height: f32,
109    pub font_size: f32,
110    pub separator_height: f32,
111    pub padding: Padding,
112    pub popup: crate::PopupStyle,
113    pub item: crate::ControlStyle,
114}
115impl ContextMenuStyle {
116    /// Sizes that are not finite and positive fall back to the defaults; padding
117    /// becomes non-negative.
118    #[track_caller]
119    pub(in crate::components) fn normalize(&mut self) {
120        use super::sanitize::{length, positive};
121        let default = Self::default();
122        self.min_width =
123            positive("ContextMenuStyle::min_width", self.min_width).unwrap_or(default.min_width);
124        self.row_height =
125            positive("ContextMenuStyle::row_height", self.row_height).unwrap_or(default.row_height);
126        self.separator_height =
127            positive("ContextMenuStyle::separator_height", self.separator_height)
128                .unwrap_or(default.separator_height);
129        self.font_size =
130            positive("ContextMenuStyle::font_size", self.font_size).unwrap_or(default.font_size);
131        self.padding.left = length("ContextMenuStyle::padding", self.padding.left);
132        self.padding.right = length("ContextMenuStyle::padding", self.padding.right);
133        self.padding.top = length("ContextMenuStyle::padding", self.padding.top);
134        self.padding.bottom = length("ContextMenuStyle::padding", self.padding.bottom);
135    }
136}
137impl Default for ContextMenuStyle {
138    fn default() -> Self {
139        Self {
140            min_width: 220.0,
141            row_height: 24.0,
142            font_size: 14.0,
143            separator_height: 9.0,
144            padding: Padding::all(4.0),
145            popup: Default::default(),
146            item: Default::default(),
147        }
148    }
149}
150
151#[derive(Clone, Copy, Debug, Default)]
152pub struct ContextMenuOutput {
153    pub open: bool,
154    pub rect: Option<Rect>,
155    /// Exactly one activation per gesture. The menu closes before returning it.
156    pub selected: Option<Id>,
157}
158
159#[derive(Default)]
160pub(crate) struct MenuState {
161    open: bool,
162    position: Vec2,
163    active: Option<Id>,
164    pointer: Option<Vec2>,
165    keyboard: bool,
166    cache: Option<cache::MenuCache>,
167    pub(crate) last_frame: u64,
168}
169
170pub struct ContextMenu<'a> {
171    source: Id,
172    items: &'a [ContextMenuItem],
173    style: ContextMenuStyle,
174    position: Option<Vec2>,
175    target: access::Target,
176}
177impl<'a> ContextMenu<'a> {
178    pub fn new(source: impl Hash, items: &'a [ContextMenuItem]) -> Self {
179        Self {
180            source: Id::new(source),
181            items,
182            style: Default::default(),
183            position: None,
184            target: access::Target::Find,
185        }
186    }
187    pub fn style(mut self, style: ContextMenuStyle) -> Self {
188        self.style = style;
189        self
190    }
191    /// Open programmatically on this pass. Omit on later passes to retain state.
192    #[track_caller]
193    pub fn open_at(mut self, position: Vec2) -> Self {
194        self.position =
195            super::sanitize::finite_vec2("ContextMenu::open_at", position).or(self.position);
196        self
197    }
198    /// Attach after building the target, in the same UI scope. Works with passive
199    /// text as well as controls, and follows deferred layout and scroll clipping.
200    /// Action IDs must be unique within this menu.
201    pub fn show(self, ui: &mut Ui<'_>, target: Response) -> ContextMenuOutput {
202        if !actions::any(self.items) {
203            return self.show_items(ui, target);
204        }
205        let items = actions::resolve(ui, self.items);
206        let menu = ContextMenu {
207            source: self.source,
208            items: &items,
209            style: self.style,
210            position: self.position,
211            target: self.target,
212        };
213        let mut output = menu.show_items(ui, target);
214        actions::raise(ui, &items, &mut output.selected);
215        output
216    }
217
218    fn show_items(mut self, ui: &mut Ui<'_>, target: Response) -> ContextMenuOutput {
219        self.style.normalize();
220        let style = &self.style;
221        let id = ui.scope.with(("context-menu", self.source, target.id));
222        let anchor_id = id.with("anchor");
223        let hit = HitRegion {
224            id: anchor_id,
225            window: ui.window,
226            rect: target.rect,
227            clip: ui.clip,
228            action: HitAction::ContextMenu,
229        };
230        if !ui.attach_tooltip_anchor(target.id, hit) {
231            ui.context.register_hit(hit);
232        }
233        let popup_id = Popup::id(ui, Id::new(id));
234        let mut state = ui
235            .context
236            .menus
237            .context_menus
238            .remove(&id)
239            .unwrap_or_default();
240        state.last_frame = ui.context.frame;
241        if ui.context.take_popup_dismissal(popup_id) {
242            state.open = false;
243        }
244        // The same secondary-click signal that `Response::secondary_clicked` reports.
245        let pointer_open = ui.context.gestures.secondary_position(anchor_id);
246        // A request from assistive technology opens the menu at the target, with the first
247        // item highlighted as the keyboard would leave it.
248        let asked = access::asked(ui, self.target, target, anchor_id, !self.items.is_empty());
249        let placed = self.position.or(pointer_open);
250        let opening = placed.or(asked);
251        if let Some(position) = opening {
252            state.position = position;
253            state.keyboard = placed.is_none();
254            state.open = ui.enabled;
255            state.active = self
256                .items
257                .iter()
258                .find(|i| i.enabled && i.id.is_some())
259                .and_then(|i| i.id);
260            ui.context.request_repaint();
261        }
262        state.open &= ui.enabled && !self.items.is_empty();
263        let mut output = ContextMenuOutput::default();
264        if state.open {
265            let pointer = ui.context.input().pointer;
266            let pointer_moved = pointer != state.pointer;
267            state.pointer = pointer;
268            if pointer_moved {
269                state.keyboard = false;
270            }
271            let cache = match state.cache.take() {
272                Some(cache) if cache.matches(self.items, style) => cache,
273                _ => cache::MenuCache::new(ui, self.items, style),
274            };
275            let enabled = &cache.enabled;
276            if !state.active.is_some_and(|id| enabled.contains(&id)) {
277                state.active = enabled.first().copied();
278            }
279            let mut reveal = false;
280            for key in ui.context.take_menu_keys(id) {
281                let index = state
282                    .active
283                    .and_then(|a| enabled.iter().position(|i| *i == a))
284                    .unwrap_or(0);
285                let next = match key {
286                    KeyCode::ArrowDown => Some((index + 1) % enabled.len().max(1)),
287                    KeyCode::ArrowUp => {
288                        Some((index + enabled.len().saturating_sub(1)) % enabled.len().max(1))
289                    }
290                    KeyCode::Home => Some(0),
291                    KeyCode::End => Some(enabled.len().saturating_sub(1)),
292                    KeyCode::Enter | KeyCode::Space => {
293                        output.selected = state.active;
294                        None
295                    }
296                    _ => None,
297                };
298                if let Some(next) = next {
299                    state.active = enabled.get(next).copied();
300                    state.keyboard = true;
301                    reveal = true;
302                }
303            }
304            let metrics = &cache.metrics;
305            let popup_style = paint::popup_style(ui, style);
306            let mut popup = Popup::new(id, Rect::from_min_size(state.position, Vec2::ZERO))
307                .size(Vec2::new(
308                    metrics.width + style.padding.size().x,
309                    metrics.height + style.padding.size().y,
310                ))
311                .gap(0.0)
312                .padding(style.padding)
313                .style(popup_style);
314            // The shared keyboard queue preserves multiple key events per redraw.
315            popup.key_target = Some(id);
316            if placed.is_none() && asked.is_some() {
317                // Asked for without a pointer: focus goes back to the widget it belongs to.
318                popup = popup.return_focus(target.id);
319            }
320            let active = state.keyboard.then_some(state.active).flatten();
321            let focus = id.with("focus");
322            let shown = popup.show(ui, &mut state.open, |ui| {
323                // The open menu holds keyboard focus, on a region under its rows.
324                ui.context.register_hit(HitRegion {
325                    id: focus,
326                    window: ui.window,
327                    rect: ui.layout.bounds,
328                    clip: ui.clip,
329                    action: HitAction::Focus,
330                });
331                let mut scroll = ui.style().scroll;
332                scroll.padding = Padding::all(0.0);
333                scroll.spacing = 0.0;
334                scroll.bar_margin = 0.0;
335                let mut scroll_area = ScrollArea::vertical()
336                    .id_source(id.with("scroll"))
337                    .max_height(ui.available_height())
338                    .overlay_scrollbars(true)
339                    .style(scroll)
340                    .show_hints(false)
341                    .middle_mouse_scroll(false)
342                    .a11y_hidden();
343                // The highlighted row speaks for the menu that holds focus.
344                let menu = ui.a11y_begin(id, crate::AccessRole::Menu, |node| {
345                    node.focus_on(focus);
346                    if let Some(active) = active {
347                        node.active_descendant(id.with(("item", active)));
348                    }
349                });
350                if reveal {
351                    if let Some(index) = self
352                        .items
353                        .iter()
354                        .position(|item| item.id == active && item.id.is_some())
355                    {
356                        scroll_area = scroll_area.scroll_to_rect(Rect::from_min_size(
357                            Vec2::new(0.0, cache.offsets[index]),
358                            Vec2::new(metrics.width, style.row_height),
359                        ));
360                    }
361                }
362                let area = scroll_area.show(ui, |ui| {
363                    ui.layout.spacing = 0.0;
364                    let origin = ui.layout.bounds.min;
365                    let visible = ui.clip_rect();
366                    let first = cache
367                        .offsets
368                        .partition_point(|y| *y <= visible.min.y - origin.y)
369                        .saturating_sub(1)
370                        .min(self.items.len());
371                    let end = cache
372                        .offsets
373                        .partition_point(|y| *y < visible.max.y - origin.y)
374                        .min(self.items.len())
375                        .max(first);
376                    ui.add_space(cache.offsets[first]);
377                    for item in &self.items[first..end] {
378                        let (response, selected) = paint::row(ui, id, item, active, metrics, style);
379                        if selected {
380                            output.selected = item.id;
381                        }
382                        if let Some(response) = response {
383                            if pointer_moved && response.hovered && response.enabled {
384                                state.active = item.id;
385                            }
386                        }
387                    }
388                    ui.add_space(metrics.height - cache.offsets[end]);
389                });
390                ui.context.a11y_scroll(&menu, area.id);
391                ui.a11y_end(menu, Some(area.viewport));
392            });
393            output.rect = shown.map(|p| p.rect);
394            if opening.is_some() && state.open {
395                ui.context.set_focus(Some(focus));
396            }
397            if output.selected.is_some() {
398                ui.context.close_popup();
399                state.open = false;
400            }
401            state.cache = Some(cache);
402        }
403        output.open = state.open;
404        ui.context.menus.context_menus.insert(id, state);
405        output
406    }
407}
408
409/// A widget with a context menu attached; see [`super::Widget::context_menu`].
410pub struct ContextMenuWidget<'a, W> {
411    widget: W,
412    items: &'a [ContextMenuItem],
413}
414impl<'a, W> ContextMenuWidget<'a, W> {
415    pub(super) fn new(widget: W, items: &'a [ContextMenuItem]) -> Self {
416        Self { widget, items }
417    }
418}
419impl<W: super::Widget> super::Widget for ContextMenuWidget<'_, W> {
420    fn ui(self, ui: &mut Ui<'_>) -> Response {
421        let before = access::before(ui);
422        let mut response = self.widget.ui(ui);
423        let mut menu = ContextMenu::new(response.id, self.items);
424        menu.target = access::wrapped(ui, before);
425        response.menu_selected = menu.show(ui, response).selected;
426        response
427    }
428}
429
430impl Ui<'_> {
431    pub fn context_menu(
432        &mut self,
433        target: Response,
434        items: &[ContextMenuItem],
435    ) -> ContextMenuOutput {
436        ContextMenu::new(target.id, items).show(self, target)
437    }
438}