# ui/uidraggable (vanilla-engine 0.4.0)

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

드래그 가능 컴포넌트. (원본 ui/uidraggable.js 의 UIDraggable)
- 노드에 붙이면 눌러서 끌 수 있다. 놓으면 끝 이벤트로 알리고, set_snap_back_enabled(true) 면 잡기 전 자리로 미끄러져 돌아간다.
- 이동량은 뷰 좌표 차이를 그대로 로컬 좌표에 더한다. (조상 노드에 배율이 있으면 감도가 달라진다. 원본과 같음)
- 원본은 UIControl 을 상속한다. 러스트 판은 UIControl 을 품고(ui_control 필드) content, 배경색을 넘겨준다.
  attach_to_tree 에서 호스트 노드를 interactable 로 켠다. node_tree.add_component(node_id, UIDraggable::new()) 로 붙인다.
- 사용:
  ```text
    let draggable = node_tree.add_component(card_id, UIDraggable::new()).expect("draggable");
    draggable.set_snap_back_enabled(true);
    draggable.set_drag_end_event(Box::new(|draggable, context, view_position| { if 놓을 자리면 { draggable.settle_here(context.get_node_tree_mut()); } }));
  ```
- 원본과 다른 것:
  - 이벤트는 드래그 컴포넌트와 문맥을 받는다. (이동 / 끝은 뷰 좌표도) 원본 콜백은 컴포넌트(와 뷰 좌표)만 받는다.
  - settle_here / snap_home 은 노드 자리를 읽고 써야 해서 트리를 받는다. (끝 이벤트 안에서는 context.get_node_tree_mut())

## UIDraggableEvent (type)

드래그 이벤트. (드래그 컴포넌트와 문맥을 받는다. 시작 이벤트)

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

## UIDraggablePositionEvent (type)

드래그 자리 이벤트. (드래그 컴포넌트, 문맥, 뷰 좌표. 이동 / 끝 이벤트)

```rust
pub type UIDraggablePositionEvent = Box<dyn FnMut(&mut UIDraggable, &mut ComponentContext, Vector2)>
```

## UIDraggable (struct) (Default, Component)

드래그 가능 컴포넌트.

예제: 놓을 자리에 놓으면 눌러앉고, 아니면 제자리로 돌아가는 카드

```rust
use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, TouchKind, UIDraggable, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let card_id = node_tree.create_child(root_id, "Card");
node_tree[card_id].set_local_position(Vector2::create(100.0, 100.0));
node_tree[card_id].set_content_size(Vector2::create(50.0, 50.0));
let draggable = node_tree.add_component(card_id, UIDraggable::new()).expect("draggable");
draggable.set_snap_back_enabled(true);
draggable.set_drag_end_event(Box::new(|draggable: &mut UIDraggable, context: &mut ComponentContext, view_position: Vector2| {
	if view_position.x > 300.0 {
		draggable.settle_here(context.get_node_tree_mut());
	}
}));
node_tree.dispatch_touch(card_id, &engine, TouchKind::Press, Vector2::create(100.0, 100.0));
node_tree.dispatch_touch(card_id, &engine, TouchKind::Moved, Vector2::create(400.0, 100.0));
node_tree.dispatch_touch(card_id, &engine, TouchKind::Release, Vector2::create(400.0, 100.0));
node_tree.tick(&engine, 0.5);
assert_eq!(node_tree[card_id].get_local_position(), Vector2::create(400.0, 100.0));
assert_eq!(node_tree[card_id].get_component::<UIDraggable>().expect("draggable").get_home_position(), Some(Vector2::create(400.0, 100.0)));
```

- `pub fn new() -> UIDraggable` (constructor, since 0.3.2): 생성. (복귀 꺼짐, 복귀 속도 14)
  - returns UIDraggable: 붙기 전의 드래그 컴포넌트.
- `pub fn get_uicontrol(&self) -> &UIControl` (method, since 0.3.2): 품은 컨트롤 반환.
  - returns &UIControl: 품은 UIControl.
- `pub fn get_uicontrol_mut(&mut self) -> &mut UIControl` (method, since 0.3.2): 품은 컨트롤 반환. (변경용)
  - returns &mut UIControl: 품은 UIControl.
- `pub fn get_content(&self) -> Option<NodeId>` (method, since 0.3.2): 컨텐트 노드 핸들.
  - returns Option<NodeId>: 컨텐트 노드. (트리에 붙기 전이면 None)
- `pub fn set_background_color(&mut self, background_color: impl Into<Color>)` (method, since 0.3.2): 배경색 설정.
  - `background_color` impl Into<Color>: 배경색. (품은 UIControl 이 그린다)
- `pub fn settle_here(&mut self, node_tree: &mut NodeTree)` (method, since 0.3.2): 지금 자리에 눌러앉기. (끝 이벤트에서 놓기에 성공했을 때 부른다. 복귀를 멈춘다)
  - `node_tree` &mut NodeTree: 드래그 노드가 든 노드 트리. (지금 로컬 자리를 제자리로 삼는다, 끝 이벤트 안에서는 context.get_node_tree_mut())
- `pub fn snap_home(&mut self, node_tree: &mut NodeTree)` (method, since 0.3.2): 제자리로 바로 되돌리기.
  - `node_tree` &mut NodeTree: 드래그 노드가 든 노드 트리. (잡은 적이 없으면 자리는 그대로이고 복귀만 멈춘다)
- `pub fn set_snap_back_enabled(&mut self, is_snap_back_enabled: bool)` (method, since 0.3.2): 놓으면 제자리로 돌아갈지 설정.
  - `is_snap_back_enabled` bool: 놓으면 제자리로 미끄러져 돌아가면 true. (기본 false)
- `pub fn set_snap_back_speed(&mut self, snap_back_speed: f64)` (method, since 0.3.2): 복귀 속도 설정. (초당 남은 거리를 줄이는 비율 계수)
  - `snap_back_speed` f64: 복귀 속도. (tick 마다 남은 거리의 속도 x 초 몫만큼 다가가고, 그 몫이 1 을 넘으면 바로 닿는다. 기본 14)

  예제: 속도 10 이면 0.05 초에 남은 거리의 반을 간다

  ```rust
  use vanilla::{Engine, EngineConfiguration, NodeTree, TouchKind, UIDraggable, Vector2};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let card_id = node_tree.create_child(root_id, "Card");
  node_tree[card_id].set_local_position(Vector2::create(100.0, 100.0));
  if let Some(draggable) = node_tree.add_component(card_id, UIDraggable::new()) {
  	draggable.set_snap_back_enabled(true);
  	draggable.set_snap_back_speed(10.0);
  }
  node_tree.dispatch_touch(card_id, &engine, TouchKind::Press, Vector2::create(100.0, 100.0));
  node_tree.dispatch_touch(card_id, &engine, TouchKind::Moved, Vector2::create(200.0, 100.0));
  node_tree.dispatch_touch(card_id, &engine, TouchKind::Release, Vector2::create(200.0, 100.0));
  node_tree.tick(&engine, 0.05);
  assert!((node_tree[card_id].get_local_position().x - 150.0).abs() < 0.001);
  ```

- `pub fn set_drag_start_event(&mut self, drag_start_event: UIDraggableEvent)` (method, since 0.3.2): 시작 이벤트 설정.
  - `drag_start_event` UIDraggableEvent: 눌러 잡을 때 부르는 이벤트. (잡기 전 자리를 기억한 뒤)
- `pub fn set_drag_move_event(&mut self, drag_move_event: UIDraggablePositionEvent)` (method, since 0.3.2): 이동 이벤트 설정.
  - `drag_move_event` UIDraggablePositionEvent: 끄는 동안 움직일 때마다 부르는 이벤트. (노드를 옮긴 뒤, 터치의 뷰 좌표를 받는다)
- `pub fn set_drag_end_event(&mut self, drag_end_event: UIDraggablePositionEvent)` (method, since 0.3.2): 끝 이벤트 설정.
  - `drag_end_event` UIDraggablePositionEvent: 놓거나 터치가 취소되면 부르는 이벤트. (터치의 뷰 좌표를 받는다, 복귀를 켰으면 돌아가기 시작한 뒤라 settle_here 로 멈춘다)
- `pub fn is_dragging(&self) -> bool` (method, since 0.3.2): 끄는 중인지.
  - returns bool: 눌러 잡은 뒤 놓기 전이면 true.
- `pub fn is_returning(&self) -> bool` (method, since 0.3.2): 돌아가는 중인지.
  - returns bool: 제자리로 미끄러지는 중이면 true. (0.5 픽셀 안에 들면 false)
- `pub fn get_home_position(&self) -> Option<Vector2>` (method, since 0.3.2): 잡기 전 로컬 자리. (한 번도 잡지 않았으면 None)
  - returns Option<Vector2>: 제자리. (마지막으로 잡기 전 로컬 자리, settle_here 뒤에는 눌러앉은 자리, 잡은 적이 없으면 None)
