# ui/uibutton (vanilla-engine 0.4.0)

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

Button. (UIButton, ButtonState of the original ui/uibutton.js)
- Press / release / cancel / click / long press / mouse over events, and a tint transition that changes color when pressed or hovered.
- A click happens only when pressed and then released inside the button area. (a press that fired a long press swallows the click)
- As in the original, the tint applies to Sprite / UIImageView (cover color) and Paint / Text / UILabel (original color interpolation) of the host node and all descendants.
  Other components of the host node are found as siblings during tick / touch. (NodeTree briefly takes out only the component it is calling)
  In the original, Sprite inherits Paint, so it is also caught by getComponents(Paint). So sprites get the original color interpolation once more after the cover color,
  and the later one wins. To produce the same result, the Rust version also holds sprites (and UIImageView's sprites) twice.
- Differences from the original:
  - Events are `Box<dyn FnMut(&mut UIButton, &mut ComponentContext)>`. Original callbacks take only the button.
    The context is passed along so callbacks can change, create, and delete other nodes. (the bool return of click events was dropped because the original never used it either)
    Received events are stored in `Rc<RefCell>`. Event getters return that Rc, and the caller borrows it with borrow_mut and calls it with the button and the context.
    If the same event is called again while it is being called (like fire_click_events inside the callback), it is skipped because it is already borrowed.
  - The original setInteractable / UIToggleButton.set_is_on gather the color targets and apply the tint on the spot. The Rust version cannot reach the nodes there, so
    it gathers and applies them on the next tick. (tick reapplies the tint every frame, so the visible result is the same)
  - Excluded components are specified by (node, component type) instead of instance: `exclude_component_from_tint::<Paint>`(node_id).
  - setStateEvent (an empty function in the original too) was not ported.
- attach_to_tree turns the host node interactable. Attach with node_tree.add_component(node_id, UIButton::new()).

## UIButtonEvent (type)

Button event. (takes the button and the context)

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

## UIButton (struct) (Default, Component)

Button.

Example: Make a button with text

```rust
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, Paint, Text, 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, "OkButton");
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[button_id].add_component(Text::create_with_text("OK", 24.0));
let click_count = Rc::new(Cell::new(0));
let click_count_for_event = click_count.clone();
let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
button.set_click_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
	click_count_for_event.set(click_count_for_event.get() + 1);
}));
assert!(node_tree[button_id].is_interactable());

let inside = Vector2::create(210.0, 105.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, inside);
assert_eq!(click_count.get(), 1);

let outside = Vector2::create(400.0, 105.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, outside);
assert_eq!(click_count.get(), 1);
```

- `pub fn new() -> UIButton` (constructor, since 0.3.2): Constructor.
  - To attach to a tree, use node_tree.add_component(node_id, UIButton::new()). (on attach, creates the content node and turns the host node interactable)
  - returns UIButton: New button with no events. (long press 0.5 seconds, minimum press 0 seconds, pressed tint black alpha 0.3, over tint white alpha 0.12, transition 0.3 seconds)
- `pub fn get_uicontrol(&self) -> &UIControl` (method, since 0.3.2): Returns the embedded control.
  - returns &UIControl: The embedded UIControl.
- `pub fn get_uicontrol_mut(&mut self) -> &mut UIControl` (method, since 0.3.2): Returns the embedded control. (mutable)
  - returns &mut UIControl: The embedded UIControl.
- `pub fn get_content(&self) -> Option<NodeId>` (method, since 0.3.2): Content node handle.
  - returns Option<NodeId>: Content node created under the host node. None before being attached to a tree.
- `pub fn exclude_node_from_tint(&mut self, node_id: NodeId)` (method, since 0.3.2): Excludes a node from the transition targets. (components of that node and all its descendants drop out of the color targets)
  - Takes effect the next time color targets are gathered (press, over, disabled).
  - `node_id` NodeId: Node to exclude from the tint. (unchanged if already included)

  Example: Keep a badge inside the button untinted

  ```rust
  use vanilla::{Color, 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, "Button");
  node_tree[button_id].set_content_size(Vector2::create(100.0, 40.0));
  node_tree[button_id].add_component(Paint::create_with_color(Color::white()));
  let badge_id = node_tree.create_child(button_id, "Badge");
  node_tree[badge_id].add_component(Paint::create_with_color(Color::white()));
  let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
  button.exclude_node_from_tint(badge_id);
  
  node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, Vector2::zero());
  node_tree.tick(&engine, 0.3);
  let button_color = node_tree[button_id].get_component::<Paint>().expect("paint").get_color();
  let badge_color = node_tree[badge_id].get_component::<Paint>().expect("paint").get_color();
  assert!((button_color.red - 0.7).abs() < 0.001);
  assert_eq!(badge_color, Color::white());
  ```

- `pub fn exclude_component_from_tint<T: Component + 'static>(&mut self, node_id: NodeId)` (method, since 0.3.2): Excludes only the T-type components of that node from the transition targets. (the original takes a component instance)
  - Takes effect the next time color targets are gathered. T on descendant nodes is not excluded.
  - `node_id` NodeId: Node whose T-type component to exclude. (the host node or one of its descendants)

  Example: Tint only the text and leave the background Paint as is

  ```rust
  use vanilla::{Color, Engine, EngineConfiguration, NodeTree, Paint, Text, 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");
  node_tree[button_id].set_content_size(Vector2::create(100.0, 40.0));
  node_tree[button_id].add_component(Paint::create_with_color(Color::white()));
  node_tree[button_id].add_component(Text::create_with_text("OK", 20.0));
  let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
  button.exclude_component_from_tint::<Paint>(button_id);
  
  node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, Vector2::zero());
  node_tree.tick(&engine, 0.3);
  let paint_color = node_tree[button_id].get_component::<Paint>().expect("paint").get_color();
  let text_color = node_tree[button_id].get_component::<Text>().expect("text").get_text_color();
  assert_eq!(paint_color, Color::white());
  assert!(text_color.red < 1.0);
  ```

- `pub fn clear_tint_exclusions(&mut self)` (method, since 0.3.2): Clears the exclusion list.
- `pub fn fire_click_events(&mut self, context: &mut ComponentContext)` (method, since 0.4.0): Fires only the click notifications. (Clicked, then Click, as if clicked without pressing, for forwarding a click on the area widened by UIHitArea)
  - An event currently being called is skipped. (calling it inside the clicked event fires only the click once more)
  - `context` &mut ComponentContext: Context of this button node. (passed straight to the events)

  Example: Forward another button's click to this button

  ```rust
  use std::cell::Cell;
  use std::rc::Rc;
  use vanilla::{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 click_count = Rc::new(Cell::new(0));
  let click_count_for_event = click_count.clone();
  let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
  button.set_click_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
  	click_count_for_event.set(click_count_for_event.get() + 1);
  }));
  
  let relay_id = node_tree.create_child(root_id, "Relay");
  node_tree[relay_id].set_content_size(Vector2::create(40.0, 40.0));
  let relay_button = node_tree.add_component(relay_id, UIButton::new()).expect("relay");
  relay_button.set_click_event(Box::new(move |_relay_button: &mut UIButton, context: &mut ComponentContext| {
  	context.with_component_mut::<UIButton, ()>(button_id, |button, button_context| {
  		button.fire_click_events(button_context);
  	});
  }));
  node_tree.dispatch_touch(relay_id, &engine, TouchKind::Press, Vector2::zero());
  node_tree.dispatch_touch(relay_id, &engine, TouchKind::Release, Vector2::zero());
  assert_eq!(click_count.get(), 1);
  ```

- `pub fn set_button_state(&mut self, button_state: ButtonState)` (method, since 0.3.2): Sets the button state.
  - `button_state` ButtonState: New state. (does not fire events or reapply the tint)
- `pub fn get_button_state(&self) -> ButtonState` (method, since 0.3.2): Returns the button state.
  - returns ButtonState: The current state.
- `pub fn set_long_pressed_event(&mut self, long_pressed_event: UIButtonEvent)` (method, since 0.3.2): Sets the long press event. (notifies once past the threshold time and swallows that press's click)
  - The threshold time is set with set_long_press_seconds. Time is counted in tick.
  - `long_pressed_event` UIButtonEvent: Function called on a long press. (takes the button and the context)

  Example: Delete on a long press, open on a short press

  ```rust
  use std::cell::Cell;
  use std::rc::Rc;
  use vanilla::{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, "Slot");
  node_tree[button_id].set_content_size(Vector2::create(80.0, 80.0));
  let delete_count = Rc::new(Cell::new(0));
  let open_count = Rc::new(Cell::new(0));
  let delete_count_for_event = delete_count.clone();
  let open_count_for_event = open_count.clone();
  let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
  button.set_long_press_seconds(0.5);
  button.set_long_pressed_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
  	delete_count_for_event.set(delete_count_for_event.get() + 1);
  }));
  button.set_click_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
  	open_count_for_event.set(open_count_for_event.get() + 1);
  }));
  
  node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, Vector2::zero());
  node_tree.tick(&engine, 0.3);
  node_tree.tick(&engine, 0.3);
  node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, Vector2::zero());
  assert_eq!(delete_count.get(), 1);
  assert_eq!(open_count.get(), 0);
  
  node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, Vector2::zero());
  node_tree.tick(&engine, 0.1);
  node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, Vector2::zero());
  assert_eq!(delete_count.get(), 1);
  assert_eq!(open_count.get(), 1);
  ```

- `pub fn get_pressed_elapsed_seconds(&self) -> f64` (method, since 0.3.2): Returns how long the current press has lasted. (0 if not pressing. for gauge effects)
  - returns f64: Seconds since the press. (accumulated in tick, 0 if not pressing)
- `pub fn set_long_press_seconds(&mut self, long_press_seconds: f64)` (method, since 0.3.2): Sets the long press threshold time. (seconds)
  - `long_press_seconds` f64: A press lasting this long counts as a long press. (seconds, default 0.5)
- `pub fn get_long_press_seconds(&self) -> f64` (method, since 0.3.2): Returns the long press threshold time.
  - returns f64: Long press threshold time. (seconds)
- `pub fn set_minimum_pressed_seconds(&mut self, minimum_pressed_seconds: f64)` (method, since 0.3.2): Sets the minimum pressed display time. (even a short press shows the pressed look for this long before clicking. default 0 = immediate)
  - A release before the time is up is deferred and handled in tick, and the state stays Pressed meanwhile.
  - `minimum_pressed_seconds` f64: Minimum pressed display time. (seconds, 0 if less than 0)

  Example: Show the pressed look for 0.2 seconds even on a tap

  ```rust
  use std::cell::Cell;
  use std::rc::Rc;
  use vanilla::{ButtonState, 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");
  node_tree[button_id].set_content_size(Vector2::create(100.0, 40.0));
  let click_count = Rc::new(Cell::new(0));
  let click_count_for_event = click_count.clone();
  let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
  button.set_minimum_pressed_seconds(0.2);
  button.set_click_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
  	click_count_for_event.set(click_count_for_event.get() + 1);
  }));
  
  node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, Vector2::zero());
  node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, Vector2::zero());
  let button_state = node_tree[button_id].get_component::<UIButton>().expect("button").get_button_state();
  assert_eq!(button_state, ButtonState::Pressed);
  assert_eq!(click_count.get(), 0);
  node_tree.tick(&engine, 0.25);
  assert_eq!(click_count.get(), 1);
  ```

- `pub fn get_minimum_pressed_seconds(&self) -> f64` (method, since 0.3.2): Returns the minimum pressed display time.
  - returns f64: Minimum pressed display time. (seconds, default 0)
- `pub fn set_click_event(&mut self, click_event: UIButtonEvent)` (method, since 0.3.2): Sets the click event. (called after the clicked event)
  - A click happens only when pressed and then released inside the button area. A press that fired a long press swallows the click.
  - `click_event` UIButtonEvent: Function called on click. (takes the button and the context, the context can change other nodes)

  Example: Hide the panel when the close button is clicked

  ```rust
  use vanilla::{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 panel_id = node_tree.create_child(root_id, "Panel");
  let close_id = node_tree.create_child(root_id, "Close");
  node_tree[close_id].set_content_size(Vector2::create(40.0, 40.0));
  let close_button = node_tree.add_component(close_id, UIButton::new()).expect("button");
  close_button.set_click_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
  	context.get_node_tree_mut()[panel_id].set_visible(false);
  }));
  
  node_tree.dispatch_touch(close_id, &engine, TouchKind::Press, Vector2::zero());
  node_tree.dispatch_touch(close_id, &engine, TouchKind::Release, Vector2::zero());
  assert!(!node_tree[panel_id].is_visible());
  ```

- `pub fn get_click_event(&self) -> Option<Rc<RefCell<UIButtonEvent>>>` (method, since 0.4.0): Returns the click event. (borrow it with borrow_mut to call it)
  - returns Option<Rc<RefCell<UIButtonEvent>>>: The set click event. None if not set.

  Example: Take out and call the click event the moment it is pressed

  ```rust
  use std::cell::Cell;
  use std::rc::Rc;
  use vanilla::{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 click_count = Rc::new(Cell::new(0));
  let click_count_for_event = click_count.clone();
  let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
  assert!(button.get_click_event().is_none());
  button.set_click_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
  	click_count_for_event.set(click_count_for_event.get() + 1);
  }));
  button.set_pressed_event(Box::new(|button: &mut UIButton, context: &mut ComponentContext| {
  	if let Some(click_event) = button.get_click_event() {
  		(*click_event.borrow_mut())(button, context);
  	}
  }));
  
  node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, Vector2::zero());
  assert_eq!(click_count.get(), 1);
  ```

- `pub fn set_pressed_event(&mut self, pressed_event: UIButtonEvent)` (method, since 0.3.2): Sets the press event.
  - `pressed_event` UIButtonEvent: Function called on press. (takes the button and the context, not called if not pressable)
- `pub fn get_pressed_event(&self) -> Option<Rc<RefCell<UIButtonEvent>>>` (method, since 0.4.0): Returns the press event. (borrow it with borrow_mut to call it)
  - returns Option<Rc<RefCell<UIButtonEvent>>>: The set press event. None if not set.
- `pub fn set_released_event(&mut self, released_event: UIButtonEvent)` (method, since 0.3.2): Sets the release event. (called even when released outside the area)
  - `released_event` UIButtonEvent: Function called on release. (takes the button and the context, called before the clicked and click events, not called on cancel)
- `pub fn get_released_event(&self) -> Option<Rc<RefCell<UIButtonEvent>>>` (method, since 0.4.0): Returns the release event. (borrow it with borrow_mut to call it)
  - returns Option<Rc<RefCell<UIButtonEvent>>>: The set release event. None if not set.
- `pub fn set_clicked_event(&mut self, clicked_event: UIButtonEvent)` (method, since 0.3.2): Sets the clicked event.
  - `clicked_event` UIButtonEvent: Function called before the click event on click. (takes the button and the context)
- `pub fn get_clicked_event(&self) -> Option<Rc<RefCell<UIButtonEvent>>>` (method, since 0.4.0): Returns the clicked event. (borrow it with borrow_mut to call it)
  - returns Option<Rc<RefCell<UIButtonEvent>>>: The set clicked event. None if not set.
- `pub fn set_hover_tint_color(&mut self, color: impl Into<Color>)` (method, since 0.3.2): Sets the over tint color.
  - `color` impl Into<Color>: Color to cover or blend with when hovered. (alpha is the strength, default white alpha 0.12)
- `pub fn get_hover_tint_color(&self) -> Color` (method, since 0.3.2): Returns the over tint color.
  - returns Color: Hover tint color.
- `pub fn set_hover_event(&mut self, hover_event: UIButtonEvent)` (method, since 0.3.2): Sets the over enter event.
  - `hover_event` UIButtonEvent: Function called once when the mouse enters the button. (takes the button and the context)
- `pub fn get_hover_event(&self) -> Option<Rc<RefCell<UIButtonEvent>>>` (method, since 0.4.0): Returns the over enter event. (borrow it with borrow_mut to call it)
  - returns Option<Rc<RefCell<UIButtonEvent>>>: The set over enter event. None if not set.
- `pub fn set_pressed_tint_color(&mut self, color: impl Into<Color>)` (method, since 0.3.2): Sets the pressed tint color.
  - `color` impl Into<Color>: Color to cover or blend with when pressed. (alpha is the strength, default black alpha 0.3)
- `pub fn get_pressed_tint_color(&self) -> Color` (method, since 0.3.2): Returns the pressed tint color.
  - returns Color: Pressed tint color.
- `pub fn set_transition_duration(&mut self, transition_duration: f64)` (method, since 0.3.2): Sets the transition time. (seconds)
  - `transition_duration` f64: Time for the tint to fully fill in or fade out. (seconds, default 0.3)
- `pub fn get_transition_duration(&self) -> f64` (method, since 0.3.2): Returns the transition time.
  - returns f64: Transition time. (seconds)
- `pub fn set_interactable(&mut self, is_interactable: bool)` (method, since 0.3.2): Sets whether it is enabled. (when turned off, gathers color targets on the next tick and applies a dark tint)
  - `is_interactable` bool: true to make it pressable. (off sets the state to Disabled, on sets Normal, unchanged if the same as now)
- `pub fn get_interactable(&self) -> bool` (method, since 0.3.2): Whether it is enabled.
  - returns bool: true if pressable. (default true)

## ButtonState (enum) (Clone, Copy, Debug, PartialEq, Eq, crate::core::reflection::ToReflectValue)

Button state.

- `Normal`: Normal. (neither pressed nor hovered)
- `Hover`: Mouse hovering over it.
- `Pressed`: Being pressed. (also while the release is deferred to fill the minimum press time)
- `Released`: Handling the release. (only while firing the release and click events, then Normal)
- `Disabled`: Not pressable. (set_interactable(false))
