Skip to main content

fc_ui/capabilities/controls/
sortable_list.rs

1use gpui::{prelude::FluentBuilder as _, *};
2use std::rc::Rc;
3
4use crate::capabilities::foundation::theme::use_theme;
5
6#[derive(Clone)]
7pub struct SortableItemDrag {
8    index: usize,
9    position: Point<Pixels>,
10}
11
12impl std::fmt::Debug for SortableItemDrag {
13    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        f.debug_struct("SortableItemDrag")
15            .field("index", &self.index)
16            .finish()
17    }
18}
19
20impl Render for SortableItemDrag {
21    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
22        let theme = use_theme(cx);
23        div().pl(self.position.x).pt(self.position.y).child(
24            div()
25                .px(px(12.0))
26                .py(px(8.0))
27                .bg(theme.tokens.card.opacity(0.95))
28                .border_1()
29                .border_color(theme.tokens.primary)
30                .rounded(theme.tokens.radius_md)
31                .shadow(smallvec::smallvec![BoxShadow {
32                    color: hsla(0.0, 0.0, 0.0, 0.2),
33                    offset: point(px(0.0), px(4.0)),
34                    blur_radius: px(8.0),
35                    spread_radius: px(0.0),
36                    inset: false,
37                }])
38                .text_size(px(14.0))
39                .text_color(theme.tokens.foreground)
40                .font_family(theme.tokens.font_family.clone())
41                .child("Moving..."),
42        )
43    }
44}
45
46pub struct SortableListState<T: Clone + 'static> {
47    items: Vec<T>,
48    dragging_index: Option<usize>,
49    hover_index: Option<usize>,
50}
51
52impl<T: Clone + 'static> SortableListState<T> {
53    pub fn new(items: Vec<T>) -> Self {
54        Self {
55            items,
56            dragging_index: None,
57            hover_index: None,
58        }
59    }
60
61    pub fn items(&self) -> &[T] {
62        &self.items
63    }
64
65    pub fn set_items(&mut self, items: Vec<T>, cx: &mut Context<Self>) {
66        self.items = items;
67        cx.notify();
68    }
69
70    pub fn dragging_index(&self) -> Option<usize> {
71        self.dragging_index
72    }
73
74    pub fn hover_index(&self) -> Option<usize> {
75        self.hover_index
76    }
77}
78
79#[derive(IntoElement)]
80pub struct SortableList<T: Clone + 'static> {
81    state: Entity<SortableListState<T>>,
82    item_renderer: Rc<dyn Fn(&T, usize, bool) -> AnyElement>,
83    on_reorder: Option<Rc<dyn Fn(Vec<T>, &mut Window, &mut App)>>,
84    direction: Axis,
85    gap: Pixels,
86    style: StyleRefinement,
87}
88
89impl<T: Clone + 'static> SortableList<T> {
90    pub fn new(
91        state: Entity<SortableListState<T>>,
92        renderer: impl Fn(&T, usize, bool) -> AnyElement + 'static,
93    ) -> Self {
94        Self {
95            state,
96            item_renderer: Rc::new(renderer),
97            on_reorder: None,
98            direction: Axis::Vertical,
99            gap: px(4.0),
100            style: StyleRefinement::default(),
101        }
102    }
103
104    pub fn on_reorder(
105        mut self,
106        callback: impl Fn(Vec<T>, &mut Window, &mut App) + 'static,
107    ) -> Self {
108        self.on_reorder = Some(Rc::new(callback));
109        self
110    }
111
112    pub fn direction(mut self, direction: Axis) -> Self {
113        self.direction = direction;
114        self
115    }
116
117    pub fn gap(mut self, gap: impl Into<Pixels>) -> Self {
118        self.gap = gap.into();
119        self
120    }
121}
122
123impl<T: Clone + 'static> Styled for SortableList<T> {
124    fn style(&mut self) -> &mut StyleRefinement {
125        &mut self.style
126    }
127}
128
129impl<T: Clone + 'static> RenderOnce for SortableList<T> {
130    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
131        let theme = use_theme(cx);
132        let user_style = self.style;
133        let items = self.state.read(cx).items.clone();
134        let dragging_index = self.state.read(cx).dragging_index;
135        let drag_over_bg = theme.tokens.primary.opacity(0.1);
136        let indicator_color = theme.tokens.primary;
137        let instance_id = self.state.entity_id().as_u64();
138
139        let mut container = div()
140            .flex()
141            .when(self.direction == Axis::Vertical, |d| d.flex_col())
142            .gap(self.gap);
143
144        for (idx, item) in items.iter().enumerate() {
145            let is_dragging = dragging_index == Some(idx);
146            let rendered = (self.item_renderer)(item, idx, is_dragging);
147
148            let state_drop = self.state.clone();
149            let on_reorder = self.on_reorder.clone();
150            let state_drag = self.state.clone();
151            let state_hover = self.state.clone();
152
153            let item_el = div()
154                .id(ElementId::Name(
155                    format!("sortable-item-{}-{}", instance_id, idx).into(),
156                ))
157                .child(rendered)
158                .on_drag(
159                    SortableItemDrag {
160                        index: idx,
161                        position: Point::default(),
162                    },
163                    move |data: &SortableItemDrag, pos, _window, cx| {
164                        state_drag.update(cx, |s, cx| {
165                            s.dragging_index = Some(data.index);
166                            cx.notify();
167                        });
168                        cx.new(|_| SortableItemDrag {
169                            index: data.index,
170                            position: pos,
171                        })
172                    },
173                )
174                .drag_over::<SortableItemDrag>(move |style, _, _, cx| {
175                    state_hover.update(cx, |s, cx| {
176                        if s.hover_index != Some(idx) {
177                            s.hover_index = Some(idx);
178                            cx.notify();
179                        }
180                    });
181                    style
182                        .bg(drag_over_bg)
183                        .border_t(px(2.0))
184                        .border_color(indicator_color)
185                })
186                .on_drop(move |dragged: &SortableItemDrag, window, cx| {
187                    let from = dragged.index;
188                    let to = idx;
189                    if from == to {
190                        state_drop.update(cx, |s, ctx| {
191                            s.dragging_index = None;
192                            s.hover_index = None;
193                            ctx.notify();
194                        });
195                        return;
196                    }
197
198                    state_drop.update(cx, |s, ctx| {
199                        let mut reordered = s.items.clone();
200                        if from < reordered.len() {
201                            let moved = reordered.remove(from);
202                            let insert_at = to.min(reordered.len());
203                            reordered.insert(insert_at, moved);
204                            s.items = reordered;
205                        }
206                        s.dragging_index = None;
207                        s.hover_index = None;
208                        ctx.notify();
209                    });
210
211                    if let Some(ref callback) = on_reorder {
212                        let reordered_items = state_drop.read(cx).items.clone();
213                        callback(reordered_items, window, cx);
214                    }
215                })
216                .when(is_dragging, |d| d.opacity(0.5));
217
218            container = container.child(item_el);
219        }
220
221        container
222            .on_mouse_up(MouseButton::Left, clear_drag_state(&self.state))
223            .on_mouse_up_out(MouseButton::Left, clear_drag_state(&self.state))
224            .map(|mut this| {
225                this.style().refine(&user_style);
226                this
227            })
228    }
229}
230
231fn clear_drag_state<T: Clone + 'static>(
232    state: &Entity<SortableListState<T>>,
233) -> impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static {
234    let state = state.clone();
235    move |_, _, cx| {
236        state.update(cx, |s, cx| {
237            if s.dragging_index.is_some() || s.hover_index.is_some() {
238                s.dragging_index = None;
239                s.hover_index = None;
240                cx.notify();
241            }
242        });
243    }
244}