day-pieces 0.7.3

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! The app menu builder: `menu_item`, `sub_menu`, `menu_separator`, and `menu_role`, assembled
//! with `app_menu`. Lowers to day_spec's toolkit-neutral `MenuItem` model and registers each
//! item's action closure.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use day_reactive::Scope;

use day_core::Piece;

use crate::{Decorated, IntoReactive, IntoText, Reactive, TextSource};

// ---------------------------------------------------------------------------
// Menus: the app-side builder over day_spec's toolkit-neutral MenuItem model. Lowering registers
// each item's action closure with day-core (which dispatches `Event::MenuAction`) and assigns its
// id.
// ---------------------------------------------------------------------------

/// A menu entry under construction. Build a command with [`menu_item`], a nested submenu with
/// [`sub_menu`], a standard system command with [`menu_role`], and a divider with [`menu_separator`].
/// Attach to a Piece via [`Decorate::context_menu`](crate::decorators::Decorate::context_menu) or install app-wide via [`app_menu`].
#[derive(Clone)]
pub struct MenuEntry {
    id: Option<String>,
    /// The title, live: resolved (tracked) when the menu is lowered, so a localized title
    /// follows a language switch and a title built from a signal follows the signal.
    label: TextSource,
    shortcut: Option<day_spec::Shortcut>,
    enabled: Reactive<bool>,
    role: Option<day_spec::MenuRole>,
    icon: Option<day_spec::Icon>,
    checked: Option<Reactive<bool>>,
    action: Option<Rc<dyn Fn()>>,
    children: Option<Vec<MenuEntry>>,
    separator: bool,
    bar_role: Option<day_spec::MenuBarRole>,
}

impl MenuEntry {
    fn command(label: TextSource) -> MenuEntry {
        MenuEntry {
            id: None,
            label,
            shortcut: None,
            enabled: Reactive::Const(true),
            role: None,
            icon: None,
            bar_role: None,
            checked: None,
            action: None,
            children: None,
            separator: false,
        }
    }

    /// A standard [`Symbol`](day_spec::Symbol) beside the item's title, drawn with the
    /// platform's glyph, the same vocabulary toolbars take. Menus carry icons on macOS,
    /// Windows, GNOME, KDE and Android; a backend whose menus are text-only ignores it, so an
    /// icon is always an addition to a menu that already reads correctly without one.
    pub fn icon(mut self, s: day_spec::Symbol) -> MenuEntry {
        self.icon = Some(day_spec::Icon::Symbol(s));
        self
    }

    /// A bundled image from `resource/images`, for an item the standard set has no glyph for:
    /// an app's own vocabulary (a shape, a brand). Same rule as [`MenuEntry::icon`].
    pub fn image(mut self, name: impl Into<String>) -> MenuEntry {
        self.icon = Some(day_spec::Icon::Image(name.into()));
        self
    }
    /// Run `f` when the item is chosen.
    pub fn action(mut self, f: impl Fn() + 'static) -> MenuEntry {
        self.action = Some(Rc::new(f));
        self
    }
    /// Full shortcut spec, e.g. `Shortcut::primary("s").shift()`.
    pub fn shortcut(mut self, s: day_spec::Shortcut) -> MenuEntry {
        self.shortcut = Some(s);
        self
    }
    /// Convenience: the platform's primary modifier (⌘ / Ctrl) + `key`. This sets the item's
    /// shortcut; to name the item, use [`MenuEntry::id`].
    pub fn key(mut self, key: impl Into<String>) -> MenuEntry {
        self.shortcut = Some(day_spec::Shortcut::primary(key));
        self
    }

    /// Name this item, so something outside the menu can address it: a dayscript
    /// `menu: { id: "view-both" }` step, or a `tap` on the composed menu's row where the platform
    /// has no native menus.
    ///
    /// A label cannot do that job. It is localized, so it changes with the run's language, and an
    /// item that shows its own state changes it whenever the state moves, which is exactly the
    /// case [`MenuEntry::checked`] creates. Give an id to any item a script drives.
    pub fn id(mut self, id: day_core::ElementId) -> MenuEntry {
        self.id = Some(id.as_str().to_owned());
        self
    }

    /// Draw this item with the platform's check mark, on or off, for a setting the menu toggles
    /// or one of several mutually exclusive choices. An item that never calls this is a plain
    /// command and reserves no room for a mark.
    ///
    /// Choosing the item still runs its [`action`](MenuEntry::action); no backend flips the mark
    /// by itself. The app owns the state: pass the signal (or a closure reading it) and the mark
    /// follows the state, the menu re-lowering when it changes.
    ///
    /// ```ignore
    /// menu_item(tr("view_grid")).id(day_core::id!(view_grid)).checked(grid).action(move || grid.set(!grid.get()))
    /// ```
    pub fn checked<M>(mut self, on: impl IntoReactive<bool, M>) -> MenuEntry {
        self.checked = Some(on.into_reactive());
        self
    }
    /// Whether the item can be chosen (default `true`): a constant, a `Signal<bool>`, or a
    /// closure, re-read whenever the menu is lowered.
    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> MenuEntry {
        self.enabled = on.into_reactive();
        self
    }
    /// Tag a custom command with a standard [`day_spec::MenuRole`] (usually you use [`menu_role`]).
    pub fn role(mut self, role: day_spec::MenuRole) -> MenuEntry {
        self.role = Some(role);
        self
    }
}

/// A clickable command: `menu_item(res::str::save()).key("s").action(|| …)`. The title takes
/// the same sources as a label (a literal, a localized text, a signal, a closure) and stays
/// live.
pub fn menu_item<M>(label: impl IntoText<M>) -> MenuEntry {
    MenuEntry::command(label.into_text())
}

/// A nested submenu: `sub_menu(res::str::menu_file(), vec![menu_item(…), …])`.
pub fn sub_menu<M>(label: impl IntoText<M>, items: Vec<MenuEntry>) -> MenuEntry {
    MenuEntry {
        children: Some(items),
        ..MenuEntry::command(label.into_text())
    }
}

/// Claim one of the platform's standard menu-bar slots for this submenu: the backend places it
/// where that menu belongs and does not add its stock version. Without a role, a submenu is
/// an app menu and sits between the standard ones.
///
/// ```ignore
/// sub_menu(res::str::menu_file(), menu_items).bar_role(MenuBarRole::File)
/// ```
impl MenuEntry {
    pub fn bar_role(mut self, role: day_spec::MenuBarRole) -> MenuEntry {
        self.bar_role = Some(role);
        self
    }
}

/// A visual divider between items.
pub fn menu_separator() -> MenuEntry {
    MenuEntry {
        separator: true,
        ..MenuEntry::command(TextSource::Static(String::new()))
    }
}

/// A standard/system command (`MenuRole::Copy`, `MenuRole::Quit`, …) rendered with the platform's
/// native item (correct label, default shortcut, focus-targeting, and automatic enable/disable),
/// so default menu items (Edit ▸ Cut/Copy/Paste, the app's Quit/About) work without
/// re-implementation.
pub fn menu_role(role: day_spec::MenuRole) -> MenuEntry {
    MenuEntry {
        role: Some(role),
        ..MenuEntry::command(TextSource::Static(String::new()))
    }
}

/// The core-catalog key for a standard menu command's label (docs/menus.md, docs/localization.md).
fn role_catalog_key(role: day_spec::MenuRole) -> &'static str {
    use day_spec::MenuRole as R;
    match role {
        R::Cut => "day_cut",
        R::Copy => "day_copy",
        R::Paste => "day_paste",
        R::SelectAll => "day_select_all",
        R::Undo => "day_undo",
        R::Redo => "day_redo",
        R::Delete => "day_delete",
        R::About => "day_about",
        R::Quit => "day_quit",
        R::Preferences => "day_preferences",
        R::Minimize => "day_minimize",
        R::CloseWindow => "day_close",
        R::Fullscreen => "day_fullscreen",
        R::NewWindow => "day_new_window",
        R::CheckForUpdates => "day_check_for_updates",
    }
}

/// Lower app-side entries to the spec model, registering action closures with day-core. A standard
/// `role` item with no explicit label gets its label from the localized core catalog here, so the
/// backends receive a ready, locale-correct label instead of each hardcoding English (day-localization).
///
/// This variant registers process-lived closures, correct for the app menu and toolbars, whose
/// ids day-core manages by shape-rebinding, toolbar slots and explicit sweeps. Menus owned by a piece build
/// (a `.context_menu`, a nav row's menu) go through [`lower_menu_scoped`] instead, so their
/// closures are reclaimed when the registering scope is disposed rather than leaking per remount.
pub(crate) fn lower_menu(entries: Vec<MenuEntry>) -> Vec<day_spec::MenuItem> {
    lower_menu_with(entries, &day_core::register_menu_action)
}

/// [`lower_menu`] with scope-tied action registration (see there for when to use which).
pub(crate) fn lower_menu_scoped(entries: Vec<MenuEntry>) -> Vec<day_spec::MenuItem> {
    lower_menu_with(entries, &day_core::register_scoped_menu_action)
}

fn lower_menu_with(
    entries: Vec<MenuEntry>,
    register: &dyn Fn(Rc<dyn Fn()>) -> u64,
) -> Vec<day_spec::MenuItem> {
    entries
        .into_iter()
        .map(|e| {
            if e.separator {
                day_spec::MenuItem::Separator
            } else if let Some(children) = e.children {
                day_spec::MenuItem::Submenu {
                    label: e.label.resolve(),
                    items: lower_menu_with(children, register),
                    role: e.bar_role,
                }
            } else {
                let mut action = e.action.map(register).unwrap_or(0);
                // Tracked reads: a menu lowered inside `app_menu`'s effect re-lowers when
                // a title, availability or check state changes.
                let mut enabled = e.enabled.get();
                let mut shortcut = e.shortcut;
                // Window roles have no native selector on any platform: an action-less item
                // lowers to the registered day dispatcher (docs/windows.md): live when the
                // app registered a builder/preferences piece, disabled otherwise.
                if action == 0 {
                    match e.role {
                        Some(day_spec::MenuRole::NewWindow) => {
                            action = day_core::windows::new_window_action_id();
                            enabled = enabled && action != 0;
                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("n")));
                        }
                        // The undo pair and the clipboard trio lower to standing dispatchers
                        // too, for toolkits whose role items come back as plain menu actions
                        // (Android's app-bar menu, the iOS menu, web context menus). Toolkits
                        // with a native responder route ignore the action and keep their selector
                        // (see each backend's menu build). Each also takes the platform-neutral
                        // standard shortcut (primary+Z/X/C/V/A, shift for redo) unless the app
                        // set its own. AppKit's native items already carry these, so this is
                        // what gives GTK/Qt/web the same accelerators.
                        Some(day_spec::MenuRole::Undo) => {
                            action = day_core::undo_action_id(false);
                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("z")));
                        }
                        Some(day_spec::MenuRole::Redo) => {
                            action = day_core::undo_action_id(true);
                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("z").shift()));
                        }
                        Some(day_spec::MenuRole::Cut) => {
                            action = day_core::edit_action_id(day_spec::EditOp::Cut);
                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("x")));
                        }
                        Some(day_spec::MenuRole::Copy) => {
                            action = day_core::edit_action_id(day_spec::EditOp::Copy);
                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("c")));
                        }
                        Some(day_spec::MenuRole::Paste) => {
                            action = day_core::edit_action_id(day_spec::EditOp::Paste);
                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("v")));
                        }
                        Some(day_spec::MenuRole::SelectAll) => {
                            action = day_core::edit_action_id(day_spec::EditOp::SelectAll);
                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary("a")));
                        }
                        Some(day_spec::MenuRole::Preferences) => {
                            action = day_core::windows::preferences_action_id();
                            shortcut = shortcut.or(Some(day_spec::Shortcut::primary(",")));
                        }
                        // About keeps the toolkit's stock panel (action 0) until an app
                        // registers its own (docs/settings.md); the updater command has no
                        // native fallback and lowers disabled when nothing registered.
                        Some(day_spec::MenuRole::About) => {
                            action = day_core::windows::about_action_id();
                        }
                        Some(day_spec::MenuRole::CheckForUpdates) => {
                            action = day_core::windows::check_for_updates_action_id();
                            enabled = enabled && action != 0;
                        }
                        _ => {}
                    }
                }
                let label = e.label.resolve();
                let label = match (label.is_empty(), e.role) {
                    (true, Some(role)) => day_localization::t(role_catalog_key(role)),
                    _ => label,
                };
                day_spec::MenuItem::Action {
                    id: e.id,
                    action,
                    label,
                    shortcut,
                    enabled,
                    checked: e.checked.as_ref().map(Reactive::get),
                    role: e.role,
                    icon: e.icon,
                }
            }
        })
        .collect()
}

/// Where a menu's entries come from: a fixed list, or a closure that derives the list and
/// re-runs whenever its reactive reads change. What [`app_menu`], [`dock_menu`] and
/// [`StatusItem::menu`](crate::StatusItem::menu) accept, through [`MenuContent`].
#[derive(Clone)]
pub enum MenuSource {
    Fixed(Vec<MenuEntry>),
    Derived(Rc<dyn Fn() -> Vec<MenuEntry>>),
}

impl MenuSource {
    /// The entries right now: a tracked read for a derived source.
    pub(crate) fn entries(&self) -> Vec<MenuEntry> {
        match self {
            MenuSource::Fixed(v) => v.clone(),
            MenuSource::Derived(f) => f(),
        }
    }
}

/// Anything an app menu takes: a `Vec` or array of entries, or a closure that derives the
/// entries and re-runs whenever its reactive reads change. The marker parameter is the same
/// E0119 dodge as [`ToolbarContent`](crate::ToolbarContent).
pub trait MenuContent<M> {
    fn into_source(self) -> MenuSource;
}

impl MenuContent<crate::ManyMark> for Vec<MenuEntry> {
    fn into_source(self) -> MenuSource {
        MenuSource::Fixed(self)
    }
}

impl<const N: usize> MenuContent<crate::ManyMark> for [MenuEntry; N] {
    fn into_source(self) -> MenuSource {
        MenuSource::Fixed(Vec::from(self))
    }
}

impl<C, F> MenuContent<crate::DerivedMark> for F
where
    C: IntoIterator<Item = MenuEntry>,
    F: Fn() -> C + 'static,
{
    fn into_source(self) -> MenuSource {
        MenuSource::Derived(Rc::new(move || self().into_iter().collect()))
    }
}

day_reactive::tls_slots! { menus;
    /// The scope owning the current app-menu and dock-menu installs, so a second call replaces
    /// the first (and reclaims its bindings) instead of leaving two installers racing.
    static APP_MENU_SCOPE: Cell<Option<Scope>> = const { Cell::new(None) };
    static DOCK_MENU_SCOPE: Cell<Option<Scope>> = const { Cell::new(None) };
}

/// Install `source` through `install`, in a root-owned scope that replaces the previous one.
fn install_menu(
    slot: &Cell<Option<Scope>>,
    source: MenuSource,
    install: fn(Vec<day_spec::MenuItem>),
) {
    if let Some(old) = slot.take() {
        old.dispose();
    }
    let scope = Scope::root().enter(Scope::child);
    scope.enter(|| {
        day_reactive::bind(
            move || {
                // Track the locale even when the entries carry no localized reads, so
                // role-label fallbacks still refresh; every entry's title, availability and
                // check state is a tracked read of its own inside `lower_menu`.
                let _ = day_localization::locale().get();
                lower_menu(source.entries())
            },
            move |items: &Vec<day_spec::MenuItem>| install(items.clone()),
        );
    });
    slot.set(Some(scope));
}

/// Install the application menu: the native menu bar on desktop, the app-bar overflow on Android,
/// the UIMenuBuilder main menu on iPadOS/Catalyst. Top-level entries are usually `sub_menu(…)`s
/// (the menu-bar menus). Takes a list of entries or a closure that derives them.
///
/// The menu is live (docs/menus.md): every title, `enabled` and `checked` is re-read, and the
/// menu re-lowered and reinstalled, whenever one of them changes, so `menu_role` labels,
/// `res::str` titles and `day::tr` all follow a runtime language switch, and a derived closure
/// re-runs on whatever signals it reads. Calling it again replaces the previous install and
/// reclaims its action closures. Install once, at startup.
///
/// ```ignore
/// app_menu([
///     sub_menu(res::str::menu_file(), vec![menu_item(res::str::new_item()).key("n").action(add)]),
///     sub_menu(res::str::menu_view(), vec![menu_item(res::str::grid()).checked(grid).action(flip)]),
/// ]);
/// ```
pub fn app_menu<M>(menus: impl MenuContent<M>) {
    APP_MENU_SCOPE.with(|slot| install_menu(slot, menus.into_source(), day_core::set_app_menu));
}

/// Install the app's Dock menu (docs/menus.md "Dock menu"): the entries macOS lists when the
/// user right-clicks the app's Dock icon, above the app's `[[shortcuts]]` and the system's own
/// Show / Hide / Quit items. Probe `Cap::DockMenu`; elsewhere the call does nothing. Live, like
/// [`app_menu`]: `Resume <last document>`, a checked "Do Not Disturb", the locale. Install
/// once, at startup.
///
/// The menu works while the app runs, so its actions are ordinary closures, unlike shortcuts,
/// which are routes because they also launch the app.
pub fn dock_menu<M>(entries: impl MenuContent<M>) {
    DOCK_MENU_SCOPE.with(|slot| install_menu(slot, entries.into_source(), day_core::set_dock_menu));
}

// ---------------------------------------------------------------------------
// Menu buttons (docs/menus.md "Menu buttons"): a native button whose primary press opens a menu.
// ---------------------------------------------------------------------------

/// A button that opens a menu when pressed: the ⋯ More button beside a browser's address bar, an
/// Add ▾ button, a page-actions button in a toolbar row the app draws itself. Build one with
/// [`menu_button`].
///
/// It is the platform's own pull-down: an `NSButton` that pops its `NSMenu` under itself, a
/// `UIButton` whose menu is its primary action, a `GtkMenuButton`-style popover, a `QPushButton`
/// with a `QMenu`, a Material button with a `PopupMenu`, a WinUI `Button` with a `MenuFlyout`,
/// and the web toolbar's pull-down popover. The entries are the same [`MenuEntry`] values a
/// context menu takes, so checked, disabled and destructive-looking items, separators and
/// submenus behave as they do there.
///
/// The button carries the piece's [`.id`](crate::Decorate::id); each item keeps its own
/// [`MenuEntry::id`]. A dayscript `context_menu: { id: <button>, item_id: <item> }` step chooses
/// an item, as a press and a choice would.
pub struct MenuButton {
    button: crate::Button,
    entries: MenuSource,
    enabled: Reactive<bool>,
}

/// A button that opens `entries` as a menu when pressed (docs/menus.md "Menu buttons").
///
/// `entries` is a `Vec` or array of [`MenuEntry`] values, or a closure that builds them. Either
/// way the menu is built when it opens, so every title, [`checked`](MenuEntry::checked) and
/// [`enabled`](MenuEntry::enabled) state is the current one; the closure form also lets the
/// list itself depend on what is true at that moment.
///
/// ```ignore
/// menu_button(res::str::more(), move || {
///     vec![
///         menu_item(res::str::reader_view())
///             .id(id!(reader))
///             .checked(reader)
///             .action(move || reader.set(!reader.get())),
///         menu_separator(),
///         menu_item(res::str::share()).id(id!(share)).enabled(move || page.get().is_some()).action(share),
///     ]
/// })
/// .icon(Symbol::More)
/// .icon_only()
/// .plain()
/// .id(id!(more))
/// ```
pub fn menu_button<M, E>(label: impl IntoText<M>, entries: impl MenuContent<E>) -> MenuButton {
    MenuButton {
        button: crate::button(label),
        entries: entries.into_source(),
        enabled: Reactive::Const(true),
    }
}

#[day_macros::builder(MenuButtonBuilder)]
impl MenuButton {
    /// Show a platform symbol beside (or, with [`icon_only`](MenuButton::icon_only), instead of)
    /// the label, as [`Button::icon`](crate::Button::icon) does.
    pub fn icon<M>(mut self, symbol: impl IntoReactive<day_spec::Symbol, M>) -> Self {
        self.button = self.button.icon(symbol);
        self
    }

    /// Show a bundled image or vector alongside the label, as
    /// [`Button::image`](crate::Button::image) does.
    pub fn image(mut self, name: impl Into<day_spec::ImageName>) -> Self {
        self.button = self.button.image(name);
        self
    }

    /// Hide the visible label when an icon is available. The label stays the accessible name
    /// and, on desktop and web, the tooltip.
    pub fn icon_only(mut self) -> Self {
        self.button = self.button.icon_only();
        self
    }

    /// A borderless button, for a toolbar row or a list accessory ([`Button::plain`](crate::Button::plain)).
    pub fn plain(mut self) -> Self {
        self.button = self.button.plain();
        self
    }

    /// A contained button where the stock look is borderless ([`Button::bordered`](crate::Button::bordered)).
    pub fn bordered(mut self) -> Self {
        self.button = self.button.bordered();
        self
    }

    /// No wider than its label ([`Button::compact`](crate::Button::compact)).
    pub fn compact(mut self) -> Self {
        self.button = self.button.compact();
        self
    }

    /// The platform's accent-filled button ([`Button::prominent`](crate::Button::prominent)).
    pub fn prominent(mut self) -> Self {
        self.button = self.button.prominent();
        self
    }

    /// Whether the button can open its menu (default `true`): a constant, a signal or a closure.
    /// A disabled menu button is drawn disabled by the native control and opens nothing, a
    /// dayscript `context_menu` step included.
    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Self {
        let on = on.into_reactive();
        self.button = match on.clone() {
            Reactive::Const(v) => self.button.enabled(v),
            Reactive::Dyn(f) => self.button.enabled(move || f()),
        };
        self.enabled = on;
        self
    }
}

impl Piece for MenuButton {
    fn build(self, cx: &mut day_core::BuildCx) -> day_core::RNode {
        // The same wrapper a `.context_menu` builds: the button fills it, and the composed
        // presenter's lazy mount sits beside it for a toolkit that reports the press instead of
        // showing a native menu (ArkUI).
        let w = cx.layout_only(
            Rc::new(crate::decorators::OverlayHost),
            day_core::Flex::default(),
            day_core::Boundary::No,
        );
        let mut n = w;
        let MenuButton {
            button,
            entries,
            enabled,
        } = self;
        cx.under(w, |cx| {
            n = button.build(cx);
            let provider = menu_button_provider(entries, enabled);
            day_core::with_tree(|t| t.set_button_menu(n, provider.clone()));
            mount_composed_menu(cx, n, provider);
        });
        day_core::with_tree(|t| t.forward_whole_row(w, n));
        // Identity modifiers and the dayscript step name the button, not the wrapper.
        n
    }
}

/// The provider a menu button hands the toolkit: lowers the entries when the menu opens, each
/// time into a fresh scope that the next open (or the button's teardown) disposes, the rule
/// `.context_menu(|| …)` follows, so an often-opened menu never accumulates registrations.
fn menu_button_provider(entries: MenuSource, enabled: Reactive<bool>) -> day_spec::ContextMenuFn {
    let last: Rc<RefCell<Option<Scope>>> = Rc::default();
    {
        let last = last.clone();
        Scope::current().on_cleanup(move || {
            if let Some(s) = last.borrow_mut().take() {
                s.dispose();
            }
        });
    }
    Rc::new(move |_at| {
        if !enabled.get_untracked() {
            return Vec::new();
        }
        if let Some(s) = last.borrow_mut().take() {
            s.dispose();
        }
        let scope = Scope::child();
        let entries = &entries;
        let items = scope.enter(|| lower_menu_scoped(entries.entries()));
        *last.borrow_mut() = Some(scope);
        items
    })
}

// ---------------------------------------------------------------------------
// The composed context menu (docs/menus.md "Dynamic context menus"): presentation for a
// toolkit that REPORTS the summon (`Event::ContextMenu`) instead of showing a native menu
// of its own (web-dom). Works on the LOWERED model, so role resolution, localization, and
// per-summon action scoping are exactly what a native backend would have received.
// ---------------------------------------------------------------------------

/// The composed menu's stand-in for a native check mark, and the blank that holds its column.
const COMPOSED_CHECK_ON: &str = "\u{2713}\u{2002}";
const COMPOSED_CHECK_OFF: &str = "\u{2002}\u{2002}";
/// Panel width of the composed menu, and the extra indent inlined submenu items take.
const COMPOSED_MENU_W: f64 = 220.0;
const COMPOSED_SUBMENU_INDENT: f64 = 12.0;

/// Mount the composed presentation beside a `.context_menu` node: an
/// `Event::ContextMenu` handler plus a lazily-armed, unrouted [`crate::cover`] that shows the
/// provider's items at the summon point. Nothing builds until the first summon arrives, so
/// backends that serve the menu natively (and therefore never emit the event) never pay.
pub(crate) fn mount_composed_menu(
    cx: &mut day_core::BuildCx,
    node: day_core::RNode,
    provider: day_spec::ContextMenuFn,
) {
    use day_reactive::Signal;
    use std::cell::RefCell;

    struct Pending {
        items: Vec<day_spec::MenuItem>,
        at: day_spec::Point,
    }
    let armed = Signal::new(false);
    let open: Signal<Option<String>> = Signal::new(None);
    let pending: Rc<RefCell<Pending>> = Rc::new(RefCell::new(Pending {
        items: Vec::new(),
        at: day_spec::Point::ZERO,
    }));

    {
        let pending = pending.clone();
        cx.on(node, move |ev| {
            if let day_spec::Event::ContextMenu { local, window } = ev {
                let items = provider(*local);
                if items.is_empty() {
                    return;
                }
                *pending.borrow_mut() = Pending { items, at: *window };
                armed.set(true);
                open.set(Some("menu".into()));
            }
        });
    }

    let host = crate::when(
        move || armed.get(),
        move || {
            let pending = pending.clone();
            crate::cover(open, move |_: &String| {
                let (items, at) = {
                    let p = pending.borrow();
                    (p.items.clone(), p.at)
                };
                composed_menu_host(items, at, open)
            })
            .unrouted()
            .background(|_| day_spec::Color::rgba(0.0, 0.0, 0.0, 0.0))
        },
    );
    let _ = day_core::Piece::build(host, cx);
}

/// The presented surface: a fullscreen dismiss catcher plus the item panel, placed at the
/// summon point (clamped into the window by [`MenuPlace`]).
fn composed_menu_host(
    items: Vec<day_spec::MenuItem>,
    at: day_spec::Point,
    open: day_reactive::Signal<Option<String>>,
) -> impl day_core::Piece {
    use crate::Decorate;

    let mut rows: Vec<day_core::AnyPiece> = Vec::new();
    let mut next = 0usize;
    composed_menu_rows(&items, 0.0, &mut next, open, &mut rows);

    let panel = crate::column(rows)
        .padding(day_spec::Insets::symmetric(0.0, 5.0))
        .background(|| {
            if day_core::dark_mode() {
                day_spec::Color::rgb(0.22, 0.22, 0.24)
            } else {
                day_spec::Color::rgb(0.97, 0.97, 0.97)
            }
        })
        .corner_radius(8.0);
    let catcher = crate::spacer()
        .background(day_spec::Color::rgba(0.0, 0.0, 0.0, 0.0))
        .on_tap(move || open.set(None));
    ComposedMenuHost {
        at,
        catcher: day_core::AnyPiece::new(catcher),
        panel: day_core::AnyPiece::new(panel),
    }
}

/// One flattened item row per entry. Submenus inline as a dimmed header plus indented
/// children, since the composed panel has no flyout (docs/menus.md).
fn composed_menu_rows(
    items: &[day_spec::MenuItem],
    indent: f64,
    next: &mut usize,
    open: day_reactive::Signal<Option<String>>,
    out: &mut Vec<day_core::AnyPiece>,
) {
    use crate::Decorate;
    for item in items {
        match item {
            day_spec::MenuItem::Separator => {
                out.push(day_core::AnyPiece::new(
                    crate::divider().padding(day_spec::Insets::symmetric(0.0, 4.0)),
                ));
            }
            day_spec::MenuItem::Submenu { label, items, .. } => {
                out.push(day_core::AnyPiece::new(
                    crate::label(label.clone())
                        .padding(day_spec::Insets::symmetric(12.0 + indent, 5.0))
                        .width(COMPOSED_MENU_W)
                        .opacity(0.55),
                ));
                composed_menu_rows(items, indent + COMPOSED_SUBMENU_INDENT, next, open, out);
            }
            day_spec::MenuItem::Action {
                id,
                action,
                label,
                enabled,
                checked,
                ..
            } => {
                let n = *next;
                *next += 1;
                // A checkable item reserves the mark's column whichever way it sits, so a run of
                // choices lines up on its titles instead of stepping in and out by a tick's width.
                let text = match checked {
                    Some(true) => format!("{COMPOSED_CHECK_ON}{label}"),
                    Some(false) => format!("{COMPOSED_CHECK_OFF}{label}"),
                    None => label.clone(),
                };
                // The app's own name where it gave one, so a dayscript `tap` addresses the row it
                // means; the positional fallback keeps every other row reachable.
                let element_id = id
                    .clone()
                    .unwrap_or_else(|| day_core::id!(day_menu_item, n).as_str().to_owned());
                let base = crate::label(text)
                    .padding(day_spec::Insets::symmetric(12.0 + indent, 5.0))
                    .width(COMPOSED_MENU_W);
                let row = if *enabled && *action != 0 {
                    let action = *action;
                    base.background(day_spec::Color::rgba(0.0, 0.0, 0.0, 0.0))
                        .on_tap(move || {
                            open.set(None);
                            day_core::dispatch_menu_action(action);
                        })
                        .tweak(move |node| {
                            day_core::with_tree(|tree| tree.set_id(node, element_id))
                        })
                } else {
                    base.opacity(0.45).tweak(move |node| {
                        day_core::with_tree(|tree| tree.set_id(node, element_id))
                    })
                };
                out.push(day_core::AnyPiece::new(row));
            }
        }
    }
}

/// Places the catcher over the full window and the panel at the summon point, pulled back
/// inside the bounds when the summon point sits too close to an edge.
struct MenuPlace {
    at: day_spec::Point,
}

impl day_core::Layout for MenuPlace {
    fn measure(
        &self,
        _cx: &mut dyn day_core::LayoutOps,
        _children: &[day_core::RNode],
        p: day_spec::Proposal,
    ) -> day_spec::Size {
        day_spec::Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0))
    }
    fn place(
        &self,
        cx: &mut dyn day_core::LayoutOps,
        children: &[day_core::RNode],
        bounds: day_spec::Rect,
    ) {
        if let Some(&c) = children.first() {
            let _ = cx.measure_child(c, day_spec::Proposal::exact(bounds.size));
            cx.place_child(c, day_spec::Rect::from_size(bounds.size));
        }
        if let Some(&c) = children.get(1) {
            let s = cx.measure_child(c, day_spec::Proposal::new(Some(COMPOSED_MENU_W), None));
            // Pull the panel back inside the window when the summon point sits near an edge,
            // unless bounds are degenerate (a pass before the backend reported the size).
            let (x, y) = if bounds.size.width > 1.0 && bounds.size.height > 1.0 {
                (
                    self.at.x.min(bounds.size.width - s.width).max(0.0),
                    self.at.y.min(bounds.size.height - s.height).max(0.0),
                )
            } else {
                (self.at.x, self.at.y)
            };
            cx.place_child(c, day_spec::Rect::new(x, y, s.width, s.height));
        }
    }
}

/// The [`MenuPlace`] wrapper piece: catcher first, panel second.
struct ComposedMenuHost {
    at: day_spec::Point,
    catcher: day_core::AnyPiece,
    panel: day_core::AnyPiece,
}

impl day_core::Piece for ComposedMenuHost {
    fn build(self, cx: &mut day_core::BuildCx) -> day_core::RNode {
        let n = cx.layout_only(
            Rc::new(MenuPlace { at: self.at }),
            day_core::Flex {
                grow_w: true,
                grow_h: true,
                ..Default::default()
            },
            day_core::Boundary::No,
        );
        cx.under(n, |cx| {
            let _ = self.catcher.build(cx);
            let _ = self.panel.build(cx);
        });
        n
    }
}

#[cfg(feature = "conformance")]
pub(crate) mod conformance {
    use day_core::conformance::{Case, Drive};
    use day_reactive::Signal;

    use crate::*;

    /// Choosing a context-menu item runs that item's action, and only that one.
    #[day_macros::test(day_core)]
    fn context_menu_runs_action() -> Case {
        Case::new()
            .proves_modifier("context_menu")
            .proves_duty("set_context_menu")
            .page(|| {
                let last = Signal::new(String::from("none"));
                column((
                    label(move || format!("ran {}", last.get())).id(day_core::id!(ran)),
                    label("Target")
                        .padding(8.0)
                        .context_menu(vec![
                            menu_item("Copy it").action(move || last.set("copy".into())),
                            menu_item("Paste it").action(move || last.set("paste".into())),
                        ])
                        .id(day_core::id!(target)),
                ))
            })
            .drive(|d: Drive| async move {
                d.context_menu("target", "Paste it").await?;
                d.assert_text("ran", "ran paste").await?;
                d.context_menu("target", "Copy it").await?;
                d.assert_text("ran", "ran copy").await
            })
    }

    /// A menu built on summon reflects the state at that moment.
    #[day_macros::test(day_core)]
    fn context_menu_fn_builds_on_summon() -> Case {
        Case::new()
            .proves_modifier("context_menu")
            .proves_duty("set_context_menu_fn")
            .page(|| {
                let count = Signal::new(0i64);
                let chose = Signal::new(0i64);
                column((
                    label(move || format!("chose {}", chose.get())).id(day_core::id!(chose)),
                    button("Add")
                        .action(move || count.update(|n| *n += 1))
                        .id(day_core::id!(add)),
                    label("Target")
                        .padding(8.0)
                        .context_menu(move || {
                            let n = count.get_untracked();
                            vec![menu_item(format!("Take {n}")).action(move || chose.set(n))]
                        })
                        .id(day_core::id!(target)),
                ))
            })
            .drive(|d: Drive| async move {
                d.tap("add").await?;
                d.tap("add").await?;
                d.context_menu("target", "Take 2").await?;
                d.assert_text("chose", "chose 2").await
            })
    }

    /// A menu button's menu is built when it opens, so it reflects the state at that moment,
    /// and choosing an item runs that item's action.
    #[day_macros::test(day_core)]
    fn menu_button_builds_on_open() -> Case {
        Case::new()
            .proves_duty("set_button_menu")
            .page(|| {
                let count = Signal::new(0i64);
                let chose = Signal::new(0i64);
                column((
                    label(move || format!("chose {}", chose.get())).id(day_core::id!(chose)),
                    button("Add")
                        .action(move || count.update(|n| *n += 1))
                        .id(day_core::id!(add)),
                    menu_button("More", move || {
                        let n = count.get_untracked();
                        vec![
                            menu_item(format!("Take {n}")).action(move || chose.set(n)),
                            menu_separator(),
                            menu_item("Never")
                                .enabled(false)
                                .action(move || chose.set(-1)),
                        ]
                    })
                    .icon(day_spec::Symbol::More)
                    .id(day_core::id!(more)),
                ))
            })
            .drive(|d: Drive| async move {
                d.tap("add").await?;
                d.tap("add").await?;
                d.context_menu("more", "Take 2").await?;
                d.assert_text("chose", "chose 2").await
            })
    }
}

// ---------------------------------------------------------------------------
// Sharing (docs/sharing.md)
// ---------------------------------------------------------------------------

/// A link to share through the system's share chooser, with the app's own actions beside the
/// system's targets: Safari's Add Bookmark and Find on Page. Build one with
/// [`Share::url`], then [`present`](Share::present) it from a user action.
///
/// ```rust,ignore
/// Share::url(page.url())
///     .title(page.title())
///     .action(share_action(res::str::add_bookmark()).symbol(Symbol::Bookmark).action(add))
///     .action(share_action(res::str::find_on_page()).symbol(Symbol::Search).action(find))
///     .anchor(id!(share))
///     .present();
/// ```
#[must_use = "a share request does nothing until it is presented"]
pub struct Share {
    url: String,
    title: String,
    actions: Vec<ShareAction>,
    anchor: Option<day_core::ElementId>,
}

impl Share {
    /// Share `url`.
    pub fn url(url: impl Into<String>) -> Self {
        Share {
            url: url.into(),
            title: String::new(),
            actions: Vec::new(),
            anchor: None,
        }
    }

    /// The link's title: a mail's subject, the chooser's header where it shows one.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Offer one of the app's own actions in the chooser, after the system's. Where the chooser
    /// cannot carry the app's actions (`Cap::ShareActions` is `Unsupported`), they are left out:
    /// offer the same commands in the app's own menu as well.
    pub fn action(mut self, action: ShareAction) -> Self {
        self.actions.push(action);
        self
    }

    /// The control the chooser points at where it opens as a popover (iPad, macOS), by its
    /// element id: usually the share button itself. Without one, the chooser points at the
    /// window's top trailing corner.
    pub fn anchor(mut self, id: day_core::ElementId) -> Self {
        self.anchor = Some(id);
        self
    }

    /// Present the chooser. Call it from a user action (the web requires one). Returns whether
    /// the chooser opened; cancelling it is not an error, and nothing reports what was shared.
    pub fn present(self) -> bool {
        let actions = self
            .actions
            .into_iter()
            .map(|a| (a.label.resolve(), a.symbol, a.handler))
            .collect();
        day_core::present_share(
            &self.url,
            &self.title,
            actions,
            self.anchor.as_ref().map(|id| id.as_str()),
        )
    }
}

/// One of the app's actions in a share chooser (see [`Share::action`]).
pub struct ShareAction {
    label: TextSource,
    symbol: Option<day_spec::Symbol>,
    handler: Rc<dyn Fn()>,
}

/// Build a share-chooser action named `label` (a literal or a `res::str::…` text, resolved
/// when the chooser opens). Chain [`symbol`](ShareAction::symbol) for its glyph and
/// [`action`](ShareAction::action) for the work, which runs once the chooser has closed.
pub fn share_action<M>(label: impl IntoText<M>) -> ShareAction {
    ShareAction {
        label: label.into_text(),
        symbol: None,
        handler: Rc::new(|| {}),
    }
}

impl ShareAction {
    /// The action's glyph, where the chooser draws one.
    pub fn symbol(mut self, symbol: day_spec::Symbol) -> Self {
        self.symbol = Some(symbol);
        self
    }

    /// What choosing the action does.
    pub fn action(mut self, f: impl Fn() + 'static) -> Self {
        self.handler = Rc::new(f);
        self
    }
}

/// Whether this target can present a share chooser at all (docs/sharing.md).
pub fn share_support() -> day_spec::Support {
    day_core::share_support()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The role items every Edit menu carries take the standard accelerators when the app
    /// sets none, which is what gives GTK/Qt/web the shortcuts AppKit's native items always had.
    #[test]
    fn role_items_take_standard_shortcuts() {
        use day_spec::{MenuItem, MenuRole};
        let lowered = lower_menu(vec![
            menu_role(MenuRole::Undo),
            menu_role(MenuRole::Redo),
            menu_role(MenuRole::Cut),
            menu_role(MenuRole::Copy),
            menu_role(MenuRole::Paste),
            menu_role(MenuRole::SelectAll),
        ]);
        let expect = [
            ("z", false),
            ("z", true),
            ("x", false),
            ("c", false),
            ("v", false),
            ("a", false),
        ];
        for (item, (key, shift)) in lowered.iter().zip(expect) {
            let MenuItem::Action {
                shortcut, action, ..
            } = item
            else {
                panic!("role item lowered to a non-action");
            };
            let sc = shortcut.as_ref().expect("role item has a default shortcut");
            assert_eq!(sc.key, key);
            assert!(sc.primary);
            assert_eq!(sc.shift, shift);
            assert_ne!(*action, 0, "role item carries its standing dispatcher");
        }
    }
}