vizia_core 0.4.0

Core components of vizia
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
use std::{
    collections::BTreeSet,
    ops::{Deref, Range},
};

use crate::prelude::*;

/// A view for creating a list of items from a binding to an iteratable list. Rather than creating a view for each item, items are recycled in the list.
pub struct VirtualList {
    /// Whether the scrollbar should scroll to the cursor when pressed.
    scroll_to_cursor: Signal<bool>,
    /// Callback that is called when the list is scrolled.
    on_scroll: Option<Box<dyn Fn(&mut EventContext, f32, f32) + Send + Sync>>,
    /// The number of items in the list.
    num_items: Signal<usize>,
    /// The height of each item in the list.
    item_height: f32,
    /// The range of visible items in the list.
    visible_range: Signal<Range<usize>>,
    /// The horizontal scroll position of the list.
    scroll_x: Signal<f32>,
    /// The vertical scroll position of the list.
    scroll_y: Signal<f32>,
    /// Whether the horizontal scrollbar should be visible.
    show_horizontal_scrollbar: Signal<bool>,
    /// Whether the vertical scrollbar should be visible.
    show_vertical_scrollbar: Signal<bool>,
    /// The set of selected items in the list.
    selection: Signal<BTreeSet<usize>>,
    /// The selectable state of the list.
    selectable: Signal<Selectable>,
    /// The index of the currently focused item in the list.
    focused: Signal<Option<usize>>,
    /// Whether the selection should follow the focus.
    selection_follows_focus: Signal<bool>,
    /// Callback that is called when an item is selected.
    on_select: Option<Box<dyn Fn(&mut EventContext, usize)>>,
}

impl VirtualList {
    fn evaluate_index(index: usize, start: usize, end: usize) -> usize {
        match end - start {
            0 => 0,
            len => start + (len - (start % len) + index) % len,
        }
    }

    fn recalc(&self, cx: &mut EventContext) {
        let num_items = self.num_items.get();
        if num_items == 0 {
            self.visible_range.set_if_changed(0..0);
            return;
        }

        let current = cx.current();
        let current_height = cx.cache.get_height(current);
        if current_height == f32::MAX {
            return;
        }

        let item_height = self.item_height;
        let total_height = item_height * (num_items as f32);
        let visible_height = current_height / cx.scale_factor();

        let mut num_visible_items = (visible_height / item_height).ceil();
        num_visible_items += 1.0; // To account for partially-visible items.

        let visible_items_height = item_height * num_visible_items;
        let empty_height = (total_height - visible_items_height).max(0.0);

        // The pixel offsets within the container to the visible area.
        let visible_start = empty_height * self.scroll_y.get();
        let visible_end = visible_start + visible_items_height;

        // The indices of the first and last item of the visible area.
        let mut start_index = (visible_start / item_height).trunc() as usize;
        let mut end_index = 1 + (visible_end / item_height).trunc() as usize;

        // Ensure we always have (num_visible_items + 1) items when possible
        let desired_range_size = (num_visible_items as usize) + 1;
        end_index = end_index.min(num_items);

        let current_range_size = end_index.saturating_sub(start_index);

        if current_range_size < desired_range_size {
            match end_index == num_items {
                // Try to extend backwards if we're at the end of the list
                true => {
                    start_index =
                        start_index.saturating_sub(desired_range_size - current_range_size);
                }
                // Try to extend forwards if we have room
                false if end_index < num_items => {
                    end_index = (start_index + desired_range_size).min(num_items);
                }
                _ => {}
            }
        }

        self.visible_range.set_if_changed(start_index..end_index);
    }
}

impl VirtualList {
    /// Creates a new [VirtualList] view.
    pub fn new<V: View, S, L, T>(
        cx: &mut Context,
        list: S,
        item_height: f32,
        item_content: impl 'static + Copy + Fn(&mut Context, usize, Memo<T>) -> Handle<V>,
    ) -> Handle<Self>
    where
        S: Res<L> + 'static,
        L: Deref<Target = [T]> + Clone + 'static,
        T: Clone + PartialEq + 'static,
    {
        Self::new_generic(
            cx,
            list,
            |list| list.len(),
            |list, index| list[index].clone(),
            item_height,
            item_content,
        )
    }

    /// Creates a new [VirtualList] view with a binding to the given source and a template for constructing the list items.
    pub fn new_generic<V: View, S, L, T>(
        cx: &mut Context,
        list: S,
        list_len: impl 'static + Fn(&L) -> usize,
        list_index: impl 'static + Copy + Fn(&L, usize) -> T,
        item_height: f32,
        item_content: impl 'static + Copy + Fn(&mut Context, usize, Memo<T>) -> Handle<V>,
    ) -> Handle<Self>
    where
        S: Res<L> + 'static,
        L: Clone + 'static,
        T: Clone + PartialEq + 'static,
    {
        let list = list.to_signal(cx);
        let num_items = list.map(list_len).to_signal(cx);
        let visible_range = Signal::new(0..0);
        let scroll_x = Signal::new(0.0);
        let scroll_y = Signal::new(0.0);
        let show_horizontal_scrollbar = Signal::new(false);
        let show_vertical_scrollbar = Signal::new(true);
        let selection = Signal::new(BTreeSet::default());
        let selectable = Signal::new(Selectable::None);
        let focused = Signal::new(None);
        let selection_follows_focus = Signal::new(false);
        let scroll_to_cursor = Signal::new(true);

        Self {
            scroll_to_cursor,
            on_scroll: None,
            num_items,
            item_height,
            visible_range,
            scroll_x,
            scroll_y,
            show_horizontal_scrollbar,
            show_vertical_scrollbar,
            selection,
            selectable,
            focused,
            selection_follows_focus,
            on_select: None,
        }
        .build(cx, |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);

            ScrollView::new(cx, move |cx| {
                Binding::new(cx, num_items, move |cx| {
                    let num_items = num_items.get();
                    cx.emit(ScrollEvent::SetY(0.0));
                    // The ScrollView contains a VStack which is sized to the total height
                    // needed to fit all items. This ensures we have a correct scroll bar.
                    VStack::new(cx, |cx| {
                        // Within the VStack we create a view for each visible item.
                        // This binding ensures the amount of views stay up to date.
                        let num_visible_items = visible_range.map(Range::len);
                        Binding::new(cx, num_visible_items, move |cx| {
                            for i in 0..num_visible_items.get().min(num_items) {
                                // Each item of the range maps to an index into the backing list.
                                // As we scroll the index may change, representing an item going in/out of visibility.
                                // Wrap `item_content` in a binding to said index, so it rebuilds only when necessary.
                                let item_index = visible_range.map(move |range| {
                                    Self::evaluate_index(i, range.start, range.end)
                                });
                                Binding::new(cx, item_index, move |cx| {
                                    let index = item_index.get();
                                    let item = list.map(move |list| list_index(list, index));

                                    ListItem::new(
                                        cx,
                                        index,
                                        item,
                                        selection,
                                        focused,
                                        move |cx, index, item| {
                                            item_content(cx, index, item).height(Percentage(100.0));
                                        },
                                    )
                                    .min_width(Auto)
                                    .height(Pixels(item_height))
                                    .position_type(PositionType::Absolute)
                                    .bind(
                                        item_index,
                                        move |handle| {
                                            let index = item_index.get();
                                            handle.top(Pixels(index as f32 * item_height));
                                        },
                                    );
                                });
                            }
                        })
                    })
                    .height(Pixels(num_items as f32 * item_height));
                })
            })
            .show_horizontal_scrollbar(show_horizontal_scrollbar)
            .show_vertical_scrollbar(show_vertical_scrollbar)
            .scroll_to_cursor(scroll_to_cursor)
            .scroll_x(scroll_x)
            .scroll_y(scroll_y)
            .on_scroll(|cx, x, y| {
                if y.is_finite() && x.is_finite() {
                    cx.emit(ListEvent::Scroll(x, y));
                }
            });
        })
        .toggle_class("selectable", selectable.map(|s| *s != Selectable::None))
        .navigable(true)
        .role(Role::ListBox)
    }
}

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

    fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
        event.take(|list_event, meta| match list_event {
            ListEvent::Select(index) => {
                cx.focus();
                let selectable = self.selectable.get();
                let mut selection = self.selection.get();
                let mut focused = self.focused.get();

                match selectable {
                    Selectable::Single => {
                        if selection.contains(&index) {
                            selection.clear();
                            focused = None;
                        } else {
                            selection.clear();
                            selection.insert(index);
                            focused = Some(index);
                            if let Some(on_select) = &self.on_select {
                                on_select(cx, index);
                            }
                        }
                    }

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

                    Selectable::None => {}
                }

                self.selection.set(selection);
                self.focused.set(focused);

                meta.consume();
            }

            ListEvent::SelectFocused => {
                if let Some(focused) = self.focused.get() {
                    cx.emit(ListEvent::Select(focused))
                }
                meta.consume();
            }

            ListEvent::ClearSelection => {
                self.selection.set(BTreeSet::default());
                meta.consume();
            }

            ListEvent::FocusNext => {
                let mut focused = self.focused.get();
                let num_items = self.num_items.get();
                if let Some(f) = &mut focused {
                    if *f < num_items.saturating_sub(1) {
                        *f = f.saturating_add(1);
                        if self.selection_follows_focus.get() {
                            cx.emit(ListEvent::SelectFocused);
                        }
                    }
                } else {
                    focused = Some(0);
                    if self.selection_follows_focus.get() {
                        cx.emit(ListEvent::SelectFocused);
                    }
                }

                self.focused.set(focused);

                meta.consume();
            }

            ListEvent::FocusPrev => {
                let mut focused = self.focused.get();
                let num_items = self.num_items.get();
                if let Some(f) = &mut focused {
                    if *f > 0 {
                        *f = f.saturating_sub(1);
                        if self.selection_follows_focus.get() {
                            cx.emit(ListEvent::SelectFocused);
                        }
                    }
                } else {
                    focused = Some(num_items.saturating_sub(1));
                    if self.selection_follows_focus.get() {
                        cx.emit(ListEvent::SelectFocused);
                    }
                }

                self.focused.set(focused);

                meta.consume();
            }

            ListEvent::Scroll(x, y) => {
                self.scroll_x.set(x);
                self.scroll_y.set(y);

                self.recalc(cx);

                if let Some(callback) = &self.on_scroll {
                    (callback)(cx, x, y);
                }

                meta.consume();
            }
        });

        event.map(|window_event, _| match window_event {
            WindowEvent::GeometryChanged(geo) => {
                if geo.intersects(GeoChanged::WIDTH_CHANGED | GeoChanged::HEIGHT_CHANGED) {
                    self.recalc(cx);
                }
            }

            _ => {}
        });
    }
}

impl Handle<'_, VirtualList> {
    /// Sets the selected items of the list from a signal of indices.
    pub fn selection<R>(self, selection: impl Res<R> + 'static) -> Self
    where
        R: Deref<Target = [usize]> + Clone + 'static,
    {
        let selection = selection.to_signal(self.cx);
        self.bind(selection, move |handle| {
            selection.with(|selected_indices| {
                handle.modify(|list| {
                    let mut selection = BTreeSet::default();
                    let mut focused = None;
                    for idx in selected_indices.deref().iter().copied() {
                        selection.insert(idx);
                        focused = Some(idx);
                    }
                    list.selection.set(selection);
                    list.focused.set(focused);
                });
            });
        })
    }

    /// 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| list.on_select = Some(Box::new(callback)))
    }

    /// Set the selectable state of the [List].
    pub fn selectable<U: Into<Selectable> + Clone + 'static>(
        self,
        selectable: impl Res<U> + 'static,
    ) -> Self {
        let selectable = selectable.to_signal(self.cx);
        self.bind(selectable, move |handle| {
            let selectable = selectable.get();
            let s = selectable.into();
            handle.modify(|list| list.selectable.set(s));
        })
    }

    /// Sets whether the selection should follow the focus.
    pub fn selection_follows_focus<U: Into<bool> + Clone + 'static>(
        self,
        flag: impl Res<U> + 'static,
    ) -> Self {
        let flag = flag.to_signal(self.cx);
        self.bind(flag, move |handle| {
            let selection_follows_focus = flag.get();
            let s = selection_follows_focus.into();
            handle.modify(|list| list.selection_follows_focus.set(s));
        })
    }

    /// Sets whether the scrollbar should move to the cursor when pressed.
    pub fn scroll_to_cursor(self, flag: bool) -> Self {
        self.modify(|virtual_list: &mut VirtualList| {
            virtual_list.scroll_to_cursor.set(flag);
        })
    }

    /// Sets a callback which will be called when a scrollview is scrolled, either with the mouse wheel, touchpad, or using the scroll bars.
    pub fn on_scroll(
        self,
        callback: impl Fn(&mut EventContext, f32, f32) + 'static + Send + Sync,
    ) -> Self {
        self.modify(|list| list.on_scroll = Some(Box::new(callback)))
    }

    /// Set the horizontal scroll position of the [ScrollView]. Accepts a value or lens to an 'f32' between 0 and 1.
    pub fn scroll_x(self, scrollx: impl Res<f32> + 'static) -> Self {
        let scrollx = scrollx.to_signal(self.cx);
        self.bind(scrollx, move |handle| {
            let sx = scrollx.get();
            handle.modify(|list| list.scroll_x.set(sx));
        })
    }

    /// Set the vertical scroll position of the [ScrollView]. Accepts a value or lens to an 'f32' between 0 and 1.
    pub fn scroll_y(self, scrollx: impl Res<f32> + 'static) -> Self {
        let scrollx = scrollx.to_signal(self.cx);
        self.bind(scrollx, move |handle| {
            let sy = scrollx.get();
            handle.modify(|list| list.scroll_y.set(sy));
        })
    }

    /// Sets whether the horizontal scrollbar should be visible.
    pub fn show_horizontal_scrollbar(self, flag: impl Res<bool> + 'static) -> Self {
        let flag = flag.to_signal(self.cx);
        self.bind(flag, move |handle| {
            let s = flag.get();
            handle.modify(|list| list.show_horizontal_scrollbar.set(s));
        })
    }

    /// Sets whether the vertical scrollbar should be visible.
    pub fn show_vertical_scrollbar(self, flag: impl Res<bool> + 'static) -> Self {
        let flag = flag.to_signal(self.cx);
        self.bind(flag, move |handle| {
            let s = flag.get();
            handle.modify(|list| list.show_vertical_scrollbar.set(s));
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn evaluate_indices(range: Range<usize>) -> Vec<usize> {
        (0..range.len())
            .map(|index| VirtualList::evaluate_index(index, range.start, range.end))
            .collect()
    }

    #[test]
    fn test_evaluate_index() {
        // Move forward by 0
        assert_eq!(evaluate_indices(0..4), [0, 1, 2, 3]);
        // Move forward by 1
        assert_eq!(evaluate_indices(1..5), [4, 1, 2, 3]);
        // Move forward by 2
        assert_eq!(evaluate_indices(2..6), [4, 5, 2, 3]);
        // Move forward by 3
        assert_eq!(evaluate_indices(3..7), [4, 5, 6, 3]);
        // Move forward by 4
        assert_eq!(evaluate_indices(4..8), [4, 5, 6, 7]);
        // Move forward by 5
        assert_eq!(evaluate_indices(5..9), [8, 5, 6, 7]);
        // Move forward by 6
        assert_eq!(evaluate_indices(6..10), [8, 9, 6, 7]);
        // Move forward by 7
        assert_eq!(evaluate_indices(7..11), [8, 9, 10, 7]);
        // Move forward by 8
        assert_eq!(evaluate_indices(8..12), [8, 9, 10, 11]);
        // Move forward by 9
        assert_eq!(evaluate_indices(9..13), [12, 9, 10, 11]);
    }
}