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;
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;
for fold in snapshot.folds_in_range(layout.visible_anchor_range.clone()) {
let fold_range = fold.range.clone();
@ -948,7 +949,7 @@ impl EditorElement {
fold_bounds.size,
cx,
|fold_element_state, cx| {
if fold_element_state.is_active() {
if cx.element_clicked(&global_element_id) {
cx.theme().colors().ghost_element_active
} else if fold_bounds.contains(&cx.mouse_position()) {
cx.theme().colors().ghost_element_hover
@ -2016,7 +2017,7 @@ impl EditorElement {
.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(
start_row..end_row,
&snapshot,
@ -2101,7 +2102,7 @@ impl EditorElement {
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(
fold_statuses,
&style,
@ -2840,7 +2841,7 @@ impl Element for EditorElement {
self.paint_mouse_listeners(bounds, gutter_bounds, text_bounds, &layout, cx);
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);
});
}

View file

@ -17,10 +17,11 @@ use time::UtcOffset;
use crate::{
current_platform, image_cache::ImageCache, init_app_menus, Action, ActionRegistry, Any,
AnyView, AnyWindowHandle, AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context,
DispatchPhase, DisplayId, Entity, EventEmitter, ForegroundExecutor, KeyBinding, Keymap,
Keystroke, LayoutId, Menu, PathPromptOptions, Pixels, Platform, PlatformDisplay, Point, Render,
SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement,
TextSystem, View, ViewContext, Window, WindowContext, WindowHandle, WindowId,
DispatchPhase, DisplayId, Entity, EventEmitter, ForegroundExecutor, GlobalElementId,
KeyBinding, Keymap, Keystroke, LayoutId, Menu, MouseDownEvent, PathPromptOptions, Pixels,
Platform, PlatformDisplay, Point, Render, SharedString, SubscriberSet, Subscription,
SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem, View, ViewContext, Window,
WindowContext, WindowHandle, WindowId,
};
use anyhow::{anyhow, Result};
use collections::{FxHashMap, FxHashSet, VecDeque};
@ -188,7 +189,7 @@ pub struct AppContext {
flushing_effects: bool,
pending_updates: usize,
pub(crate) actions: Rc<ActionRegistry>,
pub(crate) active_drag: Option<AnyDrag>,
pub(crate) mouse_state: MouseState,
pub(crate) active_tooltip: Option<AnyTooltip>,
pub(crate) next_frame_callbacks: FxHashMap<DisplayId, Vec<FrameCallback>>,
pub(crate) frame_consumers: FxHashMap<DisplayId, Task<()>>,
@ -250,7 +251,7 @@ impl AppContext {
actions: Rc::new(ActionRegistry::default()),
flushing_effects: false,
pending_updates: 0,
active_drag: None,
mouse_state: MouseState::None,
active_tooltip: None,
next_frame_callbacks: FxHashMap::default(),
frame_consumers: FxHashMap::default(),
@ -1089,13 +1090,24 @@ impl AppContext {
}
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> {
self.active_drag
.as_ref()
.and_then(|drag| drag.value.downcast_ref())
if let MouseState::Dragging(drag) = &self.mouse_state {
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
/// within the window or by dragging into the app from the underlying platform.
pub struct AnyDrag {

View file

@ -2,8 +2,8 @@ use crate::{
point, px, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, BorrowAppContext,
BorrowWindow, Bounds, ClickEvent, DispatchPhase, Element, ElementId, FocusHandle, IntoElement,
KeyContext, KeyDownEvent, KeyUpEvent, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent,
MouseUpEvent, ParentElement, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size,
StackingOrder, Style, StyleRefinement, Styled, Task, View, Visibility, WindowContext,
MouseState, MouseUpEvent, ParentElement, Pixels, Point, Render, ScrollWheelEvent, SharedString,
Size, StackingOrder, Style, StyleRefinement, Styled, Task, View, Visibility, WindowContext,
};
use collections::HashMap;
@ -38,9 +38,7 @@ pub struct DragMoveEvent<T> {
impl<T: 'static> DragMoveEvent<T> {
pub fn drag<'b>(&self, cx: &'b AppContext) -> &'b T {
cx.active_drag
.as_ref()
.and_then(|drag| drag.value.downcast_ref::<T>())
cx.active_drag()
.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
.push(Box::new(move |event, bounds, phase, cx| {
if phase == DispatchPhase::Capture {
if cx
.active_drag
.as_ref()
.is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::<T>())
{
(listener)(
&DragMoveEvent {
event: event.clone(),
bounds: bounds.bounds,
drag: PhantomData,
},
cx,
);
if let MouseState::Dragging(drag) = &cx.mouse_state {
if drag.value.as_ref().downcast_ref::<T>().is_some() {
(listener)(
&DragMoveEvent {
event: event.clone(),
bounds: bounds.bounds,
drag: PhantomData,
},
cx,
);
}
}
}
}));
@ -561,21 +557,6 @@ pub trait StatefulInteractiveElement: InteractiveElement {
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
where
Self: Sized,
@ -587,14 +568,14 @@ pub trait StatefulInteractiveElement: InteractiveElement {
fn on_drag<T, W>(
mut self,
value: T,
constructor: impl Fn(&T, &mut WindowContext) -> View<W> + 'static,
listener: impl Fn(&T, &mut WindowContext) -> View<W> + 'static,
) -> Self
where
Self: Sized,
T: 'static,
W: 'static + Render,
{
self.interactivity().on_drag(value, constructor);
self.interactivity().on_drag(value, listener);
self
}
@ -811,15 +792,6 @@ pub struct DivState {
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 element_id: Option<ElementId>,
pub key_context: Option<KeyContext>,
@ -833,7 +805,6 @@ pub struct Interactivity {
pub hover_style: Option<Box<StyleRefinement>>,
pub group_hover_style: Option<GroupStyle>,
pub active_style: Option<Box<StyleRefinement>>,
pub group_active_style: Option<GroupStyle>,
pub drag_over_styles: Vec<(TypeId, StyleRefinement)>,
pub group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
pub mouse_down_listeners: Vec<MouseDownListener>,
@ -895,7 +866,7 @@ impl Interactivity {
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);
(layout_id, element_state)
}
@ -908,7 +879,7 @@ impl Interactivity {
cx: &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 {
return;
@ -1114,7 +1085,7 @@ impl Interactivity {
if self.hover_style.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 hovered = bounds.contains(&cx.mouse_position());
@ -1135,18 +1106,14 @@ impl Interactivity {
cx.on_mouse_event({
let interactive_bounds = interactive_bounds.clone();
move |event: &MouseUpEvent, phase, cx| {
if let Some(drag) = &cx.active_drag {
if let MouseState::Dragging(drag) = &cx.mouse_state {
if phase == DispatchPhase::Bubble
&& interactive_bounds.drag_target_contains(&event.position, cx)
{
let drag_state_type = drag.value.as_ref().type_id();
for (drop_state_type, listener) in &drop_listeners {
if *drop_state_type == drag_state_type {
let drag = cx
.active_drag
.take()
.expect("checked for type drag state type above");
let drag = cx.mouse_state.take_drag().unwrap();
listener(drag.value.as_ref(), cx);
cx.notify();
cx.stop_propagation();
@ -1158,81 +1125,76 @@ impl Interactivity {
});
}
if !click_listeners.is_empty() || drag_listener.is_some() {
let pending_mouse_down = element_state
.pending_mouse_down
.get_or_insert_with(Default::default)
.clone();
if self.element_id.is_some() {
let global_id = cx.global_element_id().clone();
let active_state = element_state
.clicked_state
.get_or_insert_with(Default::default)
.clone();
cx.on_mouse_event({
let interactive_bounds = interactive_bounds.clone();
let pending_mouse_down = pending_mouse_down.clone();
move |event: &MouseDownEvent, phase, cx| {
if phase == DispatchPhase::Bubble
&& event.button == MouseButton::Left
&& 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 !click_listeners.is_empty()
|| drag_listener.is_some()
|| self.active_style.is_some()
{
cx.on_mouse_event({
let interactive_bounds = interactive_bounds.clone();
let global_id = global_id.clone();
move |event: &MouseDownEvent, phase, cx| {
if phase == DispatchPhase::Bubble
&& event.button == MouseButton::Left
&& interactive_bounds.visibly_contains(&event.position, cx)
{
if let Some((drag_value, drag_listener)) = drag_listener.take() {
*active_state.borrow_mut() = ElementClickedState::default();
let cursor_offset = event.position - bounds.origin;
let drag = (drag_listener)(drag_value.as_ref(), cx);
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();
dbg!("CLICK DOWN!");
cx.mouse_state = MouseState::Clicked {
clicked_id: global_id.clone(),
event: event.clone(),
};
cx.notify();
}
}
// Fire click handlers during the bubble phase.
DispatchPhase::Bubble => {
if let Some(mouse_down) = captured_mouse_down.take() {
if interactive_bounds.visibly_contains(&event.position, cx) {
});
if drag_listener.is_some() {
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 {
down: mouse_down,
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
.clicked_state
.get_or_insert_with(Default::default)
.clone();
if active_state.borrow().is_clicked() {
cx.on_mouse_event(move |_: &MouseUpEvent, phase, cx| {
if phase == DispatchPhase::Capture {
*active_state.borrow_mut() = ElementClickedState::default();
cx.notify();
}
});
} else {
let active_group_bounds = self
.group_active_style
.as_ref()
.and_then(|group_active| GroupBounds::get(&group_active.group, cx));
let interactive_bounds = interactive_bounds.clone();
cx.on_mouse_event(move |down: &MouseDownEvent, phase, cx| {
if phase == DispatchPhase::Bubble && !cx.default_prevented() {
let group = active_group_bounds
.map_or(false, |bounds| bounds.contains(&down.position));
let element = interactive_bounds.visibly_contains(&down.position, cx);
if group || element {
*active_state.borrow_mut() = ElementClickedState { group, element };
cx.notify();
if let Some(hover_listener) = self.hover_listener.take() {
let was_hovered = element_state
.hover_state
.get_or_insert_with(Default::default)
.clone();
let interactive_bounds = interactive_bounds.clone();
let global_element_id = global_id.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)
&& !cx.element_clicked(&global_element_id);
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 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;
@ -1457,12 +1383,7 @@ impl Interactivity {
});
}
pub fn compute_style(
&self,
bounds: Option<Bounds<Pixels>>,
element_state: &mut InteractiveElementState,
cx: &mut WindowContext,
) -> Style {
pub fn compute_style(&self, bounds: Option<Bounds<Pixels>>, cx: &mut WindowContext) -> Style {
let mut style = Style::default();
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 {
if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
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
.clicked_state
.get_or_insert_with(Default::default)
.borrow();
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)
if self.element_id.is_some() {
if let Some(active_style) = self.active_style.as_ref() {
if cx.element_clicked(cx.global_element_id()) {
style.refine(active_style)
}
}
}
});
@ -1568,7 +1481,6 @@ impl Default for Interactivity {
hover_style: None,
group_hover_style: None,
active_style: None,
group_active_style: None,
drag_over_styles: Vec::new(),
group_drag_over_styles: Vec::new(),
mouse_down_listeners: Vec::new(),
@ -1593,9 +1505,7 @@ impl Default for Interactivity {
#[derive(Default)]
pub struct InteractiveElementState {
pub focus_handle: Option<FocusHandle>,
pub clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
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 active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
}
@ -1605,19 +1515,6 @@ pub struct ActiveTooltip {
_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)]
pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);

View file

@ -160,9 +160,7 @@ impl Element for UniformList {
element_state: &mut Self::State,
cx: &mut WindowContext,
) {
let style =
self.interactivity
.compute_style(Some(bounds), &mut element_state.interactive, cx);
let style = self.interactivity.compute_style(Some(bounds), cx);
let border = style.border_widths.to_pixels(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,
FontId, GlobalElementId, GlyphId, Hsla, ImageData, InputEvent, IsZero, KeyBinding, KeyContext,
KeyDownEvent, KeystrokeEvent, LayoutId, Model, ModelContext, Modifiers, MonochromeSprite,
MouseButton, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay,
PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, PromptLevel, Quad, Render,
RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels, Scene, SceneBuilder,
Shadow, SharedString, Size, Style, SubscriberSet, Subscription, Surface, TaffyLayoutEngine,
Task, Underline, UnderlineStyle, View, VisualContext, WeakView, WindowBounds, WindowOptions,
SUBPIXEL_VARIANTS,
MouseButton, MouseMoveEvent, MouseState, MouseUpEvent, Path, Pixels, PlatformAtlas,
PlatformDisplay, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, PromptLevel,
Quad, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels, Scene,
SceneBuilder, Shadow, SharedString, Size, Style, SubscriberSet, Subscription, Surface,
TaffyLayoutEngine, Task, Underline, UnderlineStyle, View, VisualContext, WeakView,
WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
};
use anyhow::{anyhow, Context as _, Result};
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| {
let offset = cx.mouse_position() - active_drag.cursor_offset;
let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
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() {
self.with_z_index(1, |cx| {
let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
@ -1435,8 +1435,8 @@ impl<'a> WindowContext<'a> {
InputEvent::FileDrop(file_drop) => match file_drop {
FileDropEvent::Entered { position, files } => {
self.window.mouse_position = position;
if self.active_drag.is_none() {
self.active_drag = Some(AnyDrag {
if !self.mouse_state.is_dragging() {
self.mouse_state = MouseState::Dragging(AnyDrag {
value: Box::new(files.clone()),
view: self.build_view(|_| files).into(),
cursor_offset: position,
@ -1515,7 +1515,7 @@ impl<'a> WindowContext<'a> {
}
if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() {
self.active_drag = None;
self.mouse_state = MouseState::None;
}
self.window
@ -1799,6 +1799,12 @@ impl<'a> WindowContext<'a> {
.platform_window
.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<'_> {
@ -1999,17 +2005,18 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
fn with_element_id<R>(
&mut self,
id: Option<impl Into<ElementId>>,
f: impl FnOnce(&mut Self) -> R,
f: impl FnOnce(Option<GlobalElementId>, &mut Self) -> R,
) -> R {
if let Some(id) = id.map(Into::into) {
let window = self.window_mut();
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();
window.element_id_stack.pop();
result
} else {
f(self)
f(None, self)
}
}
@ -2099,7 +2106,7 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
where
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();
if let Some(any) = cx