fluidattacks-designs 0.12.0

Fluid Attacks design system, GPUI variant: desktop widgets over the shared tokens
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
//! `Select` — the web combobox: a field holding one chosen value, over a
//! menu that filters as you type.
//!
//! [`SelectState`] holds the options and the standing as an entity the app
//! owns; [`Select`] renders it:
//!
//! ```ignore
//! let picker = cx.new(|cx| SelectState::new("Select a group", window, cx));
//! picker.update(cx, |state, cx| state.set_options(options, cx));
//! Select::new(&picker).on_change(|value, _| load_group(value))
//! ```
//!
//! Filling the menu and choosing from it are different things, and only the
//! second reports: [`SelectState::set_options`] cannot reach `on_change`.
//!
//! Out of scope against the web: multi-selection, the clear button, per-option
//! tags and links, and the label, help and error rows the outline container
//! carries.

use fluidattacks_designs_domain::icon::Style as IconStyle;
use fluidattacks_designs_domain::inputs::{Size, State, Validation, PLACEHOLDER};
use fluidattacks_designs_domain::navigation::{choosable, label_of, position_of, step, Step};
use fluidattacks_designs_domain::select::{
    compare, grouped, header_at, matches, menu_height, Item, CHEVRON, CHEVRON_CLOSED,
    CHEVRON_DISABLED, CHEVRON_GLYPH, CHEVRON_OPEN, EMPTY_MESSAGE, EMPTY_TEXT, GROUP_BORDER,
    GROUP_HEIGHT, GROUP_MARGIN_Y, GROUP_TEXT, GROUP_WEIGHT, MENU_BG, MENU_BORDER, MENU_MIN_WIDTH,
    MENU_OFFSET, MENU_PADDING_Y, MENU_RADIUS, MENU_SHADOW, OPTION_DISABLED_BG,
    OPTION_DISABLED_TEXT, OPTION_GAP, OPTION_HEIGHT, OPTION_HOVER_BG, OPTION_LINE_HEIGHT,
    OPTION_PADDING, OPTION_SELECTED_BG, OPTION_TEXT, OPTION_TEXT_SIZE, SELECTED_GLYPH,
    SELECTED_ICON,
};
use fluidattacks_designs_domain::typography::FONT_PRIMARY;
use gpui::prelude::FluentBuilder as _;
use gpui::{
    anchored, canvas, deferred, div, point, px, rgb, uniform_list, App, AppContext as _, Context,
    Div, Entity, FocusHandle, Focusable, FontWeight, InteractiveElement as _, IntoElement,
    KeyBinding, MouseButton, ParentElement as _, Pixels, Point, RenderOnce, ScrollHandle,
    SharedString, Stateful, StatefulInteractiveElement as _, Styled as _, UniformListScrollHandle,
    Window,
};

use crate::icon::Icon;
use crate::text_input::{sized_field_frame, TextInputState};
use crate::theme::{ActiveTheme as _, Theme};
use crate::widget::{elevation, report, scrolling, text, ValueHandler};

const CONTEXT: &str = "DesignsSelect";
const SCROLLBAR: &str = "designs-select-scrollbar";

#[allow(
    clippy::derive_partial_eq_without_eq,
    reason = "the actions! expansion derives PartialEq without Eq"
)]
mod action_defs {
    gpui::actions!(designs_select, [Next, Previous, Confirm, Dismiss]);
}

use action_defs::{Confirm, Dismiss, Next, Previous};

/// Bind the menu's keymap. [`crate::Theme::init`] calls this; an app that
/// installs the theme needs nothing of its own.
pub fn bind_keys(cx: &mut App) {
    cx.bind_keys([
        KeyBinding::new("down", Next, Some(CONTEXT)),
        KeyBinding::new("up", Previous, Some(CONTEXT)),
        KeyBinding::new("enter", Confirm, Some(CONTEXT)),
        KeyBinding::new("escape", Dismiss, Some(CONTEXT)),
    ]);
}

/// One row of the list a select is given — the web's `IItem`.
#[derive(Clone, Debug)]
pub struct SelectOption {
    label: SharedString,
    value: SharedString,
    group: Option<SharedString>,
    disabled: bool,
}

impl SelectOption {
    #[must_use]
    pub fn new(label: impl Into<SharedString>, value: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            value: value.into(),
            group: None,
            disabled: false,
        }
    }

    /// The header this row files under. One grouped row is enough to put the
    /// whole menu under headers.
    #[must_use]
    pub fn group(mut self, group: impl Into<SharedString>) -> Self {
        self.group = Some(group.into());
        self
    }

    /// Shown, but not choosable by pointer or keyboard.
    #[must_use]
    pub const fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    fn as_item(&self) -> Item<'_> {
        Item {
            label: &self.label,
            value: &self.value,
            group: self.group.as_ref().map(text),
            disabled: self.disabled,
        }
    }
}

/// What a select holds: its options, which one is chosen, and whether the menu
/// is open and where the keyboard sits in it.
pub struct SelectState {
    field: Entity<TextInputState>,
    options: Vec<SelectOption>,
    /// Options in display order, minus the ones the query rules out. Indices
    /// into `options`, the way the table keeps its visible rows.
    shown: Vec<usize>,
    value: Option<SharedString>,
    /// Where the keyboard sits, as a position in `shown`.
    highlight: Option<usize>,
    open: bool,
    empty_message: SharedString,
    /// Kept alongside the field's own copy: a disabled select renders its text
    /// itself, and the field does not hand its placeholder back out.
    placeholder: SharedString,
    scroll: UniformListScrollHandle,
    /// The grouped menu draws its rows straight, so it scrolls on a plain
    /// handle rather than the virtualized one.
    group_scroll: ScrollHandle,
    /// Last frame's field width, which the menu matches. The web measures the
    /// field the same way; nothing else can tell a floating box how wide the
    /// control it hangs off turned out to be.
    field_width: Option<Pixels>,
    /// Last frame's field position, and where it stood when the menu opened.
    /// The two parting is how the select learns that something scrolled.
    field_origin: Option<Point<Pixels>>,
    anchor: Option<Point<Pixels>>,
}

impl SelectState {
    /// The placeholder is taken up front because it is what the field reads
    /// whenever nothing is chosen, which for a select is its resting state
    /// rather than a decoration.
    pub fn new(
        placeholder: impl Into<SharedString>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        let prompt: SharedString = placeholder.into();
        let shown = prompt.clone();
        let field = cx.new(|inner| TextInputState::new(window, inner).placeholder(shown));
        cx.observe(&field, |state, _, inner| state.field_changed(inner))
            .detach();
        let focus = field.read(cx).focus_handle(cx);
        // the web opens on focus (`menuTrigger: "focus"`), so a click on the
        // field is enough to see the list
        cx.on_focus(&focus, window, |state, _, inner| state.open_menu(inner))
            .detach();
        Self {
            field,
            options: Vec::new(),
            shown: Vec::new(),
            value: None,
            highlight: None,
            open: false,
            empty_message: SharedString::new_static(EMPTY_MESSAGE),
            placeholder: prompt,
            scroll: UniformListScrollHandle::new(),
            group_scroll: ScrollHandle::new(),
            field_width: None,
            field_origin: None,
            anchor: None,
        }
    }

    /// What the menu says when the query leaves no rows.
    #[must_use]
    pub fn empty_message(mut self, message: impl Into<SharedString>) -> Self {
        self.empty_message = message.into();
        self
    }

    /// Replace the list. This is repopulation, not a choice: it reports
    /// nothing, and it leaves the chosen value alone so a list arriving late
    /// does not throw away what the app had already set.
    pub fn set_options(&mut self, options: Vec<SelectOption>, cx: &mut Context<Self>) {
        self.options = options;
        self.recompute("");
        self.sync_field(cx);
        self.highlight = self.selected_position();
        cx.notify();
    }

    /// Set the chosen value from the app's side, which also reports nothing.
    pub fn set_value(&mut self, value: Option<impl Into<SharedString>>, cx: &mut Context<Self>) {
        self.value = value.map(Into::into);
        self.sync_field(cx);
        cx.notify();
    }

    #[must_use]
    pub const fn value(&self) -> Option<&SharedString> {
        self.value.as_ref()
    }

    #[must_use]
    pub const fn is_open(&self) -> bool {
        self.open
    }

    /// Take the choice at a position in the shown list, or `None` when that
    /// row cannot be chosen. Only the keyboard resolves a position: a click
    /// arrives alongside the dismissal and would read its position against a
    /// list already unfiltered.
    fn take(&mut self, position: usize, cx: &mut Context<Self>) -> Option<SharedString> {
        if !choosable(&self.shown_items(), position) {
            return None;
        }
        let value = self
            .shown
            .get(position)
            .and_then(|&index| self.options.get(index))
            .map(|option| option.value.clone())?;
        self.choose(value.clone(), cx);
        Some(value)
    }

    fn choose(&mut self, value: SharedString, cx: &mut Context<Self>) {
        self.value = Some(value);
        self.close(cx);
    }

    /// Show the list, standing on whatever is already chosen. Idempotent, so
    /// a press re-opens a field that already holds the caret and hands out no
    /// focus.
    fn open_menu(&mut self, cx: &mut Context<Self>) {
        self.open = true;
        self.highlight = self.selected_position();
        self.anchor = self.field_origin;
        cx.notify();
    }

    fn close(&mut self, cx: &mut Context<Self>) {
        self.open = false;
        self.highlight = None;
        self.anchor = None;
        self.recompute("");
        self.sync_field(cx);
        cx.notify();
    }

    /// Whether the field has moved out from under an open menu.
    ///
    /// `anchored` keeps the menu inside the window, so a scrolling field leaves
    /// it pinned to the edge rather than taking it along. The web closes for
    /// the same reason (`react-aria`'s `usePopover`), and so does this. A
    /// resize or a reflow strands the menu just as a scroll does, so any
    /// movement counts.
    fn drifted(&self) -> bool {
        match (self.anchor, self.field_origin) {
            // nothing to compare against on the frame the menu opens
            (Some(anchor), Some(origin)) => anchor != origin,
            _ => false,
        }
    }

    fn walk(&mut self, direction: Step, cx: &mut Context<Self>) {
        self.open = true;
        if let Some(next) = step(&self.shown_items(), self.highlight, direction) {
            self.highlight = Some(next);
            self.scroll.scroll_to_item(next, gpui::ScrollStrategy::Top);
        }
        cx.notify();
    }

    /// The query is what the field holds once it stops reading as the chosen
    /// label — so a menu that just opened shows everything, and one letter
    /// narrows it. Nothing has to remember whether the last write was the
    /// reader's or ours.
    fn query(&self, cx: &App) -> String {
        let typed = self.field.read(cx).value();
        if Some(typed) == self.selected_label() {
            return String::new();
        }
        typed.to_owned()
    }

    fn field_changed(&mut self, cx: &mut Context<Self>) {
        let query = self.query(cx);
        // an empty query is the field reading as the chosen label, which is
        // what our own writes leave behind: show everything, and stand on the
        // choice rather than on the first row
        if query.is_empty() {
            self.recompute("");
            self.highlight = self.selected_position();
            cx.notify();
            return;
        }
        // typing is the reader reaching for the list
        self.open = true;
        self.recompute(&query);
        self.highlight = step(&self.shown_items(), None, Step::Next);
        cx.notify();
    }

    /// Put the chosen label back in the field, which is also what clears a
    /// query the reader abandoned.
    fn sync_field(&self, cx: &mut Context<Self>) {
        let label = self.selected_label().unwrap_or_default().to_owned();
        self.field
            .update(cx, |field, inner| field.set_value(label, inner));
    }

    fn selected_label(&self) -> Option<&str> {
        label_of(&self.all_items(), self.value.as_ref().map(text)?)
    }

    fn selected_position(&self) -> Option<usize> {
        position_of(&self.shown_items(), self.value.as_ref().map(text)?)
    }

    fn all_items(&self) -> Vec<Item<'_>> {
        self.options.iter().map(SelectOption::as_item).collect()
    }

    /// How many headers the shown rows open, which the menu adds to its own
    /// height — a header is taller than the row under it.
    fn header_count(&self) -> u16 {
        let items = self.shown_items();
        let opened = (0..items.len())
            .filter(|&position| header_at(&items, position).is_some())
            .count();
        u16::try_from(opened).unwrap_or(u16::MAX)
    }

    fn shown_items(&self) -> Vec<Item<'_>> {
        self.shown
            .iter()
            .filter_map(|&index| self.options.get(index))
            .map(SelectOption::as_item)
            .collect()
    }

    /// Order the whole list, then drop what the query rules out. Sorting
    /// first is what lets the filter keep the order, and what makes a group's
    /// rows contiguous so headers can be derived from them.
    fn recompute(&mut self, query: &str) {
        let shown = {
            let items = self.all_items();
            let has_groups = grouped(&items);
            let mut order: Vec<usize> = (0..items.len()).collect();
            order.sort_by(
                |&first, &second| match (items.get(first), items.get(second)) {
                    (Some(left), Some(right)) => compare(left, right, has_groups),
                    _ => core::cmp::Ordering::Equal,
                },
            );
            order
                .into_iter()
                .filter(|&index| items.get(index).is_some_and(|item| matches(item, query)))
                .collect()
        };
        self.shown = shown;
    }
}

impl Focusable for SelectState {
    fn focus_handle(&self, cx: &App) -> FocusHandle {
        self.field.read(cx).focus_handle(cx)
    }
}

#[derive(IntoElement)]
pub struct Select {
    state: Entity<SelectState>,
    disabled: bool,
    size: Size,
    on_change: Option<ValueHandler>,
}

impl Select {
    #[must_use]
    pub fn new(state: &Entity<SelectState>) -> Self {
        Self {
            state: state.clone(),
            disabled: false,
            size: Size::default(),
            on_change: None,
        }
    }

    /// The whole field goes dead: no menu, no typing, gray-100 behind a
    /// gray-300 chevron.
    #[must_use]
    pub const fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// How large the field sits. [`Size::Sm`] is the number-and-chevron the
    /// web's paginator uses; the default is a full field.
    #[must_use]
    pub const fn size(mut self, size: Size) -> Self {
        self.size = size;
        self
    }

    /// Called with the value a reader chose, and only then — never when
    /// [`SelectState::set_options`] or [`SelectState::set_value`] moves it.
    #[must_use]
    pub fn on_change(mut self, handler: impl Fn(&str, &mut App) + 'static) -> Self {
        self.on_change = Some(std::rc::Rc::new(handler));
        self
    }
}

impl RenderOnce for Select {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let Self {
            state,
            disabled,
            size,
            on_change,
        } = self;
        let focused = state.read(cx).focus_handle(cx).is_focused(window);
        let open = state.read(cx).open && !disabled;
        let standing = State::resolve(focused, Validation::None, disabled);
        let element = div()
            .key_context(CONTEXT)
            .relative()
            .w_full()
            .child(measure(&state))
            .child(field_at(&state, standing, disabled, cx, size))
            .when(open, |el| {
                el.child(deferred(hung(menu(&state, on_change.as_ref(), cx), size)))
            });
        if disabled {
            element
        } else {
            actions(element, &state, on_change)
        }
    }
}

/// The keyboard, and the click that lands anywhere but on this select.
/// Dismissing on a mouse-down outside rather than on blur is what lets a click
/// on a row land at all: choosing blurs the field.
fn actions(element: Div, state: &Entity<SelectState>, on_change: Option<ValueHandler>) -> Div {
    let (walking, stepping, confirming, dismissing, outside) = (
        state.clone(),
        state.clone(),
        state.clone(),
        state.clone(),
        state.clone(),
    );
    element
        .on_action(move |_: &Next, _win, app| {
            walking.update(app, |select, inner| select.walk(Step::Next, inner));
        })
        .on_action(move |_: &Previous, _win, app| {
            stepping.update(app, |select, inner| select.walk(Step::Previous, inner));
        })
        .on_action(move |_: &Dismiss, _win, app| {
            dismissing.update(app, SelectState::close);
        })
        .on_action(move |_: &Confirm, _win, app| {
            let Some(position) = confirming.read(app).highlight else {
                return;
            };
            let chosen = confirming.update(app, |select, inner| select.take(position, inner));
            report(chosen, on_change.as_ref(), app);
        })
        .on_mouse_down_out(move |_, _win, app| {
            outside.update(app, SelectState::close);
        })
}

/// Hang the menu off the field's *top* edge, the field's own height and the
/// web's gap below it. The height has to come from `size`: measuring the drop
/// against a full field would leave a small one holding its menu adrift.
///
/// An anchored element with no explicit position falls back to where it was
/// laid out — below the field — so the flipped menu would cover it. The strip
/// pins the anchor to the top edge and carries no height of its own.
fn hung(menu: Div, size: Size) -> Div {
    div().absolute().top_0().left_0().w_full().h(px(0.0)).child(
        anchored()
            .offset(point(px(0.0), px(size.height() + MENU_OFFSET)))
            .child(menu),
    )
}

/// Read the field's width and position off the frame that just laid it out:
/// the menu matches the width and closes when the position moves. Paints
/// nothing.
fn measure(state: &Entity<SelectState>) -> impl IntoElement {
    let measuring = state.clone();
    canvas(
        move |bounds, _win, app| {
            measuring.update(app, |select, inner| {
                // no notify: both are read on the next frame the menu draws,
                // and a redraw asked for from inside one would never settle
                select.field_width = Some(bounds.size.width);
                select.field_origin = Some(bounds.origin);
                // closing is the exception, and it settles: one step, and the
                // frame it asks for finds nothing left to close
                if select.open && select.drifted() {
                    select.close(inner);
                }
            });
        },
        |_, (), _, _| {},
    )
    .absolute()
    .size_full()
}

/// The field: the same outline box a text input wears, with the editable line
/// inside it and the chevron where the reveal toggle would sit.
fn field_at(
    state: &Entity<SelectState>,
    standing: State,
    disabled: bool,
    cx: &App,
    size: Size,
) -> Div {
    let read = state.read(cx);
    let theme = cx.theme();
    let open = read.open && !disabled;
    sized_field_frame(standing, size, theme)
        .map(|el| {
            if disabled {
                el.cursor(gpui::CursorStyle::OperationNotAllowed)
                    .child(static_text(read, theme))
            } else {
                el.child(editable(state, read.field.clone()))
            }
        })
        .child(chevron(state, open, disabled, theme))
}

/// The editable line, which also opens the list. The chevron is left out of
/// this on purpose, so it keeps working as a toggle.
fn editable(state: &Entity<SelectState>, field: Entity<TextInputState>) -> Stateful<Div> {
    let opening = state.clone();
    div()
        .id("designs-select-field")
        .flex_1()
        .overflow_hidden()
        .child(field)
        .on_mouse_down(MouseButton::Left, move |_, _win, app| {
            opening.update(app, SelectState::open_menu);
        })
}

/// A disabled field cannot hold an editable line, so it reads its own label.
fn static_text(read: &SelectState, theme: &Theme) -> Div {
    let chosen = read.selected_label().map(str::to_owned);
    let empty = chosen.is_none();
    div()
        .flex_1()
        .overflow_hidden()
        .when(empty, |el| el.text_color(rgb(theme.shade(PLACEHOLDER))))
        .child(chosen.map_or_else(
            // an editable field falls back to its placeholder on its own; a
            // disabled one draws its own text and has to do the same, or it
            // reads as a blank box with a chevron
            || read.placeholder.clone(),
            SharedString::from,
        ))
}

/// The chevron flips with the menu and toggles it, as the web's does.
fn chevron(
    state: &Entity<SelectState>,
    open: bool,
    disabled: bool,
    theme: &Theme,
) -> Stateful<Div> {
    let toggling = state.clone();
    div()
        .id("designs-select-chevron")
        .flex()
        .flex_none()
        .items_center()
        .child(
            Icon::new(if open { CHEVRON_OPEN } else { CHEVRON_CLOSED })
                .style(IconStyle::Light)
                .size(CHEVRON_GLYPH)
                .color(theme.shade(if disabled { CHEVRON_DISABLED } else { CHEVRON })),
        )
        .when(!disabled, |el| {
            el.cursor_pointer().on_click(move |_, win, app| {
                toggling.update(app, |select, inner| toggle(select, win, inner));
            })
        })
}

fn toggle(select: &mut SelectState, window: &mut Window, cx: &mut Context<SelectState>) {
    if select.open {
        select.close(cx);
        return;
    }
    select.open_menu(cx);
    // a menu opened by the chevron still has to take the caret, or the next
    // keystroke goes nowhere
    select.focus_handle(cx).focus(window, cx);
}

/// The floating menu: `deferred` paints it over the field's siblings,
/// `anchored` flips it above when there is no room below, `occlude` stops the
/// pointer reaching through. An absolutely positioned child sits outside its
/// parent's hitbox, which is why a row commits on the press.
fn menu(state: &Entity<SelectState>, on_change: Option<&ValueHandler>, cx: &App) -> Div {
    let read = state.read(cx);
    let theme = cx.theme();
    let rows = read.shown.len();
    // the empty message still needs a row's worth of room to sit in
    let slots = u16::try_from(rows.max(1)).unwrap_or(u16::MAX);
    div()
        // an anchored menu is sized by its content, so the width the field
        // measured to is the only thing that can make the two line up; the
        // web's floor stands in until the first frame has been laid out
        .w(read.field_width.unwrap_or(px(MENU_MIN_WIDTH)))
        .h(px(menu_height(slots, read.header_count())))
        .flex()
        .flex_col()
        .overflow_hidden()
        .py(px(MENU_PADDING_Y))
        .bg(rgb(theme.shade(MENU_BG)))
        .border_1()
        .border_color(rgb(theme.shade(MENU_BORDER)))
        .rounded(px(MENU_RADIUS))
        .shadow(elevation(MENU_SHADOW))
        .occlude()
        .font_family(FONT_PRIMARY)
        .text_size(px(OPTION_TEXT_SIZE.px()))
        .map(|el| {
            if rows == 0 {
                el.child(empty_row(read.empty_message.clone(), theme))
            } else {
                el.child(rows_slot(state, rows, on_change, cx))
            }
        })
}

/// A grouped menu draws its rows straight, a flat one virtualizes them: they
/// cannot share one list, because `uniform_list` needs every row the same
/// height and a header is taller than an option.
fn rows_slot(
    state: &Entity<SelectState>,
    rows: usize,
    on_change: Option<&ValueHandler>,
    cx: &App,
) -> gpui::AnyElement {
    let read = state.read(cx);
    if grouped(&read.shown_items()) {
        return scrolling(
            SCROLLBAR,
            div()
                .id("designs-select-grouped-rows")
                .size_full()
                .flex()
                .flex_col()
                .overflow_y_scroll()
                .track_scroll(&read.group_scroll)
                .children((0..rows).map(|position| row(state, position, on_change, cx)))
                .into_any_element(),
            &read.group_scroll,
        );
    }
    let listing = state.clone();
    let handler = on_change.cloned();
    // gpui paints no bar of its own, and the handle a uniform list tracks is
    // the plain one underneath it
    let bar = read.scroll.0.borrow().base_handle.clone();
    scrolling(
        SCROLLBAR,
        uniform_list("designs-select-rows", rows, move |range, _win, app| {
            range
                .map(|position| row(&listing, position, handler.as_ref(), app))
                .collect::<Vec<_>>()
        })
        .track_scroll(&read.scroll)
        .size_full()
        .into_any_element(),
        &bar,
    )
}

/// One row, with the header it opens above it when it starts a group.
fn row(
    state: &Entity<SelectState>,
    position: usize,
    on_change: Option<&ValueHandler>,
    cx: &App,
) -> gpui::AnyElement {
    let read = state.read(cx);
    let theme = cx.theme();
    let items = read.shown_items();
    let Some(item) = items.get(position) else {
        return div().h(px(OPTION_HEIGHT)).into_any_element();
    };
    let chosen = read.value.as_ref().map(text) == Some(item.value);
    let highlighted = read.highlight == Some(position);
    let option = option_row(
        state,
        position,
        (item, chosen, highlighted),
        on_change,
        theme,
    );
    match header_at(&items, position) {
        Some(group) => div()
            .flex()
            .flex_col()
            .w_full()
            .child(group_header(SharedString::from(group.to_owned()), theme))
            .child(option)
            .into_any_element(),
        None => option.into_any_element(),
    }
}

/// The web paints the chosen row gray-200 with a tick, hovers the rest
/// gray-100, and washes a disabled one out.
fn option_row(
    state: &Entity<SelectState>,
    position: usize,
    (item, chosen, highlighted): (&Item<'_>, bool, bool),
    on_change: Option<&ValueHandler>,
    theme: &Theme,
) -> Stateful<Div> {
    let choosing = state.clone();
    let handler = on_change.cloned();
    let live = !item.disabled;
    // the value is read now, while the shown list is the one the reader is
    // looking at, rather than at press time when it may already have changed
    let picked = SharedString::from(item.value.to_owned());
    div()
        .id(("designs-select-option", position))
        .flex()
        .flex_none()
        // a `uniform_list` child sizes to its content, so without this the
        // wash on a hovered or chosen row stops at the end of its label
        .w_full()
        .items_center()
        .justify_between()
        .gap(px(OPTION_GAP))
        .h(px(OPTION_HEIGHT))
        .py(px(OPTION_PADDING.0))
        .px(px(OPTION_PADDING.1))
        .line_height(px(OPTION_LINE_HEIGHT))
        .map(|el| paint(el, (live, chosen, highlighted), theme))
        .child(div().overflow_hidden().child(item.label.to_owned()))
        .when(chosen && live, |el| {
            el.child(
                Icon::new(SELECTED_ICON)
                    .style(IconStyle::Light)
                    .size(SELECTED_GLYPH),
            )
        })
        .when(live, |el| {
            // on the press, not the release: the dismissal below fires during
            // the same event's capture phase, and by the time a release
            // arrived this row would no longer be mounted to receive it
            el.cursor_pointer()
                .on_mouse_down(MouseButton::Left, move |_, _win, app| {
                    choosing.update(app, |select, inner| select.choose(picked.clone(), inner));
                    report(Some(picked.clone()), handler.as_ref(), app);
                })
        })
}

fn paint(
    element: Stateful<Div>,
    (live, chosen, highlighted): (bool, bool, bool),
    theme: &Theme,
) -> Stateful<Div> {
    if !live {
        return element
            .bg(rgb(theme.shade(OPTION_DISABLED_BG)))
            .text_color(rgb(theme.shade(OPTION_DISABLED_TEXT)))
            .cursor(gpui::CursorStyle::OperationNotAllowed);
    }
    let hover_bg = theme.shade(OPTION_HOVER_BG);
    element
        .text_color(rgb(theme.shade(OPTION_TEXT)))
        // the keyboard's row reads like a hovered one, so a walk and a
        // pointer never disagree about where the reader is
        .when(highlighted && !chosen, |el| el.bg(rgb(hover_bg)))
        .when(chosen, |el| el.bg(rgb(theme.shade(OPTION_SELECTED_BG))))
        .hover(move |style| style.bg(rgb(hover_bg)))
}

/// A header stands in a slot of its own, taller than a row: the hairline that
/// opens it, then the web's air either side of the label.
fn group_header(group: SharedString, theme: &Theme) -> Div {
    div()
        .flex()
        .flex_none()
        .w_full()
        .items_center()
        // the slot is the whole of it: adding the web's margins on top of the
        // height would push the rows past what `menu_height` reserved and
        // start the menu scrolling a header too early
        .h(px(GROUP_HEIGHT))
        .pt(px(GROUP_MARGIN_Y))
        .px(px(OPTION_PADDING.1))
        .border_t_1()
        .border_color(rgb(theme.shade(GROUP_BORDER)))
        .line_height(px(OPTION_LINE_HEIGHT))
        .text_color(rgb(theme.shade(GROUP_TEXT)))
        .font_weight(FontWeight(f32::from(GROUP_WEIGHT.value())))
        .child(group)
}

fn empty_row(message: SharedString, theme: &Theme) -> Div {
    div()
        .flex()
        .flex_none()
        .w_full()
        .items_center()
        .h(px(OPTION_HEIGHT))
        .px(px(OPTION_PADDING.1))
        .line_height(px(OPTION_LINE_HEIGHT))
        .text_color(rgb(theme.shade(EMPTY_TEXT)))
        .child(message)
}