bezel-ui 0.2.22

SwiftUI-flavored components for gpui — popovers, menus, buttons, toggles, and loaders
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
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
//! [`Item`] — a row in a dropped menu — and [`card`], the panel that paints a
//! list of them plus the panels its [`Item::Submenu`] rows drop.
//!
//! Every menu in the system is those two over the caller's own open state: the
//! bar's dropped panel ([`crate::menubar`]), the `···` on a row, the picker
//! under a chip. The state stays with the caller because only it knows what
//! opening means — a [`crate::popover::Popup`] for one, a field for another.
//!
//! [`Cursor`] is the one piece of state the card asks for: which submenus are
//! down and which row is live. Pointer and keyboard both move it, so the two
//! can never disagree about which row an open submenu hangs off. What the
//! pointer did comes back as a [`Hit`]; acting on it stays the caller's.

use crate::{
    icons,
    input::{FieldEvent, TextField},
    keys, popover, scroll,
    tooltip::Tooltip,
};
use gpui::{
    Action, App, Axis, Context, Entity, Focusable as _, Global, KeyBinding, MouseDownEvent, Pixels,
    Point, ScrollHandle, SharedString, Size, Subscription, Window, actions, div, prelude::*, px,
};
use icons::Icon;
use std::{cell::Cell, rc::Rc};
use theme::{TextStyle, Theme, Typeset};

/// The leading glyph and the trailing check, at the size the rows are set in.
const GLYPH: f32 = 13.0;

/// A segment's glyph, over its label.
const SEGMENT_GLYPH: f32 = 16.0;

/// How many rows a searchable submenu shows before it scrolls.
const SEARCH_ROWS: f32 = 10.0;

actions!(
    bezel_menu,
    [
        SelectNext,
        SelectPrevious,
        SelectChild,
        SelectParent,
        Confirm,
        Dismiss
    ]
);

/// How far each [`Item::indented`] level moves a row's content in, app-wide.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MenuIndent(pub Pixels);

impl Default for MenuIndent {
    fn default() -> Self {
        Self(px(12.0))
    }
}

impl Global for MenuIndent {}

pub(crate) fn indent(cx: &App) -> MenuIndent {
    cx.try_global::<MenuIndent>().copied().unwrap_or_default()
}

/// Changes the step and repaints open windows.
pub(crate) fn set_indent(indent: MenuIndent, cx: &mut App) {
    cx.set_global(indent);
    cx.refresh_windows();
}

/// How wide a menu's panels sit, app-wide.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MenuWidth {
    /// The narrowest a panel sits. A panel without a described row grows past
    /// it to its widest row.
    pub min: Pixels,
    /// How a panel holding an [`Item::with_description`] row is sized.
    pub described: Described,
}

/// How a panel holding a described row is sized. A description is one line,
/// cut at the panel's edge.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Described {
    /// Exactly this wide, whatever its rows measure.
    Fixed(Pixels),
    /// As wide as its widest row, from [`MenuWidth::min`] up to this.
    Fit(Pixels),
}

impl Default for MenuWidth {
    fn default() -> Self {
        Self {
            min: px(180.0),
            described: Described::Fixed(px(280.0)),
        }
    }
}

impl Global for MenuWidth {}

pub(crate) fn width(cx: &App) -> MenuWidth {
    cx.try_global::<MenuWidth>().copied().unwrap_or_default()
}

/// Changes the widths and repaints open windows.
pub(crate) fn set_width(width: MenuWidth, cx: &mut App) {
    cx.set_global(width);
    cx.refresh_windows();
}

/// The key context around a searchable submenu's query field. Typing goes to
/// the field; the arrows, enter and escape fall through to the menu.
pub const SEARCH_CONTEXT: &str = "MenuSearch";

/// The keymap a searchable submenu and a [`crate::context_menu`] answer to,
/// as data — see [`crate::keys`].
pub fn bindings() -> Vec<KeyBinding> {
    let ctx = Some(SEARCH_CONTEXT);
    let context = Some(crate::context_menu::KEY_CONTEXT);
    vec![
        KeyBinding::new("down", SelectNext, ctx),
        KeyBinding::new("up", SelectPrevious, ctx),
        KeyBinding::new("ctrl-n", SelectNext, ctx),
        KeyBinding::new("ctrl-p", SelectPrevious, ctx),
        KeyBinding::new("enter", Confirm, ctx),
        KeyBinding::new("escape", Dismiss, ctx),
        KeyBinding::new("down", SelectNext, context),
        KeyBinding::new("up", SelectPrevious, context),
        KeyBinding::new("right", SelectChild, context),
        KeyBinding::new("left", SelectParent, context),
        KeyBinding::new("enter", Confirm, context),
        KeyBinding::new("escape", Dismiss, context),
    ]
}

/// Install [`bindings`]. Call once at startup.
pub fn init(cx: &mut App) {
    cx.bind_keys(bindings());
}

/// A row in a menu.
///
/// Deliberately not a struct with an `is_separator` flag: a separator has no
/// label, no accelerator and nothing to enable, and every one of those fields
/// would have to be answered anyway.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Item {
    Action {
        label: SharedString,
        /// A second line under the label, for a row whose name does not say
        /// enough on its own — what a command will do, which file it will act
        /// on. `None` keeps the row one line tall; nothing reserves space for
        /// a description the way the glyph gutter reserves space for an icon,
        /// because a row's two lines read as one block and a blank second line
        /// would read as a gap.
        description: Option<SharedString>,
        /// Hover text for the row, shown after gpui's tooltip delay. Where the
        /// whole of a [`Item::with_description`] too long for its one line
        /// goes, and where a disabled row says why — a disabled row takes no
        /// click, but it still takes a tooltip.
        tooltip: Option<SharedString>,
        /// The leading glyph. A menu where no row has one keeps no room
        /// for it.
        icon: Option<Icon>,
        /// Levels of [`Item::indented`]; 0 sits flush.
        indent: usize,
        /// The accelerator to *print* — the binding itself is the app's, and
        /// bezel never dispatches it. A menu that showed a keystroke it did not
        /// own would be documenting a lie, which is what
        /// [`Item::with_shortcut`] fills this from the keymap to avoid.
        keystroke: Option<SharedString>,
        /// The choice the menu is currently on, marked with a trailing check.
        checked: bool,
        enabled: bool,
    },
    /// A row that drops a menu of its own, the way a SwiftUI `Menu` nests
    /// inside a `Menu`. It carries no accelerator and nothing to check: the
    /// only thing choosing it does is open.
    Submenu {
        label: SharedString,
        icon: Option<Icon>,
        indent: usize,
        enabled: bool,
        items: Vec<Item>,
        /// The placeholder of the query field the panel opens with, focused.
        /// Typing narrows its rows by label and description; the panel shows
        /// [`SEARCH_ROWS`] rows and scrolls past them. `None` opens a plain
        /// panel.
        search: Option<SharedString>,
    },
    /// Options side by side in one row, each a glyph over its label, the
    /// `selected` one highlighted. A pick is a [`Hit::Choose`] whose path is
    /// the row's, then the segment's index.
    Segmented {
        segments: Vec<Segment>,
        selected: usize,
        enabled: bool,
    },
    /// A section's name over the rows after it. Never lit, never chosen.
    Heading(SharedString),
    /// A line of plain text about what the menu is on. Never lit, never
    /// chosen.
    Note(SharedString),
    Separator,
}

/// One option of an [`Item::Segmented`] row.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Segment {
    pub icon: Icon,
    pub label: SharedString,
}

impl Segment {
    pub fn new(icon: impl Into<Icon>, label: impl Into<SharedString>) -> Self {
        Self {
            icon: icon.into(),
            label: label.into(),
        }
    }
}

impl Item {
    pub fn action(label: impl Into<SharedString>) -> Self {
        Item::Action {
            label: label.into(),
            description: None,
            tooltip: None,
            icon: None,
            indent: 0,
            keystroke: None,
            checked: false,
            enabled: true,
        }
    }

    pub fn submenu(label: impl Into<SharedString>, items: Vec<Item>) -> Self {
        Item::Submenu {
            label: label.into(),
            icon: None,
            indent: 0,
            enabled: true,
            items,
            search: None,
        }
    }

    /// Open the submenu with a query field — see [`Item::Submenu::search`].
    /// No-ops on anything but a submenu row.
    pub fn searchable(mut self, placeholder: impl Into<SharedString>) -> Self {
        if let Item::Submenu { search, .. } = &mut self {
            *search = Some(placeholder.into());
        }
        self
    }

    pub fn segmented(segments: impl IntoIterator<Item = Segment>, selected: usize) -> Self {
        Item::Segmented {
            segments: segments.into_iter().collect(),
            selected,
            enabled: true,
        }
    }

    /// No-ops on a separator and a heading, which have nothing to hang a glyph
    /// on, and on a segmented row, whose glyphs are its segments'.
    pub fn with_icon(mut self, icon: impl Into<Icon>) -> Self {
        match &mut self {
            Item::Action { icon: slot, .. } | Item::Submenu { icon: slot, .. } => {
                *slot = Some(icon.into())
            }
            Item::Segmented { .. } | Item::Heading(_) | Item::Note(_) | Item::Separator => {}
        }
        self
    }

    /// Moves the row's content in by `level` steps of the app's
    /// [`MenuIndent`], so a flat list of rows can show a hierarchy. No-ops on
    /// a separator, a heading and a segmented row.
    pub fn indented(mut self, level: usize) -> Self {
        match &mut self {
            Item::Action { indent, .. } | Item::Submenu { indent, .. } => *indent = level,
            Item::Segmented { .. } | Item::Heading(_) | Item::Note(_) | Item::Separator => {}
        }
        self
    }

    /// A second line under the label. No-ops on anything but an action row: a
    /// submenu's second line is the panel it opens, and a separator has no
    /// first line to put one under.
    pub fn with_description(mut self, description: impl Into<SharedString>) -> Self {
        if let Item::Action {
            description: slot, ..
        } = &mut self
        {
            *slot = Some(description.into());
        }
        self
    }

    /// The description *and* the whole of it on hover, from one string. A
    /// sentence long enough to need clipping is one no caller should have to
    /// write twice — two copies of it drift.
    pub fn with_long_description(self, description: impl Into<SharedString>) -> Self {
        let description = description.into();
        self.with_description(description.clone())
            .with_tooltip(description)
    }

    /// Hover text for the row — the rest of a description the row had to clip,
    /// or why a disabled row is disabled. No-ops on anything but an action
    /// row: a submenu row is already hovered to open it, and a label the
    /// pointer waits on top of would fight the panel it drops.
    pub fn with_tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
        if let Item::Action { tooltip: slot, .. } = &mut self {
            *slot = Some(tooltip.into());
        }
        self
    }

    /// No-ops on anything but an action row: a submenu's keystroke is the
    /// arrow that opens it, and a separator has nothing to hang one on.
    pub fn with_keystroke(mut self, keystroke: impl Into<SharedString>) -> Self {
        if let Item::Action {
            keystroke: slot, ..
        } = &mut self
        {
            *slot = Some(keystroke.into());
        }
        self
    }

    /// The accelerator read off the keymap instead of typed in — the same slot
    /// [`Item::with_keystroke`] fills, filled with what would actually fire.
    /// An action with nothing bound to it leaves the row bare, because a menu
    /// that prints a chord it no longer owns is documenting a lie.
    ///
    /// Still nothing to dispatch: the row's click stays the caller's, and the
    /// action passed here is read, never run.
    pub fn with_shortcut(self, action: &dyn Action, window: &Window) -> Self {
        match keys::shortcut(action, window) {
            Some(keystroke) => self.with_keystroke(keystroke),
            None => self,
        }
    }

    /// [`Item::with_shortcut`] for a chord bound to a surface that is not
    /// focused — which is most menu rows, since opening the menu took focus
    /// off whatever the row acts on. `context` is the one the binding was
    /// scoped to (`editor::CONTEXT`, [`crate::input::KEY_CONTEXT`]).
    pub fn with_shortcut_in(self, action: &dyn Action, context: &str, window: &Window) -> Self {
        match keys::shortcut_in(action, context, window) {
            Some(keystroke) => self.with_keystroke(keystroke),
            None => self,
        }
    }

    /// Takes the flag, because what a menu is on is decided per render. No-ops
    /// on a submenu, which is not itself a choice.
    pub fn checked(mut self, checked: bool) -> Self {
        if let Item::Action { checked: slot, .. } = &mut self {
            *slot = checked;
        }
        self
    }

    pub fn disabled(mut self) -> Self {
        match &mut self {
            Item::Action { enabled, .. }
            | Item::Submenu { enabled, .. }
            | Item::Segmented { enabled, .. } => *enabled = false,
            Item::Heading(_) | Item::Note(_) | Item::Separator => {}
        }
        self
    }

    /// Whether the keyboard and the pointer can land here at all. A submenu
    /// with nothing to choose in it counts as unlandable: opening it would drop
    /// a panel that is a dead end.
    pub fn selectable(&self) -> bool {
        match self {
            Item::Action { enabled, .. } => *enabled,
            Item::Submenu { enabled, items, .. } => *enabled && items.iter().any(Item::selectable),
            Item::Segmented {
                enabled, segments, ..
            } => *enabled && !segments.is_empty(),
            Item::Heading(_) | Item::Note(_) | Item::Separator => false,
        }
    }

    fn has_description(&self) -> bool {
        matches!(
            self,
            Item::Action {
                description: Some(_),
                ..
            }
        )
    }

    fn has_icon(&self) -> bool {
        matches!(
            self,
            Item::Action { icon: Some(_), .. } | Item::Submenu { icon: Some(_), .. }
        )
    }

    /// The segment a cursor landing on this row starts on: the selected one.
    fn landing(&self) -> Option<usize> {
        match self {
            Item::Segmented {
                segments, selected, ..
            } if !segments.is_empty() => Some((*selected).min(segments.len() - 1)),
            _ => None,
        }
    }

    /// What a query is matched against: the label, then the description.
    fn keywords(&self) -> String {
        match self {
            Item::Action {
                label, description, ..
            } => match description {
                Some(description) => format!("{label} {description}"),
                None => label.to_string(),
            },
            Item::Submenu { label, .. } => label.to_string(),
            Item::Segmented { .. } | Item::Heading(_) | Item::Note(_) | Item::Separator => {
                String::new()
            }
        }
    }

    /// The placeholder of the query field this row's submenu opens with.
    fn search(&self) -> Option<&SharedString> {
        match self {
            Item::Submenu { search, .. } => search.as_ref(),
            _ => None,
        }
    }

    /// The submenu this row opens, if it is one that can be opened.
    fn opens(&self) -> Option<&[Item]> {
        match self {
            Item::Submenu {
                enabled: true,
                items,
                ..
            } => Some(items),
            _ => None,
        }
    }
}

/// The item `path` names — one row index per level, outermost first. `None`
/// for a path to a segment of an [`Item::Segmented`] row; its path less the
/// last index names the row.
pub fn at<'a>(items: &'a [Item], path: &[usize]) -> Option<&'a Item> {
    let (&row, above) = path.split_last()?;
    items_at(items, above)?.get(row)
}

/// The menu `path` opens into: `items` itself for an empty path, else the rows
/// of the submenu each index names. `None` as soon as one of them does not name
/// an open-able submenu.
pub fn items_at<'a>(items: &'a [Item], path: &[usize]) -> Option<&'a [Item]> {
    let mut level = items;
    for &row in path {
        level = level.get(row)?.opens()?;
    }
    Some(level)
}

/// How many levels of `open` still name an open-able submenu — where both the
/// painting and the out-click count stop when the chain has gone stale.
fn open_depth(items: &[Item], open: &[usize]) -> usize {
    let mut level = items;
    for (depth, &row) in open.iter().enumerate() {
        match level.get(row).and_then(Item::opens) {
            Some(inner) => level = inner,
            None => return depth,
        }
    }
    open.len()
}

/// The next row the keyboard can land on, `delta` deciding the direction:
/// separators and disabled rows are stepped straight over, and both ends wrap.
/// `from` of `None` enters the menu at the edge the direction comes from.
///
/// [`popover::menu_step`] cannot do this — it counts rows and knows nothing
/// about which of them can be landed on. `None` back means *nothing* in the menu
/// is selectable, which is the one shape that would otherwise spin forever.
pub fn next_selectable(items: &[Item], from: Option<usize>, delta: isize) -> Option<usize> {
    let count = items.len();
    if count == 0 {
        return None;
    }
    let step = if delta >= 0 { 1 } else { -1 };
    let wrap = |at: usize| (at as isize + step).rem_euclid(count as isize) as usize;
    // Entering, the first candidate is the edge itself; moving, it is the row
    // after the one you are on.
    let mut at = match from {
        None if step > 0 => 0,
        None => count - 1,
        Some(at) => wrap(at.min(count - 1)),
    };
    for _ in 0..count {
        if items[at].selectable() {
            return Some(at);
        }
        at = wrap(at);
    }
    None
}

// ---------------------------------------------------------------------------
// Cursor
// ---------------------------------------------------------------------------

/// Where an open menu is being worked: `open` is the chain of submenu rows
/// currently down, outermost first, `row` is the live row in the menu that
/// chain ends at, and `segment` the live segment when that row is an
/// [`Item::Segmented`].
///
/// One cursor for both input devices. A menu that tracked hover separately from
/// the keyboard could have two rows lit and a submenu hanging off neither.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Cursor {
    open: Vec<usize>,
    row: Option<usize>,
    segment: Option<usize>,
}

impl Cursor {
    /// The submenu rows currently down, outermost first.
    pub fn open(&self) -> &[usize] {
        &self.open
    }

    /// The live row in the innermost open menu.
    pub fn row(&self) -> Option<usize> {
        self.row
    }

    /// The live segment, while the live row is an [`Item::Segmented`].
    pub fn segment(&self) -> Option<usize> {
        self.segment
    }

    /// Whether a submenu is down — where a menubar's `left` closes a level
    /// instead of crossing to the previous menu.
    pub fn nested(&self) -> bool {
        !self.open.is_empty()
    }

    /// The full path to the live row, outermost first, and on to the live
    /// segment of a segmented row.
    pub fn path(&self) -> Option<Vec<usize>> {
        let row = self.row?;
        let mut path = self.open.clone();
        path.push(row);
        path.extend(self.segment);
        Some(path)
    }

    /// Nothing down, nothing live — a menu opens here, and closes back to it.
    pub fn clear(&mut self) {
        self.open.clear();
        self.row = None;
        self.segment = None;
    }

    /// The row lit in the panel at `depth`: the row holding the submenu open
    /// above the innermost panel, the live row in it, nothing below.
    pub fn lit(&self, depth: usize) -> Option<usize> {
        match depth.cmp(&self.open.len()) {
            std::cmp::Ordering::Less => Some(self.open[depth]),
            std::cmp::Ordering::Equal => self.row,
            std::cmp::Ordering::Greater => None,
        }
    }

    /// Move within the innermost open panel.
    pub fn step(&mut self, root: &[Item], delta: isize) {
        let Some(items) = items_at(root, &self.open) else {
            return;
        };
        self.row = next_selectable(items, self.row, delta);
        self.segment = self.row.and_then(|row| items[row].landing());
    }

    /// Move across the segments of the live row, stopping at either end.
    /// `false` when the live row is not an [`Item::Segmented`].
    pub fn slide(&mut self, root: &[Item], delta: isize) -> bool {
        let Some(Item::Segmented { segments, .. }) = self
            .row
            .and_then(|row| items_at(root, &self.open)?.get(row))
        else {
            return false;
        };
        let at = self.segment.unwrap_or(0) as isize + delta.signum();
        self.segment = Some(at.clamp(0, segments.len() as isize - 1) as usize);
        true
    }

    /// Open the submenu under the live row and land on its first row. `false`
    /// when the live row is not one — which is a menubar's cue that `right`
    /// meant the next menu instead.
    pub fn descend(&mut self, root: &[Item]) -> bool {
        let Some(row) = self.row else { return false };
        let Some(inner) = items_at(root, &self.open)
            .and_then(|items| items.get(row))
            .and_then(Item::opens)
        else {
            return false;
        };
        self.row = next_selectable(inner, None, 1);
        self.segment = self.row.and_then(|row| inner[row].landing());
        self.open.push(row);
        true
    }

    /// Close the innermost submenu, landing back on the row that opened it.
    /// `false` at the top level, where closing is the whole menu's to do.
    pub fn ascend(&mut self) -> bool {
        match self.open.pop() {
            Some(row) => {
                self.row = Some(row);
                self.segment = None;
                true
            }
            None => false,
        }
    }

    /// Put the cursor on the row `path` names, opening the chain above it and,
    /// if it is a submenu row, itself — pointing at a submenu row is what opens
    /// it. Nothing is lit inside the fresh panel until something moves into it.
    /// A path to a segment puts the cursor on that segment of its row.
    ///
    /// Answers whether that changed anything, because the pointer reports every
    /// move and only a change is worth a repaint.
    pub fn point_at(&mut self, root: &[Item], path: &[usize]) -> bool {
        let (open, row, segment) = match path {
            [] => (Vec::new(), None, None),
            [above @ .., row, segment]
                if matches!(
                    at(root, &path[..path.len() - 1]),
                    Some(Item::Segmented { .. })
                ) =>
            {
                (above.to_vec(), Some(*row), Some(*segment))
            }
            _ if at(root, path).and_then(Item::opens).is_some() => (path.to_vec(), None, None),
            [above @ .., row] => (
                above.to_vec(),
                Some(*row),
                at(root, path).and_then(Item::landing),
            ),
        };
        if self.open == open && self.row == row && self.segment == segment {
            return false;
        }
        self.open = open;
        self.row = row;
        self.segment = segment;
        true
    }
}

// ---------------------------------------------------------------------------
// The panels
// ---------------------------------------------------------------------------

/// What the pointer did to a menu. Every variant is a request: the caller's
/// [`Cursor`] and open state are what answer it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Hit {
    /// The pointer is on this row, or a submenu row was clicked. Feed it to
    /// [`Cursor::point_at`], which is also what opens a submenu.
    Point(Vec<usize>),
    /// An action row was chosen.
    Choose(Vec<usize>),
    /// A press outside every panel of the open tree. Reported here rather than
    /// left to an `.on_mouse_down_out` on the card, which sees only its own
    /// bounds and would read a click in a submenu as a click away.
    Dismiss,
}

/// A row of a text surface's right-click menu, in the order [`edit_items`]
/// lists them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Edit {
    Cut,
    Copy,
    Paste,
    SelectAll,
}

impl Edit {
    /// The row a [`Hit::Choose`] path names in [`edit_items`].
    pub fn at(path: &[usize]) -> Option<Self> {
        match path {
            [0] => Some(Edit::Cut),
            [1] => Some(Edit::Copy),
            [2] => Some(Edit::Paste),
            [4] => Some(Edit::SelectAll),
            _ => None,
        }
    }
}

/// The rows of a text surface's right-click menu. `actions` are the surface's
/// own Cut, Copy, Paste and Select All, read for the chord each row prints.
pub fn edit_items(
    selected: bool,
    pasteable: bool,
    actions: [&dyn Action; 4],
    window: &Window,
) -> Vec<Item> {
    let [cut, copy, paste, select_all] = actions;
    let enable = |item: Item, on: bool| if on { item } else { item.disabled() };
    vec![
        enable(Item::action("Cut").with_shortcut(cut, window), selected),
        enable(Item::action("Copy").with_shortcut(copy, window), selected),
        enable(
            Item::action("Paste").with_shortcut(paste, window),
            pasteable,
        ),
        Item::Separator,
        Item::action("Select All").with_shortcut(select_all, window),
    ]
}

/// The panel a menu drops: every [`Item`] as a row, in a
/// [`popover::popover_card`], with a further panel hanging off each submenu row
/// the [`Cursor`] holds open. `id` prefixes the rows' element ids, so two menus
/// open at once keep their hover state apart. In a test build each action and
/// submenu row answers to the debug selector `{id}/{label}`.
///
/// The root panel is returned unanchored: mount it through one of
/// [`popover`]'s anchored layers ([`popover::anchored_menu_below`],
/// [`popover::menu_at`], …). Childed bare, it paints in flow, under every
/// later sibling. Submenu panels are anchored here.
///
/// Every panel is capped at the window's height less the snap margin either
/// side, and scrolls its rows past that. A submenu hangs off its row wherever
/// the row has scrolled to, outside the parent's clip.
///
/// The pointer moves the cursor rather than lighting a row of its own, so a
/// submenu can only ever hang off the row that is live. Everything the pointer
/// does arrives as a [`Hit`], dismissal included.
///
/// `closing` is the popup's, the same instant its anchored layer is given:
/// every open submenu panel plays its exit with the root card.
#[allow(clippy::too_many_arguments)]
pub fn card<V: 'static>(
    theme: &Theme,
    id: impl Into<SharedString>,
    items: &[Item],
    cursor: &Cursor,
    closing: Option<web_time::Instant>,
    window: &mut Window,
    cx: &mut Context<V>,
    on: impl Fn(&mut V, Hit, &mut Window, &mut Context<V>) + 'static,
) -> gpui::Div {
    let tree = Tree {
        id: id.into(),
        closing,
        panels: 1 + open_depth(items, cursor.open()),
        outside: Rc::new(Cell::new((None, 0))),
        chain: popover::Chain::default(),
        on: Rc::new(on),
    };
    tree.panel(theme, items, cursor, &[], None, window, cx)
}

/// A searchable panel's query: its field, and whether it has been focused
/// yet. Held in the panel's element state, so it lives while the panel is
/// down and a panel opened again starts empty.
struct Query {
    field: Entity<TextField>,
    focused: bool,
    _changed: Subscription,
}

/// A gpui mouse listener, boxed: `Context::listener` borrows the context it is
/// made from, and these are handed back out of a method that must not.
type Listener<E> = Box<dyn Fn(&E, &mut Window, &mut gpui::App)>;

/// The caller's [`Hit`] handler, shared by every panel of one open tree.
type Reporter<V> = Rc<dyn Fn(&mut V, Hit, &mut Window, &mut Context<V>)>;

/// The parts every panel of one open tree shares.
struct Tree<V: 'static> {
    id: SharedString,
    /// How many panels will paint — the divisor of the out-click count below.
    panels: usize,
    /// The press each panel has already reported as outside itself, stamped
    /// with where it landed. A press outside *all* of them is the one that
    /// dismisses, and no panel alone can tell.
    outside: Rc<Cell<(Option<Point<Pixels>>, usize)>>,
    /// Which way the open panels are stepping across the window.
    chain: popover::Chain,
    /// When the popup began to close, while it is closing.
    closing: Option<web_time::Instant>,
    on: Reporter<V>,
}

impl<V: 'static> Tree<V> {
    #[allow(clippy::too_many_arguments)]
    fn panel(
        &self,
        theme: &Theme,
        items: &[Item],
        cursor: &Cursor,
        prefix: &[usize],
        search: Option<&SharedString>,
        window: &mut Window,
        cx: &mut Context<V>,
    ) -> gpui::Div {
        let depth = prefix.len();
        let lit = cursor.lit(depth);
        let down = cursor.open().get(depth).copied();
        let rows_id = SharedString::from(format!("{}-rows", row_id(&self.id, prefix)));
        let Scrolled(handle, shown) = window
            .use_keyed_state(
                SharedString::from(format!("{rows_id}-scrolled")),
                cx,
                |_, _| Scrolled::default(),
            )
            .read(cx)
            .clone();
        let query = search.map(|placeholder| self.query(&rows_id, placeholder, window, cx));
        let text = query
            .as_ref()
            .map(|query| query.read(cx).field.read(cx).content().trim().to_owned())
            .unwrap_or_default();
        // The rows on show, by index into `items`, in the order they paint. A
        // query ranks them and drops what it does not match.
        let visible: Vec<usize> = if text.is_empty() {
            (0..items.len()).collect()
        } else {
            let words: Vec<String> = items.iter().map(Item::keywords).collect();
            popover::filter_indices(&text, &words)
                .into_iter()
                .filter(|&row| items[row].selectable())
                .collect()
        };
        // Only a change of live row or of the viewport's size scrolls: a wheel
        // that carried the live row out of view is left where it put it. gpui
        // drops a request made before the rows have been laid out, and measures
        // one against the viewport of the frame before.
        let size = handle.bounds().size;
        if size.height > Pixels::ZERO && shown.get() != Some((lit, size)) {
            shown.set(Some((lit, size)));
            if let Some(at) = lit.and_then(|lit| visible.iter().position(|&row| row == lit)) {
                handle.scroll_to_item(at);
            }
        }
        let inset = px(popover::SNAP) + window.client_inset().unwrap_or(Pixels::ZERO);
        let cap = window.viewport_size().height - inset * 2.0;
        // A menu where nothing carries a glyph keeps no room for one — a bar's
        // menus would otherwise open with an empty column down their left.
        let gutter = items.iter().any(Item::has_icon);
        let MenuIndent(step) = indent(cx);
        let described = items.iter().any(Item::has_description);
        let width = width(cx);
        let rows = div()
            .id(rows_id.clone())
            .p(px(popover::MENU_PAD))
            .children(visible.iter().map(|&row| {
                let item = &items[row];
                match item {
                    Item::Separator => return popover::divider(theme).into_any_element(),
                    Item::Heading(label) => {
                        return popover::menu_heading(theme, label.clone()).into_any_element();
                    }
                    Item::Note(text) => {
                        return popover::menu_note(theme, text.clone()).into_any_element();
                    }
                    _ => {}
                }
                let path: Vec<usize> = prefix.iter().copied().chain([row]).collect();
                if let Item::Segmented {
                    segments,
                    selected,
                    enabled,
                } = item
                {
                    let live = cursor.segment().filter(|_| lit == Some(row));
                    return self
                        .segmented(theme, segments, *selected, *enabled, live, &path, cx)
                        .into_any_element();
                }
                let id = row_id(&self.id, &path);
                let (label, icon, indent, enabled) = match item {
                    Item::Action {
                        label,
                        icon,
                        indent,
                        enabled,
                        ..
                    }
                    | Item::Submenu {
                        label,
                        icon,
                        indent,
                        enabled,
                        ..
                    } => (label.clone(), icon.clone(), *indent, *enabled),
                    Item::Segmented { .. } | Item::Heading(_) | Item::Note(_) | Item::Separator => {
                        unreachable!("returned above")
                    }
                };
                let (description, hint) = match item {
                    Item::Action {
                        description,
                        tooltip,
                        ..
                    } => (description.clone(), tooltip.clone()),
                    _ => (None, None),
                };
                let row = if enabled {
                    popover::menu_row(theme, lit == Some(row), None)
                        .id(id.clone())
                        .on_mouse_move(self.reports(Hit::Point(path.clone()), cx))
                        .on_click(self.reports(
                            match item {
                                // Clicking a submenu row opens it; there is
                                // nothing else it could mean.
                                Item::Submenu { .. } => Hit::Point(path.clone()),
                                _ => Hit::Choose(path.clone()),
                            },
                            cx,
                        ))
                } else {
                    disabled_row(theme).id(id.clone())
                };
                let selector = format!("{}/{label}", self.id);
                let row = row.debug_selector(move || selector);
                let row = row.when_some(hint, |row, hint| {
                    row.tooltip(move |window, cx| Tooltip::text(hint.clone(), window, cx))
                });
                row.when(indent > 0, |row| {
                    row.pl(px(popover::MENU_ROW_INSET) + step * indent as f32)
                })
                .when(gutter, |row| row.child(glyph_slot(theme, icon, enabled)))
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .flex()
                        .flex_col()
                        .child(div().truncate().child(label))
                        .children(
                            description
                                .map(|description| description_line(theme, description, enabled)),
                        ),
                )
                .map(|row| match item {
                    Item::Action {
                        keystroke, checked, ..
                    } => row
                        .when(*checked, |row| {
                            row.child(
                                icons::icon(icons::glyph::Check)
                                    .size(px(GLYPH))
                                    .text_color(theme.text),
                            )
                        })
                        .when_some(keystroke.clone(), |row, keystroke| {
                            row.child(popover::kbd_hint(theme, &keystroke))
                        }),
                    _ => row.child(
                        icons::icon(icons::glyph::ChevronRight)
                            .size(px(GLYPH))
                            .text_color(theme.text_faint),
                    ),
                })
                .when_some(
                    item.opens().filter(|_| down == Some(path[depth])),
                    |parent, inner| {
                        let panel = self
                            .panel(theme, inner, cursor, &path, item.search(), window, cx)
                            .into_any_element();
                        parent.relative().child(popover::anchored_submenu(
                            SharedString::from(format!("{id}-panel")),
                            panel,
                            &self.chain,
                            self.closing,
                        ))
                    },
                )
                .into_any_element()
            }));
        popover::popover_card(theme)
            .p_0()
            .flex()
            .flex_col()
            .max_h(cap)
            .map(|card| match (described, width.described) {
                (true, Described::Fixed(wide)) => card.w(wide),
                (true, Described::Fit(most)) => card.min_w(width.min).max_w(most),
                (false, _) => card.min_w(width.min),
            })
            .on_mouse_down_out(self.dismissal(cx))
            .map(|card| match query {
                None => card.child(
                    scroll::Viewport::new(rows_id, rows, Axis::Vertical)
                        .track_scroll(&handle)
                        .fill(),
                ),
                Some(query) => {
                    let field = query.read(cx).field.clone();
                    let rows = rows.max_h(px(
                        SEARCH_ROWS * popover::menu_row_height() + 2.0 * popover::MENU_PAD
                    ));
                    card.child(
                        div()
                            .key_context(SEARCH_CONTEXT)
                            .px(px(popover::MENU_PAD))
                            .pt(px(popover::MENU_PAD))
                            .map(|el| self.keys(el, items, &visible, lit, prefix, cx))
                            .child(popover::search_line(theme, field.into_any_element())),
                    )
                    .child(match visible.is_empty() {
                        true => div()
                            .px(px(popover::MENU_PAD + popover::MENU_ROW_INSET))
                            .pb(px(8.0))
                            .text_style(TextStyle::Body)
                            .text_color(theme.text_muted)
                            .child("No matches")
                            .into_any_element(),
                        false => scroll::Viewport::new(rows_id, rows, Axis::Vertical)
                            .track_scroll(&handle)
                            .into_any_element(),
                    })
                }
            })
    }

    /// The query of the searchable panel at `key`, focused the first time it
    /// paints. Each edit repaints the view the menu is drawn in.
    fn query(
        &self,
        key: &SharedString,
        placeholder: &SharedString,
        window: &mut Window,
        cx: &mut Context<V>,
    ) -> Entity<Query> {
        let host = cx.entity_id();
        let placeholder = placeholder.clone();
        let query = window.use_keyed_state(
            SharedString::from(format!("{key}-query")),
            cx,
            move |_, cx| {
                let field = cx.new(|cx| crate::search::query_field(placeholder, cx));
                let _changed = cx.subscribe(&field, move |_, _, _: &FieldEvent, cx| {
                    let app: &mut App = cx;
                    app.notify(host);
                });
                Query {
                    field,
                    focused: false,
                    _changed,
                }
            },
        );
        if !query.read(cx).focused {
            query.update(cx, |query, _| query.focused = true);
            let handle = query.read(cx).field.focus_handle(cx);
            window.focus(&handle, cx);
        }
        query
    }

    /// The arrows, enter and escape on a searchable panel's query: they walk
    /// and choose among the rows on show, and report it as the pointer would.
    fn keys(
        &self,
        el: gpui::Div,
        items: &[Item],
        shown: &[usize],
        lit: Option<usize>,
        prefix: &[usize],
        cx: &mut Context<V>,
    ) -> gpui::Div {
        let landable: Rc<Vec<usize>> = Rc::new(
            shown
                .iter()
                .copied()
                .filter(|&row| items[row].selectable())
                .collect(),
        );
        let at = lit.and_then(|lit| landable.iter().position(|&row| row == lit));
        let path = {
            let prefix = prefix.to_vec();
            move |row: usize| prefix.iter().copied().chain([row]).collect::<Vec<_>>()
        };
        let step = |delta: isize| {
            let count = landable.len() as isize;
            (count > 0).then(|| {
                let next = match at {
                    Some(at) => (at as isize + delta).rem_euclid(count),
                    None if delta > 0 => 0,
                    None => count - 1,
                };
                landable[next as usize]
            })
        };
        let next = step(1).map(&path);
        let previous = step(-1).map(&path);
        let chosen = at
            .map(|at| landable[at])
            .or_else(|| landable.first().copied())
            .map(|row| match items[row].opens() {
                Some(_) => Hit::Point(path(row)),
                None => Hit::Choose(path(row)),
            });
        let on = self.on.clone();
        let report = move |hit: Option<Hit>| {
            let on = on.clone();
            move |view: &mut V, window: &mut Window, cx: &mut Context<V>| {
                if let Some(hit) = hit.clone() {
                    on(view, hit, window, cx);
                }
            }
        };
        let (down, up, enter, escape) = (
            report(next.map(Hit::Point)),
            report(previous.map(Hit::Point)),
            report(chosen),
            report(Some(Hit::Dismiss)),
        );
        el.on_action(cx.listener(move |view, _: &SelectNext, window, cx| down(view, window, cx)))
            .on_action(
                cx.listener(move |view, _: &SelectPrevious, window, cx| up(view, window, cx)),
            )
            .on_action(cx.listener(move |view, _: &Confirm, window, cx| enter(view, window, cx)))
            .on_action(cx.listener(move |view, _: &Dismiss, window, cx| escape(view, window, cx)))
    }

    /// An [`Item::Segmented`] row: its segments share the row's width, the
    /// selected one washed, the live one lit the way a live row is.
    #[allow(clippy::too_many_arguments)]
    fn segmented(
        &self,
        theme: &Theme,
        segments: &[Segment],
        selected: usize,
        enabled: bool,
        live: Option<usize>,
        path: &[usize],
        cx: &mut Context<V>,
    ) -> gpui::Stateful<gpui::Div> {
        div()
            .id(row_id(&self.id, path))
            .flex()
            .flex_row()
            .gap(px(popover::MENU_PAD))
            .children(segments.iter().enumerate().map(|(at, segment)| {
                let path: Vec<usize> = path.iter().copied().chain([at]).collect();
                let chosen = at == selected;
                let ink = match (enabled, chosen || live == Some(at)) {
                    (false, _) => theme.text_faint.opacity(0.5),
                    (true, true) => theme.text,
                    (true, false) => theme.text_muted,
                };
                let cell = div()
                    .id(row_id(&self.id, &path))
                    .flex_1()
                    .min_w_0()
                    .flex()
                    .flex_col()
                    .items_center()
                    .gap(px(4.0))
                    .px(px(8.0))
                    .py(px(6.0))
                    .rounded(px(Theme::inset_radius(
                        Theme::surface_radius(),
                        popover::MENU_PAD,
                    )))
                    .text_style(TextStyle::Callout)
                    .text_color(ink)
                    .when(chosen, |cell| {
                        cell.bg(theme.element_active)
                            .font_weight(gpui::FontWeight::MEDIUM)
                    })
                    .when(!chosen && live == Some(at), |cell| {
                        cell.bg(theme.card_selected_bg())
                    })
                    .child(
                        icons::icon(segment.icon.clone())
                            .size(px(SEGMENT_GLYPH))
                            .text_color(ink),
                    )
                    .child(div().max_w_full().truncate().child(segment.label.clone()));
                match enabled {
                    true => cell
                        .cursor_pointer()
                        .on_mouse_move(self.reports(Hit::Point(path.clone()), cx))
                        .on_click(self.reports(Hit::Choose(path), cx)),
                    false => cell,
                }
            }))
    }

    /// One panel's share of the out-click test: it reports the press it did not
    /// contain, and whichever panel completes the tally is the one that calls
    /// it a dismissal. Order between them does not matter, only the count.
    ///
    /// The dismissing press is swallowed. It runs in the capture phase, where
    /// stopping propagation skips the bubble phase entirely — which is where
    /// gpui records the press a click is later built from, so the row under the
    /// pointer never fires. A press that lands on something while a menu is
    /// open is a press asking for the menu to go away, and acting on what it
    /// landed on runs an operation nobody aimed at (user report, DEV-11). The
    /// thing under it is still one more press away.
    fn dismissal(&self, cx: &mut Context<V>) -> Listener<MouseDownEvent> {
        let outside = self.outside.clone();
        let panels = self.panels;
        let on = self.on.clone();
        Box::new(
            cx.listener(move |view, event: &MouseDownEvent, window, cx| {
                let (at, count) = outside.get();
                let count = if at == Some(event.position) {
                    count + 1
                } else {
                    1
                };
                outside.set((Some(event.position), count));
                if count >= panels {
                    outside.set((None, 0));
                    on(view, Hit::Dismiss, window, cx);
                    cx.stop_propagation();
                }
            }),
        )
    }

    /// A listener that hands `hit` back to the caller, whatever the event was.
    fn reports<E: 'static>(&self, hit: Hit, cx: &mut Context<V>) -> Listener<E> {
        let on = self.on.clone();
        Box::new(cx.listener(move |view, _: &E, window, cx| on(view, hit.clone(), window, cx)))
    }
}

/// One panel's scroll position, and the live row and viewport size it last
/// scrolled for.
#[derive(Clone, Default)]
struct Scrolled(ScrollHandle, Rc<Cell<Option<Shown>>>);

type Shown = (Option<usize>, Size<Pixels>);

/// A row's element id: the card's, then the path, so rows of two panels — or of
/// two menus open at once — never collide.
fn row_id(id: &SharedString, path: &[usize]) -> SharedString {
    let mut out = id.to_string();
    for row in path {
        out.push('-');
        out.push_str(&row.to_string());
    }
    SharedString::from(out)
}

/// The leading column: the row's glyph, or the room one would have taken, so a
/// menu of mixed rows keeps its labels on one edge.
pub fn glyph_slot(theme: &Theme, icon: Option<Icon>, enabled: bool) -> gpui::Div {
    div()
        .flex_none()
        .size(px(GLYPH))
        .flex()
        .items_center()
        .justify_center()
        .children(icon.map(|glyph| {
            icons::icon(glyph).size(px(GLYPH)).text_color(if enabled {
                theme.text_faint
            } else {
                theme.text_faint.opacity(0.5)
            })
        }))
}

/// The second line under a row's label: the same relationship a card row's
/// meta line has to its title ([`crate::widgets::Scaffolding::meta_line`]),
/// which is where the size and the tone come from.
///
/// One line, clipped — rows of a menu are a column of equal things, and a
/// sentence that wrapped would make its row two or three times its neighbours'
/// height. What a caller cannot do from outside is guess where to cut: it
/// would be counting characters against a proportional font at a width only
/// the panel knows. [`Item::with_tooltip`] is where the rest of it goes.
///
/// It sets its own colour rather than inheriting the row's, because the row's
/// is the *label's* — a lit row paints that at full contrast, and a
/// description that followed it there would stop reading as the quieter half.
fn description_line(theme: &Theme, description: SharedString, enabled: bool) -> gpui::Div {
    div()
        .mt(px(2.0))
        .truncate()
        .text_style(TextStyle::Subheadline)
        .text_color(if enabled {
            theme.text_muted
        } else {
            // The dimming `glyph_slot` gives a disabled glyph, so the whole
            // row fades by one rule rather than two.
            theme.text_faint.opacity(0.5)
        })
        .child(description)
}

/// A row that cannot be chosen: [`popover::menu_row`]'s metrics without its
/// hover fade or its click, because a disabled row that lit under the pointer
/// would be inviting a press that does nothing.
fn disabled_row(theme: &Theme) -> gpui::Div {
    div()
        .flex()
        .flex_row()
        .items_center()
        .gap(px(10.0))
        .px(px(8.0))
        .py(px(popover::MENU_ROW_PAD_Y))
        // The disabled twin of `popover::menu_row`, in the same card — so it
        // takes its corners from the same rule rather than a matching literal.
        .rounded(px(Theme::inset_radius(
            Theme::surface_radius(),
            popover::MENU_PAD,
        )))
        .text_style(TextStyle::Body)
        .text_color(theme.text_faint)
}