Visual Studio Code, rebuilt in Rust
Rust
//! cellDnd.ts: a cell dragged by its left focus indicator column and dropped above or below another cell (the half
//! of the cell under the pointer), its selection range moving with it; Alt copies (`isCopy` on macOS).
use gpui::{Context, DragMoveEvent, Render, SharedString, Window, div, prelude::*, px};
use serde_json::{Value, json};
use super::super::Workbench;
use super::CellRow;
use crate::notebook::layout;
/// The dragged cell, drawn under the pointer as its first line (`CodeCellDragImageRenderer`).
#[derive(Clone)]
pub(in crate::workbench) struct CellDrag {
tab: u32,
handle: u64,
label: SharedString,
background: gpui::Rgba,
foreground: gpui::Rgba,
}
impl Render for CellDrag {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().px(px(16.)).py(px(12.)).bg(self.background).text_color(self.foreground).text_size(px(13.)).opacity(0.8).child(self.label.clone())
}
}
impl Workbench {
/// The left focus indicator column of a cell (`registerDragHandle`): pressed and moved, it drags the cell.
pub(super) fn cell_drag_handle(&self, tab: u32, row: &CellRow, first_line: String) -> Option<gpui::Stateful<gpui::Div>> {
if self.setting("notebook.dragAndDropEnabled") == false {
return None;
}
let drag = CellDrag { tab, handle: row.handle, label: first_line.into(), background: self.color("editor.background"), foreground: self.foreground_or("editor.foreground") };
Some(
div()
.id(("notebook-cell-drag-handle", row.handle as usize))
.debug_selector({
let handle = row.handle;
move || format!("notebook-cell-drag-handle-{handle}")
})
.absolute()
.left_0()
.top_0()
.w(px(layout::CODE_CELL_LEFT_MARGIN))
.h(px(row.layout.height - layout::BOTTOM_TOOLBAR_GAP))
.cursor_grab()
.on_drag(drag.clone(), |drag, _, _, cx| cx.new(|_| drag.clone())),
)
}
/// `onCellDragover`: the insertion indicator above or below the cell under the pointer, none over the dragged cell.
pub(super) fn cell_drag_move(&mut self, tab: u32, row_handle: u64, event: &DragMoveEvent<CellDrag>, cx: &mut Context<Self>) {
let drag = event.drag(cx);
if drag.tab != tab {
return;
}
let dragged = drag.handle;
let view = self.notebook_views.views.entry(tab).or_default();
let over = event.bounds.contains(&event.event.position);
let target = match over && dragged != row_handle {
true => Some((dragged, row_handle, event.event.position.y > event.bounds.center().y)),
false => None,
};
let mine = view.drop_target.is_some_and(|(_, handle, _)| handle == row_handle);
if over || mine {
if view.drop_target != target {
view.drop_target = target;
cx.notify();
}
}
}
/// `onCellDrop`: the dragged cell, or the selection ranges when it is selected, move above or below the cell it was
/// dropped on; with Alt the one selection range holding it is copied there (`getCellRangeAroundDragTarget`).
pub(super) fn drop_cell(&mut self, tab: u32, over_handle: u64, copy: bool, cx: &mut Context<Self>) {
let Some(view) = self.notebook_views.views.get_mut(&tab) else { return };
let Some((dragged_handle, target, below)) = view.drop_target.take().filter(|(_, handle, _)| *handle == over_handle) else { return };
cx.notify();
let Some(editor) = self.host.notebooks.editor(tab) else { return };
let key = editor.notebook.clone();
let Some(model) = self.host.notebooks.model(&key) else { return };
let (Some(dragged), Some(over)) = (model.index_of_handle(dragged_handle), model.index_of_handle(target)) else { return };
// getNextVisibleCellIndex: below a collapsed header is after its section.
let rows = self.notebook_rows(tab, model);
let mut to = over;
if below {
to = rows.iter().find(|row| row.index > over && !row.hidden).map_or(model.cells.len(), |row| row.index);
}
if copy {
let (start, end) = editor.selections.iter().copied().find(|(start, end)| *start <= dragged && dragged < *end).unwrap_or((dragged, dragged + 1));
let cells: Vec<_> = model.cells[start..end].iter().map(|cell| self.cell_data(cell)).collect();
let focus = if to <= start { to + dragged - start } else { dragged + to - start };
self.edit_notebook_cells(&key, vec![json!({ "editType": 1, "index": to, "count": 0, "cells": cells })], Some(focus), cx);
return;
}
let (edits, focus, selection) = cell_drop_edits(editor.selections.clone(), editor.focus, dragged, to);
if self.edit_notebook_cells(&key, edits, Some(focus), cx)
&& let Some(editor) = self.host.notebooks.editors.iter_mut().find(|editor| editor.tab_model_id == tab)
{
editor.selections = vec![selection];
}
}
/// The insertion indicator (`cell-list-insertion-indicator`): 2px across the list, half the bottom toolbar gap
/// below the cell's top or bottom.
pub(super) fn cell_drop_indicator(&self, tab: u32, rows: &[CellRow], scroll_top: f32) -> Option<gpui::Div> {
let (_, handle, below) = self.notebook_views.views.get(&tab)?.drop_target?;
let row = rows.iter().find(|row| row.handle == handle)?;
let top = if below { row.layout.top + row.layout.height } else { row.layout.top };
Some(div().absolute().left_0().right_0().top(px(top - scroll_top + layout::BOTTOM_TOOLBAR_GAP / 2.)).h(px(2.)).bg(self.color("notebook.cellInsertionIndicator")))
}
}
/// `performCellDropEdits`: every selection range moves to `to` when the dragged cell is in one, else the dragged
/// cell alone; the `Move` edits go last range first, as the model applies them. Returns the edits, the focus and the
/// selection of the moved cells.
fn cell_drop_edits(mut selections: Vec<(usize, usize)>, mut focus: usize, dragged: usize, mut to: usize) -> (Vec<Value>, usize, (usize, usize)) {
if selections.is_empty() {
selections = vec![(focus, focus + 1)];
}
if !selections.iter().any(|&(start, end)| start <= dragged && dragged < end) {
selections = vec![(dragged, dragged + 1)];
focus = dragged;
}
if let Some(&(start, _)) = selections.iter().find(|&&(start, end)| start <= to && to < end) {
to = start;
}
selections.sort_by(|a, b| b.0.cmp(&a.0));
let (mut moved, mut new_focus, mut insertion, mut last_index) = (0, to, to, to);
let mut edits = Vec::new();
for (start, end) in selections {
let length = end - start;
let new_index = if end <= insertion { insertion - length } else { insertion };
if (start..=end).contains(&focus) {
new_focus = new_index + focus - start;
}
// A range below the drop place moved down by the ranges already moved above it.
let from = if start >= to { start + moved } else { start };
edits.push(json!({ "editType": 6, "index": from, "length": length, "newIdx": new_index }));
moved += length;
if end < insertion {
insertion -= length;
}
last_index = new_index;
}
(edits, new_focus, (last_index, last_index + moved))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_selected_range_moves_to_the_drop_place() {
let indices = |edits: &[Value]| edits.iter().map(|edit| (edit["index"].as_u64().unwrap(), edit["length"].as_u64().unwrap(), edit["newIdx"].as_u64().unwrap())).collect::<Vec<_>>();
// Cells 0 and 2 selected, 2 dragged below cell 4 (drop index 5).
let (edits, focus, selection) = cell_drop_edits(vec![(0, 1), (2, 3)], 2, 2, 5);
assert_eq!(indices(&edits), [(2, 1, 4), (0, 1, 3)]);
assert_eq!((focus, selection), (4, (3, 5)));
// A dragged cell outside the selection moves alone.
let (edits, focus, selection) = cell_drop_edits(vec![(0, 1)], 0, 3, 1);
assert_eq!(indices(&edits), [(3, 1, 1)]);
assert_eq!((focus, selection), (1, (1, 2)));
}
}