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};
#[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(),
}
}
}
#[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
}
}
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,
}
}
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)>;
#[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);
})
})
.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(),
)
.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)
}
}
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());
}
}