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