Skip to main content

day_pieces/
menus.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The app menu builder: `menu_item`, `sub_menu`, `menu_separator`, and `menu_role`, assembled
5//! with `app_menu`. Lowers to day_spec's toolkit-neutral `MenuItem` model and registers each
6//! item's action closure.
7
8use std::cell::RefCell;
9use std::rc::Rc;
10
11use day_reactive::Scope;
12
13use crate::{IntoReactive, IntoText, Reactive, TextSource};
14
15// ---------------------------------------------------------------------------
16// Menus: the app-side builder over day_spec's toolkit-neutral MenuItem model. Lowering registers
17// each item's action closure with day-core (which dispatches `Event::MenuAction`) and assigns its
18// id.
19// ---------------------------------------------------------------------------
20
21/// A menu entry under construction. Build a command with [`menu_item`], a nested submenu with
22/// [`sub_menu`], a standard system command with [`menu_role`], and a divider with [`menu_separator`].
23/// Attach to a Piece via [`Decorate::context_menu`](crate::decorators::Decorate::context_menu) or install app-wide via [`app_menu`].
24#[derive(Clone)]
25pub struct MenuEntry {
26    id: Option<String>,
27    /// The title, live: resolved (tracked) when the menu is lowered, so a localized title
28    /// follows a language switch and a title built from a signal follows the signal.
29    label: TextSource,
30    shortcut: Option<day_spec::Shortcut>,
31    enabled: Reactive<bool>,
32    role: Option<day_spec::MenuRole>,
33    icon: Option<day_spec::Icon>,
34    checked: Option<Reactive<bool>>,
35    action: Option<Rc<dyn Fn()>>,
36    children: Option<Vec<MenuEntry>>,
37    separator: bool,
38    bar_role: Option<day_spec::MenuBarRole>,
39}
40
41impl MenuEntry {
42    fn command(label: TextSource) -> MenuEntry {
43        MenuEntry {
44            id: None,
45            label,
46            shortcut: None,
47            enabled: Reactive::Const(true),
48            role: None,
49            icon: None,
50            bar_role: None,
51            checked: None,
52            action: None,
53            children: None,
54            separator: false,
55        }
56    }
57
58    /// A standard [`Symbol`](day_spec::Symbol) beside the item's title, drawn with the
59    /// platform's glyph, the same vocabulary toolbars take. Menus carry icons on macOS,
60    /// Windows, GNOME, KDE and Android; a backend whose menus are text-only ignores it, so an
61    /// icon is always an addition to a menu that already reads correctly without one.
62    pub fn icon(mut self, s: day_spec::Symbol) -> MenuEntry {
63        self.icon = Some(day_spec::Icon::Symbol(s));
64        self
65    }
66
67    /// A bundled image from `resource/images`, for an item the standard set has no glyph for:
68    /// an app's own vocabulary (a shape, a brand). Same rule as [`MenuEntry::icon`].
69    pub fn image(mut self, name: impl Into<String>) -> MenuEntry {
70        self.icon = Some(day_spec::Icon::Image(name.into()));
71        self
72    }
73    /// Run `f` when the item is chosen.
74    pub fn action(mut self, f: impl Fn() + 'static) -> MenuEntry {
75        self.action = Some(Rc::new(f));
76        self
77    }
78    /// Full shortcut spec, e.g. `Shortcut::primary("s").shift()`.
79    pub fn shortcut(mut self, s: day_spec::Shortcut) -> MenuEntry {
80        self.shortcut = Some(s);
81        self
82    }
83    /// Convenience: the platform's primary modifier (⌘ / Ctrl) + `key`. This sets the item's
84    /// shortcut; to name the item, use [`MenuEntry::id`].
85    pub fn key(mut self, key: impl Into<String>) -> MenuEntry {
86        self.shortcut = Some(day_spec::Shortcut::primary(key));
87        self
88    }
89
90    /// Name this item, so something outside the menu can address it: a dayscript
91    /// `menu: { id: "view-both" }` step, or a `tap` on the composed menu's row where the platform
92    /// has no native menus.
93    ///
94    /// A label cannot do that job. It is localized, so it changes with the run's language, and an
95    /// item that shows its own state changes it whenever the state moves, which is exactly the
96    /// case [`MenuEntry::checked`] creates. Give an id to any item a script drives.
97    pub fn id(mut self, id: day_core::ElementId) -> MenuEntry {
98        self.id = Some(id.as_str().to_owned());
99        self
100    }
101
102    /// Draw this item with the platform's check mark, on or off, for a setting the menu toggles
103    /// or one of several mutually exclusive choices. An item that never calls this is a plain
104    /// command and reserves no room for a mark.
105    ///
106    /// Choosing the item still runs its [`action`](MenuEntry::action); no backend flips the mark
107    /// by itself. The app owns the state: pass the signal (or a closure reading it) and the mark
108    /// follows the state, the menu re-lowering when it changes.
109    ///
110    /// ```ignore
111    /// menu_item(tr("view_grid")).id(day_core::id!(view_grid)).checked(grid).action(move || grid.set(!grid.get()))
112    /// ```
113    pub fn checked<M>(mut self, on: impl IntoReactive<bool, M>) -> MenuEntry {
114        self.checked = Some(on.into_reactive());
115        self
116    }
117    /// Whether the item can be chosen (default `true`): a constant, a `Signal<bool>`, or a
118    /// closure, re-read whenever the menu is lowered.
119    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> MenuEntry {
120        self.enabled = on.into_reactive();
121        self
122    }
123    /// Tag a custom command with a standard [`day_spec::MenuRole`] (usually you use [`menu_role`]).
124    pub fn role(mut self, role: day_spec::MenuRole) -> MenuEntry {
125        self.role = Some(role);
126        self
127    }
128}
129
130/// A clickable command: `menu_item(res::str::save()).key("s").action(|| …)`. The title takes
131/// the same sources as a label (a literal, a localized text, a signal, a closure) and stays
132/// live.
133pub fn menu_item<M>(label: impl IntoText<M>) -> MenuEntry {
134    MenuEntry::command(label.into_text())
135}
136
137/// A nested submenu: `sub_menu(res::str::menu_file(), vec![menu_item(…), …])`.
138pub fn sub_menu<M>(label: impl IntoText<M>, items: Vec<MenuEntry>) -> MenuEntry {
139    MenuEntry {
140        children: Some(items),
141        ..MenuEntry::command(label.into_text())
142    }
143}
144
145/// Claim one of the platform's standard menu-bar slots for this submenu: the backend places it
146/// where that menu belongs and does not add its stock version. Without a role, a submenu is
147/// an app menu and sits between the standard ones.
148///
149/// ```ignore
150/// sub_menu(res::str::menu_file(), menu_items).bar_role(MenuBarRole::File)
151/// ```
152impl MenuEntry {
153    pub fn bar_role(mut self, role: day_spec::MenuBarRole) -> MenuEntry {
154        self.bar_role = Some(role);
155        self
156    }
157}
158
159/// A visual divider between items.
160pub fn menu_separator() -> MenuEntry {
161    MenuEntry {
162        separator: true,
163        ..MenuEntry::command(TextSource::Static(String::new()))
164    }
165}
166
167/// A standard/system command (`MenuRole::Copy`, `MenuRole::Quit`, …) rendered with the platform's
168/// native item (correct label, default shortcut, focus-targeting, and automatic enable/disable),
169/// so default menu items (Edit ▸ Cut/Copy/Paste, the app's Quit/About) work without
170/// re-implementation.
171pub fn menu_role(role: day_spec::MenuRole) -> MenuEntry {
172    MenuEntry {
173        role: Some(role),
174        ..MenuEntry::command(TextSource::Static(String::new()))
175    }
176}
177
178/// The core-catalog key for a standard menu command's label (docs/menus.md, docs/localization.md).
179fn role_catalog_key(role: day_spec::MenuRole) -> &'static str {
180    use day_spec::MenuRole as R;
181    match role {
182        R::Cut => "day_cut",
183        R::Copy => "day_copy",
184        R::Paste => "day_paste",
185        R::SelectAll => "day_select_all",
186        R::Undo => "day_undo",
187        R::Redo => "day_redo",
188        R::Delete => "day_delete",
189        R::About => "day_about",
190        R::Quit => "day_quit",
191        R::Preferences => "day_preferences",
192        R::Minimize => "day_minimize",
193        R::CloseWindow => "day_close",
194        R::Fullscreen => "day_fullscreen",
195        R::NewWindow => "day_new_window",
196        R::CheckForUpdates => "day_check_for_updates",
197    }
198}
199
200/// Lower app-side entries to the spec model, registering action closures with day-core. A standard
201/// `role` item with no explicit label gets its label from the localized core catalog here, so the
202/// backends receive a ready, locale-correct label instead of each hardcoding English (day-localization).
203///
204/// This variant registers process-lived closures, correct for the app menu and toolbars, whose
205/// ids day-core manages by shape-rebinding, toolbar slots and explicit sweeps. Menus owned by a piece build
206/// (a `.context_menu`, a nav row's menu) go through [`lower_menu_scoped`] instead, so their
207/// closures are reclaimed when the registering scope is disposed rather than leaking per remount.
208pub(crate) fn lower_menu(entries: Vec<MenuEntry>) -> Vec<day_spec::MenuItem> {
209    lower_menu_with(entries, &day_core::register_menu_action)
210}
211
212/// [`lower_menu`] with scope-tied action registration (see there for when to use which).
213pub(crate) fn lower_menu_scoped(entries: Vec<MenuEntry>) -> Vec<day_spec::MenuItem> {
214    lower_menu_with(entries, &day_core::register_scoped_menu_action)
215}
216
217fn lower_menu_with(
218    entries: Vec<MenuEntry>,
219    register: &dyn Fn(Rc<dyn Fn()>) -> u64,
220) -> Vec<day_spec::MenuItem> {
221    entries
222        .into_iter()
223        .map(|e| {
224            if e.separator {
225                day_spec::MenuItem::Separator
226            } else if let Some(children) = e.children {
227                day_spec::MenuItem::Submenu {
228                    label: e.label.resolve(),
229                    items: lower_menu_with(children, register),
230                    role: e.bar_role,
231                }
232            } else {
233                let mut action = e.action.map(register).unwrap_or(0);
234                // Tracked reads: a menu lowered inside `app_menu`'s effect re-lowers when
235                // a title, availability or check state changes.
236                let mut enabled = e.enabled.get();
237                let mut shortcut = e.shortcut;
238                // Window roles have no native selector on any platform: an action-less item
239                // lowers to the registered day dispatcher (docs/windows.md): live when the
240                // app registered a builder/preferences piece, disabled otherwise.
241                if action == 0 {
242                    match e.role {
243                        Some(day_spec::MenuRole::NewWindow) => {
244                            action = day_core::windows::new_window_action_id();
245                            enabled = enabled && action != 0;
246                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("n")));
247                        }
248                        // The undo pair and the clipboard trio lower to standing dispatchers
249                        // too, for toolkits whose role items come back as plain menu actions
250                        // (Android's app-bar menu, the iOS menu, web context menus). Toolkits
251                        // with a native responder route ignore the action and keep their selector
252                        // (see each backend's menu build). Each also takes the platform-neutral
253                        // standard shortcut (primary+Z/X/C/V/A, shift for redo) unless the app
254                        // set its own. AppKit's native items already carry these, so this is
255                        // what gives GTK/Qt/web the same accelerators.
256                        Some(day_spec::MenuRole::Undo) => {
257                            action = day_core::undo_action_id(false);
258                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("z")));
259                        }
260                        Some(day_spec::MenuRole::Redo) => {
261                            action = day_core::undo_action_id(true);
262                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("z").shift()));
263                        }
264                        Some(day_spec::MenuRole::Cut) => {
265                            action = day_core::edit_action_id(day_spec::EditOp::Cut);
266                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("x")));
267                        }
268                        Some(day_spec::MenuRole::Copy) => {
269                            action = day_core::edit_action_id(day_spec::EditOp::Copy);
270                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("c")));
271                        }
272                        Some(day_spec::MenuRole::Paste) => {
273                            action = day_core::edit_action_id(day_spec::EditOp::Paste);
274                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("v")));
275                        }
276                        Some(day_spec::MenuRole::SelectAll) => {
277                            action = day_core::edit_action_id(day_spec::EditOp::SelectAll);
278                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("a")));
279                        }
280                        Some(day_spec::MenuRole::Preferences) => {
281                            action = day_core::windows::preferences_action_id();
282                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary(",")));
283                        }
284                        // About keeps the toolkit's stock panel (action 0) until an app
285                        // registers its own (docs/settings.md); the updater command has no
286                        // native fallback and lowers disabled when nothing registered.
287                        Some(day_spec::MenuRole::About) => {
288                            action = day_core::windows::about_action_id();
289                        }
290                        Some(day_spec::MenuRole::CheckForUpdates) => {
291                            action = day_core::windows::check_for_updates_action_id();
292                            enabled = enabled && action != 0;
293                        }
294                        _ => {}
295                    }
296                }
297                let label = e.label.resolve();
298                let label = match (label.is_empty(), e.role) {
299                    (true, Some(role)) => day_localization::t(role_catalog_key(role)),
300                    _ => label,
301                };
302                day_spec::MenuItem::Action {
303                    id: e.id,
304                    action,
305                    label,
306                    shortcut,
307                    enabled,
308                    checked: e.checked.as_ref().map(Reactive::get),
309                    role: e.role,
310                    icon: e.icon,
311                }
312            }
313        })
314        .collect()
315}
316
317/// Where a menu's entries come from: a fixed list, or a closure that derives the list and
318/// re-runs whenever its reactive reads change. What [`app_menu`], [`dock_menu`] and
319/// [`StatusItem::menu`](crate::StatusItem::menu) accept, through [`MenuContent`].
320#[derive(Clone)]
321pub enum MenuSource {
322    Fixed(Vec<MenuEntry>),
323    Derived(Rc<dyn Fn() -> Vec<MenuEntry>>),
324}
325
326impl MenuSource {
327    /// The entries right now: a tracked read for a derived source.
328    pub(crate) fn entries(&self) -> Vec<MenuEntry> {
329        match self {
330            MenuSource::Fixed(v) => v.clone(),
331            MenuSource::Derived(f) => f(),
332        }
333    }
334}
335
336/// Anything an app menu takes: a `Vec` or array of entries, or a closure that derives the
337/// entries and re-runs whenever its reactive reads change. The marker parameter is the same
338/// E0119 dodge as [`ToolbarContent`](crate::ToolbarContent).
339pub trait MenuContent<M> {
340    fn into_source(self) -> MenuSource;
341}
342
343impl MenuContent<crate::ManyMark> for Vec<MenuEntry> {
344    fn into_source(self) -> MenuSource {
345        MenuSource::Fixed(self)
346    }
347}
348
349impl<const N: usize> MenuContent<crate::ManyMark> for [MenuEntry; N] {
350    fn into_source(self) -> MenuSource {
351        MenuSource::Fixed(Vec::from(self))
352    }
353}
354
355impl<C, F> MenuContent<crate::DerivedMark> for F
356where
357    C: IntoIterator<Item = MenuEntry>,
358    F: Fn() -> C + 'static,
359{
360    fn into_source(self) -> MenuSource {
361        MenuSource::Derived(Rc::new(move || self().into_iter().collect()))
362    }
363}
364
365thread_local! {
366    /// The scope owning the current app-menu and dock-menu installs, so a second call replaces
367    /// the first (and reclaims its bindings) instead of leaving two installers racing.
368    static APP_MENU_SCOPE: RefCell<Option<Scope>> = const { RefCell::new(None) };
369    static DOCK_MENU_SCOPE: RefCell<Option<Scope>> = const { RefCell::new(None) };
370}
371
372/// Install `source` through `install`, in a root-owned scope that replaces the previous one.
373fn install_menu(
374    slot: &'static std::thread::LocalKey<RefCell<Option<Scope>>>,
375    source: MenuSource,
376    install: fn(Vec<day_spec::MenuItem>),
377) {
378    if let Some(old) = slot.with(|s| s.borrow_mut().take()) {
379        old.dispose();
380    }
381    let scope = Scope::root().enter(Scope::child);
382    scope.enter(|| {
383        day_reactive::bind(
384            move || {
385                // Track the locale even when the entries carry no localized reads, so
386                // role-label fallbacks still refresh; every entry's title, availability and
387                // check state is a tracked read of its own inside `lower_menu`.
388                let _ = day_localization::locale().get();
389                lower_menu(source.entries())
390            },
391            move |items: &Vec<day_spec::MenuItem>| install(items.clone()),
392        );
393    });
394    slot.with(|s| *s.borrow_mut() = Some(scope));
395}
396
397/// Install the application menu: the native menu bar on desktop, the app-bar overflow on Android,
398/// the UIMenuBuilder main menu on iPadOS/Catalyst. Top-level entries are usually `sub_menu(…)`s
399/// (the menu-bar menus). Takes a list of entries or a closure that derives them.
400///
401/// The menu is live (docs/menus.md): every title, `enabled` and `checked` is re-read, and the
402/// menu re-lowered and reinstalled, whenever one of them changes, so `menu_role` labels,
403/// `res::str` titles and `day::tr` all follow a runtime language switch, and a derived closure
404/// re-runs on whatever signals it reads. Calling it again replaces the previous install and
405/// reclaims its action closures. Install once, at startup.
406///
407/// ```ignore
408/// app_menu([
409///     sub_menu(res::str::menu_file(), vec![menu_item(res::str::new_item()).key("n").action(add)]),
410///     sub_menu(res::str::menu_view(), vec![menu_item(res::str::grid()).checked(grid).action(flip)]),
411/// ]);
412/// ```
413pub fn app_menu<M>(menus: impl MenuContent<M>) {
414    install_menu(&APP_MENU_SCOPE, menus.into_source(), day_core::set_app_menu);
415}
416
417/// Install the app's Dock menu (docs/menus.md "Dock menu"): the entries macOS lists when the
418/// user right-clicks the app's Dock icon, above the app's `[[shortcuts]]` and the system's own
419/// Show / Hide / Quit items. Probe `Cap::DockMenu`; elsewhere the call does nothing. Live, like
420/// [`app_menu`]: `Resume <last document>`, a checked "Do Not Disturb", the locale. Install
421/// once, at startup.
422///
423/// The menu works while the app runs, so its actions are ordinary closures, unlike shortcuts,
424/// which are routes because they also launch the app.
425pub fn dock_menu<M>(entries: impl MenuContent<M>) {
426    install_menu(
427        &DOCK_MENU_SCOPE,
428        entries.into_source(),
429        day_core::set_dock_menu,
430    );
431}
432
433// ---------------------------------------------------------------------------
434// The composed context menu (docs/menus.md "Dynamic context menus"): presentation for a
435// toolkit that REPORTS the summon (`Event::ContextMenu`) instead of showing a native menu
436// of its own (web-dom). Works on the LOWERED model, so role resolution, localization, and
437// per-summon action scoping are exactly what a native backend would have received.
438// ---------------------------------------------------------------------------
439
440/// The composed menu's stand-in for a native check mark, and the blank that holds its column.
441const COMPOSED_CHECK_ON: &str = "\u{2713}\u{2002}";
442const COMPOSED_CHECK_OFF: &str = "\u{2002}\u{2002}";
443/// Panel width of the composed menu, and the extra indent inlined submenu items take.
444const COMPOSED_MENU_W: f64 = 220.0;
445const COMPOSED_SUBMENU_INDENT: f64 = 12.0;
446
447/// Mount the composed presentation beside a `.context_menu` node: an
448/// `Event::ContextMenu` handler plus a lazily-armed, unrouted [`crate::cover`] that shows the
449/// provider's items at the summon point. Nothing builds until the first summon arrives, so
450/// backends that serve the menu natively (and therefore never emit the event) never pay.
451pub(crate) fn mount_composed_menu(
452    cx: &mut day_core::BuildCx,
453    node: day_core::RNode,
454    provider: day_spec::ContextMenuFn,
455) {
456    use day_reactive::Signal;
457    use std::cell::RefCell;
458
459    struct Pending {
460        items: Vec<day_spec::MenuItem>,
461        at: day_spec::Point,
462    }
463    let armed = Signal::new(false);
464    let open: Signal<Option<String>> = Signal::new(None);
465    let pending: Rc<RefCell<Pending>> = Rc::new(RefCell::new(Pending {
466        items: Vec::new(),
467        at: day_spec::Point::ZERO,
468    }));
469
470    {
471        let pending = pending.clone();
472        cx.on(node, move |ev| {
473            if let day_spec::Event::ContextMenu { local, window } = ev {
474                let items = provider(*local);
475                if items.is_empty() {
476                    return;
477                }
478                *pending.borrow_mut() = Pending { items, at: *window };
479                armed.set(true);
480                open.set(Some("menu".into()));
481            }
482        });
483    }
484
485    let host = crate::when(
486        move || armed.get(),
487        move || {
488            let pending = pending.clone();
489            crate::cover(open, move |_: &String| {
490                let (items, at) = {
491                    let p = pending.borrow();
492                    (p.items.clone(), p.at)
493                };
494                composed_menu_host(items, at, open)
495            })
496            .unrouted()
497            .background(|_| day_spec::Color::rgba(0.0, 0.0, 0.0, 0.0))
498        },
499    );
500    let _ = day_core::Piece::build(host, cx);
501}
502
503/// The presented surface: a fullscreen dismiss catcher plus the item panel, placed at the
504/// summon point (clamped into the window by [`MenuPlace`]).
505fn composed_menu_host(
506    items: Vec<day_spec::MenuItem>,
507    at: day_spec::Point,
508    open: day_reactive::Signal<Option<String>>,
509) -> impl day_core::Piece {
510    use crate::Decorate;
511
512    let mut rows: Vec<day_core::AnyPiece> = Vec::new();
513    let mut next = 0usize;
514    composed_menu_rows(&items, 0.0, &mut next, open, &mut rows);
515
516    let panel = crate::column(rows)
517        .padding(day_spec::Insets::symmetric(0.0, 5.0))
518        .background(|| {
519            if day_core::dark_mode() {
520                day_spec::Color::rgb(0.22, 0.22, 0.24)
521            } else {
522                day_spec::Color::rgb(0.97, 0.97, 0.97)
523            }
524        })
525        .corner_radius(8.0);
526    let catcher = crate::spacer()
527        .background(day_spec::Color::rgba(0.0, 0.0, 0.0, 0.0))
528        .on_tap(move || open.set(None));
529    ComposedMenuHost {
530        at,
531        catcher: day_core::AnyPiece::new(catcher),
532        panel: day_core::AnyPiece::new(panel),
533    }
534}
535
536/// One flattened item row per entry. Submenus inline as a dimmed header plus indented
537/// children, since the composed panel has no flyout (docs/menus.md).
538fn composed_menu_rows(
539    items: &[day_spec::MenuItem],
540    indent: f64,
541    next: &mut usize,
542    open: day_reactive::Signal<Option<String>>,
543    out: &mut Vec<day_core::AnyPiece>,
544) {
545    use crate::Decorate;
546    for item in items {
547        match item {
548            day_spec::MenuItem::Separator => {
549                out.push(day_core::AnyPiece::new(
550                    crate::divider().padding(day_spec::Insets::symmetric(0.0, 4.0)),
551                ));
552            }
553            day_spec::MenuItem::Submenu { label, items, .. } => {
554                out.push(day_core::AnyPiece::new(
555                    crate::label(label.clone())
556                        .padding(day_spec::Insets::symmetric(12.0 + indent, 5.0))
557                        .width(COMPOSED_MENU_W)
558                        .opacity(0.55),
559                ));
560                composed_menu_rows(items, indent + COMPOSED_SUBMENU_INDENT, next, open, out);
561            }
562            day_spec::MenuItem::Action {
563                id,
564                action,
565                label,
566                enabled,
567                checked,
568                ..
569            } => {
570                let n = *next;
571                *next += 1;
572                // A checkable item reserves the mark's column whichever way it sits, so a run of
573                // choices lines up on its titles instead of stepping in and out by a tick's width.
574                let text = match checked {
575                    Some(true) => format!("{COMPOSED_CHECK_ON}{label}"),
576                    Some(false) => format!("{COMPOSED_CHECK_OFF}{label}"),
577                    None => label.clone(),
578                };
579                // The app's own name where it gave one, so a dayscript `tap` addresses the row it
580                // means; the positional fallback keeps every other row reachable.
581                let element_id = id
582                    .clone()
583                    .unwrap_or_else(|| day_core::id!(day_menu_item, n).as_str().to_owned());
584                let base = crate::label(text)
585                    .padding(day_spec::Insets::symmetric(12.0 + indent, 5.0))
586                    .width(COMPOSED_MENU_W);
587                let row = if *enabled && *action != 0 {
588                    let action = *action;
589                    base.background(day_spec::Color::rgba(0.0, 0.0, 0.0, 0.0))
590                        .on_tap(move || {
591                            open.set(None);
592                            day_core::dispatch_menu_action(action);
593                        })
594                        .tweak(move |node| {
595                            day_core::with_tree(|tree| tree.set_id(node, element_id))
596                        })
597                } else {
598                    base.opacity(0.45).tweak(move |node| {
599                        day_core::with_tree(|tree| tree.set_id(node, element_id))
600                    })
601                };
602                out.push(day_core::AnyPiece::new(row));
603            }
604        }
605    }
606}
607
608/// Places the catcher over the full window and the panel at the summon point, pulled back
609/// inside the bounds when the summon point sits too close to an edge.
610struct MenuPlace {
611    at: day_spec::Point,
612}
613
614impl day_core::Layout for MenuPlace {
615    fn measure(
616        &self,
617        _cx: &mut dyn day_core::LayoutOps,
618        _children: &[day_core::RNode],
619        p: day_spec::Proposal,
620    ) -> day_spec::Size {
621        day_spec::Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0))
622    }
623    fn place(
624        &self,
625        cx: &mut dyn day_core::LayoutOps,
626        children: &[day_core::RNode],
627        bounds: day_spec::Rect,
628    ) {
629        if let Some(&c) = children.first() {
630            let _ = cx.measure_child(c, day_spec::Proposal::exact(bounds.size));
631            cx.place_child(c, day_spec::Rect::from_size(bounds.size));
632        }
633        if let Some(&c) = children.get(1) {
634            let s = cx.measure_child(c, day_spec::Proposal::new(Some(COMPOSED_MENU_W), None));
635            // Pull the panel back inside the window when the summon point sits near an edge,
636            // unless bounds are degenerate (a pass before the backend reported the size).
637            let (x, y) = if bounds.size.width > 1.0 && bounds.size.height > 1.0 {
638                (
639                    self.at.x.min(bounds.size.width - s.width).max(0.0),
640                    self.at.y.min(bounds.size.height - s.height).max(0.0),
641                )
642            } else {
643                (self.at.x, self.at.y)
644            };
645            cx.place_child(c, day_spec::Rect::new(x, y, s.width, s.height));
646        }
647    }
648}
649
650/// The [`MenuPlace`] wrapper piece: catcher first, panel second.
651struct ComposedMenuHost {
652    at: day_spec::Point,
653    catcher: day_core::AnyPiece,
654    panel: day_core::AnyPiece,
655}
656
657impl day_core::Piece for ComposedMenuHost {
658    fn build(self, cx: &mut day_core::BuildCx) -> day_core::RNode {
659        let n = cx.layout_only(
660            Rc::new(MenuPlace { at: self.at }),
661            day_core::Flex {
662                grow_w: true,
663                grow_h: true,
664                ..Default::default()
665            },
666            day_core::Boundary::No,
667        );
668        cx.under(n, |cx| {
669            let _ = self.catcher.build(cx);
670            let _ = self.panel.build(cx);
671        });
672        n
673    }
674}
675
676#[cfg(feature = "conformance")]
677pub(crate) mod conformance {
678    use day_core::conformance::{Case, Drive};
679    use day_reactive::Signal;
680
681    use crate::*;
682
683    /// Choosing a context-menu item runs that item's action, and only that one.
684    #[day_macros::test(day_core)]
685    fn context_menu_runs_action() -> Case {
686        Case::new()
687            .proves_modifier("context_menu")
688            .proves_duty("set_context_menu")
689            .page(|| {
690                let last = Signal::new(String::from("none"));
691                column((
692                    label(move || format!("ran {}", last.get())).id(day_core::id!(ran)),
693                    label("Target")
694                        .padding(8.0)
695                        .context_menu(vec![
696                            menu_item("Copy it").action(move || last.set("copy".into())),
697                            menu_item("Paste it").action(move || last.set("paste".into())),
698                        ])
699                        .id(day_core::id!(target)),
700                ))
701            })
702            .drive(|d: Drive| async move {
703                d.context_menu("target", "Paste it").await?;
704                d.assert_text("ran", "ran paste").await?;
705                d.context_menu("target", "Copy it").await?;
706                d.assert_text("ran", "ran copy").await
707            })
708    }
709
710    /// A menu built on summon reflects the state at that moment.
711    #[day_macros::test(day_core)]
712    fn context_menu_fn_builds_on_summon() -> Case {
713        Case::new()
714            .proves_modifier("context_menu")
715            .proves_duty("set_context_menu_fn")
716            .page(|| {
717                let count = Signal::new(0i64);
718                let chose = Signal::new(0i64);
719                column((
720                    label(move || format!("chose {}", chose.get())).id(day_core::id!(chose)),
721                    button("Add")
722                        .action(move || count.update(|n| *n += 1))
723                        .id(day_core::id!(add)),
724                    label("Target")
725                        .padding(8.0)
726                        .context_menu(move || {
727                            let n = count.get_untracked();
728                            vec![menu_item(format!("Take {n}")).action(move || chose.set(n))]
729                        })
730                        .id(day_core::id!(target)),
731                ))
732            })
733            .drive(|d: Drive| async move {
734                d.tap("add").await?;
735                d.tap("add").await?;
736                d.context_menu("target", "Take 2").await?;
737                d.assert_text("chose", "chose 2").await
738            })
739    }
740}
741
742#[cfg(test)]
743mod tests {
744    use super::*;
745
746    /// The role items every Edit menu carries take the standard accelerators when the app
747    /// sets none, which is what gives GTK/Qt/web the shortcuts AppKit's native items always had.
748    #[test]
749    fn role_items_take_standard_shortcuts() {
750        use day_spec::{MenuItem, MenuRole};
751        let lowered = lower_menu(vec![
752            menu_role(MenuRole::Undo),
753            menu_role(MenuRole::Redo),
754            menu_role(MenuRole::Cut),
755            menu_role(MenuRole::Copy),
756            menu_role(MenuRole::Paste),
757            menu_role(MenuRole::SelectAll),
758        ]);
759        let expect = [
760            ("z", false),
761            ("z", true),
762            ("x", false),
763            ("c", false),
764            ("v", false),
765            ("a", false),
766        ];
767        for (item, (key, shift)) in lowered.iter().zip(expect) {
768            let MenuItem::Action {
769                shortcut, action, ..
770            } = item
771            else {
772                panic!("role item lowered to a non-action");
773            };
774            let sc = shortcut.as_ref().expect("role item has a default shortcut");
775            assert_eq!(sc.key, key);
776            assert!(sc.primary);
777            assert_eq!(sc.shift, shift);
778            assert_ne!(*action, 0, "role item carries its standing dispatcher");
779        }
780    }
781}