use crate::motion::{self, Motion};
use crate::theme::color;
use crate::tokens::ColorRole;
use gpui_kit::{
Anchor, AnyElement, App, Bounds, BoxShadow, Element, ElementId, Entity, FocusHandle,
GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, KeyDownEvent, LayoutId,
MouseButton, ParentElement, Pixels, Point, Rems, Size, Styled, Window, canvas, div, point, px,
};
use gpui_kit::{KeyBinding, actions, prelude::FluentBuilder as _};
use std::{cell::Cell, rc::Rc};
actions!(
u0ui_floating,
[
IntoSurface,
SurfaceTab,
SurfaceTabPrev
]
);
pub(crate) const TRIGGER_CONTEXT: &str = "U0FloatingTrigger";
pub(crate) const SURFACE_CONTEXT: &str = "U0FloatingSurface";
pub(crate) fn init(cx: &mut App) {
cx.bind_keys([
KeyBinding::new("tab", IntoSurface, Some(TRIGGER_CONTEXT)),
KeyBinding::new("tab", SurfaceTab, Some(SURFACE_CONTEXT)),
KeyBinding::new("shift-tab", SurfaceTabPrev, Some(SURFACE_CONTEXT)),
]);
}
pub(crate) fn tab_past(
from: &FocusHandle,
surface: &FocusHandle,
window: &mut Window,
cx: &mut App,
) {
from.focus(window, cx);
let Ok(tab) = cx.build_action("root::Tab", None) else {
return;
};
let mut seen = Vec::new();
while let Some(at) = window.focused(cx) {
if seen.contains(&at) {
break;
}
at.dispatch_action(&*tab, window, cx);
seen.push(at);
if !surface.contains_focused(window, cx) {
break;
}
}
}
fn step(name: &str, window: &mut Window, cx: &mut App) {
if let (Some(at), Ok(action)) = (window.focused(cx), cx.build_action(name, None)) {
at.dispatch_action(&*action, window, cx);
}
}
type FlowState = (FocusHandle, FocusHandle, bool);
fn trigger_now(handles: &Entity<FlowState>, window: &Window, cx: &App) -> bool {
handles.read(cx).0.contains_focused(window, cx)
}
pub(crate) struct TabFlow {
pub trigger: FocusHandle,
pub end: FocusHandle,
}
impl TabFlow {
pub fn new(
id: &ElementId,
open: bool,
surface: &FocusHandle,
set_open: &OpenChange,
window: &mut Window,
cx: &mut App,
) -> Self {
let handles: Entity<FlowState> =
window.use_keyed_state((id.clone(), "tab-flow"), cx, |_, cx| {
(cx.focus_handle(), cx.focus_handle(), false)
});
let (trigger, end, had) = handles.read(cx).clone();
let inside = surface.contains_focused(window, cx) || trigger.contains_focused(window, cx);
if !open {
if had {
handles.update(cx, |h, _| h.2 = false);
}
} else if inside {
if !had {
handles.update(cx, |h, _| h.2 = true);
}
} else if had {
let set_open = set_open.clone();
let surface = surface.clone();
window.defer(cx, move |window, cx| {
let inside =
surface.contains_focused(window, cx) || trigger_now(&handles, window, cx);
if !inside {
handles.update(cx, |h, _| h.2 = false);
set_open(false, window, cx);
}
});
}
Self { trigger, end }
}
pub fn trigger(
&self,
wrapper: gpui_kit::Stateful<gpui_kit::Div>,
open: bool,
surface: &FocusHandle,
set_open: &OpenChange,
) -> gpui_kit::Stateful<gpui_kit::Div> {
let end = self.end.clone();
let into = {
let surface = surface.clone();
let set_open = set_open.clone();
let end = end.clone();
move |_: &IntoSurface, window: &mut Window, cx: &mut App| {
cx.stop_propagation();
surface.focus(window, cx);
step("root::Tab", window, cx);
if !surface.contains_focused(window, cx) || surface.is_focused(window) {
set_open(false, window, cx);
tab_past(&end, &surface, window, cx);
}
}
};
wrapper
.track_focus(&self.trigger.clone().tab_stop(false))
.when(open, |this| {
this.key_context(TRIGGER_CONTEXT).on_action(into)
})
.child(div().track_focus(&end.tab_stop(false)).absolute().size_0())
}
pub fn surface(
&self,
surface_el: gpui_kit::Stateful<gpui_kit::Div>,
surface: &FocusHandle,
set_open: &OpenChange,
) -> gpui_kit::Stateful<gpui_kit::Div> {
let tab = {
let surface = surface.clone();
let set_open = set_open.clone();
let end = self.end.clone();
move |_: &SurfaceTab, window: &mut Window, cx: &mut App| {
cx.stop_propagation();
step("root::Tab", window, cx);
if !surface.contains_focused(window, cx) {
set_open(false, window, cx);
tab_past(&end, &surface, window, cx);
}
}
};
let back = {
let surface = surface.clone();
let end = self.end.clone();
move |_: &SurfaceTabPrev, window: &mut Window, cx: &mut App| {
cx.stop_propagation();
step("root::TabPrev", window, cx);
if !surface.contains_focused(window, cx) || surface.is_focused(window) {
end.focus(window, cx);
step("root::TabPrev", window, cx);
}
}
};
surface_el
.key_context(SURFACE_CONTEXT)
.on_action(tab)
.on_action(back)
}
}
pub(crate) fn rem(px_value: f32) -> Rems {
gpui_kit::rems(px_value / crate::tokens::REM_PX)
}
pub fn floating_shadow() -> Vec<BoxShadow> {
vec![BoxShadow::new(px(0.), px(2.), color(ColorRole::Shadow)).blur_radius(px(6.))]
}
pub fn popover_drop_shadow() -> Vec<BoxShadow> {
vec![BoxShadow::new(px(0.), px(2.), gpui_kit::hsla(0., 0., 0., 0.2)).blur_radius(px(2.))]
}
pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
pub type Callback = Rc<dyn Fn(&mut Window, &mut App)>;
#[derive(Clone)]
pub(crate) struct Openness {
pub open: bool,
state: Entity<bool>,
controlled: bool,
on_change: Option<OpenChange>,
}
impl Openness {
pub fn set(&self, open: bool, window: &mut Window, cx: &mut App) {
if !self.controlled {
self.state.update(cx, |state, cx| {
if *state != open {
*state = open;
cx.notify();
}
});
}
if let Some(on_change) = &self.on_change {
on_change(open, window, cx);
}
window.refresh();
}
pub fn setter(&self) -> OpenChange {
let this = self.clone();
Rc::new(move |open, window, cx| this.set(open, window, cx))
}
}
pub(crate) fn openness(
id: &ElementId,
open: Option<bool>,
default_open: bool,
on_change: Option<OpenChange>,
window: &mut Window,
cx: &mut App,
) -> Openness {
let state = window.use_keyed_state((id.clone(), "open"), cx, |_, _| default_open);
Openness {
open: open.unwrap_or_else(|| *state.read(cx)),
state,
controlled: open.is_some(),
on_change,
}
}
pub(crate) fn presence(
id: impl Into<ElementId>,
open: bool,
enter: Motion,
exit: Motion,
window: &mut Window,
cx: &mut App,
) -> f32 {
let id: ElementId = id.into();
let motion = if open { enter } else { exit };
motion::animate(
(id, "presence"),
if open { 1f32 } else { 0. },
motion.spatial(false),
window,
cx,
)
}
pub(crate) fn entrance(
id: impl Into<ElementId>,
open: bool,
enter: Motion,
window: &mut Window,
cx: &mut App,
) -> f32 {
let id: ElementId = id.into();
if open {
motion::animate((id, "presence"), 1f32, enter.spatial(false), window, cx)
} else {
gpui_kit::base::transition(
(id, "presence"),
0f32,
gpui_kit::base::Transition::new(std::time::Duration::ZERO),
window,
cx,
)
}
}
struct SurfaceFocus {
focus: FocusHandle,
previous: Option<FocusHandle>,
shown: bool,
}
pub(crate) fn surface_focus(
id: &ElementId,
open: bool,
initial: Option<FocusHandle>,
window: &mut Window,
cx: &mut App,
) -> FocusHandle {
surface_focus_returning(id, open, initial, None, window, cx)
}
pub(crate) fn surface_focus_returning(
id: &ElementId,
open: bool,
initial: Option<FocusHandle>,
return_to: Option<FocusHandle>,
window: &mut Window,
cx: &mut App,
) -> FocusHandle {
let state = window.use_keyed_state((id.clone(), "surface-focus"), cx, |_, cx| SurfaceFocus {
focus: cx.focus_handle(),
previous: None,
shown: false,
});
let shown = state.read(cx).shown;
if open && !shown {
let previous = return_to.or_else(|| window.focused(cx));
state.update(cx, |state, _| {
state.shown = true;
state.previous = previous;
});
let target = initial.unwrap_or_else(|| state.read(cx).focus.clone());
window.defer(cx, move |window, cx| target.focus(window, cx));
} else if !open && shown {
let previous = state.update(cx, |state, _| {
state.shown = false;
state.previous.take()
});
let surface = state.read(cx).focus.clone();
let now = window.focused(cx);
if moved_elsewhere(now.as_ref(), previous.as_ref(), || {
surface.contains_focused(window, cx)
}) {
return state.read(cx).focus.clone();
}
window.defer(cx, move |window, cx| match previous {
Some(previous) => previous.focus(window, cx),
None if surface.contains_focused(window, cx) => window.blur(cx),
None => {}
});
}
state.read(cx).focus.clone()
}
fn moved_elsewhere(
now: Option<&FocusHandle>,
previous: Option<&FocusHandle>,
inside: impl FnOnce() -> bool,
) -> bool {
match now {
Some(now) => Some(now) != previous && !inside(),
None => false,
}
}
pub(crate) fn trigger_wrapper(
id: impl Into<ElementId>,
trigger: AnyElement,
activate: Callback,
) -> gpui_kit::Stateful<gpui_kit::Div> {
let on_key = activate.clone();
div()
.id(id)
.flex_shrink_0()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
activate(window, cx);
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if matches!(event.keystroke.key.as_str(), "enter" | "space") && !event.is_held {
on_key(window, cx);
cx.stop_propagation();
}
})
.child(trigger)
}
pub const WINDOW_MARGIN: f32 = 8.;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DropSide {
#[default]
Below,
Above,
}
impl DropSide {
pub fn choose(top: f32, bottom: f32, height: f32, viewport: f32) -> Self {
let below = Self::Below.room(top, bottom, viewport);
let above = Self::Above.room(top, bottom, viewport);
if height <= below || (height > above && below >= above) {
Self::Below
} else {
Self::Above
}
}
pub fn room(self, top: f32, bottom: f32, viewport: f32) -> f32 {
match self {
Self::Below => viewport - WINDOW_MARGIN - bottom,
Self::Above => top - WINDOW_MARGIN,
}
.max(0.)
}
pub fn anchor(self) -> Anchor {
match self {
Self::Below => Anchor::TopLeft,
Self::Above => Anchor::BottomLeft,
}
}
pub fn anchor_center(self) -> Anchor {
match self {
Self::Below => Anchor::TopCenter,
Self::Above => Anchor::BottomCenter,
}
}
pub fn anchor_end(self) -> Anchor {
match self {
Self::Below => Anchor::TopRight,
Self::Above => Anchor::BottomRight,
}
}
}
pub fn menu_hangs_from_end(left: f32, right: f32, width: f32, viewport: f32) -> bool {
let start_fits = viewport - WINDOW_MARGIN - width - left >= 0.;
let end_fits = right - width >= 0.;
!start_fits && end_fits
}
#[derive(Clone, Default)]
pub(crate) struct DropAnchor {
trigger: Rc<Cell<Bounds<Pixels>>>,
surface: Rc<Cell<Size<Pixels>>>,
side: Rc<Cell<DropSide>>,
top_inset: Rc<Cell<f32>>,
settled: Rc<Cell<bool>>,
}
pub(crate) fn drop_anchor(
id: impl Into<ElementId>,
window: &mut Window,
cx: &mut App,
) -> DropAnchor {
window
.use_keyed_state(id.into(), cx, |_, _| DropAnchor::default())
.read(cx)
.clone()
}
impl DropAnchor {
pub fn width(&self) -> f32 {
f32::from(self.trigger.get().size.width)
}
pub fn height(&self) -> f32 {
f32::from(self.trigger.get().size.height)
}
pub fn set_top_inset(&self, inset: f32) {
self.top_inset.set(inset.max(0.));
}
fn edges(trigger: Bounds<Pixels>, inset: f32) -> (f32, f32) {
let bottom = f32::from(trigger.bottom());
((f32::from(trigger.top()) + inset).min(bottom), bottom)
}
pub fn measure_trigger(&self) -> impl IntoElement + use<> {
let trigger = self.trigger.clone();
canvas(move |bounds, _, _| trigger.set(bounds), |_, _, _, _| {})
.absolute()
.top_0()
.left_0()
.size_full()
}
pub fn place(&self, height: f32, window: &Window) -> (DropSide, f32) {
let (top, bottom) = Self::edges(self.trigger.get(), self.top_inset.get());
let viewport = f32::from(window.viewport_size().height);
let side = DropSide::choose(top, bottom, height, viewport);
self.side.set(side);
(side, side.room(top, bottom, viewport))
}
pub fn hangs_from_end(&self, window: &Window) -> Option<bool> {
let width = f32::from(self.surface.get().width);
if width <= 0. {
return None;
}
let trigger = self.trigger.get();
Some(menu_hangs_from_end(
f32::from(trigger.left()),
f32::from(trigger.right()),
width,
f32::from(window.viewport_size().width),
))
}
pub fn place_measured(&self, window: &Window) -> DropSide {
self.place(f32::from(self.surface.get().height), window).0
}
pub fn measure_surface(&self) -> impl IntoElement + use<> {
let (trigger, surface, side, inset, settled) = (
self.trigger.clone(),
self.surface.clone(),
self.side.clone(),
self.top_inset.clone(),
self.settled.clone(),
);
canvas(
move |bounds, window, _| {
surface.set(bounds.size);
let (top, bottom) = Self::edges(trigger.get(), inset.get());
let want = DropSide::choose(
top,
bottom,
f32::from(bounds.size.height),
f32::from(window.viewport_size().height),
);
settled.set(want == side.get());
if want != side.get() {
window.request_animation_frame();
}
},
|_, _, _, _| {},
)
.absolute()
.top_0()
.left_0()
.size_full()
}
}
impl DropAnchor {
pub fn surface(&self, content: impl IntoElement) -> AnyElement {
self.settled.set(true);
PaintGate {
child: div()
.relative()
.child(content)
.child(self.measure_surface())
.into_any_element(),
settled: self.settled.clone(),
}
.into_any_element()
}
}
struct PaintGate {
child: AnyElement,
settled: Rc<Cell<bool>>,
}
impl Element for PaintGate {
type RequestLayoutState = ();
type PrepaintState = ();
fn id(&self) -> Option<ElementId> {
None
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, ()) {
(self.child.request_layout(window, cx), ())
}
fn prepaint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
_: &mut (),
window: &mut Window,
cx: &mut App,
) {
self.child.prepaint(window, cx);
}
fn paint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
_: &mut (),
_: &mut (),
window: &mut Window,
cx: &mut App,
) {
if self.settled.get() {
self.child.paint(window, cx);
}
}
}
pub(crate) struct Translate {
child: AnyElement,
fraction: Point<f32>,
offset: Point<Pixels>,
}
pub fn cross_origin(center: f32, size: f32, fraction: f32, px: f32, viewport: f32) -> f32 {
let desired = center - size / 2. + fraction * size + px;
desired
.min(viewport - WINDOW_MARGIN - size)
.max(WINDOW_MARGIN)
}
impl Translate {
pub fn new(child: impl IntoElement, fraction: Point<f32>, offset: Point<Pixels>) -> Self {
Self {
child: child.into_any_element(),
fraction,
offset,
}
}
pub fn y(child: impl IntoElement, y: f32) -> Self {
Self::new(child, point(0., 0.), point(px(0.), px(y)))
}
}
impl Element for Translate {
type RequestLayoutState = ();
type PrepaintState = ();
fn id(&self) -> Option<ElementId> {
None
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, ()) {
(self.child.request_layout(window, cx), ())
}
fn prepaint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
bounds: Bounds<Pixels>,
_: &mut (),
window: &mut Window,
cx: &mut App,
) {
let offset = point(
bounds.size.width * self.fraction.x + self.offset.x,
bounds.size.height * self.fraction.y + self.offset.y,
);
window.with_element_offset(offset, |window| self.child.prepaint(window, cx));
}
fn paint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
_: &mut (),
_: &mut (),
window: &mut Window,
cx: &mut App,
) {
self.child.paint(window, cx);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn menus_hang_from_the_trigger_start_unless_the_window_end_is_near() {
assert!(!menu_hangs_from_end(146., 178., 188., 960.));
assert!(menu_hangs_from_end(900., 932., 188., 960.));
assert!(!menu_hangs_from_end(764., 796., 188., 960.));
assert!(menu_hangs_from_end(765., 796., 188., 960.));
assert!(!menu_hangs_from_end(100., 132., 400., 300.));
}
#[test]
fn floating_shadow_is_carbons() {
crate::theme::tests_set(crate::tokens::CarbonTheme::White);
let shadow = &floating_shadow()[0];
assert_eq!(
(shadow.offset.x, shadow.offset.y, shadow.blur_radius),
(px(0.), px(2.), px(6.))
);
assert!(!shadow.inset);
let drop = &popover_drop_shadow()[0];
assert_eq!(
(drop.offset.y, drop.blur_radius, drop.color.a),
(px(2.), px(2.), 0.2)
);
}
#[test]
fn end_aligned_surfaces_shift_before_clamping() {
assert_eq!(cross_origin(1390., 336., -0.5, 20., 1440.), 1074.);
assert_eq!(cross_origin(1430., 336., -0.5, 20., 1440.), 1096.);
assert_eq!(cross_origin(1300., 336., -0.5, 20., 1440.), 984.);
assert_eq!(cross_origin(100., 336., 0., 0., 1440.), 8.);
assert_eq!(cross_origin(720., 336., 0., 0., 1440.), 552.);
assert_eq!(cross_origin(400., 200., 0.5, -20., 1440.), 380.);
}
fn trigger_top(window: &Window) -> Pixels {
window.viewport_size().height - px(60.)
}
struct DropHarness {
painted: Rc<std::cell::RefCell<Vec<Bounds<Pixels>>>>,
}
impl gpui_kit::Render for DropHarness {
fn render(
&mut self,
window: &mut Window,
cx: &mut gpui_kit::Context<Self>,
) -> impl IntoElement {
let anchor = drop_anchor("drop", window, cx);
let trigger = div()
.relative()
.size(px(100.))
.h(px(32.))
.child(anchor.measure_trigger());
let side = anchor.place_measured(window);
let painted = self.painted.clone();
let content = div().w(px(100.)).h(px(120.)).child(
canvas(|_, _, _| {}, move |b, _, _, _| painted.borrow_mut().push(b)).size_full(),
);
div().size_full().relative().child(
div()
.absolute()
.top(trigger_top(window))
.left(px(20.))
.child(
gpui_kit::base::Popup::new("popup", trigger)
.anchor(side.anchor())
.content(anchor.surface(content)),
),
)
}
}
#[gpui_kit::test]
fn a_drop_surface_never_paints_on_the_side_it_does_not_fit(cx: &mut gpui_kit::TestAppContext) {
let painted = Rc::new(std::cell::RefCell::new(Vec::new()));
let (_, window) = cx.add_window_view({
let painted = painted.clone();
|_, _| DropHarness { painted }
});
for _ in 0..4 {
window.update(|window, cx| window.draw(cx).clear(cx));
}
let top = window.update(|window, _| trigger_top(window));
let painted = painted.borrow();
assert!(!painted.is_empty(), "the surface never painted");
for bounds in painted.iter() {
assert!(
bounds.bottom() <= top,
"painted over the trigger: {bounds:?}"
);
}
}
#[test]
fn drop_side_opens_below_and_flips_above_without_covering_the_trigger() {
assert_eq!(DropSide::choose(400., 432., 160., 900.), DropSide::Below);
assert_eq!(DropSide::Below.room(400., 432., 900.), 460.);
assert_eq!(DropSide::choose(804., 836., 160., 900.), DropSide::Above);
assert_eq!(DropSide::Above.room(804., 836., 900.), 796.);
assert_eq!(DropSide::choose(700., 732., 160., 900.), DropSide::Below);
assert_eq!(DropSide::choose(700., 733., 160., 900.), DropSide::Above);
assert_eq!(DropSide::choose(100., 132., 800., 900.), DropSide::Below);
assert_eq!(DropSide::choose(700., 732., 800., 900.), DropSide::Above);
assert_eq!(DropSide::Below.room(100., 900., 900.), 0.);
assert_eq!(DropSide::Below.anchor(), Anchor::TopLeft);
assert_eq!(DropSide::Above.anchor(), Anchor::BottomLeft);
}
}