1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
use crate::{
    Drawable, EventCtx, GeomBatch, GeomBatchStack, GfxCtx, Outcome, ScreenDims, ScreenPt,
    ScreenRectangle, StackAlignment, StackAxis, Widget, WidgetImpl, WidgetOutput,
};

const SPACE_BETWEEN_CARDS: f64 = 2.0;

pub struct DragDrop<T: Copy + PartialEq> {
    label: String,
    cards: Vec<Card<T>>,
    draw: Drawable,
    state: State,
    axis: StackAxis,
    dims: ScreenDims,
    top_left: ScreenPt,
}

struct Card<T: PartialEq> {
    value: T,
    dims: ScreenDims,
    default_batch: GeomBatch,
    hovering_batch: GeomBatch,
    selected_batch: GeomBatch,
}

#[derive(PartialEq)]
enum State {
    Initial {
        hovering: Option<usize>,
        selected: Option<usize>,
    },
    Idle {
        hovering: Option<usize>,
        selected: Option<usize>,
    },
    Dragging {
        orig_idx: usize,
        drag_from: ScreenPt,
        cursor_at: ScreenPt,
        new_idx: usize,
    },
}

impl<T: 'static + Copy + PartialEq> DragDrop<T> {
    /// This widget emits several events.
    ///
    /// - `Outcome::Changed(label)` when a different card is selected or hovered on
    /// - `Outcome::Changed("dragging " + label)` while dragging, when the drop position of the
    ///    card changes. Call `get_dragging_state` to learn the indices.
    /// - `Outcome::DragDropReleased` when a card is dropped
    ///
    /// When you build a `Panel` containing one of these, you may need to call
    /// `ignore_initial_events()`. If the cursor is hovering over a card when the panel is first
    /// created, `Outcome::Changed` is immediately fired from this widget.
    pub fn new(ctx: &EventCtx, label: &str, axis: StackAxis) -> Self {
        DragDrop {
            label: label.to_string(),
            cards: vec![],
            draw: Drawable::empty(ctx),
            state: State::Idle {
                hovering: None,
                selected: None,
            },
            axis,
            dims: ScreenDims::zero(),
            top_left: ScreenPt::zero(),
        }
    }

    pub fn into_widget(mut self, ctx: &EventCtx) -> Widget {
        self.recalc_draw(ctx);
        let label = self.label.clone();
        Widget::new(Box::new(self)).named(label)
    }

    pub fn selected_value(&self) -> Option<T> {
        let idx = match self.state {
            State::Initial { selected, .. } | State::Idle { selected, .. } => selected,
            State::Dragging { orig_idx, .. } => Some(orig_idx),
        }?;

        Some(self.cards[idx].value)
    }

    pub fn hovering_value(&self) -> Option<T> {
        let idx = match self.state {
            State::Initial { hovering, .. } | State::Idle { hovering, .. } => hovering,
            _ => None,
        }?;
        Some(self.cards[idx].value)
    }

    pub fn push_card(
        &mut self,
        value: T,
        dims: ScreenDims,
        default_batch: GeomBatch,
        hovering_batch: GeomBatch,
        selected_batch: GeomBatch,
    ) {
        self.cards.push(Card {
            value,
            dims,
            default_batch,
            hovering_batch,
            selected_batch,
        });
    }

    pub fn set_initial_state(&mut self, selected_value: Option<T>, hovering_value: Option<T>) {
        let selected = selected_value.and_then(|selected_value| {
            self.cards
                .iter()
                .position(|card| card.value == selected_value)
        });

        let hovering = hovering_value.and_then(|hovering_value| {
            self.cards
                .iter()
                .position(|card| card.value == hovering_value)
        });

        self.state = State::Initial { selected, hovering };
    }

    /// If a card is currently being dragged, return its original and (potential) new index.
    pub fn get_dragging_state(&self) -> Option<(usize, usize)> {
        match self.state {
            State::Dragging {
                orig_idx, new_idx, ..
            } => Some((orig_idx, new_idx)),
            _ => None,
        }
    }
}

impl<T: 'static + Copy + PartialEq> DragDrop<T> {
    fn recalc_draw(&mut self, ctx: &EventCtx) {
        let mut stack = GeomBatchStack::from_axis(Vec::new(), self.axis);
        stack.set_spacing(SPACE_BETWEEN_CARDS);

        // TODO: we could make alignment separately configurable, but these are the only
        // combinations we currently use
        stack.set_alignment(if self.axis == StackAxis::Vertical {
            StackAlignment::Left
        } else {
            StackAlignment::Top
        });

        let (dims, batch) = match self.state {
            State::Initial { hovering, selected } | State::Idle { hovering, selected } => {
                for (idx, card) in self.cards.iter().enumerate() {
                    if selected == Some(idx) {
                        stack.push(card.selected_batch.clone());
                    } else if hovering == Some(idx) {
                        stack.push(card.hovering_batch.clone());
                    } else {
                        stack.push(card.default_batch.clone());
                    }
                }
                let batch = stack.batch();
                (batch.get_dims(), batch)
            }
            State::Dragging {
                orig_idx,
                drag_from,
                cursor_at,
                new_idx,
            } => {
                let orig_dims = self.cards[orig_idx].dims;

                for (idx, card) in self.cards.iter().enumerate() {
                    // the target we're dragging
                    let batch = if idx == orig_idx {
                        card.selected_batch.clone()
                    } else if idx <= new_idx && idx > orig_idx {
                        // move batch to the left or top if target is newly greater than us
                        match self.axis {
                            StackAxis::Horizontal => card
                                .default_batch
                                .clone()
                                .translate(-(orig_dims.width + SPACE_BETWEEN_CARDS), 0.0),
                            StackAxis::Vertical => card
                                .default_batch
                                .clone()
                                .translate(0.0, -(orig_dims.height + SPACE_BETWEEN_CARDS)),
                        }
                    } else if idx >= new_idx && idx < orig_idx {
                        // move batch to the right or bottom if target is newly less than us
                        match self.axis {
                            StackAxis::Horizontal => card
                                .default_batch
                                .clone()
                                .translate(orig_dims.width + SPACE_BETWEEN_CARDS, 0.0),
                            StackAxis::Vertical => card
                                .default_batch
                                .clone()
                                .translate(0.0, orig_dims.height + SPACE_BETWEEN_CARDS),
                        }
                    } else {
                        card.default_batch.clone()
                    };

                    stack.push(batch);
                }

                // PERF: avoid this clone by implementing a non-consuming `stack.get_dims()`.
                // At the moment it seems like not a big deal to just clone the thing
                let dims = stack.clone().batch().get_dims();

                // The dragged batch follows the cursor, but don't translate it until we've captured
                // the pre-existing `dims`, otherwise the dragged position will be included in the
                // overall dims of this widget, causing other screen content to shift around as we
                // drag.
                let mut dragged_batch = std::mem::take(stack.get_mut(orig_idx).unwrap());

                // offset the dragged item just a little to initially hint that it's moveable
                let floating_effect_offset = 4.0;
                dragged_batch = dragged_batch
                    .translate(
                        cursor_at.x - drag_from.x + floating_effect_offset,
                        cursor_at.y - drag_from.y - floating_effect_offset,
                    )
                    .set_z_offset(-0.1);
                *stack.get_mut(orig_idx).unwrap() = dragged_batch;

                (dims, stack.batch())
            }
        };
        self.dims = dims;
        self.draw = batch.upload(ctx);
    }

    fn mouseover_card(&self, ctx: &EventCtx) -> Option<usize> {
        let pt = ctx.canvas.get_cursor_in_screen_space()?;
        let mut top_left = self.top_left;
        for (idx, Card { dims, .. }) in self.cards.iter().enumerate() {
            if ScreenRectangle::top_left(top_left, *dims).contains(pt) {
                return Some(idx);
            }
            match self.axis {
                StackAxis::Horizontal => {
                    top_left.x += dims.width + SPACE_BETWEEN_CARDS;
                }
                StackAxis::Vertical => {
                    top_left.y += dims.height + SPACE_BETWEEN_CARDS;
                }
            }
        }
        None
    }
}

impl<T: 'static + Copy + PartialEq> WidgetImpl for DragDrop<T> {
    fn get_dims(&self) -> ScreenDims {
        self.dims
    }

    fn set_pos(&mut self, top_left: ScreenPt) {
        self.top_left = top_left;
    }

    fn event(&mut self, ctx: &mut EventCtx, output: &mut WidgetOutput) {
        let new_state = match self.state {
            State::Initial { selected, hovering } => {
                if let Some(idx) = self.mouseover_card(ctx) {
                    if hovering != Some(idx) {
                        output.outcome = Outcome::Changed(self.label.clone());
                    }
                    State::Idle {
                        hovering: Some(idx),
                        selected,
                    }
                } else {
                    // Keep the initial state, which reflects hovering/selection from interacting
                    // with the lanes on the map.
                    return;
                }
            }
            State::Idle { hovering, selected } => match self.mouseover_card(ctx) {
                Some(idx) if ctx.input.left_mouse_button_pressed() => {
                    let cursor = ctx.canvas.get_cursor_in_screen_space().unwrap();
                    State::Dragging {
                        orig_idx: idx,
                        drag_from: cursor,
                        cursor_at: cursor,
                        new_idx: idx,
                    }
                }
                maybe_idx => {
                    if hovering != maybe_idx {
                        output.outcome = Outcome::Changed(self.label.clone());
                    }
                    State::Idle {
                        hovering: maybe_idx,
                        selected,
                    }
                }
            },
            State::Dragging {
                orig_idx,
                new_idx,
                cursor_at,
                drag_from,
            } => {
                if ctx.input.left_mouse_button_released() {
                    output.outcome =
                        Outcome::DragDropReleased(self.label.clone(), orig_idx, new_idx);
                    if orig_idx != new_idx {
                        let item = self.cards.remove(orig_idx);
                        self.cards.insert(new_idx, item);
                    }

                    State::Idle {
                        hovering: Some(new_idx),
                        selected: Some(new_idx),
                    }
                } else {
                    // TODO https://jqueryui.com/sortable/ only swaps once you cross the center of
                    // the new card
                    let updated_idx = self.mouseover_card(ctx).unwrap_or(new_idx);
                    if new_idx != updated_idx {
                        output.outcome = Outcome::Changed(format!("dragging {}", self.label));
                    }

                    State::Dragging {
                        orig_idx,
                        new_idx: updated_idx,
                        cursor_at: ctx.canvas.get_cursor_in_screen_space().unwrap_or(cursor_at),
                        drag_from,
                    }
                }
            }
        };

        if self.state != new_state {
            self.state = new_state;
            self.recalc_draw(ctx);
        }

        match self.state {
            State::Initial {
                hovering: Some(_), ..
            }
            | State::Idle {
                hovering: Some(_), ..
            } => ctx.cursor_grabbable(),
            State::Dragging { .. } => {
                ctx.cursor_grabbing();
                if matches!(output.outcome, Outcome::Nothing) {
                    output.outcome = Outcome::Focused(self.label.clone());
                }
            }
            _ => {}
        }
    }

    fn draw(&self, g: &mut GfxCtx) {
        g.redraw_at(self.top_left, &self.draw);
    }
}