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
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, ChangeCallback, ChangeWithEventCallback, IconName,
        compute_input_style, create_internal_state, icon, use_internal_state,
    },
    i18n::{I18n, I18nContext, TextDirection, defaults::DefaultPlaceholders},
    theme::ActiveTheme,
};

use crate::rtl;

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)
}

use crate::animation::ease_out_quint_clamped;

/// Creates a new select option.
///
/// # Example
///
/// ```rust,ignore
/// select_option()
///     .value("option1")
///     .label("Option 1")
///     .disabled(true)
/// ```
pub fn select_option() -> SelectOption {
    SelectOption::new()
}

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

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

impl SelectOption {
    pub fn new() -> Self {
        Self {
            value: None,
            label: None,
            disabled: false,
        }
    }

    /// Set the option value (used as the underlying value when selected).
    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.value = Some(value.into());
        self
    }

    /// Set the option label (displayed in the UI).
    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }

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

/// Creates a new select dropdown.
/// Use `.id()` to set a stable element ID for state management.
///
/// # Accessibility
///
/// This component provides accessibility support through the following attributes:
/// - The select element is keyboard accessible (Tab to focus, Space/Enter to open)
/// - Arrow keys can navigate through options when the menu is open
/// - Escape closes the menu
/// - The menu is properly labeled for screen readers
///
/// 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
/// - Selected options are visually indicated with a checkmark
/// - Disabled options are properly marked
pub fn select(id: impl Into<ElementId>) -> Select {
    Select::new().id(id)
}

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

    value: Option<String>,
    placeholder: SharedString,
    /// Whether to use localized placeholder 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>,
    on_change: Option<ChangeCallback<String>>,
    on_change_simple: Option<Arc<dyn Fn(String)>>,
    on_change_with_event: Option<ChangeWithEventCallback<String>>,
}

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

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

    /// Use localized placeholder 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: SelectOption) -> Self {
        self.options.push(option);
        self
    }

    pub fn options(mut self, options: impl IntoIterator<Item = SelectOption>) -> 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 disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Set a change handler for the select.
    /// The handler receives the selected value without event information.
    pub fn on_change<F>(mut self, handler: F) -> Self
    where
        F: 'static + Fn(String, &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 window or app context.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// select()
    ///     .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
    }

    /// Set a change handler that receives the selected value and click event.
    /// Use this when you need access to the event information (e.g., mouse position).
    pub fn on_change_with_event<F>(mut self, handler: F) -> Self
    where
        F: 'static + Fn(String, &ClickEvent, &mut gpui::Window, &mut gpui::App),
    {
        self.on_change_with_event = 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
    }
}

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

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

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

impl StatefulInteractiveElement for Select {}

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

impl RenderOnce for Select {
    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 on_change = self.on_change;
        let on_change_simple = self.on_change_simple;
        let on_change_with_event = self.on_change_with_event;

        // Select 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:select:trigger-bounds"),
            cx,
            |_, _| Bounds::default(),
        );

        let menu_open = window.use_keyed_state((id.clone(), "ui:select:open"), cx, |_, _| false);
        let is_open = *menu_open.read(cx);

        let has_on_change =
            on_change.is_some() || on_change_simple.is_some() || on_change_with_event.is_some();
        let use_internal = use_internal_state(self.value.is_some(), has_on_change);
        let default_value = options
            .first()
            .and_then(|opt| opt.value.clone())
            .unwrap_or_default();
        let internal_value = create_internal_state(
            window,
            cx,
            &id,
            format!("{}:value", id),
            default_value,
            use_internal,
        );

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

        let selected_label = options
            .iter()
            .find(|opt| opt.value.as_ref() == Some(&value))
            .and_then(|opt| opt.label.clone());

        let theme = cx.theme().clone();

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

        let hint = theme.content.tertiary;

        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 on_change_with_event_for_select = on_change_with_event.clone();

        let trigger_bounds_state_for_menu = trigger_bounds_state.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),
            )
            .when(is_open, move |this| {
                let options = options.clone();
                let value = value.clone();
                let on_change = on_change_for_select.clone();
                let on_change_simple = on_change_simple_for_select.clone();
                let on_change_with_event = on_change_with_event_for_select.clone();
                let internal_value = internal_value_for_select.clone();
                let text_color = input_style.text_color;
                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.unwrap_or_else(|| trigger_bounds.size.width);
                let menu_left = desired_menu_left(trigger_bounds, menu_width_px, direction, window);
                let relative_left = menu_left - trigger_bounds.left();

                let menu = div()
                    .id((id.clone(), "select-menu"))
                    .absolute()
                    .top_full()
                    .left_0()
                    .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()
                    // Align menu content: start in LTR, end in RTL.
                    .text_align(rtl::text_align_start(direction))
                    .on_mouse_down_out(move |_ev, _window, cx| {
                        menu_open_for_outside.update(cx, |open, _cx| *open = false);
                    })
                    .children(options.into_iter().map(move |opt| {
                        let is_selected = opt.value.as_ref() == Some(&value);
                        let is_disabled = disabled || opt.disabled;
                        let option_value =
                            opt.value.clone().expect("SelectOption value is required");
                        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 on_change_with_event = on_change_with_event.clone();
                        let internal_value = internal_value.clone();

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

                        div()
                            .id((ElementId::from("ui:select: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.expect("SelectOption label is required"))
                            .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_with_event.as_ref(),
                                    on_change.as_ref(),
                                    on_change_simple.as_ref(),
                                    Some(ev),
                                    window,
                                    cx,
                                );

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

                let animated_menu = menu.with_animation(
                    format!("select-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))
            });

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

        trigger
    }
}