gpui-material-components 0.1.0

Material 3 Expressive desktop components for 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
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
use std::{
    cell::{Cell, RefCell},
    rc::Rc,
};

use crate::motion::{OverlayMotion, ScaledOverlay, menu_pivot};
use gpui::{
    Anchor, App, AppContext, Bounds, Context, ElementId, Entity, EntityInputHandler, Focusable,
    InteractiveElement, IntoElement, ListAlignment, ListOffset, ListSizingBehavior, ListState,
    ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled,
    Subscription, Window, canvas, div, list, prelude::FluentBuilder, px,
};
use gpui_base::{Popup, TestSupportExt};
use gpui_material_foundation::{Surface, animate, color, logical_anchor, window_material_theme};
use gpui_material_theme::{
    ColorRole, Elevation, MotionKind, MotionSpeed, TypeRole, TypographyEmphasis,
};

use super::{TextField, TextFieldEvent, TextFieldState, TextFieldVariant};

/// A selectable dropdown value. IDs remain stable when options are reordered.
#[derive(Clone, PartialEq, Eq)]
pub struct DropdownOption {
    pub id: ElementId,
    pub label: SharedString,
}

impl DropdownOption {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
        }
    }
}

/// Retains the filtered model independently of the visible rows. Comparisons
/// use stable IDs and labels; only a changed collection or query is filtered.
#[derive(Default)]
struct OptionSnapshot {
    source: Rc<[DropdownOption]>,
    query: Option<SharedString>,
    visible: Rc<[DropdownOption]>,
}

impl OptionSnapshot {
    fn reconcile(&mut self, source: Vec<DropdownOption>, query: Option<SharedString>) -> bool {
        if self.source.as_ref() == source.as_slice() && self.query == query {
            return false;
        }
        self.source = source.into();
        self.visible = if let Some(query) = &query {
            let query = query.to_lowercase();
            self.source
                .iter()
                .filter(|option| option.label.to_lowercase().contains(&query))
                .cloned()
                .collect()
        } else {
            self.source.clone()
        };
        self.query = query;
        true
    }
}

/// Keeps the editable query and pending keyboard choice across renders.
pub struct ExposedDropdownState {
    input: Entity<TextFieldState>,
    committed: SharedString,
    editable: bool,
    open: bool,
    active: Option<ElementId>,
    scroll: ListState,
    presented: Rc<[DropdownOption]>,
    metrics: Option<(
        gpui::Pixels,
        f32,
        gpui::Pixels,
        gpui_material_theme::Typography,
        u64,
    )>,
    options: OptionSnapshot,
    _input: Subscription,
}

impl ExposedDropdownState {
    pub fn new(
        value: impl Into<SharedString>,
        editable: bool,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        let committed = value.into();
        let input = cx.new(|cx| {
            let mut state = TextFieldState::new(window, cx).default_value(committed.clone());
            state.set_readonly(!editable, cx);
            state
        });
        let subscription = cx.subscribe_in(&input, window, |state, input, event, window, cx| {
            if !state.editable || !matches!(event, TextFieldEvent::Change) {
                return;
            }
            if input.update(cx, |input, cx| {
                input.marked_text_range(window, cx).is_some()
            }) {
                return;
            }
            if input.read(cx).value() != state.committed {
                state.open = true;
                state.active = None;
            }
            cx.notify();
        });
        Self {
            input,
            committed,
            editable,
            open: false,
            active: None,
            scroll: ListState::new(0, ListAlignment::Top, px(280.)),
            presented: Rc::default(),
            metrics: None,
            options: OptionSnapshot::default(),
            _input: subscription,
        }
    }

    /// Synchronizes an externally selected label and dismisses the pending list.
    pub fn set_value(
        &mut self,
        value: impl Into<SharedString>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.committed = value.into();
        self.open = false;
        self.active = None;
        self.input.update(cx, |input, cx| {
            if input.value() != self.committed {
                input.set_value(self.committed.clone(), window, cx);
            }
        });
        cx.notify();
    }

    fn toggle(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.input.read(cx).focus_handle(cx).focus(window, cx);
        if self.open {
            self.cancel(window, cx);
        } else {
            self.open = true;
            cx.notify();
        }
    }

    fn navigate(&mut self, backwards: bool, cx: &mut Context<Self>) {
        let choices = &self.options.visible;
        let index = self
            .active
            .as_ref()
            .and_then(|id| choices.iter().position(|choice| &choice.id == id));
        let next = index.map_or_else(
            || {
                if backwards {
                    choices.len().saturating_sub(1)
                } else {
                    0
                }
            },
            |index| {
                if backwards {
                    index
                        .checked_sub(1)
                        .unwrap_or(choices.len().saturating_sub(1))
                } else {
                    (index + 1) % choices.len()
                }
            },
        );
        self.active = choices.get(next).map(|choice| choice.id.clone());
        self.open = true;
        if self.scroll.bounds_for_item(next).is_some() {
            self.scroll.scroll_to_reveal_item(next);
        } else {
            self.scroll.scroll_to(ListOffset {
                item_ix: next,
                offset_in_item: px(0.),
            });
        }
        cx.notify();
    }

    fn pending(&self) -> Option<DropdownOption> {
        let choices = &self.options.visible;
        let index = self
            .active
            .as_ref()
            .and_then(|id| choices.iter().position(|choice| &choice.id == id))
            .unwrap_or(0);
        choices.get(index).cloned()
    }

    fn cancel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.set_value(self.committed.clone(), window, cx);
    }
}

type Select = Rc<dyn Fn(&DropdownOption, &mut Window, &mut App)>;

/// A Material field and anchored list in editable and selection-only modes.
/// Typing filters the list, while only selecting an option calls the owner.
#[derive(IntoElement)]
pub struct ExposedDropdown {
    id: ElementId,
    label: SharedString,
    state: Entity<ExposedDropdownState>,
    options: Vec<DropdownOption>,
    on_select: Option<Select>,
}

impl ExposedDropdown {
    pub fn new(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        state: &Entity<ExposedDropdownState>,
        options: impl IntoIterator<Item = DropdownOption>,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            state: state.clone(),
            options: options.into_iter().collect(),
            on_select: None,
        }
    }

    pub fn on_select(
        mut self,
        on_select: impl Fn(&DropdownOption, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_select = Some(Rc::new(on_select));
        self
    }
}

fn choose(
    state: &Entity<ExposedDropdownState>,
    choice: &DropdownOption,
    callback: &Option<Select>,
    window: &mut Window,
    cx: &mut App,
) {
    state.update(cx, |state, cx| {
        state.set_value(choice.label.clone(), window, cx)
    });
    if let Some(callback) = callback {
        callback(choice, window, cx);
    }
}

impl RenderOnce for ExposedDropdown {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let model = self.state.read(cx);
        let input = model.input.clone();
        let open = model.open;
        let editable = model.editable;
        let scroll = model.scroll.clone();
        let query = input.read(cx).value();
        let committed = model.committed.clone();
        let composing = input.update(cx, |input, cx| {
            input.marked_text_range(window, cx).is_some()
        });
        let filter = editable && !composing && query != committed;
        let (options, active) = self.state.update(cx, |state, _| {
            if state
                .options
                .reconcile(self.options, filter.then_some(query))
            {
                let index = state.active.as_ref().and_then(|id| {
                    state
                        .options
                        .visible
                        .iter()
                        .position(|option| &option.id == id)
                });
                if index.is_none() {
                    state.active = None;
                }
            }
            (state.options.visible.clone(), state.active.clone())
        });
        let last_visible_options = window
            .use_keyed_state((self.id.clone(), "presented-options"), cx, |_, _| {
                Rc::new(RefCell::new((
                    Rc::<[DropdownOption]>::default(),
                    None::<ElementId>,
                )))
            })
            .read(cx)
            .clone();
        if open {
            let mut visible = last_visible_options.borrow_mut();
            visible.0 = options.clone();
            visible.1.clone_from(&active);
        }
        let theme = window_material_theme(window, cx);
        let anchor = logical_anchor(Anchor::TopLeft, theme.layout.direction);
        let ink = color(theme.colors.color(ColorRole::OnSurface));
        let selected = color(theme.colors.color(ColorRole::SecondaryContainer));
        let selected_ink = color(theme.colors.color(ColorRole::OnSecondaryContainer));
        let typography = theme.typography.clone();
        let text_style = TypeRole::LabelLarge.style(TypographyEmphasis::Baseline);
        let arrow = animate(
            (self.id.clone(), "arrow"),
            f32::from(open),
            theme
                .motion
                .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion()),
            window,
            cx,
        )
        .clamp(0., 1.);
        let parent = window.current_view();
        let close = self.state.clone();
        let keys = close.clone();
        let toggle = close.clone();
        let callback = self.on_select.clone();
        let key_input = input.clone();
        let primary_toggle = self.state.clone();
        let bounds = window
            .use_keyed_state((self.id.clone(), "bounds"), cx, |_, _| {
                Rc::new(Cell::new(Bounds::default()))
            })
            .read(cx)
            .clone();
        let measure = bounds.clone();
        let popup_width = bounds.get().size.width;
        let trigger = div()
            .id((self.id.clone(), "combobox"))
            .test_support()
            .when(!editable, |trigger| {
                trigger.on_click(move |_, window, cx| {
                    primary_toggle.update(cx, |state, cx| state.toggle(window, cx));
                    cx.notify(parent);
                })
            })
            // TextField owns the single ComboBox node and delegates IME focus
            // to its Base editor. Base Select/Combobox adds a second owner
            // and cannot veto dismissal during composition, so this adapter
            // keeps only collection navigation and draft commit/cancel here.
            .capture_key_down(move |event, window, cx| {
                let key = event.keystroke.key.as_str();
                if !matches!(key, "up" | "down" | "enter" | "escape")
                    && !(key == "space" && !editable)
                {
                    return;
                }
                if key_input.update(cx, |input, cx| {
                    input.marked_text_range(window, cx).is_some()
                }) {
                    return;
                }
                let open = keys.read(cx).open;
                match key {
                    "up" | "down" => keys.update(cx, |state, cx| state.navigate(key == "up", cx)),
                    "escape" if open => keys.update(cx, |state, cx| state.cancel(window, cx)),
                    "enter" if open => {
                        if let Some(choice) = keys.read(cx).pending() {
                            choose(&keys, &choice, &callback, window, cx);
                        }
                    }
                    "enter" | "space" if !editable => {
                        keys.update(cx, |state, cx| state.toggle(window, cx));
                    }
                    _ => return,
                }
                cx.notify(parent);
                cx.stop_propagation();
            })
            .child(
                TextField::new("value", self.label, &input)
                    .variant(TextFieldVariant::Outlined)
                    .expanded(open)
                    .trailing(
                        gpui_base::Button::new("toggle-options")
                            .accessibility_label(if open {
                                "Close options"
                            } else {
                                "Open options"
                            })
                            .aria_expanded(open)
                            .min_w(px(36.))
                            .min_h(px(36.))
                            .focus_visible(move |style| style.border_1().border_color(ink))
                            .on_click(move |_, window, cx| {
                                cx.stop_propagation();
                                toggle.update(cx, |state, cx| state.toggle(window, cx));
                                cx.notify(parent);
                            })
                            .child(dropdown_arrow(arrow, ink)),
                    ),
            );
        let height = (window.viewport_size().height * 0.55).min(px(280.));
        let trigger = trigger
            .relative()
            .child(
                canvas(
                    move |bounds, window, _| {
                        if measure.replace(bounds).size != bounds.size && open {
                            window.refresh();
                        }
                    },
                    |_, _, _, _| {},
                )
                .absolute()
                .inset_0(),
            )
            // Register the arrow after the Base editor's I-beam without blocking clicks.
            .when(!editable, |trigger| {
                trigger.child(div().absolute().inset_0().cursor_default())
            });
        let motion = OverlayMotion::sample(&self.id, open, window, cx);

        let placement = window
            .use_keyed_state((self.id.clone(), "last-popup-bounds"), cx, |_, _| {
                Rc::new(Cell::new((Bounds::default(), Bounds::default())))
            })
            .read(cx)
            .clone();
        let (last_bounds, last_trigger) = placement.get();
        let trigger_bounds = placement.clone();
        let popup = Popup::new(self.id.clone(), trigger)
            .anchor(anchor)
            .offset(px(4.))
            .on_position(move |resolved, trigger| trigger_bounds.set((resolved.bounds, trigger)));
        let content = motion.map(|motion| {
            let dp = move |value| motion.px(value);
            let spacing = dp(16.);
            let (options, active) = if open {
                (options, active)
            } else {
                last_visible_options.borrow().clone()
            };
            let width = if open {
                popup_width.max(px(120.)).min(window.viewport_size().width)
            } else {
                last_bounds.size.width
            };
            let font_revision = gpui_material_foundation::font_cache_revision(cx);
            self.state.update(cx, |state, _| {
                let metrics = (
                    width,
                    motion.scale,
                    window.rem_size(),
                    typography,
                    font_revision,
                );
                if !Rc::ptr_eq(&state.presented, &options) {
                    state.scroll.reset(options.len());
                    if let Some(index) = active
                        .as_ref()
                        .and_then(|id| options.iter().position(|option| &option.id == id))
                    {
                        state.scroll.scroll_to(ListOffset {
                            item_ix: index,
                            offset_in_item: px(0.),
                        });
                    }
                    state.presented = options.clone();
                } else if state.metrics.as_ref() != Some(&metrics) {
                    let anchor = state.scroll.logical_scroll_top();
                    state.scroll.remeasure();
                    state.scroll.scroll_to(anchor);
                }
                state.metrics = Some(metrics);
            });
            let content = div()
                .id(if open { "options" } else { "options-exit" })
                .test_support()
                .opacity(motion.alpha)
                .w(width * motion.scale)
                .text_color(ink)
                .max_h(height * motion.scale)
                .when(open, |list| {
                    list.role(Role::ListBox)
                        .on_mouse_down_out(move |event, window, cx| {
                            if !bounds.get().contains(&event.position) {
                                close.update(cx, |state, cx| state.cancel(window, cx));
                                cx.notify(parent);
                            }
                        })
                })
                .child(
                    Surface::new(ColorRole::SurfaceContainer)
                        .shadow_elevation(Elevation::Level2)
                        .shadow_scale(motion.scale)
                        .rounded(spacing * 0.25)
                        .w_full()
                        .py(spacing * 0.5)
                        .child(if options.is_empty() {
                            div()
                                .id("options-scroll-region")
                                .test_support()
                                .max_h((height - px(16.)).max(px(0.)) * motion.scale)
                                .overflow_hidden()
                                .child(
                                    div()
                                        .px(spacing * 0.75)
                                        .py(spacing * 0.5)
                                        .child("No matching options"),
                                )
                                .into_any_element()
                        } else {
                            let row_state = self.state.clone();
                            let row_callback = self.on_select.clone();
                            div()
                                .id("options-scroll-region")
                                .test_support()
                                .max_h((height - px(16.)).max(px(0.)) * motion.scale)
                                .overflow_hidden()
                                .child(
                                    list(scroll.clone(), move |index, _, _| {
                                        let choice = options[index].clone();
                                        let current = active.as_ref() == Some(&choice.id);
                                        let state = row_state.clone();
                                        let callback = row_callback.clone();
                                        let accessible = choice.clone();
                                        let accessible_state = state.clone();
                                        let accessible_callback = callback.clone();
                                        div()
                                            .id(choice.id.clone())
                                            .test_support()
                                            .when(open, |row| {
                                                row.role(Role::ListBoxOption)
                                                    .aria_label(choice.label.clone())
                                                    .aria_selected(current)
                                                    .aria_position_in_set(index + 1)
                                                    .aria_size_of_set(options.len())
                                            })
                                            .when(current, |row| {
                                                row.bg(selected).text_color(selected_ink)
                                            })
                                            .when(open && current, |row| {
                                                row.aria_active_descendant()
                                            })
                                            .when(open, |row| {
                                                row.hover(move |style| {
                                                    style.bg(if current {
                                                        selected.blend(selected_ink.opacity(0.08))
                                                    } else {
                                                        ink.opacity(0.08)
                                                    })
                                                })
                                            })
                                            .min_h(dp(48.))
                                            .w_full()
                                            .px(spacing * 0.75)
                                            .flex()
                                            .items_center()
                                            .child(choice.label.clone())
                                            .when(open, |row| {
                                                row.on_a11y_action(
                                                    gpui::AccessibleAction::Click,
                                                    move |_, window, cx| {
                                                        choose(
                                                            &accessible_state,
                                                            &accessible,
                                                            &accessible_callback,
                                                            window,
                                                            cx,
                                                        );
                                                        cx.notify(parent);
                                                    },
                                                )
                                                .on_click(move |_, window, cx| {
                                                    choose(&state, &choice, &callback, window, cx);
                                                    cx.notify(parent);
                                                })
                                            })
                                            .into_any_element()
                                    })
                                    .with_sizing_behavior(ListSizingBehavior::Infer)
                                    .w_full()
                                    .max_h((height - px(16.)).max(px(0.)) * motion.scale),
                                )
                                .into_any_element()
                        }),
                )
                .when(!open, |list| {
                    list.child(div().absolute().inset_0().occlude())
                });
            let content =
                gpui_material_foundation::text_style(content, text_style, motion.scale, window, cx);
            ScaledOverlay::new(content, motion, move |menu| {
                menu_pivot(
                    menu,
                    if open {
                        placement.get().1
                    } else {
                        last_trigger
                    },
                )
            })
            .width(width)
        });
        if open {
            return div().child(popup.content(content.expect("open dropdown")));
        }
        let exit = content
            .filter(|_| last_bounds.size.width > px(0.))
            .map(|content| {
                gpui::deferred(
                    gpui_base::Positioner::corner(Anchor::TopLeft, last_bounds.origin)
                        .child(content),
                )
                .with_priority(100)
            });
        div().child(popup).children(exit)
    }
}

// The official dropdown symbol rotates with the existing expansion animation.
// Keep this decorative element separate from the Base trigger's semantics.
fn dropdown_arrow(progress: f32, ink: gpui::Hsla) -> impl IntoElement {
    div()
        .flex()
        .items_center()
        .justify_center()
        .text_color(ink)
        .child(
            crate::Icon::new(crate::IconName::ArrowDropDown)
                .size(px(24.))
                .rotate(gpui::radians(std::f32::consts::PI * progress)),
        )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn option_snapshot_reuses_results_and_invalidates_labels_and_query() {
        let mut snapshot = OptionSnapshot::default();
        let options = || {
            vec![
                DropdownOption::new("a", "Alpha"),
                DropdownOption::new("b", "Beta"),
            ]
        };
        assert!(snapshot.reconcile(options(), None));
        let unfiltered = snapshot.visible.clone();
        assert!(Rc::ptr_eq(&unfiltered, &snapshot.source));
        assert!(!snapshot.reconcile(options(), None));
        assert!(Rc::ptr_eq(&unfiltered, &snapshot.visible));
        assert!(snapshot.reconcile(options(), Some("ALP".into())));
        assert_eq!(snapshot.visible.len(), 1);
        assert_eq!(snapshot.visible[0].id, ElementId::from("a"));
        assert!(snapshot.reconcile(
            vec![
                DropdownOption::new("a", "Renamed"),
                DropdownOption::new("b", "Beta")
            ],
            Some("ALP".into())
        ));
        assert!(snapshot.visible.is_empty());
    }
}