# ui/uisnapscrollview (vanilla-engine 0.4.0)

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

스냅 스크롤 뷰. (원본 ui/uisnapscrollview.js 의 UISnapScrollView)
- 드래그를 놓으면 content 자식(아이템) 하나의 가운데가 보이는 영역 가운데에 오도록 미끄러진다. 아이템 크기가 달라도 된다.
- 가로 스냅: set_horizontal(true), set_vertical(false) (기본). 세로 스냅: set_horizontal(false), set_vertical(true).
- 한 번 끌면 최대 한 칸만 움직인다. 놓을 때 드래그 속도가 set_velocity_threshold(기본 200, 오프셋의 초당 픽셀) 이상이면 그 방향으로 한 칸 넘기고,
  아니면 끈 거리가 다음 아이템 크기의 set_page_change_threshold 비율(기본 0.35) 이상일 때 넘어간다. 끄는 동안에는 오프셋이 지금 칸 ±1 칸 범위를 넘지 않는다.
- set_snap_to_nearest(true) 면 끄는 동안 칸 범위를 자르지 않고, 놓으면 스냅 오프셋이 지금 오프셋과 가장 가까운 아이템으로 간다.
- page_to(node_tree, index, smooth): 지정 칸으로 이동. smooth 면 0.3 초 cubic.out 으로 미끄러지고, 아니면 바로 옮긴다.
- 원본은 UIScrollView 를 상속한다. 러스트 판은 UIScrollView 를 품고(scroll_view 필드) 터치, 휠, 그리기, 붙기를 넘겨준다.
  스크롤 뷰 설정은 get_scroll_view_mut 로 품은 뷰에 한다. 자주 쓰는 것(콘텐트 크기, 오프셋, 축)은 이 위젯에도 있다.
  node_tree.add_component(node_id, UISnapScrollView::new()) 로 붙인다. (content 노드, Mask, interactable 은 품은 뷰가 만든다)
- 원본과 다른 것:
  - 칸을 바꾸는 함수(page_to, set_snap_current_index, play_snap_tween 등)는 content 자식을 읽어야 해서 트리를 받는다.
    씬 코드에서는 node_tree.`with_component_mut::<UISnapScrollView, _>`(snap_id, |snap_view, tree| snap_view.page_to(tree, 2, true)) 로 부른다.
  - 스냅 미끄러짐은 원본 Tween 객체 대신 같은 계산(0.3 초, cubic.out, 만든 tick 에 첫 걸음)을 이 위젯 안에서 한다.
    (원본 트윈의 갱신 콜백이 스크롤 뷰 자신을 부르는데, 러스트 트윈 콜백은 트리만 받아 tick 중에 꺼내진 이 위젯에 닿지 않는다)
  - 미끄러지는 동안 content 노드는 그 tick 안에서 바로 옮긴다. (품은 뷰의 반영은 다음 tick 이라 한 프레임 늦지 않게)
  - 원본은 스냅 뷰가 UIScrollView 이기도 해서 TouchRecognizer, UIScrollBar, UIListView 가 그대로 알아본다.
    러스트 판은 TouchRecognizer 와 UIListView 가 find_scroll_view 로 알아본다. UIScrollBar 는 UIScrollView 컴포넌트만 찾아서
    스냅 뷰에는 스크롤바를 붙일 수 없다. (setShows...ScrollBar 는 품은 뷰에 값만 들어간다)

## UISnapScrollView (struct) (Default, Component)

스냅 스크롤 뷰.
- content 자식 하나하나가 한 칸이다. 놓으면 가장 가까운 칸(끈 방향으로 최대 한 칸)의 가운데가 보이는 영역 가운데로 미끄러진다.
- 오프셋은 품은 스크롤 뷰가 콘텐트 크기로 자르므로 set_scroll_content_size 로 칸 전체 길이를 정해 둔다.

예제: 다섯 칸 가로 페이지를 끌어 다음 칸으로 넘기기

```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): 생성. (clamp 모드, 가로만 스크롤)
  - 노드에 붙일 때는 node_tree.add_component 를 쓴다. (품은 뷰가 content 노드와 Mask 를 만든다)
  - returns UISnapScrollView: 지금 칸 0, 칸 넘김 비율 0.35, 방향성 스냅 최소 속도 200 의 새 스냅 뷰.
- `pub fn get_scroll_view(&self) -> &UIScrollView` (method, since 0.3.2): 품은 스크롤 뷰 반환.
  - returns &UIScrollView: 품은 스크롤 뷰.
- `pub fn get_scroll_view_mut(&mut self) -> &mut UIScrollView` (method, since 0.3.2): 품은 스크롤 뷰 반환. (변경용)
  - returns &mut UIScrollView: 품은 스크롤 뷰의 가변 참조. (드래그 배율, 휠 배율 같은 스크롤 뷰 설정을 여기에 한다)
- `pub fn get_content(&self) -> Option<NodeId>` (method, since 0.3.2): 컨텐트 노드 핸들. (아이템 노드를 여기에 붙인다)
  - returns Option<NodeId>: content 노드. 트리에 붙기(node_tree.add_component) 전에는 None.
- `pub fn set_background_color(&mut self, background_color: impl Into<Color>)` (method, since 0.3.2): 배경색 설정.
  - `background_color` impl Into<Color>: 보이는 영역의 바탕색. (기본 투명, 투명이면 그리지 않는다)
- `pub fn set_scroll_content_size(&mut self, scroll_content_size: Vector2)` (method, since 0.3.2): 스크롤 콘텐츠 크기 설정.
  - `scroll_content_size` Vector2: 칸 전체를 담는 콘텐트 크기. (픽셀, 오프셋을 이 크기로 자르므로 칸 전체 길이 이상으로 둔다)
- `pub fn get_scroll_content_size(&self) -> Vector2` (method, since 0.3.2): 스크롤 콘텐츠 크기 반환.
  - returns Vector2: 콘텐트 전체 크기. (픽셀)
- `pub fn set_scroll_offset(&mut self, offset: Vector2)` (method, since 0.3.2): 오프셋 설정. (범위로 자른다)
  - `offset` Vector2: 새 오프셋. (픽셀, content 노드의 로컬 위치. 칸을 바꾸지 않고 content 는 다음 tick 에 옮겨진다)
- `pub fn get_scroll_offset(&self) -> Vector2` (method, since 0.3.2): 오프셋 반환.
  - returns Vector2: 지금 오프셋. (픽셀, 0 이하)
- `pub fn set_horizontal(&mut self, is_horizontal: bool)` (method, since 0.3.2): 가로 스크롤 켜기 설정.
  - `is_horizontal` bool: true 면 가로로 스냅한다. (기본 true, 세로 스냅은 false 로 두고 set_vertical(true))
- `pub fn is_horizontal(&self) -> bool` (method, since 0.3.2): 가로 스크롤 켜짐 여부.
  - returns bool: 가로 스크롤이 켜져 있으면 true. (true 면 진행 축이 x 다)
- `pub fn set_vertical(&mut self, is_vertical: bool)` (method, since 0.3.2): 세로 스크롤 켜기 설정.
  - `is_vertical` bool: true 면 세로로 스크롤한다. (기본 false)
- `pub fn is_vertical(&self) -> bool` (method, since 0.3.2): 세로 스크롤 켜짐 여부.
  - returns bool: 세로 스크롤이 켜져 있으면 true.
- `pub fn is_dragging(&self) -> bool` (method, since 0.3.2): 드래그 중인지.
  - returns bool: 눌러 끄는 중이면 true.
- `pub fn set_snap_to_nearest(&mut self, is_snap_to_nearest: bool)` (method, since 0.3.2): 스냅 모드 설정. (true 면 끄는 동안 칸 범위를 자르지 않고, 놓으면 가장 가까운 아이템으로 간다)
  - `is_snap_to_nearest` bool: 가장 가까운 칸으로 스냅할지. (기본 false)
- `pub fn get_snap_to_nearest(&self) -> bool` (method, since 0.3.2): 스냅 모드 반환.
  - returns bool: set_snap_to_nearest 로 정한 값.
- `pub fn set_velocity_threshold(&mut self, velocity_threshold: f64)` (method, since 0.3.2): 방향성 스냅 최소 속도 설정. (오프셋의 초당 픽셀, 한 칸 모드에서 놓을 때 드래그 속도가 이 이상이면 끈 거리와 상관없이 그 방향으로 한 칸 넘긴다)
  - `velocity_threshold` f64: 방향성 스냅 최소 속도. (픽셀/초, 기본 200)
- `pub fn get_velocity_threshold(&self) -> f64` (method, since 0.3.2): 방향성 스냅 최소 속도 반환.
  - returns f64: 방향성 스냅 최소 속도. (픽셀/초)
- `pub fn set_page_change_threshold(&mut self, page_change_threshold: f64)` (method, since 0.3.2): 칸을 넘길 끈 거리 비율 설정. (다음 아이템 크기 대비, 기본 0.35)
  - `page_change_threshold` f64: 끈 거리가 끈 쪽 다음 칸 크기의 이 비율 이상이면 그 칸으로 넘긴다. (0 ~ 1)
- `pub fn get_page_change_threshold(&self) -> f64` (method, since 0.3.2): 칸을 넘길 끈 거리 비율 반환.
  - returns f64: 칸 넘김 비율.
- `pub fn get_drag_velocity(&self) -> f64` (method, since 0.4.0): 드래그 속도 반환. (끄는 동안 진행 축 오프셋이 움직인 초당 픽셀, 다음 칸 쪽이 음수. 마지막으로 끈 tick 의 값이고 끌기를 시작하면 0)
  - returns f64: 끄는 동안 스크롤 축 오프셋이 움직인 속도. (초당 픽셀, 다음 칸 쪽이 음수, 마지막으로 끈 tick 의 값이고 끌기를 시작하면 0)
- `pub fn get_snap_current_index(&self) -> usize` (method, since 0.3.2): 지금 스냅 칸 반환.
  - returns usize: 지금 칸 번호. (0 부터, content 자식 순서)
- `pub fn is_snapping(&self) -> bool` (method, since 0.3.2): 미끄러지는 중인지.
  - returns bool: 스냅 미끄러짐이 진행 중이면 true.
- `pub fn compute_snap_offsets(&self, node_tree: &NodeTree) -> Vec<f64>` (method, since 0.3.2): content 자식마다 스냅 오프셋 계산. (각 아이템 가운데가 보이는 영역 가운데에 오는 오프셋, 크기가 달라도 맞다)
  - `node_tree` &NodeTree: 이 스냅 뷰가 붙은 노드 트리.
  - returns Vec<f64>: content 자식 순서대로 진행 축의 스냅 오프셋. (픽셀, 범위로 자르지 않은 값) 트리에 붙기 전이거나 content 가 없으면 빈 목록.

  예제: 200 픽셀 칸 셋의 스냅 오프셋

  ```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): 끄는 동안 오프셋을 지금 칸의 앞뒤 칸 범위로 자른다.
  - tick 이 끄는 중에 부른다. 칸이 없으면 아무것도 하지 않는다.
  - `node_tree` &mut NodeTree: 이 스냅 뷰가 붙은 노드 트리. (content 자식을 읽는다)
- `pub fn play_snap_tween(&mut self, node_tree: &mut NodeTree)` (method, since 0.3.2): 지금 오프셋으로 목표 칸을 정하고 미끄러짐을 시작한다.
  - 가장 가까운 아이템 모드: 스냅 오프셋이 지금 오프셋과 가장 가까운 칸. (같으면 앞 칸)
  - 한 칸 모드: 드래그 속도가 최소 속도 이상이면 속도 방향으로 한 칸, 아니면 끈 방향으로 최대 한 칸. (다음 칸이 비율 이상 드러나면 넘김)
  - `node_tree` &mut NodeTree: 이 스냅 뷰가 붙은 노드 트리. (content 자식을 읽는다)
- `pub fn page_to(&mut self, node_tree: &mut NodeTree, index: usize, smooth: bool)` (method, since 0.3.2): 지정 칸으로 이동. (smooth 면 미끄러지고, 아니면 바로 옮긴다)
  - 이 컴포넌트를 트리에서 꺼내 불러야 해서 씬 코드에서는 node_tree.with_component_mut 안에서 부른다.
  - `node_tree` &mut NodeTree: 이 스냅 뷰가 붙은 노드 트리.
  - `index` usize: 옮길 칸 번호. (0 부터, 칸 수를 넘으면 마지막 칸) 칸이 없으면 아무것도 하지 않는다.
  - `smooth` bool: true 면 0.3 초 cubic.out 으로 미끄러지고(다음 tick 부터), false 면 오프셋과 content 노드를 바로 옮긴다.

  예제: 바로 옮기기와 미끄러지기

  ```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): 지정 칸으로 미끄러짐 시작. (지금 오프셋에서 그 칸의 스냅 오프셋까지)
  - 미끄러짐은 다음 tick 부터 0.3 초 cubic.out 으로 간다. (page_to 의 smooth 와 같다)
  - `node_tree` &mut NodeTree: 이 스냅 뷰가 붙은 노드 트리.
  - `index` usize: 목표 칸 번호. (0 부터, 칸 수를 넘으면 마지막 칸) 칸이 없으면 아무것도 하지 않는다.

## Functions and constants

- `pub fn find_scroll_view(node: &WorldNode) -> Option<&UIScrollView>` (method, since 0.3.2): 노드의 스크롤 뷰 찾기. (UIScrollView, 없으면 UISnapScrollView 가 품은 뷰. 원본 getComponents(UIScrollView) 가 하위 클래스까지 잡는 자리)
  - `node` &WorldNode: 찾을 노드.
  - returns Option<&UIScrollView>: 노드의 UIScrollView, 없으면 UISnapScrollView 가 품은 스크롤 뷰. 둘 다 없거나 그 컴포넌트가 tick 중이라 꺼내져 있으면 None.

  예제: 스냅 뷰 노드에서 품은 스크롤 뷰 찾기

  ```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): 노드의 스크롤 뷰 찾기. (변경용)
  - `node` &mut WorldNode: 찾을 노드.
  - returns Option<&mut UIScrollView>: 노드의 UIScrollView, 없으면 UISnapScrollView 가 품은 스크롤 뷰의 가변 참조. 둘 다 없으면 None.
