yororen_ui 0.2.0

Reusable UI components and widgets built on top of gpui.
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
use std::sync::Arc;

use gpui::{
    Animation, AnimationExt, ClickEvent, Div, ElementId, Hsla, InteractiveElement, IntoElement,
    ParentElement, Pixels, Bounds, RenderOnce, SharedString, StatefulInteractiveElement, Styled, div,
    prelude::FluentBuilder, px,
};

use crate::{
    animation::constants::duration,
    component::{ArrowDirection, BoundsTrackerElement, IconName, compute_input_style, icon, text_input},
    i18n::{I18n, I18nContext, TextDirection, defaults::DefaultPlaceholders},
    theme::ActiveTheme,
};

use crate::rtl;

use crate::animation::ease_out_quint_clamped;

#[derive(Clone, Debug)]
pub struct ComboBoxOption {
    pub value: String,
    pub label: SharedString,
    pub disabled: bool,
}

impl ComboBoxOption {
    pub fn new(value: impl Into<String>, label: impl Into<SharedString>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            disabled: false,
        }
    }

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

/// Creates a new combo box element.
/// Requires an id to be set via `.id()` for internal state management.
///
/// # Accessibility
///
/// This component provides accessibility support through the following attributes:
/// - The input element is keyboard accessible (Tab to focus)
/// - Arrow keys can navigate through filtered options when the menu is open
/// - Escape closes the menu and clears the search
/// - The search input is properly associated with the dropdown list
///
/// For full accessibility support:
/// - The component tracks `aria-expanded` state internally (true when menu is open)
/// - The menu container has a unique ID for `aria-controls` association
/// - The search input uses `aria-autocomplete="list"` to indicate autocomplete behavior
/// - Selected options are visually indicated with a checkmark
/// - Disabled options are properly marked
pub fn combo_box(id: impl Into<ElementId>) -> ComboBox {
    ComboBox::new().id(id)
}

fn desired_menu_left(
    trigger_bounds: Bounds<Pixels>,
    menu_width: Pixels,
    direction: TextDirection,
    window: &gpui::Window,
) -> Pixels {
    let desired_left = if direction.is_rtl() {
        trigger_bounds.right() - menu_width
    } else {
        trigger_bounds.left()
    };

    let window_bounds = window.bounds();
    let min_left = window_bounds.left();
    let max_left = (window_bounds.right() - menu_width).max(min_left);
    desired_left.clamp(min_left, max_left)
}

fn menu_width_px(menu_width: Option<Pixels>, default: Pixels) -> Pixels {
    menu_width.unwrap_or(default)
}

type ChangeFn = Arc<dyn Fn(String, &ClickEvent, &mut gpui::Window, &mut gpui::App)>;
type SimpleChangeFn = Arc<dyn Fn(String)>;

#[derive(IntoElement)]
pub struct ComboBox {
    element_id: ElementId,
    base: Div,
    options: Vec<ComboBoxOption>,

    value: Option<String>,
    placeholder: SharedString,
    search_placeholder: SharedString,
    /// Whether to use localized placeholders from i18n
    localized: bool,
    disabled: bool,

    bg: Option<Hsla>,
    border: Option<Hsla>,
    focus_border: Option<Hsla>,
    text_color: Option<Hsla>,
    height: Option<gpui::AbsoluteLength>,

    menu_width: Option<gpui::Pixels>,
    max_results: usize,
    on_change: Option<ChangeFn>,
    on_change_simple: Option<SimpleChangeFn>,
}

impl Default for ComboBox {
    fn default() -> Self {
        Self::new()
    }
}

impl ComboBox {
    pub fn new() -> Self {
        Self {
            element_id: "ui:combo-box".into(),
            base: div(),
            options: Vec::new(),
            value: None,
            placeholder: "Select…".into(),
            search_placeholder: "Search…".into(),
            localized: false,
            disabled: false,
            bg: None,
            border: None,
            focus_border: None,
            text_color: None,
            height: None,
            menu_width: None,
            max_results: 12,
            on_change: None,
            on_change_simple: None,
        }
    }

    /// Use localized placeholders from i18n.
    /// The placeholder text will be determined by the current locale.
    pub fn localized(mut self) -> Self {
        self.localized = true;
        self
    }

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

    /// Alias for `id(...)`. Use `key(...)` when you want to emphasize state identity.
    pub fn key(self, key: impl Into<ElementId>) -> Self {
        self.id(key)
    }

    pub fn option(mut self, option: ComboBoxOption) -> Self {
        self.options.push(option);
        self
    }

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

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

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

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

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

    pub fn max_results(mut self, max_results: usize) -> Self {
        self.max_results = max_results.max(1);
        self
    }

    pub fn on_change<F>(mut self, handler: F) -> Self
    where
        F: 'static + Fn(String, &ClickEvent, &mut gpui::Window, &mut gpui::App),
    {
        self.on_change = Some(Arc::new(handler));
        self
    }

    /// Set a simplified change handler that only receives the selected value.
    /// Use this when you don't need access to event, window or app context.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// combo_box("my-combo")
    ///     .on_change_simple(|value| {
    ///         println!("Selected: {}", value);
    ///     })
    /// ```
    pub fn on_change_simple<F>(mut self, handler: F) -> Self
    where
        F: 'static + Fn(String),
    {
        self.on_change_simple = Some(Arc::new(handler));
        self
    }

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

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

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

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

    pub fn height(mut self, height: gpui::AbsoluteLength) -> Self {
        self.height = Some(height);
        self
    }

    pub fn menu_width(mut self, width: gpui::Pixels) -> Self {
        self.menu_width = Some(width);
        self
    }

    pub fn min_menu_width(mut self, width: gpui::Pixels) -> Self {
        self.menu_width = Some(width);
        self
    }
}

impl ParentElement for ComboBox {
    fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) {
        self.base.extend(elements);
    }
}

impl Styled for ComboBox {
    fn style(&mut self) -> &mut gpui::StyleRefinement {
        self.base.style()
    }
}

impl InteractiveElement for ComboBox {
    fn interactivity(&mut self) -> &mut gpui::Interactivity {
        self.base.interactivity()
    }
}

impl StatefulInteractiveElement for ComboBox {}

/// Helper function to call on_change handlers with the correct priority.
#[allow(clippy::too_many_arguments)]
fn call_on_change(
    option_value: String,
    on_change: Option<&ChangeFn>,
    on_change_simple: Option<&SimpleChangeFn>,
    ev: &ClickEvent,
    window: &mut gpui::Window,
    cx: &mut gpui::App,
) {
    if let Some(handler) = on_change {
        handler(option_value.clone(), ev, window, cx);
    } else if let Some(handler) = on_change_simple {
        handler(option_value);
    }
}

impl RenderOnce for ComboBox {
    fn render(self, window: &mut gpui::Window, cx: &mut gpui::App) -> impl IntoElement {
        let disabled = self.disabled;
        let height = self.height.unwrap_or_else(|| px(36.).into());
        let menu_width = self.menu_width;
        let options = self.options;
        let localized = self.localized;
        let placeholder = if localized {
            DefaultPlaceholders::select_placeholder(cx.i18n().locale()).into()
        } else {
            self.placeholder
        };
        let search_placeholder = if localized {
            DefaultPlaceholders::combobox_search_placeholder(cx.i18n().locale()).into()
        } else {
            self.search_placeholder
        };
        let on_change = self.on_change;
        let on_change_simple = self.on_change_simple;
        let max_results = self.max_results;

        // ComboBox requires an element ID for keyed state management.
        // Use `.id()` to provide a stable ID, or a unique ID will be generated automatically.
        let id = self.element_id;

        let trigger_bounds_state = window.use_keyed_state(
            (id.clone(), "ui:combo-box:trigger-bounds"),
            cx,
            |_, _| Bounds::default(),
        );

        let menu_open =
            window.use_keyed_state((id.clone(), format!("{}:open", id)), cx, |_, _| false);
        let is_open = *menu_open.read(cx);

        // Track if we should set content on the text input
        // Only set content when menu just opened, not on every render
        let needs_content_init = window.use_keyed_state(
            (id.clone(), format!("{}:needs-content-init", id)),
            cx,
            |_, _| true,
        );

        // Store search text for filtering (synced on menu open, not on every keystroke)
        let search_text =
            window.use_keyed_state((id.clone(), format!("{}:search-text", id)), cx, |_, _| {
                SharedString::new_static("")
            });

        let use_internal_value =
            on_change.is_none() && on_change_simple.is_none() && self.value.is_none();
        let internal_value = use_internal_value.then(|| {
            window.use_keyed_state((id.clone(), format!("{}:value", id)), cx, |_, _| {
                options
                    .first()
                    .map(|opt| opt.value.clone())
                    .unwrap_or_default()
            })
        });

        let value = if use_internal_value {
            internal_value
                .as_ref()
                .expect("internal value should exist")
                .read(cx)
                .clone()
        } else {
            self.value
                .clone()
                .or_else(|| options.first().map(|opt| opt.value.clone()))
                .unwrap_or_default()
        };

        let selected_label = options
            .iter()
            .find(|opt| opt.value == value)
            .map(|opt| opt.label.clone());

        let theme = cx.theme().clone();
        let hint = theme.content.tertiary;

        let input_style = compute_input_style(
            &theme,
            disabled,
            self.bg,
            self.border,
            self.focus_border,
            self.text_color,
        );

        let menu_open_for_button = menu_open.clone();
        let menu_open_for_outside = menu_open.clone();
        let menu_open_for_select = menu_open.clone();

        let internal_value_for_select = internal_value.clone();
        let on_change_for_select = on_change.clone();
        let on_change_simple_for_select = on_change_simple.clone();

        let trigger = self
            .base
            .id(id.clone())
            .relative()
            .flex()
            .items_center()
            .justify_between()
            .gap_2()
            .h(height)
            .px_3()
            .rounded_md()
            .bg(input_style.bg)
            .border_1()
            .border_color(input_style.border)
            .text_color(input_style.text_color)
            .focusable()
            .focus_visible(|style| style.border_2().border_color(input_style.focus_border))
            .when(disabled, |this| this.opacity(0.6).cursor_not_allowed())
            .when(!disabled, |this| this.cursor_pointer())
            .when(is_open, |this| this.bg(theme.surface.hover))
            .on_click(move |_ev, _window, cx| {
                if disabled {
                    return;
                }
                menu_open_for_button.update(cx, |open, _| *open = !*open);
            })
            .child(
                div()
                    .flex_1()
                    .min_w(px(0.))
                    .truncate()
                    .text_color(
                        selected_label
                            .as_ref()
                            .map(|_| input_style.text_color)
                            .unwrap_or(hint),
                    )
                    .child(selected_label.unwrap_or(placeholder)),
            )
            .child(
                icon(IconName::Arrow(ArrowDirection::Down))
                    .size(px(14.))
                    .color(hint),
            );

        let trigger_bounds_state_for_menu = trigger_bounds_state.clone();
        let trigger = trigger.when(is_open, move |this| {
                let text_color = input_style.text_color;
                let value = value.clone();
                let options = options.clone();
                let on_change = on_change_for_select.clone();
                let on_change_simple = on_change_simple_for_select.clone();
                let internal_value = internal_value_for_select.clone();
                let search_text = search_text.clone();
                let needs_content_init = needs_content_init.clone();
                let max_results = max_results;

                let direction = cx
                    .try_global::<I18n>()
                    .map(|i18n| i18n.text_direction())
                    .unwrap_or(TextDirection::Ltr);

                let trigger_bounds = *trigger_bounds_state_for_menu.read(cx);
                let menu_width_px = menu_width_px(menu_width, px(420.));
                let menu_left = desired_menu_left(trigger_bounds, menu_width_px, direction, window);
                let relative_left = menu_left - trigger_bounds.left();

                // Check if we need to initialize content
                let should_init_content = *needs_content_init.read(cx);
                if should_init_content {
                    needs_content_init.update(cx, |v, _| *v = false);
                }

                // Read search text for filtering
                let query = search_text.read(cx).clone();
                let query_lower = query.to_lowercase();

                let filtered = options
                    .into_iter()
                    .filter(move |opt| {
                        if query_lower.is_empty() {
                            return true;
                        }
                        opt.label.to_string().to_lowercase().contains(&query_lower)
                            || opt.value.to_lowercase().contains(&query_lower)
                    })
                    .take(max_results)
                    .collect::<Vec<_>>();

                let menu = div()
                    .id(format!("{}:menu", id))
                    .absolute()
                    .top_full()
                    .left_0()
                    // Horizontal overflow protection: shift within window bounds.
                    .when(relative_left != Pixels::ZERO, |this| this.left(relative_left))
                    .mt(px(10.))
                    .rounded_md()
                    .border_1()
                    .border_color(theme.border.default)
                    .bg(theme.surface.raised)
                    .shadow_md()
                    .py_1()
                    .w(menu_width_px)
                    .occlude()
                    .text_align(rtl::text_align_start(direction))
                    .on_mouse_down_out({
                        let needs_content_init = needs_content_init.clone();
                        move |_ev, _window, cx| {
                            menu_open_for_outside.update(cx, |open, _cx| *open = false);
                            needs_content_init.update(cx, |v, _| *v = true);
                        }
                    })
                    .child(
                        div().px_2().pb_2().child(
                            text_input(format!("{}:query", id))
                                .placeholder(search_placeholder)
                                .bg(theme.surface.base)
                                .border(theme.border.default)
                                .focus_border(theme.border.focus)
                                .text_color(theme.content.primary)
                                .when(should_init_content, |this| this.content(query.clone()))
                                .on_change({
                                    let search_text = search_text.clone();
                                    move |value, _window, cx| {
                                        search_text.update(cx, |text, _| {
                                            *text = value;
                                        });
                                    }
                                }),
                        ),
                    )
                    .children(filtered.into_iter().map(move |opt| {
                        let is_selected = opt.value == value;
                        let is_disabled = disabled || opt.disabled;
                        let option_value = opt.value.clone();
                        let menu_open_for_select = menu_open_for_select.clone();
                        let on_change = on_change.clone();
                        let on_change_simple = on_change_simple.clone();
                        let internal_value = internal_value.clone();

                        let row_fg = if is_disabled {
                            theme.content.disabled
                        } else {
                            text_color
                        };

                        div()
                            .id((ElementId::from("ui:combo-box:option"), option_value.clone()))
                            .px_3()
                            .py_2()
                            .flex()
                            .items_center()
                            .justify_between()
                            .gap_2()
                            .text_color(row_fg)
                            .when(!is_disabled, |this| {
                                this.cursor_pointer()
                                    .hover(|this| this.bg(theme.surface.hover))
                            })
                            .when(is_disabled, |this| this.cursor_not_allowed().opacity(0.6))
                            .child(opt.label)
                            .when(is_selected, |this| {
                                this.child(
                                    icon(IconName::Check)
                                        .size(px(12.))
                                        .color(theme.action.primary.bg),
                                )
                            })
                            .on_click(move |ev, window, cx| {
                                if is_disabled {
                                    return;
                                }

                                if let Some(internal_value) = &internal_value {
                                    internal_value.update(cx, |state, _| {
                                        *state = option_value.clone();
                                    });
                                }

                                call_on_change(
                                    option_value.clone(),
                                    on_change.as_ref(),
                                    on_change_simple.as_ref(),
                                    ev,
                                    window,
                                    cx,
                                );

                                menu_open_for_select.update(cx, |open, _| *open = false);
                            })
                    }));

                let animated_menu = menu.with_animation(
                    format!("combo-box-menu-{}", is_open),
                    Animation::new(duration::MENU_OPEN).with_easing(ease_out_quint_clamped),
                    |this, value| this.opacity(value).mt(px(10.0 - 6.0 * value)),
                );

                this.child(gpui::deferred(animated_menu).with_priority(100))
            });

        BoundsTrackerElement {
            bounds_state: trigger_bounds_state,
            inner: trigger.into_any_element(),
        }
    }
}