teksilo-widgets 0.9.0

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! The [`MenuModel`] data type and its builders.

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

use teksilo_core::signal::{Prop, Signal};
use teksilo_core::widget::EventContext;
use teksilo_core::{Intent, MenuItemId};
use teksilo_data::CheckState;
use teksilo_i18n::LocalizedString;
use teksilo_platform::native_menu::StandardMenuRole;

use crate::menu_item::MenuItem;
use crate::menu_list::MenuList;

/// Checkable / radio state for a menu item, mirroring the [`MenuItem`] modes.
#[derive(Clone)]
pub enum MenuItemState {
    /// A plain command, no check column.
    Plain,
    /// Two-state checkbox bound to a `Signal<bool>`; activation flips it.
    Check(Signal<bool>),
    /// Reflect-only checkmark mirroring a `Signal<bool>`; activation does NOT
    /// write it (the `intent`/`on_activate` owns the change). For commands that
    /// mirror externally-owned state — "View ▸ Sidebar / Full Screen".
    ReflectCheck(Signal<bool>),
    /// Tri-state checkbox bound to a `Signal<CheckState>`.
    TriCheck(Signal<CheckState>),
    /// Radio item: selected iff `selected == value`.
    Radio {
        /// This item's value within the group.
        value: usize,
        /// The shared selection signal.
        selected: Signal<usize>,
    },
}

/// One leaf command in the menu tree. Both the builder and the stored spec.
#[derive(Clone)]
pub struct MenuEntry {
    pub(crate) title: LocalizedString,
    pub(crate) intent: Option<&'static str>,
    pub(crate) action: Option<Rc<dyn Fn(&mut EventContext)>>,
    pub(crate) shortcut_id: Option<&'static str>,
    pub(crate) enabled: Prop<bool>,
    pub(crate) visible: Prop<bool>,
    pub(crate) state: MenuItemState,
    pub(crate) id: MenuItemId,
}

impl MenuEntry {
    /// Start a new leaf item with the given (possibly mnemonic-bearing,
    /// localized) title. Allocates a process-unique [`MenuItemId`].
    pub fn new(title: impl Into<LocalizedString>) -> Self {
        Self {
            title: title.into(),
            intent: None,
            action: None,
            shortcut_id: None,
            enabled: Prop::Static(true),
            visible: Prop::Static(true),
            state: MenuItemState::Plain,
            id: MenuItemId::next(),
        }
    }

    /// Fire this intent by name when the item is chosen (in-window or native).
    pub fn intent(mut self, name: &'static str) -> Self {
        self.intent = Some(name);
        self
    }

    /// Run this closure when the item is chosen. Runs after `intent`, if both
    /// are set. The escape hatch for behaviour that isn't a plain intent.
    pub fn on_activate(mut self, f: impl Fn(&mut EventContext) + 'static) -> Self {
        self.action = Some(Rc::new(f));
        self
    }

    /// Bind the displayed shortcut to a `ShortcutRegistry` entry by id. The
    /// in-window item shows the resolved chord; the native item gets a key
    /// equivalent (and the OS fires it directly).
    pub fn shortcut(mut self, id: &'static str) -> Self {
        self.shortcut_id = Some(id);
        self
    }

    /// Enabled state (static or signal-bound).
    pub fn enabled(mut self, enabled: impl Into<Prop<bool>>) -> Self {
        self.enabled = enabled.into();
        self
    }

    /// Visibility (static or signal-bound). A hidden item collapses to zero
    /// height in the in-window menu (reactively); on the native menu it is
    /// omitted from the snapshot at build time (toggling it settles on the next
    /// menu rebuild — for fully-dynamic native menus prefer
    /// [`MenuModel::remove`] / [`MenuModel::push_item`]).
    pub fn visible(mut self, visible: impl Into<Prop<bool>>) -> Self {
        self.visible = visible.into();
        self
    }

    /// Make this a two-state checkbox item bound to `state`. Activation flips
    /// `state` — use when the signal *is* the source of truth.
    pub fn checkable(mut self, state: Signal<bool>) -> Self {
        self.state = MenuItemState::Check(state);
        self
    }

    /// Show a checkmark that **reflects** `state` read-only. Activation does not
    /// write it — pair with [`intent`](Self::intent) / [`on_activate`](Self::on_activate)
    /// that drive the change; the checkmark then follows `state` reactively. Use
    /// when the truth is owned elsewhere (e.g. `DockingModel::dock_open_signal`),
    /// where two-way [`checkable`](Self::checkable) would fight the model.
    pub fn checked(mut self, state: Signal<bool>) -> Self {
        self.state = MenuItemState::ReflectCheck(state);
        self
    }

    /// Make this a tri-state checkbox item bound to `state`.
    pub fn tri_checkable(mut self, state: Signal<CheckState>) -> Self {
        self.state = MenuItemState::TriCheck(state);
        self
    }

    /// Make this a radio item: selected iff `selected.get() == value`.
    pub fn radio(mut self, value: usize, selected: Signal<usize>) -> Self {
        self.state = MenuItemState::Radio { value, selected };
        self
    }

    /// The stable id of this item.
    pub fn id(&self) -> MenuItemId {
        self.id
    }

    /// Build the live [`MenuItem`] widget for the in-window menu.
    pub(crate) fn to_menu_item(&self) -> MenuItem {
        // Pass the enabled `Prop` through (not its current value) so a bound
        // signal greys the in-window item out reactively.
        let mut mi = MenuItem::new(self.title.clone()).enabled(self.enabled.clone());
        if let Some(id) = self.shortcut_id {
            mi = mi.for_shortcut(id);
        }
        let intent = self.intent;
        let action = self.action.clone();
        mi = mi.on_activate_fn(move |ctx| {
            if let Some(name) = intent {
                ctx.send_intent(Intent::new(name));
            }
            if let Some(a) = &action {
                a(ctx);
            }
        });
        match &self.state {
            MenuItemState::Plain => {}
            MenuItemState::Check(s) => mi = mi.checked(s.clone()),
            MenuItemState::ReflectCheck(s) => mi = mi.reflect_checked(s.clone()),
            MenuItemState::TriCheck(s) => mi = mi.check_state(s.clone()),
            MenuItemState::Radio { value, selected } => mi = mi.radio(*value, selected.clone()),
        }
        mi
    }
}

/// One node of the menu tree.
#[derive(Clone)]
pub enum MenuNode {
    /// A leaf command.
    Item(MenuEntry),
    /// A submenu.
    Submenu {
        /// Stable id, so the submenu can be addressed by runtime mutators
        /// ([`MenuModel::push_item`], [`MenuModel::remove`]).
        id: MenuItemId,
        /// Submenu title.
        title: LocalizedString,
        /// Child nodes.
        children: Vec<MenuNode>,
    },
    /// A separator line.
    Separator,
    /// A platform-standard menu (macOS App / Window / Help) with localized
    /// chrome. Rendered by the native backend; ignored by the in-window bar.
    Standard(StandardMenu),
}

/// A platform-standard menu (macOS App / Window / Help) with **localized**
/// labels. The framework wires the system selectors (About / Hide / Quit,
/// Minimize / Zoom); you supply the strings — defaults are English `lit!`s, so
/// pass `tr!`-resolved [`LocalizedString`]s for a localized app menu. This keeps
/// the OS menu bar inside the i18n net like every other widget.
#[derive(Clone)]
pub struct StandardMenu {
    role: StandardMenuRole,
    title: LocalizedString,
    about: LocalizedString,
    settings: LocalizedString,
    hide: LocalizedString,
    quit: LocalizedString,
    minimize: LocalizedString,
    zoom: LocalizedString,
    /// Set by [`quit_intent`](Self::quit_intent): the intent to fire, paired
    /// with the id the native item is built under. Minted once here rather than
    /// per install, so the id an activation is recorded against survives every
    /// rebuild of the model.
    quit_route: Option<(&'static str, MenuItemId)>,
    /// Set by [`settings_intent`](Self::settings_intent), same shape as
    /// `quit_route`. `None` omits the item entirely — there is no platform
    /// default to fall back on.
    settings_route: Option<(&'static str, MenuItemId)>,
    /// Shortcut ids for the two routed rows, if the app named one. Unset, the
    /// row falls back to the platform's conventional chord — see
    /// [`quit_shortcut`](Self::quit_shortcut).
    quit_shortcut: Option<&'static str>,
    settings_shortcut: Option<&'static str>,
}

impl StandardMenu {
    /// The application menu (About / Hide / Quit). `title` is the bold app-name
    /// submenu label — set it to your localized app name.
    pub fn app() -> Self {
        Self {
            role: StandardMenuRole::App,
            title: LocalizedString::literal("App"),
            about: LocalizedString::literal("About"),
            settings: LocalizedString::literal("Settings…"),
            hide: LocalizedString::literal("Hide"),
            quit: LocalizedString::literal("Quit"),
            minimize: LocalizedString::literal(""),
            zoom: LocalizedString::literal(""),
            quit_route: None,
            settings_route: None,
            quit_shortcut: None,
            settings_shortcut: None,
        }
    }

    /// The Window menu (Minimize / Zoom + the live window list).
    pub fn window() -> Self {
        Self {
            role: StandardMenuRole::Window,
            title: LocalizedString::literal("Window"),
            about: LocalizedString::literal(""),
            settings: LocalizedString::literal(""),
            hide: LocalizedString::literal(""),
            quit: LocalizedString::literal(""),
            minimize: LocalizedString::literal("Minimize"),
            zoom: LocalizedString::literal("Zoom"),
            quit_route: None,
            settings_route: None,
            quit_shortcut: None,
            settings_shortcut: None,
        }
    }

    /// The Help menu.
    pub fn help() -> Self {
        Self {
            role: StandardMenuRole::Help,
            title: LocalizedString::literal("Help"),
            about: LocalizedString::literal(""),
            settings: LocalizedString::literal(""),
            hide: LocalizedString::literal(""),
            quit: LocalizedString::literal(""),
            minimize: LocalizedString::literal(""),
            zoom: LocalizedString::literal(""),
            quit_route: None,
            settings_route: None,
            quit_shortcut: None,
            settings_shortcut: None,
        }
    }

    /// Default standard menu for a role.
    pub fn for_role(role: StandardMenuRole) -> Self {
        match role {
            StandardMenuRole::App => Self::app(),
            StandardMenuRole::Window => Self::window(),
            StandardMenuRole::Help => Self::help(),
        }
    }

    /// This menu's role.
    pub fn role(&self) -> StandardMenuRole {
        self.role
    }

    /// Submenu title (the app name for `App`; the menu label for Window / Help).
    pub fn title(mut self, title: impl Into<LocalizedString>) -> Self {
        self.title = title.into();
        self
    }
    /// "About …" label (App).
    pub fn about(mut self, label: impl Into<LocalizedString>) -> Self {
        self.about = label.into();
        self
    }
    /// "Settings…" label (App). macOS 13+ says "Settings…"; older releases said
    /// "Preferences…" — pass whichever your app targets, localized.
    ///
    /// The label alone does not create the item: pair it with
    /// [`settings_intent`](Self::settings_intent).
    pub fn settings(mut self, label: impl Into<LocalizedString>) -> Self {
        self.settings = label.into();
        self
    }
    /// "Hide …" label (App).
    pub fn hide(mut self, label: impl Into<LocalizedString>) -> Self {
        self.hide = label.into();
        self
    }
    /// "Quit …" label (App).
    pub fn quit(mut self, label: impl Into<LocalizedString>) -> Self {
        self.quit = label.into();
        self
    }
    /// "Minimize" label (Window).
    pub fn minimize(mut self, label: impl Into<LocalizedString>) -> Self {
        self.minimize = label.into();
        self
    }
    /// "Zoom" label (Window).
    pub fn zoom(mut self, label: impl Into<LocalizedString>) -> Self {
        self.zoom = label.into();
        self
    }

    /// Route the App menu's **Quit** through `intent` instead of the platform's
    /// terminate selector, keeping its ⌘Q key equivalent.
    ///
    /// Set this whenever quitting has to pass through the app first — unsaved
    /// work to confirm, a session to write out, a background job to stop. By
    /// default the item is the platform's own (`terminate:` on macOS), which
    /// exits immediately: it never reaches winit's exit path, so no
    /// `LoopExiting` hook and nothing the app registered runs.
    ///
    /// An in-app ⌘Q shortcut is **not** a substitute. AppKit dispatches
    /// main-menu key equivalents before the responder chain, so the App menu's
    /// item wins and the app's own shortcut never sees the keystroke — the app
    /// looks wired up and is not. Routing the item is the only place that
    /// decision can be taken.
    ///
    /// Whatever `intent` resolves to now owns the exit — nothing terminates on
    /// the app's behalf once this is set.
    ///
    /// ```ignore
    /// StandardMenu::app()
    ///     .title(tr!(app_name()))
    ///     .quit(tr!(quit()))
    ///     .quit_intent("app.quit")   // the guarded action, same as File ▸ Quit
    /// ```
    pub fn quit_intent(mut self, intent: &'static str) -> Self {
        self.quit_route = Some((intent, MenuItemId::next()));
        self
    }

    /// The intent [`quit_intent`](Self::quit_intent) installed, or `None` if
    /// Quit is still the platform's own terminate selector.
    ///
    /// Public so an app can *test* that its Quit is guarded. Everything the
    /// routing does happens on macOS, where a downstream test suite generally
    /// does not run, so without a getter the difference between a guarded ⌘Q and
    /// an unguarded one is invisible from the app's side — which is the same
    /// blind spot that let the unrouted default ship in the first place.
    pub fn quit_intent_name(&self) -> Option<&'static str> {
        self.quit_route.map(|(intent, _)| intent)
    }

    /// The intent + item id [`quit_intent`](Self::quit_intent) installed, if any.
    pub(crate) fn quit_route(&self) -> Option<(&'static str, MenuItemId)> {
        self.quit_route
    }

    /// Put **Settings…** in the App menu, routed through `intent`, with the
    /// platform's own placement and key equivalent (⌘, on macOS).
    ///
    /// macOS keeps app settings in the application menu, not in File or Edit,
    /// and ⌘, is the only chord users try. Neither is reachable from a plain
    /// `MenuEntry`: the App menu is filled in by the platform, so an entry the
    /// model declares lands in some other menu instead.
    ///
    /// Unlike [`quit_intent`](Self::quit_intent) this is the *only* way to get
    /// the item at all — no platform opens an app's settings on its own, so
    /// leaving it unset omits the row rather than falling back to a system
    /// behaviour. Route it to the same intent your in-window "Settings" command
    /// fires, and the two stay one command.
    ///
    /// ```ignore
    /// StandardMenu::app()
    ///     .title(tr!(app_name()))
    ///     .settings(tr!(settings()))
    ///     .settings_intent("app.settings")
    /// ```
    pub fn settings_intent(mut self, intent: &'static str) -> Self {
        self.settings_route = Some((intent, MenuItemId::next()));
        self
    }

    /// The intent [`settings_intent`](Self::settings_intent) installed, or
    /// `None` if the App menu carries no Settings item.
    ///
    /// Public for the same reason as
    /// [`quit_intent_name`](Self::quit_intent_name): the wiring only takes
    /// effect on macOS, where an app's test suite generally does not run, so
    /// without a getter a missing route is invisible from the app's side.
    pub fn settings_intent_name(&self) -> Option<&'static str> {
        self.settings_route.map(|(intent, _)| intent)
    }

    /// The intent + item id [`settings_intent`](Self::settings_intent)
    /// installed, if any.
    /// Advertise the registered shortcut `id` on the routed **Quit** row,
    /// instead of the platform's conventional chord (⌘Q on macOS).
    ///
    /// Worth naming whenever the app registers a quit shortcut of its own —
    /// which is to say whenever [`quit_intent`](Self::quit_intent) is set, since
    /// the intent has to be reachable somehow. The chord then comes from the
    /// `ShortcutRegistry` like every other menu row's: it follows the
    /// primary-accelerator convention, and it follows a user's rebind. Left
    /// unset, this row is the one place in the app advertising a chord nothing
    /// registered — still live after the user moved the command elsewhere, and
    /// shadowing the chord they moved it to, because the platform dispatches a
    /// main-menu key equivalent before the responder chain.
    pub fn quit_shortcut(mut self, id: &'static str) -> Self {
        self.quit_shortcut = Some(id);
        self
    }

    /// Advertise the registered shortcut `id` on the routed **Settings…** row,
    /// instead of the platform's conventional chord (⌘, on macOS). Same
    /// reasoning as [`quit_shortcut`](Self::quit_shortcut).
    pub fn settings_shortcut(mut self, id: &'static str) -> Self {
        self.settings_shortcut = Some(id);
        self
    }

    /// The shortcut id named for the Quit row, if any.
    pub fn quit_shortcut_id(&self) -> Option<&'static str> {
        self.quit_shortcut
    }

    /// The shortcut id named for the Settings row, if any.
    pub fn settings_shortcut_id(&self) -> Option<&'static str> {
        self.settings_shortcut
    }

    pub(crate) fn settings_route(&self) -> Option<(&'static str, MenuItemId)> {
        self.settings_route
    }

    /// Resolve to the platform's localized-label struct (widget-layer i18n
    /// resolution happens here, so the platform never hardcodes English).
    pub(crate) fn resolve_labels(&self) -> teksilo_platform::native_menu::StandardLabels {
        teksilo_platform::native_menu::StandardLabels {
            title: self.title.resolve_now(),
            about: self.about.resolve_now(),
            settings: self.settings.resolve_now(),
            hide: self.hide.resolve_now(),
            quit: self.quit.resolve_now(),
            minimize: self.minimize.resolve_now(),
            zoom: self.zoom.resolve_now(),
        }
    }
}

/// Builder for the contents of one (sub)menu — a sequence of items, separators,
/// and nested submenus.
#[derive(Clone, Default)]
pub struct MenuItems {
    pub(crate) nodes: Vec<MenuNode>,
}

impl MenuItems {
    /// An empty contents builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Append a leaf command.
    pub fn item(mut self, entry: MenuEntry) -> Self {
        self.nodes.push(MenuNode::Item(entry));
        self
    }

    /// Append a separator.
    pub fn separator(mut self) -> Self {
        self.nodes.push(MenuNode::Separator);
        self
    }

    /// Append a nested submenu (auto-assigned id).
    pub fn submenu(
        self,
        title: impl Into<LocalizedString>,
        build: impl FnOnce(MenuItems) -> MenuItems,
    ) -> Self {
        self.submenu_with_id(MenuItemId::next(), title, build)
    }

    /// Append a nested submenu with a caller-supplied id, so it can be
    /// addressed later by [`MenuModel::push_item`] / [`MenuModel::remove`].
    pub fn submenu_with_id(
        mut self,
        id: MenuItemId,
        title: impl Into<LocalizedString>,
        build: impl FnOnce(MenuItems) -> MenuItems,
    ) -> Self {
        let children = build(MenuItems::new()).nodes;
        self.nodes.push(MenuNode::Submenu {
            id,
            title: title.into(),
            children,
        });
        self
    }
}

/// A declarative menu tree shared by the in-window [`MenuBar`](crate::menu_bar::MenuBar)
/// and the native OS menu bar. Cloneable by handle (`Rc` inside); a clone shares
/// the same nodes and `version` signal, so mutating one updates every view.
#[derive(Clone)]
pub struct MenuModel {
    nodes: Rc<RefCell<Vec<MenuNode>>>,
    version: Signal<u64>,
}

impl Default for MenuModel {
    fn default() -> Self {
        Self::new()
    }
}

impl MenuModel {
    /// An empty model.
    pub fn new() -> Self {
        Self {
            nodes: Rc::new(RefCell::new(Vec::new())),
            version: Signal::new(0),
        }
    }

    /// Append a top-level menu with the given title and contents (auto id).
    pub fn menu(
        self,
        title: impl Into<LocalizedString>,
        build: impl FnOnce(MenuItems) -> MenuItems,
    ) -> Self {
        self.menu_with_id(MenuItemId::next(), title, build)
    }

    /// Append a top-level menu with a caller-supplied id, so it can be addressed
    /// later by [`push_item`](Self::push_item) / [`remove`](Self::remove).
    pub fn menu_with_id(
        self,
        id: MenuItemId,
        title: impl Into<LocalizedString>,
        build: impl FnOnce(MenuItems) -> MenuItems,
    ) -> Self {
        let children = build(MenuItems::new()).nodes;
        self.nodes.borrow_mut().push(MenuNode::Submenu {
            id,
            title: title.into(),
            children,
        });
        self.bump();
        self
    }

    /// Append a platform-standard top-level menu (macOS App / Window / Help)
    /// with default (English) labels. Use [`standard_menu`](Self::standard_menu)
    /// to supply localized labels.
    pub fn standard(self, role: StandardMenuRole) -> Self {
        self.standard_menu(StandardMenu::for_role(role))
    }

    /// Append a platform-standard top-level menu with localized labels.
    pub fn standard_menu(self, menu: StandardMenu) -> Self {
        self.nodes.borrow_mut().push(MenuNode::Standard(menu));
        self.bump();
        self
    }

    /// A `Signal<u64>` bumped whenever the tree's *structure* changes. The
    /// native bridge re-installs the menu on a bump; per-item state changes go
    /// through the finer-grained `update_item` path instead.
    pub fn version(&self) -> Signal<u64> {
        self.version.clone()
    }

    /// Borrow the top-level nodes.
    pub fn nodes(&self) -> Ref<'_, Vec<MenuNode>> {
        self.nodes.borrow()
    }

    // ── Runtime structural mutation ────────────────────────────────────────
    //
    // These `&self` mutators change the menu *structure* at runtime and bump
    // `version`. A `MenuBar::from_model` bar binds `version` at `Rebuild` level,
    // so a bump re-derives the in-window dropdowns AND re-installs the native
    // menu. Per-item *state* (enabled / check / radio) does NOT need these —
    // bind a `Signal` to the `MenuEntry` instead (reactive without a rebuild).

    /// Mutate the node tree directly, then bump `version`. The escape hatch for
    /// any structural change the typed helpers don't cover (reorder, retitle,
    /// bulk edits). `MenuNode` / `MenuEntry` are public, so the closure can
    /// build whatever it needs.
    pub fn modify(&self, f: impl FnOnce(&mut Vec<MenuNode>)) {
        f(&mut self.nodes.borrow_mut());
        self.bump();
    }

    /// Append a top-level menu at runtime, returning its id. Mirrors
    /// [`menu`](Self::menu) but takes `&self`.
    pub fn push_menu(
        &self,
        title: impl Into<LocalizedString>,
        build: impl FnOnce(MenuItems) -> MenuItems,
    ) -> MenuItemId {
        let id = MenuItemId::next();
        let children = build(MenuItems::new()).nodes;
        self.nodes.borrow_mut().push(MenuNode::Submenu {
            id,
            title: title.into(),
            children,
        });
        self.bump();
        id
    }

    /// Append `entry` to the submenu identified by `into` (a top-level menu or
    /// nested submenu id). Returns `true` if the submenu was found.
    pub fn push_item(&self, into: MenuItemId, entry: MenuEntry) -> bool {
        let ok = {
            let mut nodes = self.nodes.borrow_mut();
            push_into_submenu(&mut nodes, into, MenuNode::Item(entry))
        };
        if ok {
            self.bump();
        }
        ok
    }

    /// Append a separator to the submenu identified by `into`. Returns `true`
    /// if the submenu was found.
    pub fn push_separator(&self, into: MenuItemId) -> bool {
        let ok = {
            let mut nodes = self.nodes.borrow_mut();
            push_into_submenu(&mut nodes, into, MenuNode::Separator)
        };
        if ok {
            self.bump();
        }
        ok
    }

    /// Insert a top-level menu at `index`, under a caller-supplied id.
    ///
    /// [`push_menu`](Self::push_menu) appends, which puts a menu after Help —
    /// fine for something added once at startup, wrong for a menu that comes and
    /// goes, since a writer looking for it needs it in the same place every
    /// time. The id is the caller's for the same reason: a menu that will be
    /// removed again has to be nameable before it exists.
    ///
    /// `index` is clamped, so a model that has since grown or shrunk cannot
    /// panic a caller holding a stale position.
    pub fn insert_menu_at(
        &self,
        index: usize,
        id: MenuItemId,
        title: impl Into<LocalizedString>,
        build: impl FnOnce(MenuItems) -> MenuItems,
    ) {
        let children = build(MenuItems::new()).nodes;
        {
            let mut nodes = self.nodes.borrow_mut();
            let at = index.min(nodes.len());
            nodes.insert(
                at,
                MenuNode::Submenu {
                    id,
                    title: title.into(),
                    children,
                },
            );
        }
        self.bump();
    }

    /// Whether a node with this id is anywhere in the tree.
    ///
    /// The companion to [`remove`](Self::remove) for callers that add and
    /// remove the same node as state changes: without it, "is it already
    /// there?" can only be answered by removing it and seeing what comes back,
    /// which bumps the version and re-installs the native menu for nothing.
    pub fn contains(&self, id: MenuItemId) -> bool {
        fn find(nodes: &[MenuNode], id: MenuItemId) -> bool {
            nodes.iter().any(|n| match n {
                MenuNode::Item(entry) => entry.id == id,
                MenuNode::Submenu {
                    id: sid, children, ..
                } => *sid == id || find(children, id),
                _ => false,
            })
        }
        find(&self.nodes.borrow(), id)
    }

    /// Remove the item or submenu with the given id, anywhere in the tree.
    /// Returns `true` if a node was removed.
    pub fn remove(&self, id: MenuItemId) -> bool {
        let removed = {
            let mut nodes = self.nodes.borrow_mut();
            remove_by_id(&mut nodes, id)
        };
        if removed {
            self.bump();
        }
        removed
    }

    fn bump(&self) {
        let v = self.version.get();
        self.version.set(v.wrapping_add(1));
    }
}

/// Append `node` to the children of the submenu with id `into` (searched
/// recursively). Returns whether the submenu was found.
fn push_into_submenu(nodes: &mut [MenuNode], into: MenuItemId, node: MenuNode) -> bool {
    // Two-phase to avoid moving `node` into a non-matching branch: first locate.
    fn find(nodes: &mut [MenuNode], into: MenuItemId) -> Option<&mut Vec<MenuNode>> {
        for n in nodes {
            if let MenuNode::Submenu { id, children, .. } = n {
                if *id == into {
                    return Some(children);
                }
                if let Some(found) = find(children, into) {
                    return Some(found);
                }
            }
        }
        None
    }
    match find(nodes, into) {
        Some(children) => {
            children.push(node);
            true
        }
        None => false,
    }
}

/// Remove the first node whose id matches (item or submenu), recursively.
fn remove_by_id(nodes: &mut Vec<MenuNode>, id: MenuItemId) -> bool {
    if let Some(pos) = nodes.iter().position(|n| match n {
        MenuNode::Item(e) => e.id == id,
        MenuNode::Submenu { id: sid, .. } => *sid == id,
        _ => false,
    }) {
        nodes.remove(pos);
        return true;
    }
    for n in nodes.iter_mut() {
        if let MenuNode::Submenu { children, .. } = n {
            if remove_by_id(children, id) {
                return true;
            }
        }
    }
    false
}

/// Build the in-window dropdown [`MenuList`] for a slice of nodes. Standard
/// roles are skipped (they only exist in the native bar).
pub(crate) fn build_menu_list(nodes: &[MenuNode]) -> MenuList {
    let mut list = MenuList::new();
    for node in nodes {
        match node {
            MenuNode::Item(entry) => {
                // `item_when` gates visibility reactively (Static(true) ⇒ always
                // shown, equivalent to `.item`).
                list = list.item_when(entry.to_menu_item(), entry.visible.clone());
            }
            MenuNode::Separator => {
                list = list.separator();
            }
            MenuNode::Submenu {
                title, children, ..
            } => {
                let children = children.clone();
                list = list.item(MenuItem::submenu(title.clone(), move || {
                    Box::new(build_menu_list(&children))
                }));
            }
            MenuNode::Standard(_) => {}
        }
    }
    list
}

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

    #[test]
    fn menu_appends_nodes_and_bumps_version() {
        let model = MenuModel::new();
        let v0 = model.version().get();
        let model = model
            .menu(lit!("File"), |m| {
                m.item(MenuEntry::new(lit!("New"))).separator()
            })
            .standard(StandardMenuRole::Window);
        assert!(
            model.version().get() > v0,
            "structural change bumps version"
        );
        let nodes = model.nodes();
        assert_eq!(nodes.len(), 2);
        assert!(matches!(nodes[0], MenuNode::Submenu { .. }));
        let MenuNode::Standard(sm) = &nodes[1] else {
            panic!("expected standard menu");
        };
        assert_eq!(sm.role(), StandardMenuRole::Window);
    }

    #[test]
    fn each_entry_gets_a_unique_id() {
        let a = MenuEntry::new(lit!("A"));
        let b = MenuEntry::new(lit!("B"));
        assert_ne!(a.id(), b.id());
    }

    #[test]
    fn push_item_into_submenu_by_id_and_remove() {
        let recent = teksilo_core::MenuItemId::next();
        let model = MenuModel::new().menu_with_id(recent, lit!("File"), |m| m);
        let v0 = model.version().get();

        // Add into the addressed submenu.
        let doc = MenuEntry::new(lit!("doc.txt"));
        let doc_id = doc.id();
        assert!(model.push_item(recent, doc));
        assert!(model.version().get() > v0, "push bumps version");

        // It landed inside the File submenu.
        {
            let nodes = model.nodes();
            let MenuNode::Submenu { children, .. } = &nodes[0] else {
                panic!("expected submenu");
            };
            assert_eq!(children.len(), 1);
        }

        // Push to a non-existent submenu is a no-op (returns false).
        assert!(!model.push_item(teksilo_core::MenuItemId::next(), MenuEntry::new(lit!("x"))));

        // Remove the item by id.
        assert!(model.remove(doc_id));
        {
            let nodes = model.nodes();
            let MenuNode::Submenu { children, .. } = &nodes[0] else {
                panic!("expected submenu");
            };
            assert!(children.is_empty());
        }
        assert!(!model.remove(doc_id), "second remove is a no-op");
    }

    #[test]
    fn push_menu_and_modify_at_runtime() {
        let model = MenuModel::new();
        let id = model.push_menu(lit!("Edit"), |m| m.item(MenuEntry::new(lit!("Cut"))));
        assert_eq!(model.nodes().len(), 1);

        // Escape hatch: append a top-level separator-bearing menu via modify.
        model.modify(|nodes| {
            nodes.push(MenuNode::Separator);
        });
        assert_eq!(model.nodes().len(), 2);

        // The pushed menu is addressable.
        assert!(model.remove(id));
        assert_eq!(model.nodes().len(), 1);
    }

    #[test]
    fn submenu_nesting_is_preserved() {
        let model = MenuModel::new().menu(lit!("File"), |m| {
            m.submenu(lit!("Recent"), |s| s.item(MenuEntry::new(lit!("doc.txt"))))
        });
        let nodes = model.nodes();
        let MenuNode::Submenu { children, .. } = &nodes[0] else {
            panic!("expected submenu");
        };
        assert!(matches!(children[0], MenuNode::Submenu { .. }));
    }
}