vampir 0.4.0

Lit widget toolkit for GPUI: buttons, fields, pop-ups, menus and a text input, over a small OKLCH palette.
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
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
//! Right-click context menus.
//!
//! A menu is opened from wherever the press happened, by putting it in the
//! host's [`ControlState`], and rendered once near the root of the view.
//! Which items it holds is the host's decision each frame, because that
//! depends on what was clicked, which the state carries as an opaque target
//! string.
//!
//! ```ignore
//! // Around the row — a right-click opens the menu, aimed at this row:
//! vampir::menu_target("row", row_id, cx, |host, id, _cx| host.selected = Some(id), row)
//!
//! // Once, near the root of render:
//! .children(vampir::context_menu("row", &items, palette, self, cx,
//!     |host, item, _window, cx| host.run_menu_item(item, cx)))
//! ```

use std::collections::hash_map::DefaultHasher;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::time::Instant;

use gpui::{
    Anchor, AnyElement, App, ClickEvent, ElementId, FontWeight, KeyDownEvent, MouseButton,
    MouseDownEvent, MouseMoveEvent, Rgba, SharedString, Window, anchored, canvas, deferred, div,
    point, prelude::*, px,
};

use crate::controls::WidgetContext;
use crate::keyboard::{self, Dismiss, Key, Orientation};
use crate::lighting;
use crate::palette::Palette;
use crate::state::{ComboId, ControlHost, ControlState, MenuBranch};

/// Metrics chosen so a menu of ordinary items lines up with the pop-up list
/// a [`crate::controls::combo`] drops, which is the same thing seen from a
/// different angle.
const ITEM_HEIGHT: f32 = 26.0;
const HEADER_HEIGHT: f32 = 22.0;
/// The space either side of a separator's hairline.
const SEPARATOR_GAP: f32 = 3.0;
const SEPARATOR_HEIGHT: f32 = 2.0 * SEPARATOR_GAP + 1.0;
const MENU_PADDING: f32 = 5.0;
const MENU_RADIUS: f32 = 7.0;
const MENU_MIN_WIDTH: f32 = 168.0;
const MENU_MAX_HEIGHT: f32 = 520.0;
/// The column a row's icon sits in, kept for every row of a level that has
/// one, so labels line up whether or not each row has an icon.
const ICON_SLOT: f32 = 16.0;
const ICON_SIZE: f32 = 14.0;
/// Kept clear of the window edges, so a menu summoned in a corner still
/// reads as floating above the content rather than welded to the frame.
pub(crate) const VIEWPORT_MARGIN: f32 = 8.0;

/// An icon drawn ahead of a row's label: whatever the host draws at a size
/// in a colour. The menu never looks inside it.
///
/// A host with an icon enum of its own converts it once —
/// `impl From<Icon> for MenuIcon` — and [`MenuItem::icon`] takes it from
/// there.
#[derive(Clone)]
pub struct MenuIcon(Rc<dyn Fn(f32, Rgba) -> AnyElement>);

impl MenuIcon {
    pub fn new(draw: impl Fn(f32, Rgba) -> AnyElement + 'static) -> Self {
        Self(Rc::new(draw))
    }

    /// The icon, `size` points square, in `color`.
    pub fn draw(&self, size: f32, color: Rgba) -> AnyElement {
        (self.0)(size, color)
    }
}

impl fmt::Debug for MenuIcon {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("MenuIcon")
    }
}

/// One row of a menu.
///
/// `I` is what an action answers with when it is chosen: a `&'static str`
/// by default, or the host's own command type, so no table has to map a
/// row back to what it does.
#[derive(Clone, Debug)]
pub enum MenuItem<I = ComboId> {
    Action(MenuAction<I>),
    /// A branch whose rows replace this level in the same floating panel.
    Submenu {
        label: SharedString,
        items: Vec<MenuItem<I>>,
        enabled: bool,
        icon: Option<MenuIcon>,
    },
    /// A hairline between groups.
    Separator,
    /// A quiet label naming the group below it.
    Header(SharedString),
}

/// A menu row that does something when clicked.
#[derive(Clone, Debug)]
pub struct MenuAction<I = ComboId> {
    /// Comes back to the activation callback.
    pub id: I,
    pub label: SharedString,
    /// Right-aligned accelerator text, if the action has one.
    pub shortcut: Option<SharedString>,
    pub enabled: bool,
    /// Draws a trailing tick, for a menu that toggles something.
    pub checked: bool,
    /// Destructive: tinted, and always last in its group.
    pub danger: bool,
    /// Drawn ahead of the label, so a row can be found by its shape.
    pub icon: Option<MenuIcon>,
}

impl<I> MenuItem<I> {
    /// An enabled, unchecked, ordinary action.
    pub fn action(id: I, label: impl Into<SharedString>) -> Self {
        MenuItem::Action(MenuAction {
            id,
            label: label.into(),
            shortcut: None,
            enabled: true,
            checked: false,
            danger: false,
            icon: None,
        })
    }

    pub fn header(label: impl Into<SharedString>) -> Self {
        MenuItem::Header(label.into())
    }

    /// A nested level. Its leaf actions use the same activation callback as
    /// actions in the root menu.
    pub fn submenu(label: impl Into<SharedString>, items: Vec<MenuItem<I>>) -> Self {
        MenuItem::Submenu {
            label: label.into(),
            items,
            enabled: true,
            icon: None,
        }
    }

    pub fn separator() -> Self {
        MenuItem::Separator
    }

    /// Right-aligned accelerator text. Purely a label: binding the key is
    /// the host's business.
    pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
        if let MenuItem::Action(action) = &mut self {
            action.shortcut = Some(shortcut.into());
        }
        self
    }

    /// Greys the row out and stops it taking clicks. Prefer this to dropping
    /// the item: a menu whose rows move between openings is hard to use.
    pub fn disabled(mut self) -> Self {
        self.set_enabled(false);
        self
    }

    /// Enabled or greyed out, from a value.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.set_enabled(enabled);
        self
    }

    fn set_enabled(&mut self, value: bool) {
        match self {
            MenuItem::Action(action) => action.enabled = value,
            MenuItem::Submenu { enabled, .. } => *enabled = value,
            _ => {}
        }
    }

    pub fn checked(mut self, checked: bool) -> Self {
        if let MenuItem::Action(action) = &mut self {
            action.checked = checked;
        }
        self
    }

    pub fn danger(mut self) -> Self {
        if let MenuItem::Action(action) = &mut self {
            action.danger = true;
        }
        self
    }

    /// The same row with `icon` ahead of its label.
    pub fn icon(mut self, icon: impl Into<MenuIcon>) -> Self {
        match &mut self {
            MenuItem::Action(action) => action.icon = Some(icon.into()),
            MenuItem::Submenu { icon: slot, .. } => *slot = Some(icon.into()),
            _ => {}
        }
        self
    }

    /// The row's icon, if it has one.
    pub fn icon_of(&self) -> Option<&MenuIcon> {
        match self {
            MenuItem::Action(action) => action.icon.as_ref(),
            MenuItem::Submenu { icon, .. } => icon.as_ref(),
            _ => None,
        }
    }

    /// The row's text, for an action, a submenu or a header.
    pub fn label(&self) -> Option<&str> {
        match self {
            MenuItem::Action(action) => Some(&action.label),
            MenuItem::Submenu { label, .. } | MenuItem::Header(label) => Some(label),
            MenuItem::Separator => None,
        }
    }

    /// Whether the keyboard can land on it.
    pub fn reachable(&self) -> bool {
        match self {
            MenuItem::Action(action) => action.enabled,
            MenuItem::Submenu { enabled, .. } => *enabled,
            _ => false,
        }
    }

    /// Whether any row of `items` has an icon, so every label of the level
    /// lines up before the trailing icon column.
    pub fn any_icon(items: &[MenuItem<I>]) -> bool {
        items.iter().any(|item| item.icon_of().is_some())
    }

    /// The first action in the tree that `matches`, at any depth, to edit
    /// in place.
    pub fn action_mut(
        items: &mut [MenuItem<I>],
        matches: impl Fn(&MenuAction<I>) -> bool + Copy,
    ) -> Option<&mut MenuAction<I>> {
        for item in items {
            match item {
                MenuItem::Action(action) if matches(action) => return Some(action),
                MenuItem::Submenu { items, .. } => {
                    if let Some(found) = MenuItem::action_mut(items, matches) {
                        return Some(found);
                    }
                }
                _ => {}
            }
        }
        None
    }
}

/// Identity is the branch's label and the shape of its own rows: the labels
/// of its actions, branches and headers. Checked state and disabled rows
/// can change while the menu is open without turning it into a different
/// branch. Nothing deeper is hashed: each level below is checked by its own
/// entry in the path, and folding it in here would throw the reader out of
/// a level that has not changed because of an edit in a sibling's subtree.
fn submenu_identity<I>(label: &SharedString, children: &[MenuItem<I>]) -> u64 {
    let mut hasher = DefaultHasher::new();
    label.hash(&mut hasher);
    children.len().hash(&mut hasher);
    for item in children {
        match item {
            MenuItem::Action(action) => {
                0_u8.hash(&mut hasher);
                action.label.hash(&mut hasher);
            }
            MenuItem::Submenu { label, .. } => {
                1_u8.hash(&mut hasher);
                label.hash(&mut hasher);
            }
            MenuItem::Separator => 2_u8.hash(&mut hasher),
            MenuItem::Header(label) => {
                3_u8.hash(&mut hasher);
                label.hash(&mut hasher);
            }
        }
    }
    hasher.finish()
}

/// The host supplies the whole tree each frame. A branch that vanished,
/// moved, changed identity or became disabled is no longer a valid place to
/// leave the keyboard.
fn visible_level<'a, I>(
    mut items: &'a [MenuItem<I>],
    levels: &[MenuBranch],
) -> Option<(&'a [MenuItem<I>], Option<&'a SharedString>)> {
    let mut title = None;
    for branch in levels {
        let MenuItem::Submenu {
            label,
            items: children,
            enabled: true,
            ..
        } = items.get(branch.index)?
        else {
            return None;
        };
        if submenu_identity(label, children) != branch.identity {
            return None;
        }
        items = children;
        title = Some(label);
    }
    Some((items, title))
}

/// Backs out of levels the host's latest tree no longer has, to the deepest
/// one it still does. Returns the branch it came back out of, if any.
///
/// The row that opened a vanished level may have moved or gone with it, so
/// the keyboard is put back on it only if a branch still stands at the same
/// place. Anywhere else the restored row could be an action the reader
/// never chose, one Enter away from running.
fn settle_levels<I>(
    items: &[MenuItem<I>],
    levels: &mut Vec<MenuBranch>,
    highlight: &mut Option<usize>,
) -> Option<MenuBranch> {
    let mut left = None;
    while visible_level(items, levels).is_none() {
        left = Some(levels.pop()?);
    }
    let branch = left?;
    let (level, _) = visible_level(items, levels)?;
    let still_there = reachable_indices(level).get(branch.highlight) == Some(&branch.index)
        && matches!(level.get(branch.index), Some(MenuItem::Submenu { .. }));
    *highlight = still_there.then_some(branch.highlight);
    Some(branch)
}

/// What a key does to the open menu, worked out without the window so it
/// can be tested.
#[derive(Clone, Copy, Debug, PartialEq)]
enum MenuCommand<I = ComboId> {
    /// Up a level. At the root, Escape closes the menu and Left does
    /// nothing: Left means "back", and there is no back from the top.
    Back { close_at_root: bool },
    Enter {
        row: usize,
        at: usize,
        identity: u64,
    },
    /// The owned action id a keyboard handler needs after render.
    Run(I),
    /// Light this reachable row.
    Highlight(usize),
}

// Event handlers outlive render, but only need the reachable rows' commands,
// not owned copies of the menu tree and all its descendants.
fn menu_commands<I: Clone>(items: &[MenuItem<I>], reachable: &[usize]) -> Vec<MenuCommand<I>> {
    reachable
        .iter()
        .enumerate()
        .map(|(at, &row)| match &items[row] {
            MenuItem::Action(action) => MenuCommand::Run(action.id.clone()),
            MenuItem::Submenu { label, items, .. } => MenuCommand::Enter {
                row,
                at,
                identity: submenu_identity(label, items),
            },
            _ => unreachable!("reachable rows are actions or enabled submenus"),
        })
        .collect()
}

fn menu_command<I: Clone>(
    key: Key,
    at: Option<usize>,
    commands: &[MenuCommand<I>],
) -> Option<MenuCommand<I>> {
    let at = at.filter(|at| *at < commands.len());
    match key {
        Key::Dismiss => Some(MenuCommand::Back {
            close_at_root: true,
        }),
        Key::Left => Some(MenuCommand::Back {
            close_at_root: false,
        }),
        Key::Activate => commands.get(at?).cloned(),
        Key::Right => match commands.get(at?)? {
            command @ MenuCommand::Enter { .. } => Some(command.clone()),
            _ => None,
        },
        key => step_highlight(key, at, commands.len()).map(MenuCommand::Highlight),
    }
}

/// No row is lit until the first arrow: Down starts at the top, Up at the
/// bottom. A level with nothing reachable has nowhere to go.
fn step_highlight(key: Key, at: Option<usize>, len: usize) -> Option<usize> {
    if len == 0 {
        return None;
    }
    match at {
        Some(at) => keyboard::step(key, Orientation::Vertical, at, len),
        None => match key {
            Key::Down | Key::Home => Some(0),
            Key::Up | Key::End => Some(len - 1),
            _ => None,
        },
    }
}

fn reachable_indices<I>(items: &[MenuItem<I>]) -> Vec<usize> {
    items
        .iter()
        .enumerate()
        .filter_map(|(index, item)| item.reachable().then_some(index))
        .collect()
}

fn menu_height<I>(items: &[MenuItem<I>], nested: bool) -> f32 {
    let rows: f32 = items
        .iter()
        .map(|item| match item {
            MenuItem::Separator => SEPARATOR_HEIGHT,
            MenuItem::Header(_) => HEADER_HEIGHT,
            _ => ITEM_HEIGHT,
        })
        .sum();
    let back = if nested {
        ITEM_HEIGHT + SEPARATOR_HEIGHT
    } else {
        0.0
    };
    (rows + back + 2.0 * (MENU_PADDING + 1.0)).min(MENU_MAX_HEIGHT)
}

/// The panel's height in a window `window` tall. The window only moves a
/// menu back inside its edges; it never shrinks one, so a level taller than
/// the window has to be cut to fit here and scroll instead of overflowing.
fn fit_to_window(height: f32, window: Option<f32>) -> f32 {
    let Some(window) = window else {
        return height;
    };
    let room = window - 2.0 * VIEWPORT_MARGIN;
    height.min(room.max(ITEM_HEIGHT + 2.0 * (MENU_PADDING + 1.0)))
}

/// Renders the context menu `id` if it is the one currently open, otherwise
/// `None`. Put the result near the root of the view: it positions itself in
/// window coordinates and floats above everything.
///
/// Clicking an item runs `on_activate` with the item's id and then closes
/// the menu; pressing anywhere else closes it without running anything.
///
/// The order matters. The menu is still open while `on_activate` runs, so
/// [`ControlState::menu_target`](crate::ControlState::menu_target) still
/// answers with whatever the menu was summoned on — which is the only
/// moment that answer is any use. A callback that opens a menu of its own
/// keeps it; only the opening that was clicked is closed.
#[allow(clippy::too_many_arguments)]
pub fn context_menu<V: ControlHost, I: Clone + 'static>(
    id: ComboId,
    items: &[MenuItem<I>],
    palette: Palette,
    view: &mut V,
    cx: &mut Context<V>,
    on_activate: impl Fn(&mut V, I, &mut Window, &mut Context<V>) + 'static,
) -> Option<impl IntoElement> {
    // A host may replace the item tree while a menu is open. Walk back to
    // the last live branch rather than leaving the keyboard in a vanished
    // level with no rows to answer it.
    let state = view.control_state_mut();
    let left = {
        let menu = state.menu.as_mut()?;
        if menu.id != id {
            return None;
        }
        settle_levels(items, &mut menu.levels, &mut menu.highlight)
    };
    if let Some(branch) = left {
        state.menu_level_changed(branch.scroll);
    }
    let menu = state.menu.as_ref()?;
    let (anchor, under, opened_at, highlight, levels) = (
        menu.anchor,
        menu.under,
        menu.opened_at,
        menu.highlight,
        menu.levels.clone(),
    );
    let tree = items;
    let (level, title) = visible_level(items, &levels)?;
    let title = title.cloned();
    let items = level;
    let reachable = reachable_indices(items);
    let key_commands = menu_commands(items, &reachable);
    let key_reachable = reachable.clone();
    let selected = highlight.filter(|index| *index < reachable.len());
    let nested = !levels.is_empty();
    let icons = MenuItem::any_icon(items);
    let row_offset = if nested { 2 } else { 0 };
    let dark = palette.is_dark;
    let on_activate: Activate<V, I> = Rc::new(on_activate);
    let on_key_activate = on_activate.clone();
    let focus = view.control_state_mut().menu_focus(cx);
    let focus_on_open = focus.clone();
    let weak = cx.entity().downgrade();
    let scroll = view.control_state().menu_scroll(id);
    let key_scroll = scroll.clone();
    let window_height = view
        .control_state()
        .measured((id, "menu-window"))
        .map(|window| f32::from(window.size.height));

    // A menu that would run off the window is slid back inside it, the
    // margin clear of the edge, rather than cut off. `anchored` measures
    // the real panel to decide, so a long label is accounted for; this only
    // has to say which corner sits at the pointer.
    let at = under
        .map(|under| under.bottom_left() + point(px(0.0), px(4.0)))
        .unwrap_or(anchor);

    // The panel fades in over the same reveal a pop-up list uses, so the
    // two kinds of thing that drop out of a click arrive the same way.
    let reveal = crate::easing::ease_out_cubic(crate::easing::progress(
        opened_at,
        view.control_state().scaled(crate::state::COMBO_REVEAL),
    ));

    // Each level's rows get their own washes, so a row does not inherit the
    // light of the one that sat at its index in the level before.
    let level_key = {
        let mut hasher = DefaultHasher::new();
        for branch in &levels {
            (branch.index, branch.identity).hash(&mut hasher);
        }
        hasher.finish()
    };

    // A level change is noticed during render, regardless of whether it
    // came from a key, pointer, or host mutation. The panel keeps its
    // location while its rows and height settle into the next level.
    let depth = levels.len() as f32;
    let position =
        view.control_state()
            .tween((id, "menu-level", opened_at), depth, crate::state::MOVE);
    let level_reveal = (1.0 - (position - depth).abs()).clamp(0.0, 1.0);
    let level_offset = (depth - position) * 10.0;
    // The window's cap is applied outside the tween: it is a limit, not a
    // change of level, and a resize should not set the panel sliding.
    let height = fit_to_window(
        view.control_state().tween(
            (id, "menu-height", opened_at),
            menu_height(items, nested),
            crate::state::MOVE,
        ),
        window_height,
    );

    let mut rows: Vec<gpui::AnyElement> = Vec::with_capacity(items.len() + row_offset);
    if let Some(title) = title {
        rows.push(render_back(title, id, opened_at, palette, cx));
        rows.push(render_item(
            Row {
                index: 0,
                reachable_at: None,
                item: &MenuItem::Separator,
                lit: 0.0,
                icons,
            },
            id,
            opened_at,
            palette,
            cx,
            &on_activate,
        ));
    }
    for (index, item) in items.iter().enumerate() {
        let reachable_at = reachable.binary_search(&index).ok();
        let lit = selected.is_some_and(|at| reachable.get(at) == Some(&index));
        // The keyboard's wash moves from row to row rather than jumping.
        let lit = view.control_state().blend(
            (id, "menu-lit", (opened_at, level_key, index)),
            lit,
            crate::state::SWITCH_SLIDE,
        );
        rows.push(render_item(
            Row {
                index,
                reachable_at,
                item,
                lit,
                icons,
            },
            id,
            opened_at,
            palette,
            cx,
            &on_activate,
        ));
    }

    let panel = div()
        .id(ElementId::Name(format!("{id}-menu").into()))
        .opacity(reveal)
        .mt(px(-4.0 * (1.0 - reveal)))
        .h(px(height))
        .min_w(px(MENU_MIN_WIDTH))
        .max_w(px(360.0))
        .p(px(MENU_PADDING))
        .flex()
        .flex_col()
        .rounded(px(MENU_RADIUS))
        .bg(if dark {
            palette.soft_fill
        } else {
            palette.field_surface
        })
        .border_1()
        .border_color(lighting::rim(
            if dark {
                palette.soft_fill
            } else {
                palette.field_surface
            },
            dark,
        ))
        .shadow(lighting::panel(dark))
        .track_focus(&focus)
        .child(
            // Prepaint is the first moment there is a `Window` to focus
            // with, or to measure. The handle is unchanged as the menu
            // drills in or back.
            canvas(
                move |_bounds, window, cx| {
                    let viewport =
                        gpui::Bounds::new(point(px(0.0), px(0.0)), window.viewport_size());
                    if let Some(host) = weak.upgrade() {
                        let resized = host.update(cx, |host, _cx| {
                            let state = host.control_state_mut();
                            let resized = state.measured((id, "menu-window")) != Some(viewport);
                            if resized {
                                state.measure((id, "menu-window"), viewport);
                            }
                            resized
                        });
                        // Render has already used the old size. A notify
                        // from inside a draw is dropped, so ask for the
                        // next frame directly.
                        if resized {
                            window.request_animation_frame();
                        }
                    }
                    if focus_on_open.is_focused(window) {
                        return;
                    }
                    let previous = window.focused(cx);
                    if let Some(host) = weak.upgrade() {
                        host.update(cx, |host, _cx| {
                            host.control_state_mut().menu_return_focus = previous;
                        });
                    }
                    window.focus(&focus_on_open, cx);
                },
                |_bounds, _state, _window, _cx| {},
            )
            .absolute()
            .size_full(),
        )
        // Once `bind_keys` has run, Escape arrives as this action and never
        // as a key. A child level consumes it to return to its parent.
        .on_action(cx.listener(move |this, _: &Dismiss, window, cx| {
            if !this.control_state_mut().back_menu() {
                this.control_state_mut().close_menu();
                restore_focus(this, window, cx);
            }
            cx.notify();
        }))
        .on_key_down(cx.listener(move |this, event: &KeyDownEvent, window, cx| {
            let Some(key) = keyboard::key(event) else {
                return;
            };
            cx.stop_propagation();
            let at = this.control_state().menu_highlight();
            match menu_command(key, at, &key_commands) {
                Some(MenuCommand::Back { close_at_root }) => {
                    if !this.control_state_mut().back_menu() && close_at_root {
                        this.control_state_mut().close_menu();
                        restore_focus(this, window, cx);
                    }
                }
                Some(MenuCommand::Enter { row, at, identity }) => {
                    this.control_state_mut().enter_menu(row, at, identity, true);
                }
                Some(MenuCommand::Run(action)) => {
                    activate(this, action, opened_at, window, cx, &on_key_activate);
                }
                Some(MenuCommand::Highlight(moved)) => {
                    this.control_state_mut().highlight_menu(Some(moved));
                    if let Some(&row) = key_reachable.get(moved) {
                        key_scroll.scroll_to_item(row + row_offset);
                    }
                }
                None => {}
            }
            cx.notify();
        }))
        // Hover lights a row for the keyboard too, so the light has to go
        // when the pointer does: otherwise Enter runs a row the hand has
        // already left.
        .on_hover(cx.listener(|this, hovered: &bool, _window, cx| {
            if !*hovered && this.control_state().menu_highlight().is_some() {
                this.control_state_mut().highlight_menu(None);
                cx.notify();
            }
        }))
        .occlude()
        .on_mouse_down_out(
            cx.listener(move |this, event: &MouseDownEvent, window, cx| {
                // The trigger toggles on release. Closing on its press would
                // let the same click immediately reopen the menu.
                let on_own_button = this
                    .control_state()
                    .track(id)
                    .is_some_and(|bounds| bounds.contains(&event.position));
                if on_own_button {
                    return;
                }
                this.control_state_mut().close_menu();
                restore_focus(this, window, cx);
                cx.notify();
            }),
        )
        .on_mouse_down(
            MouseButton::Right,
            cx.listener(|_this, _event: &MouseDownEvent, _window, _cx| {}),
        )
        .child(
            // The slide moves the rows further than the padding is wide, so
            // the frame they slide in clips them: a lit row must not poke
            // past the border on its way in.
            div()
                .flex_1()
                .min_h(px(0.0))
                .flex()
                .flex_col()
                .overflow_hidden()
                .child(
                    div()
                        .id(ElementId::Name(format!("{id}-menu-rows").into()))
                        .relative()
                        .left(px(level_offset))
                        .opacity(level_reveal)
                        .flex_1()
                        .min_h(px(0.0))
                        .flex()
                        .flex_col()
                        .overflow_y_scroll()
                        .restrict_scroll_to_axis()
                        .track_scroll(&scroll)
                        .children(rows),
                ),
        )
        // The panel is as wide as the widest level in the tree, not the one
        // showing, so a level change never changes the width — nothing to
        // jump, and nothing for the edge snap to shove sideways. Tweening
        // the width instead would need last frame's measurement of the
        // content, and a frame drawn at the wrong width before the slide
        // could start. This way the layout engine works the width out from
        // the items in the same pass, and the control stays a function of
        // its data. The rows are laid out at no height, so they are never
        // seen and never hit.
        .child(
            div()
                .h(px(0.0))
                .flex_none()
                .flex()
                .flex_col()
                .overflow_hidden()
                .children(
                    every_level(tree)
                        .into_iter()
                        .flat_map(|level| {
                            let icons = MenuItem::any_icon(level);
                            level.iter().map(move |item| sizing_row(item, icons))
                        })
                        .flatten(),
                ),
        );
    // An occluding panel must keep an in-flight drag underneath it moving
    // and release it even if the pointer ends over the menu.
    let panel = crate::state::handle_mouse(panel, cx);
    Some(
        deferred(
            anchored()
                .position(at)
                .anchor(Anchor::TopLeft)
                .snap_to_window_with_margin(px(VIEWPORT_MARGIN))
                .child(panel),
        )
        .priority(200),
    )
}

type Activate<V, I> = Rc<dyn Fn(&mut V, I, &mut Window, &mut Context<V>)>;

/// Hands the keyboard back to whatever had it before the menu opened.
///
/// Without this, closing a menu leaves focus on an element that is no longer
/// in the tree, and the next Tab starts again from the top of the window —
/// which for someone navigating by keyboard means losing their place.
fn restore_focus<V: ControlHost>(view: &mut V, window: &mut Window, cx: &mut App) {
    view.control_state_mut().restore_menu_focus(window, cx);
}

fn activate<V: ControlHost, I>(
    view: &mut V,
    id: I,
    opened_at: Instant,
    window: &mut Window,
    cx: &mut Context<V>,
    on_activate: &Activate<V, I>,
) {
    // Restore first so a callback that opens another overlay remembers a
    // live control, while retaining the menu's target until it has run.
    restore_focus(view, window, cx);
    on_activate(view, id, window, cx);
    if view.control_state().menu_opened_at() == Some(opened_at) {
        view.control_state_mut().close_menu();
    }
}

/// Every level of the tree, depth first: what the panel's width is taken
/// from.
fn every_level<I>(items: &[MenuItem<I>]) -> Vec<&[MenuItem<I>]> {
    let mut levels = Vec::new();
    let mut stack = vec![items];
    while let Some(level) = stack.pop() {
        levels.push(level);
        for item in level {
            if let MenuItem::Submenu { items, .. } = item {
                stack.push(items);
            }
        }
    }
    levels
}

/// Every row of every level, depth first.
#[cfg(test)]
fn every_row<I>(items: &[MenuItem<I>]) -> Vec<&MenuItem<I>> {
    every_level(items).into_iter().flatten().collect()
}

/// A row's content at the metrics `render_item` draws it with, and nothing
/// else. A branch is set in the back row's heavier weight, so it holds the
/// room for its title when the level it opens is showing.
fn sizing_row<I>(item: &MenuItem<I>, icons: bool) -> Option<gpui::AnyElement> {
    let row = div()
        .flex()
        .items_center()
        .gap(px(8.0))
        .pr(px(8.0))
        .whitespace_nowrap()
        .when(icons && !matches!(item, MenuItem::Header(_)), |row| {
            row.child(div().w(px(ICON_SLOT)).flex_none())
        });
    Some(match item {
        MenuItem::Separator => return None,
        MenuItem::Header(label) => row
            .pl(px(8.0))
            .text_size(px(11.0))
            .font_weight(FontWeight::MEDIUM)
            .child(label.clone())
            .into_any_element(),
        MenuItem::Submenu { label, .. } => row
            .pl(px(8.0))
            .text_size(px(12.5))
            .font_weight(FontWeight::MEDIUM)
            .child(label.clone())
            .when(icons, |row| row.child(div().w(px(ICON_SLOT)).flex_none()))
            .child(div().w(px(10.0)).flex_none())
            .into_any_element(),
        MenuItem::Action(action) => row
            .pl(px(8.0))
            .text_size(px(12.5))
            .child(action.label.clone())
            .children(
                action
                    .shortcut
                    .clone()
                    .map(|shortcut| div().text_size(px(11.5)).child(shortcut)),
            )
            .when(icons, |row| row.child(div().w(px(ICON_SLOT)).flex_none()))
            .when(action.checked, |row| {
                row.child(div().w(px(12.0)).flex_none())
            })
            .into_any_element(),
    })
}

#[derive(Clone, Copy)]
enum RowClick {
    Navigate,
    Activate,
}

// A stationary pointer can produce click counts above one across several
// intentional back/forward steps. Only actions need protection from a late
// double-click running the command that slid under the pointer.
fn takes_click(
    state: &ControlState,
    opened_at: Instant,
    click_count: usize,
    kind: RowClick,
) -> bool {
    (matches!(kind, RowClick::Navigate) || click_count <= 1) && state.menu_takes_click(opened_at)
}

/// The pointer lights the row it is over for the keyboard too. A disabled
/// row cannot hold the keyboard, and passing over one on the way to the
/// next should not drop the row that has it.
fn hover_row<V: ControlHost>(view: &mut V, reachable_at: Option<usize>, cx: &mut Context<V>) {
    if let Some(at) = reachable_at
        && view.control_state().menu_highlight() != Some(at)
    {
        view.control_state_mut().highlight_menu(Some(at));
        cx.notify();
    }
}

fn chevron(right: bool, color: gpui::Rgba) -> impl IntoElement {
    let color: gpui::Hsla = crate::color::to_hsla(color);
    div().w(px(10.0)).h(px(10.0)).flex_none().child(
        canvas(
            |_bounds, _window, _cx| {},
            move |bounds, _state, window, _cx| {
                let origin = bounds.origin;
                let mut builder = gpui::PathBuilder::stroke(px(1.4));
                let edge = if right { 7.0 } else { 3.0 };
                let tip = if right { 3.0 } else { 7.0 };
                builder.move_to(point(origin.x + px(tip), origin.y + px(1.5)));
                builder.line_to(point(origin.x + px(edge), origin.y + px(5.0)));
                builder.line_to(point(origin.x + px(tip), origin.y + px(8.5)));
                if let Ok(path) = builder.build() {
                    window.paint_path(path, color);
                }
            },
        )
        .size_full(),
    )
}

/// The trailing icon column stays aligned even on rows with no icon.
fn icon_slot(icon: Option<&MenuIcon>, color: Rgba) -> gpui::Div {
    let slot = div()
        .w(px(ICON_SLOT))
        .h(px(ICON_SLOT))
        .flex_none()
        .flex()
        .items_center()
        .justify_center();
    match icon {
        Some(icon) => slot.child(icon.draw(ICON_SIZE, color)),
        None => slot,
    }
}

/// The tick a checked row carries, 12 points square.
fn tick_mark(color: gpui::Hsla) -> gpui::Div {
    div().w(px(12.0)).h(px(12.0)).flex_none().child(
        canvas(
            |_bounds, _window, _cx| {},
            move |bounds, _state, window, _cx| {
                let origin = bounds.origin;
                let mut builder = gpui::PathBuilder::stroke(px(1.5));
                builder.move_to(point(origin.x + px(1.5), origin.y + px(6.0)));
                builder.line_to(point(origin.x + px(4.5), origin.y + px(9.0)));
                builder.line_to(point(origin.x + px(10.5), origin.y + px(2.5)));
                if let Ok(path) = builder.build() {
                    window.paint_path(path, color);
                }
            },
        )
        .size_full(),
    )
}

fn render_back<V: ControlHost>(
    title: SharedString,
    menu_id: ComboId,
    opened_at: Instant,
    palette: Palette,
    cx: &mut Context<V>,
) -> gpui::AnyElement {
    div()
        .id(ElementId::Name(format!("{menu_id}-menu-back").into()))
        .h(px(ITEM_HEIGHT))
        .flex_none()
        .w_full()
        .px(px(8.0))
        .flex()
        .items_center()
        .gap(px(8.0))
        .rounded(px(MENU_RADIUS - 3.0))
        .text_size(px(12.5))
        .font_weight(FontWeight::MEDIUM)
        .text_color(palette.text_primary)
        .cursor_pointer()
        .hover(move |style| style.bg(lighting::lit(palette.row_hover, 0.08)))
        .on_mouse_move(cx.listener(|this, _: &MouseMoveEvent, _window, cx| {
            if this.control_state().menu_highlight().is_some() {
                this.control_state_mut().highlight_menu(None);
                cx.notify();
            }
        }))
        .on_click(cx.listener(move |this, event: &ClickEvent, _window, cx| {
            if takes_click(
                this.control_state(),
                opened_at,
                event.click_count(),
                RowClick::Navigate,
            ) {
                this.control_state_mut().back_menu();
                cx.notify();
            }
        }))
        .child(div().flex_1().overflow_hidden().child(title))
        .child(chevron(false, palette.text_secondary))
        .into_any_element()
}

// A row's text and its auxiliary marks travel with the same highlight as
// its fill, so both pointer and keyboard selection use the paired roles.
fn menu_row_labels(palette: Palette, danger: bool, lit: f32) -> (gpui::Rgba, gpui::Rgba) {
    let label = if danger {
        palette.danger_label
    } else {
        palette.text_primary
    };
    let highlighted = if danger {
        palette.danger_label
    } else {
        palette.control_label
    };
    (
        crate::color::lerp(label, highlighted, lit),
        crate::color::lerp(palette.text_secondary, highlighted, lit),
    )
}

/// One row as the level draws it: where it sits, whether the keyboard can
/// land on it, and how lit it is.
struct Row<'a, I> {
    index: usize,
    reachable_at: Option<usize>,
    item: &'a MenuItem<I>,
    lit: f32,
    /// Whether the level keeps an icon column.
    icons: bool,
}

fn render_item<V: ControlHost, I: Clone + 'static>(
    row: Row<'_, I>,
    menu_id: ComboId,
    opened_at: Instant,
    palette: Palette,
    cx: &mut Context<V>,
    on_activate: &Activate<V, I>,
) -> gpui::AnyElement {
    let Row {
        index,
        reachable_at,
        item,
        lit,
        icons,
    } = row;
    match item {
        MenuItem::Separator => {
            let mut color: gpui::Hsla = crate::color::to_hsla(palette.field_border);
            color.alpha = 0.8;
            div()
                .my(px(SEPARATOR_GAP))
                .h(px(1.0))
                .w_full()
                .flex_none()
                .bg(color)
                .into_any_element()
        }
        MenuItem::Header(label) => div()
            .h(px(HEADER_HEIGHT))
            .flex_none()
            .px(px(8.0))
            .flex()
            .items_center()
            .text_size(px(11.0))
            .font_weight(FontWeight::MEDIUM)
            .text_color(palette.text_secondary)
            .whitespace_nowrap()
            .child(label.clone())
            .into_any_element(),
        MenuItem::Submenu {
            label,
            items,
            enabled,
            icon,
        } => {
            let identity = submenu_identity(label, items);
            let (label_color, chevron_color) = menu_row_labels(palette, false, lit);
            div()
                .id(ElementId::NamedInteger(
                    format!("{menu_id}-submenu").into(),
                    index as u64,
                ))
                .h(px(ITEM_HEIGHT))
                .flex_none()
                .w_full()
                .px(px(8.0))
                .flex()
                .items_center()
                .gap(px(8.0))
                .rounded(px(MENU_RADIUS - 3.0))
                .text_size(px(12.5))
                .text_color(label_color)
                .whitespace_nowrap()
                .overflow_hidden()
                .when(!enabled, |el| el.opacity(0.45))
                .when(lit > 0.01, |el| {
                    el.bg(lighting::lit_at(palette.control_fill, 0.08, lit))
                })
                .on_mouse_move(cx.listener(move |this, _: &MouseMoveEvent, _window, cx| {
                    hover_row(this, reachable_at, cx);
                }))
                .when(*enabled, |el| {
                    el.cursor_pointer().on_click(cx.listener(
                        move |this, event: &ClickEvent, _window, cx| {
                            if takes_click(
                                this.control_state(),
                                opened_at,
                                event.click_count(),
                                RowClick::Navigate,
                            ) && let Some(at) = reachable_at
                            {
                                this.control_state_mut()
                                    .enter_menu(index, at, identity, false);
                                cx.notify();
                            }
                        },
                    ))
                })
                .child(div().flex_1().overflow_hidden().child(label.clone()))
                .when(icons, |el| {
                    el.child(icon_slot(icon.as_ref(), chevron_color))
                })
                .child(chevron(true, chevron_color))
                .into_any_element()
        }
        MenuItem::Action(action) => {
            let on_activate = on_activate.clone();
            let id = action.id.clone();
            let (label_color, shortcut_color) = menu_row_labels(palette, action.danger, lit);
            let tick: gpui::Hsla = crate::color::to_hsla(label_color);
            let (enabled, checked, danger) = (action.enabled, action.checked, action.danger);
            div()
                .id(ElementId::NamedInteger(
                    format!("{menu_id}-item").into(),
                    index as u64,
                ))
                .h(px(ITEM_HEIGHT))
                .flex_none()
                .w_full()
                .pl(px(8.0))
                .pr(px(8.0))
                .flex()
                .items_center()
                .gap(px(8.0))
                .rounded(px(MENU_RADIUS - 3.0))
                .text_size(px(12.5))
                .text_color(label_color)
                .whitespace_nowrap()
                .overflow_hidden()
                .when(!enabled, |el| el.opacity(0.45))
                // The keyboard's row is filled the same way the mouse fills
                // one under the pointer, so there is one idea of "this one"
                // rather than two competing marks.
                .when(lit > 0.01, move |el| {
                    el.bg(lighting::lit_at(
                        if danger {
                            palette.danger_fill
                        } else {
                            palette.control_fill
                        },
                        0.08,
                        lit,
                    ))
                })
                .on_mouse_move(cx.listener(move |this, _: &MouseMoveEvent, _window, cx| {
                    hover_row(this, reachable_at, cx);
                }))
                .when(enabled, move |el| {
                    let on_activate = on_activate.clone();
                    el.cursor_pointer().on_click(cx.listener(
                        move |this, event: &ClickEvent, window, cx| {
                            if takes_click(
                                this.control_state(),
                                opened_at,
                                event.click_count(),
                                RowClick::Activate,
                            ) {
                                activate(this, id.clone(), opened_at, window, cx, &on_activate);
                                cx.notify();
                            }
                        },
                    ))
                })
                .child(div().flex_1().overflow_hidden().child(action.label.clone()))
                .children(action.shortcut.clone().map(|shortcut| {
                    div()
                        .flex_none()
                        .text_size(px(11.5))
                        .text_color(shortcut_color)
                        .child(shortcut)
                }))
                .when(icons, |el| {
                    el.child(icon_slot(action.icon.as_ref(), label_color))
                })
                .when(checked, |el| el.child(tick_mark(tick)))
                .into_any_element()
        }
    }
}

/// A button that drops a menu beneath itself instead of at the pointer.
///
/// The menu itself is still rendered by [`context_menu`] near the root; this
/// only opens it, anchored to the button's own bounds. Splitting it that way
/// keeps the list above everything, whatever the button is nested inside.
pub fn menu_button<V: ControlHost>(
    id: ComboId,
    label: &str,
    enabled: bool,
    ctx: WidgetContext<'_, '_, '_, V>,
) -> impl IntoElement {
    let WidgetContext { palette, view, cx } = ctx;
    let dark = palette.is_dark;
    let open = view.control_state().is_menu_open(id);
    let fill = if dark {
        palette.soft_fill
    } else {
        palette.field_surface
    };
    let weak = cx.entity().downgrade();

    div()
        .id(ElementId::Name(format!("{id}-menu-button").into()))
        .relative()
        .h(px(crate::controls::CONTROL_HEIGHT))
        .flex_none()
        .px(px(12.0))
        .flex()
        .items_center()
        .gap(px(6.0))
        .rounded(px(crate::controls::CONTROL_RADIUS))
        .bg(lighting::lit(fill, 0.05))
        .border_1()
        .border_color(if open {
            palette.accent
        } else {
            lighting::rim(fill, dark)
        })
        .shadow(lighting::raised(dark))
        .text_size(px(12.5))
        .text_color(palette.text_primary)
        .whitespace_nowrap()
        .when(!enabled, |el| el.opacity(0.5))
        .when(enabled, |el| {
            el.cursor_pointer()
                .hover(move |style| style.bg(lighting::lit(fill, 0.09)))
        })
        .child(
            // Records the button's bounds so the menu can hang from them.
            canvas(
                move |bounds, _window, cx| {
                    if let Some(host) = weak.upgrade() {
                        host.update(cx, |host, _cx| {
                            host.control_state_mut().record_track(id, bounds);
                        });
                    }
                },
                |_bounds, _state, _window, _cx| {},
            )
            .absolute()
            .size_full(),
        )
        .child(SharedString::from(label.to_string()))
        .child(
            div().w(px(9.0)).h(px(9.0)).flex_none().child(
                canvas(
                    |_bounds, _window, _cx| {},
                    move |bounds, _state, window, _cx| {
                        let origin = bounds.origin;
                        let mut builder = gpui::PathBuilder::stroke(px(1.4));
                        builder.move_to(point(origin.x + px(0.5), origin.y + px(3.0)));
                        builder.line_to(point(origin.x + px(4.5), origin.y + px(7.0)));
                        builder.line_to(point(origin.x + px(8.5), origin.y + px(3.0)));
                        if let Ok(path) = builder.build() {
                            let color: gpui::Hsla = crate::color::to_hsla(palette.text_secondary);
                            window.paint_path(path, color);
                        }
                    },
                )
                .size_full(),
            ),
        )
        .when(enabled, |el| {
            el.on_click(cx.listener(move |this, _event, window, cx| {
                let state = this.control_state_mut();
                if state.is_menu_open(id) {
                    state.close_menu();
                    state.restore_menu_focus(window, cx);
                } else if let Some(bounds) = state.track(id) {
                    state.open_menu_under(id, bounds, "");
                }
                cx.notify();
            }))
        })
        .when(enabled, |el| {
            el.child(
                keyboard::ring(
                    ElementId::Name(format!("{id}-menu-button-focus").into()),
                    crate::controls::CONTROL_RADIUS,
                    palette,
                )
                .on_key_down(cx.listener(
                    move |this, event: &KeyDownEvent, _window, cx| {
                        if !matches!(keyboard::key(event), Some(Key::Activate | Key::Down)) {
                            return;
                        }
                        cx.stop_propagation();
                        if let Some(bounds) = this.control_state().track(id) {
                            this.control_state_mut().open_menu_under(id, bounds, "");
                            cx.notify();
                        }
                    },
                )),
            )
        })
}

/// Wraps `child` so that a right-click on it opens the context menu `menu`,
/// aimed at `target`, after running `on_open` with the same target.
///
/// The listener belongs on the row rather than on the list, because the
/// menu has to be about what was actually clicked: hung on the container
/// instead, it only ever knows about the selection, and right-clicking one
/// row opens a menu aimed at another. `on_open` is where a host selects the
/// row on the way, which is what every file list does and what keeps the
/// highlight and the menu saying the same thing.
///
/// ```ignore
/// menu_target("row", file.id.clone(), cx, |this, id, _cx| this.selected = Some(id),
///     tree_row(..))
/// ```
pub fn menu_target<V: ControlHost>(
    menu: ComboId,
    target: impl Into<SharedString>,
    cx: &mut Context<V>,
    on_open: impl Fn(&mut V, SharedString, &mut Context<V>) + 'static,
    child: impl IntoElement,
) -> gpui::Div {
    let target = target.into();
    div()
        .flex_none()
        .on_mouse_down(
            MouseButton::Right,
            cx.listener(move |this, event: &MouseDownEvent, _window, cx| {
                on_open(this, target.clone(), cx);
                this.control_state_mut()
                    .open_menu(menu, event.position, target.clone());
                cx.notify();
            }),
        )
        .child(child)
}

/// The menu a context menu is currently showing, re-exported for hosts that
/// build their item list from it.
pub use crate::state::OpenMenu as ContextMenu;

#[cfg(test)]
mod tests {
    use super::{
        MenuBranch, MenuCommand, MenuIcon, MenuItem, RowClick, every_row, fit_to_window,
        menu_command, menu_commands, menu_height, menu_row_labels, reachable_indices,
        settle_levels, step_highlight, submenu_identity, takes_click, visible_level,
    };
    use crate::ControlState;
    use crate::keyboard::Key;

    #[test]
    fn keyboard_snapshot_owns_typed_ids_without_retaining_icons_or_subtrees() {
        let token = std::rc::Rc::new(());
        let weak = std::rc::Rc::downgrade(&token);
        let icon = MenuIcon::new(move |_, _| {
            let _ = &token;
            gpui::IntoElement::into_any_element(gpui::Empty)
        });
        let items = vec![
            MenuItem::action(String::from("disabled"), "Disabled").disabled(),
            MenuItem::action(String::from("open"), "Open").icon(icon),
            MenuItem::submenu(
                "More",
                vec![MenuItem::action(String::from("nested"), "Nested")],
            ),
        ];
        let reachable = reachable_indices(&items);
        let commands = menu_commands(&items, &reachable);
        drop(items);
        assert!(weak.upgrade().is_none());
        assert_eq!(
            menu_command(Key::Activate, Some(0), &commands),
            Some(MenuCommand::Run(String::from("open")))
        );
        assert_eq!(menu_command(Key::Right, Some(0), &commands), None);
        assert!(matches!(
            menu_command(Key::Right, Some(1), &commands),
            Some(MenuCommand::Enter { row: 2, at: 1, .. })
        ));
    }

    #[test]
    fn highlighted_menu_text_and_marks_use_the_fills_label_role() {
        for hue in (0..360).step_by(30) {
            for saturation in [0.0, 1.0, 2.0, crate::MAX_SATURATION] {
                for dark in [false, true] {
                    let palette =
                        crate::Palette::from_hue_and_saturation(hue as f64, saturation, dark);
                    for (danger, lit, expected) in [
                        (false, 0.0, (palette.text_primary, palette.text_secondary)),
                        (false, 1.0, (palette.control_label, palette.control_label)),
                        (true, 1.0, (palette.danger_label, palette.danger_label)),
                    ] {
                        let actual = menu_row_labels(palette, danger, lit);
                        for (actual, expected) in [(actual.0, expected.0), (actual.1, expected.1)] {
                            for (actual, expected) in crate::color::channels(actual)
                                .into_iter()
                                .zip(crate::color::channels(expected))
                            {
                                assert!((actual - expected).abs() < 1e-6);
                            }
                        }
                    }
                }
            }
        }
    }

    fn branch(item: &MenuItem, index: usize, highlight: usize) -> MenuBranch {
        let MenuItem::Submenu { label, items, .. } = item else {
            panic!("expected submenu");
        };
        MenuBranch {
            index,
            highlight,
            identity: submenu_identity(label, items),
            scroll: Default::default(),
        }
    }

    fn children(item: &MenuItem) -> &[MenuItem] {
        let MenuItem::Submenu { items, .. } = item else {
            panic!("expected submenu");
        };
        items
    }

    /// File > Organize > Move to, with a sibling branch beside Move to.
    fn tree(move_to: &[&'static str], tag: &[&'static str]) -> Vec<MenuItem> {
        let actions = |ids: &[&'static str]| {
            ids.iter()
                .map(|id| MenuItem::action(*id, *id))
                .collect::<Vec<_>>()
        };
        vec![
            MenuItem::action("open", "Open"),
            MenuItem::submenu(
                "Organize",
                vec![
                    MenuItem::action("pin", "Pin"),
                    MenuItem::submenu("Move to", actions(move_to)),
                    MenuItem::submenu("Tag", actions(tag)),
                ],
            ),
        ]
    }

    fn path_to_move(items: &[MenuItem]) -> Vec<MenuBranch> {
        vec![
            branch(&items[1], 1, 1),
            branch(&children(&items[1])[1], 1, 1),
        ]
    }

    #[test]
    fn nested_levels_find_the_leaf_and_reject_a_removed_branch() {
        let items = vec![MenuItem::submenu(
            "Organize",
            vec![MenuItem::submenu(
                "Move to",
                vec![MenuItem::action("inbox", "Inbox")],
            )],
        )];
        let MenuItem::Submenu {
            items: children, ..
        } = &items[0]
        else {
            unreachable!();
        };
        let path = [branch(&items[0], 0, 0), branch(&children[0], 0, 0)];
        let (level, title) = visible_level(&items, &path).expect("nested level");
        assert_eq!(title.map(|title| title.as_ref()), Some("Move to"));
        assert!(matches!(level, [MenuItem::Action(action)] if action.id == "inbox"));

        let disabled: Vec<MenuItem> = vec![MenuItem::submenu("Organize", vec![]).disabled()];
        assert!(visible_level(&disabled, &path[..1]).is_none());
    }

    /// Identity is what the reader sees — the labels — so it needs nothing
    /// of the id type, and a host whose ids are commands can still open a
    /// menu of them. Toggling a row keeps the level; replacing its rows
    /// does not.
    #[test]
    fn a_reordered_or_replaced_branch_cannot_show_another_submenu() {
        let original = vec![
            MenuItem::submenu("Organize", vec![MenuItem::action("inbox", "Inbox")]),
            MenuItem::submenu("Other", vec![MenuItem::action("settings", "Settings")]),
        ];
        let path = [branch(&original[0], 0, 0)];
        assert!(visible_level(&original, &path).is_some());

        let reordered = vec![original[1].clone(), original[0].clone()];
        assert!(visible_level(&reordered, &path).is_none());
        let replaced = vec![MenuItem::submenu(
            "Organize",
            vec![MenuItem::action("archive", "Archive")],
        )];
        assert!(visible_level(&replaced, &path).is_none());

        let toggled = vec![MenuItem::submenu(
            "Organize",
            vec![MenuItem::action("inbox", "Inbox").checked(true).disabled()],
        )];
        assert!(visible_level(&toggled, &path).is_some());

        let commands: Vec<MenuItem<Option<u32>>> = vec![MenuItem::submenu(
            "Organize",
            vec![
                MenuItem::action(Some(7), "Inbox"),
                MenuItem::action(None, "Gone"),
            ],
        )];
        let MenuItem::Submenu { label, items, .. } = &commands[0] else {
            unreachable!();
        };
        let path = [MenuBranch {
            index: 0,
            highlight: 0,
            identity: submenu_identity(label, items),
            scroll: Default::default(),
        }];
        assert!(visible_level(&commands, &path).is_some());
    }

    /// Editing one branch's subtree must not throw the reader out of
    /// another: only the levels on the path, and their own rows, count.
    #[test]
    fn an_edit_in_a_sibling_subtree_keeps_the_open_level() {
        let original = tree(&["inbox"], &["red"]);
        let path = path_to_move(&original);
        let retagged = tree(&["inbox"], &["red", "blue"]);
        let (level, title) = visible_level(&retagged, &path).expect("still open");
        assert_eq!(title.map(|title| title.as_ref()), Some("Move to"));
        assert!(matches!(level, [MenuItem::Action(action)] if action.id == "inbox"));

        // The open level's own rows changing still rejects it.
        let moved = tree(&["archive"], &["red"]);
        assert!(visible_level(&moved, &path).is_none());
        assert!(visible_level(&moved, &path[..1]).is_some());
    }

    #[test]
    fn settling_backs_out_only_as_far_as_the_tree_changed() {
        let original = tree(&["inbox"], &["red"]);
        let path = path_to_move(&original);

        let mut levels = path.clone();
        let mut highlight = Some(0);
        let retagged = tree(&["inbox"], &["red", "blue"]);
        assert_eq!(settle_levels(&retagged, &mut levels, &mut highlight), None);
        assert_eq!((levels.len(), highlight), (2, Some(0)));

        // Move to's rows changed: back to Organize, keyboard on Move to,
        // which is still a branch in the same place.
        let moved = tree(&["archive"], &["red"]);
        let left = settle_levels(&moved, &mut levels, &mut highlight);
        assert_eq!(left, Some(path[1]));
        assert_eq!((levels.len(), highlight), (1, Some(1)));

        // Organize itself gone: back to the root, with nothing lit rather
        // than a stranger in Organize's place.
        let mut levels = path.clone();
        let mut highlight = Some(0);
        let flattened = vec![
            MenuItem::action("open", "Open"),
            MenuItem::action("delete", "Delete").danger(),
        ];
        let left = settle_levels(&flattened, &mut levels, &mut highlight);
        assert_eq!(left, Some(path[0]));
        assert!(levels.is_empty());
        assert_eq!(highlight, None);
    }

    #[test]
    fn arrows_in_a_level_with_nothing_reachable_go_nowhere() {
        for key in [Key::Down, Key::Home, Key::Up, Key::End] {
            assert_eq!(step_highlight(key, None, 0), None);
            assert_eq!(step_highlight(key, Some(3), 0), None);
        }
        let inert = vec![
            MenuItem::header("Recent"),
            MenuItem::separator(),
            MenuItem::action("none", "Nothing yet").disabled(),
        ];
        let reachable = reachable_indices(&inert);
        assert!(reachable.is_empty());
        assert_eq!(
            menu_command(Key::Down, None, &menu_commands(&inert, &reachable)),
            None
        );
        assert_eq!(
            menu_command(Key::Home, Some(0), &menu_commands(&inert, &reachable)),
            None
        );
        assert_eq!(
            menu_command(Key::Activate, Some(0), &menu_commands(&inert, &reachable)),
            None
        );

        assert_eq!(step_highlight(Key::Down, None, 3), Some(0));
        assert_eq!(step_highlight(Key::Up, None, 3), Some(2));
    }

    /// Left is "back" and Escape is "back, or away": at the root only
    /// Escape closes the menu.
    #[test]
    fn left_and_escape_go_back_and_only_escape_closes_the_root() {
        let items = tree(&["inbox"], &["red"]);
        let reachable = reachable_indices(&items);
        assert_eq!(
            menu_command(Key::Left, None, &menu_commands(&items, &reachable)),
            Some(MenuCommand::Back {
                close_at_root: false
            })
        );
        assert_eq!(
            menu_command(Key::Dismiss, None, &menu_commands(&items, &reachable)),
            Some(MenuCommand::Back {
                close_at_root: true
            })
        );
        assert_eq!(
            menu_command(Key::Right, Some(1), &menu_commands(&items, &reachable)),
            Some(MenuCommand::Enter {
                row: 1,
                at: 1,
                identity: branch(&items[1], 1, 1).identity,
            })
        );
        assert_eq!(
            menu_command(Key::Activate, Some(0), &menu_commands(&items, &reachable)),
            Some(MenuCommand::Run("open"))
        );
        assert_eq!(
            menu_command(Key::Right, Some(0), &menu_commands(&items, &reachable)),
            None
        );
    }

    #[test]
    fn navigation_skips_inert_rows_but_enters_enabled_submenus() {
        let items = vec![
            MenuItem::header("Files"),
            MenuItem::action("open", "Open"),
            MenuItem::separator(),
            MenuItem::action("closed", "Closed").disabled(),
            MenuItem::submenu("Organize", vec![MenuItem::action("move", "Move")]),
            MenuItem::submenu("Unavailable", vec![]).disabled(),
        ];
        assert_eq!(reachable_indices(&items), vec![1, 4]);
    }

    #[test]
    fn long_levels_scroll_and_nested_levels_make_room_for_back() {
        let short = vec![MenuItem::action("open", "Open")];
        assert_eq!(menu_height(&short, true) - menu_height(&short, false), 33.0);
        let long: Vec<MenuItem> = (0..40).map(|_| MenuItem::header("Section")).collect();
        assert_eq!(menu_height(&long, false), super::MENU_MAX_HEIGHT);
    }

    /// Navigation accepts stationary repeated clicks after settling; actions
    /// still reject the tail of a double-click. Moving levels accept neither.
    #[test]
    fn repeated_navigation_settles_without_requiring_pointer_movement() {
        let mut state = ControlState::new();
        state.open_menu("row", gpui::point(gpui::px(0.0), gpui::px(0.0)), "");
        let opening = state.menu_opened_at().expect("open");
        assert!(takes_click(&state, opening, 1, RowClick::Activate));
        assert!(!takes_click(&state, opening, 2, RowClick::Activate));

        state.enter_menu(1, 1, 7, false);
        assert!(!takes_click(&state, opening, 1, RowClick::Activate));
        assert!(!takes_click(&state, opening, 2, RowClick::Navigate));
        state.set_time_scale(0.001);
        std::thread::sleep(std::time::Duration::from_millis(2));
        assert!(takes_click(&state, opening, 1, RowClick::Activate));
        assert!(!takes_click(&state, opening, 2, RowClick::Activate));
        assert!(takes_click(&state, opening, 2, RowClick::Navigate));
        assert!(state.back_menu());
        assert!(!takes_click(&state, opening, 3, RowClick::Navigate));
        std::thread::sleep(std::time::Duration::from_millis(2));
        assert!(takes_click(&state, opening, 3, RowClick::Navigate));
        state.close_menu();
        assert!(!takes_click(&state, opening, 4, RowClick::Navigate));
    }

    /// The panel's height is worked out from the same constants the rows
    /// are drawn at, so the two cannot drift apart.
    #[test]
    fn menu_height_counts_rows_at_their_drawn_heights() {
        let chrome = 2.0 * (super::MENU_PADDING + 1.0);
        let one = |item: MenuItem| menu_height(&[item], false) - chrome;
        assert_eq!(one(MenuItem::separator()), 7.0);
        assert_eq!(one(MenuItem::header("Recent")), 22.0);
        assert_eq!(one(MenuItem::action("open", "Open")), super::ITEM_HEIGHT);
        assert_eq!(super::SEPARATOR_HEIGHT, 2.0 * super::SEPARATOR_GAP + 1.0);
    }

    /// The panel takes its width from every level, so a row deep in a
    /// branch the reader has not opened still counts.
    #[test]
    fn the_width_is_taken_from_every_level() {
        let items = tree(&["inbox"], &["a-very-long-tag"]);
        let ids: Vec<_> = every_row(&items)
            .into_iter()
            .filter_map(|item| match item {
                MenuItem::Action(action) => Some(action.id),
                _ => None,
            })
            .collect();
        for id in ["open", "pin", "inbox", "a-very-long-tag"] {
            assert!(ids.contains(&id), "{id} missing");
        }
    }

    #[test]
    fn a_short_window_cuts_the_panel_to_fit() {
        assert_eq!(fit_to_window(520.0, None), 520.0);
        assert_eq!(fit_to_window(520.0, Some(900.0)), 520.0);
        assert_eq!(
            fit_to_window(520.0, Some(300.0)),
            300.0 - 2.0 * super::VIEWPORT_MARGIN
        );
        // A window too small for anything still leaves one row's worth.
        assert_eq!(fit_to_window(520.0, Some(10.0)), 38.0);
    }

    /// An icon on any row gives the whole level an icon column; a level
    /// without one keeps its labels flush.
    #[test]
    fn an_icon_anywhere_in_a_level_opens_the_icon_column() {
        let icon = MenuIcon::new(|_, _| gpui::IntoElement::into_any_element(gpui::Empty));
        let plain: Vec<MenuItem> = vec![
            MenuItem::action("open", "Open"),
            MenuItem::submenu(
                "Move to",
                vec![MenuItem::action("inbox", "Inbox").icon(icon)],
            ),
        ];
        assert!(!MenuItem::any_icon(&plain));
        assert!(MenuItem::any_icon(children(&plain[1])));
        assert!(plain[1].icon_of().is_none());
        assert_eq!(plain[1].label(), Some("Move to"));
        assert_eq!(MenuItem::<&str>::separator().label(), None);
    }

    #[test]
    fn an_action_is_found_at_any_depth_to_relabel() {
        let mut items = tree(&["inbox"], &["red"]);
        assert!(MenuItem::action_mut(&mut items, |action| action.id == "none").is_none());
        let inbox =
            MenuItem::action_mut(&mut items, |action| action.id == "inbox").expect("nested");
        inbox.label = "Move to Inbox".into();
        let organize = children(&items[1]);
        let moved = children(&organize[1]);
        assert_eq!(moved[0].label(), Some("Move to Inbox"));
    }
}

#[cfg(test)]
#[path = "ownership_bench.rs"]
pub(crate) mod ownership_bench;