vizia_core/views/
list.rs

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
362
use std::{collections::BTreeSet, ops::Deref, rc::Rc};

use crate::prelude::*;

/// Represents how items can be selected in a list.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum Selectable {
    #[default]
    /// Items in the list cannot be selected.
    None,
    /// A single item in the list can be selected.
    Single,
    /// Multiple items in the list can be selected simultaneously.
    Multi,
}

impl_res_simple!(Selectable);

/// Events used by the [List] view
pub enum ListEvent {
    /// Selects a list item with the given index.
    Select(usize),
    /// Selects the focused list item.
    SelectFocused,
    ///  Moves the focus to the next item in the list.
    FocusNext,
    ///  Moves the focus to the previous item in the list.
    FocusPrev,
    /// Deselects all items from the list
    ClearSelection,
}

/// A view for creating a list of items from a binding to an iteratable list.
#[derive(Lens)]
pub struct List {
    list_len: usize,
    selected: BTreeSet<usize>,
    selectable: Selectable,
    focused: Option<usize>,
    focus_visible: bool,
    selection_follows_focus: bool,
    horizontal: bool,
    on_select: Option<Box<dyn Fn(&mut EventContext, usize)>>,
}

impl List {
    /// Creates a new [List] view.
    pub fn new<L: Lens, T: 'static>(
        cx: &mut Context,
        list: L,
        item_content: impl 'static + Fn(&mut Context, usize, MapRef<L, T>),
    ) -> Handle<Self>
    where
        L::Target: Deref<Target = [T]> + Data,
    {
        Self::new_generic(
            cx,
            list,
            |list| list.len(),
            |list, index| &list[index],
            |_| true,
            item_content,
        )
    }

    /// Creates a new [List] view with a provided filter closure.
    pub fn new_filtered<L: Lens, T: 'static>(
        cx: &mut Context,
        list: L,
        filter: impl 'static + Clone + FnMut(&&T) -> bool,
        item_content: impl 'static + Fn(&mut Context, usize, MapRef<L, T>),
    ) -> Handle<Self>
    where
        L::Target: Deref<Target = [T]> + Data,
    {
        let f = filter.clone();
        Self::new_generic(
            cx,
            list,
            move |list| list.iter().filter(filter.clone()).count(),
            move |list, index| &list[index],
            f,
            item_content,
        )
    }

    /// Creates a new [List] view with a binding to the given lens and a template for constructing the list items.
    pub fn new_generic<L: Lens, T: 'static>(
        cx: &mut Context,
        list: L,
        list_len: impl 'static + Fn(&L::Target) -> usize,
        list_index: impl 'static + Clone + Fn(&L::Target, usize) -> &T,
        filter: impl 'static + Clone + FnMut(&&T) -> bool,
        item_content: impl 'static + Fn(&mut Context, usize, MapRef<L, T>),
    ) -> Handle<Self>
    where
        L::Target: Deref<Target = [T]> + Data,
    {
        let content = Rc::new(item_content);
        let num_items = list.map(list_len);
        Self {
            list_len: num_items.get(cx),
            selected: BTreeSet::default(),
            selectable: Selectable::None,
            focused: None,
            focus_visible: false,
            selection_follows_focus: false,
            horizontal: false,
            on_select: None,
        }
        .build(cx, move |cx| {
            Keymap::from(vec![
                (
                    KeyChord::new(Modifiers::empty(), Code::ArrowDown),
                    KeymapEntry::new("Focus Next", |cx| cx.emit(ListEvent::FocusNext)),
                ),
                (
                    KeyChord::new(Modifiers::empty(), Code::ArrowUp),
                    KeymapEntry::new("Focus Previous", |cx| cx.emit(ListEvent::FocusPrev)),
                ),
                (
                    KeyChord::new(Modifiers::empty(), Code::Space),
                    KeymapEntry::new("Select Focused", |cx| cx.emit(ListEvent::SelectFocused)),
                ),
                (
                    KeyChord::new(Modifiers::empty(), Code::Enter),
                    KeymapEntry::new("Select Focused", |cx| cx.emit(ListEvent::SelectFocused)),
                ),
            ])
            .build(cx);

            Binding::new(cx, List::horizontal, |cx, horizontal| {
                if horizontal.get(cx) {
                    cx.emit(KeymapEvent::RemoveAction(
                        KeyChord::new(Modifiers::empty(), Code::ArrowDown),
                        "Focus Next",
                    ));

                    cx.emit(KeymapEvent::RemoveAction(
                        KeyChord::new(Modifiers::empty(), Code::ArrowUp),
                        "Focus Previous",
                    ));

                    cx.emit(KeymapEvent::InsertAction(
                        KeyChord::new(Modifiers::empty(), Code::ArrowRight),
                        KeymapEntry::new("Focus Next", |cx| cx.emit(ListEvent::FocusNext)),
                    ));

                    cx.emit(KeymapEvent::InsertAction(
                        KeyChord::new(Modifiers::empty(), Code::ArrowLeft),
                        KeymapEntry::new("Focus Previous", |cx| cx.emit(ListEvent::FocusPrev)),
                    ));
                }
            });

            ScrollView::new(cx, move |cx| {
                // Bind to the list data
                Binding::new(cx, num_items, move |cx, _| {
                    // If the number of list items is different to the number of children of the ListView
                    // then remove and rebuild all the children

                    let mut f = filter.clone();
                    let ll = list
                        .get(cx)
                        .iter()
                        .enumerate()
                        .filter(|(_, v)| f(v))
                        .map(|(idx, _)| idx)
                        .collect::<Vec<_>>();

                    for index in ll.into_iter() {
                        let ll = list_index.clone();
                        let item = list.map_ref(move |list| ll(list, index));
                        let content = content.clone();
                        ListItem::new(cx, index, item, move |cx, index, item| {
                            content(cx, index, item);
                        });
                    }
                });
            });
        })
        .toggle_class("selectable", List::selectable.map(|s| *s != Selectable::None))
        .toggle_class("horizontal", List::horizontal)
        .navigable(true)
        .role(Role::List)
    }
}

impl View for List {
    fn element(&self) -> Option<&'static str> {
        Some("list")
    }

    fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
        event.take(|list_event, _| match list_event {
            ListEvent::Select(index) => {
                cx.focus();
                match self.selectable {
                    Selectable::Single => {
                        if self.selected.contains(&index) {
                            self.selected.clear();
                            self.focused = None;
                        } else {
                            self.selected.clear();
                            self.selected.insert(index);
                            self.focused = Some(index);
                            self.focus_visible = false;
                            if let Some(on_select) = &self.on_select {
                                on_select(cx, index);
                            }
                        }
                    }

                    Selectable::Multi => {
                        if self.selected.contains(&index) {
                            self.selected.remove(&index);
                            self.focused = None;
                        } else {
                            self.selected.insert(index);
                            self.focused = Some(index);
                            self.focus_visible = false;
                            if let Some(on_select) = &self.on_select {
                                on_select(cx, index);
                            }
                        }
                    }

                    Selectable::None => {}
                }
            }

            ListEvent::SelectFocused => {
                if let Some(focused) = &self.focused {
                    cx.emit(ListEvent::Select(*focused))
                }
            }

            ListEvent::ClearSelection => {
                self.selected.clear();
            }

            ListEvent::FocusNext => {
                if let Some(focused) = &mut self.focused {
                    *focused = focused.saturating_add(1);

                    if *focused >= self.list_len {
                        *focused = 0;
                    }
                } else {
                    self.focused = Some(0);
                }

                self.focus_visible = true;

                if self.selection_follows_focus {
                    cx.emit(ListEvent::SelectFocused);
                }
            }

            ListEvent::FocusPrev => {
                if let Some(focused) = &mut self.focused {
                    if *focused == 0 {
                        *focused = self.list_len;
                    }

                    *focused = focused.saturating_sub(1);
                } else {
                    self.focused = Some(self.list_len.saturating_sub(1));
                }

                self.focus_visible = true;

                if self.selection_follows_focus {
                    cx.emit(ListEvent::SelectFocused);
                }
            }
        })
    }
}

impl Handle<'_, List> {
    /// Sets the  selected items of the list. Takes a lens to a list of indices.
    pub fn selected<S: Lens>(self, selected: S) -> Self
    where
        S::Target: Deref<Target = [usize]> + Data,
    {
        self.bind(selected, |handle, s| {
            let ss = s.get(&handle).deref().to_vec();
            handle.modify(|list| {
                for idx in ss {
                    list.selected.insert(idx);
                    list.focused = Some(idx);
                }
            });
        })
    }

    /// Sets the callback triggered when a [ListItem] is selected.
    pub fn on_select<F>(self, callback: F) -> Self
    where
        F: 'static + Fn(&mut EventContext, usize),
    {
        self.modify(|list: &mut List| list.on_select = Some(Box::new(callback)))
    }

    /// Set the selectable state of the [List].
    pub fn selectable<U: Into<Selectable>>(self, selectable: impl Res<U>) -> Self {
        self.bind(selectable, |handle, selectable| {
            let s = selectable.get(&handle).into();
            handle.modify(|list: &mut List| list.selectable = s);
        })
    }

    /// Sets whether the selection should follow the focus.
    pub fn selection_follows_focus<U: Into<bool>>(self, flag: impl Res<U>) -> Self {
        self.bind(flag, |handle, selection_follows_focus| {
            let s = selection_follows_focus.get(&handle).into();
            handle.modify(|list: &mut List| list.selection_follows_focus = s);
        })
    }

    // todo: replace with orientation
    /// Sets the orientation of the list.
    pub fn horizontal<U: Into<bool>>(self, flag: impl Res<U>) -> Self {
        self.bind(flag, |handle, horizontal| {
            let s = horizontal.get(&handle).into();
            handle.modify(|list: &mut List| list.horizontal = s);
        })
    }
}

/// A view which represents a selectable item within a list.
pub struct ListItem {}

impl ListItem {
    /// Create a new [ListItem] view.
    pub fn new<L: Lens, T: 'static>(
        cx: &mut Context,
        index: usize,
        item: MapRef<L, T>,
        item_content: impl 'static + Fn(&mut Context, usize, MapRef<L, T>),
    ) -> Handle<Self> {
        Self {}
            .build(cx, move |cx| {
                item_content(cx, index, item);
            })
            .role(Role::ListItem)
            .checked(List::selected.map(move |selected| selected.contains(&index)))
            //.toggle_class("focused", List::focused.map(move |focused| *focused == Some(index)))
            .focused_with_visibility(
                List::focused.map(move |f| *f == Some(index)),
                List::focus_visible,
            )
            .on_press(move |cx| cx.emit(ListEvent::Select(index)))
    }
}

impl View for ListItem {
    fn element(&self) -> Option<&'static str> {
        Some("list-item")
    }
}