bezel-ui 0.1.20

SwiftUI-flavored components for gpui — popovers, menus, buttons, toggles, and loaders
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
//! Popover / menu primitives: an anchored floating layer with the `menu-in`
//! animation, outside-click dismissal, and pure keyboard-navigation + search
//! reducers shared by every picker and menu (feature-inventory §1.12 popovers).
//!
//! gpui pattern (examples/popover.rs at the pinned rev): the trigger element
//! conditionally children a `deferred(anchored().child(content))` — deferred
//! paints on a floating layer above everything, anchored positions it relative
//! to the trigger (or an explicit point for context menus).
//!
//! Pure logic (wrap-around list navigation, ranked substring filtering, key
//! classification) lives in free functions with unit tests; the elements only
//! feed them measurements/events.

use crate::{icons, stack};
use gpui::{
    Anchor, AnyElement, ElementId, IntoElement, Pixels, Point, SharedString, div, prelude::*, px,
};
use icons::Icon;
use motion::{self as motion, AnimationExt as _, Fade, PULSE, Painter};
use theme::{TextStyle, Theme, Typeset, hairline, ink};

// ---------------------------------------------------------------------------
// Loadable — async slot state shared by pickers/settings pages
// ---------------------------------------------------------------------------

/// One async-loaded slot: `Idle` (never requested) → `Loading` (skeletons) →
/// `Ready` / `Error` (inline message + Retry).
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Loadable<T> {
    #[default]
    Idle,
    Loading,
    Ready(T),
    Error(String),
}

impl<T> Loadable<T> {
    pub fn ready(&self) -> Option<&T> {
        match self {
            Loadable::Ready(value) => Some(value),
            _ => None,
        }
    }

    pub fn is_loading(&self) -> bool {
        matches!(self, Loadable::Loading)
    }

    pub fn error(&self) -> Option<&str> {
        match self {
            Loadable::Error(message) => Some(message),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// Popup — open/closing/closed lifecycle (exit animations)
// ---------------------------------------------------------------------------

/// Popup state with an exit phase. gpui unmounts an element the frame its
/// state drops, so a closing animation needs the state held alive while
/// [`motion::menu_out`] plays: `open` → `begin_close` (render keeps mounting,
/// with the out animation and dead hit-testing) → [`reap_popup`]'s timer
/// `finish_close`es ~[`motion::MENU_OUT`] later. Use [`Self::is_open`] for
/// logic (a closing popup already reads as closed) and [`Self::get`] /
/// [`Self::is_closing`] for rendering.
pub struct Popup<T> {
    /// `Some((state, closing_since))` while mounted; `closing_since` is the
    /// exit-phase start.
    inner: Option<(T, Option<web_time::Instant>)>,
    /// Whether the popup was still mounted when the current trigger press
    /// began — see [`Self::note_trigger_press`].
    pressed_while_open: bool,
    generation: u64,
}

impl<T> Default for Popup<T> {
    fn default() -> Self {
        Self {
            inner: None,
            pressed_while_open: false,
            generation: 0,
        }
    }
}

impl<T> Popup<T> {
    pub fn open(&mut self, value: T) {
        self.generation = self.generation.wrapping_add(1);
        self.inner = Some((value, None));
    }

    /// Open and interactive (not closing).
    pub fn is_open(&self) -> bool {
        matches!(self.inner, Some((_, None)))
    }

    pub fn is_closing(&self) -> bool {
        matches!(self.inner, Some((_, Some(_))))
    }

    /// When the exit phase began — what the render path hands to the popover
    /// wrappers, which derive the eased exit progress from it each frame.
    pub fn closing_since(&self) -> Option<web_time::Instant> {
        match &self.inner {
            Some((_, Some(since))) => Some(*since),
            _ => None,
        }
    }

    /// The state while mounted — open OR playing the exit animation. Render
    /// paths use this; logic paths use [`Self::as_open`]/[`Self::open_mut`].
    pub fn get(&self) -> Option<&T> {
        self.inner.as_ref().map(|(value, _)| value)
    }

    /// The state only while genuinely open — `None` during the exit phase, so
    /// event handlers on a dying popup fall through.
    pub fn as_open(&self) -> Option<&T> {
        match &self.inner {
            Some((value, None)) => Some(value),
            _ => None,
        }
    }

    pub fn open_mut(&mut self) -> Option<&mut T> {
        match &mut self.inner {
            Some((value, None)) => Some(value),
            _ => None,
        }
    }

    /// Unmount now, with no exit phase.
    ///
    /// For a surface that has no exit animation to play — [`modal`], which
    /// takes no `closing` and paints the same either way. Sending one of those
    /// through [`Self::begin_close`] buys nothing and costs everything: it
    /// stays fully painted for the animation's span, and if the reap never
    /// lands it stays forever, because nothing retries.
    ///
    /// Not for a popup something toggles: unmounting on the press erases what
    /// [`Self::note_trigger_press`] has to read, so the note comes back false
    /// and the trigger reopens what it just shut. Those close through
    /// [`close_popup`].
    pub fn close(&mut self) {
        self.inner = None;
    }

    /// Enter the exit phase. Returns `true` when this call started it (the
    /// caller then schedules [`reap_popup`]); `false` if already closing or
    /// closed.
    pub fn begin_close(&mut self) -> bool {
        match &mut self.inner {
            Some((_, closing @ None)) => {
                self.generation = self.generation.wrapping_add(1);
                *closing = Some(web_time::Instant::now());
                true
            }
            _ => false,
        }
    }

    /// Record, from the trigger's `on_mouse_down`, whether this popup is
    /// still mounted. The anchored card's `on_mouse_down_out` fires on that
    /// same press and begins the close, so by click (mouse-up) time the
    /// popup already reads as closed — the click handler alone cannot tell
    /// "this press dismissed it; stay closed" from "open fresh", and a
    /// plain toggle closes-and-reopens (user report). Both handler orders
    /// work: open and mid-exit each count as mounted. Every trigger click
    /// is preceded by a trigger mouse-down, so the note is never stale.
    ///
    /// [`menu_trigger`] wires this and the matching click together. Reach for
    /// it directly only when the open is not a click — a gutter handle whose
    /// menu belongs to the release of a possible drag.
    pub fn note_trigger_press(&mut self) {
        self.note_trigger_press_matching(|_| true);
    }

    /// [`Self::note_trigger_press`] for popups whose state distinguishes
    /// which trigger owns them (e.g. one `Popup<PickerKind>` shared by
    /// several triggers): only a press on the OWNING trigger counts, so
    /// clicking a different trigger switches menus instead of swallowing.
    pub fn note_trigger_press_matching(&mut self, owns: impl FnOnce(&T) -> bool) {
        self.pressed_while_open = self.inner.as_ref().is_some_and(|(value, _)| owns(value));
    }

    /// Consume the press note: `true` when the press that produced the
    /// current click found the popup mounted — the click should leave it
    /// closed rather than reopen it.
    pub fn take_press_was_open(&mut self) -> bool {
        std::mem::take(&mut self.pressed_while_open)
    }

    /// Drop the state now the exit phase has run its course. A popup reopened
    /// since the matching [`Self::begin_close`] is left alone — it is `None`
    /// again in the second slot, and the newer phase's own reap handles it.
    ///
    /// It does not re-check the clock. [`reap_popup`] already waited out the
    /// span on the executor's timer, and asking `Instant::elapsed` to agree
    /// makes one deadline depend on two clocks — where they disagree, and a
    /// throttled executor is where, the popup is stranded open with nothing
    /// left to retry.
    pub fn finish_close(&mut self) {
        if matches!(&self.inner, Some((_, Some(_)))) {
            self.inner = None;
        }
    }
}

/// Schedule the reap for a [`Popup::begin_close`]: after the exit animation's
/// span, drop the popup state and repaint. `popup` re-borrows the field from
/// the view (the state can't be captured — the view owns it).
pub fn reap_popup<V: 'static, T: 'static>(
    view: &mut V,
    cx: &mut gpui::Context<V>,
    popup: impl Fn(&mut V) -> &mut Popup<T> + 'static,
) {
    let generation = popup(view).generation;
    cx.spawn(async move |view, cx| {
        cx.background_executor()
            .timer(
                motion::MENU_OUT
                    .total()
                    .mul_f32(motion::speed_scale())
                    .saturating_add(std::time::Duration::from_millis(20)),
            )
            .await;
        view.update(cx, |view, cx| {
            let popup = popup(view);
            if popup.generation == generation && popup.is_closing() {
                popup.finish_close();
                cx.notify();
            }
        })
        .ok();
    })
    .detach();
}

/// Begin a popup's exit phase and schedule its reap — [`Popup::begin_close`]
/// and [`reap_popup`], which are only ever correct together. A popup already
/// closing or closed is left alone.
pub fn close_popup<V: 'static, T: 'static>(
    view: &mut V,
    cx: &mut gpui::Context<V>,
    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
) {
    if popup(view).begin_close() {
        reap_popup(view, cx, popup);
        cx.notify();
    }
}

/// Dismiss `popup` on a press outside `el` — the card side of the pair
/// [`menu_trigger`] completes.
///
/// It closes through [`close_popup`] rather than [`Popup::close`], and that is
/// load-bearing rather than cosmetic: the exit phase is what keeps the popup
/// reading as mounted while the trigger's own press handler runs, whichever of
/// the two the frame happens to dispatch first.
///
/// The press is swallowed, as [`crate::menu::card`]'s own dismissal swallows
/// it: this listener runs in the capture phase, and stopping there skips the
/// bubble phase where gpui records the press a click is built from. A press
/// that dismisses an open card is spent on the dismissal, and whatever it
/// landed on is one more press away.
pub fn dismiss_on_out<V: 'static, T: 'static, E: gpui::InteractiveElement>(
    el: E,
    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
    cx: &gpui::Context<V>,
) -> E {
    el.on_mouse_down_out(cx.listener(move |view, _: &gpui::MouseDownEvent, _, cx| {
        close_popup(view, cx, popup);
        cx.stop_propagation();
    }))
}

/// Wire a trigger to the popup it toggles: press note on the way down, open or
/// close on the way up.
///
/// The press/release split is why this exists rather than a plain
/// `on_click`. `on_mouse_down_out` fires on the **press** and `on_click` on the
/// **release**, so one physical click on the trigger of an open menu runs the
/// card's dismissal first and the trigger's toggle second — by which time the
/// state a toggle would branch on is already gone, and the menu reopens on the
/// click that shut it (user report). No click handler can tell the two apart;
/// the note has to be taken in the phase the dismissal cannot precede.
///
/// `value` is what to open with, from the click that opened it — a point for a
/// menu anchored where it was pressed, or `move |_| ..` for one that already
/// knows.
///
/// This is a true toggle either way: a card that dismisses itself on the
/// out-press is already closing by the release and the close here is a no-op,
/// while a card that does not (one dismissed by Escape alone, or one the
/// trigger sits inside) is closed by the release itself.
pub fn menu_trigger<V: 'static, T: 'static, E: gpui::StatefulInteractiveElement>(
    el: E,
    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
    value: impl Fn(&gpui::ClickEvent) -> T + 'static,
    cx: &gpui::Context<V>,
) -> E {
    menu_trigger_matching(el, popup, |_| true, value, cx)
}

/// [`menu_trigger`] for one popup shared by several triggers (a `Popup<Menu>`
/// with a row's index inside it): `owns` says whether the open popup is *this*
/// trigger's, so pressing another trigger switches menus instead of swallowing
/// the press. See [`Popup::note_trigger_press_matching`].
pub fn menu_trigger_matching<V: 'static, T: 'static, E: gpui::StatefulInteractiveElement>(
    el: E,
    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
    owns: impl Fn(&T) -> bool + 'static,
    value: impl Fn(&gpui::ClickEvent) -> T + 'static,
    cx: &gpui::Context<V>,
) -> E {
    trigger_press_matching(el, popup, owns, cx).on_click(cx.listener(
        move |view, event: &gpui::ClickEvent, _, cx| {
            if popup(view).take_press_was_open() {
                close_popup(view, cx, popup);
            } else {
                popup(view).open(value(event));
            }
            cx.notify();
        },
    ))
}

/// The press half of [`menu_trigger`] on its own, for a trigger whose open is
/// more than `Popup::open` — a combobox that clears its query and focuses it, a
/// gutter handle whose menu belongs to the release of a possible drag. The
/// click side is then the caller's, and reads the note with
/// [`Popup::take_press_was_open`].
pub fn trigger_press<V: 'static, T: 'static, E: gpui::InteractiveElement>(
    el: E,
    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
    cx: &gpui::Context<V>,
) -> E {
    trigger_press_matching(el, popup, |_| true, cx)
}

/// [`trigger_press`] for one popup shared by several triggers — see
/// [`menu_trigger_matching`].
pub fn trigger_press_matching<V: 'static, T: 'static, E: gpui::InteractiveElement>(
    el: E,
    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
    owns: impl Fn(&T) -> bool + 'static,
    cx: &gpui::Context<V>,
) -> E {
    // Capture, not bubble: `on_mouse_down_out` is itself a capture-phase
    // listener, so a bubble-phase note is dispatched after every dismissal in
    // the frame and reads whatever they left behind. Survivable while every
    // dismissal goes through [`close_popup`] — mid-exit still counts as
    // mounted — and not survivable the moment one reaches for [`Popup::close`],
    // which is a footgun to leave lying under a component's own trigger.
    el.capture_any_mouse_down(cx.listener(move |view, _: &gpui::MouseDownEvent, _, _| {
        popup(view).note_trigger_press_matching(&owns);
    }))
}

// ---------------------------------------------------------------------------
// Pure reducers
// ---------------------------------------------------------------------------

/// Step the active row of a menu: wraps at both ends; `None` enters at the
/// edge matching the direction. Empty menus stay `None`.
pub fn menu_step(active: Option<usize>, count: usize, delta: isize) -> Option<usize> {
    if count == 0 {
        return None;
    }
    let count_i = count as isize;
    let next = match active {
        None => {
            if delta >= 0 {
                0
            } else {
                count_i - 1
            }
        }
        Some(at) => (at as isize + delta).rem_euclid(count_i),
    };
    Some(next as usize)
}

/// Match rank of a label against a query: `0` prefix match, `1` substring,
/// `None` no match. Case-insensitive; an empty query matches everything at
/// rank 1 (input order preserved).
pub fn match_rank(query: &str, label: &str) -> Option<usize> {
    let query = query.trim().to_lowercase();
    if query.is_empty() {
        return Some(1);
    }
    let label = label.to_lowercase();
    if label.starts_with(&query) {
        Some(0)
    } else if label.contains(&query) {
        Some(1)
    } else {
        None
    }
}

/// Filter + rank labels for a search query: prefix matches first, then
/// substring matches, stable within each rank. Returns indices into `labels`.
pub fn filter_indices<S: AsRef<str>>(query: &str, labels: &[S]) -> Vec<usize> {
    let mut ranked: Vec<(usize, usize)> = labels
        .iter()
        .enumerate()
        .filter_map(|(ix, label)| match_rank(query, label.as_ref()).map(|rank| (rank, ix)))
        .collect();
    ranked.sort_by_key(|&(rank, ix)| (rank, ix));
    ranked.into_iter().map(|(_, ix)| ix).collect()
}

/// The state behind a searchable list: the items, the ranked view of them, and
/// which row of that view is active. Shared by every picker — the palette, the
/// combobox — so the mapping below is written and tested once.
pub struct Filter {
    items: Vec<SharedString>,
    /// Indices into `items`, ranked by [`filter_indices`].
    filtered: Vec<usize>,
    /// Position within `filtered`, not within `items`.
    active: Option<usize>,
}

impl Filter {
    pub fn new(items: Vec<SharedString>) -> Self {
        let filtered: Vec<usize> = (0..items.len()).collect();
        let active = (!filtered.is_empty()).then_some(0);
        Self {
            items,
            filtered,
            active,
        }
    }

    pub fn items(&self) -> &[SharedString] {
        &self.items
    }

    /// The ranked view: indices into [`Self::items`], in display order.
    pub fn filtered(&self) -> &[usize] {
        &self.filtered
    }

    /// The highlighted row's position in the FILTERED view — what a renderer
    /// compares each row against.
    pub fn active(&self) -> Option<usize> {
        self.active
    }

    /// Re-rank against `query`, re-entering the list at the top: after
    /// narrowing, the best match should be one Enter away.
    pub fn refilter(&mut self, query: &str) {
        self.filtered = filter_indices(query, &self.items);
        self.active = (!self.filtered.is_empty()).then_some(0);
    }

    pub fn step(&mut self, delta: isize) {
        self.active = menu_step(self.active, self.filtered.len(), delta);
    }

    /// Put the cursor on a position in the FILTERED view — what the mouse
    /// calls as it crosses a row, so a menu never shows a mouse cursor and a
    /// keyboard cursor at once.
    pub fn set_active(&mut self, position: usize) {
        if position < self.filtered.len() {
            self.active = Some(position);
        }
    }

    /// The item confirming right now would pick — an index into
    /// [`Self::items`], never into the filtered view. Confusing the two is the
    /// defining bug of a filtered list: it only appears once a query narrows
    /// the rows, and then every selection picks the wrong thing.
    pub fn active_item(&self) -> Option<usize> {
        self.active
            .and_then(|position| self.filtered.get(position))
            .copied()
    }
}

/// Keys the pickers care about, classified from a raw keystroke.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MenuKey {
    Up,
    Down,
    /// Plain Enter — activate the highlighted row.
    Enter,
    /// Cmd/Ctrl+Enter — the "pick this folder" accelerator in the browser.
    ModEnter,
    Escape,
    Backspace,
    Other,
}

pub fn classify_key(key: &str, cmd: bool, ctrl: bool) -> MenuKey {
    match key {
        "up" => MenuKey::Up,
        "down" => MenuKey::Down,
        // Readline/emacs motion: ctrl-n/ctrl-p mirror ↓/↑ in every picker.
        // Safe to claim frame-wide — neither chord is a text-editing binding
        // in the palette keymaps, so they always bubble here unconsumed.
        "n" if ctrl => MenuKey::Down,
        "p" if ctrl => MenuKey::Up,
        "enter" if cmd || ctrl => MenuKey::ModEnter,
        "enter" => MenuKey::Enter,
        "escape" => MenuKey::Escape,
        "backspace" => MenuKey::Backspace,
        _ => MenuKey::Other,
    }
}

// ---------------------------------------------------------------------------
// Elements
// ---------------------------------------------------------------------------

/// The floating-menu surface: `rounded-xl border border-white/[0.1] p-1` over
/// whichever look [`Theme::menu_style`] names — the hairline and the baked-in
/// shadow are the card's, and the surface under it paints everything inside
/// them. Opaque platforms keep the near-opaque tone the reference composites
/// to on the dark panels (~#161616).
/// The inner inset of a [`popover_card`], and so the amount [`menu_row`]'s
/// corners come in by. Named because two things read it: the card's padding and
/// its rows' radius. Change it and the rows follow.
pub(crate) const MENU_PAD: f32 = 4.0;

pub fn popover_card(theme: &Theme) -> gpui::Div {
    let card = div()
        .rounded(px(Theme::surface_radius()))
        .p(px(MENU_PAD))
        .overflow_hidden()
        .text_style(TextStyle::Body)
        .text_color(theme.text);
    // Contents only. Fill, boundary and shadow are the surface's — every look
    // paints its own, so nothing here has to know which one is under it. An
    // card with the recipes off has no surface at all, and keeps the fill.
    if theme.glass {
        card
    } else {
        card.bg(theme.surface_overlay)
            .border_1()
            .border_color(hairline(0.10))
            .shadow_lg()
    }
}

/// [`popover_card`] without the `p-1` inset — for popovers that manage their
/// own internal panes (the harness/model picker's rail + list split).
pub fn popover_card_flush(theme: &Theme) -> gpui::Div {
    popover_card(theme).p(px(0.0))
}

/// Pin a floating layer's origin to the trigger's top-left. The anchored
/// element is absolutely positioned; without explicit insets its *static*
/// position is subject to the trigger's own flex alignment (an `items_center`
/// trigger would vertically center the whole floating layer). A zero-size
/// absolutely-inset wrapper fixes the origin at the corner.
fn pinned_layer(layer: AnyElement) -> AnyElement {
    div()
        .absolute()
        .top_0()
        .left_0()
        .size_0()
        .child(layer)
        .into_any_element()
}

/// Eased exit progress (0..=1) for a [`Popup`] closing instant, computed from
/// the wall clock at render time. Monotonic by construction — unlike the
/// animation element's own clock, it can never replay from 0 mid-exit.
fn exit_progress(since: web_time::Instant) -> f32 {
    let total = motion::MENU_OUT
        .total()
        .mul_f32(motion::speed_scale())
        .as_secs_f32();
    let raw = if total <= 0.0 {
        1.0
    } else {
        (since.elapsed().as_secs_f32() / total).clamp(0.0, 1.0)
    };
    motion::MENU_OUT.progress(raw)
}

/// The surface under a popover layer, on whichever look [`Theme::menu_style`]
/// names. It needs no exit ramp of its own: the primitive reads the element
/// tree's opacity, so a layer playing `menu_out` fades its surface with
/// everything else in it.
fn material_menu(content: AnyElement) -> AnyElement {
    crate::surface::popover(Theme::surface_radius(), content).into_any_element()
}

/// Entrance or exit motion for a popover layer. While exiting (the [`Popup`]
/// closing phase, `exit = Some(progress)`) the content plays
/// [`motion::menu_out`] under a fresh animation id (same-id reuse would
/// inherit the entrance's finished clock and snap to the end state) and gets
/// an occluding overlay on top — the dying menu's rows must not take clicks,
/// and the overlay also keeps stray clicks from reaching whatever sits
/// underneath.
fn menu_motion(id: SharedString, exit: Option<f32>, inner: gpui::Div) -> AnyElement {
    if let Some(t) = exit {
        let inner = inner.relative().child(div().absolute().inset_0().occlude());
        motion::menu_out(SharedString::from(format!("{id}-out")), t, inner).into_any_element()
    } else {
        motion::menu_in(id, inner).into_any_element()
    }
}

/// The common floating layer. Trigger wrappers only choose the origin.
fn menu_layer(
    id: impl Into<SharedString>,
    content: AnyElement,
    closing: Option<web_time::Instant>,
    anchor: Anchor,
    position: Option<Point<Pixels>>,
    gap: f32,
) -> AnyElement {
    let content = material_menu(content);
    let inner = match anchor {
        Anchor::BottomLeft | Anchor::BottomRight => div().occlude().pb(px(gap)),
        _ => div().occlude().pt(px(gap)),
    }
    .child(content);
    let mut layer = gpui::anchored()
        .anchor(anchor)
        .snap_to_window_with_margin(px(8.0));
    if let Some(position) = position {
        layer = layer.position(position);
    }
    gpui::deferred(layer.child(menu_motion(id.into(), closing.map(exit_progress), inner)))
        .priority(1)
        .into_any_element()
}

/// Wrap popover content in a floating anchored layer attached to the trigger:
/// the caller `.child(anchored_menu(...))`s this from the trigger element while
/// open. Plays `menu-in` (0.14s fade + 2px drop); `closing` (the [`Popup`]
/// exit phase) swaps in `menu-out`. Dismissal is the caller's
/// `.on_mouse_down_out` on the content. The layer `.occlude()`s: hitboxes are
/// paint-order only in gpui, so without it clicks on menu rows would ALSO fire
/// whatever clickable sits under the floating layer.
pub fn anchored_menu(
    id: impl Into<SharedString>,
    content: AnyElement,
    closing: Option<web_time::Instant>,
) -> AnyElement {
    pinned_layer(menu_layer(id, content, closing, Anchor::TopLeft, None, 6.0))
}

/// [`anchored_menu`] opening DOWNWARD from the trigger's bottom edge — a
/// dropdown proper (the sidebar's space filter). The default variant pins to
/// the trigger's top-left, which reads fine for context-style menus but
/// covers a button-shaped trigger.
pub fn anchored_menu_below(
    id: impl Into<SharedString>,
    content: AnyElement,
    closing: Option<web_time::Instant>,
) -> AnyElement {
    anchored_menu_below_gap(id, content, closing, 6.0)
}

/// [`anchored_menu_below`] with a caller-chosen trigger→card gap — the
/// changes-header dropdowns hang off a tight titlebar band and need more
/// breathing room than the default 6px (user report; t3code sits near 10).
pub fn anchored_menu_below_gap(
    id: impl Into<SharedString>,
    content: AnyElement,
    closing: Option<web_time::Instant>,
    gap: f32,
) -> AnyElement {
    div()
        .absolute()
        .bottom_0()
        .left_0()
        .size_0()
        .child(menu_layer(id, content, closing, Anchor::TopLeft, None, gap))
        .into_any_element()
}

/// The panel a [`crate::menu::Item::Submenu`] row drops: pinned to the row's
/// top-right and pulled back by the card's own inset, so the child's first row
/// lines up with the row that opened it and the two cards touch. No gap on
/// purpose — a strip of nothing between them is a strip the pointer crosses on
/// its way in, and it would land on a sibling row and close what it was
/// reaching for. Near the right edge the layer snaps rather than flipping;
/// gpui's `anchored` picks no sides.
///
/// No `closing`: a submenu is held open by the cursor, and the cursor is
/// cleared before the menu it hangs in begins its own exit.
pub fn anchored_submenu(id: impl Into<SharedString>, content: AnyElement) -> AnyElement {
    div()
        .absolute()
        .top(px(-MENU_PAD))
        .right(px(-MENU_PAD))
        .size_0()
        .child(menu_layer(id, content, None, Anchor::TopLeft, None, 0.0))
        .into_any_element()
}

/// [`anchored_menu`] opening UPWARD from the trigger (composer pickers, the
/// user menu — anything anchored near the window bottom; Radix flips these
/// automatically, gpui's `anchored` needs the side picked).
pub fn anchored_menu_above(
    id: impl Into<SharedString>,
    content: AnyElement,
    closing: Option<web_time::Instant>,
) -> AnyElement {
    pinned_layer(menu_layer(
        id,
        content,
        closing,
        Anchor::BottomLeft,
        None,
        6.0,
    ))
}

/// Open an upward menu at a point inside a relative trigger. Useful for text
/// completions, whose natural anchor is the token/caret rather than the input
/// element's outer edge.
pub fn anchored_menu_above_at(
    id: impl Into<SharedString>,
    position: Point<Pixels>,
    content: AnyElement,
    closing: Option<web_time::Instant>,
) -> AnyElement {
    div()
        .absolute()
        .left(position.x)
        .top(position.y)
        .size_0()
        .child(anchored_menu_above(id, content, closing))
        .into_any_element()
}

/// [`anchored_menu_above`] right-aligned to the trigger's right edge (t3code
/// ComboboxPopup `align="end"` — right-side triggers like the composer's ref
/// picker open leftward instead of running off the window).
pub fn anchored_menu_above_end(
    id: impl Into<SharedString>,
    content: AnyElement,
    closing: Option<web_time::Instant>,
) -> AnyElement {
    div()
        .absolute()
        .top_0()
        .right_0()
        .size_0()
        .child(menu_layer(
            id,
            content,
            closing,
            Anchor::BottomRight,
            None,
            6.0,
        ))
        .into_any_element()
}

/// A floating menu at an explicit window position (context menus). Occludes
/// like [`anchored_menu`] so row clicks never reach elements underneath.
pub fn menu_at(
    id: impl Into<SharedString>,
    position: Point<Pixels>,
    content: AnyElement,
    closing: Option<web_time::Instant>,
) -> AnyElement {
    menu_layer(id, content, closing, Anchor::TopLeft, Some(position), 0.0)
}

/// Modal/overlay scrim at the *current* appearance, quoted in dark-mode terms
/// like [`ink`]/[`hairline`] — for callers (`modal`, the attachment lightbox)
/// that paint from a `deferred`/`anchored` layer with no `Theme`/`cx` in
/// scope. Mirrors [`Theme::scrim`], which is pinned at `X = 0.6` dark /
/// `0.32` light; other dark-mode alphas scale the light side by the same
/// ratio so the *dark* result is always exactly `alpha_dark` (never routed
/// through [`Hsla::opacity`], whose `0..=1` clamp would clip a
/// larger-than-0.6 alpha before it could scale the light side).
pub(crate) fn scrim_alpha(alpha_dark: f32) -> gpui::Hsla {
    theme::scrim(alpha_dark)
}

/// Full-window modal: dim scrim + centered card with the `dialog-in` entrance.
/// The scrim swallows clicks; the caller wires its own dismiss/confirm.
/// `viewport` is the window size (an `anchored` layer sizes to its children,
/// so the scrim needs explicit dimensions). The frost radius matches
/// [`dialog_card`]'s 16px rounding.
/// `on_dismiss` is the scrim press. It is a parameter rather than the caller's
/// `.on_mouse_down_out`, for the same reason [`sheet`]'s is: the scrim lives
/// inside this deferred layer, so nothing outside can reach it. Without it a
/// dialog could not be dismissed by clicking away from it *by any caller* —
/// which is how this one shipped, and what it looked like was a dialog that
/// only closed on its own buttons.
pub fn modal(
    id: impl Into<ElementId>,
    viewport: gpui::Size<Pixels>,
    card: AnyElement,
    on_dismiss: impl Fn(&gpui::MouseDownEvent, &mut gpui::Window, &mut gpui::App) + 'static,
) -> AnyElement {
    modal_with(id, viewport, card, DIALOG_RADIUS, 0.6, on_dismiss)
}

/// [`modal`] for glass-tinted cards (the add-space palette): a LIGHTER scrim,
/// so the material card reads like the popovers — the standard 0.6 dim buried
/// the backdrop hue under the blur and the palette came out a flat grey slab
/// next to the hue-inheriting menus (user report).
///
/// The radius is [`Theme::surface_radius`], not a parameter: a glass-tinted
/// modal *is* a popover surface, and the parameter this used to take carried
/// the doc line "must match the card's rounding" — a footgun handed to the
/// caller in writing.
pub fn modal_glass(
    id: impl Into<ElementId>,
    viewport: gpui::Size<Pixels>,
    card: AnyElement,
    on_dismiss: impl Fn(&gpui::MouseDownEvent, &mut gpui::Window, &mut gpui::App) + 'static,
) -> AnyElement {
    modal_with(
        id,
        viewport,
        card,
        Theme::surface_radius(),
        0.35,
        on_dismiss,
    )
}

fn modal_with(
    id: impl Into<ElementId>,
    viewport: gpui::Size<Pixels>,
    card: AnyElement,
    corner_radius: f32,
    scrim: f32,
    on_dismiss: impl Fn(&gpui::MouseDownEvent, &mut gpui::Window, &mut gpui::App) + 'static,
) -> AnyElement {
    let card = crate::surface::popover(corner_radius, card).into_any_element();
    gpui::deferred(
        gpui::anchored()
            .position(gpui::point(px(0.0), px(0.0)))
            .child(
                div()
                    .occlude()
                    .w(viewport.width)
                    .h(viewport.height)
                    .bg(scrim_alpha(scrim))
                    .flex()
                    .items_center()
                    .justify_center()
                    // On the card's wrapper, not the scrim: a press inside the
                    // card is not "out", so the dialog's own buttons keep
                    // working with no occluding overlay and no propagation
                    // games. The scrim covers the viewport and occludes, so
                    // "outside the card" and "on the scrim" are the same press.
                    .child(motion::dialog_in(
                        id,
                        div().child(card).on_mouse_down_out(on_dismiss),
                    )),
            ),
    )
    .priority(2)
    .into_any_element()
}

// ---------------------------------------------------------------------------
// Sheet — a dialog pinned to an edge
// ---------------------------------------------------------------------------

/// Which edge a [`sheet`] slides in from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
    Left,
    Right,
    /// Up from the bottom edge, full width — the shape a phone puts a picker
    /// or a share list in, and what a narrow window wants instead of a side
    /// panel that leaves no room for the page behind it.
    Bottom,
}

impl Side {
    /// Which way the panel travels. The extent a [`sheet`] is given is read
    /// along this axis: a width for the vertical edges, a height for the
    /// horizontal one.
    fn axis(self) -> gpui::Axis {
        match self {
            Side::Left | Side::Right => gpui::Axis::Horizontal,
            Side::Bottom => gpui::Axis::Vertical,
        }
    }
}

/// Corner rounding of [`dialog_card`], and of a [`sheet_panel`]'s two inner
/// corners (the two on the window edge are off-screen). One number rather than
/// two that happen to match: a sheet *is* the dialog card, pinned to an edge
/// instead of centred. Read three times over — the card, the sheet panel, and
/// the blur under each — which is exactly why it is not a literal.
const DIALOG_RADIUS: f32 = 16.0;

/// The panel body of a [`sheet`]: glass card chrome rounded and hairlined on
/// its *inner* edge only — the corners against the window edge are off-screen
/// — so it reads as pulled out of the window rather than floating near it.
pub fn sheet_panel(theme: &Theme, side: Side) -> gpui::Div {
    let card = div()
        .size_full()
        .flex()
        .flex_col()
        .shadow_lg()
        .text_color(theme.text);
    let card = match side {
        Side::Left => card
            .rounded_r(px(DIALOG_RADIUS))
            .border_r_1()
            .border_color(hairline(0.10)),
        Side::Right => card
            .rounded_l(px(DIALOG_RADIUS))
            .border_l_1()
            .border_color(hairline(0.10)),
        Side::Bottom => card
            .rounded_t(px(DIALOG_RADIUS))
            .border_t_1()
            .border_color(hairline(0.10)),
    };
    if theme.glass {
        card.bg(theme.glass_overlay())
    } else {
        card.bg(theme.surface_overlay)
    }
}

/// A panel over a dim scrim — [`modal`] pinned to an edge. It slides in over
/// [`motion::DIALOG_IN`] and, once the caller's [`Popup`] enters its exit
/// phase, back out over [`motion::MENU_OUT`] — which it must, because
/// [`Popup::finish_close`] reaps on that spec's span.
///
/// `extent` is measured across the edge the sheet is pinned to: a width on
/// [`Side::Left`] and [`Side::Right`], a height on [`Side::Bottom`]. The other
/// axis always spans the viewport.
///
/// `on_dismiss` is the scrim click. Unlike the anchored menus, dismissal
/// cannot be the caller's `.on_mouse_down_out`: the scrim lives inside this
/// deferred layer, so nothing outside can reach it.
///
/// The slide is written here rather than as a `motion` helper because
/// only the *spec* is motion — which inset carries it is layout, and it
/// differs per side.
pub fn sheet(
    id: impl Into<SharedString>,
    viewport: gpui::Size<Pixels>,
    side: Side,
    extent: Pixels,
    content: AnyElement,
    closing: Option<web_time::Instant>,
    on_dismiss: impl Fn(&gpui::ClickEvent, &mut gpui::Window, &mut gpui::App) + 'static,
) -> AnyElement {
    let id = id.into();
    let exit = closing.map(exit_progress);
    // The panel spans the edge it is pinned to and takes `extent` across it,
    // which is why the argument is not called a width: on [`Side::Bottom`] it
    // is the height.
    let panel = div().absolute();
    let panel = match side.axis() {
        gpui::Axis::Horizontal => panel.top_0().bottom_0().w(extent),
        gpui::Axis::Vertical => panel.left_0().right_0().h(extent),
    };
    let panel = panel.child(crate::surface::popover(DIALOG_RADIUS, content));
    // `t` runs 0 (fully off-screen) → 1 (seated against the edge).
    let seat = move |el: gpui::Div, t: f32| {
        let inset = extent * (t - 1.0);
        match side {
            Side::Left => el.left(inset),
            Side::Right => el.right(inset),
            Side::Bottom => el.bottom(inset),
        }
    };
    let panel = if let Some(t) = exit {
        // The dying panel must not take clicks — same overlay `menu_motion`
        // puts over an exiting menu.
        let panel = seat(panel, 1.0 - t).child(div().absolute().inset_0().occlude());
        panel
            .with_animation(
                SharedString::from(format!("{id}-out")),
                motion::MENU_OUT.animation(),
                move |el, _| el,
            )
            .into_any_element()
    } else {
        panel
            .with_animation(id.clone(), motion::DIALOG_IN.animation(), seat)
            .into_any_element()
    };

    gpui::deferred(
        gpui::anchored()
            .position(gpui::point(px(0.0), px(0.0)))
            .child(
                div()
                    .id(SharedString::from(format!("{id}-scrim")))
                    .occlude()
                    .relative()
                    .w(viewport.width)
                    .h(viewport.height)
                    .bg(scrim_alpha(0.6 * (1.0 - exit.unwrap_or(0.0))))
                    .on_click(on_dismiss)
                    .child(panel),
            ),
    )
    .priority(2)
    .into_any_element()
}

/// One menu row (the reference `menuItem`): `gap-2.5 rounded-lg px-2 py-1.5`,
/// active = `bg-white/10 text-foreground`. The caller adds the id/click
/// listener.
///
/// `active` is the row the cursor is on, and a menu has exactly one cursor.
/// `Some(fade)` lets the mouse light a row by itself, animated over
/// `transition-colors` (floating-styles.ts), for a menu holding no cursor of
/// its own; its key must be stable across frames (the id string is a good
/// choice). `None` is for a menu that owns an active index and moves it from
/// `on_mouse_move` — move, not hover: gpui settles hover at paint time, so a
/// list that re-filters or scrolls under a still mouse would drag the cursor
/// to wherever the pointer sits.
pub fn menu_row(theme: &Theme, active: bool, fade: Option<Fade>) -> gpui::Div {
    let row = div()
        .flex()
        .flex_row()
        .items_center()
        .gap(px(10.0))
        .px(px(8.0))
        .py(px(6.0))
        // Concentric with the card it sits in rather than a radius of its own:
        // 12 − 4 = 8, which is where the crate's most-repeated corner value
        // came from all along.
        .rounded(px(Theme::inset_radius(Theme::surface_radius(), MENU_PAD)))
        .text_style(TextStyle::Body)
        .cursor_pointer();
    match (active, fade) {
        (true, _) => row.bg(theme.card_selected_bg()).text_color(theme.text),
        (false, None) => row.text_color(theme.text.opacity(0.9)),
        (false, Some(fade)) => {
            let mut row = row
                .text_color(motion::hover_blend(
                    &fade,
                    theme.text.opacity(0.9),
                    theme.text,
                ))
                .bg(motion::hover_blend(
                    &fade,
                    theme::ink(0.0),
                    theme.element_hover,
                ));
            // Imperative form — the caller's `.id(...)` makes the element stateful
            // (hover listeners need element state, `.on_hover` needs `Stateful`).
            row.interactivity().on_hover(motion::hover_listener(fade));
            row
        }
    }
}

/// Small uppercase section heading inside a floating menu (the reference
/// `MenuHeading`): `px-2 pb-1 pt-1.5 uppercase tracking-[0.1em]
/// text-muted-foreground/60`. gpui has no letter-spacing at the pinned rev;
/// the tracking is approximated with hair spaces.
pub fn menu_heading(theme: &Theme, label: impl Into<SharedString>) -> gpui::Div {
    let label = label.into();
    div()
        .px(px(8.0))
        .pb(px(4.0))
        .pt(px(6.0))
        .text_style(TextStyle::Caption2)
        .text_color(theme.text_muted.opacity(0.6))
        .child(tracked_upper(&label))
}

/// Uppercase + hair-space tracking (see [`menu_heading`]).
pub fn tracked_upper(label: &str) -> String {
    let upper = label.to_uppercase();
    let mut out = String::with_capacity(upper.len() * 2);
    let mut first = true;
    for ch in upper.chars() {
        if !first {
            out.push('\u{200A}'); // hair space ≈ 0.1em tracking
        }
        out.push(ch);
        first = false;
    }
    out
}

/// Hairline divider between menu sections (the reference `MenuSeparator`:
/// `mx-1 my-1 h-px bg-white/[0.07]`).
pub fn divider() -> gpui::Div {
    // Full-bleed: negative margins cancel the card's p-1 inset so the hairline
    // runs border to border (user request).
    div().h(px(1.0)).mx(px(-4.0)).my(px(4.0)).bg(hairline(0.07))
}

/// The recessed band tone for a palette/picker header or footer strip — a
/// translucent black so the glass still reads through (the add-space palette
/// converged on this; measured subtler tones vanish against the dim scrim).
/// Free function (like [`ink`]/[`hairline`]/[`wash`]), mirroring
/// [`Theme::band`], for the several callers with no `Theme`/`cx` in scope
/// (some outside this crate's `ui` module tree — threading a `&Theme` param
/// would ripple past this task's file scope).
pub fn band() -> gpui::Hsla {
    theme::band()
}

/// One footer key-cap (22px, rounded-5, `white/[0.05]`) holding arbitrary
/// children — the base of [`key_hint`]/[`key_hint_pair`] and the search-bar
/// chips ("⌘K", "esc").
pub fn key_cap(_theme: &Theme) -> gpui::Div {
    div()
        .h(px(22.0))
        .px(px(5.0))
        .rounded(px(5.0))
        .flex()
        .flex_row()
        .items_center()
        .justify_center()
        .gap(px(4.0))
        .bg(ink(0.05))
}

/// The tiny verb after a key-cap.
fn key_hint_label(theme: &Theme, label: &'static str) -> gpui::Div {
    div()
        .text_style(TextStyle::Caption)
        .text_color(theme.text_muted.opacity(0.45))
        .child(SharedString::from(label))
}

/// A footer legend: one icon key-cap + tiny verb (the add-space palette's
/// footer voice, shared by the pickers).
pub fn key_hint(theme: &Theme, icon: impl Into<Icon>, label: &'static str) -> gpui::Div {
    div()
        .flex()
        .flex_row()
        .items_center()
        .gap(px(5.0))
        .child(
            key_cap(theme).child(
                crate::icons::icon(icon)
                    .size(px(12.5))
                    .text_color(theme.text_muted.opacity(0.7)),
            ),
        )
        .child(key_hint_label(theme, label))
}

/// A footer legend whose cap holds a WORD ("tab", "esc") instead of a glyph
/// — for keys with no icon in the set.
pub fn key_hint_text(
    theme: &Theme,
    cap: impl Into<SharedString>,
    label: &'static str,
) -> gpui::Div {
    div()
        .flex()
        .flex_row()
        .items_center()
        .gap(px(5.0))
        .child(
            key_cap(theme)
                .text_style(TextStyle::Subheadline)
                .font_family(theme.font_mono.clone())
                .text_color(theme.text_muted.opacity(0.7))
                .child(cap.into()),
        )
        .child(key_hint_label(theme, label))
}

/// A footer legend whose cap holds TWO glyphs split by a hairline
/// ("[ ↑ | ↓ ] Navigate") sharing one verb.
pub fn key_hint_pair(
    theme: &Theme,
    first: impl Into<Icon>,
    second: impl Into<Icon>,
    label: &'static str,
) -> gpui::Div {
    div()
        .flex()
        .flex_row()
        .items_center()
        .gap(px(5.0))
        .child(
            key_cap(theme)
                .child(
                    crate::icons::icon(first)
                        .size(px(12.5))
                        .text_color(theme.text_muted.opacity(0.7)),
                )
                .child(div().w(px(1.0)).h(px(11.0)).bg(hairline(0.10)))
                .child(
                    crate::icons::icon(second)
                        .size(px(12.5))
                        .text_color(theme.text_muted.opacity(0.7)),
                ),
        )
        .child(key_hint_label(theme, label))
}

/// A muted kbd hint chip inside menu rows (`⌘↵`-style accelerators).
pub fn kbd_hint(theme: &Theme, label: impl Into<SharedString>) -> gpui::Div {
    div()
        .flex_none()
        .px(px(5.0))
        .py(px(1.0))
        .rounded(px(5.0))
        .bg(ink(0.05))
        .text_style(TextStyle::Caption)
        .font_family(theme.font_mono.clone())
        .text_color(theme.text_muted.opacity(0.6))
        .child(label.into())
}

/// The query line at the top of a picker popover: a magnifier, the field, and
/// a hairline under it.
///
/// The field belongs in `with_frame(false)` — a box here would be a second
/// frame inside the card's. Full-bleed like [`divider`], and the glyph sits on
/// the row labels' own inset so the line reads as the head of the list rather
/// than a control dropped on top of it.
pub fn search_line(theme: &Theme, input: AnyElement) -> gpui::Div {
    stack::row()
        .mx(px(-MENU_PAD))
        .px(px(MENU_PAD + 8.0))
        .py(px(7.0))
        .mb(px(MENU_PAD))
        .border_b_1()
        .border_color(hairline(0.07))
        .text_style(TextStyle::Body)
        .child(
            icons::icon(icons::glyph::Search)
                .size(px(13.0))
                .text_color(theme.text_faint),
        )
        .child(div().flex_1().child(input))
}

/// A bordered trailing menu section (the reference picker action groups /
/// branch-picker worktree block: `mt-1 flex flex-col gap-0.5 border-t
/// border-white/[0.06] pt-1` — the hairline runs edge-to-edge of the card's
/// p-1 inset, unlike [`divider`]'s mx-1).
pub fn menu_section() -> gpui::Div {
    div()
        .mt(px(4.0))
        .pt(px(4.0))
        .border_t_1()
        .border_color(hairline(0.06))
        .flex()
        .flex_col()
        .gap(px(2.0))
}

// ---------------------------------------------------------------------------
// Dialog primitives (the reference dialog.tsx / sidebar dialogs.tsx)
// ---------------------------------------------------------------------------

/// The centered dialog card (`dialog-pop`): `w-[360px] rounded-2xl border
/// border-white/[0.1] bg-popover/95 p-5 shadow-2xl` — popover tone ≈ #101010.
pub fn dialog_card(theme: &Theme) -> gpui::Div {
    div()
        .w(px(360.0))
        .p(px(20.0))
        .rounded(px(DIALOG_RADIUS))
        .bg(theme.surface_dialog)
        .border_1()
        .border_color(hairline(0.10))
        .shadow_lg()
        .flex()
        .flex_col()
        .text_color(theme.text)
}

/// Dialog title.
pub fn dialog_title(theme: &Theme, title: impl Into<SharedString>) -> gpui::Div {
    div()
        .text_style(TextStyle::Headline)
        .text_color(theme.text)
        .child(title.into())
}

/// Dialog body copy: `leading-relaxed text-muted-foreground`.
pub fn dialog_body(theme: &Theme, copy: impl Into<SharedString>) -> gpui::Div {
    div()
        .text_style(TextStyle::Body)
        .line_height(px(19.0))
        .text_color(theme.text_muted)
        .child(copy.into())
}

/// Dialog text-field frame: `rounded-lg border border-white/[0.08]
/// bg-white/[0.04] px-3 py-2`.
pub fn dialog_field(input: AnyElement) -> gpui::Div {
    div()
        .w_full()
        .px(px(12.0))
        .py(px(8.0))
        .rounded(px(Theme::button_radius()))
        .border_1()
        .border_color(hairline(0.08))
        .bg(ink(0.04))
        .text_style(TextStyle::Body)
        .child(input)
}

/// Pulsing skeleton rows shown while a list loads (the reference:
/// `h-7 animate-pulse rounded-md bg-white/[0.04]`).
pub fn redacted_rows(
    _id: &'static str,
    _theme: &Theme,
    count: usize,
    painter: Painter,
    cx: &mut gpui::App,
) -> AnyElement {
    let wash = ink(0.04);
    let delta = motion::pulse_delta(&PULSE, painter, cx);
    div()
        .flex()
        .flex_col()
        .gap(px(6.0))
        .py(px(4.0))
        .children((0..count).map(move |i| {
            let phase = motion::staggered_phase(delta, i, 0.08);
            div()
                .h(px(28.0))
                .rounded(px(Theme::control_radius()))
                .bg(wash)
                .opacity(0.35 + 0.4 * motion::pulse_wave(phase))
        }))
        .into_any_element()
}

/// Inline error row + Retry affordance (the caller attaches the listener to the
/// returned id).
pub fn error_row(theme: &Theme, message: impl Into<SharedString>) -> gpui::Div {
    div()
        .flex()
        .flex_col()
        .gap(px(6.0))
        .p(px(Theme::SPACE))
        .text_style(TextStyle::Callout)
        .text_color(theme.danger)
        .child(message.into())
}