ailloli_ui_widgets/controls/
context_menu.rs

1//! Right-click menus rendered through retained popup portals.
2
3use std::cell::Cell;
4use std::rc::Rc;
5
6use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
7use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
8use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
9use ailloli_ui_core::geometry::{Constraints, Rect, Size};
10use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
11use ailloli_ui_core::{Color, FontId, IconId, Offset, Point, TextStyle, Theme};
12use ailloli_ui_runtime::app::{PresentationGeneration, RuntimeHandle};
13use ailloli_ui_runtime::component::{
14    Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
15};
16use ailloli_ui_runtime::input::{
17    ActivationPolicy, ClickAction, EventCtx, FocusPolicy, HoverCursorRole, IntoClickAction,
18};
19use ailloli_ui_runtime::layout::{ChildLayout, LayoutChild, LayoutCtx, LayoutPass, LayoutResult};
20use ailloli_ui_runtime::popup::{
21    PopupContent, PopupDismissReason, PopupId, PopupMountPolicy, PopupOwner, PopupPlacementSpec,
22    PopupRequest, HEADLESS_POPUP_WINDOW_ID,
23};
24use ailloli_ui_runtime::scene::PaintCtx;
25use ailloli_ui_runtime::{DrawCmd, DrawImage, DrawRect};
26use lucide_icons::Icon;
27
28use super::popup::{
29    apply_opacity, measure_text, menu_popup_semantics, paint_overlay_text_in_rect,
30    paint_popup_border, paint_popup_shell, PopupAlignment, PopupPlacement, PopupPortalBridge,
31};
32use super::select::{SelectSize, SelectStyle};
33
34#[derive(Clone, Debug, PartialEq)]
35/// Resolved colors, typography, and logical-pixel geometry for context menus.
36///
37/// Menus are clipped to `popup.popup_max_height`; this control does not add a
38/// scrollbar, so callers should keep the complete entry stack within that cap.
39/// Custom non-positive or non-finite geometry is not normalized.
40///
41/// # Examples
42///
43/// ```
44/// use ailloli_ui_core::Theme;
45/// use ailloli_ui_widgets::controls::ContextMenuStyle;
46/// let style = ContextMenuStyle::from_theme(Theme::dark());
47/// assert_eq!((style.width, style.row_height), (252.0, 28.0));
48/// assert_eq!(style.popup.popup_max_height, 420.0);
49/// ```
50pub struct ContextMenuStyle {
51    /// Shared popup shell, active-row, item-text, and height-cap style.
52    pub popup: SelectStyle,
53    /// Right-aligned shortcut hint typography.
54    pub shortcut_text: TextStyle,
55    /// One-pixel separator-line color.
56    pub separator: Color,
57    /// Item row height in logical pixels.
58    pub row_height: f32,
59    /// Vertical space reserved for a separator in logical pixels.
60    pub separator_height: f32,
61    /// Root menu width in logical pixels.
62    pub width: f32,
63    /// First-level submenu width in logical pixels.
64    pub submenu_width: f32,
65    /// Horizontal distance between root menu and submenu in logical pixels.
66    pub submenu_gap: f32,
67    /// Leading and submenu-chevron icon size in logical pixels.
68    pub icon_size: f32,
69    /// Gap after icons and around shortcut/chevron regions in logical pixels.
70    pub icon_gap: f32,
71    /// Horizontal content inset in logical pixels.
72    pub padding_x: f32,
73    /// Alpha multiplier applied to disabled item visuals.
74    pub disabled_opacity: f32,
75}
76
77impl Default for ContextMenuStyle {
78    fn default() -> Self {
79        Self::from_theme(Theme::default())
80    }
81}
82
83impl ContextMenuStyle {
84    /// Resolves compact menu styling from a theme.
85    ///
86    /// The root defaults to 252 logical pixels wide, submenus to 228, item
87    /// rows to 28, and the clipped height cap to 420.
88    ///
89    /// # Examples
90    ///
91    /// ```
92    /// use ailloli_ui_core::Theme;
93    /// use ailloli_ui_widgets::controls::ContextMenuStyle;
94    /// let style = ContextMenuStyle::from_theme(Theme::default());
95    /// assert_eq!((style.submenu_width, style.submenu_gap), (228.0, 4.0));
96    /// assert_eq!((style.icon_size, style.padding_x), (14.0, 10.0));
97    /// ```
98    pub fn from_theme(theme: Theme) -> Self {
99        let palette = theme.palette();
100        let mut popup = SelectStyle::from_theme(theme, SelectSize::Compact);
101        popup.width = 252.0;
102        popup.option_height = 28.0;
103        popup.popup_max_height = 420.0;
104        popup.radius = Radius::uniform(theme.radius().md);
105        popup.popup_border = Border::new(1.0, palette.border);
106        Self {
107            shortcut_text: TextStyle::new(FontId::Mono, 11, palette.text_muted),
108            separator: palette.border.with_alpha(0.86),
109            row_height: 28.0,
110            separator_height: 9.0,
111            width: 252.0,
112            submenu_width: 228.0,
113            submenu_gap: 4.0,
114            icon_size: 14.0,
115            icon_gap: 8.0,
116            padding_x: 10.0,
117            disabled_opacity: 0.45,
118            popup,
119        }
120    }
121}
122
123/// One row in a root menu or first-level submenu.
124///
125/// Separators occupy `separator_height`, are skipped by navigation, and cannot
126/// activate. Items occupy `row_height`.
127///
128/// # Examples
129///
130/// ```
131/// use ailloli_ui_widgets::controls::{ContextMenuEntry, ContextMenuItem};
132/// let entries: Vec<ContextMenuEntry<()>> = vec![
133///     ContextMenuEntry::Item(ContextMenuItem::new("Copy")),
134///     ContextMenuEntry::Separator,
135/// ];
136/// assert!(matches!(entries[1], ContextMenuEntry::Separator));
137/// ```
138pub enum ContextMenuEntry<A = ()> {
139    /// Selectable or submenu-bearing row.
140    Item(ContextMenuItem<A>),
141    /// Non-interactive horizontal divider.
142    Separator,
143}
144
145impl<A> Clone for ContextMenuEntry<A> {
146    fn clone(&self) -> Self {
147        match self {
148            Self::Item(item) => Self::Item(item.clone()),
149            Self::Separator => Self::Separator,
150        }
151    }
152}
153
154/// A context-menu row with optional metadata, action, or submenu.
155///
156/// A leaf item closes the complete menu after activation even when it has no
157/// action. Disabled items remain visible but cannot be highlighted or activated.
158/// The current controller opens one submenu tier; submenu entries that themselves
159/// contain a submenu are displayed with a chevron but are not opened.
160///
161/// # Examples
162///
163/// ```
164/// use ailloli_ui_widgets::controls::{ContextMenuEntry, ContextMenuItem};
165/// let item: ContextMenuItem<()> = ContextMenuItem::new("More")
166///     .submenu([ContextMenuEntry::Item(ContextMenuItem::new("Details"))]);
167/// assert_eq!(item.label(), "More");
168/// assert_eq!(item.submenu_entries().len(), 1);
169/// ```
170pub struct ContextMenuItem<A = ()> {
171    /// Primary row label.
172    label: String,
173    /// Optional non-semantic shortcut hint.
174    shortcut: Option<String>,
175    /// Optional leading icon.
176    icon: Option<IconId>,
177    /// Live disabled state.
178    disabled: Binding<bool>,
179    /// Optional leaf action.
180    action: Option<Rc<ClickAction<A>>>,
181    /// Owned first-level submenu entries.
182    submenu: Vec<ContextMenuEntry<A>>,
183}
184
185impl<A> Clone for ContextMenuItem<A> {
186    fn clone(&self) -> Self {
187        Self {
188            label: self.label.clone(),
189            shortcut: self.shortcut.clone(),
190            icon: self.icon.clone(),
191            disabled: self.disabled.clone(),
192            action: self.action.clone(),
193            submenu: self.submenu.clone(),
194        }
195    }
196}
197
198impl<A: 'static> ContextMenuItem<A> {
199    /// Creates an enabled leaf item without icon, shortcut, or action.
200    ///
201    /// # Examples
202    ///
203    /// ```
204    /// use ailloli_ui_widgets::controls::ContextMenuItem;
205    /// let item: ContextMenuItem<()> = ContextMenuItem::new("Copy");
206    /// assert_eq!(item.label(), "Copy");
207    /// ```
208    pub fn new(label: impl Into<String>) -> Self {
209        Self {
210            label: label.into(),
211            shortcut: None,
212            icon: None,
213            disabled: Binding::Static(false),
214            action: None,
215            submenu: Vec::new(),
216        }
217    }
218
219    /// Sets the right-aligned display-only shortcut hint.
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// use ailloli_ui_widgets::controls::ContextMenuItem;
225    /// let item: ContextMenuItem<()> = ContextMenuItem::new("Copy").shortcut("Ctrl+C");
226    /// assert_eq!(item.shortcut_label(), Some("Ctrl+C"));
227    /// ```
228    pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
229        self.shortcut = Some(shortcut.into());
230        self
231    }
232
233    /// Sets the leading icon, replacing any previous icon.
234    ///
235    /// # Examples
236    ///
237    /// ```
238    /// use ailloli_ui_core::IconId;
239    /// use ailloli_ui_widgets::controls::ContextMenuItem;
240    /// let item: ContextMenuItem<()> = ContextMenuItem::new("History").leading_icon(IconId::History);
241    /// let _ = item;
242    /// ```
243    pub fn leading_icon(mut self, icon: IconId) -> Self {
244        self.icon = Some(icon);
245        self
246    }
247
248    /// Sets static or reactive disabled state.
249    ///
250    /// # Examples
251    ///
252    /// ```
253    /// use ailloli_ui_widgets::controls::ContextMenuItem;
254    /// let item: ContextMenuItem<()> = ContextMenuItem::new("Unavailable").disabled(true);
255    /// assert!(item.is_disabled());
256    /// ```
257    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
258        self.disabled = disabled.into();
259        self
260    }
261
262    /// Sets the leaf action, replacing any previous action.
263    ///
264    /// Items with non-empty submenus open the submenu instead of running this
265    /// action.
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use ailloli_ui_widgets::controls::ContextMenuItem;
271    /// #[derive(Clone)]
272    /// enum Action { Copy }
273    /// let item = ContextMenuItem::new("Copy").on_select(Action::Copy);
274    /// let _ = item;
275    /// ```
276    pub fn on_select(mut self, action: impl IntoClickAction<A>) -> Self {
277        self.action = Some(Rc::new(action.into_click_action()));
278        self
279    }
280
281    /// Replaces the submenu entries with values collected in iterator order.
282    ///
283    /// An empty iterator restores leaf behavior. Only one interactive submenu
284    /// tier is currently supported.
285    ///
286    /// # Examples
287    ///
288    /// ```
289    /// use ailloli_ui_widgets::controls::{ContextMenuEntry, ContextMenuItem};
290    /// let item: ContextMenuItem<()> = ContextMenuItem::new("More").submenu([
291    ///     ContextMenuEntry::Item(ContextMenuItem::new("Details")),
292    ///     ContextMenuEntry::Separator,
293    /// ]);
294    /// assert_eq!(item.submenu_entries().len(), 2);
295    /// ```
296    pub fn submenu(mut self, entries: impl IntoIterator<Item = ContextMenuEntry<A>>) -> Self {
297        self.submenu = entries.into_iter().collect();
298        self
299    }
300
301    /// Reads the current static or reactive disabled value.
302    ///
303    /// # Examples
304    ///
305    /// ```
306    /// use ailloli_ui_widgets::controls::ContextMenuItem;
307    /// let item: ContextMenuItem<()> = ContextMenuItem::new("Delete").disabled(true);
308    /// assert!(item.is_disabled());
309    /// ```
310    pub fn is_disabled(&self) -> bool {
311        self.disabled.read()
312    }
313
314    /// Returns the label exactly as supplied.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// use ailloli_ui_widgets::controls::ContextMenuItem;
320    /// let item: ContextMenuItem<()> = ContextMenuItem::new("");
321    /// assert_eq!(item.label(), "");
322    /// ```
323    pub fn label(&self) -> &str {
324        &self.label
325    }
326
327    /// Returns the optional shortcut hint; empty text remains `Some("")`.
328    ///
329    /// # Examples
330    ///
331    /// ```
332    /// use ailloli_ui_widgets::controls::ContextMenuItem;
333    /// let item: ContextMenuItem<()> = ContextMenuItem::new("Copy").shortcut("");
334    /// assert_eq!(item.shortcut_label(), Some(""));
335    /// ```
336    pub fn shortcut_label(&self) -> Option<&str> {
337        self.shortcut.as_deref()
338    }
339
340    /// Borrows submenu entries in their display order.
341    ///
342    /// # Examples
343    ///
344    /// ```
345    /// use ailloli_ui_widgets::controls::ContextMenuItem;
346    /// let item: ContextMenuItem<()> = ContextMenuItem::new("Leaf");
347    /// assert!(item.submenu_entries().is_empty());
348    /// ```
349    pub fn submenu_entries(&self) -> &[ContextMenuEntry<A>] {
350        &self.submenu
351    }
352}
353
354/// A retained right-click menu attached to an optional host child.
355///
356/// Visibility can be controlled, two-way bound, or internal. A right click can
357/// open/re-anchor bound and internal menus; a controlled `false` value prevents
358/// opening, while controlled `true` permits re-anchoring. When no pointer or
359/// explicit anchor exists, the menu starts at the host's bottom-left corner.
360/// Escape/outside dismissal can write only bound or internal state.
361///
362/// # Examples
363///
364/// ```
365/// use ailloli_ui_widgets::controls::{ContextMenu, ContextMenuEntry, ContextMenuItem};
366/// use ailloli_ui_widgets::text::Text;
367/// let menu = ContextMenu::<()>::new(Text::new("File"))
368///     .entries(vec![ContextMenuEntry::Item(ContextMenuItem::new("Open"))]);
369/// let _ = menu;
370/// ```
371pub struct ContextMenu<A = ()> {
372    /// Layout configuration for the host slot.
373    pub(crate) layout: LayoutStyle,
374    /// Flex behavior used by the parent layout.
375    pub(crate) flex_item: FlexItemStyle,
376    /// Optional controlled or bound visibility source.
377    open: Option<Binding<bool>>,
378    /// Writable visibility signal in bound mode.
379    bound_open: Option<Signal<bool>>,
380    /// Initial internal visibility without an external source.
381    default_open: bool,
382    /// Static or reactive programmatic anchor in host coordinates.
383    anchor: Binding<Point>,
384    /// Whether the programmatic anchor was explicitly configured.
385    anchor_explicit: bool,
386    /// Static or reactive complete entry collection.
387    entries: Binding<Vec<ContextMenuEntry<A>>>,
388    /// Live disabled state.
389    disabled: Binding<bool>,
390    /// Resolved popup and row style.
391    style: ContextMenuStyle,
392    /// Optional sole host child painted below the portal.
393    child: Option<View<A>>,
394}
395
396crate::impl_layout_builders!(ContextMenu);
397
398impl<A: 'static> Default for ContextMenu<A> {
399    fn default() -> Self {
400        Self::empty()
401    }
402}
403
404impl<A: 'static> ContextMenu<A> {
405    /// Creates a closed menu around one host child.
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// use ailloli_ui_widgets::controls::ContextMenu;
411    /// use ailloli_ui_widgets::text::Text;
412    /// let menu: ContextMenu<()> = ContextMenu::new(Text::new("Right-click"));
413    /// let _ = menu;
414    /// ```
415    pub fn new(child: impl IntoView<A>) -> Self {
416        Self::empty().child(child)
417    }
418
419    /// Creates a closed menu without a child or entries.
420    ///
421    /// In an unbounded host it intrinsically measures as zero by zero.
422    ///
423    /// # Examples
424    ///
425    /// ```
426    /// use ailloli_ui_widgets::controls::ContextMenu;
427    /// let menu: ContextMenu<()> = ContextMenu::empty();
428    /// let _ = menu;
429    /// ```
430    pub fn empty() -> Self {
431        Self {
432            layout: LayoutStyle::default(),
433            flex_item: FlexItemStyle::default(),
434            open: None,
435            bound_open: None,
436            default_open: false,
437            anchor: Binding::Static(Point::default()),
438            anchor_explicit: false,
439            entries: Binding::Static(Vec::new()),
440            disabled: Binding::Static(false),
441            style: ContextMenuStyle::default(),
442            child: None,
443        }
444    }
445
446    /// Sets controlled visibility and clears two-way bound mode.
447    ///
448    /// Portal dismissal cannot mutate this binding. A controlled `false` value
449    /// also prevents right-click opening.
450    ///
451    /// # Examples
452    ///
453    /// ```
454    /// use ailloli_ui_widgets::controls::ContextMenu;
455    /// let menu: ContextMenu<()> = ContextMenu::empty().open(true);
456    /// let _ = menu;
457    /// ```
458    pub fn open(mut self, open: impl Into<Binding<bool>>) -> Self {
459        self.open = Some(open.into());
460        self.bound_open = None;
461        self
462    }
463
464    /// Installs a writable visibility signal for opening and dismissal.
465    ///
466    /// # Examples
467    ///
468    /// ```
469    /// use std::{cell::RefCell, rc::Rc};
470    /// use ailloli_ui_runtime::component::Signal;
471    /// use ailloli_ui_widgets::controls::ContextMenu;
472    /// let open = Signal::new(Rc::new(RefCell::new(false)), Rc::new(|| {}));
473    /// let menu: ContextMenu<()> = ContextMenu::empty().bind_open(open);
474    /// let _ = menu;
475    /// ```
476    pub fn bind_open(mut self, open: impl Into<Signal<bool>>) -> Self {
477        let signal = open.into();
478        self.open = Some(Binding::Signal(signal.clone()));
479        self.bound_open = Some(signal);
480        self
481    }
482
483    /// Sets initial internal visibility when no external source exists.
484    ///
485    /// # Examples
486    ///
487    /// ```
488    /// use ailloli_ui_widgets::controls::ContextMenu;
489    /// let menu: ContextMenu<()> = ContextMenu::empty().default_open(true);
490    /// let _ = menu;
491    /// ```
492    pub fn default_open(mut self, open: bool) -> Self {
493        self.default_open = open;
494        self
495    }
496
497    /// Sets a static or reactive programmatic anchor in host coordinates.
498    ///
499    /// A later right click temporarily takes precedence until the menu closes.
500    ///
501    /// # Examples
502    ///
503    /// ```
504    /// use ailloli_ui_core::Point;
505    /// use ailloli_ui_widgets::controls::ContextMenu;
506    /// let menu: ContextMenu<()> = ContextMenu::empty().anchor(Point::new(12.0, 24.0));
507    /// let _ = menu;
508    /// ```
509    pub fn anchor(mut self, anchor: impl Into<Binding<Point>>) -> Self {
510        self.anchor = anchor.into();
511        self.anchor_explicit = true;
512        self
513    }
514
515    /// Installs a writable anchor signal and marks the anchor explicit.
516    ///
517    /// The menu reads it reactively but does not write it during pointer opens.
518    ///
519    /// # Examples
520    ///
521    /// ```
522    /// use std::{cell::RefCell, rc::Rc};
523    /// use ailloli_ui_core::Point;
524    /// use ailloli_ui_runtime::component::Signal;
525    /// use ailloli_ui_widgets::controls::ContextMenu;
526    /// let anchor = Signal::new(Rc::new(RefCell::new(Point::new(1.0, 2.0))), Rc::new(|| {}));
527    /// let menu: ContextMenu<()> = ContextMenu::empty().bind_anchor(anchor);
528    /// let _ = menu;
529    /// ```
530    pub fn bind_anchor(mut self, anchor: impl Into<Signal<Point>>) -> Self {
531        self.anchor = Binding::Signal(anchor.into());
532        self.anchor_explicit = true;
533        self
534    }
535
536    /// Sets the static or reactive complete entry collection.
537    ///
538    /// Empty collections keep open state but publish no visible menu content.
539    ///
540    /// # Examples
541    ///
542    /// ```
543    /// use ailloli_ui_widgets::controls::{ContextMenu, ContextMenuEntry, ContextMenuItem};
544    /// let entries = vec![ContextMenuEntry::Item(ContextMenuItem::new("Open"))];
545    /// let menu: ContextMenu<()> = ContextMenu::empty().entries(entries);
546    /// let _ = menu;
547    /// ```
548    pub fn entries(mut self, entries: impl Into<Binding<Vec<ContextMenuEntry<A>>>>) -> Self {
549        self.entries = entries.into();
550        self
551    }
552
553    /// Installs a writable signal as the live complete entry collection.
554    ///
555    /// The menu only reads the signal; it never mutates its entries.
556    ///
557    /// # Examples
558    ///
559    /// ```
560    /// use std::{cell::RefCell, rc::Rc};
561    /// use ailloli_ui_runtime::component::Signal;
562    /// use ailloli_ui_widgets::controls::{ContextMenu, ContextMenuEntry};
563    /// let entries = Signal::new(
564    ///     Rc::new(RefCell::new(Vec::<ContextMenuEntry<()>>::new())),
565    ///     Rc::new(|| {}),
566    /// );
567    /// let menu: ContextMenu<()> = ContextMenu::empty().bind_entries(entries);
568    /// let _ = menu;
569    /// ```
570    pub fn bind_entries(mut self, entries: impl Into<Signal<Vec<ContextMenuEntry<A>>>>) -> Self {
571        self.entries = Binding::Signal(entries.into());
572        self
573    }
574
575    /// Sets static or reactive disabled state.
576    ///
577    /// Disabled state prevents right-click opening/focus and closes an existing
578    /// portal programmatically without changing controlled visibility.
579    ///
580    /// # Examples
581    ///
582    /// ```
583    /// use ailloli_ui_widgets::controls::ContextMenu;
584    /// let menu: ContextMenu<()> = ContextMenu::empty().disabled(true);
585    /// let _ = menu;
586    /// ```
587    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
588        self.disabled = disabled.into();
589        self
590    }
591
592    /// Replaces the complete popup and row style.
593    ///
594    /// # Examples
595    ///
596    /// ```
597    /// use ailloli_ui_widgets::controls::{ContextMenu, ContextMenuStyle};
598    /// let menu: ContextMenu<()> = ContextMenu::empty().context_menu_style(ContextMenuStyle::default());
599    /// let _ = menu;
600    /// ```
601    pub fn context_menu_style(mut self, style: ContextMenuStyle) -> Self {
602        self.style = style;
603        self
604    }
605
606    /// Sets root-menu width in both the menu and nested popup styles.
607    ///
608    /// This does not change `submenu_width`. The value is in logical pixels and
609    /// is not clamped.
610    ///
611    /// # Examples
612    ///
613    /// ```
614    /// use ailloli_ui_widgets::controls::ContextMenu;
615    /// let menu: ContextMenu<()> = ContextMenu::empty().menu_width(300.0);
616    /// let _ = menu;
617    /// ```
618    pub fn menu_width(mut self, width: f32) -> Self {
619        self.style.width = width;
620        self.style.popup.width = width;
621        self
622    }
623
624    /// Sets the sole host child, replacing any previous child.
625    ///
626    /// # Examples
627    ///
628    /// ```
629    /// use ailloli_ui_widgets::controls::ContextMenu;
630    /// use ailloli_ui_widgets::text::Text;
631    /// let menu: ContextMenu<()> = ContextMenu::empty().child(Text::new("Target"));
632    /// let _ = menu;
633    /// ```
634    pub fn child(mut self, child: impl IntoView<A>) -> Self {
635        self.child = Some(child.into_view());
636        self
637    }
638}
639
640/// Component properties used to allocate retained menu and submenu state.
641struct ContextMenuComponent<A> {
642    /// Outer logical sizing policy for the underlying host child.
643    layout: LayoutStyle,
644    /// Optional readable external open state.
645    open: Option<Binding<bool>>,
646    /// Optional writable external open state.
647    bound_open: Option<Signal<bool>>,
648    /// Initial open state used by an uncontrolled menu.
649    default_open: bool,
650    /// Static or reactive preferred anchor in logical window coordinates.
651    anchor: Binding<Point>,
652    /// Whether the caller explicitly supplied the anchor.
653    anchor_explicit: bool,
654    /// Reactive root entry collection.
655    entries: Binding<Vec<ContextMenuEntry<A>>>,
656    /// Reactive interaction-disable flag.
657    disabled: Binding<bool>,
658    /// Popup, row, and submenu styling.
659    style: ContextMenuStyle,
660    /// Optional underlying host content painted below the menu.
661    child: Option<View<A>>,
662}
663
664impl<A: 'static> ComponentNode<A> for ContextMenuComponent<A> {
665    fn build(&self, context: &mut Context<A>) -> View<A> {
666        let mut children = Vec::new();
667        if let Some(child) = self.child.clone() {
668            children.push(child);
669        }
670        let initially_open = self
671            .open
672            .as_ref()
673            .map(Binding::read)
674            .unwrap_or(self.default_open);
675        let runtime = context.runtime();
676        let root_popup_id = runtime.popup_id_for_element(context.element_id()).ok();
677        let internal_open = context.signal(self.default_open);
678        let popup_was_open = root_popup_id.is_some_and(|popup_id| runtime.popup_is_open(popup_id));
679        let last_requested_open = context
680            .signal_with(|| Rc::new(Cell::new(popup_was_open)))
681            .read();
682        let pointer_anchor = context.signal(None);
683        let active_index = context.signal(None);
684        let submenu_parent_index = context.signal(None);
685        let submenu_active_index = context.signal(None);
686        let pressed_entry = context.signal(None);
687        let geometry = context.signal_with(|| Rc::new(Cell::new(None))).read();
688        let submenu_popup_id = context.signal_with(|| Rc::new(Cell::new(None))).read();
689        let controller = ContextMenuController {
690            runtime,
691            open: self.open.clone(),
692            bound_open: self.bound_open.clone(),
693            internal_open,
694            last_requested_open,
695            anchor: self.anchor.clone(),
696            anchor_explicit: self.anchor_explicit,
697            pointer_anchor,
698            entries: self.entries.clone(),
699            disabled: self.disabled.clone(),
700            style: self.style.clone(),
701            active_index,
702            submenu_parent_index,
703            submenu_active_index,
704            pressed_entry,
705            geometry,
706            root_popup_id,
707            submenu_popup_id,
708        };
709        let popup_content = context_menu_root_content(controller.clone());
710        let popup = PopupPortalBridge::new_retained_with_content(
711            context,
712            menu_popup_semantics(true),
713            initially_open,
714            popup_content,
715        );
716        if !controller.sync_portal_visibility(&popup) || controller.disabled.read() {
717            popup.close(PopupDismissReason::Programmatic);
718        }
719        View::node(
720            ContextMenuWidget {
721                layout: self.layout,
722                controller,
723                popup,
724            },
725            children,
726        )
727    }
728}
729
730impl<A: 'static> IntoView<A> for ContextMenu<A> {
731    fn into_view(self) -> View<A> {
732        finish_view_sized(
733            View::component(ContextMenuComponent {
734                layout: self.layout,
735                open: self.open,
736                bound_open: self.bound_open,
737                default_open: self.default_open,
738                anchor: self.anchor,
739                anchor_explicit: self.anchor_explicit,
740                entries: self.entries,
741                disabled: self.disabled,
742                style: self.style,
743                child: self.child,
744            }),
745            self.flex_item,
746            LayoutSizeHint::from_layout(self.layout),
747        )
748    }
749}
750
751/// Host widget that opens and synchronizes the root popup portal.
752struct ContextMenuWidget<A> {
753    /// Outer logical sizing policy for the underlying host child.
754    layout: LayoutStyle,
755    /// Shared retained controller for root and submenu content.
756    controller: ContextMenuController<A>,
757    /// Bridge synchronizing popup registry content and lifecycle.
758    popup: PopupPortalBridge<A>,
759}
760
761/// Shared state machine used by the host and both retained popup widgets.
762struct ContextMenuController<A> {
763    /// UI-local runtime used to allocate and close popup registrations.
764    runtime: RuntimeHandle<A>,
765    /// Optional readable external open state.
766    open: Option<Binding<bool>>,
767    /// Optional writable external open state.
768    bound_open: Option<Signal<bool>>,
769    /// Retained open state used by an uncontrolled menu.
770    internal_open: Signal<bool>,
771    /// Passive last open state reconciled into the popup registry.
772    ///
773    /// This is bookkeeping rather than a render input. Keeping it outside the
774    /// reactive graph prevents an edge update from superseding the build or
775    /// layout that is currently publishing the corresponding portal state.
776    last_requested_open: Rc<Cell<bool>>,
777    /// Static or reactive preferred anchor in logical window coordinates.
778    anchor: Binding<Point>,
779    /// Whether the caller explicitly supplied the anchor.
780    anchor_explicit: bool,
781    /// Pointer-derived anchor captured for implicit context-menu opening.
782    pointer_anchor: Signal<Option<Point>>,
783    /// Reactive root entry collection.
784    entries: Binding<Vec<ContextMenuEntry<A>>>,
785    /// Reactive interaction-disable flag.
786    disabled: Binding<bool>,
787    /// Popup, row, and submenu styling.
788    style: ContextMenuStyle,
789    /// Keyboard-active root entry index.
790    active_index: Signal<Option<usize>>,
791    /// Root entry whose submenu is currently open.
792    submenu_parent_index: Signal<Option<usize>>,
793    /// Keyboard-active entry within the open submenu.
794    submenu_active_index: Signal<Option<usize>>,
795    /// Entry and depth captured by the active pointer press.
796    pressed_entry: Signal<Option<ContextMenuPressedEntry>>,
797    /// Passive last resolved root/submenu rectangles and entry rows.
798    ///
799    /// Host geometry is refreshed by input handling. It must not invalidate
800    /// the popup while that same popup is painting its committed artifact.
801    geometry: Rc<Cell<Option<ContextMenuGeometry>>>,
802    /// Popup identity reserved for root menu content.
803    root_popup_id: Option<PopupId>,
804    /// Passive popup identity reserved for the current submenu, if any.
805    ///
806    /// The retained popup component writes this during its build. Treating the
807    /// identity as reactive would continuously rebuild the owner tree.
808    submenu_popup_id: Rc<Cell<Option<PopupId>>>,
809}
810
811impl<A> Clone for ContextMenuController<A> {
812    fn clone(&self) -> Self {
813        Self {
814            runtime: self.runtime.clone(),
815            open: self.open.clone(),
816            bound_open: self.bound_open.clone(),
817            internal_open: self.internal_open.clone(),
818            last_requested_open: self.last_requested_open.clone(),
819            anchor: self.anchor.clone(),
820            anchor_explicit: self.anchor_explicit,
821            pointer_anchor: self.pointer_anchor.clone(),
822            entries: self.entries.clone(),
823            disabled: self.disabled.clone(),
824            style: self.style.clone(),
825            active_index: self.active_index.clone(),
826            submenu_parent_index: self.submenu_parent_index.clone(),
827            submenu_active_index: self.submenu_active_index.clone(),
828            pressed_entry: self.pressed_entry.clone(),
829            geometry: self.geometry.clone(),
830            root_popup_id: self.root_popup_id,
831            submenu_popup_id: self.submenu_popup_id.clone(),
832        }
833    }
834}
835
836#[derive(Debug, Clone, Copy, PartialEq, Eq)]
837/// Pointer-pressed row identity used to require same-row release.
838struct ContextMenuPressedEntry {
839    /// `None` for root rows or the root parent index for submenu rows.
840    parent: Option<usize>,
841    /// Absolute index within the root or submenu entry slice.
842    index: usize,
843}
844
845#[derive(Debug, Clone, Copy, PartialEq)]
846/// Resolved viewport and root menu rectangles used to place a submenu.
847struct ContextMenuGeometry {
848    /// Complete presentation viewport.
849    viewport: Rect,
850    /// Root popup rectangle after host placement resolution.
851    menu: Rect,
852}
853
854impl<A: 'static> Widget<A> for ContextMenuWidget<A> {
855    fn debug_name(&self) -> &'static str {
856        "ContextMenu"
857    }
858
859    fn layout(
860        &self,
861        engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
862        ctx: &mut LayoutCtx<'_>,
863        children: &mut [LayoutChild],
864        constraints: Constraints,
865    ) -> LayoutResult {
866        let size = host_slot_size(engine, ctx, children, constraints, self.layout);
867        let mut child_layouts = Vec::new();
868        if let Some(child) = children.first_mut() {
869            let r = ctx.with_layout_pass(LayoutPass::Commit, |ctx| {
870                child.layout(engine, ctx, Constraints::tight(size.w, size.h))
871            });
872            child_layouts.push(ChildLayout {
873                offset: Offset::default(),
874                size: r.size,
875                paint_bounds: Rect::new(0.0, 0.0, r.size.w, r.size.h),
876                visual_bounds: r.visual_bounds,
877            });
878        }
879
880        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
881        LayoutResult {
882            size,
883            children: child_layouts,
884            paint_bounds,
885            visual_bounds: paint_bounds,
886            overlay_hit_bounds: Vec::new(),
887            clip: None,
888            is_window_root_clip: false,
889            artifact: None,
890        }
891    }
892
893    fn paint(&self, _ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
894        if !self.controller.is_open() || self.controller.disabled.read() {
895            return;
896        }
897        let entries = self.controller.entries.read();
898        if entries.is_empty() {
899            return;
900        }
901        self.controller
902            .publish_root_popup_without_event(&self.popup, bounds, &entries);
903    }
904
905    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
906        self.popup.refresh_owner(ctx);
907        if self.controller.disabled.read() {
908            return;
909        }
910
911        if let Event::Pointer(PointerEvent::Button {
912            pos,
913            button: MouseButton::Right,
914            pressed: true,
915            ..
916        }) = event
917        {
918            if bounds.contains(pos.x, pos.y) && self.controller.open_at(*pos) {
919                self.controller.sync_portal(&self.popup, ctx, bounds);
920                ctx.request_repaint();
921                ctx.stop_propagation();
922                return;
923            }
924        }
925
926        if !self.controller.is_open() {
927            return;
928        }
929        self.controller.sync_portal(&self.popup, ctx, bounds);
930    }
931
932    fn focus_policy(&self) -> FocusPolicy {
933        if self.controller.is_open() && !self.controller.disabled.read() {
934            FocusPolicy::Focusable
935        } else {
936            FocusPolicy::NotFocusable
937        }
938    }
939
940    fn activation_policy(&self) -> ActivationPolicy {
941        ActivationPolicy::SuppressOnFocusOnly
942    }
943}
944
945impl<A: 'static> ContextMenuController<A> {
946    /// Reconciles requested state with host-owned portal state and reports visibility.
947    fn is_open(&self) -> bool {
948        let requested = self.requested_open();
949        let portal_open = self
950            .root_popup_id
951            .is_some_and(|popup_id| self.runtime.popup_is_open(popup_id));
952        if requested && !portal_open {
953            if !self.last_requested_open.get() {
954                // A bound signal may request focus before the next layout has
955                // synchronized its rising edge into the popup portal. Keep
956                // that pending request intact; only a request already known
957                // to the portal can have been dismissed by the host.
958                return false;
959            }
960            // Host-level outside/Escape dismissal is consumed before the
961            // owner widget sees the event. Synchronize mutable state during
962            // the next paint/event query as well as layout, otherwise a
963            // focus-restoration repaint can rebuild and reopen the menu.
964            if let Some(bound) = &self.bound_open {
965                bound.set(false);
966                self.last_requested_open.set(false);
967            } else if self.open.is_none() {
968                self.internal_open.set(false);
969                self.last_requested_open.set(false);
970            }
971            return false;
972        }
973        requested && portal_open
974    }
975
976    /// Reads controlled/bound visibility or retained internal visibility.
977    fn requested_open(&self) -> bool {
978        self.open
979            .as_ref()
980            .map(Binding::read)
981            .unwrap_or_else(|| self.internal_open.read())
982    }
983
984    /// Applies visibility edges to the root portal and mirrors host dismissals.
985    fn sync_portal_visibility(&self, popup: &PopupPortalBridge<A>) -> bool {
986        let requested = self.requested_open();
987        let previously_requested = self.last_requested_open.get();
988        if previously_requested != requested {
989            self.last_requested_open.set(requested);
990        }
991        if !requested {
992            if let Some(popup_id) = self.root_popup_id {
993                if self.runtime.popup_is_open(popup_id) {
994                    self.runtime
995                        .close_popup(popup_id, PopupDismissReason::Programmatic);
996                }
997            }
998            return false;
999        }
1000
1001        if !previously_requested
1002            && self
1003                .root_popup_id
1004                .is_some_and(|popup_id| !self.runtime.popup_is_open(popup_id))
1005        {
1006            popup.open_unpositioned(None);
1007        }
1008        if self
1009            .root_popup_id
1010            .is_some_and(|popup_id| self.runtime.popup_is_open(popup_id))
1011        {
1012            return true;
1013        }
1014
1015        // A portal-level Escape/outside/stale dismissal must also update the
1016        // mutable public/internal state, otherwise layout would reopen it.
1017        if let Some(bound) = &self.bound_open {
1018            bound.set(false);
1019            self.last_requested_open.set(false);
1020        } else if self.open.is_none() {
1021            self.internal_open.set(false);
1022            self.last_requested_open.set(false);
1023        }
1024        false
1025    }
1026
1027    /// Re-anchors and opens a bound/internal menu after a right-button press.
1028    fn open_at(&self, anchor: Point) -> bool {
1029        let can_open = self.bound_open.is_some() || self.open.is_none() || self.is_open();
1030        if !can_open {
1031            return false;
1032        }
1033        self.pointer_anchor.set(Some(anchor));
1034        self.geometry.set(None);
1035        if let Some(bound) = &self.bound_open {
1036            bound.set(true);
1037        } else if self.open.is_none() {
1038            self.internal_open.set(true);
1039        }
1040        self.active_index.set(None);
1041        self.submenu_parent_index.set(None);
1042        self.submenu_active_index.set(None);
1043        self.pressed_entry.set(None);
1044        self.last_requested_open.set(true);
1045        true
1046    }
1047
1048    /// Publishes the root popup placement using event-scoped owner metadata.
1049    fn sync_portal(&self, popup: &PopupPortalBridge<A>, ctx: &EventCtx<A>, bounds: Rect) {
1050        let entries = self.entries.read();
1051        if entries.is_empty() {
1052            popup.open_unpositioned(Some(ctx));
1053            return;
1054        }
1055        popup.open_placed(ctx, self.root_placement(bounds, &entries));
1056    }
1057
1058    /// Publishes placement during paint when no event context is available.
1059    fn publish_root_popup_without_event(
1060        &self,
1061        popup: &PopupPortalBridge<A>,
1062        bounds: Rect,
1063        entries: &[ContextMenuEntry<A>],
1064    ) {
1065        popup.open_placed_without_event(self.root_placement(bounds, entries));
1066    }
1067
1068    /// Builds a flip-enabled bottom/start placement request for the root menu.
1069    fn root_placement(&self, owner: Rect, entries: &[ContextMenuEntry<A>]) -> PopupPlacementSpec {
1070        let anchor = self.effective_anchor(owner);
1071        PopupPlacementSpec::new(
1072            Rect::new(anchor.x, anchor.y, 0.0, 0.0),
1073            Size::new(
1074                self.style.width,
1075                self.menu_height(entries)
1076                    .min(self.style.popup.popup_max_height),
1077            ),
1078        )
1079        .with_placement(PopupPlacement::Bottom)
1080        .with_alignment(PopupAlignment::Start)
1081        .with_gap(0.0)
1082        .with_flip(true)
1083    }
1084
1085    /// Resolves pointer, explicit, or host-bottom-left anchor precedence.
1086    fn effective_anchor(&self, owner: Rect) -> Point {
1087        self.pointer_anchor.read().unwrap_or_else(|| {
1088            if self.anchor_explicit {
1089                self.anchor.read()
1090            } else {
1091                Point::new(owner.x, owner.bottom())
1092            }
1093        })
1094    }
1095
1096    /// Stores changed resolved geometry without redundant signal writes.
1097    fn update_geometry(&self, geometry: ContextMenuGeometry) {
1098        if self.geometry.get() != Some(geometry) {
1099            self.geometry.set(Some(geometry));
1100        }
1101    }
1102
1103    /// Refreshes root menu and viewport rectangles from the popup portal.
1104    fn refresh_resolved_geometry(&self) -> Option<ContextMenuGeometry> {
1105        let popup_id = self.root_popup_id?;
1106        let portal = self.runtime.popup_portal();
1107        let portal = portal.borrow();
1108        let geometry = ContextMenuGeometry {
1109            viewport: portal.resolved_viewport(popup_id)?,
1110            menu: portal.bounds(popup_id)?,
1111        };
1112        drop(portal);
1113        self.update_geometry(geometry);
1114        Some(geometry)
1115    }
1116
1117    /// Places a first-level submenu to the right and clamps it to the viewport.
1118    fn submenu_rect(
1119        &self,
1120        bounds: Rect,
1121        menu: Rect,
1122        parent_row: Rect,
1123        entries: &[ContextMenuEntry<A>],
1124    ) -> Rect {
1125        let desired = Rect::new(
1126            menu.right() + self.style.submenu_gap,
1127            parent_row.y,
1128            self.style.submenu_width,
1129            self.menu_height(entries)
1130                .min(self.style.popup.popup_max_height),
1131        );
1132        super::popup::clamp_rect_to_bounds(desired, bounds)
1133    }
1134
1135    /// Sums item and separator heights without applying the popup height cap.
1136    fn menu_height(&self, entries: &[ContextMenuEntry<A>]) -> f32 {
1137        entries.iter().map(|entry| self.entry_height(entry)).sum()
1138    }
1139
1140    /// Resolves an entry's configured item-row or separator height.
1141    fn entry_height(&self, entry: &ContextMenuEntry<A>) -> f32 {
1142        match entry {
1143            ContextMenuEntry::Item(_) => self.style.row_height,
1144            ContextMenuEntry::Separator => self.style.separator_height,
1145        }
1146    }
1147
1148    /// Returns an entry rectangle by accumulating all preceding row heights.
1149    fn entry_row(&self, menu: Rect, entries: &[ContextMenuEntry<A>], index: usize) -> Option<Rect> {
1150        if index >= entries.len() {
1151            return None;
1152        }
1153        let mut y = menu.y;
1154        for entry in &entries[..index] {
1155            y += self.entry_height(entry);
1156        }
1157        Some(Rect::new(
1158            menu.x,
1159            y,
1160            menu.w,
1161            self.entry_height(&entries[index]),
1162        ))
1163    }
1164
1165    /// Hit-tests a position and returns item indices while excluding separators.
1166    fn item_index_at(
1167        &self,
1168        menu: Rect,
1169        entries: &[ContextMenuEntry<A>],
1170        pos: Point,
1171    ) -> Option<usize> {
1172        if !menu.contains(pos.x, pos.y) {
1173            return None;
1174        }
1175        let mut y = menu.y;
1176        for (idx, entry) in entries.iter().enumerate() {
1177            let height = self.entry_height(entry);
1178            let row = Rect::new(menu.x, y, menu.w, height);
1179            if row.contains(pos.x, pos.y) {
1180                return matches!(entry, ContextMenuEntry::Item(_)).then_some(idx);
1181            }
1182            y += height;
1183        }
1184        None
1185    }
1186
1187    /// Returns the first enabled item index, skipping separators.
1188    fn first_enabled_index(&self, entries: &[ContextMenuEntry<A>]) -> Option<usize> {
1189        entries.iter().enumerate().find_map(|(idx, entry)| {
1190            let ContextMenuEntry::Item(item) = entry else {
1191                return None;
1192            };
1193            (!item.is_disabled()).then_some(idx)
1194        })
1195    }
1196
1197    /// Returns the last enabled item index, skipping separators.
1198    fn last_enabled_index(&self, entries: &[ContextMenuEntry<A>]) -> Option<usize> {
1199        entries.iter().enumerate().rev().find_map(|(idx, entry)| {
1200            let ContextMenuEntry::Item(item) = entry else {
1201                return None;
1202            };
1203            (!item.is_disabled()).then_some(idx)
1204        })
1205    }
1206
1207    /// Advances with wraparound through enabled item indices.
1208    fn next_enabled_index(
1209        &self,
1210        entries: &[ContextMenuEntry<A>],
1211        current: Option<usize>,
1212    ) -> Option<usize> {
1213        let enabled = entries
1214            .iter()
1215            .enumerate()
1216            .filter_map(|(idx, entry)| {
1217                let ContextMenuEntry::Item(item) = entry else {
1218                    return None;
1219                };
1220                (!item.is_disabled()).then_some(idx)
1221            })
1222            .collect::<Vec<_>>();
1223        if enabled.is_empty() {
1224            return None;
1225        }
1226        let next = current
1227            .and_then(|current| enabled.iter().position(|idx| *idx == current))
1228            .map_or(0, |position| (position + 1) % enabled.len());
1229        Some(enabled[next])
1230    }
1231
1232    /// Moves backward with wraparound through enabled item indices.
1233    fn previous_enabled_index(
1234        &self,
1235        entries: &[ContextMenuEntry<A>],
1236        current: Option<usize>,
1237    ) -> Option<usize> {
1238        let enabled: Vec<usize> = entries
1239            .iter()
1240            .enumerate()
1241            .filter_map(|(idx, entry)| {
1242                let ContextMenuEntry::Item(item) = entry else {
1243                    return None;
1244                };
1245                (!item.is_disabled()).then_some(idx)
1246            })
1247            .collect();
1248        if enabled.is_empty() {
1249            return None;
1250        }
1251        let pos = current
1252            .and_then(|current| enabled.iter().position(|idx| *idx == current))
1253            .unwrap_or(0);
1254        Some(enabled[(pos + enabled.len() - 1) % enabled.len()])
1255    }
1256
1257    /// Handles root Escape, navigation, submenu, and activation keys.
1258    fn handle_root_keyboard(&self, ctx: &mut EventCtx<A>, key: &Key) {
1259        let entries = self.entries.read();
1260        match key {
1261            Key::Named(NamedKey::Escape) => {
1262                self.close_with_runtime(ctx, PopupDismissReason::Escape);
1263                ctx.request_repaint();
1264                ctx.stop_propagation();
1265            }
1266            Key::Named(NamedKey::ArrowDown) => {
1267                self.set_active(
1268                    ctx,
1269                    self.next_enabled_index(&entries, self.active_index.read()),
1270                );
1271            }
1272            Key::Named(NamedKey::ArrowUp) => {
1273                self.set_active(
1274                    ctx,
1275                    self.previous_enabled_index(&entries, self.active_index.read()),
1276                );
1277            }
1278            Key::Named(NamedKey::Home) => {
1279                self.set_active(ctx, self.first_enabled_index(&entries));
1280            }
1281            Key::Named(NamedKey::End) => {
1282                self.set_active(ctx, self.last_enabled_index(&entries));
1283            }
1284            Key::Named(NamedKey::ArrowRight) => {
1285                if let Some(index) = self.active_index.read() {
1286                    self.open_submenu(ctx, &entries, index);
1287                }
1288            }
1289            Key::Named(NamedKey::ArrowLeft) => {
1290                self.close_submenu(ctx, PopupDismissReason::Escape);
1291            }
1292            Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
1293                if let Some(index) = self
1294                    .active_index
1295                    .read()
1296                    .or_else(|| self.first_enabled_index(&entries))
1297                {
1298                    self.activate_entry(ctx, &entries, index);
1299                }
1300            }
1301            _ => {}
1302        }
1303    }
1304
1305    /// Highlights the hovered root item and opens or closes its submenu.
1306    fn handle_root_pointer_move(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
1307        let entries = self.entries.read();
1308        if let Some(index) = self.item_index_at(bounds, &entries, pos) {
1309            self.active_index.set(Some(index));
1310            if self.has_submenu(&entries, index) {
1311                self.open_submenu(ctx, &entries, index);
1312            } else {
1313                self.close_submenu(ctx, PopupDismissReason::Programmatic);
1314            }
1315            ctx.request_repaint();
1316        }
1317    }
1318
1319    /// Records an enabled leaf press or opens a pressed submenu parent.
1320    fn handle_root_pointer_press(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
1321        let entries = self.entries.read();
1322        self.pressed_entry.set(None);
1323        if let Some(index) = self.item_index_at(bounds, &entries, pos) {
1324            if self.has_submenu(&entries, index) {
1325                self.open_submenu(ctx, &entries, index);
1326            } else if matches!(entries.get(index), Some(ContextMenuEntry::Item(item)) if !item.is_disabled())
1327            {
1328                self.active_index.set(Some(index));
1329                self.pressed_entry.set(Some(ContextMenuPressedEntry {
1330                    parent: None,
1331                    index,
1332                }));
1333                ctx.request_repaint();
1334            }
1335            return;
1336        }
1337        ctx.stop_propagation();
1338    }
1339
1340    /// Activates only a left-button release matching the recorded root press.
1341    fn handle_root_pointer_release(
1342        &self,
1343        ctx: &mut EventCtx<A>,
1344        bounds: Rect,
1345        pos: Point,
1346        button: MouseButton,
1347    ) {
1348        let pressed = self.pressed_entry.read();
1349        self.pressed_entry.set(None);
1350        if button != MouseButton::Left {
1351            ctx.request_repaint();
1352            ctx.stop_propagation();
1353            return;
1354        }
1355        let entries = self.entries.read();
1356        let release = self
1357            .item_index_at(bounds, &entries, pos)
1358            .map(|index| (None, index));
1359        let Some(pressed) = pressed else {
1360            ctx.request_repaint();
1361            return;
1362        };
1363        if release != Some((pressed.parent, pressed.index)) {
1364            ctx.request_repaint();
1365            return;
1366        }
1367        if self.has_submenu(&entries, pressed.index) {
1368            self.open_submenu(ctx, &entries, pressed.index);
1369        } else {
1370            self.activate_entry(ctx, &entries, pressed.index);
1371        }
1372    }
1373
1374    /// Runs an enabled leaf action and closes the complete menu.
1375    fn activate_entry(&self, ctx: &mut EventCtx<A>, entries: &[ContextMenuEntry<A>], index: usize) {
1376        let Some(ContextMenuEntry::Item(item)) = entries.get(index) else {
1377            return;
1378        };
1379        if item.is_disabled() {
1380            ctx.stop_propagation();
1381            return;
1382        }
1383        if !item.submenu.is_empty() {
1384            self.open_submenu(ctx, entries, index);
1385            return;
1386        }
1387        if let Some(action) = &item.action {
1388            action.run(ctx);
1389        }
1390        self.close_with_runtime(ctx, PopupDismissReason::Programmatic);
1391        ctx.request_repaint();
1392        ctx.stop_propagation();
1393    }
1394
1395    /// Registers, places, and opens an enabled first-level submenu.
1396    fn open_submenu(&self, ctx: &mut EventCtx<A>, entries: &[ContextMenuEntry<A>], index: usize) {
1397        let Some(ContextMenuEntry::Item(item)) = entries.get(index) else {
1398            return;
1399        };
1400        if item.is_disabled() || item.submenu.is_empty() {
1401            return;
1402        }
1403        self.active_index.set(Some(index));
1404        self.submenu_parent_index.set(Some(index));
1405        self.submenu_active_index
1406            .set(self.first_enabled_index(&item.submenu));
1407
1408        let Some(root_geometry) = self
1409            .refresh_resolved_geometry()
1410            .or_else(|| self.geometry.get())
1411        else {
1412            ctx.request_repaint();
1413            ctx.stop_propagation();
1414            return;
1415        };
1416        let Some(parent_row) = self.entry_row(root_geometry.menu, entries, index) else {
1417            return;
1418        };
1419        let submenu = self.submenu_rect(
1420            root_geometry.viewport,
1421            root_geometry.menu,
1422            parent_row,
1423            &item.submenu,
1424        );
1425        if self.ensure_submenu_registered(ctx) {
1426            if let Some(popup_id) = self.submenu_popup_id.get() {
1427                let _ = ctx.runtime().open_popup(popup_id, parent_row, submenu);
1428            }
1429        }
1430        ctx.request_repaint();
1431        ctx.stop_propagation();
1432    }
1433
1434    /// Reports whether an indexed root item owns any submenu entries.
1435    fn has_submenu(&self, entries: &[ContextMenuEntry<A>], index: usize) -> bool {
1436        matches!(entries.get(index), Some(ContextMenuEntry::Item(item)) if !item.submenu.is_empty())
1437    }
1438
1439    /// Changes root keyboard selection and closes the current submenu.
1440    fn set_active(&self, ctx: &mut EventCtx<A>, next: Option<usize>) {
1441        self.active_index.set(next);
1442        self.close_submenu(ctx, PopupDismissReason::Programmatic);
1443        ctx.request_repaint();
1444        ctx.stop_propagation();
1445    }
1446
1447    /// Clones entries for the currently open submenu parent.
1448    fn submenu_entries(&self) -> Option<Vec<ContextMenuEntry<A>>> {
1449        let parent = self.submenu_parent_index.read()?;
1450        let entries = self.entries.read();
1451        let ContextMenuEntry::Item(item) = entries.get(parent)? else {
1452            return None;
1453        };
1454        Some(item.submenu.clone())
1455    }
1456
1457    /// Ensures the submenu portal has the current owner, parent, and content.
1458    fn ensure_submenu_registered(&self, ctx: &EventCtx<A>) -> bool {
1459        let (Some(root_popup_id), Some(submenu_popup_id)) =
1460            (self.root_popup_id, self.submenu_popup_id.get())
1461        else {
1462            return false;
1463        };
1464        let runtime = ctx.runtime();
1465        let owner = popup_owner_for_event(&runtime, ctx);
1466        let current_matches = {
1467            let portal = runtime.popup_portal();
1468            let portal = portal.borrow();
1469            portal.request(submenu_popup_id).is_some_and(|request| {
1470                request.owner() == &owner
1471                    && request.parent() == Some(root_popup_id)
1472                    && request.mount_policy() == PopupMountPolicy::RetainedOverlay
1473            })
1474        };
1475        if current_matches {
1476            return true;
1477        }
1478        if runtime.popup_portal().borrow().contains(submenu_popup_id) {
1479            runtime.unregister_popup(submenu_popup_id);
1480        }
1481        let content = context_menu_submenu_content(self.clone());
1482        runtime
1483            .register_popup(
1484                PopupRequest::new(submenu_popup_id, owner, content)
1485                    .with_parent(root_popup_id)
1486                    .with_semantics(menu_popup_semantics(true))
1487                    .with_mount_policy(PopupMountPolicy::RetainedOverlay),
1488            )
1489            .is_ok()
1490    }
1491
1492    /// Clears submenu interaction state and requests host dismissal.
1493    fn close_submenu(&self, ctx: &mut EventCtx<A>, reason: PopupDismissReason) {
1494        self.submenu_parent_index.set(None);
1495        self.submenu_active_index.set(None);
1496        self.pressed_entry.set(None);
1497        if let Some(popup_id) = self.submenu_popup_id.get() {
1498            ctx.runtime().close_popup(popup_id, reason);
1499        }
1500        ctx.request_repaint();
1501    }
1502
1503    /// Clears complete menu state, writable visibility, and both portals.
1504    fn close_with_runtime(&self, ctx: &mut EventCtx<A>, reason: PopupDismissReason) {
1505        if let Some(bound) = &self.bound_open {
1506            bound.set(false);
1507        } else if self.open.is_none() {
1508            self.internal_open.set(false);
1509        }
1510        self.last_requested_open.set(false);
1511        self.active_index.set(None);
1512        self.submenu_parent_index.set(None);
1513        self.submenu_active_index.set(None);
1514        self.pressed_entry.set(None);
1515        self.pointer_anchor.set(None);
1516        self.geometry.set(None);
1517        if let Some(popup_id) = self.root_popup_id {
1518            ctx.runtime().close_popup(popup_id, reason);
1519        }
1520        ctx.request_repaint();
1521        ctx.stop_propagation();
1522    }
1523
1524    /// Handles one-tier submenu Escape, navigation, and leaf activation.
1525    fn handle_submenu_keyboard(&self, ctx: &mut EventCtx<A>, key: &Key) {
1526        let Some(entries) = self.submenu_entries() else {
1527            self.close_submenu(ctx, PopupDismissReason::Programmatic);
1528            return;
1529        };
1530        match key {
1531            Key::Named(NamedKey::Escape | NamedKey::ArrowLeft) => {
1532                self.close_submenu(ctx, PopupDismissReason::Escape);
1533                ctx.stop_propagation();
1534            }
1535            Key::Named(NamedKey::ArrowDown) => {
1536                let next = self.next_enabled_index(&entries, self.submenu_active_index.read());
1537                self.submenu_active_index.set(next);
1538                ctx.request_repaint();
1539                ctx.stop_propagation();
1540            }
1541            Key::Named(NamedKey::ArrowUp) => {
1542                let next = self.previous_enabled_index(&entries, self.submenu_active_index.read());
1543                self.submenu_active_index.set(next);
1544                ctx.request_repaint();
1545                ctx.stop_propagation();
1546            }
1547            Key::Named(NamedKey::Home) => {
1548                self.submenu_active_index
1549                    .set(self.first_enabled_index(&entries));
1550                ctx.request_repaint();
1551                ctx.stop_propagation();
1552            }
1553            Key::Named(NamedKey::End) => {
1554                self.submenu_active_index
1555                    .set(self.last_enabled_index(&entries));
1556                ctx.request_repaint();
1557                ctx.stop_propagation();
1558            }
1559            Key::Named(NamedKey::Enter | NamedKey::Space) => {
1560                if let Some(index) = self
1561                    .submenu_active_index
1562                    .read()
1563                    .or_else(|| self.first_enabled_index(&entries))
1564                {
1565                    self.activate_submenu_entry(ctx, &entries, index);
1566                }
1567            }
1568            _ => {}
1569        }
1570    }
1571
1572    /// Highlights the enabled submenu item under the pointer.
1573    fn handle_submenu_pointer_move(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
1574        let Some(entries) = self.submenu_entries() else {
1575            return;
1576        };
1577        let next = self
1578            .item_index_at(bounds, &entries, pos)
1579            .filter(|index| matches!(entries.get(*index), Some(ContextMenuEntry::Item(item)) if !item.is_disabled()));
1580        if self.submenu_active_index.read() != next {
1581            self.submenu_active_index.set(next);
1582            ctx.request_repaint();
1583        }
1584    }
1585
1586    /// Records an enabled submenu press with its root parent identity.
1587    fn handle_submenu_pointer_press(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
1588        self.pressed_entry.set(None);
1589        let Some(parent) = self.submenu_parent_index.read() else {
1590            return;
1591        };
1592        let Some(entries) = self.submenu_entries() else {
1593            return;
1594        };
1595        if let Some(index) = self
1596            .item_index_at(bounds, &entries, pos)
1597            .filter(|index| matches!(entries.get(*index), Some(ContextMenuEntry::Item(item)) if !item.is_disabled()))
1598        {
1599            self.submenu_active_index.set(Some(index));
1600            self.pressed_entry.set(Some(ContextMenuPressedEntry {
1601                parent: Some(parent),
1602                index,
1603            }));
1604            ctx.request_repaint();
1605        }
1606        ctx.stop_propagation();
1607    }
1608
1609    /// Activates only a left-button release matching the submenu press.
1610    fn handle_submenu_pointer_release(
1611        &self,
1612        ctx: &mut EventCtx<A>,
1613        bounds: Rect,
1614        pos: Point,
1615        button: MouseButton,
1616    ) {
1617        let pressed = self.pressed_entry.read();
1618        self.pressed_entry.set(None);
1619        if button != MouseButton::Left {
1620            ctx.stop_propagation();
1621            return;
1622        }
1623        let Some(parent) = self.submenu_parent_index.read() else {
1624            return;
1625        };
1626        let Some(entries) = self.submenu_entries() else {
1627            return;
1628        };
1629        let release = self.item_index_at(bounds, &entries, pos);
1630        if pressed
1631            == release.map(|index| ContextMenuPressedEntry {
1632                parent: Some(parent),
1633                index,
1634            })
1635        {
1636            if let Some(index) = release {
1637                self.activate_submenu_entry(ctx, &entries, index);
1638            }
1639        }
1640        ctx.request_repaint();
1641        ctx.stop_propagation();
1642    }
1643
1644    /// Runs an enabled submenu leaf action and closes the complete menu.
1645    fn activate_submenu_entry(
1646        &self,
1647        ctx: &mut EventCtx<A>,
1648        entries: &[ContextMenuEntry<A>],
1649        index: usize,
1650    ) {
1651        let Some(ContextMenuEntry::Item(item)) = entries.get(index) else {
1652            return;
1653        };
1654        if item.is_disabled() || !item.submenu.is_empty() {
1655            ctx.stop_propagation();
1656            return;
1657        }
1658        if let Some(action) = &item.action {
1659            action.run(ctx);
1660        }
1661        self.close_with_runtime(ctx, PopupDismissReason::Programmatic);
1662    }
1663
1664    /// Paints a clipped popup shell, all rows, and the final border.
1665    fn paint_entries(
1666        &self,
1667        ctx: &mut PaintCtx<'_>,
1668        menu: Rect,
1669        entries: &[ContextMenuEntry<A>],
1670        active: Option<usize>,
1671    ) {
1672        paint_popup_shell(ctx, menu, &self.style.popup);
1673        ctx.with_overlay_clip(menu, |ctx| {
1674            let mut y = menu.y;
1675            for (idx, entry) in entries.iter().enumerate() {
1676                let height = self.entry_height(entry);
1677                let row = Rect::new(menu.x, y, menu.w, height);
1678                match entry {
1679                    ContextMenuEntry::Item(item) => {
1680                        self.paint_item(ctx, row, item, active == Some(idx));
1681                    }
1682                    ContextMenuEntry::Separator => {
1683                        let line = Rect::new(
1684                            row.x + self.style.padding_x,
1685                            row.y + (row.h - 1.0) * 0.5,
1686                            (row.w - self.style.padding_x * 2.0).max(0.0),
1687                            1.0,
1688                        );
1689                        ctx.push_overlay(DrawCmd::Rect(DrawRect {
1690                            rect: line,
1691                            color: self.style.separator,
1692                        }));
1693                    }
1694                }
1695                y += height;
1696            }
1697        });
1698        paint_popup_border(ctx, menu, &self.style.popup);
1699    }
1700
1701    /// Paints one item row with active, disabled, metadata, and submenu states.
1702    fn paint_item(
1703        &self,
1704        ctx: &mut PaintCtx<'_>,
1705        row: Rect,
1706        item: &ContextMenuItem<A>,
1707        active: bool,
1708    ) {
1709        let disabled = item.is_disabled();
1710        let opacity = if disabled {
1711            self.style.disabled_opacity
1712        } else {
1713            1.0
1714        };
1715        if active {
1716            ctx.push_overlay(DrawCmd::Rect(DrawRect {
1717                rect: row,
1718                color: apply_opacity(self.style.popup.option_active, opacity),
1719            }));
1720        }
1721
1722        let mut x = row.x + self.style.padding_x;
1723        if let Some(icon) = &item.icon {
1724            ctx.push_overlay(DrawCmd::Image(DrawImage {
1725                rect: Rect::new(
1726                    x,
1727                    row.y + (row.h - self.style.icon_size) * 0.5,
1728                    self.style.icon_size,
1729                    self.style.icon_size,
1730                ),
1731                icon: icon.clone(),
1732                tint: apply_opacity(
1733                    if disabled {
1734                        self.style.popup.disabled_icon_tint
1735                    } else {
1736                        self.style.popup.icon_tint
1737                    },
1738                    opacity,
1739                ),
1740                rotation_rad: 0.0,
1741            }));
1742            x += self.style.icon_size + self.style.icon_gap;
1743        }
1744
1745        let trailing_icon_w = if item.submenu.is_empty() {
1746            0.0
1747        } else {
1748            self.style.icon_size + self.style.icon_gap
1749        };
1750        let shortcut_w = item
1751            .shortcut
1752            .as_ref()
1753            .map(|shortcut| {
1754                measure_text(
1755                    ctx.text_system.as_deref_mut(),
1756                    shortcut,
1757                    self.style.shortcut_text,
1758                )
1759                .w
1760            })
1761            .unwrap_or(0.0);
1762        let text_style = if disabled {
1763            self.style.popup.disabled_text
1764        } else {
1765            self.style.popup.text
1766        };
1767        let text_right =
1768            row.right() - self.style.padding_x - shortcut_w - self.style.icon_gap - trailing_icon_w;
1769        paint_overlay_text_in_rect(
1770            ctx,
1771            &item.label,
1772            text_style,
1773            Rect::new(x, row.y, (text_right - x).max(0.0), row.h),
1774            opacity,
1775        );
1776        if let Some(shortcut) = &item.shortcut {
1777            paint_overlay_text_in_rect(
1778                ctx,
1779                shortcut,
1780                self.style.shortcut_text,
1781                Rect::new(
1782                    row.right() - self.style.padding_x - shortcut_w - trailing_icon_w,
1783                    row.y,
1784                    shortcut_w,
1785                    row.h,
1786                ),
1787                opacity,
1788            );
1789        }
1790        if !item.submenu.is_empty() {
1791            ctx.push_overlay(DrawCmd::Image(DrawImage {
1792                rect: Rect::new(
1793                    row.right() - self.style.padding_x - self.style.icon_size,
1794                    row.y + (row.h - self.style.icon_size) * 0.5,
1795                    self.style.icon_size,
1796                    self.style.icon_size,
1797                ),
1798                icon: IconId::Lucide(Icon::ChevronRight),
1799                tint: apply_opacity(self.style.popup.icon_tint, opacity),
1800                rotation_rad: 0.0,
1801            }));
1802        }
1803    }
1804}
1805
1806/// Root popup component that obtains the child submenu popup identifier.
1807struct RetainedContextMenuRootComponent<A> {
1808    /// Shared controller used to build root popup content.
1809    controller: ContextMenuController<A>,
1810}
1811
1812impl<A: 'static> ComponentNode<A> for RetainedContextMenuRootComponent<A> {
1813    fn build(&self, context: &mut Context<A>) -> View<A> {
1814        self.controller.submenu_popup_id.set(
1815            context
1816                .runtime()
1817                .popup_id_for_element(context.element_id())
1818                .ok(),
1819        );
1820        View::leaf(RetainedContextMenuRoot {
1821            controller: self.controller.clone(),
1822        })
1823    }
1824}
1825
1826/// Retained root popup widget for painting and dispatching menu interaction.
1827struct RetainedContextMenuRoot<A> {
1828    /// Shared controller handling root layout, paint, and input.
1829    controller: ContextMenuController<A>,
1830}
1831
1832impl<A> Clone for RetainedContextMenuRoot<A> {
1833    fn clone(&self) -> Self {
1834        Self {
1835            controller: self.controller.clone(),
1836        }
1837    }
1838}
1839
1840impl<A: 'static> Widget<A> for RetainedContextMenuRoot<A> {
1841    fn debug_name(&self) -> &'static str {
1842        "ContextMenuPopup"
1843    }
1844
1845    fn layout(
1846        &self,
1847        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1848        _ctx: &mut LayoutCtx<'_>,
1849        _children: &mut [LayoutChild],
1850        constraints: Constraints,
1851    ) -> LayoutResult {
1852        retained_context_menu_layout(
1853            constraints,
1854            self.controller.style.width,
1855            self.controller.menu_height(&self.controller.entries.read()),
1856            self.controller.style.popup.popup_max_height,
1857        )
1858    }
1859
1860    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1861        self.controller.paint_entries(
1862            ctx,
1863            bounds,
1864            &self.controller.entries.read(),
1865            self.controller.active_index.read(),
1866        );
1867    }
1868
1869    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1870        if self.controller.disabled.read() {
1871            self.controller
1872                .close_with_runtime(ctx, PopupDismissReason::Programmatic);
1873            return;
1874        }
1875        match event {
1876            Event::Keyboard(key) if key.state == KeyState::Pressed && !key.repeat => {
1877                self.controller.handle_root_keyboard(ctx, &key.key);
1878            }
1879            Event::Pointer(PointerEvent::Moved { pos, .. }) => {
1880                self.controller.handle_root_pointer_move(ctx, bounds, *pos);
1881            }
1882            Event::Pointer(PointerEvent::Button {
1883                pos,
1884                button: MouseButton::Left | MouseButton::Right,
1885                pressed: true,
1886                ..
1887            }) => self.controller.handle_root_pointer_press(ctx, bounds, *pos),
1888            Event::Pointer(PointerEvent::Button {
1889                pos,
1890                button: MouseButton::Left | MouseButton::Right,
1891                pressed: false,
1892                ..
1893            }) => self.controller.handle_root_pointer_release(
1894                ctx,
1895                bounds,
1896                *pos,
1897                event_pointer_button(event),
1898            ),
1899            Event::Pointer(PointerEvent::Cancelled { .. }) => {
1900                self.controller.pressed_entry.set(None);
1901                ctx.request_repaint();
1902                ctx.stop_propagation();
1903            }
1904            _ => {}
1905        }
1906    }
1907
1908    fn focus_policy(&self) -> FocusPolicy {
1909        FocusPolicy::Focusable
1910    }
1911
1912    fn activation_policy(&self) -> ActivationPolicy {
1913        ActivationPolicy::SuppressOnFocusOnly
1914    }
1915
1916    fn hover_cursor_role_at(
1917        &self,
1918        bounds: Rect,
1919        _layout: &LayoutResult,
1920        pos: Point,
1921    ) -> HoverCursorRole {
1922        let entries = self.controller.entries.read();
1923        self.controller
1924            .item_index_at(bounds, &entries, pos)
1925            .filter(|index| matches!(entries.get(*index), Some(ContextMenuEntry::Item(item)) if !item.is_disabled()))
1926            .map_or(HoverCursorRole::Default, |_| HoverCursorRole::Pointer)
1927    }
1928}
1929
1930/// Retained first-level submenu widget sharing the root controller.
1931struct RetainedContextSubmenu<A> {
1932    /// Shared controller handling submenu layout, paint, and input.
1933    controller: ContextMenuController<A>,
1934}
1935
1936impl<A> Clone for RetainedContextSubmenu<A> {
1937    fn clone(&self) -> Self {
1938        Self {
1939            controller: self.controller.clone(),
1940        }
1941    }
1942}
1943
1944impl<A: 'static> Widget<A> for RetainedContextSubmenu<A> {
1945    fn debug_name(&self) -> &'static str {
1946        "ContextSubmenuPopup"
1947    }
1948
1949    fn layout(
1950        &self,
1951        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1952        _ctx: &mut LayoutCtx<'_>,
1953        _children: &mut [LayoutChild],
1954        constraints: Constraints,
1955    ) -> LayoutResult {
1956        let entries = self.controller.submenu_entries().unwrap_or_default();
1957        retained_context_menu_layout(
1958            constraints,
1959            self.controller.style.submenu_width,
1960            self.controller.menu_height(&entries),
1961            self.controller.style.popup.popup_max_height,
1962        )
1963    }
1964
1965    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1966        let Some(entries) = self.controller.submenu_entries() else {
1967            return;
1968        };
1969        self.controller.paint_entries(
1970            ctx,
1971            bounds,
1972            &entries,
1973            self.controller.submenu_active_index.read(),
1974        );
1975    }
1976
1977    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1978        match event {
1979            Event::Keyboard(key) if key.state == KeyState::Pressed && !key.repeat => {
1980                self.controller.handle_submenu_keyboard(ctx, &key.key);
1981            }
1982            Event::Pointer(PointerEvent::Moved { pos, .. }) => {
1983                self.controller
1984                    .handle_submenu_pointer_move(ctx, bounds, *pos);
1985            }
1986            Event::Pointer(PointerEvent::Button {
1987                pos,
1988                button: MouseButton::Left | MouseButton::Right,
1989                pressed: true,
1990                ..
1991            }) => self
1992                .controller
1993                .handle_submenu_pointer_press(ctx, bounds, *pos),
1994            Event::Pointer(PointerEvent::Button {
1995                pos,
1996                button: MouseButton::Left | MouseButton::Right,
1997                pressed: false,
1998                ..
1999            }) => self.controller.handle_submenu_pointer_release(
2000                ctx,
2001                bounds,
2002                *pos,
2003                event_pointer_button(event),
2004            ),
2005            Event::Pointer(PointerEvent::Cancelled { .. }) => {
2006                self.controller.pressed_entry.set(None);
2007                ctx.request_repaint();
2008                ctx.stop_propagation();
2009            }
2010            _ => {}
2011        }
2012    }
2013
2014    fn focus_policy(&self) -> FocusPolicy {
2015        FocusPolicy::Focusable
2016    }
2017
2018    fn activation_policy(&self) -> ActivationPolicy {
2019        ActivationPolicy::SuppressOnFocusOnly
2020    }
2021
2022    fn hover_cursor_role_at(
2023        &self,
2024        bounds: Rect,
2025        _layout: &LayoutResult,
2026        pos: Point,
2027    ) -> HoverCursorRole {
2028        let Some(entries) = self.controller.submenu_entries() else {
2029            return HoverCursorRole::Default;
2030        };
2031        self.controller
2032            .item_index_at(bounds, &entries, pos)
2033            .filter(|index| matches!(entries.get(*index), Some(ContextMenuEntry::Item(item)) if !item.is_disabled()))
2034            .map_or(HoverCursorRole::Default, |_| HoverCursorRole::Pointer)
2035    }
2036}
2037
2038/// Wraps the retained root component in reusable popup content.
2039fn context_menu_root_content<A: 'static>(controller: ContextMenuController<A>) -> PopupContent<A> {
2040    PopupContent::new(move || {
2041        View::component(RetainedContextMenuRootComponent {
2042            controller: controller.clone(),
2043        })
2044    })
2045}
2046
2047/// Wraps the retained submenu widget in reusable popup content.
2048fn context_menu_submenu_content<A: 'static>(
2049    controller: ContextMenuController<A>,
2050) -> PopupContent<A> {
2051    PopupContent::new(move || {
2052        View::leaf(RetainedContextSubmenu {
2053            controller: controller.clone(),
2054        })
2055    })
2056}
2057
2058/// Constrains a popup to requested width and capped content height.
2059fn retained_context_menu_layout(
2060    constraints: Constraints,
2061    width: f32,
2062    content_height: f32,
2063    max_height: f32,
2064) -> LayoutResult {
2065    let size = constraints.constrain(Size::new(width, content_height.min(max_height)));
2066    let bounds = Rect::new(0.0, 0.0, size.w, size.h);
2067    LayoutResult {
2068        size,
2069        children: Vec::new(),
2070        paint_bounds: bounds,
2071        visual_bounds: bounds,
2072        overlay_hit_bounds: Vec::new(),
2073        clip: Some(ailloli_ui_core::ClipShape::Rect(bounds)),
2074        is_window_root_clip: false,
2075        artifact: None,
2076    }
2077}
2078
2079/// Resolves popup ownership from event, presentation, or headless context.
2080fn popup_owner_for_event<A>(runtime: &RuntimeHandle<A>, ctx: &EventCtx<A>) -> PopupOwner {
2081    if let Some(meta) = ctx.event_meta() {
2082        return PopupOwner::new(
2083            meta.logical_window_id().clone(),
2084            meta.presentation_generation(),
2085            runtime.element_tree_id(),
2086            ctx.target(),
2087        );
2088    }
2089    if let Some((window, generation)) = runtime.presentation_scope() {
2090        return PopupOwner::new(window, generation, runtime.element_tree_id(), ctx.target());
2091    }
2092    PopupOwner::new(
2093        HEADLESS_POPUP_WINDOW_ID,
2094        PresentationGeneration::INITIAL,
2095        runtime.element_tree_id(),
2096        ctx.target(),
2097    )
2098}
2099
2100/// Extracts a pointer button and falls back to left for non-button events.
2101fn event_pointer_button(event: &Event) -> MouseButton {
2102    match event {
2103        Event::Pointer(PointerEvent::Button { button, .. }) => *button,
2104        _ => MouseButton::Left,
2105    }
2106}
2107
2108/// Resolves host size from its child or finite maximum constraints.
2109fn host_slot_size<A: 'static>(
2110    engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
2111    ctx: &mut LayoutCtx<'_>,
2112    children: &mut [LayoutChild],
2113    constraints: Constraints,
2114    layout: LayoutStyle,
2115) -> Size {
2116    let intrinsic = if let Some(child) = children.first_mut() {
2117        ctx.with_layout_pass(LayoutPass::Measure, |ctx| {
2118            child.layout(engine, ctx, constraints.loosen()).size
2119        })
2120    } else {
2121        Size::new(
2122            finite_or(constraints.max_w, 0.0),
2123            finite_or(constraints.max_h, 0.0),
2124        )
2125    };
2126    apply_layout_size(intrinsic, layout, constraints)
2127}
2128
2129/// Returns `value` when finite and `fallback` for NaN or either infinity.
2130fn finite_or(value: f32, fallback: f32) -> f32 {
2131    if value.is_finite() {
2132        value
2133    } else {
2134        fallback
2135    }
2136}