gpui-box-kit 0.1.1

GPUI Box Kit design-system components and interaction primitives
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
//! A control for choosing one of a known set of options.
//!
//! The open menu is transient view state, so `Select` is a view rather than a
//! builder. The chosen value is not: the select reports what was picked and
//! renders whatever the owner decides is current, so a host that rejects a
//! choice keeps showing the one that still holds.

use std::cell::Cell;
use std::rc::Rc;

use gpui::{
    AnyElement, App, Bounds, Context, EventEmitter, FocusHandle, Focusable, InteractiveElement,
    IntoElement, KeyDownEvent, MouseButton, ParentElement, Pixels, Render, ScrollHandle,
    SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
};
use gpui_kit_assets::{Icon, icon};
use gpui_kit_semantics::{NodeSpec, Role, Semantic};
use gpui_kit_theme::{ActiveTheme, ControlSize, Radius, Space, TypeScale};

use crate::foundation::{
    Disableable, Ident, Pressable, Sizable, StyledExt, text as foundation_text,
};
use crate::layout::measure;
use crate::motion;
use crate::overlay::Placement;
use crate::overlay::popover::{self, MenuKey};
use crate::strings::{ActiveStrings, StringKey};

const MENU_MIN_WIDTH: f32 = 180.0;
const MENU_MAX_HEIGHT: f32 = 320.0;

/// One choice, identified by business identity rather than by position.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelectOption {
    pub id: SharedString,
    pub label: SharedString,
    pub description: Option<SharedString>,
    pub disabled: bool,
}

impl SelectOption {
    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            description: None,
            disabled: false,
        }
    }

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

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

/// What a [`Select`] reports. The owner decides what any of it means.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SelectEvent {
    /// The typist picked this option. The owner decides whether it holds.
    Selected(SharedString),
    Opened,
    Closed,
}

impl EventEmitter<SelectEvent> for Select {}

/// A closed list of options with one answer.
///
/// The select owns only whether its menu is open. It reports the option that
/// was picked and draws whatever the caller says is current, so a refused
/// choice is visible as the checkmark not moving.
pub struct Select {
    ident: Ident,
    focus_handle: FocusHandle,
    options: Vec<SelectOption>,
    selected: Option<SharedString>,
    name: SharedString,
    placeholder: Option<SharedString>,
    size: ControlSize,
    disabled: bool,
    invalid: bool,
    open: bool,
    /// Which row the keyboard is on, which is not a choice until it is taken.
    active: Option<usize>,
    scroll: ScrollHandle,
    trigger_bounds: Rc<Cell<Bounds<Pixels>>>,
    reveal_active: bool,
    menu_geometry: Option<popover::MenuGeometry>,
}

impl std::fmt::Debug for Select {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Select")
            .field("ident", &self.ident)
            .field("options", &self.options.len())
            .field("selected", &self.selected)
            .field("open", &self.open)
            .field("disabled", &self.disabled)
            .finish()
    }
}

impl Select {
    pub fn new(ident: impl Into<Ident>, _window: &mut Window, cx: &mut Context<Self>) -> Self {
        Self {
            ident: ident.into(),
            focus_handle: cx.focus_handle(),
            options: Vec::new(),
            selected: None,
            name: SharedString::default(),
            placeholder: None,
            size: ControlSize::Md,
            disabled: false,
            invalid: false,
            open: false,
            active: None,
            scroll: ScrollHandle::new(),
            trigger_bounds: Rc::default(),
            reveal_active: false,
            menu_geometry: None,
        }
    }

    pub fn options(mut self, options: impl IntoIterator<Item = SelectOption>) -> Self {
        self.options = options.into_iter().collect();
        self
    }

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

    /// Names the control independently of its current answer or placeholder.
    pub fn name(mut self, name: impl Into<SharedString>) -> Self {
        self.name = name.into();
        self
    }

    pub fn set_name(&mut self, name: impl Into<SharedString>, cx: &mut Context<Self>) {
        self.name = name.into();
        cx.notify();
    }

    /// The placeholder the host gave, or the built-in default.
    fn resolved_placeholder(&self, cx: &App) -> SharedString {
        self.placeholder
            .clone()
            .unwrap_or_else(|| cx.strings().text(StringKey::SelectPlaceholder))
    }

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

    pub fn invalid(mut self, invalid: bool) -> Self {
        self.invalid = invalid;
        self
    }

    /// Replaces the options from the host side, keeping a selection that is
    /// still offered and dropping one that is not.
    pub fn set_options(&mut self, options: Vec<SelectOption>, cx: &mut Context<Self>) {
        let still_offered = self
            .selected
            .as_ref()
            .is_some_and(|id| options.iter().any(|option| &option.id == id));
        if !still_offered {
            self.selected = None;
        }
        self.options = options;
        self.active = None;
        self.reveal_active = true;
        cx.notify();
    }

    pub fn set_selected(&mut self, id: Option<SharedString>, cx: &mut Context<Self>) {
        self.selected = id;
        if self.open {
            self.active = self
                .selected
                .as_ref()
                .and_then(|id| self.options.iter().position(|option| &option.id == id))
                .filter(|index| !self.options[*index].disabled)
                .or_else(|| self.first_selectable(0, 1));
        }
        self.reveal_active = true;
        cx.notify();
    }

    pub fn selected_id(&self) -> Option<&SharedString> {
        self.selected.as_ref()
    }

    pub fn selected_option(&self) -> Option<&SelectOption> {
        let id = self.selected.as_ref()?;
        self.options.iter().find(|option| &option.id == id)
    }

    pub fn is_open(&self) -> bool {
        self.open
    }

    pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
        self.disabled = disabled;
        if disabled {
            self.open = false;
        }
        cx.notify();
    }

    fn open_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if self.disabled || self.open {
            return;
        }
        self.open = true;
        // The keyboard starts on what is already chosen, so the first arrow
        // key moves from the current answer rather than from the top.
        self.active = self
            .selected
            .as_ref()
            .and_then(|id| self.options.iter().position(|option| &option.id == id))
            .filter(|index| !self.options[*index].disabled)
            .or_else(|| self.first_selectable(0, 1));
        self.reveal_active = true;
        window.focus(&self.focus_handle, cx);
        cx.emit(SelectEvent::Opened);
        cx.notify();
    }

    fn close_menu(&mut self, cx: &mut Context<Self>) {
        if !self.open {
            return;
        }
        self.open = false;
        self.active = None;
        cx.emit(SelectEvent::Closed);
        cx.notify();
    }

    fn toggle(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if self.open {
            self.close_menu(cx);
        } else {
            self.open_menu(window, cx);
        }
    }

    /// The next option that can actually be chosen, skipping refusals.
    fn first_selectable(&self, from: usize, delta: isize) -> Option<usize> {
        let count = self.options.len();
        if count == 0 {
            return None;
        }
        let mut index = from.min(count - 1);
        for _ in 0..count {
            if !self.options[index].disabled {
                return Some(index);
            }
            index = ((index as isize + delta).rem_euclid(count as isize)) as usize;
        }
        None
    }

    fn step(&mut self, delta: isize, cx: &mut Context<Self>) {
        let Some(next) = popover::step(self.active, self.options.len(), delta) else {
            return;
        };
        self.active = self.first_selectable(next, delta.signum());
        self.reveal_active = true;
        cx.notify();
    }

    fn edge(&mut self, from_end: bool, cx: &mut Context<Self>) {
        let next = if from_end {
            self.options
                .len()
                .checked_sub(1)
                .and_then(|index| self.first_selectable(index, -1))
        } else {
            self.first_selectable(0, 1)
        };
        if next == self.active {
            return;
        }
        self.active = next;
        self.reveal_active = true;
        cx.notify();
    }

    fn choose(&mut self, index: usize, cx: &mut Context<Self>) {
        let Some(option) = self.options.get(index) else {
            return;
        };
        if option.disabled {
            return;
        }
        let id = option.id.clone();
        self.open = false;
        self.active = None;
        cx.emit(SelectEvent::Selected(id));
        cx.emit(SelectEvent::Closed);
        cx.notify();
    }

    fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
        if self.disabled {
            return;
        }
        let raw = event.keystroke.key.as_str();
        let key = popover::classify_key(
            raw,
            event.keystroke.modifiers.platform,
            event.keystroke.modifiers.control,
        );
        match (self.open, key) {
            (false, MenuKey::Down | MenuKey::Up | MenuKey::Enter) => {
                self.open_menu(window, cx);
                cx.stop_propagation();
            }
            (true, MenuKey::Down) => {
                self.step(1, cx);
                cx.stop_propagation();
            }
            (true, MenuKey::Up) => {
                self.step(-1, cx);
                cx.stop_propagation();
            }
            (true, _) if raw == "home" => {
                self.edge(false, cx);
                cx.stop_propagation();
            }
            (true, _) if raw == "end" => {
                self.edge(true, cx);
                cx.stop_propagation();
            }
            (true, MenuKey::Enter) => {
                if let Some(active) = self.active {
                    self.choose(active, cx);
                }
                cx.stop_propagation();
            }
            (true, MenuKey::Escape) => {
                self.close_menu(cx);
                cx.stop_propagation();
            }
            _ => {}
        }
    }

    fn menu(&mut self, geometry: popover::MenuGeometry, cx: &mut Context<Self>) -> AnyElement {
        let theme = cx.theme().clone();
        if self.menu_geometry != Some(geometry) {
            self.menu_geometry = Some(geometry);
            self.reveal_active = true;
        }
        if self.reveal_active {
            if let Some(active) = self.active {
                self.scroll.scroll_to_item(active);
            }
            self.reveal_active = false;
        }
        let rows = self
            .options
            .iter()
            .enumerate()
            .map(|(index, option)| self.row(index, option, self.options.len(), cx))
            .collect::<Vec<_>>();

        let viewport = div()
            .p(px(theme.space(Space::Xs)))
            .flex()
            .flex_col()
            .max_h(px(geometry.max_height))
            .id(self.ident.child("menu.scroll").element_id())
            .overflow_y_scroll()
            .track_scroll(&self.scroll)
            .children(rows);
        let list = popover::card_flush(&theme)
            .w(px(geometry.width))
            .max_h(px(geometry.max_height))
            .id(self.ident.child("menu").element_id())
            .child(viewport)
            .semantic_in(
                cx,
                NodeSpec::new(self.ident.child("menu").semantic_id(), Role::Menu),
            )
            .into_any_element();

        popover::menu_overlay(
            &self.ident.child("menu.anchor"),
            &theme,
            geometry.placement,
            list,
        )
    }

    fn row(
        &self,
        index: usize,
        option: &SelectOption,
        count: usize,
        cx: &mut Context<Self>,
    ) -> AnyElement {
        let theme = cx.theme().clone();
        let selected = self.selected.as_ref() == Some(&option.id);
        let active = self.active == Some(index);
        let ident = self.ident.child(option.id.as_ref());
        let hover_group = ident.child("hover").semantic_id();

        let mut spec = NodeSpec::new(ident.semantic_id(), Role::Option)
            .parent(self.ident.child("menu").semantic_id())
            .checked(selected)
            .disabled(option.disabled)
            .text(option.label.clone());
        if active {
            spec = spec.hovered(true);
        }

        let row = popover::menu_row(&theme, selected, active)
            .id(ident.element_id())
            .group(hover_group.clone())
            .when(!option.disabled, |element| {
                element.cursor_pointer().pressable(cx)
            })
            .when(option.disabled, |element| {
                element.opacity(theme.opacity.disabled)
            })
            .child(
                div()
                    .flex()
                    .flex_col()
                    .flex_1()
                    .min_w_0()
                    .gap(px(2.0))
                    .child(popover::menu_label(
                        &theme,
                        option.label.clone(),
                        selected,
                        active,
                        hover_group,
                    ))
                    .when_some(option.description.clone(), |element, description| {
                        element.child(
                            foundation_text(&theme, TypeScale::Caption, description)
                                .text_tone(&theme, gpui_kit_theme::TextTone::Muted),
                        )
                    }),
            )
            .when(selected, |element| {
                element.child(
                    div().ml_auto().child(
                        icon(Icon::Check)
                            .size(px(14.0))
                            .text_color(theme.colors.text),
                    ),
                )
            })
            .when(!option.disabled, |element| {
                element.on_mouse_down(
                    MouseButton::Left,
                    cx.listener(move |select, _, _, cx| {
                        select.choose(index, cx);
                    }),
                )
            })
            .semantic_in(cx, spec);

        motion::row_in(ident.child("in").element_id(), &theme, index, count, row).into_any_element()
    }
}

impl Disableable for Select {
    fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

impl Sizable for Select {
    fn control_size(mut self, size: ControlSize) -> Self {
        self.size = size;
        self
    }
}

impl Focusable for Select {
    fn focus_handle(&self, _cx: &App) -> FocusHandle {
        self.focus_handle.clone()
    }
}

impl Render for Select {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = cx.theme().clone();
        let metrics = theme.control.get(self.size);
        let focused = self.focus_handle.is_focused(window);
        let label = self
            .selected_option()
            .map(|option| option.label.clone())
            .unwrap_or_else(|| self.resolved_placeholder(cx));
        let has_choice = self.selected_option().is_some();

        let mut spec = NodeSpec::new(self.ident.semantic_id(), Role::Combobox)
            .disabled(self.disabled)
            .invalid(self.invalid)
            .expanded(self.open)
            .text(self.name.clone())
            .placeholder(self.resolved_placeholder(cx));
        if !self.disabled {
            spec = spec.focus(&self.focus_handle);
        }
        if let Some(option) = self.selected_option() {
            spec = spec.value(option.label.clone());
        }

        let geometry = self.open.then(|| {
            popover::menu_geometry(
                window,
                self.trigger_bounds.get(),
                &theme,
                MENU_MAX_HEIGHT,
                MENU_MIN_WIDTH,
            )
        });
        let placement = geometry.map_or(Placement::Below, |geometry| geometry.placement);
        let menu = geometry.map(|geometry| self.menu(geometry, cx));

        let trigger = div()
            .id(self.ident.element_id())
            .when(!self.disabled, |element| {
                element
                    .track_focus(&self.focus_handle)
                    .on_key_down(cx.listener(Self::on_key_down))
            })
            .w_full()
            .flex()
            .flex_row()
            .items_center()
            .justify_between()
            .gap(px(theme.space(Space::Sm)))
            .h(px(metrics.height))
            .px(px(metrics.padding_x))
            .radius(&theme, Radius::Control)
            .well(&theme)
            .when(self.invalid, |element| {
                element.border_color(theme.colors.danger)
            })
            .when(focused, |element| element.shadow(theme.focus_ring()))
            .when(self.disabled, |element| {
                element.opacity(theme.opacity.disabled)
            })
            .when(!self.disabled, |element| {
                element.cursor_pointer().on_mouse_down(
                    MouseButton::Left,
                    cx.listener(|select, _, window, cx| select.toggle(window, cx)),
                )
            })
            .child(
                foundation_text(&theme, TypeScale::Label, label)
                    .text_size(px(metrics.font_size))
                    .text_color(if self.disabled || !has_choice {
                        theme.colors.text_faint
                    } else {
                        theme.colors.text
                    }),
            )
            .child(
                // One glyph in both states: the menu itself shows whether the
                // control is open, and a flipped arrow would say it twice.
                icon(Icon::AltArrowDown)
                    .size(px(metrics.icon_size * 0.9))
                    .text_color(theme.colors.text_muted),
            )
            .semantic_in(cx, spec);
        let measured = Rc::clone(&self.trigger_bounds);
        let trigger = div()
            .w_full()
            .on_children_prepainted(move |bounds, window, _| {
                if let Some(trigger) = bounds.first() {
                    measure::record(&measured, *trigger, window);
                }
            })
            .child(trigger)
            .into_any_element();

        popover::anchored_slot(placement, trigger, menu)
    }
}