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::{Cell, RefCell};
9use std::rc::Rc;
10
11use day_reactive::Scope;
12
13use day_core::Piece;
14
15use crate::{Decorated, IntoReactive, IntoText, Reactive, TextSource};
16
17// ---------------------------------------------------------------------------
18// Menus: the app-side builder over day_spec's toolkit-neutral MenuItem model. Lowering registers
19// each item's action closure with day-core (which dispatches `Event::MenuAction`) and assigns its
20// id.
21// ---------------------------------------------------------------------------
22
23/// A menu entry under construction. Build a command with [`menu_item`], a nested submenu with
24/// [`sub_menu`], a standard system command with [`menu_role`], and a divider with [`menu_separator`].
25/// Attach to a Piece via [`Decorate::context_menu`](crate::decorators::Decorate::context_menu) or install app-wide via [`app_menu`].
26#[derive(Clone)]
27#[must_use]
28pub struct MenuEntry {
29    id: Option<String>,
30    /// The title, live: resolved (tracked) when the menu is lowered, so a localized title
31    /// follows a language switch and a title built from a signal follows the signal.
32    label: TextSource,
33    shortcut: Option<day_spec::Shortcut>,
34    enabled: Reactive<bool>,
35    role: Option<day_spec::MenuRole>,
36    icon: Option<day_spec::Icon>,
37    checked: Option<Reactive<bool>>,
38    action: Option<Rc<dyn Fn()>>,
39    children: Option<Vec<MenuEntry>>,
40    separator: bool,
41    bar_role: Option<day_spec::MenuBarRole>,
42}
43
44impl MenuEntry {
45    fn command(label: TextSource) -> MenuEntry {
46        MenuEntry {
47            id: None,
48            label,
49            shortcut: None,
50            enabled: Reactive::Const(true),
51            role: None,
52            icon: None,
53            bar_role: None,
54            checked: None,
55            action: None,
56            children: None,
57            separator: false,
58        }
59    }
60
61    /// A standard [`Symbol`](day_spec::Symbol) beside the item's title, drawn with the
62    /// platform's glyph, the same vocabulary toolbars take. Menus carry icons on macOS,
63    /// Windows, GNOME, KDE and Android; a backend whose menus are text-only ignores it, so an
64    /// icon is always an addition to a menu that already reads correctly without one.
65    pub fn icon(mut self, s: day_spec::Symbol) -> MenuEntry {
66        self.icon = Some(day_spec::Icon::Symbol(s));
67        self
68    }
69
70    /// A bundled image from `resource/images`, for an item the standard set has no glyph for:
71    /// an app's own vocabulary (a shape, a brand). Same rule as [`MenuEntry::icon`].
72    pub fn image(mut self, name: impl Into<String>) -> MenuEntry {
73        self.icon = Some(day_spec::Icon::Image(name.into()));
74        self
75    }
76    /// Run `f` when the item is chosen.
77    pub fn action(mut self, f: impl Fn() + 'static) -> MenuEntry {
78        self.action = Some(Rc::new(f));
79        self
80    }
81    /// Full shortcut spec, e.g. `Shortcut::primary("s").shift()`.
82    pub fn shortcut(mut self, s: day_spec::Shortcut) -> MenuEntry {
83        self.shortcut = Some(s);
84        self
85    }
86    /// Convenience: the platform's primary modifier (⌘ / Ctrl) + `key`. This sets the item's
87    /// shortcut; to name the item, use [`MenuEntry::id`].
88    pub fn key(mut self, key: impl Into<String>) -> MenuEntry {
89        self.shortcut = Some(day_spec::Shortcut::primary(key));
90        self
91    }
92
93    /// Name this item, so something outside the menu can address it: a dayscript
94    /// `menu: { id: "view-both" }` step, or a `tap` on the composed menu's row where the platform
95    /// has no native menus.
96    ///
97    /// A label cannot do that job. It is localized, so it changes with the run's language, and an
98    /// item that shows its own state changes it whenever the state moves, which is exactly the
99    /// case [`MenuEntry::checked`] creates. Give an id to any item a script drives.
100    #[expect(
101        clippy::needless_pass_by_value,
102        reason = "public builder signature; `id!` yields the id by value"
103    )]
104    pub fn id(mut self, id: day_core::ElementId) -> MenuEntry {
105        self.id = Some(id.as_str().to_owned());
106        self
107    }
108
109    /// Draw this item with the platform's check mark, on or off, for a setting the menu toggles
110    /// or one of several mutually exclusive choices. An item that never calls this is a plain
111    /// command and reserves no room for a mark.
112    ///
113    /// Choosing the item still runs its [`action`](MenuEntry::action); no backend flips the mark
114    /// by itself. The app owns the state: pass the signal (or a closure reading it) and the mark
115    /// follows the state, the menu re-lowering when it changes.
116    ///
117    /// ```ignore
118    /// menu_item(tr("view_grid")).id(day_core::id!(view_grid)).checked(grid).action(move || grid.set(!grid.get()))
119    /// ```
120    pub fn checked<M>(mut self, on: impl IntoReactive<bool, M>) -> MenuEntry {
121        self.checked = Some(on.into_reactive());
122        self
123    }
124    /// Whether the item can be chosen (default `true`): a constant, a `Signal<bool>`, or a
125    /// closure, re-read whenever the menu is lowered.
126    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> MenuEntry {
127        self.enabled = on.into_reactive();
128        self
129    }
130    /// Tag a custom command with a standard [`day_spec::MenuRole`] (usually you use [`menu_role`]).
131    pub fn role(mut self, role: day_spec::MenuRole) -> MenuEntry {
132        self.role = Some(role);
133        self
134    }
135}
136
137/// A clickable command: `menu_item(res::str::save()).key("s").action(|| …)`. The title takes
138/// the same sources as a label (a literal, a localized text, a signal, a closure) and stays
139/// live.
140pub fn menu_item<M>(label: impl IntoText<M>) -> MenuEntry {
141    MenuEntry::command(label.into_text())
142}
143
144/// A nested submenu: `sub_menu(res::str::menu_file(), vec![menu_item(…), …])`.
145pub fn sub_menu<M>(label: impl IntoText<M>, items: Vec<MenuEntry>) -> MenuEntry {
146    MenuEntry {
147        children: Some(items),
148        ..MenuEntry::command(label.into_text())
149    }
150}
151
152/// Claim one of the platform's standard menu-bar slots for this submenu: the backend places it
153/// where that menu belongs and does not add its stock version. Without a role, a submenu is
154/// an app menu and sits between the standard ones.
155///
156/// ```ignore
157/// sub_menu(res::str::menu_file(), menu_items).bar_role(MenuBarRole::File)
158/// ```
159impl MenuEntry {
160    pub fn bar_role(mut self, role: day_spec::MenuBarRole) -> MenuEntry {
161        self.bar_role = Some(role);
162        self
163    }
164}
165
166/// A visual divider between items.
167pub fn menu_separator() -> MenuEntry {
168    MenuEntry {
169        separator: true,
170        ..MenuEntry::command(TextSource::Static(String::new()))
171    }
172}
173
174/// A standard/system command (`MenuRole::Copy`, `MenuRole::Quit`, …) rendered with the platform's
175/// native item (correct label, default shortcut, focus-targeting, and automatic enable/disable),
176/// so default menu items (Edit ▸ Cut/Copy/Paste, the app's Quit/About) work without
177/// re-implementation.
178pub fn menu_role(role: day_spec::MenuRole) -> MenuEntry {
179    MenuEntry {
180        role: Some(role),
181        ..MenuEntry::command(TextSource::Static(String::new()))
182    }
183}
184
185/// The core-catalog key for a standard menu command's label (docs/menus.md, docs/localization.md).
186fn role_catalog_key(role: day_spec::MenuRole) -> &'static str {
187    use day_spec::MenuRole as R;
188    match role {
189        R::Cut => "day_cut",
190        R::Copy => "day_copy",
191        R::Paste => "day_paste",
192        R::SelectAll => "day_select_all",
193        R::Undo => "day_undo",
194        R::Redo => "day_redo",
195        R::Delete => "day_delete",
196        R::About => "day_about",
197        R::Quit => "day_quit",
198        R::Preferences => "day_preferences",
199        R::Minimize => "day_minimize",
200        R::CloseWindow => "day_close",
201        R::Fullscreen => "day_fullscreen",
202        R::NewWindow => "day_new_window",
203        R::CheckForUpdates => "day_check_for_updates",
204    }
205}
206
207/// Lower app-side entries to the spec model, registering action closures with day-core. A standard
208/// `role` item with no explicit label gets its label from the localized core catalog here, so the
209/// backends receive a ready, locale-correct label instead of each hardcoding English (day-localization).
210///
211/// This variant registers process-lived closures, correct for the app menu and toolbars, whose
212/// ids day-core manages by shape-rebinding, toolbar slots and explicit sweeps. Menus owned by a piece build
213/// (a `.context_menu`, a nav row's menu) go through [`lower_menu_scoped`] instead, so their
214/// closures are reclaimed when the registering scope is disposed rather than leaking per remount.
215pub(crate) fn lower_menu(entries: Vec<MenuEntry>) -> Vec<day_spec::MenuItem> {
216    lower_menu_with(entries, &day_core::register_menu_action)
217}
218
219/// [`lower_menu`] with scope-tied action registration (see there for when to use which).
220pub(crate) fn lower_menu_scoped(entries: Vec<MenuEntry>) -> Vec<day_spec::MenuItem> {
221    lower_menu_with(entries, &day_core::register_scoped_menu_action)
222}
223
224fn lower_menu_with(
225    entries: Vec<MenuEntry>,
226    register: &dyn Fn(Rc<dyn Fn()>) -> u64,
227) -> Vec<day_spec::MenuItem> {
228    entries
229        .into_iter()
230        .map(|e| {
231            if e.separator {
232                day_spec::MenuItem::Separator
233            } else if let Some(children) = e.children {
234                day_spec::MenuItem::Submenu {
235                    label: e.label.resolve(),
236                    items: lower_menu_with(children, register),
237                    role: e.bar_role,
238                }
239            } else {
240                let mut action = e.action.map_or(0, register);
241                // Tracked reads: a menu lowered inside `app_menu`'s effect re-lowers when
242                // a title, availability or check state changes.
243                let mut enabled = e.enabled.get();
244                let mut shortcut = e.shortcut;
245                // Window roles have no native selector on any platform: an action-less item
246                // lowers to the registered day dispatcher (docs/windows.md): live when the
247                // app registered a builder/preferences piece, disabled otherwise.
248                if action == 0 {
249                    match e.role {
250                        Some(day_spec::MenuRole::NewWindow) => {
251                            action = day_core::windows::new_window_action_id();
252                            enabled = enabled && action != 0;
253                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("n")));
254                        }
255                        // The undo pair and the clipboard trio lower to standing dispatchers
256                        // too, for toolkits whose role items come back as plain menu actions
257                        // (Android's app-bar menu, the iOS menu, web context menus). Toolkits
258                        // with a native responder route ignore the action and keep their selector
259                        // (see each backend's menu build). Each also takes the platform-neutral
260                        // standard shortcut (primary+Z/X/C/V/A, shift for redo) unless the app
261                        // set its own. AppKit's native items already carry these, so this is
262                        // what gives GTK/Qt/web the same accelerators.
263                        Some(day_spec::MenuRole::Undo) => {
264                            action = day_core::undo_action_id(false);
265                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("z")));
266                        }
267                        Some(day_spec::MenuRole::Redo) => {
268                            action = day_core::undo_action_id(true);
269                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("z").shift()));
270                        }
271                        Some(day_spec::MenuRole::Cut) => {
272                            action = day_core::edit_action_id(day_spec::EditOp::Cut);
273                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("x")));
274                        }
275                        Some(day_spec::MenuRole::Copy) => {
276                            action = day_core::edit_action_id(day_spec::EditOp::Copy);
277                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("c")));
278                        }
279                        Some(day_spec::MenuRole::Paste) => {
280                            action = day_core::edit_action_id(day_spec::EditOp::Paste);
281                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("v")));
282                        }
283                        Some(day_spec::MenuRole::SelectAll) => {
284                            action = day_core::edit_action_id(day_spec::EditOp::SelectAll);
285                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("a")));
286                        }
287                        Some(day_spec::MenuRole::Preferences) => {
288                            action = day_core::windows::preferences_action_id();
289                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary(",")));
290                        }
291                        // About keeps the toolkit's stock panel (action 0) until an app
292                        // registers its own (docs/settings.md); the updater command has no
293                        // native fallback and lowers disabled when nothing registered.
294                        Some(day_spec::MenuRole::About) => {
295                            action = day_core::windows::about_action_id();
296                        }
297                        Some(day_spec::MenuRole::CheckForUpdates) => {
298                            action = day_core::windows::check_for_updates_action_id();
299                            enabled = enabled && action != 0;
300                        }
301                        _ => {}
302                    }
303                }
304                let label = e.label.resolve();
305                let label = match (label.is_empty(), e.role) {
306                    (true, Some(role)) => day_localization::t(role_catalog_key(role)),
307                    _ => label,
308                };
309                day_spec::MenuItem::Action {
310                    id: e.id,
311                    action,
312                    label,
313                    shortcut,
314                    enabled,
315                    checked: e.checked.as_ref().map(Reactive::get),
316                    role: e.role,
317                    icon: e.icon,
318                }
319            }
320        })
321        .collect()
322}
323
324/// Where a menu's entries come from: a fixed list, or a closure that derives the list and
325/// re-runs whenever its reactive reads change. What [`app_menu`], [`dock_menu`] and
326/// [`StatusItem::menu`](crate::StatusItem::menu) accept, through [`MenuContent`].
327#[derive(Clone)]
328pub enum MenuSource {
329    Fixed(Vec<MenuEntry>),
330    Derived(Rc<dyn Fn() -> Vec<MenuEntry>>),
331}
332
333impl MenuSource {
334    /// The entries right now: a tracked read for a derived source.
335    pub(crate) fn entries(&self) -> Vec<MenuEntry> {
336        match self {
337            MenuSource::Fixed(v) => v.clone(),
338            MenuSource::Derived(f) => f(),
339        }
340    }
341}
342
343/// Anything an app menu takes: a `Vec` or array of entries, or a closure that derives the
344/// entries and re-runs whenever its reactive reads change. The marker parameter is the same
345/// E0119 dodge as [`ToolbarContent`](crate::ToolbarContent).
346pub trait MenuContent<M> {
347    fn into_source(self) -> MenuSource;
348}
349
350impl MenuContent<crate::ManyMark> for Vec<MenuEntry> {
351    fn into_source(self) -> MenuSource {
352        MenuSource::Fixed(self)
353    }
354}
355
356impl<const N: usize> MenuContent<crate::ManyMark> for [MenuEntry; N] {
357    fn into_source(self) -> MenuSource {
358        MenuSource::Fixed(Vec::from(self))
359    }
360}
361
362impl<C, F> MenuContent<crate::DerivedMark> for F
363where
364    C: IntoIterator<Item = MenuEntry>,
365    F: Fn() -> C + 'static,
366{
367    fn into_source(self) -> MenuSource {
368        MenuSource::Derived(Rc::new(move || self().into_iter().collect()))
369    }
370}
371
372day_reactive::tls_slots! { menus;
373    /// The scope owning the current app-menu and dock-menu installs, so a second call replaces
374    /// the first (and reclaims its bindings) instead of leaving two installers racing.
375    static APP_MENU_SCOPE: Cell<Option<Scope>> = const { Cell::new(None) };
376    static DOCK_MENU_SCOPE: Cell<Option<Scope>> = const { Cell::new(None) };
377}
378
379/// Install `source` through `install`, in a root-owned scope that replaces the previous one.
380fn install_menu(
381    slot: &Cell<Option<Scope>>,
382    source: MenuSource,
383    install: fn(Vec<day_spec::MenuItem>),
384) {
385    if let Some(old) = slot.take() {
386        old.dispose();
387    }
388    let scope = Scope::root().enter(Scope::child);
389    scope.enter(|| {
390        day_reactive::bind(
391            move || {
392                // Track the locale even when the entries carry no localized reads, so
393                // role-label fallbacks still refresh; every entry's title, availability and
394                // check state is a tracked read of its own inside `lower_menu`.
395                let _ = day_localization::locale().get();
396                lower_menu(source.entries())
397            },
398            move |items: &Vec<day_spec::MenuItem>| install(items.clone()),
399        );
400    });
401    slot.set(Some(scope));
402}
403
404/// Install the application menu: the native menu bar on desktop, the app-bar overflow on Android,
405/// the `UIMenuBuilder` main menu on iPadOS/Catalyst. Top-level entries are usually `sub_menu(…)`s
406/// (the menu-bar menus). Takes a list of entries or a closure that derives them.
407///
408/// The menu is live (docs/menus.md): every title, `enabled` and `checked` is re-read, and the
409/// menu re-lowered and reinstalled, whenever one of them changes, so `menu_role` labels,
410/// `res::str` titles and `day::tr` all follow a runtime language switch, and a derived closure
411/// re-runs on whatever signals it reads. Calling it again replaces the previous install and
412/// reclaims its action closures. Install once, at startup.
413///
414/// ```ignore
415/// app_menu([
416///     sub_menu(res::str::menu_file(), vec![menu_item(res::str::new_item()).key("n").action(add)]),
417///     sub_menu(res::str::menu_view(), vec![menu_item(res::str::grid()).checked(grid).action(flip)]),
418/// ]);
419/// ```
420pub fn app_menu<M>(menus: impl MenuContent<M>) {
421    APP_MENU_SCOPE.with(|slot| install_menu(slot, menus.into_source(), day_core::set_app_menu));
422}
423
424/// Install the app's Dock menu (docs/menus.md "Dock menu"): the entries macOS lists when the
425/// user right-clicks the app's Dock icon, above the app's `[[shortcuts]]` and the system's own
426/// Show / Hide / Quit items. Probe `Cap::DockMenu`; elsewhere the call does nothing. Live, like
427/// [`app_menu`]: `Resume <last document>`, a checked "Do Not Disturb", the locale. Install
428/// once, at startup.
429///
430/// The menu works while the app runs, so its actions are ordinary closures, unlike shortcuts,
431/// which are routes because they also launch the app.
432pub fn dock_menu<M>(entries: impl MenuContent<M>) {
433    DOCK_MENU_SCOPE.with(|slot| install_menu(slot, entries.into_source(), day_core::set_dock_menu));
434}
435
436// ---------------------------------------------------------------------------
437// Menu buttons (docs/menus.md "Menu buttons"): a native button whose primary press opens a menu.
438// ---------------------------------------------------------------------------
439
440/// A button that opens a menu when pressed: the ⋯ More button beside a browser's address bar, an
441/// Add ▾ button, a page-actions button in a toolbar row the app draws itself. Build one with
442/// [`menu_button`].
443///
444/// It is the platform's own pull-down: an `NSButton` that pops its `NSMenu` under itself, a
445/// `UIButton` whose menu is its primary action, a `GtkMenuButton`-style popover, a `QPushButton`
446/// with a `QMenu`, a Material button with a `PopupMenu`, a WinUI `Button` with a `MenuFlyout`,
447/// and the web toolbar's pull-down popover. The entries are the same [`MenuEntry`] values a
448/// context menu takes, so checked, disabled and destructive-looking items, separators and
449/// submenus behave as they do there.
450///
451/// The button carries the piece's [`.id`](crate::Decorate::id); each item keeps its own
452/// [`MenuEntry::id`]. A dayscript `context_menu: { id: <button>, item_id: <item> }` step chooses
453/// an item, as a press and a choice would.
454#[must_use]
455pub struct MenuButton {
456    button: crate::Button,
457    entries: MenuSource,
458    enabled: Reactive<bool>,
459}
460
461/// A button that opens `entries` as a menu when pressed (docs/menus.md "Menu buttons").
462///
463/// `entries` is a `Vec` or array of [`MenuEntry`] values, or a closure that builds them. Either
464/// way the menu is built when it opens, so every title, [`checked`](MenuEntry::checked) and
465/// [`enabled`](MenuEntry::enabled) state is the current one; the closure form also lets the
466/// list itself depend on what is true at that moment.
467///
468/// ```ignore
469/// menu_button(res::str::more(), move || {
470///     vec![
471///         menu_item(res::str::reader_view())
472///             .id(id!(reader))
473///             .checked(reader)
474///             .action(move || reader.set(!reader.get())),
475///         menu_separator(),
476///         menu_item(res::str::share()).id(id!(share)).enabled(move || page.get().is_some()).action(share),
477///     ]
478/// })
479/// .icon(Symbol::More)
480/// .icon_only()
481/// .plain()
482/// .id(id!(more))
483/// ```
484pub fn menu_button<M, E>(label: impl IntoText<M>, entries: impl MenuContent<E>) -> MenuButton {
485    MenuButton {
486        button: crate::button(label),
487        entries: entries.into_source(),
488        enabled: Reactive::Const(true),
489    }
490}
491
492#[day_macros::builder(MenuButtonBuilder)]
493impl MenuButton {
494    /// Show a platform symbol beside (or, with [`icon_only`](MenuButton::icon_only), instead of)
495    /// the label, as [`Button::icon`](crate::Button::icon) does.
496    pub fn icon<M>(mut self, symbol: impl IntoReactive<day_spec::Symbol, M>) -> Self {
497        self.button = self.button.icon(symbol);
498        self
499    }
500
501    /// Show a bundled image or vector alongside the label, as
502    /// [`Button::image`](crate::Button::image) does.
503    pub fn image(mut self, name: impl Into<day_spec::ImageName>) -> Self {
504        self.button = self.button.image(name);
505        self
506    }
507
508    /// Hide the visible label when an icon is available. The label stays the accessible name
509    /// and, on desktop and web, the tooltip.
510    pub fn icon_only(mut self) -> Self {
511        self.button = self.button.icon_only();
512        self
513    }
514
515    /// A borderless button, for a toolbar row or a list accessory ([`Button::plain`](crate::Button::plain)).
516    pub fn plain(mut self) -> Self {
517        self.button = self.button.plain();
518        self
519    }
520
521    /// A contained button where the stock look is borderless ([`Button::bordered`](crate::Button::bordered)).
522    pub fn bordered(mut self) -> Self {
523        self.button = self.button.bordered();
524        self
525    }
526
527    /// No wider than its label ([`Button::compact`](crate::Button::compact)).
528    pub fn compact(mut self) -> Self {
529        self.button = self.button.compact();
530        self
531    }
532
533    /// The platform's accent-filled button ([`Button::prominent`](crate::Button::prominent)).
534    pub fn prominent(mut self) -> Self {
535        self.button = self.button.prominent();
536        self
537    }
538
539    /// Whether the button can open its menu (default `true`): a constant, a signal or a closure.
540    /// A disabled menu button is drawn disabled by the native control and opens nothing, a
541    /// dayscript `context_menu` step included.
542    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Self {
543        let on = on.into_reactive();
544        self.button = match on.clone() {
545            Reactive::Const(v) => self.button.enabled(v),
546            Reactive::Dyn(f) => self.button.enabled(move || f()),
547        };
548        self.enabled = on;
549        self
550    }
551}
552
553impl Piece for MenuButton {
554    fn build(self, cx: &mut day_core::BuildCx) -> day_core::RNode {
555        // The same wrapper a `.context_menu` builds: the button fills it, and the composed
556        // presenter's lazy mount sits beside it for a toolkit that reports the press instead of
557        // showing a native menu (ArkUI).
558        let w = cx.layout_only(
559            Rc::new(crate::decorators::OverlayHost),
560            day_core::Flex::default(),
561            day_core::Boundary::No,
562        );
563        let mut n = w;
564        let MenuButton {
565            button,
566            entries,
567            enabled,
568        } = self;
569        cx.under(w, |cx| {
570            n = button.build(cx);
571            let provider = menu_button_provider(entries, enabled);
572            day_core::with_tree(|t| t.set_button_menu(n, provider.clone()));
573            mount_composed_menu(cx, n, provider);
574        });
575        day_core::with_tree(|t| t.forward_whole_row(w, n));
576        // Identity modifiers and the dayscript step name the button, not the wrapper.
577        n
578    }
579}
580
581/// The provider a menu button hands the toolkit: lowers the entries when the menu opens, each
582/// time into a fresh scope that the next open (or the button's teardown) disposes, the rule
583/// `.context_menu(|| …)` follows, so an often-opened menu never accumulates registrations.
584fn menu_button_provider(entries: MenuSource, enabled: Reactive<bool>) -> day_spec::ContextMenuFn {
585    let last: Rc<RefCell<Option<Scope>>> = Rc::default();
586    {
587        let last = last.clone();
588        Scope::current().on_cleanup(move || {
589            if let Some(s) = last.borrow_mut().take() {
590                s.dispose();
591            }
592        });
593    }
594    Rc::new(move |_at| {
595        if !enabled.get_untracked() {
596            return Vec::new();
597        }
598        if let Some(s) = last.borrow_mut().take() {
599            s.dispose();
600        }
601        let scope = Scope::child();
602        let entries = &entries;
603        let items = scope.enter(|| lower_menu_scoped(entries.entries()));
604        *last.borrow_mut() = Some(scope);
605        items
606    })
607}
608
609// ---------------------------------------------------------------------------
610// The composed context menu (docs/menus.md "Dynamic context menus"): presentation for a
611// toolkit that REPORTS the summon (`Event::ContextMenu`) instead of showing a native menu
612// of its own (web-dom). Works on the LOWERED model, so role resolution, localization, and
613// per-summon action scoping are exactly what a native backend would have received.
614// ---------------------------------------------------------------------------
615
616/// The composed menu's stand-in for a native check mark, and the blank that holds its column.
617const COMPOSED_CHECK_ON: &str = "\u{2713}\u{2002}";
618const COMPOSED_CHECK_OFF: &str = "\u{2002}\u{2002}";
619/// Panel width of the composed menu, and the extra indent inlined submenu items take.
620const COMPOSED_MENU_W: f64 = 220.0;
621const COMPOSED_SUBMENU_INDENT: f64 = 12.0;
622
623/// Mount the composed presentation beside a `.context_menu` node: an
624/// `Event::ContextMenu` handler plus a lazily-armed, unrouted [`crate::cover`] that shows the
625/// provider's items at the summon point. Nothing builds until the first summon arrives, so
626/// backends that serve the menu natively (and therefore never emit the event) never pay.
627pub(crate) fn mount_composed_menu(
628    cx: &mut day_core::BuildCx,
629    node: day_core::RNode,
630    provider: day_spec::ContextMenuFn,
631) {
632    use day_reactive::Signal;
633    use std::cell::RefCell;
634
635    struct Pending {
636        items: Vec<day_spec::MenuItem>,
637        at: day_spec::Point,
638    }
639    let armed = Signal::new(false);
640    let open: Signal<Option<String>> = Signal::new(None);
641    let pending: Rc<RefCell<Pending>> = Rc::new(RefCell::new(Pending {
642        items: Vec::new(),
643        at: day_spec::Point::ZERO,
644    }));
645
646    {
647        let pending = pending.clone();
648        cx.on(node, move |ev| {
649            if let day_spec::Event::ContextMenu { local, window } = ev {
650                let items = provider(*local);
651                if items.is_empty() {
652                    return;
653                }
654                *pending.borrow_mut() = Pending { items, at: *window };
655                armed.set(true);
656                open.set(Some("menu".into()));
657            }
658        });
659    }
660
661    let host = crate::when(
662        move || armed.get(),
663        move || {
664            let pending = pending.clone();
665            crate::cover(open, move |_: &String| {
666                let (items, at) = {
667                    let p = pending.borrow();
668                    (p.items.clone(), p.at)
669                };
670                composed_menu_host(&items, at, open)
671            })
672            .unrouted()
673            .background(|_| day_spec::Color::rgba(0.0, 0.0, 0.0, 0.0))
674        },
675    );
676    let _ = day_core::Piece::build(host, cx);
677}
678
679/// The presented surface: a fullscreen dismiss catcher plus the item panel, placed at the
680/// summon point (clamped into the window by [`MenuPlace`]).
681fn composed_menu_host(
682    items: &[day_spec::MenuItem],
683    at: day_spec::Point,
684    open: day_reactive::Signal<Option<String>>,
685) -> impl day_core::Piece + use<> {
686    use crate::Decorate;
687
688    let mut rows: Vec<day_core::AnyPiece> = Vec::new();
689    let mut next = 0usize;
690    composed_menu_rows(items, 0.0, &mut next, open, &mut rows);
691
692    let panel = crate::column(rows)
693        .padding(day_spec::Insets::symmetric(0.0, 5.0))
694        .background(|| {
695            if day_core::dark_mode() {
696                day_spec::Color::rgb(0.22, 0.22, 0.24)
697            } else {
698                day_spec::Color::rgb(0.97, 0.97, 0.97)
699            }
700        })
701        .corner_radius(8.0);
702    let catcher = crate::spacer()
703        .background(day_spec::Color::rgba(0.0, 0.0, 0.0, 0.0))
704        .on_tap(move || open.set(None));
705    ComposedMenuHost {
706        at,
707        catcher: day_core::AnyPiece::new(catcher),
708        panel: day_core::AnyPiece::new(panel),
709    }
710}
711
712/// One flattened item row per entry. Submenus inline as a dimmed header plus indented
713/// children, since the composed panel has no flyout (docs/menus.md).
714fn composed_menu_rows(
715    items: &[day_spec::MenuItem],
716    indent: f64,
717    next: &mut usize,
718    open: day_reactive::Signal<Option<String>>,
719    out: &mut Vec<day_core::AnyPiece>,
720) {
721    use crate::Decorate;
722    for item in items {
723        match item {
724            day_spec::MenuItem::Separator => {
725                out.push(day_core::AnyPiece::new(
726                    crate::divider().padding(day_spec::Insets::symmetric(0.0, 4.0)),
727                ));
728            }
729            day_spec::MenuItem::Submenu { label, items, .. } => {
730                out.push(day_core::AnyPiece::new(
731                    crate::label(label.clone())
732                        .padding(day_spec::Insets::symmetric(12.0 + indent, 5.0))
733                        .width(COMPOSED_MENU_W)
734                        .opacity(0.55),
735                ));
736                composed_menu_rows(items, indent + COMPOSED_SUBMENU_INDENT, next, open, out);
737            }
738            day_spec::MenuItem::Action {
739                id,
740                action,
741                label,
742                enabled,
743                checked,
744                ..
745            } => {
746                let n = *next;
747                *next += 1;
748                // A checkable item reserves the mark's column whichever way it sits, so a run of
749                // choices lines up on its titles instead of stepping in and out by a tick's width.
750                let text = match checked {
751                    Some(true) => format!("{COMPOSED_CHECK_ON}{label}"),
752                    Some(false) => format!("{COMPOSED_CHECK_OFF}{label}"),
753                    None => label.clone(),
754                };
755                // The app's own name where it gave one, so a dayscript `tap` addresses the row it
756                // means; the positional fallback keeps every other row reachable.
757                let element_id = id
758                    .clone()
759                    .unwrap_or_else(|| day_core::id!(day_menu_item, n).as_str().to_owned());
760                let base = crate::label(text)
761                    .padding(day_spec::Insets::symmetric(12.0 + indent, 5.0))
762                    .width(COMPOSED_MENU_W);
763                let row = if *enabled && *action != 0 {
764                    let action = *action;
765                    base.background(day_spec::Color::rgba(0.0, 0.0, 0.0, 0.0))
766                        .on_tap(move || {
767                            open.set(None);
768                            day_core::dispatch_menu_action(action);
769                        })
770                        .tweak(move |node| {
771                            day_core::with_tree(|tree| tree.set_id(node, element_id));
772                        })
773                } else {
774                    base.opacity(0.45).tweak(move |node| {
775                        day_core::with_tree(|tree| tree.set_id(node, element_id));
776                    })
777                };
778                out.push(day_core::AnyPiece::new(row));
779            }
780        }
781    }
782}
783
784/// Places the catcher over the full window and the panel at the summon point, pulled back
785/// inside the bounds when the summon point sits too close to an edge.
786struct MenuPlace {
787    at: day_spec::Point,
788}
789
790impl day_core::Layout for MenuPlace {
791    fn measure(
792        &self,
793        _cx: &mut dyn day_core::LayoutOps,
794        _children: &[day_core::RNode],
795        p: day_spec::Proposal,
796    ) -> day_spec::Size {
797        day_spec::Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0))
798    }
799    fn place(
800        &self,
801        cx: &mut dyn day_core::LayoutOps,
802        children: &[day_core::RNode],
803        bounds: day_spec::Rect,
804    ) {
805        if let Some(&c) = children.first() {
806            let _ = cx.measure_child(c, day_spec::Proposal::exact(bounds.size));
807            cx.place_child(c, day_spec::Rect::from_size(bounds.size));
808        }
809        if let Some(&c) = children.get(1) {
810            let s = cx.measure_child(c, day_spec::Proposal::new(Some(COMPOSED_MENU_W), None));
811            // Pull the panel back inside the window when the summon point sits near an edge,
812            // unless bounds are degenerate (a pass before the backend reported the size).
813            let (x, y) = if bounds.size.width > 1.0 && bounds.size.height > 1.0 {
814                (
815                    self.at.x.min(bounds.size.width - s.width).max(0.0),
816                    self.at.y.min(bounds.size.height - s.height).max(0.0),
817                )
818            } else {
819                (self.at.x, self.at.y)
820            };
821            cx.place_child(c, day_spec::Rect::new(x, y, s.width, s.height));
822        }
823    }
824}
825
826/// The [`MenuPlace`] wrapper piece: catcher first, panel second.
827struct ComposedMenuHost {
828    at: day_spec::Point,
829    catcher: day_core::AnyPiece,
830    panel: day_core::AnyPiece,
831}
832
833impl day_core::Piece for ComposedMenuHost {
834    fn build(self, cx: &mut day_core::BuildCx) -> day_core::RNode {
835        let n = cx.layout_only(
836            Rc::new(MenuPlace { at: self.at }),
837            day_core::Flex {
838                grow_w: true,
839                grow_h: true,
840                ..Default::default()
841            },
842            day_core::Boundary::No,
843        );
844        cx.under(n, |cx| {
845            let _ = self.catcher.build(cx);
846            let _ = self.panel.build(cx);
847        });
848        n
849    }
850}
851
852#[cfg(feature = "conformance")]
853pub(crate) mod conformance {
854    use day_core::conformance::{Case, Drive};
855    use day_reactive::Signal;
856
857    use crate::*;
858
859    /// Choosing a context-menu item runs that item's action, and only that one.
860    #[day_macros::test(day_core)]
861    fn context_menu_runs_action() -> Case {
862        Case::new()
863            .proves_modifier("context_menu")
864            .proves_duty("set_context_menu")
865            .page(|| {
866                let last = Signal::new(String::from("none"));
867                column((
868                    label(move || format!("ran {}", last.get())).id(day_core::id!(ran)),
869                    label("Target")
870                        .padding(8.0)
871                        .context_menu(vec![
872                            menu_item("Copy it").action(move || last.set("copy".into())),
873                            menu_item("Paste it").action(move || last.set("paste".into())),
874                        ])
875                        .id(day_core::id!(target)),
876                ))
877            })
878            .drive(|d: Drive| async move {
879                d.context_menu("target", "Paste it").await?;
880                d.assert_text("ran", "ran paste").await?;
881                d.context_menu("target", "Copy it").await?;
882                d.assert_text("ran", "ran copy").await
883            })
884    }
885
886    /// A menu built on summon reflects the state at that moment.
887    #[day_macros::test(day_core)]
888    fn context_menu_fn_builds_on_summon() -> Case {
889        Case::new()
890            .proves_modifier("context_menu")
891            .proves_duty("set_context_menu_fn")
892            .page(|| {
893                let count = Signal::new(0i64);
894                let chose = Signal::new(0i64);
895                column((
896                    label(move || format!("chose {}", chose.get())).id(day_core::id!(chose)),
897                    button("Add")
898                        .action(move || count.update(|n| *n += 1))
899                        .id(day_core::id!(add)),
900                    label("Target")
901                        .padding(8.0)
902                        .context_menu(move || {
903                            let n = count.get_untracked();
904                            vec![menu_item(format!("Take {n}")).action(move || chose.set(n))]
905                        })
906                        .id(day_core::id!(target)),
907                ))
908            })
909            .drive(|d: Drive| async move {
910                d.tap("add").await?;
911                d.tap("add").await?;
912                d.context_menu("target", "Take 2").await?;
913                d.assert_text("chose", "chose 2").await
914            })
915    }
916
917    /// A menu button's menu is built when it opens, so it reflects the state at that moment,
918    /// and choosing an item runs that item's action.
919    #[day_macros::test(day_core)]
920    fn menu_button_builds_on_open() -> Case {
921        Case::new()
922            .proves_duty("set_button_menu")
923            .page(|| {
924                let count = Signal::new(0i64);
925                let chose = Signal::new(0i64);
926                column((
927                    label(move || format!("chose {}", chose.get())).id(day_core::id!(chose)),
928                    button("Add")
929                        .action(move || count.update(|n| *n += 1))
930                        .id(day_core::id!(add)),
931                    menu_button("More", move || {
932                        let n = count.get_untracked();
933                        vec![
934                            menu_item(format!("Take {n}")).action(move || chose.set(n)),
935                            menu_separator(),
936                            menu_item("Never")
937                                .enabled(false)
938                                .action(move || chose.set(-1)),
939                        ]
940                    })
941                    .icon(day_spec::Symbol::More)
942                    .id(day_core::id!(more)),
943                ))
944            })
945            .drive(|d: Drive| async move {
946                d.tap("add").await?;
947                d.tap("add").await?;
948                d.context_menu("more", "Take 2").await?;
949                d.assert_text("chose", "chose 2").await
950            })
951    }
952}
953
954// ---------------------------------------------------------------------------
955// Sharing (docs/sharing.md)
956// ---------------------------------------------------------------------------
957
958/// A link to share through the system's share chooser, with the app's own actions beside the
959/// system's targets: Safari's Add Bookmark and Find on Page. Build one with
960/// [`Share::url`], then [`present`](Share::present) it from a user action.
961///
962/// ```rust,ignore
963/// Share::url(page.url())
964///     .title(page.title())
965///     .action(share_action(res::str::add_bookmark()).symbol(Symbol::Bookmark).action(add))
966///     .action(share_action(res::str::find_on_page()).symbol(Symbol::Search).action(find))
967///     .anchor(id!(share))
968///     .present();
969/// ```
970#[must_use = "a share request does nothing until it is presented"]
971pub struct Share {
972    url: String,
973    title: String,
974    actions: Vec<ShareAction>,
975    anchor: Option<day_core::ElementId>,
976}
977
978impl Share {
979    /// Share `url`.
980    pub fn url(url: impl Into<String>) -> Self {
981        Share {
982            url: url.into(),
983            title: String::new(),
984            actions: Vec::new(),
985            anchor: None,
986        }
987    }
988
989    /// The link's title: a mail's subject, the chooser's header where it shows one.
990    pub fn title(mut self, title: impl Into<String>) -> Self {
991        self.title = title.into();
992        self
993    }
994
995    /// Offer one of the app's own actions in the chooser, after the system's. Where the chooser
996    /// cannot carry the app's actions (`Cap::ShareActions` is `Unsupported`), they are left out:
997    /// offer the same commands in the app's own menu as well.
998    pub fn action(mut self, action: ShareAction) -> Self {
999        self.actions.push(action);
1000        self
1001    }
1002
1003    /// The control the chooser points at where it opens as a popover (iPad, macOS), by its
1004    /// element id: usually the share button itself. Without one, the chooser points at the
1005    /// window's top trailing corner.
1006    pub fn anchor(mut self, id: day_core::ElementId) -> Self {
1007        self.anchor = Some(id);
1008        self
1009    }
1010
1011    /// Present the chooser. Call it from a user action (the web requires one). Returns whether
1012    /// the chooser opened; cancelling it is not an error, and nothing reports what was shared.
1013    #[must_use]
1014    pub fn present(self) -> bool {
1015        let actions = self
1016            .actions
1017            .into_iter()
1018            .map(|a| (a.label.resolve(), a.symbol, a.handler))
1019            .collect();
1020        day_core::present_share(
1021            &self.url,
1022            &self.title,
1023            actions,
1024            self.anchor.as_ref().map(day_core::ElementId::as_str),
1025        )
1026    }
1027}
1028
1029/// One of the app's actions in a share chooser (see [`Share::action`]).
1030#[must_use]
1031pub struct ShareAction {
1032    label: TextSource,
1033    symbol: Option<day_spec::Symbol>,
1034    handler: Rc<dyn Fn()>,
1035}
1036
1037/// Build a share-chooser action named `label` (a literal or a `res::str::…` text, resolved
1038/// when the chooser opens). Chain [`symbol`](ShareAction::symbol) for its glyph and
1039/// [`action`](ShareAction::action) for the work, which runs once the chooser has closed.
1040pub fn share_action<M>(label: impl IntoText<M>) -> ShareAction {
1041    ShareAction {
1042        label: label.into_text(),
1043        symbol: None,
1044        handler: Rc::new(|| {}),
1045    }
1046}
1047
1048impl ShareAction {
1049    /// The action's glyph, where the chooser draws one.
1050    pub fn symbol(mut self, symbol: day_spec::Symbol) -> Self {
1051        self.symbol = Some(symbol);
1052        self
1053    }
1054
1055    /// What choosing the action does.
1056    pub fn action(mut self, f: impl Fn() + 'static) -> Self {
1057        self.handler = Rc::new(f);
1058        self
1059    }
1060}
1061
1062/// Whether this target can present a share chooser at all (docs/sharing.md).
1063#[must_use]
1064pub fn share_support() -> day_spec::Support {
1065    day_core::share_support()
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070    use super::*;
1071
1072    /// The role items every Edit menu carries take the standard accelerators when the app
1073    /// sets none, which is what gives GTK/Qt/web the shortcuts AppKit's native items always had.
1074    #[test]
1075    fn role_items_take_standard_shortcuts() {
1076        use day_spec::{MenuItem, MenuRole};
1077        let lowered = lower_menu(vec![
1078            menu_role(MenuRole::Undo),
1079            menu_role(MenuRole::Redo),
1080            menu_role(MenuRole::Cut),
1081            menu_role(MenuRole::Copy),
1082            menu_role(MenuRole::Paste),
1083            menu_role(MenuRole::SelectAll),
1084        ]);
1085        let expect = [
1086            ("z", false),
1087            ("z", true),
1088            ("x", false),
1089            ("c", false),
1090            ("v", false),
1091            ("a", false),
1092        ];
1093        for (item, (key, shift)) in lowered.iter().zip(expect) {
1094            let MenuItem::Action {
1095                shortcut, action, ..
1096            } = item
1097            else {
1098                panic!("role item lowered to a non-action");
1099            };
1100            let sc = shortcut.as_ref().expect("role item has a default shortcut");
1101            assert_eq!(sc.key, key);
1102            assert!(sc.primary);
1103            assert_eq!(sc.shift, shift);
1104            assert_ne!(*action, 0, "role item carries its standing dispatcher");
1105        }
1106    }
1107}