use std::{cell::RefCell, rc::Rc};
use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
MouseMoveEvent, MouseUpEvent, ParentElement, RenderOnce, Role, SharedString, Styled, Window,
base::StyledExt as _, canvas, div, point, prelude::*, px,
};
pub const REORDER_ROW_PITCH_PX: f32 = 52.0;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReorderableItem {
pub id: SharedString,
pub title: SharedString,
pub detail: Option<SharedString>,
}
impl ReorderableItem {
pub fn new(id: impl Into<SharedString>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
title: title.into(),
detail: None,
}
}
pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
self.detail = Some(detail.into());
self
}
}
pub fn reorder_move_item(
items: &[ReorderableItem],
id: &str,
delta: isize,
) -> Option<Vec<ReorderableItem>> {
let idx = items.iter().position(|it| it.id.as_ref() == id)?;
let target = idx as isize + delta;
if target < 0 || target >= items.len() as isize {
return None;
}
let mut next = items.to_vec();
next.swap(idx, target as usize);
Some(next)
}
fn paint_grip_dots(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
let cols = [-2.5_f32, 2.5];
let rows = [-4.5_f32, 0.0, 4.5];
for &dx in &cols {
for &dy in &rows {
let dot = gpui_kit::Bounds::new(
point(px(cx + dx - 1.2), px(cy + dy - 1.2)),
gpui_kit::size(px(2.4), px(2.4)),
);
window.paint_quad(gpui_kit::fill(dot, color).corner_radii(px(1.2)));
}
}
}
type ReorderCallback = Rc<dyn Fn(&Vec<ReorderableItem>, &mut Window, &mut App)>;
#[derive(Clone)]
struct ReorderInternal {
dragging_id: Option<SharedString>,
drag_start_y: f32,
drag_offset_y: f32,
lifted_id: Option<SharedString>,
lifted_until: f64,
focused_id: Option<SharedString>,
prev_indices: std::collections::HashMap<SharedString, usize>,
roll_dirs: std::collections::HashMap<SharedString, (i8, f64)>,
focus_handle: FocusHandle,
}
#[derive(IntoElement)]
pub struct ReorderableList {
id: ElementId,
label: SharedString,
items: Vec<ReorderableItem>,
on_reorder: Option<ReorderCallback>,
}
impl ReorderableList {
pub fn new(id: impl Into<ElementId>, items: impl IntoIterator<Item = ReorderableItem>) -> Self {
Self {
id: id.into(),
label: SharedString::from("Reorder items"),
items: items.into_iter().collect(),
on_reorder: None,
}
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn on_reorder(
mut self,
cb: impl Fn(&Vec<ReorderableItem>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_reorder = Some(Rc::new(cb));
self
}
}
impl RenderOnce for ReorderableList {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let state_cell = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), SharedString::from("rl-state")),
cx,
|_, cx| {
let prev_indices = self
.items
.iter()
.enumerate()
.map(|(i, it)| (it.id.clone(), i))
.collect();
Rc::new(RefCell::new(ReorderInternal {
dragging_id: None,
drag_start_y: 0.0,
drag_offset_y: 0.0,
lifted_id: None,
lifted_until: 0.0,
focused_id: self.items.first().map(|i| i.id.clone()),
prev_indices,
roll_dirs: std::collections::HashMap::new(),
focus_handle: cx.focus_handle(),
}))
},
)
.read(cx)
.clone();
let (dragging_id, drag_offset_y, lifted_id, focused_id, roll_snapshot, focus_handle) = {
let mut st = state_cell.borrow_mut();
let mut need_anim = false;
for (idx, item) in self.items.iter().enumerate() {
if let Some(&prev) = st.prev_indices.get(&item.id)
&& prev != idx
{
let dir = if idx > prev { 1 } else { -1 };
st.roll_dirs.insert(item.id.clone(), (dir, now));
}
st.prev_indices.insert(item.id.clone(), idx);
}
if st.lifted_id.is_some() && now >= st.lifted_until {
st.lifted_id = None;
}
for &(_, ts) in st.roll_dirs.values() {
if !reduced && (now - ts) < 0.28 {
need_anim = true;
}
}
if !reduced && st.lifted_id.is_some() {
need_anim = true;
}
if need_anim {
window.request_animation_frame();
}
(
st.dragging_id.clone(),
st.drag_offset_y,
st.lifted_id.clone(),
st.focused_id.clone(),
st.roll_dirs.clone(),
st.focus_handle.clone(),
)
};
let st_drag = state_cell.clone();
let items_drag = self.items.clone();
let cb_drag = self.on_reorder.clone();
let drag_probe = canvas(
|_, _, _| {},
move |_, _, window, _| {
if st_drag.borrow().dragging_id.is_none() {
return;
}
let st_m = st_drag.clone();
let items_m = items_drag.clone();
let cb_m = cb_drag.clone();
window.on_mouse_event(move |ev: &MouseMoveEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let swap_cmd = {
let mut st = st_m.borrow_mut();
let Some(ref active_id) = st.dragging_id.clone() else {
return;
};
let dy = f32::from(ev.position.y) - st.drag_start_y;
st.drag_offset_y = dy;
if dy.abs() >= REORDER_ROW_PITCH_PX * 0.65 {
let step = if dy > 0.0 { 1 } else { -1 };
if let Some(next_list) = reorder_move_item(&items_m, active_id, step) {
st.drag_start_y += step as f32 * REORDER_ROW_PITCH_PX;
st.drag_offset_y -= step as f32 * REORDER_ROW_PITCH_PX;
Some(next_list)
} else {
None
}
} else {
None
}
};
if let Some(next_list) = swap_cmd
&& let Some(ref cb) = cb_m
{
cb(&next_list, window, cx);
}
window.refresh();
});
let st_u = st_drag.clone();
window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _| {
if !phase.bubble() {
return;
}
let mut st = st_u.borrow_mut();
if st.dragging_id.is_some() {
st.dragging_id = None;
st.drag_offset_y = 0.0;
window.refresh();
}
});
},
)
.absolute()
.inset_0();
let grip_hover_bg = oklab_mix(colors.foreground, colors.surface, 0.06);
let mut list = div()
.id(self.id.clone())
.role(Role::List)
.aria_label(self.label)
.track_focus(&focus_handle)
.relative()
.w_full()
.flex()
.flex_col()
.gap(Spacing::S2)
.child(drag_probe);
let items_key = self.items.clone();
let st_key = state_cell.clone();
let cb_key = self.on_reorder.clone();
list = list.on_key_down(move |ev: &KeyDownEvent, window, cx| {
let delta = match ev.keystroke.key.as_str() {
"up" => -1,
"down" => 1,
_ => return,
};
let target_id = {
let st = st_key.borrow();
st.focused_id
.clone()
.or_else(|| items_key.first().map(|i| i.id.clone()))
};
let Some(id) = target_id else {
return;
};
if let Some(next_list) = reorder_move_item(&items_key, &id, delta) {
{
let mut st = st_key.borrow_mut();
st.lifted_id = Some(id);
st.lifted_until = motion_now(cx) + 0.26;
}
if let Some(ref cb) = cb_key {
cb(&next_list, window, cx);
}
window.refresh();
}
});
for (idx, item) in self.items.iter().enumerate() {
let is_dragging = dragging_id.as_ref() == Some(&item.id);
let is_lifted = is_dragging || lifted_id.as_ref() == Some(&item.id);
let is_focused = focused_id.as_ref() == Some(&item.id);
let row_dy = if is_dragging { drag_offset_y } else { 0.0 };
let (roll_y, roll_alpha) = if reduced {
(0.0, 1.0)
} else if let Some(&(dir, ts)) = roll_snapshot.get(&item.id) {
let dt = (now - ts).max(0.0);
if dt < 0.24 {
let t = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample((dt / 0.24) as f32);
((1.0 - t) * 7.0 * dir as f32, t)
} else {
(0.0, 1.0)
}
} else {
(0.0, 1.0)
};
let st_down = state_cell.clone();
let id_down = item.id.clone();
let fh_down = focus_handle.clone();
let grip_col = if is_lifted {
colors.foreground
} else {
colors.text_muted
};
let mut row = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("rl-row-{}", item.id)),
))
.role(Role::ListItem)
.relative()
.top(px(row_dy))
.w_full()
.min_h(px(44.0))
.px(Spacing::S3)
.py(Spacing::S2)
.rounded(Radii::PANEL)
.border_1()
.border_color(if is_lifted || is_focused {
colors.border_strong
} else {
colors.border
})
.bg(if is_lifted {
colors.surface_raised
} else {
colors.surface
})
.flex()
.flex_row()
.items_center()
.gap(Spacing::S3)
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("rl-handle-{}", item.id)),
))
.w(px(28.0))
.h(px(28.0))
.flex_none()
.rounded(Radii::CONTROL)
.hover(move |s| s.bg(grip_hover_bg))
.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
fh_down.focus(window, cx);
let mut st = st_down.borrow_mut();
st.focused_id = Some(id_down.clone());
st.dragging_id = Some(id_down.clone());
st.drag_start_y = f32::from(ev.position.y);
st.drag_offset_y = 0.0;
window.refresh();
})
.child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let cx_p = f32::from(bounds.origin.x)
+ f32::from(bounds.size.width) * 0.5;
let cy_p = f32::from(bounds.origin.y)
+ f32::from(bounds.size.height) * 0.5;
paint_grip_dots(cx_p, cy_p, grip_col, window);
},
)
.size_full(),
),
)
.child(
div()
.flex_1()
.min_w(px(0.0))
.flex()
.flex_col()
.gap(px(1.0))
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.truncate()
.child(item.title.clone()),
)
.when_some(item.detail.clone(), |el, det| {
el.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.truncate()
.child(det),
)
}),
)
.child(
div()
.w(px(28.0))
.flex_none()
.flex()
.items_center()
.justify_end()
.overflow_hidden()
.child(
div()
.relative()
.top(px(roll_y))
.opacity(roll_alpha)
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_muted)
.child(format!("{:02}", idx + 1)),
),
);
if is_lifted {
row = row.shadow(Shadows::raised(theme.mode));
}
list = list.child(row);
}
list.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reorder_move_item_swaps_within_bounds() {
let items = vec![
ReorderableItem::new("a", "Alpha"),
ReorderableItem::new("b", "Beta"),
ReorderableItem::new("c", "Gamma"),
];
assert!(reorder_move_item(&items, "a", -1).is_none());
assert!(reorder_move_item(&items, "c", 1).is_none());
let moved = reorder_move_item(&items, "b", -1).unwrap();
let ids: Vec<&str> = moved.iter().map(|i| i.id.as_ref()).collect();
assert_eq!(ids, vec!["b", "a", "c"]);
}
}