use std::rc::Rc;
use gpui::{
Anchor, AnyElement, App, Context, DismissEvent, Element, ElementId, Entity, FocusHandle,
Focusable, GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, LayoutId,
RenderOnce, SharedString, StyleRefinement, Styled, Window, prelude::FluentBuilder,
};
use crate::{Selectable, button::Button, menu::PopupMenu, popover::Popover};
pub trait DropdownMenu: Styled + Selectable + InteractiveElement + IntoElement + 'static {
fn dropdown_menu(
self,
f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
) -> DropdownMenuPopover<Self> {
self.dropdown_menu_with_anchor(Anchor::TopLeft, f)
}
fn dropdown_menu_with_anchor(
mut self,
anchor: impl Into<Anchor>,
f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
) -> DropdownMenuPopover<Self> {
let style = self.style().clone();
let id = self.interactivity().element_id.clone();
DropdownMenuPopover::new(id.unwrap_or(0.into()), anchor, self, f).trigger_style(style)
}
}
impl DropdownMenu for Button {}
#[derive(IntoElement)]
pub struct DropdownMenuPopover<T: Selectable + IntoElement + 'static> {
id: ElementId,
style: StyleRefinement,
anchor: Anchor,
trigger: T,
builder: Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>,
on_open_change: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>,
}
impl<T> DropdownMenuPopover<T>
where
T: Selectable + IntoElement + 'static,
{
fn new(
id: ElementId,
anchor: impl Into<Anchor>,
trigger: T,
builder: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
) -> Self {
Self {
id: SharedString::from(format!("dropdown-menu:{:?}", id)).into(),
style: StyleRefinement::default(),
anchor: anchor.into(),
trigger,
builder: Rc::new(builder),
on_open_change: None,
}
}
pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
self.anchor = anchor.into();
self
}
fn trigger_style(mut self, style: StyleRefinement) -> Self {
self.style = style;
self
}
pub fn on_open_change(
mut self,
callback: impl Fn(&bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_open_change = Some(Rc::new(callback));
self
}
}
#[derive(Default)]
struct DropdownMenuState {
menu: Option<Entity<PopupMenu>>,
}
impl<T> RenderOnce for DropdownMenuPopover<T>
where
T: Selectable + IntoElement + 'static,
{
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
TriggerFocus::new(self.id.clone(), move |trigger_focus, window, cx| {
self.render_popover(trigger_focus, window, cx)
.into_any_element()
})
}
}
impl<T> DropdownMenuPopover<T>
where
T: Selectable + IntoElement + 'static,
{
fn render_popover(
self,
trigger_focus: FocusHandle,
window: &mut Window,
cx: &mut App,
) -> Popover {
let builder = self.builder.clone();
let menu_state =
window.use_keyed_state(self.id.clone(), cx, |_, _| DropdownMenuState::default());
Popover::new(SharedString::from(format!("popover:{}", self.id)))
.appearance(false)
.overlay_closable(false)
.trigger(self.trigger)
.trigger_style(self.style)
.anchor(self.anchor)
.when_some(self.on_open_change, |this, callback| {
this.on_open_change(move |open, window, cx| callback(open, window, cx))
})
.content(move |_, window, cx| {
let menu = match menu_state.read(cx).menu.clone() {
Some(menu) => menu,
None => {
let builder = builder.clone();
let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
builder(menu, window, cx)
});
menu.update(cx, |menu, cx| {
menu.set_trigger_focus(Some(trigger_focus.clone()), cx)
});
menu_state.update(cx, |state, _| {
state.menu = Some(menu.clone());
});
menu.focus_handle(cx).focus(window, cx);
let popover_state = cx.entity();
window
.subscribe(&menu, cx, {
let menu_state = menu_state.clone();
move |_, _: &DismissEvent, window, cx| {
popover_state.update(cx, |state, cx| {
state.dismiss(window, cx);
});
menu_state.update(cx, |state, _| {
state.menu = None;
});
}
})
.detach();
menu.clone()
}
};
menu.clone()
})
}
}
type TriggerFocusBuild = Box<dyn FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement>;
struct TriggerFocus {
id: ElementId,
build: Option<TriggerFocusBuild>,
}
#[derive(Default)]
struct TriggerFocusState {
focus_handle: Option<FocusHandle>,
}
struct TriggerFocusFrame {
focus_handle: FocusHandle,
child: AnyElement,
}
impl TriggerFocus {
fn new(
id: ElementId,
build: impl FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement + 'static,
) -> Self {
Self {
id,
build: Some(Box::new(build)),
}
}
}
impl IntoElement for TriggerFocus {
type Element = Self;
fn into_element(self) -> Self::Element {
self
}
}
impl Element for TriggerFocus {
type RequestLayoutState = TriggerFocusFrame;
type PrepaintState = ();
fn id(&self) -> Option<ElementId> {
Some(self.id.clone())
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
id: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
let focus_handle =
window.with_optional_element_state::<TriggerFocusState, _>(id, |state, _| {
let mut state = state.flatten().unwrap_or_default();
let focus_handle = state
.focus_handle
.get_or_insert_with(|| cx.focus_handle())
.clone();
(focus_handle, Some(state))
});
let build = self.build.take().expect("TriggerFocus is laid out once");
let mut child = build(focus_handle.clone(), window, cx);
let layout_id = child.request_layout(window, cx);
(
layout_id,
TriggerFocusFrame {
focus_handle,
child,
},
)
}
fn prepaint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: gpui::Bounds<gpui::Pixels>,
frame: &mut Self::RequestLayoutState,
window: &mut Window,
cx: &mut App,
) {
window.set_focus_handle(&frame.focus_handle, cx);
frame.child.prepaint(window, cx);
}
fn paint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: gpui::Bounds<gpui::Pixels>,
frame: &mut Self::RequestLayoutState,
_: &mut Self::PrepaintState,
window: &mut Window,
cx: &mut App,
) {
frame.child.paint(window, cx);
}
}
#[cfg(test)]
mod tests {
use super::*;
use gpui::{
KeyBinding, MouseButton, ParentElement as _, Render, TestAppContext, actions, div, point,
px,
};
use std::cell::Cell;
actions!(dropdown_menu_test, [CopyText]);
const CONTEXT: &str = "dropdown_menu_test";
struct TestRoot {
frames: Rc<Cell<usize>>,
}
impl Render for TestRoot {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
self.frames.set(self.frames.get() + 1);
div()
.size_full()
.child(
div()
.key_context(CONTEXT)
.on_action(|_: &CopyText, _, _| {})
.child(
Button::new("trigger")
.label("Edit")
.w(px(100.))
.h(px(30.))
.dropdown_menu(|menu, _, _| menu.menu("Copy", Box::new(CopyText))),
),
)
.child(div().child("Status"))
}
}
#[gpui::test]
fn shortcut_hint_is_painted_on_the_frame_the_menu_opens(cx: &mut TestAppContext) {
cx.update(|cx| {
crate::init(cx);
cx.bind_keys([KeyBinding::new("ctrl-c", CopyText, Some(CONTEXT))]);
});
let frames = Rc::new(Cell::new(0));
let (_, cx) = cx.add_window_view({
let frames = frames.clone();
move |_, _| TestRoot { frames }
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let frames_before_open = frames.get();
cx.simulate_mouse_down(
point(px(10.), px(10.)),
MouseButton::Left,
Default::default(),
);
assert_eq!(
frames.get(),
frames_before_open + 1,
"the press must be followed by exactly one frame for this to test the first one"
);
assert!(
cx.debug_bounds("kbd:ctrl-c").is_some(),
"the shortcut hint must be painted on the same frame as its item"
);
}
}