Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

project_panel: Fix dragged folders remaining highlighted even after the drag has ended (#64038)

tidely1a84d5d92bd7
diff --git a/crates/gpui/src/elements/div.rs b/crates/gpui/src/elements/div.rs
index f9208d04ad0..72430b4546f 100644
--- a/crates/gpui/src/elements/div.rs
+++ b/crates/gpui/src/elements/div.rs
@@ -18,13 +18,13 @@
use crate::{
Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent, DispatchPhase,
Display, Element, ElementId, Entity, EntityId, ExternalDragPayload, ExternalDragPayloadSource,
- FocusHandle, Global, GlobalElementId, Hitbox, HitboxBehavior, HitboxId, InspectorElementId,
- IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, KeyboardButton, KeyboardClickEvent,
- LayoutId, ModifiersChangedEvent, MouseButton, MouseClickEvent, MouseDownEvent, MouseExitEvent,
- MouseMoveEvent, MousePressureEvent, MouseUpEvent, OngoingScroll, Overflow, ParentElement,
- PinchEvent, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, Style,
- StyleRefinement, Styled, Task, TooltipId, Visibility, Window, WindowControlArea, point, px,
- size,
+ FileDropEvent, FocusHandle, Global, GlobalElementId, Hitbox, HitboxBehavior, HitboxId,
+ InspectorElementId, IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, KeyboardButton,
+ KeyboardClickEvent, LayoutId, ModifiersChangedEvent, MouseButton, MouseClickEvent,
+ MouseDownEvent, MouseExitEvent, MouseMoveEvent, MousePressureEvent, MouseUpEvent,
+ OngoingScroll, Overflow, ParentElement, PinchEvent, Pixels, Point, Render, ScrollWheelEvent,
+ SharedString, Size, Style, StyleRefinement, Styled, Task, TooltipId, Visibility, Window,
+ WindowControlArea, point, px, size,
};
use collections::HashMap;
use gpui_util::ResultExt;
@@ -328,6 +328,28 @@ impl Interactivity {
}));
}
+ /// Bind the given callback to [`FileDropEvent::Exited`] when a platform file drag
+ /// leaves this element's window while the element is hovered.
+ ///
+ /// This is a window-local exit event, not notification that the platform drag session ended.
+ /// The imperative API equivalent to [`InteractiveElement::on_file_drop_exit`].
+ ///
+ /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
+ pub fn on_file_drop_exit(
+ &mut self,
+ listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
+ ) {
+ self.file_drop_exit_listeners
+ .push(Box::new(move |event, phase, hitbox, window, cx| {
+ if phase == DispatchPhase::Bubble
+ && matches!(event, FileDropEvent::Exited)
+ && hitbox.id.is_hovered_ignoring_last_input(window)
+ {
+ (listener)(event, window, cx);
+ }
+ }));
+ }
+
/// Bind the given callback to the mouse drag event of the given type. Note that this
/// will be called for all move events, inside or outside of this element, as long as the
/// drag was started with this element under the mouse. Useful for implementing draggable
@@ -998,6 +1020,21 @@ pub trait InteractiveElement: Sized {
self
}
+ /// Bind the given callback to [`FileDropEvent::Exited`] when a platform file drag
+ /// leaves this element's window while the element is hovered.
+ ///
+ /// This is a window-local exit event, not notification that the platform drag session ended.
+ /// The fluent API equivalent to [`Interactivity::on_file_drop_exit`].
+ ///
+ /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
+ fn on_file_drop_exit(
+ mut self,
+ listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
+ ) -> Self {
+ self.interactivity().on_file_drop_exit(listener);
+ self
+ }
+
/// Bind the given callback to the mouse drag event of the given type. Note that this
/// will be called for all move events, inside or outside of this element, as long as the
/// drag was started with this element under the mouse. Useful for implementing draggable
@@ -1679,6 +1716,9 @@ pub(crate) type MouseMoveListener =
pub(crate) type MouseExitListener =
Box<dyn Fn(&MouseExitEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
+pub(crate) type FileDropExitListener =
+ Box<dyn Fn(&FileDropEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
+
pub(crate) type ScrollWheelListener =
Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
@@ -2119,6 +2159,7 @@ pub struct Interactivity {
pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
pub(crate) mouse_exit_listeners: Vec<MouseExitListener>,
+ pub(crate) file_drop_exit_listeners: Vec<FileDropExitListener>,
pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
pub(crate) pinch_listeners: Vec<PinchListener>,
pub(crate) key_down_listeners: Vec<KeyDownListener>,
@@ -2364,6 +2405,7 @@ impl Interactivity {
|| !self.mouse_down_listeners.is_empty()
|| !self.mouse_move_listeners.is_empty()
|| !self.mouse_exit_listeners.is_empty()
+ || !self.file_drop_exit_listeners.is_empty()
|| !self.click_listeners.is_empty()
|| !self.aux_click_listeners.is_empty()
|| !self.scroll_wheel_listeners.is_empty()
@@ -2766,6 +2808,13 @@ impl Interactivity {
})
}
+ for listener in self.file_drop_exit_listeners.drain(..) {
+ let hitbox = hitbox.clone();
+ window.on_mouse_event(move |event: &FileDropEvent, phase, window, cx| {
+ listener(event, phase, &hitbox, window, cx);
+ })
+ }
+
for listener in self.scroll_wheel_listeners.drain(..) {
let hitbox = hitbox.clone();
window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index 879b702e1e3..33c2c96458b 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -7439,10 +7439,11 @@ mod tests {
use crate::{
AnyWindowHandle, AppContext as _, Bounds, Context, DispatchPhase, DragMoveEvent, Empty,
ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle,
- InputEvent as _, InteractiveElement as _, IntoElement, LongPressEvent, MouseButton,
- MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Point, Render, RequestFrameOptions,
- StatefulInteractiveElement as _, Styled, TestAppContext, TouchDragEvent, TouchEvent,
- TouchId, TouchPhase, Window, WindowAppearance, WindowOptions, canvas, div, point, px, size,
+ InputEvent as _, InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke,
+ LongPressEvent, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels,
+ PlatformInput, Point, Render, RequestFrameOptions, StatefulInteractiveElement as _, Styled,
+ TestAppContext, TouchDragEvent, TouchEvent, TouchId, TouchPhase, Window, WindowAppearance,
+ WindowOptions, canvas, div, point, px, size,
};
#[gpui::test]
@@ -7897,6 +7898,17 @@ mod tests {
observed_drops: Rc<RefCell<Vec<PathBuf>>>,
}
+ struct FileDropExitView(Rc<Cell<usize>>);
+
+ impl Render for FileDropExitView {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ div().size_full().on_file_drop_exit({
+ let observed_file_drop_exit = self.0.clone();
+ move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
+ })
+ }
+ }
+
impl Render for FileDragView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
@@ -8014,10 +8026,24 @@ mod tests {
Some(&outside_position)
);
- let destination: AnyWindowHandle = cx.add_window(|_, _| EmptyView).into();
+ let first_destination_exit_count = Rc::new(Cell::new(0));
+ let first_destination: AnyWindowHandle = cx
+ .add_window({
+ let first_destination_exit_count = first_destination_exit_count.clone();
+ move |_, _| FileDropExitView(first_destination_exit_count)
+ })
+ .into();
+ let second_destination_exit_count = Rc::new(Cell::new(0));
+ let second_destination: AnyWindowHandle = cx
+ .add_window({
+ let second_destination_exit_count = second_destination_exit_count.clone();
+ move |_, _| FileDropExitView(second_destination_exit_count)
+ })
+ .into();
let reentry_position = point(px(30.), px(30.));
let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
- let update_result = cx.update_window(destination, |_, window, cx| {
+ let update_result = cx.update_window(first_destination, |_, window, cx| {
+ window.draw(cx).clear(cx);
window.dispatch_event(
FileDropEvent::Entered {
position: reentry_position,
@@ -8033,10 +8059,48 @@ mod tests {
);
window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
assert!(cx.active_drag.is_none());
+ assert_eq!(first_destination_exit_count.get(), 1);
+ assert_eq!(second_destination_exit_count.get(), 0);
+ });
+ assert!(
+ update_result.is_ok(),
+ "failed to handle drag in first destination window: {update_result:?}"
+ );
+
+ let update_result = cx.update_window(second_destination, |_, window, cx| {
+ window.draw(cx).clear(cx);
+ window.dispatch_event(
+ PlatformInput::KeyDown(KeyDownEvent {
+ keystroke: Keystroke::parse("down").expect("valid keystroke"),
+ is_held: false,
+ prefer_character_input: false,
+ }),
+ cx,
+ );
+ window.dispatch_event(
+ FileDropEvent::Entered {
+ position: reentry_position,
+ paths: external_paths(),
+ }
+ .to_platform_input(),
+ cx,
+ );
+ assert!(
+ cx.active_drag
+ .as_ref()
+ .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
+ );
+ assert_eq!(first_destination_exit_count.get(), 1);
+ assert_eq!(second_destination_exit_count.get(), 0);
+
+ window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
+ assert!(cx.active_drag.is_none());
+ assert_eq!(first_destination_exit_count.get(), 1);
+ assert_eq!(second_destination_exit_count.get(), 1);
});
assert!(
update_result.is_ok(),
- "failed to handle drag in destination window: {update_result:?}"
+ "failed to handle drag in second destination window: {update_result:?}"
);
let update_result = cx.update_window(successful.window, |_, window, cx| {
diff --git a/crates/project_panel/src/project_panel.rs b/crates/project_panel/src/project_panel.rs
index 26a263dcabe..c9ab9baeb9e 100644
--- a/crates/project_panel/src/project_panel.rs
+++ b/crates/project_panel/src/project_panel.rs
@@ -20,13 +20,13 @@ use git_ui_core::file_diff_view::FileDiffView;
use gpui::{
Action, AnyElement, App, AsyncWindowContext, Bounds, ClipboardEntry as GpuiClipboardEntry,
ClipboardItem, Context, CursorStyle, DismissEvent, Div, DragMoveEvent, Entity, EventEmitter,
- ExternalDragPayload, ExternalPaths, FileDragPaths, FocusHandle, Focusable, FontWeight, Hsla,
- InteractiveElement, KeyContext, ListHorizontalSizingBehavior, ListSizingBehavior, Modifiers,
- ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseExitEvent, ParentElement,
- PathPromptOptions, Pixels, Point, PromptLevel, Render, ScrollStrategy, Stateful, Styled,
- Subscription, Task, UniformListScrollHandle, WeakEntity, Window, actions, anchored, deferred,
- div, hsla, linear_color_stop, linear_gradient, point, px, size, transparent_white,
- uniform_list,
+ ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle, Focusable,
+ FontWeight, Hsla, InteractiveElement, KeyContext, ListHorizontalSizingBehavior,
+ ListSizingBehavior, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
+ MouseExitEvent, ParentElement, PathPromptOptions, Pixels, Point, PromptLevel, Render,
+ ScrollStrategy, Stateful, Styled, Subscription, Task, UniformListScrollHandle, WeakEntity,
+ Window, actions, anchored, deferred, div, hsla, linear_color_stop, linear_gradient, point, px,
+ size, transparent_white, uniform_list,
};
use language::DiagnosticSeverity;
use markdown_preview::markdown_preview_view::MarkdownPreviewView;
@@ -7125,6 +7125,10 @@ fn item_width_estimate(depth: usize, item_text_chars: usize, is_symlink: bool) -
impl Render for ProjectPanel {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ if !cx.has_active_drag() {
+ self.clear_drag_state(cx);
+ }
+
let has_worktree = !self.state.visible_entries.is_empty();
let project = self.project.read(cx);
let panel_settings = ProjectPanelSettings::get_global(cx);
@@ -7237,6 +7241,9 @@ impl Render for ProjectPanel {
cx.stop_active_drag(window);
this.clear_drag_state(cx);
}))
+ .on_file_drop_exit(cx.listener(|this, _: &FileDropEvent, _window, cx| {
+ this.clear_drag_state(cx);
+ }))
})
.size_full()
.relative()
diff --git a/crates/project_panel/src/project_panel_tests.rs b/crates/project_panel/src/project_panel_tests.rs
index 55fa3ea8672..e6bb8e78b95 100644
--- a/crates/project_panel/src/project_panel_tests.rs
+++ b/crates/project_panel/src/project_panel_tests.rs
@@ -6,7 +6,10 @@ use git::{
Oid,
repository::{InitialGraphCommitData, LogSource, RepoPath},
};
-use gpui::{Empty, Entity, TestAppContext, VisualTestContext};
+use gpui::{
+ AnyWindowHandle, Empty, Entity, InputEvent as _, KeyDownEvent, Keystroke, TestAppContext,
+ VisualTestContext,
+};
use language::{
Diagnostic, DiagnosticEntry, DiagnosticMessage, DiagnosticSourceKind, LanguageServerId,
PointUtf16, Unclipped,
@@ -12027,3 +12030,165 @@ async fn test_file_rows_reserve_the_chevron_slot(cx: &mut gpui::TestAppContext)
);
}
}
+
+#[gpui::test]
+async fn test_file_drag_state_clears_before_window_handoff(cx: &mut TestAppContext) {
+ init_test_with_editor(cx);
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/root"), json!({ "file.txt": "" }))
+ .await;
+ let first_project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
+ let second_project = Project::test(fs, [path!("/root").as_ref()], cx).await;
+ let (first_window, first_panel) = create_drag_test_panel(&first_project, cx);
+ let (second_window, second_panel) = create_drag_test_panel(&second_project, cx);
+
+ cx.update(|cx| {
+ cx.update_window(first_window, |_, window, cx| {
+ window.dispatch_event(
+ KeyDownEvent {
+ keystroke: Keystroke::parse("down").expect("valid keystroke"),
+ is_held: false,
+ prefer_character_input: false,
+ }
+ .to_platform_input(),
+ cx,
+ );
+ enter_file_drag_over_root(&first_panel, window, cx);
+ window.draw(cx).clear(cx);
+ window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
+ })
+ .expect("first window is open");
+ cx.update_window(second_window, |_, window, cx| {
+ enter_file_drag_over_root(&second_panel, window, cx);
+ })
+ .expect("second window is open");
+
+ assert!(cx.has_active_drag());
+ assert_drag_state_cleared(first_panel.read(cx));
+ cx.update_window(first_window, |_, window, cx| {
+ window.draw(cx).clear(cx);
+ assert_drag_state_cleared(first_panel.read(cx));
+ })
+ .expect("first window is open");
+ assert!(second_panel.read(cx).drag_target_entry.is_some());
+ assert!(cx.has_active_drag());
+
+ cx.update_window(second_window, |_, window, cx| {
+ window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
+ assert_drag_state_cleared(second_panel.read(cx));
+ })
+ .expect("second window is open");
+ assert!(!cx.has_active_drag());
+ });
+}
+
+#[gpui::test]
+async fn test_file_drag_state_clears_on_render_after_drag_stops(cx: &mut TestAppContext) {
+ init_test_with_editor(cx);
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(path!("/root"), json!({ "file.txt": "" }))
+ .await;
+ let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
+ let (window, panel) = create_drag_test_panel(&project, cx);
+
+ cx.update_window(window, |_, window, cx| {
+ enter_file_drag_over_root(&panel, window, cx);
+ window.draw(cx).clear(cx);
+ assert!(cx.stop_active_drag(window));
+ assert!(panel.read(cx).drag_target_entry.is_some());
+
+ window.draw(cx).clear(cx);
+ assert_drag_state_cleared(panel.read(cx));
+ })
+ .expect("window is open");
+}
+
+fn create_drag_test_panel(
+ project: &Entity<Project>,
+ cx: &mut TestAppContext,
+) -> (AnyWindowHandle, Entity<ProjectPanel>) {
+ let window = cx.open_window(size(px(800.), px(600.)), |window, cx| {
+ MultiWorkspace::test_new(project.clone(), window, cx)
+ });
+ let workspace = window
+ .read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone())
+ .expect("window is open");
+ let window = AnyWindowHandle::from(window);
+ let panel = cx
+ .update_window(window, |_, window, cx| {
+ workspace.update(cx, |workspace, cx| {
+ let panel = ProjectPanel::new(workspace, window, cx);
+ workspace.add_panel(panel.clone(), window, cx);
+ workspace.open_panel::<ProjectPanel>(window, cx);
+ panel
+ })
+ })
+ .expect("window is open");
+ cx.run_until_parked();
+ cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
+ .expect("window is open");
+ (window, panel)
+}
+
+fn enter_file_drag_over_root(panel: &Entity<ProjectPanel>, window: &mut Window, cx: &mut App) {
+ let (position, root_entry_id) = {
+ let panel = panel.read(cx);
+ let scroll = panel.scroll_handle.0.borrow();
+ let bounds = scroll.base_handle.bounds();
+ let item_size = scroll
+ .last_item_size
+ .expect("project entries were rendered");
+ let item_count = panel
+ .state
+ .visible_entries
+ .iter()
+ .map(|worktree| worktree.entries.len())
+ .sum::<usize>();
+ assert_eq!(item_count, 2);
+ let item_height = item_size.contents.height / item_count as f32;
+ let position = bounds.origin + point(bounds.size.width / 2., item_height / 2.);
+ let worktree = panel
+ .project
+ .read(cx)
+ .visible_worktrees(cx)
+ .next()
+ .expect("project has a worktree")
+ .read(cx);
+ let root_entry_id = worktree.root_entry().expect("worktree has a root").id;
+ (position, root_entry_id)
+ };
+ window.dispatch_event(
+ FileDropEvent::Entered {
+ position,
+ paths: ExternalPaths(
+ [PathBuf::from(path!("/outside/file.txt"))]
+ .into_iter()
+ .collect(),
+ ),
+ }
+ .to_platform_input(),
+ cx,
+ );
+ let panel = panel.read(cx);
+ let target_entry_ids = panel
+ .drag_target_entry
+ .as_ref()
+ .and_then(|target| match target {
+ DragTarget::Entry {
+ entry_id,
+ highlight_entry_id,
+ } => Some((*entry_id, *highlight_entry_id)),
+ DragTarget::Background => None,
+ });
+ assert_eq!(target_entry_ids, Some((root_entry_id, root_entry_id)));
+ assert_eq!(panel.previous_drag_position, Some(position));
+ assert!(panel.hover_scroll_task.is_some());
+}
+
+fn assert_drag_state_cleared(panel: &ProjectPanel) {
+ assert!(panel.drag_target_entry.is_none());
+ assert!(panel.folded_directory_drag_target.is_none());
+ assert!(panel.hover_scroll_task.is_none());
+ assert!(panel.hover_expand_task.is_none());
+ assert_eq!(panel.previous_drag_position, None);
+}