# ui/buttonmotion (vanilla-engine 0.4.0)

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

단추 반응. (vanilla.js ui/buttonmotion.js 의 ButtonMotion, ButtonMotionStyle, attachButtonMotion, setButtonMotionArea, shakeButton)
- 단추 노드에 UIButton 다음으로 붙이면, 프레임마다 그 단추의 상태를 읽어 노드를 가운데를 두고 키우고 줄인다.
  올리면 커지고, 누르는 동안 줄고, 떼면 통 튀고, 누를 수 없을 때 shake 를 부르면 좌우로 흔들린다.
- 색은 건드리지 않는다. (글 단추의 바탕과 글자 색은 화면의 코드가 정하고, 그림 단추는 UIButton 의 틴트가 맡는다)
- 손가락이 주된 기기는 올림을 쓰지 않는다. (뗀 뒤에도 손가락 자리가 남아 올린 채로 보이지 않게)
- 반응이 없을 때는 노드의 자리와 크기를 건드리지 않아, 다른 곳이 같은 노드를 키우는 연출과 겹치지 않는다.
- 꼴은 set_style 로 단추마다 정하거나, 비워 두면 위 노드 가운데 ButtonMotionArea 를 건 가장 가까운 것을 따르고, 없으면 Normal 이다.
- Inset 꼴에서 올린 동안은 단추 바탕 Paint 의 색을 밝히고 안쪽에 흰 테를 그린다. (바탕 Paint 가 없거나 보이지 않는 단추는 밝히지 않는다)
  단추에 얹은 꾸밈이 제 모양으로 밝히게 하려면 set_lit_handler 로 함수를 건다. (그때 단추의 눌림 색은 투명으로 둔다)
  건 함수는 `Rc<RefCell>` 에 담는다. get_lit_handler 는 그 Rc 를 돌려주고, 부르는 쪽은 borrow_mut 로 빌려 부른다.
- 원본과 다른 것: 가운데를 두는 셈이 피봇을 읽는다. (원본은 왼쪽 위 피봇만), 꼴을 거는 표시는 ButtonMotionArea 컴포넌트다. (원본은 WeakMap)
  밝힌 바탕과 흰 테를 자식 노드로 두지 않는다. (원본은 맨 밑 자식 둘, 러스트 예제처럼 글이 같은 노드의 컴포넌트면 자식이 글을 덮는다)

## ButtonLitHandler (type)

밝힘을 맡는 함수. (문맥, 밝히는지, 누르는 중인지)

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

## ButtonMotionArea (struct) (Component)

노드 밑의 단추가 따를 꼴을 거는 표시. (창이 제 판에 건다)

예제: 판 안의 단추를 Inset 꼴로

```rust
use vanilla::{attach_button_motion, set_button_motion_area, ButtonMotionArea, ButtonMotionStyle, Engine, EngineConfiguration, NodeTree, TouchKind, UIButton, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let panel_id = node_tree.create_child(root_id, "Panel");
set_button_motion_area(&mut node_tree, panel_id, ButtonMotionStyle::Inset);
let button_id = node_tree.create_child(panel_id, "Button");
node_tree[button_id].set_content_size(Vector2::create(120.0, 40.0));
node_tree.add_component(button_id, UIButton::new());
attach_button_motion(&mut node_tree, button_id).expect("button motion");

node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, Vector2::zero());
node_tree.tick(&engine, 0.1);
let pressed_scale = node_tree[button_id].get_local_scale();
assert!((pressed_scale.x - 0.96).abs() < 0.001);
let area = node_tree[panel_id].get_component::<ButtonMotionArea>().expect("area");
assert_eq!(area.get_style(), ButtonMotionStyle::Inset);
```

- `pub fn new(style: ButtonMotionStyle) -> ButtonMotionArea` (constructor, since 0.4.0): 생성. (노드에 걸 때는 set_button_motion_area 를 쓴다)
  - `style` ButtonMotionStyle: 이 노드 밑의 단추가 따를 꼴.
  - returns ButtonMotionArea: 그 꼴을 거는 표시.
- `pub fn get_style(&self) -> ButtonMotionStyle` (method, since 0.4.0): 건 꼴 반환.
  - returns ButtonMotionStyle: 이 노드 밑의 단추가 따를 꼴.

## ButtonMotion (struct) (Default, Component)

단추 반응. (단추 노드에 UIButton 다음으로 붙어, 단추 상태에 따라 노드를 가운데를 두고 키우고 줄인다)

예제: 눌러지는 단추와 누를 수 없을 때 흔들기

```rust
use vanilla::{attach_button_motion, shake_button, Engine, EngineConfiguration, NodeTree, Paint, TouchKind, UIButton, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let button_id = node_tree.create_child(root_id, "PlayButton");
node_tree[button_id].set_local_position(Vector2::create(200.0, 100.0));
node_tree[button_id].set_content_size(Vector2::create(160.0, 48.0));
node_tree[button_id].add_component(Paint::create_with_color("#3b82f6"));
node_tree.add_component(button_id, UIButton::new());
attach_button_motion(&mut node_tree, button_id).expect("button motion");

node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, Vector2::create(200.0, 100.0));
node_tree.tick(&engine, 0.05);
let pressed_scale = node_tree[button_id].get_local_scale();
assert!((pressed_scale.x - 0.92).abs() < 0.001);

node_tree.dispatch_touch(button_id, &engine, TouchKind::Cancel, Vector2::create(200.0, 100.0));
for _frame_index in 0..30 {
	node_tree.tick(&engine, 0.05);
}
assert_eq!(node_tree[button_id].get_local_scale(), Vector2::create(1.0, 1.0));
assert_eq!(node_tree[button_id].get_local_position(), Vector2::create(200.0, 100.0));

node_tree[button_id].get_component_mut::<UIButton>().expect("button").set_interactable(false);
shake_button(&mut node_tree, button_id);
node_tree.tick(&engine, 0.05);
assert_ne!(node_tree[button_id].get_local_position().x, 200.0);
```

- `pub fn new() -> ButtonMotion` (constructor, since 0.4.0): 생성.
  - returns ButtonMotion: 꼴을 정하지 않은 새 단추 반응. (위 노드에 건 꼴을 따른다, 단추 노드에 붙일 때는 attach_button_motion 을 쓴다)
- `pub fn set_style(&mut self, style: Option<ButtonMotionStyle>)` (method, since 0.4.0): 이 단추의 꼴 설정. (None 이면 위 노드에 건 꼴을 따른다)
  - `style` Option<ButtonMotionStyle>: 이 단추의 꼴. (None 이면 위 노드에 건 가장 가까운 꼴, 그것도 없으면 Normal)
- `pub fn shake(&mut self)` (method, since 0.4.0): 누를 수 없을 때 흔들기. (누른 쪽에서 부른다)
- `pub fn set_lit_handler(&mut self, lit_handler: Option<ButtonLitHandler>)` (method, since 0.4.0): 밝힘을 맡는 함수 설정. (None 이면 이 부품이 바탕 Paint 의 색을 밝히고 draw 가 안쪽 흰 테를 그린다)
  - `lit_handler` Option<ButtonLitHandler>: 밝힘을 맡을 함수. (문맥, 밝히는지, 누르는 중인지를 받아 tick 마다 불린다, None 이면 함수를 뗀다)

  예제: 얹은 빛 노드로 밝히기

  ```rust
  use vanilla::{attach_button_motion, ButtonMotionStyle, ComponentContext, Engine, EngineConfiguration, NodeTree, TouchKind, UIButton, Vector2};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let button_id = node_tree.create_child(root_id, "Button");
  let glow_id = node_tree.create_child(button_id, "Glow");
  node_tree[glow_id].set_visible(false);
  node_tree.add_component(button_id, UIButton::new());
  let button_motion = attach_button_motion(&mut node_tree, button_id).expect("button motion");
  button_motion.set_style(Some(ButtonMotionStyle::Inset));
  button_motion.set_lit_handler(Some(Box::new(move |context: &mut ComponentContext, is_lit: bool, _is_pressed: bool| {
  	context.get_node_tree_mut()[glow_id].set_visible(is_lit);
  })));
  
  node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, Vector2::zero());
  node_tree.tick(&engine, 0.016);
  assert_eq!(node_tree[glow_id].is_visible(), !engine.is_coarse_pointer());
  ```

- `pub fn get_lit_handler(&self) -> Option<Rc<RefCell<ButtonLitHandler>>>` (method, since 0.4.0): 밝힘을 맡는 함수 반환. (부를 때는 borrow_mut 로 빌린다)
  - returns Option<Rc<RefCell<ButtonLitHandler>>>: 건 밝힘 함수. 걸지 않았으면 None.

## Functions and constants

- `pub fn set_button_motion_area(node_tree: &mut NodeTree, node_id: NodeId, style: ButtonMotionStyle)` (method, since 0.4.0): 노드 밑의 단추가 따를 꼴 걸기. (창이 제 판에 Inset 을 걸면 그 안의 단추는 커지지 않는다, 단추가 set_style 로 정한 꼴이 먼저)
  - `node_tree` &mut NodeTree: 노드 트리.
  - `node_id` NodeId: 꼴을 걸 노드. (창의 판 같은, 이미 ButtonMotionArea 가 붙어 있으면 꼴만 바꾸고 노드가 없으면 아무 일도 없다)
  - `style` ButtonMotionStyle: 그 노드 밑의 단추가 따를 꼴. (단추에서 위로 거슬러 올라 가장 가까운 것을 따른다)
- `pub fn attach_button_motion(node_tree: &mut NodeTree, node_id: NodeId) -> Option<&mut ButtonMotion>` (method, since 0.4.0): 단추 노드에 반응 붙이기. (UIButton 이 이미 붙은 노드, 붙인 ButtonMotion 을 돌려준다. 원본 attachButtonMotion)
  - `node_tree` &mut NodeTree: 노드 트리.
  - `node_id` NodeId: UIButton 이 이미 붙은 단추 노드. (반응은 UIButton 다음 컴포넌트로 붙는다)
  - returns Option<&mut ButtonMotion>: 붙인 ButtonMotion. 노드가 없으면 None.
- `pub fn shake_button(node_tree: &mut NodeTree, node_id: NodeId)` (method, since 0.4.0): 단추 흔들기. (노드의 ButtonMotion 을 찾아 흔든다, 없으면 아무 일도 없다)
  - 0.25 초 동안 좌우로 흔들린다.
  - `node_tree` &mut NodeTree: 노드 트리.
  - `node_id` NodeId: ButtonMotion 이 붙은 단추 노드.

## ButtonMotionStyle (enum) (Clone, Copy, PartialEq, Eq, Debug)

단추 반응의 꼴.

- `Normal`: 올리면 커지고, 누르는 동안 줄고, 떼면 통 튄다.
- `Inset`: 창 안의 단추. 1 배를 넘게 커지지 않아 창 안쪽 여백을 넘지 않는다. 올리면 바탕이 밝아지고 안쪽에 흰 테가 서며, 누르면 조금 줄었다 돌아온다.
