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
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
//! Things that float above the view: tooltips and a command palette, and
//! the search field with results that the palette is built from.

use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;
use std::rc::Rc;
use std::time::Instant;

use gpui::{
    AnyElement, AnyView, App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement,
    KeyDownEvent, MouseButton, MouseDownEvent, Point, Render, Rgba, ScrollHandle, SharedString,
    StyledText, Window, deferred, div, point, prelude::*, px,
};

use crate::controls::{WidgetContext, search_field};
use crate::easing::{ease_out_cubic, progress};
use crate::keyboard::{self, Dismiss, Key, Orientation};
use crate::lighting;
use crate::palette::Palette;
use crate::state::{
    COMBO_REVEAL, ComboId, ControlHost, ControlState, ListChange, MOVE, SWITCH_SLIDE, Tag,
};
use crate::text_input::{self as text, TextInput};

// ---- Tooltip ----------------------------------------------------------------

/// A tooltip's content: one line, optionally with an accelerator after it.
///
/// GPUI already owns the hard part, which is deciding when a tooltip should
/// appear and where it fits. This is only what it looks like, handed to
/// `.tooltip(..)` on any interactive element.
pub struct Tooltip {
    text: SharedString,
    shortcut: Option<SharedString>,
    palette: Palette,
}

/// What a tooltip says: a label, and optionally the shortcut after it.
///
/// A plain `&str` converts into one, so a control that takes a `Hint` can
/// be handed `"Undo"`; `Hint::new("Favourite").shortcut(display("secondary-d"))`
/// adds the accelerator. Purely a label: binding the key is the host's
/// business.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Hint {
    pub text: SharedString,
    pub shortcut: Option<SharedString>,
}

impl Hint {
    pub fn new(text: impl Into<SharedString>) -> Self {
        Self {
            text: text.into(),
            shortcut: None,
        }
    }

    /// The accelerator shown after the label.
    pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
        self.shortcut = Some(shortcut.into());
        self
    }

    /// Builds the callback `.tooltip(..)` wants.
    pub fn tooltip(self, palette: Palette) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static {
        move |_window, cx| {
            let hint = self.clone();
            cx.new(move |_cx| Tooltip {
                text: hint.text,
                shortcut: hint.shortcut,
                palette,
            })
            .into()
        }
    }
}

impl From<&str> for Hint {
    fn from(text: &str) -> Self {
        Hint::new(text.to_string())
    }
}

impl From<String> for Hint {
    fn from(text: String) -> Self {
        Hint::new(text)
    }
}

impl From<SharedString> for Hint {
    fn from(text: SharedString) -> Self {
        Hint::new(text)
    }
}

impl Tooltip {
    /// Builds the callback `.tooltip(..)` wants, for any interactive element
    /// of the host's own. GPUI allows one tooltip per element.
    ///
    /// ```ignore
    /// div().id("thumbnail").child(image).tooltip(Tooltip::text("Open", palette))
    /// ```
    pub fn text(
        text: impl Into<SharedString>,
        palette: Palette,
    ) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static {
        Hint::new(text).tooltip(palette)
    }

    /// The same, with an accelerator shown after the label.
    pub fn with_shortcut(
        text: impl Into<SharedString>,
        shortcut: impl Into<SharedString>,
        palette: Palette,
    ) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static {
        Hint::new(text).shortcut(shortcut).tooltip(palette)
    }
}

impl Render for Tooltip {
    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
        let palette = self.palette;
        let dark = palette.is_dark;
        let fill = if dark {
            palette.soft_fill
        } else {
            palette.field_surface
        };
        div()
            .px(px(8.0))
            .py(px(4.0))
            .flex()
            .items_center()
            .gap(px(8.0))
            .rounded(px(5.0))
            .bg(fill)
            .border_1()
            .border_color(lighting::rim(fill, dark))
            .shadow(lighting::panel(dark))
            .text_size(px(11.5))
            .text_color(palette.text_primary)
            .whitespace_nowrap()
            .child(self.text.clone())
            .children(
                self.shortcut
                    .clone()
                    .map(|shortcut| div().text_color(palette.text_secondary).child(shortcut)),
            )
    }
}

// ---- Command palette --------------------------------------------------------

/// One entry in a [`command_palette`].
#[derive(Clone, Debug)]
pub struct Command {
    /// Comes back to the activation callback. Unique within one list: it
    /// names the row's element and the record its motion is kept under.
    pub id: SharedString,
    pub label: SharedString,
    /// Where the command lives, shown quietly before the label.
    pub group: Option<SharedString>,
    pub shortcut: Option<SharedString>,
}

impl Command {
    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            group: None,
            shortcut: None,
        }
    }

    pub fn group(mut self, group: impl Into<SharedString>) -> Self {
        self.group = Some(group.into());
        self
    }

    pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
        self.shortcut = Some(shortcut.into());
        self
    }
}

/// One result from a host-ranked search. Its position is already its rank:
/// [`ranked_search_list`] and [`ranked_command_palette`] never filter or
/// sort it, and [`rank_results`] is there for a host that wants the
/// toolkit's fuzzy ranking rather than its own.
///
/// The host may replace the slice at any time, as each source finishes
/// loading. Ids must be unique within one list and stable across updates.
/// Until the person moves the highlight it stays on the first row, so a
/// better match arriving takes it. Once they have moved it, it stays on the
/// result they moved it to, found by its id, so a source that lands after
/// they have arrowed down never leaves Enter on whatever now fills that
/// row. A new query puts it back on the first row either way.
#[derive(Clone, Debug)]
pub struct SearchResult {
    pub id: SharedString,
    pub label: SharedString,
    /// A second, quieter line under the label.
    pub detail: Option<SharedString>,
    /// Shown once before each run of results from the same source.
    pub section: Option<SharedString>,
    pub shortcut: Option<SharedString>,
    leading: Option<Leading>,
    /// A [`Command`]'s group, which a [`command_list`] shows before the
    /// label rather than as a heading: commands are ranked across groups,
    /// so one group's commands seldom arrive in a run.
    group: Option<SharedString>,
}

/// The host's drawing for a result's leading slot, in a type of its own so
/// that [`SearchResult`] can still be `Debug`.
#[derive(Clone)]
struct Leading(Rc<dyn Fn(Palette) -> AnyElement>);

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

impl SearchResult {
    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            detail: None,
            section: None,
            shortcut: None,
            leading: None,
            group: None,
        }
    }

    pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    pub fn section(mut self, section: impl Into<SharedString>) -> Self {
        self.section = Some(section.into());
        self
    }

    pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
        self.shortcut = Some(shortcut.into());
        self
    }

    /// A palette-aware visual in the fixed leading slot, such as an icon or
    /// favicon. The host supplies its own drawing; the toolkit sizes and
    /// aligns the slot across the list.
    pub fn leading<E: IntoElement + 'static>(
        mut self,
        render: impl Fn(Palette) -> E + 'static,
    ) -> Self {
        self.leading = Some(Leading(Rc::new(move |palette| {
            render(palette).into_any_element()
        })));
        self
    }
}

/// A command as a result row, so commands and results share one drawing.
fn command_result(command: &Command) -> SearchResult {
    SearchResult {
        id: command.id.clone(),
        label: command.label.clone(),
        detail: None,
        section: None,
        shortcut: command.shortcut.clone(),
        leading: None,
        group: command.group.clone(),
    }
}

/// How well a query matches a candidate, or `None` if it does not.
///
/// Subsequence matching, the way every fuzzy finder works: the query's
/// characters must appear in order, but not together. The score rewards
/// matches that start a word and matches that run on from the last one, so
/// "opf" ranks "Open File" above "Optional Prefix".
pub fn fuzzy_score(query: &str, candidate: &str) -> Option<i32> {
    if query.chars().all(char::is_whitespace) {
        return Some(0);
    }
    fuzzy_score_normalized(&query.to_lowercase(), candidate)
}

fn fuzzy_score_normalized(query: &str, candidate: &str) -> Option<i32> {
    if query.chars().all(char::is_whitespace) {
        return Some(0);
    }
    let candidate_lower = candidate.to_lowercase();
    let mut haystack = candidate_lower.chars().enumerate();
    let mut score = 0i32;
    let mut last_index: Option<usize> = None;
    let mut previous = None;

    for needle in query.chars() {
        if needle.is_whitespace() {
            continue;
        }
        loop {
            let (index, ch) = haystack.next()?;
            let starts_word = previous.is_none_or(|previous: char| {
                previous.is_whitespace() || previous == '-' || previous == '_'
            });
            previous = Some(ch);
            if ch != needle {
                continue;
            }
            // Starting a word is the strongest signal that this is the
            // match the person meant.
            score += if starts_word { 12 } else { 2 };
            if last_index == Some(index.saturating_sub(1)) {
                score += 6;
            }
            last_index = Some(index);
            break;
        }
    }
    // Among equally good matches, the shortest candidate is the one that
    // most nearly *is* the query.
    Some(score - (candidate.chars().count() as i32 / 8))
}

/// Commands matching a query, best first. Ties keep their original order,
/// so a host's own ranking survives where the score cannot separate two.
pub fn fuzzy_filter(query: &str, commands: &[Command]) -> Vec<Command> {
    matching_commands(query, commands)
        .map(Clone::clone)
        .collect()
}

// Keep filtering borrowed until the caller chooses its final representation:
// the command bar needs SearchResults, not an intermediate owned command list.
fn matching_commands<'a>(
    query: &str,
    commands: &'a [Command],
) -> impl Iterator<Item = &'a Command> {
    let empty = query.chars().all(char::is_whitespace);
    let mut scored: Vec<(i32, usize, &Command)> = if empty {
        Vec::new()
    } else {
        let query = query.to_lowercase();
        commands
            .iter()
            .enumerate()
            .filter_map(|(index, command)| {
                let haystack = match &command.group {
                    Some(group) => Cow::Owned(format!("{group} {}", command.label)),
                    None => Cow::Borrowed(command.label.as_ref()),
                };
                fuzzy_score_normalized(&query, &haystack).map(|score| (score, index, command))
            })
            .collect()
    };
    // The original index makes this ordering total while preserving ties.
    scored.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
    let original = if empty { commands } else { &[] };
    original
        .iter()
        .chain(scored.into_iter().map(|(_, _, command)| command))
}

pub(crate) fn command_results(query: &str, commands: &[Command]) -> Vec<SearchResult> {
    matching_commands(query, commands)
        .map(command_result)
        .collect()
}

/// Results matching a query, best first within each section, for a host
/// that would rather rank with [`fuzzy_score`] than with its own measure
/// before handing them to [`ranked_search_list`] or
/// [`ranked_command_palette`].
///
/// Each section appears once, its results together under one heading, and
/// sections are ordered by their best result: ranking across every source
/// at once would scatter them into a heading per row. The label, the detail
/// and the section are all searched, so "book" finds everything under
/// Bookmarks. Ties keep the order the sources were assembled in, and an
/// empty query keeps source order within each section and puts sections in
/// their first-seen order.
pub fn rank_results(query: &str, results: &[SearchResult]) -> Vec<SearchResult> {
    let empty = query.chars().all(char::is_whitespace);
    let query = query.to_lowercase();
    // Scored on the label alone: it is what the person reads and
    // abbreviates, and the score's length penalty would otherwise let a
    // long detail line push a result down. A result that matches only
    // through its detail or section still qualifies, after every result
    // whose label matched, in the order it came.
    let mut searchable = String::new();
    let mut rank = |result: &SearchResult| -> Option<Option<i32>> {
        if let Some(score) = fuzzy_score_normalized(&query, &result.label) {
            return Some(Some(score));
        }
        if result.detail.is_none() && result.section.is_none() {
            return None;
        }
        let capacity = result.label.len()
            + [&result.detail, &result.section]
                .into_iter()
                .flatten()
                .map(|part| part.len() + 1)
                .sum::<usize>();
        searchable.clear();
        searchable.reserve(capacity);
        searchable.push_str(&result.label);
        for part in [&result.detail, &result.section].into_iter().flatten() {
            searchable.push(' ');
            searchable.push_str(part);
        }
        fuzzy_score_normalized(&query, &searchable).map(|_| None)
    };
    type Run<'a> = Vec<(Option<i32>, &'a SearchResult)>;
    let mut sections: Vec<(Option<&str>, Run)> = Vec::new();
    let mut positions: HashMap<Option<&str>, usize> = HashMap::new();
    for result in results {
        let Some(rank) = (if empty { Some(Some(0)) } else { rank(result) }) else {
            continue;
        };
        let section = result.section.as_deref();
        let index = *positions.entry(section).or_insert_with(|| {
            let index = sections.len();
            sections.push((section, Vec::new()));
            index
        });
        sections[index].1.push((rank, result));
    }
    // Empty queries already have source order. Stable sorts keep that order
    // for ties when a nonempty query actually needs ranking.
    if !empty {
        for (_, run) in &mut sections {
            run.sort_by_key(|(rank, _)| std::cmp::Reverse(*rank));
        }
        sections.sort_by_key(|(_, run)| std::cmp::Reverse(run[0].0));
    }
    sections
        .into_iter()
        .flat_map(|(_, run)| run)
        .map(|(_, result)| result.clone())
        .collect()
}

/// Which line of a row is being emphasised.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Line {
    Label,
    Detail,
}

/// Byte ranges to emphasise in displayed text, for each word of the query.
///
/// In a label, a contiguous run of the word anywhere reads best, and
/// failing one the letters of a fuzzy abbreviation are marked wherever they
/// fall: the label is what the person was abbreviating. A detail line is
/// not, so there only a contiguous run that starts a word counts — "in"
/// picks out "in" but not the middle of "morning", and scattered letters
/// that happen to come in the right order are not a match at all.
fn matched_ranges(text: &str, query: &str, line: Line) -> Vec<Range<usize>> {
    if query.trim().is_empty() {
        return Vec::new();
    }
    let chars: Vec<(usize, char)> = text.char_indices().collect();
    let same = |a: char, b: char| a.to_lowercase().eq(b.to_lowercase());
    let mut ranges: Vec<Range<usize>> = Vec::new();
    let byte_at = |index: usize| chars.get(index).map_or(text.len(), |ch| ch.0);
    for word in query.split_whitespace() {
        let needle: Vec<char> = word.chars().collect();
        let starts_word = |start: usize| start == 0 || !chars[start - 1].1.is_alphanumeric();
        let whole = (0..=chars.len().saturating_sub(needle.len())).find(|&start| {
            start + needle.len() <= chars.len()
                && (line == Line::Label || starts_word(start))
                && needle
                    .iter()
                    .enumerate()
                    .all(|(offset, &ch)| same(chars[start + offset].1, ch))
        });
        if let Some(start) = whole {
            ranges.push(byte_at(start)..byte_at(start + needle.len()));
        } else if line == Line::Label {
            // A failed abbreviation must not leave its matched prefix highlighted.
            let checkpoint = ranges.len();
            let mut from = 0;
            for &ch in &needle {
                let Some(index) = (from..chars.len()).find(|&i| same(chars[i].1, ch)) else {
                    ranges.truncate(checkpoint);
                    break;
                };
                ranges.push(byte_at(index)..byte_at(index + 1));
                from = index + 1;
            }
        }
    }
    ranges.sort_unstable_by_key(|range| range.start);
    let mut merged = 0;
    for index in 0..ranges.len() {
        let range = ranges[index].clone();
        if merged > 0 && range.start <= ranges[merged - 1].end {
            ranges[merged - 1].end = ranges[merged - 1].end.max(range.end);
        } else {
            ranges[merged] = range;
            merged += 1;
        }
    }
    ranges.truncate(merged);
    ranges
}

fn emphasised(text: &SharedString, query: &str, line: Line) -> StyledText {
    StyledText::new(text.clone()).with_highlights(
        matched_ranges(text, query, line)
            .into_iter()
            .map(|range| (range, FontWeight::SEMIBOLD.into())),
    )
}

/// Height of one row in a [`command_list`], and of any result row without
/// a detail line.
pub const COMMAND_ROW_HEIGHT: f32 = 30.0;
/// Height of a result row with a detail line under its label.
const DETAIL_ROW_HEIGHT: f32 = 44.0;
const SECTION_HEIGHT: f32 = 20.0;
const ROW_GAP: f32 = 1.0;
const ROW_INSET: f32 = 9.0;
const LEADING_SIZE: f32 = 20.0;
const ROW_SPACING: f32 = 8.0;
/// The tallest an inline result list grows before it scrolls.
const INLINE_RESULT_MAX_HEIGHT: f32 = 300.0;
/// The same for the list in a palette, which has the window to itself.
pub(crate) const PALETTE_RESULT_MAX_HEIGHT: f32 = 340.0;

struct RowPlacement {
    /// Whether a section heading goes above this row.
    heading: bool,
    /// Which run of this section the heading belongs to.
    heading_run: usize,
    top: f32,
    height: f32,
}

/// Where each result sits in its list. Worked out from the row metrics
/// rather than read back from the last layout, so a highlight that moved
/// with its result can be scrolled to in the same frame the results
/// changed, before anything has been laid out.
fn row_layout(results: &[SearchResult]) -> Vec<RowPlacement> {
    let mut previous: Option<&str> = None;
    let mut runs: HashMap<&str, usize> = HashMap::new();
    let mut top = 0.0;
    results
        .iter()
        .map(|result| {
            let section = result.section.as_deref();
            let heading = section.is_some() && section != previous;
            previous = section;
            let heading_run = if heading {
                let count = runs
                    .entry(section.expect("a heading has a section"))
                    .or_default();
                let run = *count;
                *count += 1;
                run
            } else {
                0
            };
            if heading {
                top += SECTION_HEIGHT + ROW_GAP;
            }
            let height = if result.detail.is_some() {
                DETAIL_ROW_HEIGHT
            } else {
                COMMAND_ROW_HEIGHT
            };
            let placement = RowPlacement {
                heading,
                heading_run,
                top,
                height,
            };
            top += height + ROW_GAP;
            placement
        })
        .collect()
}

/// How far a row or heading has arrived. A list that has just appeared
/// arrives whole, with whatever brought it. Once it is up, rows the query
/// lets through fade in at their place and rows that stay slide to their
/// new one, so typing reads as the list being sifted rather than replaced.
fn arrival(state: &ControlState, key: Tag, fresh: bool) -> f32 {
    if fresh {
        state.tween(key, 1.0, SWITCH_SLIDE)
    } else {
        state.tween_from(key, 0.0, 1.0, SWITCH_SLIDE)
    }
}

/// The rows of a result list in the order given, and where each result
/// sits. Section names are quiet headings rather than rows; only results
/// take a keyboard step. `emphasis` is the text to pick out in each row.
fn result_rows<V: ControlHost>(
    id: &'static str,
    emphasis: &str,
    results: &[SearchResult],
    highlighted: usize,
    ctx: WidgetContext<'_, '_, '_, V>,
    on_activate: &Activate<V>,
) -> (Vec<AnyElement>, Vec<Range<f32>>) {
    let WidgetContext { palette, view, cx } = ctx;
    let state = view.control_state();
    let fresh = !state.present(id);
    let has_leading = results.iter().any(|result| result.leading.is_some());
    let mut elements: Vec<AnyElement> = Vec::with_capacity(results.len());
    let mut extents = Vec::with_capacity(results.len());
    for (index, (result, placement)) in results.iter().zip(row_layout(results)).enumerate() {
        if placement.heading
            && let Some(section) = &result.section
        {
            // Keyed by the section, and by which of its runs this is should
            // a host split one, rather than by the result under it: whichever
            // result leads the run, it is the same heading, and it fades in
            // once and slides with the rows.
            let key = |part: &'static str| Tag::new((id, part, section, placement.heading_run));
            let shown = arrival(state, key("section-shown"), fresh);
            let top = placement.top - SECTION_HEIGHT - ROW_GAP;
            let offset = state.tween(key("section-place"), top, MOVE) - top;
            elements.push(section_heading(
                section,
                has_leading,
                shown,
                offset,
                palette,
            ));
        }
        let cx: &mut Context<V> = &mut *cx;
        let look = RowLook {
            active: index == highlighted,
            has_leading,
            fresh,
            palette,
        };
        elements.push(result_row(
            id,
            result,
            emphasis,
            &placement,
            look,
            state,
            cx,
            on_activate.clone(),
        ));
        extents.push(placement.top..placement.top + placement.height);
    }
    (elements, extents)
}

/// Keep one viewport of spare rows on either side, so a wheel step or a
/// short place tween never exposes an unbuilt edge. The scroll container's
/// full height is kept separately from these visible children.
fn visible_result_range(placements: &[RowPlacement], offset: f32, viewport: f32) -> Range<usize> {
    let viewport = viewport.max(1.0);
    let scroll_top = (-offset).max(0.0);
    let start = scroll_top - viewport - SECTION_HEIGHT;
    let end = scroll_top + 2.0 * viewport + SECTION_HEIGHT;
    placements.partition_point(|row| row.top + row.height < start)
        ..placements.partition_point(|row| row.top <= end)
}

#[allow(clippy::too_many_arguments)]
fn visible_result_rows<V: ControlHost>(
    id: &'static str,
    emphasis: &str,
    results: &[SearchResult],
    placements: &[RowPlacement],
    visible: Range<usize>,
    highlighted: usize,
    ctx: WidgetContext<'_, '_, '_, V>,
    on_activate: &Activate<V>,
) -> Vec<AnyElement> {
    let WidgetContext { palette, view, cx } = ctx;
    let state = view.control_state();
    let fresh = !state.present(id);
    let has_leading = results.iter().any(|result| result.leading.is_some());
    let mut elements = Vec::with_capacity(2 * visible.len());
    for index in visible {
        let (result, placement) = (&results[index], &placements[index]);
        if placement.heading
            && let Some(section) = &result.section
        {
            let key = |part: &'static str| Tag::new((id, part, section, placement.heading_run));
            let shown = arrival(state, key("section-shown"), fresh);
            let top = placement.top - SECTION_HEIGHT - ROW_GAP;
            let offset = state.tween(key("section-place"), top, MOVE) - top;
            elements.push(
                div()
                    .absolute()
                    .top(px(top))
                    .left_0()
                    .right_0()
                    .child(section_heading(
                        section,
                        has_leading,
                        shown,
                        offset,
                        palette,
                    ))
                    .into_any_element(),
            );
        }
        let look = RowLook {
            active: index == highlighted,
            has_leading,
            fresh,
            palette,
        };
        elements.push(
            div()
                .absolute()
                .top(px(placement.top))
                .left_0()
                .right_0()
                .child(result_row(
                    id,
                    result,
                    emphasis,
                    placement,
                    look,
                    state,
                    cx,
                    on_activate.clone(),
                ))
                .into_any_element(),
        );
    }
    elements
}

fn section_heading(
    section: &SharedString,
    has_leading: bool,
    shown: f32,
    offset: f32,
    palette: Palette,
) -> AnyElement {
    // Over the labels rather than the icons, so a heading reads as the
    // title of the run of results under it.
    let inset = if has_leading {
        ROW_INSET + LEADING_SIZE + ROW_SPACING
    } else {
        ROW_INSET
    };
    div()
        .relative()
        .top(px(offset))
        .h(px(SECTION_HEIGHT))
        .flex_none()
        .px(px(inset))
        .flex()
        .items_center()
        .opacity(shown)
        .text_size(px(11.5))
        .font_weight(FontWeight::MEDIUM)
        .text_color(palette.text_secondary)
        .child(section.clone())
        .into_any_element()
}

#[derive(Clone, Copy)]
struct RowLook {
    active: bool,
    has_leading: bool,
    fresh: bool,
    palette: Palette,
}

/// One row of a result list or a command list: the same chrome for both,
/// so a command palette and a results palette cannot drift apart.
#[allow(clippy::too_many_arguments)]
fn result_row<V: ControlHost>(
    id: &'static str,
    result: &SearchResult,
    emphasis: &str,
    placement: &RowPlacement,
    look: RowLook,
    state: &ControlState,
    cx: &mut Context<V>,
    on_activate: Activate<V>,
) -> AnyElement {
    let RowLook {
        active,
        has_leading,
        fresh,
        palette,
    } = look;
    let key = |part: &'static str| Tag::new((id, part, &result.id));
    // Keyed by the result rather than the row, so the highlight and the
    // fade belong to the result as it moves.
    let on = state.blend(key("lit"), active, SWITCH_SLIDE);
    // Secondary ink is for unselected rows; all selected text needs
    // the foreground paired with the accent surface underneath it.
    let secondary = crate::color::lerp(palette.text_secondary, palette.soft_label, on);
    let shown = arrival(state, key("shown"), fresh);
    let offset = state.tween(key("place"), placement.top, MOVE) - placement.top;
    let picked = result.id.clone();
    div()
        .id(ElementId::Name(format!("{id}-result-{}", result.id).into()))
        .relative()
        .top(px(offset))
        .opacity(shown)
        .h(px(placement.height))
        .flex_none()
        .w_full()
        .px(px(ROW_INSET))
        .flex()
        .items_center()
        .gap(px(ROW_SPACING))
        .rounded(px(5.0))
        .cursor_pointer()
        .text_size(px(12.5))
        .text_color(crate::color::lerp(
            palette.text_primary,
            palette.soft_label,
            on,
        ))
        .when(on > 0.01, |el| {
            el.bg(lighting::lit_at(palette.soft_fill, 0.08, on))
        })
        .when(!active, |el| {
            el.hover(move |style| style.bg(palette.row_hover))
        })
        .on_click(cx.listener(move |this, _event, window, cx| {
            on_activate(this, picked.clone(), window, cx);
            cx.notify();
        }))
        .when(has_leading, |el| {
            el.child(
                div()
                    .size(px(LEADING_SIZE))
                    .flex_none()
                    .flex()
                    .items_center()
                    .justify_center()
                    .children(result.leading.as_ref().map(|leading| (leading.0)(palette))),
            )
        })
        .children(
            result
                .group
                .clone()
                .map(|group| div().flex_none().text_color(secondary).child(group)),
        )
        .child(
            div()
                .flex_1()
                .min_w(px(0.0))
                .flex()
                .flex_col()
                .gap(px(2.0))
                .child(
                    div()
                        .truncate()
                        .child(emphasised(&result.label, emphasis, Line::Label)),
                )
                .children(result.detail.as_ref().map(|detail| {
                    div()
                        .truncate()
                        .text_size(px(11.5))
                        .text_color(secondary)
                        .child(emphasised(detail, emphasis, Line::Detail))
                })),
        )
        .children(result.shortcut.clone().map(|shortcut| {
            div()
                .flex_none()
                .text_size(px(11.5))
                .text_color(secondary)
                .child(shortcut)
        }))
        .into_any_element()
}

/// A list of matching commands, one row each, with one highlighted.
///
/// The rows on their own, for a host that filters and moves the highlight
/// itself; [`search_list`] is these under a search field with the keys
/// wired, and [`command_palette`] is that in an overlay. Each row reports
/// its `Command::id` when clicked.
pub fn command_list<V: ControlHost>(
    id: &'static str,
    matches: &[Command],
    highlighted: usize,
    ctx: WidgetContext<'_, '_, '_, V>,
    on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Div {
    // A concrete `Div` rather than `impl IntoElement`: in the 2024 edition an
    // opaque return captures every input lifetime, which would keep `cx`
    // borrowed for as long as the list lived and stop the caller building
    // anything else with it.
    let results: Vec<SearchResult> = matches.iter().map(command_result).collect();
    let on_activate: Activate<V> = Rc::new(on_activate);
    let (rows, _) = result_rows(id, "", &results, highlighted, ctx, &on_activate);
    // Clipped, so a row sliding up from where it was emerges from the list's
    // edge instead of crossing whatever sits below it.
    div()
        .flex()
        .flex_col()
        .gap(px(ROW_GAP))
        .overflow_hidden()
        .children(rows)
}

/// What a palette panel does on Escape.
pub(crate) type Dismissed<V> = Rc<dyn Fn(&mut V, &mut Window, &mut Context<V>)>;

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

/// A search field with the rows that match it underneath, and the keys
/// between the two: Up and Down move the highlight, Enter picks it.
///
/// The host owns the query input and the items; this filters the items by
/// the query with [`fuzzy_filter`], keeps the keyboard's row in
/// [`ControlState`] under `id`, and reports the picked
/// `Command::id` — from a click and from Enter alike. The keys arrive as the
/// field's own actions: a single-line field has no use for Up, Down or an
/// Enter it has nothing to submit to, so it passes them on, and they are
/// caught here on the element that holds the field — which is also why they
/// only work while the field has the keyboard.
#[allow(clippy::too_many_arguments)]
pub fn search_list<V: ControlHost>(
    id: &'static str,
    query: &Entity<TextInput>,
    items: &[Command],
    mut ctx: WidgetContext<'_, '_, '_, V>,
    window: &Window,
    on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Div {
    let palette = ctx.palette;
    let on_activate: Activate<V> = Rc::new(on_activate);
    let text = query.read(ctx.cx).shared_text();
    let matches = fuzzy_filter(&text, items);
    let ids: Rc<[SharedString]> = matches.iter().map(|command| command.id.clone()).collect();
    let (highlighted, _) = ctx.view.control_state().follow_list(id, &text, &ids);
    let rows = {
        let on_activate = on_activate.clone();
        command_list(
            id,
            &matches,
            highlighted,
            ctx.reborrow(),
            move |view, id, window, cx| on_activate(view, id, window, cx),
        )
    };
    let cx: &mut Context<V> = &mut *ctx.cx;
    let list = div()
        .flex()
        .flex_col()
        .gap(px(6.0))
        .child(search_field(id, query, palette, window, cx))
        .child(rows);
    list_keys(list, id, ids, None, cx, on_activate)
}

/// A search field over results the host has already filtered and ranked,
/// in a list that scrolls under the field once it is taller than a few
/// rows. The keys work as in [`search_list`], except that Page Up and Page
/// Down move a viewport at a time; section headings take no keyboard step,
/// and the highlighted row is kept in view.
///
/// The host may replace `results` at any time. A new query puts the
/// highlight back on the first result and the list back at its top. Results
/// that change under the same query leave an untouched highlight on the
/// first row, and keep one the person has moved on the result they moved it
/// to, by id, scrolling to keep it in view — see [`SearchResult`].
///
/// `start` and `end` are the colours of the surface under the list's top
/// and bottom edges, which its edge fades land on, as for
/// [`scroll_fades`](crate::scroll_fades); the list's viewport is
/// [`ControlState::scroll`](crate::ControlState::scroll)`((id, "list"))`,
/// whose bounds say where those edges are. `id` identifies the list in
/// [`ControlState`], as for [`search_list`].
#[allow(clippy::too_many_arguments)]
pub fn ranked_search_list<V: ControlHost>(
    id: &'static str,
    query: &Entity<TextInput>,
    results: &[SearchResult],
    start: Rgba,
    end: Rgba,
    mut ctx: WidgetContext<'_, '_, '_, V>,
    window: &Window,
    on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Div {
    let palette = ctx.palette;
    let text = query.read(ctx.cx).shared_text();
    let on_activate: Activate<V> = Rc::new(on_activate);
    let list = result_list(
        id,
        &text,
        &text,
        results,
        INLINE_RESULT_MAX_HEIGHT,
        ctx.reborrow(),
        on_activate.clone(),
    );
    let state = ctx.view.control_state();
    let cx: &mut Context<V> = &mut *ctx.cx;
    let element = div()
        .flex()
        .flex_col()
        .gap(px(6.0))
        .child(search_field(id, query, palette, window, cx))
        .child(result_viewport(
            id,
            list.elements,
            &list.navigation,
            "No results",
            (start, end),
            palette,
            state,
        ));
    list_keys(
        element,
        id,
        list.ids,
        Some(list.navigation),
        cx,
        on_activate,
    )
}

/// A scrolling result list's rows, with what its keys need to move through
/// them.
pub(crate) struct ResultList {
    elements: Vec<AnyElement>,
    ids: Rc<[SharedString]>,
    navigation: Rc<ResultNavigation>,
}

/// Draws a scrolling result list, keeping the keyboard's row on its result
/// as the results change and the list's scroll in step with the row.
#[allow(clippy::too_many_arguments)]
pub(crate) fn result_list<V: ControlHost>(
    id: &'static str,
    query: &str,
    emphasis: &str,
    results: &[SearchResult],
    max_height: f32,
    ctx: WidgetContext<'_, '_, '_, V>,
    on_activate: Activate<V>,
) -> ResultList {
    let ids: Rc<[SharedString]> = results.iter().map(|result| result.id.clone()).collect();
    let state = ctx.view.control_state();
    let (highlighted, change) = state.follow_list(id, query, &ids);
    let scroll = state.scroll((id, "list"));
    let placements = row_layout(results);
    let rows = placements
        .iter()
        .map(|placement| placement.top..placement.top + placement.height)
        .collect();
    let navigation = Rc::new(ResultNavigation {
        scroll,
        rows,
        max_height,
    });
    match change {
        ListChange::Reset => navigation.scroll.set_offset(Point::default()),
        ListChange::Moved => navigation.reveal(highlighted),
        ListChange::Same => {}
    }
    let painted_height = f32::from(navigation.scroll.bounds().size.height);
    let viewport = if painted_height > 0.0 {
        painted_height
    } else {
        max_height
    };
    let visible = visible_result_range(
        &placements,
        f32::from(navigation.scroll.offset().y),
        viewport,
    );
    let elements = visible_result_rows(
        id,
        emphasis,
        results,
        &placements,
        visible,
        highlighted,
        ctx,
        &on_activate,
    );
    ResultList {
        elements,
        ids,
        navigation,
    }
}

/// A result list's rows in a viewport that scrolls under the query field,
/// which stays where it is.
fn result_viewport(
    id: &'static str,
    rows: Vec<AnyElement>,
    navigation: &ResultNavigation,
    empty_message: &'static str,
    (start, end): (Rgba, Rgba),
    palette: Palette,
    state: &ControlState,
) -> Div {
    let empty = navigation.rows.is_empty();
    div()
        .relative()
        .child(
            div()
                .id(ElementId::Name(format!("{id}-list").into()))
                .max_h(px(navigation.max_height))
                .flex()
                .flex_col()
                .overflow_y_scroll()
                .restrict_scroll_to_axis()
                .track_scroll(&navigation.scroll)
                .child(
                    div()
                        .relative()
                        // A flex child otherwise shrinks to the viewport,
                        // leaving the scroll handle with no distance to move.
                        .flex_none()
                        .w_full()
                        .h(px(navigation.content_height()))
                        .children(rows),
                )
                .when(empty, |el| {
                    el.child(
                        div()
                            .h(px(COMMAND_ROW_HEIGHT))
                            .px(px(ROW_INSET))
                            .flex()
                            .items_center()
                            .text_size(px(12.5))
                            .font_weight(FontWeight::NORMAL)
                            .text_color(palette.text_secondary)
                            .child(empty_message),
                    )
                }),
        )
        // A long list fades at the edge that has more past it, rather than
        // slicing a row in half.
        .children(crate::scroll::scroll_fades(
            state,
            id,
            &navigation.scroll,
            crate::scroll::ScrollAxis::Vertical,
            start,
            end,
        ))
}

/// Where a scrolling list's results are, for the keys that move through it.
struct ResultNavigation {
    scroll: ScrollHandle,
    /// Each result's extent, top to bottom, in the list's own coordinates.
    rows: Vec<Range<f32>>,
    max_height: f32,
}

impl ResultNavigation {
    fn content_height(&self) -> f32 {
        self.rows.last().map_or(0.0, |row| row.end)
    }

    fn viewport_height(&self) -> f32 {
        self.content_height().min(self.max_height)
    }

    /// Scrolls just far enough to bring result `index` clear of the edge
    /// fades.
    fn reveal(&self, index: usize) {
        let Some(row) = self.rows.get(index) else {
            return;
        };
        let viewport = self.viewport_height();
        let offset = self.scroll.offset();
        let next = revealed_offset(
            f32::from(offset.y),
            self.content_height() - viewport,
            0.0..viewport,
            row.clone(),
        );
        self.scroll.set_offset(point(offset.x, px(next)));
    }
}

/// The result a page away from `current`: the first whose top is a whole
/// viewport past it, or the end of the list.
fn page_target(key: Key, current: usize, rows: &[Range<f32>], viewport: f32) -> Option<usize> {
    let last = rows.len().checked_sub(1)?;
    let current = current.min(last);
    let page = viewport.max(1.0);
    match key {
        Key::PageDown => {
            let threshold = rows[current].start + page;
            Some(
                ((current + 1)..=last)
                    .find(|&index| rows[index].start >= threshold)
                    .unwrap_or(last),
            )
        }
        Key::PageUp => {
            let threshold = rows[current].start - page;
            Some(
                (0..current)
                    .rev()
                    .find(|&index| rows[index].start <= threshold)
                    .unwrap_or(0),
            )
        }
        _ => None,
    }
}

/// The scroll offset that shows `item` inside `viewport`, short of the
/// edge fades, moving as little as it can.
fn revealed_offset(offset: f32, max_offset: f32, viewport: Range<f32>, item: Range<f32>) -> f32 {
    let margin = crate::scroll::SCROLL_FADE.min((viewport.end - viewport.start) / 4.0);
    let wanted = if item.start + offset < viewport.start + margin {
        viewport.start + margin - item.start
    } else if item.end + offset > viewport.end - margin {
        viewport.end - margin - item.end
    } else {
        offset
    };
    wanted.clamp(-max_offset.max(0.0), 0.0)
}

fn navigate_list<V: ControlHost>(
    this: &mut V,
    id: &'static str,
    ids: &[SharedString],
    key: Key,
    navigation: Option<&ResultNavigation>,
    cx: &mut Context<V>,
) {
    let count = ids.len();
    let state = this.control_state();
    let here = state.list_position(id).min(count.saturating_sub(1));
    let moved = match (key, navigation) {
        (Key::PageUp | Key::PageDown, Some(navigation)) => {
            page_target(key, here, &navigation.rows, navigation.viewport_height())
        }
        // A list that does not scroll has no page to measure, so Page moves
        // ten, as it does on a slider.
        (Key::PageUp, None) => count.checked_sub(1).map(|_| here.saturating_sub(10)),
        (Key::PageDown, None) => count.checked_sub(1).map(|last| (here + 10).min(last)),
        _ => keyboard::step(key, Orientation::Vertical, here, count),
    };
    if let Some(moved) = moved
        && let Some(picked) = ids.get(moved)
    {
        state.highlight_list_item(id, moved, picked);
        if let Some(navigation) = navigation {
            navigation.reveal(moved);
        }
        cx.notify();
    }
}

/// Puts a filtering list's keys on the element that holds its query field:
/// Up and Down move the highlight through `ids`, Page Up and Page Down move
/// it a page, Enter picks the highlighted one.
fn list_keys<V: ControlHost, E: InteractiveElement>(
    element: E,
    id: &'static str,
    ids: Rc<[SharedString]>,
    navigation: Option<Rc<ResultNavigation>>,
    cx: &mut Context<V>,
    on_activate: Activate<V>,
) -> E {
    let step = {
        let ids = ids.clone();
        Rc::new(move |this: &mut V, key: Key, cx: &mut Context<V>| {
            navigate_list(this, id, &ids, key, navigation.as_deref(), cx);
        })
    };
    let step_down = step.clone();
    let step_page = step.clone();
    element
        .on_action(cx.listener(move |this, _: &text::Up, _window, cx| {
            step(this, Key::Up, cx);
        }))
        .on_action(cx.listener(move |this, _: &text::Down, _window, cx| {
            step_down(this, Key::Down, cx);
        }))
        // The field has no actions for Page Up and Page Down, so they
        // arrive as keys.
        .on_key_down(cx.listener(move |this, event: &KeyDownEvent, _window, cx| {
            if let Some(key @ (Key::PageUp | Key::PageDown)) = keyboard::key(event) {
                cx.stop_propagation();
                step_page(this, key, cx);
            }
        }))
        .on_action(cx.listener(move |this, _: &text::Enter, window, cx| {
            let here = this
                .control_state()
                .list_position(id)
                .min(ids.len().saturating_sub(1));
            if let Some(picked) = ids.get(here) {
                on_activate(this, picked.clone(), window, cx);
                cx.notify();
            }
        }))
}

/// When palette `id` opened, if it is the one open.
pub(crate) fn palette_opened_at(state: &ControlState, id: ComboId) -> Option<Instant> {
    state
        .palette_overlay
        .as_ref()
        .filter(|open| open.id == id)
        .map(|open| open.opened_at)
}

/// The host's callback, run after the palette closes, which hands the
/// keyboard back where it was, so a command that opens something starts
/// from the right place.
fn closing_palette<V: ControlHost>(
    on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Activate<V> {
    Rc::new(move |view: &mut V, picked, window, cx| {
        view.control_state_mut().close_palette(window, cx);
        on_activate(view, picked, window, cx);
    })
}

/// Centred overlay with a filter field and a list of matching commands.
///
/// Open it with [`ControlState::open_palette`](crate::ControlState::open_palette)
/// — or [`toggle_palette`](crate::ControlState::toggle_palette), from
/// whatever shortcut the host gives it; while `id` is not open this returns
/// nothing. The host owns the query input and the commands. The palette
/// filters them with [`fuzzy_filter`], moves the highlight with Up, Down,
/// Page Up and Page Down, keeping it in view, runs the highlighted command
/// on Enter or a clicked one, and closes on Escape or a press on the scrim.
/// It closes before a command runs, handing the keyboard back where it was,
/// so a command that opens something starts from the right place.
#[allow(clippy::too_many_arguments)]
pub fn command_palette<V: ControlHost>(
    id: ComboId,
    query: &Entity<TextInput>,
    commands: &[Command],
    mut ctx: WidgetContext<'_, '_, '_, V>,
    window: &Window,
    on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Option<impl IntoElement> {
    let opened_at = palette_opened_at(ctx.view.control_state(), id)?;
    let text = query.read(ctx.cx).shared_text();
    let matches = command_results(&text, commands);
    let on_activate = closing_palette(on_activate);
    let list = result_list(
        id,
        &text,
        "",
        &matches,
        PALETTE_RESULT_MAX_HEIGHT,
        ctx.reborrow(),
        on_activate.clone(),
    );
    Some(palette_with_results(
        id,
        opened_at,
        query,
        list,
        "No matching commands",
        ctx,
        window,
        on_activate,
    ))
}

/// An overlay for results the host has already filtered and ranked: a
/// [`command_palette`] in every way that concerns opening, the keyboard and
/// closing, whose rows are [`SearchResult`]s, kept on their result as the
/// results change, exactly as in [`ranked_search_list`].
#[allow(clippy::too_many_arguments)]
pub fn ranked_command_palette<V: ControlHost>(
    id: ComboId,
    query: &Entity<TextInput>,
    results: &[SearchResult],
    mut ctx: WidgetContext<'_, '_, '_, V>,
    window: &Window,
    on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Option<impl IntoElement> {
    let opened_at = palette_opened_at(ctx.view.control_state(), id)?;
    let text = query.read(ctx.cx).shared_text();
    let on_activate = closing_palette(on_activate);
    let list = result_list(
        id,
        &text,
        &text,
        results,
        PALETTE_RESULT_MAX_HEIGHT,
        ctx.reborrow(),
        on_activate.clone(),
    );
    Some(palette_with_results(
        id,
        opened_at,
        query,
        list,
        "No results",
        ctx,
        window,
        on_activate,
    ))
}

/// The palette shell and its keyboard contract are shared by fuzzy commands
/// and host-ranked results, so they cannot drift on Escape, scrim or focus.
#[allow(clippy::too_many_arguments)]
fn palette_with_results<V: ControlHost>(
    id: ComboId,
    opened_at: Instant,
    query: &Entity<TextInput>,
    list: ResultList,
    empty_message: &'static str,
    ctx: WidgetContext<'_, '_, '_, V>,
    window: &Window,
    on_activate: Activate<V>,
) -> impl IntoElement {
    let WidgetContext { palette, view, cx } = ctx;
    // The panel arrives the way a menu does: the same reveal, a short drift
    // down into place.
    let reveal = ease_out_cubic(progress(
        opened_at,
        view.control_state().scaled(COMBO_REVEAL),
    ));
    let panel = palette_panel(
        id,
        query,
        list,
        empty_message,
        WidgetContext { palette, view, cx },
        window,
        on_activate,
        Rc::new(|this: &mut V, window: &mut Window, cx: &mut Context<V>| {
            this.control_state_mut().close_palette(window, cx);
        }),
    )
    // A little above centre: the list grows downward, and a palette pinned
    // to the middle ends up low on the screen as soon as it has results.
    .mt(gpui::relative(0.16))
    .relative()
    .top(px(-6.0 * (1.0 - reveal)))
    .opacity(reveal)
    .w(px(PALETTE_WIDTH))
    .max_w(gpui::relative(0.9))
    .rounded(px(10.0))
    .border_1()
    .border_color(lighting::rim(palette_fill(palette), palette.is_dark))
    .shadow(lighting::panel(palette.is_dark));
    deferred(
        div()
            .id(ElementId::Name(format!("{id}-scrim").into()))
            .absolute()
            .inset_0()
            .flex()
            .flex_col()
            .items_center()
            .bg(crate::color::with_alpha(
                palette.scrim(),
                palette.scrim().alpha * reveal,
            ))
            .occlude()
            .on_mouse_down(
                MouseButton::Left,
                cx.listener(move |this, _event: &MouseDownEvent, window, cx| {
                    this.control_state_mut().close_palette(window, cx);
                    cx.notify();
                }),
            )
            .child(panel),
    )
    .priority(180)
}

/// How wide a command palette is, in a window or over one.
pub(crate) const PALETTE_WIDTH: f32 = 520.0;
/// The padding and gap around and between the palette's query field and
/// its list, which a window sized to the palette has to add up.
pub(crate) const PALETTE_PADDING: f32 = 8.0;
const PALETTE_GAP: f32 = 6.0;

/// The palette's surface: the field colour in the light scheme, where the
/// panel lifts off the page by its shadow, and the soft fill in the dark one.
pub(crate) fn palette_fill(palette: Palette) -> Rgba {
    if palette.is_dark {
        palette.soft_fill
    } else {
        palette.field_surface
    }
}

/// The height of a palette panel holding `list`, padding included: what a
/// window sized to the panel needs.
#[cfg(feature = "command-bar-window")]
pub(crate) fn palette_panel_height(list: &ResultList) -> f32 {
    let rows = if list.navigation.rows.is_empty() {
        COMMAND_ROW_HEIGHT
    } else {
        list.navigation.viewport_height()
    };
    2.0 * PALETTE_PADDING + crate::controls::CONTROL_HEIGHT + PALETTE_GAP + rows
}

/// The panel every command palette is made of: the query field over the
/// result list, with the list's keys, and Escape answered by `on_dismiss`.
/// The overlay places it over a scrim; the command bar window fills itself
/// with it. One implementation, so the two cannot drift on keys, focus or
/// results.
#[allow(clippy::too_many_arguments)]
pub(crate) fn palette_panel<V: ControlHost>(
    id: ComboId,
    query: &Entity<TextInput>,
    list: ResultList,
    empty_message: &'static str,
    ctx: WidgetContext<'_, '_, '_, V>,
    window: &Window,
    on_activate: Activate<V>,
    on_dismiss: Dismissed<V>,
) -> Div {
    let WidgetContext { palette, view, cx } = ctx;
    let state = view.control_state();
    let fill = palette_fill(palette);
    let panel = div()
        .flex()
        .flex_col()
        .gap(px(PALETTE_GAP))
        .p(px(PALETTE_PADDING))
        .bg(fill)
        .occlude()
        // Once `bind_keys` has run, Escape arrives as this action and never
        // as a key. The query field has the keyboard, and this is the first
        // thing above it.
        .on_action(cx.listener(move |this, _: &Dismiss, window, cx| {
            on_dismiss(this, window, cx);
            cx.notify();
        }))
        .child(search_field(id, query, palette, window, cx))
        .child(result_viewport(
            id,
            list.elements,
            &list.navigation,
            empty_message,
            (fill, fill),
            palette,
            state,
        ));
    list_keys(panel, id, list.ids, Some(list.navigation), cx, on_activate)
}

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

    #[test]
    fn word_starts_outrank_scattered_letters() {
        let open_file = fuzzy_score("opf", "Open File").expect("matches");
        let scattered = fuzzy_score("opf", "Optional Prefix").expect("matches");
        assert!(
            open_file > scattered,
            "expected Open File ({open_file}) above Optional Prefix ({scattered})"
        );
    }

    #[test]
    fn a_query_that_is_not_a_subsequence_does_not_match() {
        assert!(fuzzy_score("zzz", "Open File").is_none());
        assert!(fuzzy_score("elif", "Open File").is_none());
    }

    #[test]
    fn an_empty_query_keeps_everything_in_its_original_order() {
        let commands = vec![
            Command::new("b", "Much longer first command"),
            Command::new("a", "First"),
        ];
        for query in ["", " \t\n"] {
            let filtered = fuzzy_filter(query, &commands);
            let ids: Vec<&str> = filtered.iter().map(|command| command.id.as_ref()).collect();
            assert_eq!(ids, vec!["b", "a"]);
        }
    }

    #[test]
    fn consecutive_unicode_characters_get_the_same_bonus_as_ascii() {
        assert_eq!(fuzzy_score("été", "été"), fuzzy_score("ete", "ete"));
        assert_eq!(fuzzy_score("b", "a\tb"), fuzzy_score("b", "a b"));
    }

    #[test]
    fn the_group_is_searched_along_with_the_label() {
        let commands = vec![Command::new("save", "Save").group("File")];
        assert_eq!(fuzzy_filter("file sa", &commands).len(), 1);
    }

    #[test]
    fn emphasis_prefers_a_whole_match_and_merges_overlapping_words() {
        assert_eq!(
            matched_ranges("Design system", "sign des", Line::Label),
            vec![0..6]
        );
        assert_eq!(
            matched_ranges("Open File", "opf", Line::Label),
            vec![0..2, 5..6]
        );
    }

    #[test]
    fn emphasis_uses_valid_unicode_byte_boundaries() {
        assert_eq!(
            matched_ranges("Café résumé", "fé su", Line::Label),
            vec![2..5, 9..11]
        );
        assert!(matched_ranges("Café", "", Line::Label).is_empty());
    }

    /// A detail line is not what the person abbreviated, so scattered
    /// letters there are coincidence, and so is a run inside a word.
    #[test]
    fn a_detail_line_emphasises_only_runs_that_start_a_word() {
        let detail = "Project board · 2 minutes ago";
        assert!(matched_ranges(detail, "de", Line::Detail).is_empty());
        assert_eq!(matched_ranges(detail, "boa", Line::Detail), vec![8..11]);
        assert!(matched_ranges("Visited this morning", "in", Line::Detail).is_empty());
        assert_eq!(
            matched_ranges("Visited this morning", "mor", Line::Detail),
            vec![13..16]
        );
        assert_eq!(
            matched_ranges("Design review", "de", Line::Label),
            vec![0..2]
        );
        assert_eq!(matched_ranges("Morning", "in", Line::Label), vec![4..6]);
    }

    /// The gallery's sources, in the order it assembles them.
    fn sources() -> Vec<SearchResult> {
        [
            (
                "tab-design",
                "Design review",
                "Project board · 2 minutes ago",
                "Open tabs",
            ),
            (
                "tab-release",
                "Release checklist",
                "Draft · Current window",
                "Open tabs",
            ),
            (
                "tab-insights",
                "Traffic insights",
                "Analytics · Current window",
                "Open tabs",
            ),
            ("tab-issues", "Issue tracker", "42 open tasks", "Open tabs"),
            (
                "bookmark-system",
                "Design system",
                "Components and colour recipes",
                "Bookmarks",
            ),
            (
                "bookmark-keys",
                "Keyboard shortcuts",
                "Reference · Documentation",
                "Bookmarks",
            ),
            (
                "bookmark-api",
                "API reference",
                "Framework documentation",
                "Bookmarks",
            ),
            (
                "bookmark-roadmap",
                "Project roadmap",
                "Milestones and plans",
                "Bookmarks",
            ),
            (
                "file-budget",
                "Quarterly budget",
                "Shared documents · Updated today",
                "Files",
            ),
            (
                "file-summary",
                "Meeting summary",
                "Notes · Updated yesterday",
                "Files",
            ),
            (
                "history-notes",
                "Design notes",
                "Visited this morning",
                "History",
            ),
            (
                "history-changelog",
                "Release notes",
                "Visited yesterday",
                "History",
            ),
            (
                "action-invite",
                "Invite teammate",
                "Share this workspace",
                "Actions",
            ),
            (
                "action-export",
                "Export report",
                "Save a local copy",
                "Actions",
            ),
        ]
        .into_iter()
        .map(|(id, label, detail, section)| {
            SearchResult::new(id, label).detail(detail).section(section)
        })
        .collect()
    }

    #[test]
    fn ranking_keeps_each_section_together() {
        let sources = sources();
        for query in ["", "de", "re", "design", "no", "book"] {
            let ranked = rank_results(query, &sources);
            let mut seen: Vec<&str> = Vec::new();
            for result in &ranked {
                let section = result
                    .section
                    .as_deref()
                    .expect("every source has a section");
                if seen.last() != Some(&section) {
                    assert!(
                        !seen.contains(&section),
                        "{section} heads two runs for {query:?}"
                    );
                    seen.push(section);
                }
            }
        }
        let ids = |query: &str| -> Vec<SharedString> {
            rank_results(query, &sources)
                .into_iter()
                .map(|result| result.id)
                .collect()
        };
        let all: Vec<SharedString> = sources.iter().map(|result| result.id.clone()).collect();
        assert_eq!(ids(""), all);
        // Equal scores, so the sections keep the order they came in.
        assert_eq!(
            ids("design"),
            ["tab-design", "bookmark-system", "history-notes"]
        );
        // Through the section alone, in source order.
        assert_eq!(
            ids("book"),
            [
                "bookmark-system",
                "bookmark-keys",
                "bookmark-api",
                "bookmark-roadmap"
            ]
        );
        assert!(ids("zzz").is_empty());
    }

    #[test]
    fn many_distinct_sections_keep_source_order() {
        let results: Vec<_> = (0..2_000)
            .map(|index| {
                SearchResult::new(format!("item-{index}"), "Entry")
                    .section(format!("Section {index}"))
            })
            .collect();
        let ranked = rank_results("", &results);
        assert_eq!(ranked.len(), results.len());
        assert!(ranked.iter().zip(&results).all(|(a, b)| a.id == b.id));
    }

    #[test]
    fn ranking_scores_the_label_not_the_length_of_the_detail() {
        let results = [
            SearchResult::new("long", "Design review")
                .detail("A detail line long enough to cost several points of length"),
            SearchResult::new("short", "Design notes").detail("Brief"),
            SearchResult::new("detail-only", "Weekly sync").detail("Design"),
        ];
        let ranked: Vec<SharedString> = rank_results("design", &results)
            .into_iter()
            .map(|result| result.id)
            .collect();
        assert_eq!(ranked, ["long", "short", "detail-only"]);
    }

    #[test]
    fn section_headings_take_room_but_no_keyboard_step() {
        let results = [
            SearchResult::new("a", "First")
                .section("Tabs")
                .detail("Detail"),
            SearchResult::new("b", "Second").section("Tabs"),
            SearchResult::new("c", "Third"),
            SearchResult::new("d", "Fourth")
                .section("Bookmarks")
                .detail("Detail"),
        ];
        let layout = row_layout(&results);
        assert_eq!(
            layout.iter().map(|row| row.heading).collect::<Vec<_>>(),
            [true, false, false, true]
        );
        assert_eq!(
            layout.iter().map(|row| row.top).collect::<Vec<_>>(),
            [21.0, 66.0, 97.0, 149.0]
        );
        assert_eq!(
            layout.iter().map(|row| row.height).collect::<Vec<_>>(),
            [
                DETAIL_ROW_HEIGHT,
                COMMAND_ROW_HEIGHT,
                COMMAND_ROW_HEIGHT,
                DETAIL_ROW_HEIGHT
            ]
        );
    }

    #[test]
    fn a_long_result_list_builds_only_the_window_around_its_scroll() {
        let results: Vec<_> = (0..10_000)
            .map(|index| SearchResult::new(format!("item-{index}"), "Entry"))
            .collect();
        let layout = row_layout(&results);
        let target = 5_000;
        let visible = visible_result_range(&layout, -layout[target].top, 300.0);
        assert!(visible.contains(&target));
        assert!(visible.len() < 40, "offscreen rows must stay unbuilt");
        assert_eq!(visible_result_range(&layout, 0.0, 300.0).start, 0);
    }

    #[test]
    fn page_navigation_moves_by_viewport_and_stops_at_edges() {
        let rows: Vec<Range<f32>> = [21.0, 66.0, 99.0, 153.0, 198.0, 243.0]
            .into_iter()
            .map(|top| top..top + 30.0)
            .collect();
        assert_eq!(page_target(Key::PageDown, 0, &rows, 100.0), Some(3));
        assert_eq!(page_target(Key::PageUp, 3, &rows, 100.0), Some(0));
        assert_eq!(page_target(Key::PageDown, 3, &rows, 100.0), Some(5));
        assert_eq!(page_target(Key::PageUp, 0, &rows, 100.0), Some(0));
        assert_eq!(page_target(Key::PageDown, 0, &[], 100.0), None);
    }

    #[test]
    fn highlighted_result_clears_scroll_edge_fades() {
        assert_eq!(revealed_offset(0.0, 300.0, 0.0..100.0, 90.0..110.0), -35.0);
        assert_eq!(
            revealed_offset(-130.0, 300.0, 0.0..100.0, 120.0..140.0),
            -95.0
        );
        assert_eq!(revealed_offset(0.0, 300.0, 0.0..100.0, 0.0..20.0), 0.0);
        assert_eq!(
            revealed_offset(-295.0, 300.0, 0.0..100.0, 380.0..400.0),
            -300.0
        );
    }

    #[test]
    fn long_inline_results_page_to_a_row_inside_their_own_viewport() {
        let results: Vec<_> = (0..14)
            .map(|index| {
                SearchResult::new(format!("result-{index}"), format!("Result {index}"))
                    .section(if index < 7 { "Tabs" } else { "Files" })
                    .detail("A second line")
            })
            .collect();
        let navigation = ResultNavigation {
            scroll: ScrollHandle::new(),
            rows: row_layout(&results)
                .iter()
                .map(|row| row.top..row.top + row.height)
                .collect(),
            max_height: INLINE_RESULT_MAX_HEIGHT,
        };
        let viewport = navigation.viewport_height();
        assert_eq!(viewport, INLINE_RESULT_MAX_HEIGHT);
        let target = page_target(Key::PageDown, 0, &navigation.rows, viewport)
            .expect("page down reaches a result");
        let row = navigation.rows[target].clone();
        assert!(row.start >= viewport);
        let offset = revealed_offset(
            0.0,
            navigation.content_height() - viewport,
            0.0..viewport,
            row.clone(),
        );
        assert!(offset < 0.0);
        assert!(row.end + offset <= viewport - crate::scroll::SCROLL_FADE);
    }

    /// A list shorter than its cap is all viewport, so nothing scrolls and
    /// a page goes to the end.
    #[test]
    fn a_short_list_is_its_own_viewport() {
        let results: Vec<_> = (0..3)
            .map(|index| SearchResult::new(format!("r{index}"), "Result"))
            .collect();
        let navigation = ResultNavigation {
            scroll: ScrollHandle::new(),
            rows: row_layout(&results)
                .iter()
                .map(|row| row.top..row.top + row.height)
                .collect(),
            max_height: PALETTE_RESULT_MAX_HEIGHT,
        };
        assert_eq!(navigation.content_height(), 3.0 * COMMAND_ROW_HEIGHT + 2.0);
        assert_eq!(navigation.viewport_height(), navigation.content_height());
        assert_eq!(
            page_target(
                Key::PageDown,
                0,
                &navigation.rows,
                navigation.viewport_height()
            ),
            Some(2)
        );
    }
}

#[cfg(test)]
#[path = "emphasis_bench.rs"]
mod emphasis_bench;

#[cfg(test)]
#[path = "search_bench.rs"]
mod search_bench;