# ui/uisnapscrollview (vanilla-engine 0.4.0)

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

Snap scroll view. (UISnapScrollView of the original ui/uisnapscrollview.js)
- On drag release, slides so that the center of one content child (item) lands at the center of the visible area. Items may differ in size.
- Horizontal snap: set_horizontal(true), set_vertical(false) (default). Vertical snap: set_horizontal(false), set_vertical(true).
- One drag moves at most one slot. On release, if the drag velocity is at least set_velocity_threshold (default 200, offset pixels per second), it moves one slot in that direction,
  otherwise it moves when the dragged distance is at least the set_page_change_threshold ratio (default 0.35) of the next item's size. While dragging, the offset does not go beyond ±1 slot from the current slot.
- With set_snap_to_nearest(true), the slot range is not clamped while dragging, and on release it goes to the item whose snap offset is closest to the current offset.
- page_to(node_tree, index, smooth): moves to the given slot. If smooth, slides with 0.3 seconds cubic.out, otherwise moves right away.
- The original inherits UIScrollView. The Rust version embeds UIScrollView (scroll_view field) and passes through touch, wheel, drawing, and attaching.
  Scroll view settings are made on the embedded view with get_scroll_view_mut. Commonly used ones (content size, offset, axes) are also on this widget.
  Attach with node_tree.add_component(node_id, UISnapScrollView::new()). (the embedded view creates the content node, Mask, and interactable)
- Differences from the original:
  - Functions that change the slot (page_to, set_snap_current_index, play_snap_tween, etc.) need to read content children, so they take the tree.
    Scene code calls them with node_tree.`with_component_mut::<UISnapScrollView, _>`(snap_id, |snap_view, tree| snap_view.page_to(tree, 2, true)).
  - Instead of the original Tween object, the snap slide does the same calculation (0.3 seconds, cubic.out, first step on the tick it is made) inside this widget.
    (the original tween's update callback calls the scroll view itself, but a Rust tween callback takes only the tree and cannot reach this widget, which is taken out during tick)
  - While sliding, the content node is moved right away within that tick. (so it does not lag a frame, since the embedded view applies on the next tick)
  - In the original, the snap view is also a UIScrollView, so TouchRecognizer, UIScrollBar, UIListView recognize it as is.
    In the Rust version, TouchRecognizer and UIListView recognize it through find_scroll_view. UIScrollBar looks only for the UIScrollView component, so
    a scroll bar cannot be attached to a snap view. (setShows...ScrollBar only puts the value into the embedded view)

## UISnapScrollView (struct) (Default, Component)

Snap scroll view.
- Each content child is one slot. On release, the center of the nearest slot (at most one slot in the drag direction) slides to the center of the visible area.
- The embedded scroll view clamps the offset to the content size, so set the full length of all slots with set_scroll_content_size.

Example: Drag a five-slot horizontal page over to the next slot

```rust
use vanilla::{Engine, EngineConfiguration, NodeTree, Pivot, TouchKind, UISnapScrollView, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let snap_id = node_tree.create_child(root_id, "snap");
node_tree[snap_id].set_pivot(Pivot::TOP_LEFT);
node_tree[snap_id].set_content_size(Vector2::create(200.0, 100.0));
let snap_view = node_tree.add_component(snap_id, UISnapScrollView::new()).expect("snap view");
snap_view.set_scroll_content_size(Vector2::create(1000.0, 100.0));
let content_id = snap_view.get_content().expect("content");
for page_index in 0..5 {
	let page_id = node_tree.create_child(content_id, "page");
	node_tree[page_id].set_pivot(Pivot::TOP_LEFT);
	node_tree[page_id].set_rect(page_index as f64 * 200.0, 0.0, 200.0, 100.0);
}

node_tree.dispatch_touch(snap_id, &engine, TouchKind::Press, Vector2::create(150.0, 50.0));
node_tree.dispatch_touch(snap_id, &engine, TouchKind::Moved, Vector2::create(50.0, 50.0));
node_tree.tick(&engine, 0.016);
node_tree.dispatch_touch(snap_id, &engine, TouchKind::Release, Vector2::create(50.0, 50.0));
for _ in 0..30 {
	node_tree.tick(&engine, 0.016);
}

let snap_view = node_tree[snap_id].get_component::<UISnapScrollView>().expect("snap view");
assert_eq!(snap_view.get_snap_current_index(), 1);
assert_eq!(snap_view.get_scroll_offset(), Vector2::create(-200.0, 0.0));
assert_eq!(node_tree[content_id].get_local_position(), Vector2::create(-200.0, 0.0));
```

- `pub fn new() -> UISnapScrollView` (constructor, since 0.3.2): Constructor. (clamp mode, horizontal scrolling only)
  - Use node_tree.add_component to attach it to a node. (the embedded view creates the content node and the Mask)
  - returns UISnapScrollView: New snap view with current slot 0, slot change ratio 0.35, and directional snap minimum velocity 200.
- `pub fn get_scroll_view(&self) -> &UIScrollView` (method, since 0.3.2): Returns the embedded scroll view.
  - returns &UIScrollView: The embedded scroll view.
- `pub fn get_scroll_view_mut(&mut self) -> &mut UIScrollView` (method, since 0.3.2): Returns the embedded scroll view. (mutable)
  - returns &mut UIScrollView: Mutable reference to the embedded scroll view. (scroll view settings such as drag scale and wheel scale go here)
- `pub fn get_content(&self) -> Option<NodeId>` (method, since 0.3.2): Content node handle. (attach item nodes here)
  - returns Option<NodeId>: content node. None before being attached to a tree (node_tree.add_component).
- `pub fn set_background_color(&mut self, background_color: impl Into<Color>)` (method, since 0.3.2): Sets the background color.
  - `background_color` impl Into<Color>: Background color of the visible area. (default transparent, not drawn if transparent)
- `pub fn set_scroll_content_size(&mut self, scroll_content_size: Vector2)` (method, since 0.3.2): Sets the scroll content size.
  - `scroll_content_size` Vector2: Content size that holds all slots. (pixels, the offset is clamped to this size, so set it to at least the full length of all slots)
- `pub fn get_scroll_content_size(&self) -> Vector2` (method, since 0.3.2): Returns the scroll content size.
  - returns Vector2: Total content size. (pixels)
- `pub fn set_scroll_offset(&mut self, offset: Vector2)` (method, since 0.3.2): Sets the offset. (clamped to the range)
  - `offset` Vector2: New offset. (pixels, the local position of the content node. does not change the slot, and the content is moved on the next tick)
- `pub fn get_scroll_offset(&self) -> Vector2` (method, since 0.3.2): Returns the offset.
  - returns Vector2: Current offset. (pixels, 0 or less)
- `pub fn set_horizontal(&mut self, is_horizontal: bool)` (method, since 0.3.2): Sets whether horizontal scrolling is on.
  - `is_horizontal` bool: If true, snaps horizontally. (default true, for vertical snap set it to false and set_vertical(true))
- `pub fn is_horizontal(&self) -> bool` (method, since 0.3.2): Whether horizontal scrolling is on.
  - returns bool: true if horizontal scrolling is on. (if true, the progress axis is x)
- `pub fn set_vertical(&mut self, is_vertical: bool)` (method, since 0.3.2): Sets whether vertical scrolling is on.
  - `is_vertical` bool: If true, scrolls vertically. (default false)
- `pub fn is_vertical(&self) -> bool` (method, since 0.3.2): Whether vertical scrolling is on.
  - returns bool: true if vertical scrolling is on.
- `pub fn is_dragging(&self) -> bool` (method, since 0.3.2): Whether it is dragging.
  - returns bool: true while pressing and dragging.
- `pub fn set_snap_to_nearest(&mut self, is_snap_to_nearest: bool)` (method, since 0.3.2): Sets the snap mode. (if true, the slot range is not clamped while dragging, and on release it goes to the nearest item)
  - `is_snap_to_nearest` bool: Whether to snap to the nearest slot. (default false)
- `pub fn get_snap_to_nearest(&self) -> bool` (method, since 0.3.2): Returns the snap mode.
  - returns bool: The value set with set_snap_to_nearest.
- `pub fn set_velocity_threshold(&mut self, velocity_threshold: f64)` (method, since 0.3.2): Sets the minimum velocity for directional snapping. (offset pixels per second, in one-slot mode, if the drag velocity on release is at least this, it moves one slot in that direction regardless of the dragged distance)
  - `velocity_threshold` f64: Minimum velocity for directional snapping. (pixels/second, default 200)
- `pub fn get_velocity_threshold(&self) -> f64` (method, since 0.3.2): Returns the directional snap minimum velocity.
  - returns f64: Directional snap minimum velocity. (pixels/second)
- `pub fn set_page_change_threshold(&mut self, page_change_threshold: f64)` (method, since 0.3.2): Sets the drag distance ratio for changing slots. (relative to the next item's size, default 0.35)
  - `page_change_threshold` f64: If the drag distance is at least this ratio of the next slot's size in the drag direction, moves to that slot. (0 ~ 1)
- `pub fn get_page_change_threshold(&self) -> f64` (method, since 0.3.2): Returns the drag distance ratio for changing slots.
  - returns f64: Slot change ratio.
- `pub fn get_drag_velocity(&self) -> f64` (method, since 0.4.0): Returns the drag velocity. (pixels per second the offset on the progress axis moved while dragging, negative toward the next slot. The value of the last dragged tick, 0 when a drag starts)
  - returns f64: Velocity of the scroll axis offset while dragging. (Pixels per second, negative toward the next item, the value of the last dragging tick, 0 when a drag starts)
- `pub fn get_snap_current_index(&self) -> usize` (method, since 0.3.2): Returns the current snap slot.
  - returns usize: Current slot index. (from 0, in content child order)
- `pub fn is_snapping(&self) -> bool` (method, since 0.3.2): Whether it is sliding.
  - returns bool: true if a snap slide is in progress.
- `pub fn compute_snap_offsets(&self, node_tree: &NodeTree) -> Vec<f64>` (method, since 0.3.2): Calculates the snap offset for each content child. (the offset that puts each item's center at the center of the visible area, correct even with different sizes)
  - `node_tree` &NodeTree: Node tree this snap view is attached to.
  - returns Vec<f64>: Snap offsets along the progress axis in content child order. (pixels, values not clamped to the range) An empty list before being attached to a tree or if there is no content.

  Example: Snap offsets of three 200 pixel slots

  ```rust
  use vanilla::{NodeTree, Pivot, UISnapScrollView, Vector2};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let snap_id = node_tree.create_child(root_id, "snap");
  node_tree[snap_id].set_pivot(Pivot::TOP_LEFT);
  node_tree[snap_id].set_content_size(Vector2::create(200.0, 100.0));
  let snap_view = node_tree.add_component(snap_id, UISnapScrollView::new()).expect("snap view");
  let content_id = snap_view.get_content().expect("content");
  for page_index in 0..3 {
  	let page_id = node_tree.create_child(content_id, "page");
  	node_tree[page_id].set_pivot(Pivot::TOP_LEFT);
  	node_tree[page_id].set_rect(page_index as f64 * 200.0, 0.0, 200.0, 100.0);
  }
  
  let snap_view = node_tree[snap_id].get_component::<UISnapScrollView>().expect("snap view");
  assert_eq!(snap_view.compute_snap_offsets(&node_tree), vec![0.0, -200.0, -400.0]);
  assert!(UISnapScrollView::new().compute_snap_offsets(&node_tree).is_empty());
  ```

- `pub fn clamp_scroll_offset_to_adjacent_pages(&mut self, node_tree: &mut NodeTree)` (method, since 0.3.2): While dragging, clamps the offset to the range of slots before and after the current slot.
  - Called by tick while dragging. Does nothing if there are no slots.
  - `node_tree` &mut NodeTree: Node tree this snap view is attached to. (reads the content children)
- `pub fn play_snap_tween(&mut self, node_tree: &mut NodeTree)` (method, since 0.3.2): Decides the target slot from the current offset and starts sliding.
  - Nearest item mode: the slot whose snap offset is closest to the current offset. (the earlier slot on a tie)
  - One-slot mode: one slot in the velocity direction if the drag velocity is at least the minimum velocity, otherwise at most one slot in the drag direction. (moves if the next slot is revealed by at least the ratio)
  - `node_tree` &mut NodeTree: Node tree this snap view is attached to. (reads the content children)
- `pub fn page_to(&mut self, node_tree: &mut NodeTree, index: usize, smooth: bool)` (method, since 0.3.2): Moves to the given slot. (slides if smooth, otherwise moves right away)
  - This component 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: Node tree this snap view is attached to.
  - `index` usize: Slot index to move to. (from 0, the last slot if it exceeds the slot count) Does nothing if there are no slots.
  - `smooth` bool: If true, slides with 0.3 seconds cubic.out (from the next tick), if false, moves the offset and the content node right away.

  Example: Moving right away and sliding

  ```rust
  use vanilla::{Engine, EngineConfiguration, NodeTree, Pivot, UISnapScrollView, Vector2};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let snap_id = node_tree.create_child(root_id, "snap");
  node_tree[snap_id].set_pivot(Pivot::TOP_LEFT);
  node_tree[snap_id].set_content_size(Vector2::create(200.0, 100.0));
  let snap_view = node_tree.add_component(snap_id, UISnapScrollView::new()).expect("snap view");
  snap_view.set_scroll_content_size(Vector2::create(1000.0, 100.0));
  let content_id = snap_view.get_content().expect("content");
  for page_index in 0..5 {
  	let page_id = node_tree.create_child(content_id, "page");
  	node_tree[page_id].set_pivot(Pivot::TOP_LEFT);
  	node_tree[page_id].set_rect(page_index as f64 * 200.0, 0.0, 200.0, 100.0);
  }
  
  node_tree.with_component_mut::<UISnapScrollView, _>(snap_id, |snap_view, tree| {
  	snap_view.page_to(tree, 9, false);
  });
  assert_eq!(node_tree[content_id].get_local_position(), Vector2::create(-800.0, 0.0));
  
  node_tree.with_component_mut::<UISnapScrollView, _>(snap_id, |snap_view, tree| {
  	snap_view.page_to(tree, 2, true);
  });
  for _ in 0..20 {
  	node_tree.tick(&engine, 0.016);
  }
  let snap_view = node_tree[snap_id].get_component::<UISnapScrollView>().expect("snap view");
  assert_eq!(snap_view.get_snap_current_index(), 2);
  assert_eq!(node_tree[content_id].get_local_position(), Vector2::create(-400.0, 0.0));
  ```

- `pub fn set_snap_current_index(&mut self, node_tree: &mut NodeTree, index: usize)` (method, since 0.3.2): Starts sliding to the given slot. (from the current offset to that slot's snap offset)
  - The slide runs with 0.3 seconds cubic.out from the next tick. (same as smooth in page_to)
  - `node_tree` &mut NodeTree: Node tree this snap view is attached to.
  - `index` usize: Target slot index. (from 0, the last slot if it exceeds the slot count) Does nothing if there are no slots.

## Functions and constants

- `pub fn find_scroll_view(node: &WorldNode) -> Option<&UIScrollView>` (method, since 0.3.2): Finds the node's scroll view. (UIScrollView, or else the view embedded in UISnapScrollView. where the original getComponents(UIScrollView) also catches subclasses)
  - `node` &WorldNode: Node to find.
  - returns Option<&UIScrollView>: The node's UIScrollView, or else the scroll view embedded in UISnapScrollView. None if neither exists or that component is taken out because it is in tick.

  Example: Find the embedded scroll view from a snap view node

  ```rust
  use vanilla::{NodeTree, UISnapScrollView};
  use vanilla::ui::uisnapscrollview::find_scroll_view;
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let snap_id = node_tree.create_child(root_id, "snap");
  node_tree.add_component(snap_id, UISnapScrollView::new());
  
  let scroll_view = find_scroll_view(&node_tree[snap_id]).expect("scroll view");
  assert!(scroll_view.is_horizontal());
  assert!(!scroll_view.is_vertical());
  assert!(find_scroll_view(&node_tree[root_id]).is_none());
  ```

- `pub fn find_scroll_view_mut(node: &mut WorldNode) -> Option<&mut UIScrollView>` (method, since 0.3.2): Finds the node's scroll view. (mutable)
  - `node` &mut WorldNode: Node to find.
  - returns Option<&mut UIScrollView>: Mutable reference to the node's UIScrollView, or else the scroll view embedded in UISnapScrollView. None if neither exists.
