fluix 0.1.9

A comprehensive UI component library for GPUI 0.2 - Modern, performant, and type-safe
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
use gpui::prelude::FluentBuilder;
use gpui::*;
use crate::theme::*;
use crate::components::basic::icon::{Icon, IconName};

// ============================================================================
// Events
// ============================================================================

/// Events emitted by the Select component
#[derive(Clone, Debug)]
pub enum SelectEvent {
    /// Single selection changed with the selected value
    Changed(String),
    /// Multiple selection changed with all selected values
    MultiChanged(Vec<String>),
}

impl EventEmitter<SelectEvent> for Select {}

// ============================================================================
// Types
// ============================================================================

/// An option in the select dropdown
#[derive(Clone, Debug)]
pub struct SelectOption {
    pub value: String,
    pub label: String,
}

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

/// A group of options in the select dropdown
#[derive(Clone, Debug)]
pub struct SelectOptionGroup {
    pub label: String,
    pub options: Vec<SelectOption>,
}

impl SelectOptionGroup {
    pub fn new(label: impl Into<String>, options: Vec<SelectOption>) -> Self {
        Self {
            label: label.into(),
            options,
        }
    }
}

// ============================================================================
// Component
// ============================================================================

/// A select/dropdown component
///
/// # Example
///
/// ```rust,ignore
/// let select = cx.new(|cx| {
///     Select::new(cx)
///         .placeholder("Select an option...")
///         .options(vec![
///             SelectOption::new("react", "React"),
///             SelectOption::new("vue", "Vue"),
///             SelectOption::new("angular", "Angular"),
///         ])
/// });
///
/// cx.subscribe(&select, |this, select, event: &SelectEvent, cx| {
///     match event {
///         SelectEvent::Changed(value) => println!("Selected: {}", value),
///         SelectEvent::MultiChanged(values) => println!("Selected: {:?}", values),
///     }
/// });
/// ```
pub struct Select {
    /// Available options (flat list)
    options: Vec<SelectOption>,
    /// Grouped options
    option_groups: Vec<SelectOptionGroup>,
    /// Currently selected value (single select)
    selected_value: Option<String>,
    /// Currently selected values (multi select)
    selected_values: Vec<String>,
    /// Placeholder text
    placeholder: String,
    /// Whether the dropdown is open
    is_open: bool,
    /// Whether the select is disabled
    disabled: bool,
    /// Size of the select
    size: ComponentSize,
    /// Custom font size (overrides size.font_size() if set)
    custom_font_size: Option<Pixels>,
    /// Custom background color
    custom_bg_color: Option<Rgba>,
    /// Whether to allow multiple selection
    multiple: bool,
    /// Flag to prevent closing when clicking inside menu
    clicking_menu: bool,
}

impl Select {
    /// Create a new Select
    pub fn new(_cx: &mut Context<Self>) -> Self {
        Self {
            options: Vec::new(),
            option_groups: Vec::new(),
            selected_value: None,
            selected_values: Vec::new(),
            placeholder: "Select...".to_string(),
            is_open: false,
            disabled: false,
            size: ComponentSize::Medium,
            custom_font_size: None,
            custom_bg_color: None,
            multiple: false,
            clicking_menu: false,
        }
    }

    /// Set the options
    pub fn options(mut self, options: Vec<SelectOption>) -> Self {
        self.options = options;
        self
    }

    /// Set the option groups
    pub fn option_groups(mut self, groups: Vec<SelectOptionGroup>) -> Self {
        self.option_groups = groups;
        self
    }

    /// Set the placeholder text
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    /// Set the selected value (single select)
    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.selected_value = Some(value.into());
        self
    }

    /// Set the selected values (multi select)
    pub fn values(mut self, values: Vec<String>) -> Self {
        self.selected_values = values;
        self
    }

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

    /// Set the size
    pub fn size(mut self, size: ComponentSize) -> Self {
        self.size = size;
        self
    }

    /// Set custom font size (independent of component size)
    /// This allows you to change the text size without affecting the component height
    pub fn font_size(mut self, size: Pixels) -> Self {
        self.custom_font_size = Some(size);
        self
    }

    /// Set custom background color
    pub fn bg_color(mut self, color: Rgba) -> Self {
        self.custom_bg_color = Some(color);
        self
    }

    /// Enable multiple selection
    pub fn multiple(mut self, multiple: bool) -> Self {
        self.multiple = multiple;
        self
    }
    
    /// Get all options (flat list from both options and groups)
    fn all_options(&self) -> Vec<SelectOption> {
        let mut all = self.options.clone();
        for group in &self.option_groups {
            all.extend(group.options.clone());
        }
        all
    }

    /// Get the display text (selected label or placeholder)
    fn display_text(&self) -> String {
        if self.multiple {
            if self.selected_values.is_empty() {
                self.placeholder.clone()
            } else {
                format!("{} selected", self.selected_values.len())
            }
        } else if let Some(value) = &self.selected_value {
            self.all_options()
                .iter()
                .find(|opt| &opt.value == value)
                .map(|opt| opt.label.clone())
                .unwrap_or_else(|| self.placeholder.clone())
        } else {
            self.placeholder.clone()
        }
    }

    /// Toggle dropdown open/closed
    fn toggle_dropdown(&mut self) {
        if !self.disabled {
            self.is_open = !self.is_open;
        }
    }

    /// Close the dropdown
    fn close_dropdown(&mut self, cx: &mut Context<Self>) {
        // Don't close if we're clicking inside the menu in multi-select mode
        if self.clicking_menu && self.multiple {
            self.clicking_menu = false;
            return;
        }
        if self.is_open {
            self.is_open = false;
            cx.notify();
        }
    }

    /// Select an option
    fn select_option(&mut self, value: String, cx: &mut Context<Self>) {
        if self.multiple {
            // Toggle selection in multi-select mode
            if let Some(pos) = self.selected_values.iter().position(|v| v == &value) {
                self.selected_values.remove(pos);
            } else {
                self.selected_values.push(value);
            }
            cx.emit(SelectEvent::MultiChanged(self.selected_values.clone()));
        } else {
            // Single select mode
            self.selected_value = Some(value.clone());
            self.is_open = false;
            cx.emit(SelectEvent::Changed(value));
        }
        cx.notify();
    }

    /// Remove a selected value (for multi-select tags)
    fn remove_value(&mut self, value: String, cx: &mut Context<Self>) {
        if let Some(pos) = self.selected_values.iter().position(|v| v == &value) {
            self.selected_values.remove(pos);
            cx.emit(SelectEvent::MultiChanged(self.selected_values.clone()));
            cx.notify();
        }
    }
    
    /// Render the dropdown overlay (positioning layer)
    /// This layer handles the absolute positioning of the dropdown menu
    fn render_dropdown_overlay(&self, cx: &Context<Self>) -> impl IntoElement {
        let theme = Theme::default();

        div()
            .absolute()
            .top_full()
            .left_0()
            .right_0()
            .mt_1()
            .occlude()
            .on_mouse_down(MouseButton::Left, cx.listener(|this, _event: &MouseDownEvent, _window, _cx| {
                // Mark that we're clicking inside the menu
                this.clicking_menu = true;
            }))
            .child(self.render_dropdown_menu(&theme, cx))
    }
    
    /// Render the dropdown menu (content and styles layer)
    /// This layer handles the visual appearance and content of the dropdown
    fn render_dropdown_menu(&self, theme: &Theme, cx: &Context<Self>) -> impl IntoElement {
        let has_groups = !self.option_groups.is_empty();

        let mut menu = div()
            .occlude()
            .id("select-popup")
            .min_w(px(180.))
            .max_h(px(300.))
            .overflow_y_scroll()
            .rounded(px(BorderRadius::LG))
            .border_1()
            .border_color(theme.colors.border)
            .bg(theme.colors.background)
            .shadow(vec![
                BoxShadow {
                    color: rgba(0x00000010).into(),
                    offset: point(px(0.), px(4.)),
                    blur_radius: px(16.),
                    spread_radius: px(-2.),
                },
                BoxShadow {
                    color: rgba(0x00000008).into(),
                    offset: point(px(0.), px(2.)),
                    blur_radius: px(8.),
                    spread_radius: px(0.),
                },
            ])
            .p(px(6.));

        // Render grouped or flat options
        if has_groups {
            let mut item_counter: usize = 0;
            menu = menu.children(self.option_groups.iter().enumerate().map(|(_group_idx, group)| {
                div()
                    .flex()
                    .flex_col()
                    .gap_1()
                    .child(
                        // Group label
                        div()
                            .px(px(12.))
                            .py(px(6.))
                            .text_xs()
                            .font_weight(FontWeight::SEMIBOLD)
                            .text_color(theme.colors.text_secondary)
                            .child(group.label.clone())
                    )
                    .children(group.options.iter().map(|option| {
                        let id = ("select-group-item", item_counter);
                        item_counter += 1;
                        self.render_option(option, id, theme, cx)
                    }))
            }));
        } else {
            menu = menu.children(self.options.iter().enumerate().map(|(idx, option)| {
                self.render_option(option, ("select-item", idx), theme, cx)
            }));
        }

        menu
    }

    /// Render a single option item
    fn render_option(&self, option: &SelectOption, id: impl Into<ElementId>, theme: &Theme, cx: &Context<Self>) -> impl IntoElement {
        let value = option.value.clone();
        let label = option.label.clone();
        let multiple = self.multiple;
        let size = self.size;

        let is_selected = if multiple {
            self.selected_values.contains(&value)
        } else {
            self.selected_value.as_ref() == Some(&value)
        };

        div()
            .id(id)
            .relative()
            .flex()
            .items_center()
            .justify_between()
            .w_full()
            .px(px(12.))
            .py(px(8.))
            .cursor(CursorStyle::PointingHand)
            .text_size(self.custom_font_size.unwrap_or(size.font_size()))
            .rounded(px(BorderRadius::SM))
            .map(|this| {
                if is_selected && !multiple {
                    this.bg(theme.colors.primary)
                        .text_color(rgb(0xFFFFFF))
                } else {
                    this.text_color(theme.colors.text)
                        .hover(|style| style.bg(theme.colors.background_hover))
                }
            })
            .on_mouse_down(MouseButton::Left, cx.listener(move |this, _event: &MouseDownEvent, _window, cx| {
                this.select_option(value.clone(), cx);
            }))
            .child(
                div()
                    .flex()
                    .items_center()
                    .gap_2()
                    // Checkbox for multi-select
                    .when(multiple, |this| {
                        this.child(self.render_checkbox(is_selected, theme))
                    })
                    .child(label)
            )
            // Show checkmark for single select
            .when(is_selected && !multiple, |this| {
                this.child(
                    div()
                        .text_xs()
                        .child("✓")
                )
            })
    }

    /// Render a checkbox for multi-select
    fn render_checkbox(&self, checked: bool, theme: &Theme) -> impl IntoElement {
        div()
            .flex()
            .items_center()
            .justify_center()
            .w(px(16.))
            .h(px(16.))
            .rounded(px(4.))
            .border_1()
            .border_color(if checked { theme.colors.primary } else { theme.colors.border })
            .bg(if checked { theme.colors.primary } else { rgb(0xFFFFFF) })
            .when(checked, |this| {
                this.child(
                    div()
                        .text_xs()
                        .text_color(rgb(0xFFFFFF))
                        .child("✓")
                )
            })
    }

    /// Render selected tags for multi-select
    fn render_selected_tags(&self, theme: &Theme, cx: &Context<Self>) -> Vec<impl IntoElement> {
        let all_options = self.all_options();

        self.selected_values.iter().map(|value| {
            let label = all_options
                .iter()
                .find(|opt| &opt.value == value)
                .map(|opt| opt.label.clone())
                .unwrap_or_else(|| value.clone());

            let value_for_remove = value.clone();

            div()
                .flex()
                .items_center()
                .gap_1()
                .px(px(8.))
                .py(px(4.))
                .rounded(px(6.))
                .bg(theme.colors.primary)
                .text_color(rgb(0xFFFFFF))
                .text_xs()
                .child(label)
                .child(
                    // Remove button
                    div()
                        .flex()
                        .items_center()
                        .justify_center()
                        .w(px(14.))
                        .h(px(14.))
                        .rounded(px(7.))
                        .cursor(CursorStyle::PointingHand)
                        .hover(|style| style.bg(rgba(0xFFFFFF20)))
                        .on_mouse_down(MouseButton::Left, cx.listener(move |this, _event: &MouseDownEvent, _window, cx| {
                            this.remove_value(value_for_remove.clone(), cx);
                        }))
                        .child(
                            div()
                                .text_xs()
                                .child("×")
                        )
                )
        }).collect()
    }
}

// ============================================================================
// Render
// ============================================================================

impl Render for Select {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let theme = Theme::default();
        let disabled = self.disabled;
        let is_open = self.is_open;
        let multiple = self.multiple;
        let (padding_y, padding_x) = self.size.padding();

        let is_placeholder = if multiple {
            self.selected_values.is_empty()
        } else {
            self.selected_value.is_none()
        };

        div()
            .id("select-wrapper")
            .w_full()
            // Close dropdown when clicking outside (only for single select, multi-select uses backdrop)
            .when(is_open && !multiple, |this| {
                this.on_mouse_down_out(cx.listener(|this, _event: &MouseDownEvent, _window, cx| {
                    this.close_dropdown(cx);
                }))
            })
            .child(
                div()
                    .id("select-container")
                    .relative()
                    .w_full()
                    .child(
                        // Trigger button
                        div()
                            .id("select-trigger")
                            .relative()
                            .flex()
                            .w_full()
                            .items_center()
                            .justify_between()
                            .gap_2()
                            .py(padding_y)
                            .px(padding_x)
                            .rounded(px(BorderRadius::LG))
                            .border_1()
                            .border_color(theme.colors.border)
                            .bg(self.custom_bg_color.unwrap_or(theme.colors.background))
                            .text_size(self.custom_font_size.unwrap_or(self.size.font_size()))
                            .shadow(vec![BoxShadow {
                                color: rgba(0x0000000A).into(),
                                offset: point(px(0.), px(1.)),
                                blur_radius: px(2.),
                                spread_radius: px(0.),
                            }])
                            .when(!disabled, |this| {
                                this.cursor(CursorStyle::PointingHand)
                            })
                            .when(disabled, |this| {
                                this.opacity(0.64)
                            })
                            .on_mouse_down(MouseButton::Left, cx.listener(|this, _event: &MouseDownEvent, _window, cx| {
                                this.toggle_dropdown();
                                cx.notify();
                            }))
                            .child(
                                // Content area
                                div()
                                    .flex()
                                    .flex_1()
                                    .items_center()
                                    .gap_1()
                                    .overflow_hidden()
                                    .when(multiple && !self.selected_values.is_empty(), |this| {
                                        // Show tags for multi-select
                                        this.children(self.render_selected_tags(&theme, cx))
                                    })
                                    .when(!multiple || self.selected_values.is_empty(), |this| {
                                        // Show single value or placeholder
                                        this.child(
                                            div()
                                                .when(is_placeholder, |this| {
                                                    this.text_color(theme.colors.text_secondary)
                                                })
                                                .when(!is_placeholder, |this| {
                                                    this.text_color(theme.colors.text)
                                                })
                                                .child(self.display_text())
                                        )
                                    })
                            )
                            .child(
                                // Chevron up/down icon
                                Icon::new(IconName::ChevronUpDown)
                                    .small()
                                    .color(rgb(0x666666))
                            )
                    )
                    // Use deferred() to render dropdown overlay at the end, ensuring it's on top
                    .children(if is_open && !disabled {
                        Some(deferred(
                            self.render_dropdown_overlay(cx).into_any_element()
                        ))
                    } else {
                        None
                    })
            )
    }
}