# ui/uilistview (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/ui/uilistview/

Recycling list view. (UIListView of the original ui/uilistview.js)
- Takes only the item count, creates real nodes only for the visible range (including buffer slots before and after), and recovers and reuses nodes that leave it.
  Even with hundreds ~ thousands of items, the node count stays at one screenful. Item contents are filled in code with set_bind_item_event. (data driven)
- When it gets near the end, it sends the set_reach_end_event notification once. (infinite scroll / load more) It is rearmed when set_item_count increases the item count.
- As in the original, it attaches to the same node as the scroll view. If the node has no scroll view, a UIScrollView is attached along with it on attach. (original require)
  On a node with a UISnapScrollView, it uses that embedded view. (where the original getComponents(UIScrollView) also catches subclasses)
  The scroll view is attached first and ticks first, so this widget picks the visible range with that frame's scroll offset.
- Usage:
  ```text
    let list_view = node_tree.add_component(list_id, UIListView::new()).expect("list view");
    list_view.set_create_item_event(Box::new(|tree: &mut NodeTree| { let item_id = tree.create_node("item"); ...; item_id }));
    list_view.set_bind_item_event(Box::new(|tree: &mut NodeTree, item_id: NodeId, item_index: usize| { ... }));
    list_view.set_item_count(500);
  ```
- Differences from the original:
  - set_template_node serializes the template node with UIDocument and clones it per item as in the original. The original records every component through reflection, but
    the Rust version clones only types registered with UIDocument. (for game components, pass a UIDocument with registration done to set_template_node_with_document)
  - It also takes a function that creates item nodes (set_create_item_event). (a general feature that appeared first in the Rust version, also added to the original) Created nodes are moved under the content node as children.
    If the item size is not set (0), it reads the progress axis content_size of the first created item node, like the original reads the template size.
  - The bind event takes (tree, item node, item index). The end notification takes the list view and the context.
  - set_item_count, set_item_size, set_spacing, refresh set the values and update the scroll area and rebind on the next tick.
    (the original does it on the spot. the scroll view on the same node cannot be reached while scene code is holding this widget)
  - Active items are held in insertion order like the original Map.

## UIListViewCreateItemEvent (type)

Item node creation function. (takes the tree and returns a new item node. in place of the original template cloning)

```rust
pub type UIListViewCreateItemEvent = Box<dyn FnMut(&mut NodeTree) -> NodeId>
```

## UIListViewBindItemEvent (type)

Bind event. (tree, item node, item index)

```rust
pub type UIListViewBindItemEvent = Box<dyn FnMut(&mut NodeTree, NodeId, usize)>
```

## UIListViewReachEndEvent (type)

End notification. (takes the list view and the context)

```rust
pub type UIListViewReachEndEvent = Box<dyn FnMut(&mut UIListView, &mut ComponentContext)>
```

## UIListView (struct) (Default, Component)

Recycling list view.
- Keeps only the items visible at the offset of the scroll view on the same node (a UIScrollView is attached along with it on attach if there is none) as nodes under the content node.
- Does nothing in tick if there is no item node creation function (set_create_item_event or set_template_node).

Example: Create nodes only for the five visible items out of 500

```rust
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, NodeId, NodeTree, Pivot, UIListView, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let list_id = node_tree.create_child(root_id, "list");
node_tree[list_id].set_pivot(Pivot::TOP_LEFT);
node_tree[list_id].set_content_size(Vector2::create(200.0, 100.0));
let bound_index_list = Rc::new(RefCell::new(Vec::new()));
let bound_index_recorder = bound_index_list.clone();

let list_view = node_tree.add_component(list_id, UIListView::new()).expect("list view");
list_view.set_create_item_event(Box::new(|tree: &mut NodeTree| {
	let item_id = tree.create_node("item");
	tree[item_id].set_pivot(Pivot::TOP_LEFT);
	tree[item_id].set_content_size(Vector2::create(200.0, 30.0));
	item_id
}));
list_view.set_bind_item_event(Box::new(move |_tree: &mut NodeTree, _item_id: NodeId, item_index: usize| {
	bound_index_recorder.borrow_mut().push(item_index);
}));
list_view.set_item_count(500);
node_tree.tick(&engine, 0.016);

let list_view = node_tree[list_id].get_component::<UIListView>().expect("list view");
assert_eq!(list_view.get_item_size(), 30.0);
assert_eq!(list_view.get_active_item_count(), 5);
assert_eq!(*bound_index_list.borrow(), vec![0, 1, 2, 3, 4]);
let fourth_id = list_view.get_item_node(4).expect("item 4");
assert_eq!(node_tree[fourth_id].get_local_position(), Vector2::create(0.0, 120.0));
assert!(list_view.get_item_node(100).is_none());
```

- `pub fn new() -> UIListView` (constructor, since 0.3.2): Constructor. (vertical, 1 buffer slot, end notification distance 120 pixels)
  - Use node_tree.add_component to attach it to a node. (a UIScrollView is attached along with it if the node has no scroll view)
  - returns UIListView: New list view with 0 items, item size 0 (read from the first created item), and spacing 0.
- `pub fn set_create_item_event(&mut self, create_item_event: UIListViewCreateItemEvent)` (method, since 0.3.2): Sets the item node creation function. (in place of the original setTemplateNode)
  - `create_item_event` UIListViewCreateItemEvent: Function that builds a new item node in the tree and returns it. The returned node is moved under the content node as a child. Returning a node not in the tree stops item creation for that tick.
- `pub fn set_template_node(&mut self, node_tree: &mut NodeTree, template_node_id: NodeId)` (method, since 0.4.0): Sets the template node. (serializes it with UIDocument and clones it per item, the template is turned off. if the item size is 0, uses the template size. original setTemplateNode)
  - Clones only engine types registered with UIDocument. For a template with game components, use set_template_node_with_document.
  - This widget must be taken out of the tree to call it, so scene code calls it inside node_tree.with_component_mut.
  - `node_tree` &mut NodeTree: Tree that holds the template node.
  - `template_node_id` NodeId: Template node to clone. Does nothing if the node does not exist.

  Example: Clone the template node per item

  ```rust
  use vanilla::{Engine, EngineConfiguration, NodeTree, Pivot, UIListView, Vector2};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let list_id = node_tree.create_child(root_id, "list");
  node_tree[list_id].set_pivot(Pivot::TOP_LEFT);
  node_tree[list_id].set_content_size(Vector2::create(200.0, 100.0));
  node_tree.add_component(list_id, UIListView::new());
  let template_id = node_tree.create_child(root_id, "template");
  node_tree[template_id].set_pivot(Pivot::TOP_LEFT);
  node_tree[template_id].set_content_size(Vector2::create(200.0, 40.0));
  
  node_tree.with_component_mut::<UIListView, _>(list_id, |list_view, tree| {
  	list_view.set_template_node(tree, template_id);
  	list_view.set_item_count(20);
  });
  assert!(!node_tree[template_id].is_active());
  node_tree.tick(&engine, 0.016);
  
  let list_view = node_tree[list_id].get_component::<UIListView>().expect("list view");
  assert_eq!(list_view.get_item_size(), 40.0);
  assert_eq!(list_view.get_active_item_count(), 4);
  let item_id = list_view.get_item_node(1).expect("item 1");
  assert_eq!(node_tree[item_id].get_content_size(), Vector2::create(200.0, 40.0));
  assert!(node_tree[item_id].is_active());
  ```

- `pub fn set_template_node_with_document(&mut self, node_tree: &mut NodeTree, template_node_id: NodeId, ui_document: UIDocument)` (method, since 0.4.0): Sets the template node. (serialized and cloned with a UIDocument in which game components are registered)
  - `node_tree` &mut NodeTree: Tree that holds the template node.
  - `template_node_id` NodeId: Template node to clone. Does nothing if the node does not exist.
  - `ui_document` UIDocument: Document to write and read the template with. (one with the template's component types registered, read with this document every time an item is created)
- `pub fn set_item_count(&mut self, item_count: usize)` (method, since 0.3.2): Sets the item count. (rearms the end notification if it increases. scroll area update and rebinding happen on the next tick)
  - `item_count` usize: Total item count. (if it decreases, excess item nodes are recovered on the next tick)
- `pub fn refresh(&mut self)` (method, since 0.3.2): Rebinds all visible items. (when the data contents change. done on the next tick)
- `pub fn refresh_in_tree(&mut self, node_tree: &mut NodeTree)` (method, since 0.3.2): Rebinds all visible items right now. (for scene code holding the tree. the original refresh as is)
  - Does nothing if there is no bind event. Items beyond the item count and deleted nodes are skipped.
  - `node_tree` &mut NodeTree: Tree that holds the item nodes.
- `pub fn get_item_node(&self, item_index: usize) -> Option<NodeId>` (method, since 0.3.2): The real node of a specific item. (None if off screen)
  - `item_index` usize: Item index. (from 0)
  - returns Option<NodeId>: The node showing that item. None if outside the currently created range (visible range and buffer slots).
- `pub fn set_bind_item_event(&mut self, bind_item_event: UIListViewBindItemEvent)` (method, since 0.3.2): Sets the bind event.
  - `bind_item_event` UIListViewBindItemEvent: Function that takes (tree, item node, item index) and fills in the item node contents. Called when a node is newly placed (created or reused) and when rebinding.
- `pub fn set_reach_end_event(&mut self, reach_end_event: UIListViewReachEndEvent)` (method, since 0.3.2): Sets the end notification.
  - `reach_end_event` UIListViewReachEndEvent: Function called once when the remaining length to the end falls to the end notification distance or less. (takes the list view and the context, rearmed if set_item_count increases the items inside it)

  Example: Load 50 more items when near the end

  ```rust
  use std::cell::Cell;
  use std::rc::Rc;
  use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, Pivot, UIListView, UIScrollView, Vector2};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let list_id = node_tree.create_child(root_id, "list");
  node_tree[list_id].set_pivot(Pivot::TOP_LEFT);
  node_tree[list_id].set_content_size(Vector2::create(200.0, 100.0));
  let reach_end_count = Rc::new(Cell::new(0));
  let reach_end_counter = reach_end_count.clone();
  
  let list_view = node_tree.add_component(list_id, UIListView::new()).expect("list view");
  list_view.set_create_item_event(Box::new(|tree: &mut NodeTree| {
  	tree.create_node("item")
  }));
  list_view.set_item_size(30.0);
  list_view.set_item_count(100);
  list_view.set_reach_end_event(Box::new(move |list_view: &mut UIListView, _context: &mut ComponentContext| {
  	reach_end_counter.set(reach_end_counter.get() + 1);
  	let item_count = list_view.get_item_count();
  	list_view.set_item_count(item_count + 50);
  }));
  node_tree.tick(&engine, 0.016);
  assert_eq!(reach_end_count.get(), 0);
  
  node_tree[list_id].get_component_mut::<UIScrollView>().expect("scroll view").set_scroll_offset(Vector2::create(0.0, -2900.0));
  node_tree.tick(&engine, 0.016);
  assert_eq!(reach_end_count.get(), 1);
  assert_eq!(node_tree[list_id].get_component::<UIListView>().expect("list view").get_item_count(), 150);
  ```

- `pub fn set_reach_end_threshold(&mut self, reach_end_threshold: f64)` (method, since 0.3.2): Sets the end notification distance. (pixels)
  - `reach_end_threshold` f64: Notifies when the remaining length to the end is this value or less. (pixels, default 120)
- `pub fn set_item_size(&mut self, item_size: f64)` (method, since 0.3.2): Sets the item size along the progress axis. (the scroll area is updated on the next tick)
  - `item_size` f64: Length of one item along the progress axis. (pixels, if 0 or less, reads the content_size of the first created item node)
- `pub fn set_spacing(&mut self, spacing: f64)` (method, since 0.3.2): Sets the spacing between items. (the scroll area is updated on the next tick)
  - `spacing` f64: Spacing between items. (pixels, default 0)
- `pub fn set_horizontal(&mut self, is_horizontal: bool)` (method, since 0.3.2): Sets horizontal progress. (vertical by default)
  - When changed, the scroll area is remeasured on the next tick and visible items are placed again on the new axis. (set it before item sizes are read, the scroll view's axis is set separately)
  - `is_horizontal` bool: If true, lays the items out along the x axis.
- `pub fn set_buffer_item_count(&mut self, buffer_item_count: usize)` (method, since 0.3.2): Sets the off-screen buffer item count.
  - `buffer_item_count` usize: Number of extra items to create before and after the visible range. (default 1)
- `pub fn get_item_count(&self) -> usize` (method, since 0.3.2): Returns the item count.
  - returns usize: Total item count.
- `pub fn get_item_size(&self) -> f64` (method, since 0.3.2): Returns the item size.
  - returns f64: Length of one item along the progress axis. (pixels, 0 if not read yet)
- `pub fn get_spacing(&self) -> f64` (method, since 0.3.2): Returns the spacing between items.
  - returns f64: Spacing between items. (pixels)
- `pub fn is_horizontal(&self) -> bool` (method, since 0.3.2): Whether progress is horizontal.
  - returns bool: true if laid out horizontally.
- `pub fn get_active_item_count(&self) -> usize` (method, since 0.3.2): Number of items currently created (visible).
  - returns usize: Number of items currently created as nodes. (visible range and buffer slots)
