//! Move blocks and sibling ranges using one editor-wide gutter handle. mod movement; use gpdoc::{ AnchoredElement, BlockDropTarget, BlockPreview, EditorView, ViewBehavior, ViewFrame, ViewPlugin, }; use gpdoc_plugin::core::{DocPos, Editor, Selection, Transaction}; use gpui::{ AnyElement, App, Bounds, Context, Entity, IntoElement, MouseButton, MouseMoveEvent, Pixels, Point, Refineable, Size, TextStyleRefinement, Window, div, point, prelude::*, px, size, }; #[cfg(target_family = "wasm")] use gpui_browser as gpui; pub use movement::{BlockDragLayout, BlockPlacement}; use std::{cell::Cell, ops::Range, rc::Rc}; /// Configure the native drag gesture for document blocks. pub fn drag_handle() -> DragHandle { DragHandle { size: size(px(20.), px(24.)), preview: Rc::new(|slot, _, _| { div() .opacity(DEFAULT_PREVIEW_OPACITY) .child(slot.content) .into() }), } } const DEFAULT_PREVIEW_OPACITY: f32 = 0.55; #[must_use] #[derive(Clone)] pub struct DragHandle { size: Size, preview: PreviewRenderer, } /// A grip in the editor gutter or its preview following the pointer. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DragHandlePart { Grip, Preview, } pub struct DragHandleSlot { pub editor: Entity, pub before: DocPos, pub part: DragHandlePart, } /// The block content carried by the handle during a drag. pub struct DragPreviewSlot { /// A full-opacity copy of the blocks at their original size. pub content: AnyElement, /// The document range captured when the drag began, in ascending order. pub range: Range, /// The number of sibling blocks moved together. A container counts as one. pub block_count: usize, } /// Where a custom preview appears while the pointer moves. pub struct DragPreviewPlacement { anchor: PreviewAnchor, element: AnyElement, } enum PreviewAnchor { Blocks, Handle, } impl DragPreviewPlacement { /// Align the element with the original top-left corner of the dragged range. pub fn over_blocks(element: impl IntoElement) -> Self { Self { anchor: PreviewAnchor::Blocks, element: element.into_any_element(), } } /// Align the element with the top-right corner of the grip being dragged. pub fn beside_handle(element: impl IntoElement) -> Self { Self { anchor: PreviewAnchor::Handle, element: element.into_any_element(), } } } impl From for DragPreviewPlacement { fn from(element: E) -> Self { Self::over_blocks(element) } } type PreviewRenderer = Rc DragPreviewPlacement>; type Renderer = Rc AnyElement>; /// Draw a six-dot grip in the gutter and in the drag preview. pub fn block_grip(_: DragHandleSlot, _: &mut Window, _: &mut App) -> gpui::Div { let dot = || div().size(px(3.)).rounded_full().bg(gpui::rgb(0x9b9a97)); div() .w(px(16.)) .h(px(24.)) .flex() .flex_col() .items_center() .justify_center() .gap(px(2.)) .children((0..3).map(|_| div().flex().gap(px(2.)).child(dot()).child(dot()))) } impl From for gpdoc::EditorPlugin { fn from(plugin: DragHandle) -> Self { plugin.with_view(block_grip).into() } } impl DragHandle { /// Width to reserve for an installed grip, or zero when the view has no drag handle. pub fn installed_gutter_width(view: &EditorView) -> Pixels { view.behavior::() .map_or(px(0.), |handle| handle.options.size.width) } /// Set the width of the document gutter and the grip hitbox (default 20px). pub fn gutter_width(mut self, width: Pixels) -> Self { self.size.width = width.max(px(0.)); self } /// Set the grip hitbox height and minimum top-level block height (default 24px). pub fn handle_height(mut self, height: Pixels) -> Self { self.size.height = height.max(px(0.)); self } /// Wrap or replace the dragged block content. The default copy has 55% opacity. /// Return an element to align it with the blocks, or choose a [DragPreviewPlacement]. pub fn with_preview>( mut self, render: impl Fn(DragPreviewSlot, &mut Window, &mut App) -> P + 'static, ) -> Self { self.preview = Rc::new(move |slot, window, cx| render(slot, window, cx).into()); self } /// Compose the grip in the gutter and the grip beside the dragged block content. pub fn with_view( self, render: impl Fn(DragHandleSlot, &mut Window, &mut App) -> E + 'static, ) -> ViewPlugin { let render: Renderer = Rc::new(move |slot, window, cx| render(slot, window, cx).into_any_element()); let size = self.size; ViewPlugin::new("dragHandle", move || GutterHandle { options: self.clone(), render: render.clone(), active: Cell::new(None), grab_offset: Cell::default(), }) .wrap_blocks(move |block, body, _, cx| { let supplies_gutters = block .view .read(cx) .editor() .config() .plugin_data::() .any(|(_, layout)| block.node.kind == layout.container_node); div() .when(!supplies_gutters, |el| el.pl(size.width)) .min_h(size.height) .child(body) }) .on_block_drop(move |view, drag, targets, cx| { move_blocks(view, drag, targets, size.width, cx) }) } } struct GutterHandle { options: DragHandle, render: Renderer, active: Cell>, grab_offset: Cell>, } #[derive(Clone, Copy)] struct ActiveGrip { root: DocPos, owner: DocPos, revision: u64, // Includes the space to cross from the block's left edge to the handle. approach: Bounds, } impl GutterHandle { fn target( &self, editor: &Editor, hit: Option, mouse: Point, active: Option, ) -> Option<(DocPos, DocPos)> { let doc = editor.document(); let active = active .filter(|grip| grip.revision == editor.revision() && grip.approach.contains(&mouse)); // A grip can extend below a short line into the next block's gutter. // Its visible hitbox still belongs to the block that placed it. let hit = match active { Some(grip) if mouse.x < grip.approach.left() + self.options.size.width => grip.owner, _ => hit?, }; let path = doc.resolve(hit).ok()?; let root = DocPos(path.before(1).ok()?); if let Some(grip) = active && (hit.0..hit.0 + doc.node_at(hit)?.size()).contains(&grip.owner.0) { return Some((grip.root, grip.owner)); } let owner = editor.config().drag_handle_owner(&path)?; let owner_path = doc.resolve(owner).ok()?; let gutter = (1..=owner_path.depth()) .rev() .find(|&depth| { editor .config() .plugin_data::() .any(|(_, layout)| owner_path.node(depth).kind == layout.gutter_node) }) .and_then(|depth| owner_path.before(depth).ok()) .map(DocPos) .unwrap_or(root); Some((gutter, owner)) } fn grip(&self, frame: &ViewFrame<'_>, mouse: Point, cx: &App) -> Option { let view = frame.view.read(cx); if view.is_composing() || cx.has_active_drag() || !frame.clip.contains(&mouse) { return None; } let active = self.active.get().and_then(|mut grip| { grip.approach = self.approach(frame, grip.root, grip.owner)?; Some(grip) }); let (root, owner) = self.target(view.editor(), frame.block_at(mouse), mouse, active)?; Some(ActiveGrip { root, owner, revision: view.editor().revision(), approach: self.approach(frame, root, owner)?, }) } fn approach( &self, frame: &ViewFrame<'_>, root: DocPos, owner: DocPos, ) -> Option> { let gutter = frame.block_bounds(root)?.left(); let block = frame.block_bounds(owner)?; let top = frame.block_content_top(owner)?; Some(Bounds::from_corners( point(gutter, top), point( block.left().max(gutter + self.options.size.width), top + self.options.size.height, ), )) } } impl ViewBehavior for GutterHandle { fn mouse_move( &self, view: &mut EditorView, event: &MouseMoveEvent, window: &mut Window, cx: &mut Context, ) -> bool { if event.pressed_button.is_none() && !view.is_composing() { let hit = view .child_bounds_at(event.position, window) .map(|(hit, _)| hit); let hovered = self .target(view.editor(), hit, event.position, self.active.get()) .map(|(_, owner)| owner); if hovered != self.active.get().map(|grip| grip.owner) { cx.notify(); } } false } fn render( self: Rc, frame: &ViewFrame<'_>, window: &mut Window, cx: &mut App, ) -> Option { let grip = self.grip(frame, window.mouse_position(), cx); self.active.set(grip); let grip = grip?; let view = frame.view.clone(); let drag = BlockDrag::new(&view, grip.owner, self.render.clone(), cx); let selection = drag.selection; let gesture = self.clone(); let text_style = window.text_style().subtract(&Default::default()); let handle = div() .id(("gpdoc-drag-handle", view.entity_id())) .debug_selector(|| "gpdoc-drag-handle".into()) .w(self.options.size.width) .h(self.options.size.height) .cursor_move() .child(drag.render_part(DragHandlePart::Grip, window, cx)) .on_drag(drag, move |drag, cursor_offset, _, cx| { let range = drag .selection .bounds(drag.editor.read(cx).editor().document()); let blocks = BlockPreview::new(&drag.editor, range, cx); cx.new(|_| DragPreview { drag: drag.clone(), blocks, render_blocks: gesture.options.preview.clone(), grip_bounds: Bounds::new(grip.approach.origin, gesture.options.size), offset: cursor_offset - gesture.grab_offset.get(), text_style: text_style.clone(), }) }); let editor = view.clone(); let handle = handle.on_click(move |_, window, cx| { editor.update(cx, |view, cx| { if let Err(error) = view.select_document_in_place(selection, window, cx) { eprintln!("Failed to select clicked blocks: {error}"); } }); }); let handle = div() .on_mouse_down(MouseButton::Left, move |event, window, cx| { self.grab_offset.set(event.position - grip.approach.origin); view.update(cx, |editor, cx| editor.focus_in(window, cx)); cx.stop_propagation(); }) .child(handle); Some(AnchoredElement::new(handle, move |_, _| { grip.approach.origin })) } } #[derive(Clone)] struct BlockDrag { editor: Entity, before: DocPos, render: Renderer, revision: u64, selection: Selection, } impl BlockDrag { /// Capture the block or selected block range at the start of a native drag. fn new(view: &Entity, before: DocPos, render: Renderer, cx: &App) -> Self { let editor = view.read(cx).editor(); let selection = match editor.selection() { range @ Selection::NodeRange { .. } if range.bounds(editor.document()).contains(&before) => { range } _ => Selection::Node { before }, }; Self { editor: view.clone(), before, render, selection, revision: editor.revision(), } } fn render_part(&self, part: DragHandlePart, window: &mut Window, cx: &mut App) -> AnyElement { (self.render)( DragHandleSlot { editor: self.editor.clone(), before: self.before, part, }, window, cx, ) } } struct DragPreview { drag: BlockDrag, blocks: Option, render_blocks: PreviewRenderer, grip_bounds: Bounds, offset: Point, text_style: TextStyleRefinement, } impl Render for DragPreview { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let mut overlay = div().relative().left(self.offset.x).top(self.offset.y); *overlay.text_style() = self.text_style.clone().into(); if let Some(blocks) = &self.blocks && self.drag.revision == self.drag.editor.read(cx).editor().revision() { let slot = DragPreviewSlot { content: blocks.render(cx), range: blocks.range(), block_count: blocks.block_count(), }; let preview = (self.render_blocks)(slot, window, cx); let positioned = match preview.anchor { PreviewAnchor::Blocks => { let offset = blocks.bounds().origin - self.grip_bounds.origin; div().absolute().left(offset.x).top(offset.y) } PreviewAnchor::Handle => div().absolute().left(self.grip_bounds.size.width).top_0(), }; overlay = overlay.child(positioned.child(preview.element)); } let grip = self.drag.render_part(DragHandlePart::Preview, window, cx); div().child( overlay.child( div() .min_w(self.grip_bounds.size.width) .h(self.grip_bounds.size.height) .opacity(DEFAULT_PREVIEW_OPACITY) .child(grip), ), ) } } fn move_blocks( view: &EditorView, drag: &BlockDrag, targets: &[BlockDropTarget], gutter_width: Pixels, cx: &Context, ) -> Option<(BlockDropTarget, Transaction)> { if drag.editor.entity_id() != cx.entity_id() || view.editor().revision() != drag.revision { return None; } let editor = view.editor(); let (mut target, tx) = movement::plan(editor, drag.selection, targets, gutter_width)?; if target.indicator.size.width > target.indicator.size.height && editor.document().resolve(target.at).ok()?.depth() == 0 { let inset = gutter_width.min(target.indicator.size.width); target.indicator.origin.x += inset; target.indicator.size.width -= inset; } Some((target, tx)) }