Compare commits

...
Sign in to create a new pull request.

2 commits

Author SHA1 Message Date
Nathan Sobo
e931a1d295 WIP 2023-12-19 20:21:59 -07:00
Nathan Sobo
66f833eccf Use MouseState instead of ActiveDrag to make room for clicks
Co-Authored-By: Max <max@zed.dev>
2023-12-19 18:31:27 -07:00
5 changed files with 293 additions and 320 deletions

View file

@ -899,7 +899,8 @@ impl EditorElement {
} }
let fold_corner_radius = 0.15 * layout.position_map.line_height; let fold_corner_radius = 0.15 * layout.position_map.line_height;
cx.with_element_id(Some("folds"), |cx| { cx.with_element_id(Some("folds"), |global_element_id, cx| {
let global_element_id = global_element_id.unwrap();
let snapshot = &layout.position_map.snapshot; let snapshot = &layout.position_map.snapshot;
for fold in snapshot.folds_in_range(layout.visible_anchor_range.clone()) { for fold in snapshot.folds_in_range(layout.visible_anchor_range.clone()) {
let fold_range = fold.range.clone(); let fold_range = fold.range.clone();
@ -948,7 +949,7 @@ impl EditorElement {
fold_bounds.size, fold_bounds.size,
cx, cx,
|fold_element_state, cx| { |fold_element_state, cx| {
if fold_element_state.is_active() { if cx.element_clicked(&global_element_id) {
cx.theme().colors().ghost_element_active cx.theme().colors().ghost_element_active
} else if fold_bounds.contains(&cx.mouse_position()) { } else if fold_bounds.contains(&cx.mouse_position()) {
cx.theme().colors().ghost_element_hover cx.theme().colors().ghost_element_hover
@ -2016,7 +2017,7 @@ impl EditorElement {
.width; .width;
let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width; let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width;
let (scroll_width, blocks) = cx.with_element_id(Some("editor_blocks"), |cx| { let (scroll_width, blocks) = cx.with_element_id(Some("editor_blocks"), |_, cx| {
self.layout_blocks( self.layout_blocks(
start_row..end_row, start_row..end_row,
&snapshot, &snapshot,
@ -2101,7 +2102,7 @@ impl EditorElement {
cx, cx,
); );
let mut fold_indicators = cx.with_element_id(Some("gutter_fold_indicators"), |cx| { let mut fold_indicators = cx.with_element_id(Some("gutter_fold_indicators"), |_, cx| {
editor.render_fold_indicators( editor.render_fold_indicators(
fold_statuses, fold_statuses,
&style, &style,
@ -2840,7 +2841,7 @@ impl Element for EditorElement {
self.paint_mouse_listeners(bounds, gutter_bounds, text_bounds, &layout, cx); self.paint_mouse_listeners(bounds, gutter_bounds, text_bounds, &layout, cx);
if !layout.blocks.is_empty() { if !layout.blocks.is_empty() {
cx.with_element_id(Some("editor_blocks"), |cx| { cx.with_element_id(Some("editor_blocks"), |_, cx| {
self.paint_blocks(bounds, &mut layout, cx); self.paint_blocks(bounds, &mut layout, cx);
}); });
} }

View file

@ -17,10 +17,11 @@ use time::UtcOffset;
use crate::{ use crate::{
current_platform, image_cache::ImageCache, init_app_menus, Action, ActionRegistry, Any, current_platform, image_cache::ImageCache, init_app_menus, Action, ActionRegistry, Any,
AnyView, AnyWindowHandle, AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context, AnyView, AnyWindowHandle, AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context,
DispatchPhase, DisplayId, Entity, EventEmitter, ForegroundExecutor, KeyBinding, Keymap, DispatchPhase, DisplayId, Entity, EventEmitter, ForegroundExecutor, GlobalElementId,
Keystroke, LayoutId, Menu, PathPromptOptions, Pixels, Platform, PlatformDisplay, Point, Render, KeyBinding, Keymap, Keystroke, LayoutId, Menu, MouseDownEvent, PathPromptOptions, Pixels,
SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement, Platform, PlatformDisplay, Point, Render, SharedString, SubscriberSet, Subscription,
TextSystem, View, ViewContext, Window, WindowContext, WindowHandle, WindowId, SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem, View, ViewContext, Window,
WindowContext, WindowHandle, WindowId,
}; };
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use collections::{FxHashMap, FxHashSet, VecDeque}; use collections::{FxHashMap, FxHashSet, VecDeque};
@ -188,7 +189,7 @@ pub struct AppContext {
flushing_effects: bool, flushing_effects: bool,
pending_updates: usize, pending_updates: usize,
pub(crate) actions: Rc<ActionRegistry>, pub(crate) actions: Rc<ActionRegistry>,
pub(crate) active_drag: Option<AnyDrag>, pub(crate) mouse_state: MouseState,
pub(crate) active_tooltip: Option<AnyTooltip>, pub(crate) active_tooltip: Option<AnyTooltip>,
pub(crate) next_frame_callbacks: FxHashMap<DisplayId, Vec<FrameCallback>>, pub(crate) next_frame_callbacks: FxHashMap<DisplayId, Vec<FrameCallback>>,
pub(crate) frame_consumers: FxHashMap<DisplayId, Task<()>>, pub(crate) frame_consumers: FxHashMap<DisplayId, Task<()>>,
@ -250,7 +251,7 @@ impl AppContext {
actions: Rc::new(ActionRegistry::default()), actions: Rc::new(ActionRegistry::default()),
flushing_effects: false, flushing_effects: false,
pending_updates: 0, pending_updates: 0,
active_drag: None, mouse_state: MouseState::None,
active_tooltip: None, active_tooltip: None,
next_frame_callbacks: FxHashMap::default(), next_frame_callbacks: FxHashMap::default(),
frame_consumers: FxHashMap::default(), frame_consumers: FxHashMap::default(),
@ -1089,13 +1090,24 @@ impl AppContext {
} }
pub fn has_active_drag(&self) -> bool { pub fn has_active_drag(&self) -> bool {
self.active_drag.is_some() self.mouse_state.is_dragging()
} }
pub fn active_drag<T: 'static>(&self) -> Option<&T> { pub fn active_drag<T: 'static>(&self) -> Option<&T> {
self.active_drag if let MouseState::Dragging(drag) = &self.mouse_state {
.as_ref() drag.value.downcast_ref()
.and_then(|drag| drag.value.downcast_ref()) } else {
None
}
}
pub fn element_clicked(&self, element_id: &GlobalElementId) -> bool {
if let MouseState::Clicked { clicked_id, .. } = &self.mouse_state {
if clicked_id == element_id {
return true;
}
}
false
} }
} }
@ -1243,6 +1255,64 @@ impl<G: 'static> DerefMut for GlobalLease<G> {
} }
} }
#[derive(Default)]
pub enum MouseState {
#[default]
None,
Clicked {
clicked_id: GlobalElementId,
event: MouseDownEvent,
},
Dragging(AnyDrag),
}
impl MouseState {
pub fn as_clicked(&self, element_id: &GlobalElementId) -> Option<&MouseDownEvent> {
if let MouseState::Clicked {
clicked_id: clicked_element_id,
event,
} = self
{
if clicked_element_id == element_id {
Some(event)
} else {
None
}
} else {
None
}
}
pub fn take_click(&mut self, element_id: &GlobalElementId) -> Option<MouseDownEvent> {
match mem::take(self) {
MouseState::None | MouseState::Dragging(_) => None,
MouseState::Clicked { clicked_id, event } => {
if &clicked_id == element_id {
Some(event)
} else {
*self = MouseState::Clicked { clicked_id, event };
None
}
}
}
}
pub fn is_dragging(&self) -> bool {
matches!(self, Self::Dragging(_))
}
pub fn take_drag(&mut self) -> Option<AnyDrag> {
match mem::take(self) {
MouseState::None => None,
state @ MouseState::Clicked { .. } => {
*self = state;
None
}
MouseState::Dragging(drag) => Some(drag),
}
}
}
/// Contains state associated with an active drag operation, started by dragging an element /// Contains state associated with an active drag operation, started by dragging an element
/// within the window or by dragging into the app from the underlying platform. /// within the window or by dragging into the app from the underlying platform.
pub struct AnyDrag { pub struct AnyDrag {

View file

@ -2,8 +2,8 @@ use crate::{
point, px, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, BorrowAppContext, point, px, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, BorrowAppContext,
BorrowWindow, Bounds, ClickEvent, DispatchPhase, Element, ElementId, FocusHandle, IntoElement, BorrowWindow, Bounds, ClickEvent, DispatchPhase, Element, ElementId, FocusHandle, IntoElement,
KeyContext, KeyDownEvent, KeyUpEvent, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, KeyContext, KeyDownEvent, KeyUpEvent, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent,
MouseUpEvent, ParentElement, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, MouseState, MouseUpEvent, ParentElement, Pixels, Point, Render, ScrollWheelEvent, SharedString,
StackingOrder, Style, StyleRefinement, Styled, Task, View, Visibility, WindowContext, Size, StackingOrder, Style, StyleRefinement, Styled, Task, View, Visibility, WindowContext,
}; };
use collections::HashMap; use collections::HashMap;
@ -38,9 +38,7 @@ pub struct DragMoveEvent<T> {
impl<T: 'static> DragMoveEvent<T> { impl<T: 'static> DragMoveEvent<T> {
pub fn drag<'b>(&self, cx: &'b AppContext) -> &'b T { pub fn drag<'b>(&self, cx: &'b AppContext) -> &'b T {
cx.active_drag cx.active_drag()
.as_ref()
.and_then(|drag| drag.value.downcast_ref::<T>())
.expect("DragMoveEvent is only valid when the stored active drag is of the same type.") .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
} }
} }
@ -152,19 +150,17 @@ impl Interactivity {
self.mouse_move_listeners self.mouse_move_listeners
.push(Box::new(move |event, bounds, phase, cx| { .push(Box::new(move |event, bounds, phase, cx| {
if phase == DispatchPhase::Capture { if phase == DispatchPhase::Capture {
if cx if let MouseState::Dragging(drag) = &cx.mouse_state {
.active_drag if drag.value.as_ref().downcast_ref::<T>().is_some() {
.as_ref() (listener)(
.is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::<T>()) &DragMoveEvent {
{ event: event.clone(),
(listener)( bounds: bounds.bounds,
&DragMoveEvent { drag: PhantomData,
event: event.clone(), },
bounds: bounds.bounds, cx,
drag: PhantomData, );
}, }
cx,
);
} }
} }
})); }));
@ -561,21 +557,6 @@ pub trait StatefulInteractiveElement: InteractiveElement {
self self
} }
fn group_active(
mut self,
group_name: impl Into<SharedString>,
f: impl FnOnce(StyleRefinement) -> StyleRefinement,
) -> Self
where
Self: Sized,
{
self.interactivity().group_active_style = Some(GroupStyle {
group: group_name.into(),
style: Box::new(f(StyleRefinement::default())),
});
self
}
fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static) -> Self fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static) -> Self
where where
Self: Sized, Self: Sized,
@ -587,14 +568,14 @@ pub trait StatefulInteractiveElement: InteractiveElement {
fn on_drag<T, W>( fn on_drag<T, W>(
mut self, mut self,
value: T, value: T,
constructor: impl Fn(&T, &mut WindowContext) -> View<W> + 'static, listener: impl Fn(&T, &mut WindowContext) -> View<W> + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
T: 'static, T: 'static,
W: 'static + Render, W: 'static + Render,
{ {
self.interactivity().on_drag(value, constructor); self.interactivity().on_drag(value, listener);
self self
} }
@ -811,15 +792,6 @@ pub struct DivState {
interactive_state: InteractiveElementState, interactive_state: InteractiveElementState,
} }
impl DivState {
pub fn is_active(&self) -> bool {
self.interactive_state
.pending_mouse_down
.as_ref()
.map_or(false, |pending| pending.borrow().is_some())
}
}
pub struct Interactivity { pub struct Interactivity {
pub element_id: Option<ElementId>, pub element_id: Option<ElementId>,
pub key_context: Option<KeyContext>, pub key_context: Option<KeyContext>,
@ -833,7 +805,6 @@ pub struct Interactivity {
pub hover_style: Option<Box<StyleRefinement>>, pub hover_style: Option<Box<StyleRefinement>>,
pub group_hover_style: Option<GroupStyle>, pub group_hover_style: Option<GroupStyle>,
pub active_style: Option<Box<StyleRefinement>>, pub active_style: Option<Box<StyleRefinement>>,
pub group_active_style: Option<GroupStyle>,
pub drag_over_styles: Vec<(TypeId, StyleRefinement)>, pub drag_over_styles: Vec<(TypeId, StyleRefinement)>,
pub group_drag_over_styles: Vec<(TypeId, GroupStyle)>, pub group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
pub mouse_down_listeners: Vec<MouseDownListener>, pub mouse_down_listeners: Vec<MouseDownListener>,
@ -895,7 +866,7 @@ impl Interactivity {
element_state.scroll_offset = Some(scroll_handle.0.borrow().offset.clone()); element_state.scroll_offset = Some(scroll_handle.0.borrow().offset.clone());
} }
let style = self.compute_style(None, &mut element_state, cx); let style = self.compute_style(None, cx);
let layout_id = f(style, cx); let layout_id = f(style, cx);
(layout_id, element_state) (layout_id, element_state)
} }
@ -908,7 +879,7 @@ impl Interactivity {
cx: &mut WindowContext, cx: &mut WindowContext,
f: impl FnOnce(Style, Point<Pixels>, &mut WindowContext), f: impl FnOnce(Style, Point<Pixels>, &mut WindowContext),
) { ) {
let style = self.compute_style(Some(bounds), element_state, cx); let style = self.compute_style(Some(bounds), cx);
if style.visibility == Visibility::Hidden { if style.visibility == Visibility::Hidden {
return; return;
@ -1114,7 +1085,7 @@ impl Interactivity {
if self.hover_style.is_some() if self.hover_style.is_some()
|| self.base_style.mouse_cursor.is_some() || self.base_style.mouse_cursor.is_some()
|| cx.active_drag.is_some() && !self.drag_over_styles.is_empty() || cx.mouse_state.is_dragging() && !self.drag_over_styles.is_empty()
{ {
let bounds = bounds.intersect(&cx.content_mask().bounds); let bounds = bounds.intersect(&cx.content_mask().bounds);
let hovered = bounds.contains(&cx.mouse_position()); let hovered = bounds.contains(&cx.mouse_position());
@ -1135,18 +1106,14 @@ impl Interactivity {
cx.on_mouse_event({ cx.on_mouse_event({
let interactive_bounds = interactive_bounds.clone(); let interactive_bounds = interactive_bounds.clone();
move |event: &MouseUpEvent, phase, cx| { move |event: &MouseUpEvent, phase, cx| {
if let Some(drag) = &cx.active_drag { if let MouseState::Dragging(drag) = &cx.mouse_state {
if phase == DispatchPhase::Bubble if phase == DispatchPhase::Bubble
&& interactive_bounds.drag_target_contains(&event.position, cx) && interactive_bounds.drag_target_contains(&event.position, cx)
{ {
let drag_state_type = drag.value.as_ref().type_id(); let drag_state_type = drag.value.as_ref().type_id();
for (drop_state_type, listener) in &drop_listeners { for (drop_state_type, listener) in &drop_listeners {
if *drop_state_type == drag_state_type { if *drop_state_type == drag_state_type {
let drag = cx let drag = cx.mouse_state.take_drag().unwrap();
.active_drag
.take()
.expect("checked for type drag state type above");
listener(drag.value.as_ref(), cx); listener(drag.value.as_ref(), cx);
cx.notify(); cx.notify();
cx.stop_propagation(); cx.stop_propagation();
@ -1158,81 +1125,76 @@ impl Interactivity {
}); });
} }
if !click_listeners.is_empty() || drag_listener.is_some() { if self.element_id.is_some() {
let pending_mouse_down = element_state let global_id = cx.global_element_id().clone();
.pending_mouse_down
.get_or_insert_with(Default::default)
.clone();
let active_state = element_state if !click_listeners.is_empty()
.clicked_state || drag_listener.is_some()
.get_or_insert_with(Default::default) || self.active_style.is_some()
.clone(); {
cx.on_mouse_event({
cx.on_mouse_event({ let interactive_bounds = interactive_bounds.clone();
let interactive_bounds = interactive_bounds.clone(); let global_id = global_id.clone();
let pending_mouse_down = pending_mouse_down.clone(); move |event: &MouseDownEvent, phase, cx| {
move |event: &MouseDownEvent, phase, cx| { if phase == DispatchPhase::Bubble
if phase == DispatchPhase::Bubble && event.button == MouseButton::Left
&& event.button == MouseButton::Left && interactive_bounds.visibly_contains(&event.position, cx)
&& interactive_bounds.visibly_contains(&event.position, cx)
{
*pending_mouse_down.borrow_mut() = Some(event.clone());
cx.notify();
}
}
});
cx.on_mouse_event({
let pending_mouse_down = pending_mouse_down.clone();
move |event: &MouseMoveEvent, phase, cx| {
let mut pending_mouse_down = pending_mouse_down.borrow_mut();
if let Some(mouse_down) = pending_mouse_down.clone() {
if cx.active_drag.is_some() {
if phase == DispatchPhase::Capture {
cx.notify();
}
} else if phase == DispatchPhase::Bubble
&& (event.position - mouse_down.position).magnitude()
> DRAG_THRESHOLD
{ {
if let Some((drag_value, drag_listener)) = drag_listener.take() { dbg!("CLICK DOWN!");
*active_state.borrow_mut() = ElementClickedState::default(); cx.mouse_state = MouseState::Clicked {
let cursor_offset = event.position - bounds.origin; clicked_id: global_id.clone(),
let drag = (drag_listener)(drag_value.as_ref(), cx); event: event.clone(),
cx.active_drag = Some(AnyDrag { };
view: drag,
value: drag_value,
cursor_offset,
});
pending_mouse_down.take();
cx.notify();
cx.stop_propagation();
}
}
}
}
});
cx.on_mouse_event({
let interactive_bounds = interactive_bounds.clone();
let mut captured_mouse_down = None;
move |event: &MouseUpEvent, phase, cx| match phase {
// Clear the pending mouse down during the capture phase,
// so that it happens even if another event handler stops
// propagation.
DispatchPhase::Capture => {
let mut pending_mouse_down = pending_mouse_down.borrow_mut();
if pending_mouse_down.is_some() {
captured_mouse_down = pending_mouse_down.take();
cx.notify(); cx.notify();
} }
} }
// Fire click handlers during the bubble phase. });
DispatchPhase::Bubble => {
if let Some(mouse_down) = captured_mouse_down.take() { if drag_listener.is_some() {
if interactive_bounds.visibly_contains(&event.position, cx) { cx.on_mouse_event({
let global_id = global_id.clone();
move |event: &MouseMoveEvent, phase, cx| {
if phase.capture() {
if cx.mouse_state.is_dragging() {
cx.notify();
}
} else {
if cx.mouse_state.as_clicked(&global_id).map_or(
false,
|mouse_down| {
(event.position - mouse_down.position).magnitude()
> DRAG_THRESHOLD
},
) {
if let Some((drag_value, drag_listener)) =
drag_listener.take()
{
let cursor_offset = event.position - bounds.origin;
let drag = (drag_listener)(drag_value.as_ref(), cx);
cx.mouse_state = MouseState::Dragging(AnyDrag {
view: drag,
value: drag_value,
cursor_offset,
});
cx.notify();
cx.stop_propagation();
}
}
}
}
});
}
cx.on_mouse_event({
let interactive_bounds = interactive_bounds.clone();
let global_id = global_id.clone();
move |event: &MouseUpEvent, phase, cx| {
if phase.capture() {
if cx.mouse_state.take_click(&global_id).is_some() {
cx.notify();
}
} else if interactive_bounds.visibly_contains(&event.position, cx) {
if let Some(mouse_down) = cx.mouse_state.take_click(&global_id) {
let mouse_click = ClickEvent { let mouse_click = ClickEvent {
down: mouse_down, down: mouse_down,
up: event.clone(), up: event.clone(),
@ -1243,136 +1205,100 @@ impl Interactivity {
} }
} }
} }
} });
});
}
if let Some(hover_listener) = self.hover_listener.take() {
let was_hovered = element_state
.hover_state
.get_or_insert_with(Default::default)
.clone();
let has_mouse_down = element_state
.pending_mouse_down
.get_or_insert_with(Default::default)
.clone();
let interactive_bounds = interactive_bounds.clone();
cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
if phase != DispatchPhase::Bubble {
return;
}
let is_hovered = interactive_bounds.visibly_contains(&event.position, cx)
&& has_mouse_down.borrow().is_none();
let mut was_hovered = was_hovered.borrow_mut();
if is_hovered != was_hovered.clone() {
*was_hovered = is_hovered;
drop(was_hovered);
hover_listener(&is_hovered, cx);
}
});
}
if let Some(tooltip_builder) = self.tooltip_builder.take() {
let active_tooltip = element_state
.active_tooltip
.get_or_insert_with(Default::default)
.clone();
let pending_mouse_down = element_state
.pending_mouse_down
.get_or_insert_with(Default::default)
.clone();
let interactive_bounds = interactive_bounds.clone();
cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
let is_hovered = interactive_bounds.visibly_contains(&event.position, cx)
&& pending_mouse_down.borrow().is_none();
if !is_hovered {
active_tooltip.borrow_mut().take();
return;
}
if phase != DispatchPhase::Bubble {
return;
}
if active_tooltip.borrow().is_none() {
let task = cx.spawn({
let active_tooltip = active_tooltip.clone();
let tooltip_builder = tooltip_builder.clone();
move |mut cx| async move {
cx.background_executor().timer(TOOLTIP_DELAY).await;
cx.update(|_, cx| {
active_tooltip.borrow_mut().replace(ActiveTooltip {
tooltip: Some(AnyTooltip {
view: tooltip_builder(cx),
cursor_offset: cx.mouse_position(),
}),
_task: None,
});
cx.notify();
})
.ok();
}
});
active_tooltip.borrow_mut().replace(ActiveTooltip {
tooltip: None,
_task: Some(task),
});
}
});
let active_tooltip = element_state
.active_tooltip
.get_or_insert_with(Default::default)
.clone();
cx.on_mouse_event(move |_: &MouseDownEvent, _, _| {
active_tooltip.borrow_mut().take();
});
if let Some(active_tooltip) = element_state
.active_tooltip
.get_or_insert_with(Default::default)
.borrow()
.as_ref()
{
if active_tooltip.tooltip.is_some() {
cx.active_tooltip = active_tooltip.tooltip.clone()
}
} }
}
let active_state = element_state if let Some(hover_listener) = self.hover_listener.take() {
.clicked_state let was_hovered = element_state
.get_or_insert_with(Default::default) .hover_state
.clone(); .get_or_insert_with(Default::default)
if active_state.borrow().is_clicked() { .clone();
cx.on_mouse_event(move |_: &MouseUpEvent, phase, cx| { let interactive_bounds = interactive_bounds.clone();
if phase == DispatchPhase::Capture { let global_element_id = global_id.clone();
*active_state.borrow_mut() = ElementClickedState::default();
cx.notify(); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
} if phase != DispatchPhase::Bubble {
}); return;
} else { }
let active_group_bounds = self let is_hovered = interactive_bounds.visibly_contains(&event.position, cx)
.group_active_style && !cx.element_clicked(&global_element_id);
.as_ref() let mut was_hovered = was_hovered.borrow_mut();
.and_then(|group_active| GroupBounds::get(&group_active.group, cx));
let interactive_bounds = interactive_bounds.clone(); if is_hovered != was_hovered.clone() {
cx.on_mouse_event(move |down: &MouseDownEvent, phase, cx| { *was_hovered = is_hovered;
if phase == DispatchPhase::Bubble && !cx.default_prevented() { drop(was_hovered);
let group = active_group_bounds
.map_or(false, |bounds| bounds.contains(&down.position)); hover_listener(&is_hovered, cx);
let element = interactive_bounds.visibly_contains(&down.position, cx); }
if group || element { });
*active_state.borrow_mut() = ElementClickedState { group, element }; }
cx.notify();
if let Some(tooltip_builder) = self.tooltip_builder.take() {
let active_tooltip = element_state
.active_tooltip
.get_or_insert_with(Default::default)
.clone();
let global_element_id = global_id.clone();
let interactive_bounds = interactive_bounds.clone();
cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
let is_hovered = interactive_bounds.visibly_contains(&event.position, cx)
&& !cx.element_clicked(&global_element_id);
if !is_hovered {
active_tooltip.borrow_mut().take();
return;
}
if phase != DispatchPhase::Bubble {
return;
}
if active_tooltip.borrow().is_none() {
let task = cx.spawn({
let active_tooltip = active_tooltip.clone();
let tooltip_builder = tooltip_builder.clone();
move |mut cx| async move {
cx.background_executor().timer(TOOLTIP_DELAY).await;
cx.update(|_, cx| {
active_tooltip.borrow_mut().replace(ActiveTooltip {
tooltip: Some(AnyTooltip {
view: tooltip_builder(cx),
cursor_offset: cx.mouse_position(),
}),
_task: None,
});
cx.notify();
})
.ok();
}
});
active_tooltip.borrow_mut().replace(ActiveTooltip {
tooltip: None,
_task: Some(task),
});
}
});
let active_tooltip = element_state
.active_tooltip
.get_or_insert_with(Default::default)
.clone();
cx.on_mouse_event(move |_: &MouseDownEvent, _, _| {
active_tooltip.borrow_mut().take();
});
if let Some(active_tooltip) = element_state
.active_tooltip
.get_or_insert_with(Default::default)
.borrow()
.as_ref()
{
if active_tooltip.tooltip.is_some() {
cx.active_tooltip = active_tooltip.tooltip.clone()
} }
} }
}); }
} }
let overflow = style.overflow; let overflow = style.overflow;
@ -1457,12 +1383,7 @@ impl Interactivity {
}); });
} }
pub fn compute_style( pub fn compute_style(&self, bounds: Option<Bounds<Pixels>>, cx: &mut WindowContext) -> Style {
&self,
bounds: Option<Bounds<Pixels>>,
element_state: &mut InteractiveElementState,
cx: &mut WindowContext,
) -> Style {
let mut style = Style::default(); let mut style = Style::default();
style.refine(&self.base_style); style.refine(&self.base_style);
@ -1502,7 +1423,7 @@ impl Interactivity {
} }
} }
if let Some(drag) = cx.active_drag.take() { if let Some(drag) = cx.mouse_state.take_drag() {
for (state_type, group_drag_style) in &self.group_drag_over_styles { for (state_type, group_drag_style) in &self.group_drag_over_styles {
if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) { if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
if *state_type == drag.value.as_ref().type_id() if *state_type == drag.value.as_ref().type_id()
@ -1527,23 +1448,15 @@ impl Interactivity {
} }
} }
cx.active_drag = Some(drag); cx.mouse_state = MouseState::Dragging(drag);
} }
} }
let clicked_state = element_state if self.element_id.is_some() {
.clicked_state if let Some(active_style) = self.active_style.as_ref() {
.get_or_insert_with(Default::default) if cx.element_clicked(cx.global_element_id()) {
.borrow(); style.refine(active_style)
if clicked_state.group { }
if let Some(group) = self.group_active_style.as_ref() {
style.refine(&group.style)
}
}
if let Some(active_style) = self.active_style.as_ref() {
if clicked_state.element {
style.refine(active_style)
} }
} }
}); });
@ -1568,7 +1481,6 @@ impl Default for Interactivity {
hover_style: None, hover_style: None,
group_hover_style: None, group_hover_style: None,
active_style: None, active_style: None,
group_active_style: None,
drag_over_styles: Vec::new(), drag_over_styles: Vec::new(),
group_drag_over_styles: Vec::new(), group_drag_over_styles: Vec::new(),
mouse_down_listeners: Vec::new(), mouse_down_listeners: Vec::new(),
@ -1593,9 +1505,7 @@ impl Default for Interactivity {
#[derive(Default)] #[derive(Default)]
pub struct InteractiveElementState { pub struct InteractiveElementState {
pub focus_handle: Option<FocusHandle>, pub focus_handle: Option<FocusHandle>,
pub clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
pub hover_state: Option<Rc<RefCell<bool>>>, pub hover_state: Option<Rc<RefCell<bool>>>,
pub pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
pub scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>, pub scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
pub active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>, pub active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
} }
@ -1605,19 +1515,6 @@ pub struct ActiveTooltip {
_task: Option<Task<()>>, _task: Option<Task<()>>,
} }
/// Whether or not the element or a group that contains it is clicked by the mouse.
#[derive(Copy, Clone, Default, Eq, PartialEq)]
pub struct ElementClickedState {
pub group: bool,
pub element: bool,
}
impl ElementClickedState {
fn is_clicked(&self) -> bool {
self.group || self.element
}
}
#[derive(Default)] #[derive(Default)]
pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>); pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);

View file

@ -160,9 +160,7 @@ impl Element for UniformList {
element_state: &mut Self::State, element_state: &mut Self::State,
cx: &mut WindowContext, cx: &mut WindowContext,
) { ) {
let style = let style = self.interactivity.compute_style(Some(bounds), cx);
self.interactivity
.compute_style(Some(bounds), &mut element_state.interactive, cx);
let border = style.border_widths.to_pixels(cx.rem_size()); let border = style.border_widths.to_pixels(cx.rem_size());
let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size()); let padding = style.padding.to_pixels(bounds.size.into(), cx.rem_size());

View file

@ -6,12 +6,12 @@ use crate::{
DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent, Flatten, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent, Flatten,
FontId, GlobalElementId, GlyphId, Hsla, ImageData, InputEvent, IsZero, KeyBinding, KeyContext, FontId, GlobalElementId, GlyphId, Hsla, ImageData, InputEvent, IsZero, KeyBinding, KeyContext,
KeyDownEvent, KeystrokeEvent, LayoutId, Model, ModelContext, Modifiers, MonochromeSprite, KeyDownEvent, KeystrokeEvent, LayoutId, Model, ModelContext, Modifiers, MonochromeSprite,
MouseButton, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, MouseButton, MouseMoveEvent, MouseState, MouseUpEvent, Path, Pixels, PlatformAtlas,
PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, PromptLevel, Quad, Render, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, PromptLevel,
RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels, Scene, SceneBuilder, Quad, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels, Scene,
Shadow, SharedString, Size, Style, SubscriberSet, Subscription, Surface, TaffyLayoutEngine, SceneBuilder, Shadow, SharedString, Size, Style, SubscriberSet, Subscription, Surface,
Task, Underline, UnderlineStyle, View, VisualContext, WeakView, WindowBounds, WindowOptions, TaffyLayoutEngine, Task, Underline, UnderlineStyle, View, VisualContext, WeakView,
SUBPIXEL_VARIANTS, WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
}; };
use anyhow::{anyhow, Context as _, Result}; use anyhow::{anyhow, Context as _, Result};
use collections::FxHashMap; use collections::FxHashMap;
@ -1324,13 +1324,13 @@ impl<'a> WindowContext<'a> {
}) })
}); });
if let Some(active_drag) = self.app.active_drag.take() { if let Some(active_drag) = self.app.mouse_state.take_drag() {
self.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| { self.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
let offset = cx.mouse_position() - active_drag.cursor_offset; let offset = cx.mouse_position() - active_drag.cursor_offset;
let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent); let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
active_drag.view.draw(offset, available_space, cx); active_drag.view.draw(offset, available_space, cx);
}); });
self.active_drag = Some(active_drag); self.app.mouse_state = MouseState::Dragging(active_drag);
} else if let Some(active_tooltip) = self.app.active_tooltip.take() { } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
self.with_z_index(1, |cx| { self.with_z_index(1, |cx| {
let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent); let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
@ -1435,8 +1435,8 @@ impl<'a> WindowContext<'a> {
InputEvent::FileDrop(file_drop) => match file_drop { InputEvent::FileDrop(file_drop) => match file_drop {
FileDropEvent::Entered { position, files } => { FileDropEvent::Entered { position, files } => {
self.window.mouse_position = position; self.window.mouse_position = position;
if self.active_drag.is_none() { if !self.mouse_state.is_dragging() {
self.active_drag = Some(AnyDrag { self.mouse_state = MouseState::Dragging(AnyDrag {
value: Box::new(files.clone()), value: Box::new(files.clone()),
view: self.build_view(|_| files).into(), view: self.build_view(|_| files).into(),
cursor_offset: position, cursor_offset: position,
@ -1515,7 +1515,7 @@ impl<'a> WindowContext<'a> {
} }
if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() { if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() {
self.active_drag = None; self.mouse_state = MouseState::None;
} }
self.window self.window
@ -1799,6 +1799,12 @@ impl<'a> WindowContext<'a> {
.platform_window .platform_window
.on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true))) .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
} }
/// Return the global id of the current identified element. This may not be the current element
/// if it is not identified.
pub(crate) fn global_element_id(&self) -> &GlobalElementId {
&self.window.element_id_stack
}
} }
impl Context for WindowContext<'_> { impl Context for WindowContext<'_> {
@ -1999,17 +2005,18 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
fn with_element_id<R>( fn with_element_id<R>(
&mut self, &mut self,
id: Option<impl Into<ElementId>>, id: Option<impl Into<ElementId>>,
f: impl FnOnce(&mut Self) -> R, f: impl FnOnce(Option<GlobalElementId>, &mut Self) -> R,
) -> R { ) -> R {
if let Some(id) = id.map(Into::into) { if let Some(id) = id.map(Into::into) {
let window = self.window_mut(); let window = self.window_mut();
window.element_id_stack.push(id.into()); window.element_id_stack.push(id.into());
let result = f(self); let global_id = window.element_id_stack.clone();
let result = f(Some(global_id), self);
let window: &mut Window = self.borrow_mut(); let window: &mut Window = self.borrow_mut();
window.element_id_stack.pop(); window.element_id_stack.pop();
result result
} else { } else {
f(self) f(None, self)
} }
} }
@ -2099,7 +2106,7 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
where where
S: 'static, S: 'static,
{ {
self.with_element_id(Some(id), |cx| { self.with_element_id(Some(id), |_, cx| {
let global_id = cx.window().element_id_stack.clone(); let global_id = cx.window().element_id_stack.clone();
if let Some(any) = cx if let Some(any) = cx