fluidattacks-designs 0.11.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
//! `SearchDropdown` — the web search dropdown: a search bar that hands every
//! query to the app, over a floating list of the results the app hands back.
//!
//! [`SearchDropdownState`] holds the query, the results and whether the list
//! is open, as an entity the app owns; [`SearchDropdown`] renders it. The app
//! listens for [`SearchDropdownEvent`]:
//!
//! ```ignore
//! let inputs = cx.new(|cx| SearchDropdownState::new(|input: &Input, _| row(input), window, cx));
//! cx.subscribe(&inputs, |this, inputs, event, cx| match event {
//!     SearchDropdownEvent::Query(query) => this.ask_server(query, inputs, cx),
//!     SearchDropdownEvent::Chosen(input) => this.fill_form(input, cx),
//!     SearchDropdownEvent::Cleared => this.forget(cx),
//! });
//! SearchDropdown::new(&inputs)
//! ```
//!
//! One to one with the web, which has no keyboard walk of the results. The
//! one difference: the web keeps no copy of the query and shows only what the
//! app writes back, while here the field holds it, as every kit field does.

use std::rc::Rc;

use fluidattacks_designs_domain::icon::Style as IconStyle;
use fluidattacks_designs_domain::inputs::{LINE_HEIGHT, TEXT_SIZE};
use fluidattacks_designs_domain::search;
use fluidattacks_designs_domain::search_dropdown::{
    visible, BAR_BG, BAR_BORDER, BAR_BORDER_WIDTH, BAR_FOCUS_BORDER, BAR_FOCUS_BORDER_WIDTH,
    BAR_GAP, BAR_HEIGHT, BAR_HOVER_BORDER, BAR_PADDING, BAR_RADIUS, CLEAR_COLOR, CLEAR_ICON,
    CLEAR_PADDING, CLEAR_SIZE, EMPTY_MESSAGE, EMPTY_PADDING, EMPTY_TEXT, GLYPH_COLOR, GLYPH_SIZE,
    LIST_BG, LIST_BORDER, LIST_MAX_HEIGHT, LIST_OFFSET, LIST_PADDING_Y, LIST_RADIUS, LIST_SHADOW,
    OPEN_ON_FOCUS, ROW_HOVER_BG, ROW_PADDING,
};
use fluidattacks_designs_domain::typography::FONT_PRIMARY;
use gpui::prelude::FluentBuilder as _;
use gpui::{
    deferred, div, px, rgb, AnyElement, App, AppContext as _, Context, Div, Entity, EventEmitter,
    FocusHandle, Focusable, InteractiveElement as _, IntoElement, KeyBinding, ParentElement as _,
    RenderOnce, ScrollHandle, SharedString, StatefulInteractiveElement as _, Styled as _, Window,
};

use crate::icon::Icon;
use crate::text_input::TextInputState;
use crate::theme::{ActiveTheme as _, Theme};
use crate::widget::{elevation, ghost_icon_button, scrolling};

const CONTEXT: &str = "DesignsSearchDropdown";

// the actions! expansion derives PartialEq without Eq; not ours to fix
#[allow(clippy::derive_partial_eq_without_eq)]
mod action_defs {
    gpui::actions!(designs_search_dropdown, [Dismiss]);
}

use action_defs::Dismiss;

/// Bind Escape, which closes the list while the field has focus.
/// [`crate::Theme::init`] calls this.
pub fn bind_keys(cx: &mut App) {
    cx.bind_keys([KeyBinding::new("escape", Dismiss, Some(CONTEXT))]);
}

/// What a search dropdown tells its app — the web's `onChange`, `onSelectItem`
/// and `onClear`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SearchDropdownEvent<T> {
    /// The query changed: typed, pasted, deleted, or emptied by the clear
    /// button, which reports [`Self::Cleared`] first.
    Query(SharedString),
    /// A result was clicked; it is the value the app handed over.
    Chosen(T),
    /// The clear button was clicked.
    Cleared,
}

/// Turns a result into its row, the web's `renderItem`.
type RenderItem<T> = Rc<dyn Fn(&T, &App) -> AnyElement>;

/// What a search dropdown holds: the query field, the results the app handed
/// over, and whether the list is open.
pub struct SearchDropdownState<T> {
    field: Entity<TextInputState>,
    results: Vec<T>,
    render_item: RenderItem<T>,
    open: bool,
    open_on_focus: bool,
    empty_text: SharedString,
    /// The query last reported. The field notifies on focus and caret moves
    /// too, and only a change of text is a query.
    query: SharedString,
    /// Set while the clear button hands the focus back: in the web that focus
    /// opens the list and the same handler closes it again, and here the
    /// focus arrives after the handler has run.
    refocusing: bool,
    scroll: ScrollHandle,
}

impl<T: Clone + 'static> SearchDropdownState<T> {
    pub fn new(
        render_item: impl Fn(&T, &App) -> AnyElement + 'static,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        let field =
            cx.new(|inner| TextInputState::new(window, inner).max_length(search::MAX_LENGTH));
        cx.observe(&field, |state, _, inner| state.field_changed(inner))
            .detach();
        let focus = field.read(cx).focus_handle(cx);
        cx.on_focus(&focus, window, |state, _, inner| state.focused(inner))
            .detach();
        Self {
            field,
            results: Vec::new(),
            render_item: Rc::new(render_item),
            open: false,
            open_on_focus: OPEN_ON_FOCUS,
            empty_text: SharedString::new_static(EMPTY_MESSAGE),
            query: SharedString::default(),
            refocusing: false,
            scroll: ScrollHandle::new(),
        }
    }

    /// What the list says when the app hands it no results.
    #[must_use]
    pub fn empty_text(mut self, text: impl Into<SharedString>) -> Self {
        self.empty_text = text.into();
        self
    }

    /// Whether focusing the field opens the list (default on).
    #[must_use]
    pub const fn open_on_focus(mut self, open: bool) -> Self {
        self.open_on_focus = open;
        self
    }

    /// The prompt inside the field.
    pub fn set_placeholder(&self, placeholder: impl Into<SharedString>, cx: &mut Context<Self>) {
        self.field
            .update(cx, |field, inner| field.set_placeholder(placeholder, inner));
    }

    /// The most the field takes, in graphemes; [`search::MAX_LENGTH`] unless
    /// set. A query already longer is left as it is, as the web leaves it.
    pub fn set_max_length(&self, max_length: usize, cx: &mut Context<Self>) {
        self.field
            .update(cx, |field, _| field.set_max_length(max_length));
    }

    /// Replace the results. This is the app answering, not the reader acting:
    /// it reports nothing.
    pub fn set_results(&mut self, results: Vec<T>, cx: &mut Context<Self>) {
        self.results = results;
        cx.notify();
    }

    /// Write the query from the app's side, which reports nothing — the web
    /// owner writing `value` back.
    pub fn set_query(&mut self, query: impl Into<SharedString>, cx: &mut Context<Self>) {
        self.query = query.into();
        let shown = self.query.clone();
        self.field
            .update(cx, |field, inner| field.set_value(shown, inner));
        cx.notify();
    }

    #[must_use]
    pub fn query(&self) -> &str {
        &self.query
    }

    #[must_use]
    pub fn results(&self) -> &[T] {
        &self.results
    }

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

    fn visible(&self) -> bool {
        visible(self.open, &self.query, self.results.len())
    }

    /// Typing reports the query and opens the list. The field has already cut
    /// it to the maximum length, as the web's `maxLength` does.
    fn field_changed(&mut self, cx: &mut Context<Self>) {
        let typed = self.field.read(cx).value();
        if typed == &*self.query {
            return;
        }
        self.query = SharedString::from(typed.to_owned());
        cx.emit(SearchDropdownEvent::Query(self.query.clone()));
        self.open = true;
        cx.notify();
    }

    fn focused(&mut self, cx: &mut Context<Self>) {
        if self.refocusing {
            self.refocusing = false;
            return;
        }
        if self.open_on_focus {
            self.open = true;
            cx.notify();
        }
    }

    fn choose(&mut self, chosen: T, cx: &mut Context<Self>) {
        cx.emit(SearchDropdownEvent::Chosen(chosen));
        self.close(cx);
    }

    /// The web's order: report the clearing, report the empty query, hand the
    /// focus back to the field, close.
    fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        cx.emit(SearchDropdownEvent::Cleared);
        self.query = SharedString::default();
        cx.emit(SearchDropdownEvent::Query(self.query.clone()));
        self.field
            .update(cx, |field, inner| field.set_value("", inner));
        let focus = self.field.read(cx).focus_handle(cx);
        self.refocusing = !focus.is_focused(window);
        focus.focus(window, cx);
        self.close(cx);
    }

    fn close(&mut self, cx: &mut Context<Self>) {
        self.open = false;
        cx.notify();
    }
}

impl<T: 'static> EventEmitter<SearchDropdownEvent<T>> for SearchDropdownState<T> {}

impl<T: 'static> Focusable for SearchDropdownState<T> {
    fn focus_handle(&self, cx: &App) -> FocusHandle {
        self.field.read(cx).focus_handle(cx)
    }
}

#[derive(IntoElement)]
pub struct SearchDropdown<T: Clone + 'static> {
    state: Entity<SearchDropdownState<T>>,
}

impl<T: Clone + 'static> SearchDropdown<T> {
    #[must_use]
    pub fn new(state: &Entity<SearchDropdownState<T>>) -> Self {
        Self {
            state: state.clone(),
        }
    }
}

impl<T: Clone + 'static> RenderOnce for SearchDropdown<T> {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let state = self.state;
        let focused = state.read(cx).focus_handle(cx).is_focused(window);
        let shown = state.read(cx).visible();
        let dismissing = state.clone();
        div()
            .key_context(CONTEXT)
            .relative()
            .w_full()
            .on_action(move |_: &Dismiss, _win, app| {
                dismissing.update(app, SearchDropdownState::close);
            })
            .child(bar(&state, focused, cx))
            .when(shown, |el| el.child(deferred(list(&state, cx))))
    }
}

/// The bar: glyph, field, and the clear button while there is a query. Its
/// border thickens on focus, which the web's `:focus-within` declares after
/// `:hover`, so focus wins.
fn bar<T: Clone + 'static>(state: &Entity<SearchDropdownState<T>>, focused: bool, cx: &App) -> Div {
    let read = state.read(cx);
    let theme = cx.theme();
    let has_query = !read.field.read(cx).value().is_empty();
    let hover = theme.shade(BAR_HOVER_BORDER);
    div()
        .flex()
        .items_center()
        .w_full()
        .h(px(BAR_HEIGHT))
        .gap(px(BAR_GAP))
        .p(px(BAR_PADDING))
        .bg(rgb(theme.shade(BAR_BG)))
        .rounded(px(BAR_RADIUS))
        .map(|el| {
            if focused {
                bordered(el, BAR_FOCUS_BORDER_WIDTH)
                    .border_color(rgb(theme.shade(BAR_FOCUS_BORDER)))
            } else {
                bordered(el, BAR_BORDER_WIDTH)
                    .border_color(rgb(theme.shade(BAR_BORDER)))
                    .hover(move |style| style.border_color(rgb(hover)))
            }
        })
        .child(
            Icon::new(search::GLYPH)
                .style(IconStyle::Light)
                .size(GLYPH_SIZE)
                .color(theme.shade(GLYPH_COLOR)),
        )
        .child(
            // the bare field reads its face from the cascade; `TextInput` sets
            // it on its own wrapper, which this does not use
            div()
                .flex_1()
                .min_w_0()
                .overflow_hidden()
                .font_family(FONT_PRIMARY)
                .text_size(px(TEXT_SIZE.px()))
                .line_height(px(LINE_HEIGHT))
                .child(read.field.clone()),
        )
        .when(has_query, |el| el.child(clear_button(state, cx)))
}

/// gpui spells border widths as fixed steps only, and the token is a number.
fn bordered(mut element: Div, width: f32) -> Div {
    let edges = &mut element.style().border_widths;
    edges.top = Some(px(width).into());
    edges.right = Some(px(width).into());
    edges.bottom = Some(px(width).into());
    edges.left = Some(px(width).into());
    element
}

fn clear_button<T: Clone + 'static>(
    state: &Entity<SearchDropdownState<T>>,
    cx: &App,
) -> impl IntoElement {
    let clearing = state.clone();
    let glyph = Icon::new(CLEAR_ICON)
        .style(IconStyle::Light)
        .size(CLEAR_SIZE)
        .color(cx.theme().shade(CLEAR_COLOR));
    ghost_icon_button("designs-search-dropdown-clear", glyph, CLEAR_PADDING, cx)
        .debug_selector(|| "search-dropdown-clear".to_owned())
        .flex_none()
        .on_click(move |_, window, app| {
            clearing.update(app, |dropdown, inner| dropdown.clear(window, inner));
        })
}

/// The floating list, flush under the bar and as wide as it. `deferred` paints
/// it over what follows; `occlude` keeps the pointer from reaching through.
/// A press anywhere else closes it, as the web's `useClickOutside` on the list.
fn list<T: Clone + 'static>(state: &Entity<SearchDropdownState<T>>, cx: &App) -> Div {
    let read = state.read(cx);
    let theme = cx.theme();
    let outside = state.clone();
    div()
        .debug_selector(|| "search-dropdown-list".to_owned())
        .absolute()
        .top(px(BAR_HEIGHT + LIST_OFFSET))
        .left_0()
        .right_0()
        .bg(rgb(theme.shade(LIST_BG)))
        .border_1()
        .border_color(rgb(theme.shade(LIST_BORDER)))
        .rounded(px(LIST_RADIUS))
        .shadow(elevation(LIST_SHADOW))
        .overflow_hidden()
        .occlude()
        .on_mouse_down_out(move |_, _win, app| {
            outside.update(app, SearchDropdownState::close);
        })
        .map(|el| {
            if read.results.is_empty() {
                el.child(empty(read.empty_text.clone(), theme))
            } else {
                el.child(rows(state, cx))
            }
        })
}

fn rows<T: Clone + 'static>(state: &Entity<SearchDropdownState<T>>, cx: &App) -> AnyElement {
    let read = state.read(cx);
    let hover = cx.theme().shade(ROW_HOVER_BG);
    let children = read.results.iter().enumerate().map(|(position, result)| {
        let choosing = state.clone();
        // the result is taken now, while it is the one painted, rather than
        // looked up at click time in a list the app may have replaced
        let picked = result.clone();
        div()
            .id(("designs-search-dropdown-row", position))
            .debug_selector(|| format!("search-dropdown-row-{position}"))
            .w_full()
            .py(px(ROW_PADDING.0))
            .px(px(ROW_PADDING.1))
            .cursor_pointer()
            .hover(move |style| style.bg(rgb(hover)))
            .child((read.render_item)(result, cx))
            .on_click(move |_, _win, app| {
                choosing.update(app, |dropdown, inner| {
                    dropdown.choose(picked.clone(), inner);
                });
            })
    });
    scrolling(
        "designs-search-dropdown-scrollbar",
        div()
            .id("designs-search-dropdown-rows")
            .flex()
            .flex_col()
            .py(px(LIST_PADDING_Y))
            .max_h(px(LIST_MAX_HEIGHT))
            .overflow_y_scroll()
            .track_scroll(&read.scroll)
            .children(children)
            .into_any_element(),
        &read.scroll,
    )
}

fn empty(text: SharedString, theme: &Theme) -> Div {
    div()
        .debug_selector(|| "search-dropdown-empty".to_owned())
        .p(px(EMPTY_PADDING))
        .text_color(rgb(theme.shade(EMPTY_TEXT)))
        .child(text)
}

#[cfg(test)]
mod tests {
    use fluidattacks_designs_domain::search_dropdown::EMPTY_MESSAGE;
    use fluidattacks_designs_domain::theme::Mode;
    use gpui::{
        div, point, px, AppContext as _, ClipboardItem, Context, Entity, Focusable as _,
        IntoElement, Modifiers, ParentElement as _, Render, SharedString, Styled as _,
        TestAppContext, VisualTestContext, Window,
    };

    use super::{SearchDropdown, SearchDropdownEvent, SearchDropdownState};
    use crate::text::Text;
    use crate::theme::Theme;

    type Dropdown = Entity<SearchDropdownState<&'static str>>;
    type Heard = Entity<Vec<SearchDropdownEvent<&'static str>>>;

    /// A window holding one dropdown, 300px wide, at the top left, and what it
    /// reported.
    struct Host {
        dropdown: Dropdown,
        heard: Heard,
    }

    impl Render for Host {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().size_full().child(
                div()
                    .w(px(300.0))
                    .child(SearchDropdown::new(&self.dropdown)),
            )
        }
    }

    fn mount(
        cx: &mut TestAppContext,
        configure: fn(SearchDropdownState<&'static str>) -> SearchDropdownState<&'static str>,
    ) -> (Dropdown, Heard, &mut VisualTestContext) {
        cx.update(|app| {
            app.set_global(Theme {
                mode: Mode::Light,
                colors: Mode::Light.colors(),
            });
            crate::text_input::bind_keys(app);
            super::bind_keys(app);
        });
        let (host, cx) = cx.add_window_view(|window, inner| {
            let dropdown = inner.new(|state| {
                configure(SearchDropdownState::new(
                    |row: &&'static str, _| Text::new(*row).into_any_element(),
                    window,
                    state,
                ))
            });
            inner
                .subscribe(&dropdown, |host: &mut Host, _, event, listening| {
                    host.heard
                        .update(listening, |log, _| log.push(event.clone()));
                })
                .detach();
            Host {
                dropdown,
                heard: inner.new(|_| Vec::new()),
            }
        });
        // gpui hands focus events only to the active window
        cx.update(|window, _| window.activate_window());
        cx.run_until_parked();
        let (dropdown, heard) = cx.read(|app| {
            let host = host.read(app);
            (host.dropdown.clone(), host.heard.clone())
        });
        (dropdown, heard, cx)
    }

    fn said(heard: &Heard, cx: &VisualTestContext) -> Vec<SearchDropdownEvent<&'static str>> {
        cx.read(|app| heard.read(app).clone())
    }

    fn forget(heard: &Heard, cx: &mut VisualTestContext) {
        heard.update(cx, |log, _| log.clear());
    }

    /// A click on the field, past the glyph, the way a reader focuses it.
    fn focus(dropdown: &Dropdown, cx: &mut VisualTestContext) {
        cx.simulate_click(point(px(150.0), px(20.0)), Modifiers::none());
        cx.run_until_parked();
        let focused =
            cx.update(|window, app| dropdown.read(app).focus_handle(app).is_focused(window));
        assert!(focused, "the click did not reach the field");
    }

    fn type_in(dropdown: &Dropdown, text: &str, cx: &mut VisualTestContext) {
        focus(dropdown, cx);
        cx.simulate_input(text);
        cx.run_until_parked();
    }

    fn click(selector: &'static str, cx: &mut VisualTestContext) {
        let bounds = cx
            .debug_bounds(selector)
            .unwrap_or_else(|| unreachable_bounds(selector));
        cx.simulate_click(bounds.center(), Modifiers::none());
        cx.run_until_parked();
    }

    #[allow(
        clippy::panic,
        reason = "a test that cannot find its target has failed"
    )]
    fn unreachable_bounds(selector: &str) -> gpui::Bounds<gpui::Pixels> {
        panic!("{selector} was not drawn")
    }

    fn query(dropdown: &Dropdown, cx: &VisualTestContext) -> String {
        cx.read(|app| dropdown.read(app).query().to_owned())
    }

    fn is_open(dropdown: &Dropdown, cx: &VisualTestContext) -> bool {
        cx.read(|app| dropdown.read(app).is_open())
    }

    fn query_event(text: &str) -> SearchDropdownEvent<&'static str> {
        SearchDropdownEvent::Query(SharedString::from(text.to_owned()))
    }

    const fn same(state: SearchDropdownState<&'static str>) -> SearchDropdownState<&'static str> {
        state
    }

    /// Guards the web's "displays initial value" and "syncs value after
    /// rerender": the app's writes show, and report nothing back.
    #[gpui::test]
    fn the_field_shows_the_query_the_app_writes(cx: &mut TestAppContext) {
        let (dropdown, heard, cx) = mount(cx, same);
        dropdown.update(cx, |state, inner| state.set_query("initial", inner));
        assert_eq!(query(&dropdown, cx), "initial");
        dropdown.update(cx, |state, inner| state.set_query("second", inner));
        cx.run_until_parked();
        assert_eq!(query(&dropdown, cx), "second");
        let shown = cx.read(|app| dropdown.read(app).field.read(app).value().to_owned());
        assert_eq!(shown, "second");
        assert!(said(&heard, cx).is_empty());
    }

    #[gpui::test]
    fn the_clear_button_shows_only_while_there_is_a_query(cx: &mut TestAppContext) {
        let (dropdown, _, cx) = mount(cx, same);
        assert!(cx.debug_bounds("search-dropdown-clear").is_none());
        dropdown.update(cx, |state, inner| state.set_query("cve", inner));
        cx.run_until_parked();
        assert!(cx.debug_bounds("search-dropdown-clear").is_some());
    }

    #[gpui::test]
    fn focus_opens_the_list_by_default(cx: &mut TestAppContext) {
        let (dropdown, _, cx) = mount(cx, same);
        focus(&dropdown, cx);
        assert!(is_open(&dropdown, cx));
    }

    #[gpui::test]
    fn focus_leaves_the_list_closed_when_open_on_focus_is_off(cx: &mut TestAppContext) {
        let (dropdown, _, cx) = mount(cx, |state| state.open_on_focus(false));
        focus(&dropdown, cx);
        assert!(!is_open(&dropdown, cx));
    }

    /// Guards "opens dropdown on input change", "calls onChange" and
    /// "accumulates keystrokes": every keystroke reports the whole query.
    #[gpui::test]
    fn typing_reports_each_query_and_opens_the_list(cx: &mut TestAppContext) {
        let (dropdown, heard, cx) = mount(cx, |state| state.open_on_focus(false));
        type_in(&dropdown, "c", cx);
        cx.simulate_input("v");
        cx.simulate_input("e");
        cx.run_until_parked();
        assert!(is_open(&dropdown, cx));
        assert_eq!(query(&dropdown, cx), "cve");
        assert_eq!(
            said(&heard, cx),
            [query_event("c"), query_event("cv"), query_event("cve")]
        );
        assert!(cx.debug_bounds("search-dropdown-list").is_some());
    }

    #[gpui::test]
    fn escape_closes_the_list(cx: &mut TestAppContext) {
        let (dropdown, _, cx) = mount(cx, same);
        type_in(&dropdown, "cve", cx);
        assert!(is_open(&dropdown, cx));
        cx.simulate_keystrokes("escape");
        cx.run_until_parked();
        assert!(!is_open(&dropdown, cx));
        assert!(cx.debug_bounds("search-dropdown-list").is_none());
    }

    /// Guards the web's order: the clearing first, then the empty query, and
    /// the focus kept in a field the list no longer covers.
    #[gpui::test]
    fn clearing_reports_the_clearing_then_an_empty_query(cx: &mut TestAppContext) {
        let (dropdown, heard, cx) = mount(cx, same);
        type_in(&dropdown, "cve", cx);
        forget(&heard, cx);
        click("search-dropdown-clear", cx);
        assert_eq!(
            said(&heard, cx),
            [SearchDropdownEvent::Cleared, query_event("")]
        );
        assert_eq!(query(&dropdown, cx), "");
        assert!(!is_open(&dropdown, cx));
        let focused =
            cx.update(|window, app| dropdown.read(app).focus_handle(app).is_focused(window));
        assert!(focused);
    }

    /// Guards the web's `maxLength` plus its `slice`: a paste past the cap is
    /// cut, and the cut query is what reports.
    #[gpui::test]
    fn a_paste_past_the_cap_is_cut_and_reported_cut(cx: &mut TestAppContext) {
        let (dropdown, heard, cx) = mount(cx, same);
        dropdown.update(cx, |state, inner| state.set_max_length(5, inner));
        focus(&dropdown, cx);
        cx.write_to_clipboard(ClipboardItem::new_string("abcdefg".to_owned()));
        cx.simulate_keystrokes("cmd-v");
        cx.run_until_parked();
        assert_eq!(query(&dropdown, cx), "abcde");
        assert_eq!(said(&heard, cx), [query_event("abcde")]);
    }

    /// Guards the other half of `maxLength`: typing stops at the cap, so
    /// nothing past it is ever reported.
    #[gpui::test]
    fn typing_stops_at_the_cap(cx: &mut TestAppContext) {
        let (dropdown, heard, cx) = mount(cx, same);
        dropdown.update(cx, |state, inner| state.set_max_length(3, inner));
        type_in(&dropdown, "abcdefg", cx);
        assert_eq!(query(&dropdown, cx), "abc");
        assert_eq!(
            said(&heard, cx),
            [query_event("a"), query_event("ab"), query_event("abc")]
        );
    }

    #[gpui::test]
    fn setting_results_reports_nothing_and_fills_the_open_list(cx: &mut TestAppContext) {
        let (dropdown, heard, cx) = mount(cx, same);
        type_in(&dropdown, "a", cx);
        forget(&heard, cx);
        dropdown.update(cx, |state, inner| {
            state.set_results(vec!["alpha", "beta"], inner);
        });
        cx.run_until_parked();
        assert!(said(&heard, cx).is_empty());
        assert!(cx.debug_bounds("search-dropdown-row-0").is_some());
        assert!(cx.debug_bounds("search-dropdown-row-1").is_some());
        assert!(cx.debug_bounds("search-dropdown-empty").is_none());
    }

    #[gpui::test]
    fn clicking_a_row_reports_that_result_and_closes_the_list(cx: &mut TestAppContext) {
        let (dropdown, heard, cx) = mount(cx, same);
        type_in(&dropdown, "a", cx);
        dropdown.update(cx, |state, inner| {
            state.set_results(vec!["alpha", "beta"], inner);
        });
        cx.run_until_parked();
        forget(&heard, cx);
        click("search-dropdown-row-1", cx);
        assert_eq!(said(&heard, cx), [SearchDropdownEvent::Chosen("beta")]);
        assert!(!is_open(&dropdown, cx));
    }

    #[gpui::test]
    fn a_query_with_no_results_shows_the_default_empty_text(cx: &mut TestAppContext) {
        let (dropdown, _, cx) = mount(cx, same);
        type_in(&dropdown, "zzz", cx);
        assert!(cx.debug_bounds("search-dropdown-empty").is_some());
        let text = cx.read(|app| dropdown.read(app).empty_text.clone());
        assert_eq!(text, EMPTY_MESSAGE);
    }

    #[gpui::test]
    fn a_custom_empty_text_replaces_the_default(cx: &mut TestAppContext) {
        let (dropdown, _, cx) = mount(cx, |state| state.empty_text("Nothing found"));
        type_in(&dropdown, "zzz", cx);
        assert!(cx.debug_bounds("search-dropdown-empty").is_some());
        let text = cx.read(|app| dropdown.read(app).empty_text.clone());
        assert_eq!(text, "Nothing found");
    }

    /// Guards the web's `useClickOutside` on the list: a press anywhere else
    /// closes it.
    #[gpui::test]
    fn a_press_outside_the_list_closes_it(cx: &mut TestAppContext) {
        let (dropdown, _, cx) = mount(cx, same);
        type_in(&dropdown, "zzz", cx);
        assert!(cx.debug_bounds("search-dropdown-list").is_some());
        // well right of the 300px host and below its list
        cx.simulate_click(point(px(600.0), px(600.0)), Modifiers::none());
        cx.run_until_parked();
        assert!(!is_open(&dropdown, cx));
    }

    /// Guards the edge the web settles with `trim`: blanks alone are no query,
    /// so the list stays hidden although it is open.
    #[gpui::test]
    fn an_open_list_with_only_blanks_and_no_results_stays_hidden(cx: &mut TestAppContext) {
        let (dropdown, _, cx) = mount(cx, same);
        type_in(&dropdown, "   ", cx);
        assert!(is_open(&dropdown, cx));
        assert!(cx.debug_bounds("search-dropdown-list").is_none());
    }
}