fyrox-ui 1.0.1

Extendable UI library
Documentation
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! List view is used to display lists with arbitrary items. It supports single-selection, and by default, it stacks the items
//! vertically.

#![warn(missing_docs)]

use crate::{
    border::BorderBuilder,
    brush::Brush,
    core::{
        color::Color, pool::Handle, reflect::prelude::*, type_traits::prelude::*, uuid_provider,
        variable::InheritableVariable, visitor::prelude::*,
    },
    decorator::{Decorator, DecoratorMessage},
    draw::{CommandTexture, Draw, DrawingContext},
    message::{KeyCode, UiMessage},
    scroll_viewer::{ScrollViewer, ScrollViewerBuilder, ScrollViewerMessage},
    stack_panel::StackPanelBuilder,
    style::{resource::StyleResourceExt, Style},
    widget::{Widget, WidgetBuilder, WidgetMessage},
    BuildContext, Control, Thickness, UiNode, UserInterface,
};
use fyrox_core::pool::{HandlesVecExtension, ObjectOrVariant};

use crate::message::MessageData;
use fyrox_graph::{
    constructor::{ConstructorProvider, GraphNodeConstructor},
    SceneGraph,
};

/// A set of messages that can be used to modify/fetch the state of a [`ListView`] widget at runtime.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ListViewMessage {
    /// A message, that is used to either fetch or modify current selection of a [`ListView`] widget.
    Selection(Vec<usize>),
    /// A message, that is used to set new items of a list view.
    Items(Vec<Handle<UiNode>>),
    /// A message, that is used to add an item to a list view.
    AddItem(Handle<UiNode>),
    /// A message, that is used to remove an item from a list view.
    RemoveItem(Handle<UiNode>),
    /// A message, that is used to bring an item into view.
    BringItemIntoView(Handle<UiNode>),
}
impl MessageData for ListViewMessage {}

impl ListViewMessage {
    /// Creates [`Self::AddItem`] message.
    pub fn add_item(handle: Handle<impl ObjectOrVariant<UiNode>>) -> Self {
        Self::AddItem(handle.to_base())
    }

    /// Creates [`Self::RemoveItem`] message.
    pub fn remove_item(handle: Handle<impl ObjectOrVariant<UiNode>>) -> Self {
        Self::RemoveItem(handle.to_base())
    }

    /// Creates [`Self::BringItemIntoView`] message.
    pub fn bring_item_into_view(handle: Handle<impl ObjectOrVariant<UiNode>>) -> Self {
        Self::BringItemIntoView(handle.to_base())
    }
}

/// List view is used to display lists with arbitrary items. It supports multiple selection and by
/// default, it stacks the items vertically (this can be changed by providing a custom panel for the
/// items, see the section below).
///
/// ## Example
///
/// [`ListView`] can be created using [`ListViewBuilder`]:
///
/// ```rust
/// # use fyrox_ui::{
/// #     core::pool::Handle, list_view::ListViewBuilder, text::TextBuilder, widget::WidgetBuilder,
/// #     BuildContext, UiNode,
/// # };
/// # use fyrox_ui::list_view::ListView;
/// #
/// fn create_list(ctx: &mut BuildContext) -> Handle<ListView> {
///     ListViewBuilder::new(WidgetBuilder::new())
///         .with_items(vec![
///             TextBuilder::new(WidgetBuilder::new())
///                 .with_text("Item0")
///                 .build(ctx)
///                 .to_base(),
///             TextBuilder::new(WidgetBuilder::new())
///                 .with_text("Item1")
///                 .build(ctx)
///                 .to_base(),
///         ])
///         .build(ctx)
/// }
/// ```
///
/// Keep in mind, that the items of the list view can be pretty much any other widget. They also don't have to be the same
/// type, you can mix any type of widgets.
///
/// ## Custom Items Panel
///
/// By default, list view creates inner [`crate::stack_panel::StackPanel`] to arrange its items. It is enough for most cases,
///  however, in rare cases you might want to use something else. For example, you could use [`crate::wrap_panel::WrapPanel`]
/// to create list view with selectable "tiles":
///
/// ```rust
/// # use fyrox_ui::{
/// #     core::pool::Handle, list_view::ListViewBuilder, text::TextBuilder, widget::WidgetBuilder,
/// #     wrap_panel::WrapPanelBuilder, BuildContext, UiNode,
/// # };
/// # use fyrox_ui::list_view::ListView;
///
/// fn create_list(ctx: &mut BuildContext) -> Handle<ListView> {
///     ListViewBuilder::new(WidgetBuilder::new())
///         // Using WrapPanel instead of StackPanel:
///         .with_items_panel(WrapPanelBuilder::new(WidgetBuilder::new()).build(ctx))
///         .with_items(vec![
///             TextBuilder::new(WidgetBuilder::new())
///                 .with_text("Item0")
///                 .build(ctx)
///                 .to_base(),
///             TextBuilder::new(WidgetBuilder::new())
///                 .with_text("Item1")
///                 .build(ctx)
///                 .to_base(),
///         ])
///         .build(ctx)
/// }
/// ```
///
/// ## Selection
///
/// List view supports any number of selected items (you can add items to the current selecting by
/// holding Ctrl key), you can change it at runtime by sending [`ListViewMessage::Selection`]
/// message with [`crate::message::MessageDirection::ToWidget`] like so:
///
/// ```rust
/// # use fyrox_ui::{
/// #     core::pool::Handle, list_view::ListViewMessage, message::MessageDirection, UiNode,
/// #     UserInterface,
/// # };
/// fn change_selection(my_list_view: Handle<UiNode>, ui: &UserInterface) {
///     ui.send(my_list_view, ListViewMessage::Selection(vec![1]));
/// }
/// ```
///
/// It is also possible to not have selected item at all, to do this you need to send an empty vector
/// as a selection.
///
/// To catch the moment when selection has changed (either by a user or by the [`ListViewMessage::Selection`],) you need
/// to listen to the same message but with opposite direction, like so:
///
/// ```rust
/// # use fyrox_ui::{
/// #     core::pool::Handle, list_view::ListViewMessage, message::MessageDirection,
/// #     message::UiMessage, UiNode,
/// # };
/// #
/// fn do_something(my_list_view: Handle<UiNode>, message: &UiMessage) {
///     if let Some(ListViewMessage::Selection(selection)) = message.data() {
///         if message.destination() == my_list_view
///             && message.direction() == MessageDirection::FromWidget
///         {
///             println!("New selection is: {:?}", selection);
///         }
///     }
/// }
/// ```
///
/// ## Adding/removing items
///
/// To change items of the list view, you can use the variety of following messages: [`ListViewMessage::AddItem`], [`ListViewMessage::RemoveItem`],
/// [`ListViewMessage::Items`]. To decide which one to use is very simple - if you adding/removing a few items, use [`ListViewMessage::AddItem`]
/// and [`ListViewMessage::RemoveItem`], otherwise use [`ListViewMessage::Items`], which changes the items at once.
///
/// ```rust
/// use fyrox_ui::{
///     core::pool::Handle, list_view::ListViewMessage, message::MessageDirection,
///     text::TextBuilder, widget::WidgetBuilder, UiNode, UserInterface,
/// };
/// fn change_items(my_list_view: Handle<UiNode>, ui: &mut UserInterface) {
///     let ctx = &mut ui.build_ctx();
///
///     // Build new items first.
///     let items = vec![
///         TextBuilder::new(WidgetBuilder::new())
///             .with_text("Item0")
///             .build(ctx)
///             .to_base(),
///         TextBuilder::new(WidgetBuilder::new())
///             .with_text("Item1")
///             .build(ctx)
///             .to_base(),
///     ];
///
///     // Then send the message with their handles to the list view.
///     ui.send(my_list_view, ListViewMessage::Items(items));
/// }
/// ```
///
/// ## Bringing a particular item into view
///
/// It is possible to bring a particular item into view, which is useful when you have hundreds or thousands of items, and you
/// want to bring only a particular item into view. It could be done by sending a [`ListViewMessage::BringItemIntoView`] message:
///
/// ```rust
/// # use fyrox_ui::{
/// #     core::pool::Handle, list_view::ListViewMessage, message::MessageDirection, UiNode,
/// #     UserInterface,
/// # };
/// fn bring_item_into_view(
///     my_list_view: Handle<UiNode>,
///     my_item: Handle<UiNode>,
///     ui: &UserInterface,
/// ) {
///     ui.send(my_list_view, ListViewMessage::BringItemIntoView(my_item));
/// }
/// ```
#[derive(Default, Clone, Visit, Reflect, Debug, ComponentProvider)]
#[visit(optional)]
#[reflect(derived_type = "UiNode")]
pub struct ListView {
    /// Base widget of the list view.
    pub widget: Widget,
    /// Current selection.
    pub selection: Vec<usize>,
    /// An array of handle of item containers, which wraps the actual items.
    pub item_containers: InheritableVariable<Vec<Handle<ListViewItem>>>,
    /// Current panel widget that is used to arrange the items.
    pub panel: InheritableVariable<Handle<UiNode>>,
    /// Current items of the list view.
    pub items: InheritableVariable<Vec<Handle<UiNode>>>,
    /// Current scroll viewer instance that is used to provide scrolling functionality, when items does
    /// not fit in the view entirely.
    pub scroll_viewer: InheritableVariable<Handle<ScrollViewer>>,
}

impl ConstructorProvider<UiNode, UserInterface> for ListView {
    fn constructor() -> GraphNodeConstructor<UiNode, UserInterface> {
        GraphNodeConstructor::new::<Self>()
            .with_variant("List View", |ui| {
                ListViewBuilder::new(WidgetBuilder::new().with_name("List View"))
                    .build(&mut ui.build_ctx())
                    .to_base()
                    .into()
            })
            .with_group("Input")
    }
}

crate::define_widget_deref!(ListView);

impl ListView {
    /// Returns a slice with current items.
    pub fn items(&self) -> &[Handle<UiNode>] {
        &self.items
    }

    fn fix_selection(&self, ui: &UserInterface) {
        // Check if the current selection is out-of-bounds.
        let mut fixed_selection = Vec::with_capacity(self.selection.len());

        for &selected_index in self.selection.iter() {
            if selected_index >= self.items.len() {
                if !self.items.is_empty() {
                    fixed_selection.push(self.items.len() - 1);
                }
            } else {
                fixed_selection.push(selected_index);
            }
        }

        if self.selection != fixed_selection {
            ui.send(self.handle, ListViewMessage::Selection(fixed_selection));
        }
    }

    fn largest_selection_index(&self) -> Option<usize> {
        self.selection.iter().max().cloned()
    }

    fn smallest_selection_index(&self) -> Option<usize> {
        self.selection.iter().min().cloned()
    }

    fn sync_decorators(&self, ui: &UserInterface) {
        for (i, &container) in self.item_containers.iter().enumerate() {
            let select = self.selection.contains(&i);
            if let Ok(container) = ui.try_get(container) {
                let mut stack = container.children().to_vec();
                while let Some(handle) = stack.pop() {
                    let node = ui.node(handle);

                    if node.cast::<ListView>().is_some() {
                        // Do nothing.
                    } else if node.cast::<Decorator>().is_some() {
                        ui.send(handle, DecoratorMessage::Select(select));
                    } else {
                        stack.extend_from_slice(node.children())
                    }
                }
            }
        }
    }
}

/// A wrapper for list view items, that is used to add selection functionality to arbitrary items.
#[derive(Default, Clone, Visit, Reflect, Debug, ComponentProvider)]
#[reflect(derived_type = "UiNode")]
pub struct ListViewItem {
    /// Base widget of the list view item.
    pub widget: Widget,
}

impl ConstructorProvider<UiNode, UserInterface> for ListViewItem {
    fn constructor() -> GraphNodeConstructor<UiNode, UserInterface> {
        GraphNodeConstructor::new::<Self>()
            .with_variant("List View Item", |ui: &mut UserInterface| {
                let node = UiNode::new(ListViewItem {
                    widget: WidgetBuilder::new()
                        .with_name("List View Item")
                        .build(&ui.build_ctx()),
                });
                ui.add_node(node).into()
            })
            .with_group("Input")
    }
}

crate::define_widget_deref!(ListViewItem);

uuid_provider!(ListViewItem = "02f21415-5843-42f5-a3e4-b4a21e7739ad");

impl Control for ListViewItem {
    fn draw(&self, drawing_context: &mut DrawingContext) {
        // Emit transparent geometry so item container can be picked by hit test.
        drawing_context.push_rect_filled(&self.widget.bounding_rect(), None);
        drawing_context.commit(
            self.clip_bounds(),
            Brush::Solid(Color::TRANSPARENT),
            CommandTexture::None,
            &self.material,
            None,
        );
    }

    fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
        self.widget.handle_routed_message(ui, message);

        let parent_list_view =
            self.find_by_criteria_up(ui, |node| node.cast::<ListView>().is_some());

        if let Some(WidgetMessage::MouseUp { .. }) = message.data::<WidgetMessage>() {
            if !message.handled() {
                let list_view = ui
                    .node(parent_list_view)
                    .cast::<ListView>()
                    .expect("Parent of ListViewItem must be ListView!");

                let self_index = list_view
                    .item_containers
                    .iter()
                    .position(|c| self.handle == *c)
                    .expect("ListViewItem must be used as a child of ListView");

                let new_selection = if ui.keyboard_modifiers.control {
                    let mut selection = list_view.selection.clone();
                    selection.push(self_index);
                    selection
                } else {
                    vec![self_index]
                };

                // Explicitly set selection on parent items control. This will send
                // SelectionChanged message and all items will react.
                ui.send(parent_list_view, ListViewMessage::Selection(new_selection));
                message.set_handled(true);
            }
        }
    }
}

uuid_provider!(ListView = "5832a643-5bf9-4d84-8358-b4c45bb440e8");

impl Control for ListView {
    fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
        self.widget.handle_routed_message(ui, message);

        if let Some(msg) = message.data_for::<ListViewMessage>(self.handle()) {
            match msg {
                ListViewMessage::Items(items) => {
                    // Generate new items.
                    let item_containers = generate_item_containers(&mut ui.build_ctx(), items);

                    ui.send(
                        *self.panel,
                        WidgetMessage::ReplaceChildren(item_containers.clone().to_base()),
                    );

                    self.item_containers
                        .set_value_and_mark_modified(item_containers);
                    self.items.set_value_and_mark_modified(items.clone());

                    self.fix_selection(ui);
                    self.sync_decorators(ui);
                }
                &ListViewMessage::AddItem(item) => {
                    let item_container = generate_item_container(&mut ui.build_ctx(), item);

                    ui.send(item_container, WidgetMessage::LinkWith(*self.panel));

                    self.item_containers.push(item_container);
                    self.items.push(item);
                }
                ListViewMessage::Selection(selection) => {
                    if &self.selection != selection {
                        self.selection.clone_from(selection);
                        self.sync_decorators(ui);
                        ui.try_send_response(message);
                    }
                }
                &ListViewMessage::RemoveItem(item) => {
                    if let Some(item_position) = self.items.iter().position(|i| *i == item) {
                        self.items.remove(item_position);
                        self.item_containers.remove(item_position);

                        let container = ui.node(item).parent();

                        ui.send(container, WidgetMessage::Remove);

                        self.fix_selection(ui);
                        self.sync_decorators(ui);
                    }
                }
                &ListViewMessage::BringItemIntoView(item) => {
                    if self.items.contains(&item) {
                        ui.send(
                            *self.scroll_viewer,
                            ScrollViewerMessage::BringIntoView(item),
                        );
                    }
                }
            }
        } else if let Some(WidgetMessage::KeyDown(key_code)) = message.data() {
            if !message.handled() {
                let new_selection = if *key_code == KeyCode::ArrowDown {
                    match self.largest_selection_index() {
                        Some(i) => Some(i.saturating_add(1) % self.items.len()),
                        None => {
                            if self.items.is_empty() {
                                None
                            } else {
                                Some(0)
                            }
                        }
                    }
                } else if *key_code == KeyCode::ArrowUp {
                    match self.smallest_selection_index() {
                        Some(i) => {
                            let mut index = (i as isize).saturating_sub(1);
                            let count = self.items.len() as isize;
                            if index < 0 {
                                index += count;
                            }
                            Some((index % count) as usize)
                        }
                        None => {
                            if self.items.is_empty() {
                                None
                            } else {
                                Some(0)
                            }
                        }
                    }
                } else {
                    None
                };

                if let Some(new_selection) = new_selection {
                    ui.send(self.handle, ListViewMessage::Selection(vec![new_selection]));
                    ui.send(
                        self.handle,
                        ListViewMessage::BringItemIntoView(self.items[new_selection]),
                    );

                    message.set_handled(true);
                }
            }
        }
    }
}

/// List view builder is used to create [`ListView`] widget instances and add them to a user interface.
pub struct ListViewBuilder {
    widget_builder: WidgetBuilder,
    items: Vec<Handle<UiNode>>,
    panel: Option<Handle<UiNode>>,
    scroll_viewer: Option<Handle<ScrollViewer>>,
    selection: Vec<usize>,
}

impl ListViewBuilder {
    /// Creates new list view builder.
    pub fn new(widget_builder: WidgetBuilder) -> Self {
        Self {
            widget_builder,
            items: Vec::new(),
            panel: None,
            scroll_viewer: None,
            selection: Default::default(),
        }
    }

    /// Sets an array of handle of desired items for the list view.
    pub fn with_items(mut self, items: Vec<Handle<UiNode>>) -> Self {
        self.items = items;
        self
    }

    /// Sets the desired item panel that will be used to arrange the items.
    pub fn with_items_panel(mut self, panel: Handle<impl ObjectOrVariant<UiNode>>) -> Self {
        self.panel = Some(panel.to_base());
        self
    }

    /// Sets the desired scroll viewer.
    pub fn with_scroll_viewer(mut self, sv: Handle<ScrollViewer>) -> Self {
        self.scroll_viewer = Some(sv);
        self
    }

    /// Sets the desired selected items.
    pub fn with_selection(mut self, items: Vec<usize>) -> Self {
        self.selection = items;
        self
    }

    /// Finishes list view building and adds it to the user interface.
    pub fn build(self, ctx: &mut BuildContext) -> Handle<ListView> {
        let item_containers = generate_item_containers(ctx, &self.items);

        // Sync the decorators to the actual state of items.
        for (i, &container) in item_containers.iter().enumerate() {
            let select = self.selection.contains(&i);
            if let Ok(container) = ctx.inner().try_get(container) {
                let mut stack = container.children().to_vec();
                while let Some(handle) = stack.pop() {
                    let node = &mut ctx[handle];
                    if node.cast::<ListView>().is_some() {
                        // Do nothing.
                    } else if let Some(decorator) = node.cast_mut::<Decorator>() {
                        decorator.is_selected.set_value_and_mark_modified(select);
                        if select {
                            decorator.background = (*decorator.selected_brush).clone().into();
                        } else {
                            decorator.background = (*decorator.normal_brush).clone().into();
                        }
                    } else {
                        stack.extend_from_slice(node.children())
                    }
                }
            }
        }

        let panel = self.panel.unwrap_or_else(|| {
            StackPanelBuilder::new(WidgetBuilder::new())
                .build(ctx)
                .to_base()
        });

        for &item_container in item_containers.iter() {
            ctx.link(item_container, panel);
        }

        let style = &ctx.style;
        let back = BorderBuilder::new(
            WidgetBuilder::new()
                .with_background(style.property(Style::BRUSH_DARK))
                .with_foreground(style.property(Style::BRUSH_LIGHT)),
        )
        .with_stroke_thickness(Thickness::uniform(1.0).into())
        .build(ctx);

        let scroll_viewer = self.scroll_viewer.unwrap_or_else(|| {
            ScrollViewerBuilder::new(WidgetBuilder::new().with_margin(Thickness::uniform(0.0)))
                .build(ctx)
        });
        let scroll_viewer_ref = &mut ctx[scroll_viewer];
        scroll_viewer_ref.content = panel;
        let content_presenter = scroll_viewer_ref.scroll_panel;
        ctx.link(panel, content_presenter);

        ctx.link(scroll_viewer, back);

        let list_box = ListView {
            widget: self
                .widget_builder
                .with_accepts_input(true)
                .with_child(back)
                .build(ctx),
            selection: self.selection,
            item_containers: item_containers.into(),
            items: self.items.into(),
            panel: panel.into(),
            scroll_viewer: scroll_viewer.into(),
        };

        ctx.add(list_box)
    }
}

fn generate_item_container(ctx: &mut BuildContext, item: Handle<UiNode>) -> Handle<ListViewItem> {
    let item = ListViewItem {
        widget: WidgetBuilder::new().with_child(item).build(ctx),
    };

    ctx.add(item)
}

fn generate_item_containers(
    ctx: &mut BuildContext,
    items: &[Handle<UiNode>],
) -> Vec<Handle<ListViewItem>> {
    items
        .iter()
        .map(|&item| generate_item_container(ctx, item))
        .collect()
}

#[cfg(test)]
mod test {
    use crate::list_view::ListViewBuilder;
    use crate::{test::test_widget_deletion, widget::WidgetBuilder};

    #[test]
    fn test_deletion() {
        test_widget_deletion(|ctx| ListViewBuilder::new(WidgetBuilder::new()).build(ctx));
    }
}