This commit is contained in:
Nathan Sobo 2023-12-19 20:21:59 -07:00
parent 66f833eccf
commit e931a1d295
5 changed files with 237 additions and 284 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,11 +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, ElementId, 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};
@ -1100,6 +1100,15 @@ impl AppContext {
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
}
}
impl Context for AppContext {
@ -1250,25 +1259,58 @@ impl<G: 'static> DerefMut for GlobalLease<G> {
pub enum MouseState {
#[default]
None,
Clicked(ElementId),
Clicked {
clicked_id: GlobalElementId,
event: MouseDownEvent,
},
Dragging(AnyDrag),
}
impl MouseState {
pub fn take_drag(&mut self) -> Option<AnyDrag> {
match mem::take(self) {
MouseState::None => None,
MouseState::Clicked(element_id) => {
*self = MouseState::Clicked(element_id);
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
}
MouseState::Dragging(drag) => Some(drag),
} 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

View file

@ -557,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,
@ -583,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
}
@ -807,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>,
@ -829,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>,
@ -891,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)
}
@ -904,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;
@ -1150,47 +1125,50 @@ 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();
let active_state = element_state
.clicked_state
.get_or_insert_with(Default::default)
.clone();
if self.element_id.is_some() {
let global_id = cx.global_element_id().clone();
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 pending_mouse_down = pending_mouse_down.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)
{
*pending_mouse_down.borrow_mut() = Some(event.clone());
dbg!("CLICK DOWN!");
cx.mouse_state = MouseState::Clicked {
clicked_id: global_id.clone(),
event: event.clone(),
};
cx.notify();
}
}
});
if drag_listener.is_some() {
cx.on_mouse_event({
let pending_mouse_down = pending_mouse_down.clone();
let global_id = global_id.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 phase.capture() {
if cx.mouse_state.is_dragging() {
if phase == DispatchPhase::Capture {
cx.notify();
}
} else if phase == DispatchPhase::Bubble
&& (event.position - mouse_down.position).magnitude()
} 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()
{
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.mouse_state = MouseState::Dragging(AnyDrag {
@ -1198,7 +1176,6 @@ impl Interactivity {
value: drag_value,
cursor_offset,
});
pending_mouse_down.take();
cx.notify();
cx.stop_propagation();
}
@ -1206,25 +1183,18 @@ impl Interactivity {
}
}
});
}
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();
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();
}
}
// 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) {
} 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(),
@ -1235,7 +1205,6 @@ impl Interactivity {
}
}
}
}
});
}
@ -1244,18 +1213,15 @@ impl Interactivity {
.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();
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)
&& has_mouse_down.borrow().is_none();
&& !cx.element_clicked(&global_element_id);
let mut was_hovered = was_hovered.borrow_mut();
if is_hovered != was_hovered.clone() {
@ -1272,15 +1238,12 @@ impl Interactivity {
.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 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)
&& pending_mouse_down.borrow().is_none();
&& !cx.element_clicked(&global_element_id);
if !is_hovered {
active_tooltip.borrow_mut().take();
return;
@ -1336,35 +1299,6 @@ impl Interactivity {
}
}
}
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();
}
}
});
}
let overflow = style.overflow;
@ -1449,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);
@ -1523,21 +1452,13 @@ impl Interactivity {
}
}
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 self.element_id.is_some() {
if let Some(active_style) = self.active_style.as_ref() {
if clicked_state.element {
if cx.element_clicked(cx.global_element_id()) {
style.refine(active_style)
}
}
}
});
style
@ -1560,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(),
@ -1585,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>>>>,
}
@ -1597,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

@ -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