1use std::{cell::RefCell, rc::Rc};
13
14use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
15use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
16use gpui_kit::{
17 App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
18 MouseMoveEvent, MouseUpEvent, ParentElement, RenderOnce, Role, SharedString, Styled, Window,
19 base::StyledExt as _, canvas, div, point, prelude::*, px,
20};
21
22pub const REORDER_ROW_PITCH_PX: f32 = 52.0;
24
25#[derive(Clone, Debug, Eq, PartialEq)]
27pub struct ReorderableItem {
28 pub id: SharedString,
29 pub title: SharedString,
30 pub detail: Option<SharedString>,
31}
32
33impl ReorderableItem {
34 pub fn new(id: impl Into<SharedString>, title: impl Into<SharedString>) -> Self {
35 Self {
36 id: id.into(),
37 title: title.into(),
38 detail: None,
39 }
40 }
41
42 pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
43 self.detail = Some(detail.into());
44 self
45 }
46}
47
48pub fn reorder_move_item(
50 items: &[ReorderableItem],
51 id: &str,
52 delta: isize,
53) -> Option<Vec<ReorderableItem>> {
54 let idx = items.iter().position(|it| it.id.as_ref() == id)?;
55 let target = idx as isize + delta;
56 if target < 0 || target >= items.len() as isize {
57 return None;
58 }
59 let mut next = items.to_vec();
60 next.swap(idx, target as usize);
61 Some(next)
62}
63
64fn paint_grip_dots(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
65 let cols = [-2.5_f32, 2.5];
66 let rows = [-4.5_f32, 0.0, 4.5];
67 for &dx in &cols {
68 for &dy in &rows {
69 let dot = gpui_kit::Bounds::new(
70 point(px(cx + dx - 1.2), px(cy + dy - 1.2)),
71 gpui_kit::size(px(2.4), px(2.4)),
72 );
73 window.paint_quad(gpui_kit::fill(dot, color).corner_radii(px(1.2)));
74 }
75 }
76}
77
78type ReorderCallback = Rc<dyn Fn(&Vec<ReorderableItem>, &mut Window, &mut App)>;
79
80#[derive(Clone)]
81struct ReorderInternal {
82 dragging_id: Option<SharedString>,
83 drag_start_y: f32,
84 drag_offset_y: f32,
85 lifted_id: Option<SharedString>,
86 lifted_until: f64,
87 focused_id: Option<SharedString>,
88 prev_indices: std::collections::HashMap<SharedString, usize>,
89 roll_dirs: std::collections::HashMap<SharedString, (i8, f64)>,
90 focus_handle: FocusHandle,
91}
92
93#[derive(IntoElement)]
95pub struct ReorderableList {
96 id: ElementId,
97 label: SharedString,
98 items: Vec<ReorderableItem>,
99 on_reorder: Option<ReorderCallback>,
100}
101
102impl ReorderableList {
103 pub fn new(id: impl Into<ElementId>, items: impl IntoIterator<Item = ReorderableItem>) -> Self {
104 Self {
105 id: id.into(),
106 label: SharedString::from("Reorder items"),
107 items: items.into_iter().collect(),
108 on_reorder: None,
109 }
110 }
111
112 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
113 self.label = label.into();
114 self
115 }
116
117 pub fn on_reorder(
118 mut self,
119 cb: impl Fn(&Vec<ReorderableItem>, &mut Window, &mut App) + 'static,
120 ) -> Self {
121 self.on_reorder = Some(Rc::new(cb));
122 self
123 }
124}
125
126impl RenderOnce for ReorderableList {
127 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
128 let theme = cx.arc_theme().clone();
129 let colors = theme.colors;
130 let reduced = is_reduced_motion(cx);
131 let now = motion_now(cx);
132
133 let state_cell = window
134 .use_keyed_state(
135 ElementId::NamedChild(self.id.clone().into(), SharedString::from("rl-state")),
136 cx,
137 |_, cx| {
138 let prev_indices = self
139 .items
140 .iter()
141 .enumerate()
142 .map(|(i, it)| (it.id.clone(), i))
143 .collect();
144 Rc::new(RefCell::new(ReorderInternal {
145 dragging_id: None,
146 drag_start_y: 0.0,
147 drag_offset_y: 0.0,
148 lifted_id: None,
149 lifted_until: 0.0,
150 focused_id: self.items.first().map(|i| i.id.clone()),
151 prev_indices,
152 roll_dirs: std::collections::HashMap::new(),
153 focus_handle: cx.focus_handle(),
154 }))
155 },
156 )
157 .read(cx)
158 .clone();
159
160 let (dragging_id, drag_offset_y, lifted_id, focused_id, roll_snapshot, focus_handle) = {
161 let mut st = state_cell.borrow_mut();
162 let mut need_anim = false;
163 for (idx, item) in self.items.iter().enumerate() {
164 if let Some(&prev) = st.prev_indices.get(&item.id)
165 && prev != idx
166 {
167 let dir = if idx > prev { 1 } else { -1 };
168 st.roll_dirs.insert(item.id.clone(), (dir, now));
169 }
170 st.prev_indices.insert(item.id.clone(), idx);
171 }
172 if st.lifted_id.is_some() && now >= st.lifted_until {
173 st.lifted_id = None;
174 }
175 for &(_, ts) in st.roll_dirs.values() {
176 if !reduced && (now - ts) < 0.28 {
177 need_anim = true;
178 }
179 }
180 if !reduced && st.lifted_id.is_some() {
181 need_anim = true;
182 }
183 if need_anim {
184 window.request_animation_frame();
185 }
186 (
187 st.dragging_id.clone(),
188 st.drag_offset_y,
189 st.lifted_id.clone(),
190 st.focused_id.clone(),
191 st.roll_dirs.clone(),
192 st.focus_handle.clone(),
193 )
194 };
195
196 let st_drag = state_cell.clone();
198 let items_drag = self.items.clone();
199 let cb_drag = self.on_reorder.clone();
200 let drag_probe = canvas(
201 |_, _, _| {},
202 move |_, _, window, _| {
203 if st_drag.borrow().dragging_id.is_none() {
204 return;
205 }
206 let st_m = st_drag.clone();
207 let items_m = items_drag.clone();
208 let cb_m = cb_drag.clone();
209 window.on_mouse_event(move |ev: &MouseMoveEvent, phase, window, cx| {
210 if !phase.bubble() {
211 return;
212 }
213 let swap_cmd = {
214 let mut st = st_m.borrow_mut();
215 let Some(ref active_id) = st.dragging_id.clone() else {
216 return;
217 };
218 let dy = f32::from(ev.position.y) - st.drag_start_y;
219 st.drag_offset_y = dy;
220 if dy.abs() >= REORDER_ROW_PITCH_PX * 0.65 {
221 let step = if dy > 0.0 { 1 } else { -1 };
222 if let Some(next_list) = reorder_move_item(&items_m, active_id, step) {
223 st.drag_start_y += step as f32 * REORDER_ROW_PITCH_PX;
224 st.drag_offset_y -= step as f32 * REORDER_ROW_PITCH_PX;
225 Some(next_list)
226 } else {
227 None
228 }
229 } else {
230 None
231 }
232 };
233 if let Some(next_list) = swap_cmd
234 && let Some(ref cb) = cb_m
235 {
236 cb(&next_list, window, cx);
237 }
238 window.refresh();
239 });
240
241 let st_u = st_drag.clone();
242 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _| {
243 if !phase.bubble() {
244 return;
245 }
246 let mut st = st_u.borrow_mut();
247 if st.dragging_id.is_some() {
248 st.dragging_id = None;
249 st.drag_offset_y = 0.0;
250 window.refresh();
251 }
252 });
253 },
254 )
255 .absolute()
256 .inset_0();
257
258 let grip_hover_bg = oklab_mix(colors.foreground, colors.surface, 0.06);
259
260 let mut list = div()
261 .id(self.id.clone())
262 .role(Role::List)
263 .aria_label(self.label)
264 .track_focus(&focus_handle)
265 .relative()
266 .w_full()
267 .flex()
268 .flex_col()
269 .gap(Spacing::S2)
270 .child(drag_probe);
271
272 let items_key = self.items.clone();
273 let st_key = state_cell.clone();
274 let cb_key = self.on_reorder.clone();
275 list = list.on_key_down(move |ev: &KeyDownEvent, window, cx| {
276 let delta = match ev.keystroke.key.as_str() {
277 "up" => -1,
278 "down" => 1,
279 _ => return,
280 };
281 let target_id = {
282 let st = st_key.borrow();
283 st.focused_id
284 .clone()
285 .or_else(|| items_key.first().map(|i| i.id.clone()))
286 };
287 let Some(id) = target_id else {
288 return;
289 };
290 if let Some(next_list) = reorder_move_item(&items_key, &id, delta) {
291 {
292 let mut st = st_key.borrow_mut();
293 st.lifted_id = Some(id);
294 st.lifted_until = motion_now(cx) + 0.26;
295 }
296 if let Some(ref cb) = cb_key {
297 cb(&next_list, window, cx);
298 }
299 window.refresh();
300 }
301 });
302
303 for (idx, item) in self.items.iter().enumerate() {
304 let is_dragging = dragging_id.as_ref() == Some(&item.id);
305 let is_lifted = is_dragging || lifted_id.as_ref() == Some(&item.id);
306 let is_focused = focused_id.as_ref() == Some(&item.id);
307 let row_dy = if is_dragging { drag_offset_y } else { 0.0 };
308
309 let (roll_y, roll_alpha) = if reduced {
310 (0.0, 1.0)
311 } else if let Some(&(dir, ts)) = roll_snapshot.get(&item.id) {
312 let dt = (now - ts).max(0.0);
313 if dt < 0.24 {
314 let t = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample((dt / 0.24) as f32);
315 ((1.0 - t) * 7.0 * dir as f32, t)
316 } else {
317 (0.0, 1.0)
318 }
319 } else {
320 (0.0, 1.0)
321 };
322
323 let st_down = state_cell.clone();
324 let id_down = item.id.clone();
325 let fh_down = focus_handle.clone();
326 let grip_col = if is_lifted {
327 colors.foreground
328 } else {
329 colors.text_muted
330 };
331
332 let mut row = div()
333 .id(ElementId::NamedChild(
334 self.id.clone().into(),
335 SharedString::from(format!("rl-row-{}", item.id)),
336 ))
337 .role(Role::ListItem)
338 .relative()
339 .top(px(row_dy))
340 .w_full()
341 .min_h(px(44.0))
342 .px(Spacing::S3)
343 .py(Spacing::S2)
344 .rounded(Radii::PANEL)
345 .border_1()
346 .border_color(if is_lifted || is_focused {
347 colors.border_strong
348 } else {
349 colors.border
350 })
351 .bg(if is_lifted {
352 colors.surface_raised
353 } else {
354 colors.surface
355 })
356 .flex()
357 .flex_row()
358 .items_center()
359 .gap(Spacing::S3)
360 .child(
361 div()
362 .id(ElementId::NamedChild(
363 self.id.clone().into(),
364 SharedString::from(format!("rl-handle-{}", item.id)),
365 ))
366 .w(px(28.0))
367 .h(px(28.0))
368 .flex_none()
369 .rounded(Radii::CONTROL)
370 .hover(move |s| s.bg(grip_hover_bg))
371 .cursor_pointer()
372 .on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
373 fh_down.focus(window, cx);
374 let mut st = st_down.borrow_mut();
375 st.focused_id = Some(id_down.clone());
376 st.dragging_id = Some(id_down.clone());
377 st.drag_start_y = f32::from(ev.position.y);
378 st.drag_offset_y = 0.0;
379 window.refresh();
380 })
381 .child(
382 canvas(
383 |_, _, _| {},
384 move |bounds, _, window, _| {
385 let cx_p = f32::from(bounds.origin.x)
386 + f32::from(bounds.size.width) * 0.5;
387 let cy_p = f32::from(bounds.origin.y)
388 + f32::from(bounds.size.height) * 0.5;
389 paint_grip_dots(cx_p, cy_p, grip_col, window);
390 },
391 )
392 .size_full(),
393 ),
394 )
395 .child(
396 div()
397 .flex_1()
398 .min_w(px(0.0))
399 .flex()
400 .flex_col()
401 .gap(px(1.0))
402 .child(
403 div()
404 .text_size(Typography::TEXT_SM)
405 .font_medium()
406 .text_color(colors.foreground)
407 .truncate()
408 .child(item.title.clone()),
409 )
410 .when_some(item.detail.clone(), |el, det| {
411 el.child(
412 div()
413 .text_size(Typography::TEXT_XS)
414 .text_color(colors.text_muted)
415 .truncate()
416 .child(det),
417 )
418 }),
419 )
420 .child(
421 div()
422 .w(px(28.0))
423 .flex_none()
424 .flex()
425 .items_center()
426 .justify_end()
427 .overflow_hidden()
428 .child(
429 div()
430 .relative()
431 .top(px(roll_y))
432 .opacity(roll_alpha)
433 .text_size(Typography::TEXT_XS)
434 .font_medium()
435 .text_color(colors.text_muted)
436 .child(format!("{:02}", idx + 1)),
437 ),
438 );
439
440 if is_lifted {
441 row = row.shadow(Shadows::raised(theme.mode));
442 }
443 list = list.child(row);
444 }
445
446 list.into_any_element()
447 }
448}
449
450#[cfg(test)]
451mod tests {
452 use super::*;
453
454 #[test]
455 fn reorder_move_item_swaps_within_bounds() {
456 let items = vec![
457 ReorderableItem::new("a", "Alpha"),
458 ReorderableItem::new("b", "Beta"),
459 ReorderableItem::new("c", "Gamma"),
460 ];
461 assert!(reorder_move_item(&items, "a", -1).is_none());
462 assert!(reorder_move_item(&items, "c", 1).is_none());
463
464 let moved = reorder_move_item(&items, "b", -1).unwrap();
465 let ids: Vec<&str> = moved.iter().map(|i| i.id.as_ref()).collect();
466 assert_eq!(ids, vec!["b", "a", "c"]);
467 }
468}