# ui/uibutton (vanilla.js 0.4.0)

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

버튼.

## UIButton extends UIControl

버튼.

예제: 글자가 있는 단추 만들기

```js
import { Engine, EngineConfiguration, UIScene, UIButton, UILabel, Paint, WorldNode, Pivot, Vector2, Color } from "./build/vanilla.js";

class MainScene extends UIScene {
	constructor() {
		super();
		this.setLoadingMinDurationMs(0);
	}

	initialize(engine) {
		super.initialize(engine);
		const buttonNode = new WorldNode();
		buttonNode.setPivot(Pivot.topLeft);
		buttonNode.setAnchor(Pivot.topLeft);
		buttonNode.setLocalPosition(Vector2.create(40, 40));
		buttonNode.setContentSize(Vector2.create(200, 60));
		const paint = buttonNode.addComponent(Paint);
		paint.setColor(new Color(0.2, 0.45, 0.85, 1));
		paint.setRoundSize(12);
		const label = buttonNode.addComponent(UILabel);
		label.setText("Start");
		label.setFontSize(24);
		const button = buttonNode.addComponent(UIButton);
		button.setPressedTintColor(new Color(0, 0, 0, 0.35));
		button.setTransitionDuration(0.15);
		button.setClickedEvent((clickedButton) => {
			console.log("start", clickedButton.getButtonState());
		});
		const root = this.getRoot();
		root.addChild(buttonNode);
	}
}

const engineConfiguration = new EngineConfiguration();
engineConfiguration.canvasId = "mainCanvas";
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
engineConfiguration.autoResizeOnWindowResize = true;
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.2.0): 생성.
- `excludeNodeFromTint(node)` (method, since 0.2.1): 트랜지션 대상에서 노드를 제외. 해당 노드 자신과 모든 자손 노드의 컴포넌트가
  색상 수집에서 제외된다.
  - `node` ComponentNode: 틴트에서 뺄 노드. (자손 노드까지 빠진다)

  예제: 단추 안의 배지는 틴트하지 않기

  ```js
  import { Engine, EngineConfiguration, UIScene, UIButton, Paint, WorldNode, Pivot, Vector2, Color } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingMinDurationMs(0);
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		const buttonNode = new WorldNode();
  		buttonNode.setPivot(Pivot.topLeft);
  		buttonNode.setAnchor(Pivot.topLeft);
  		buttonNode.setLocalPosition(Vector2.create(40, 40));
  		buttonNode.setContentSize(Vector2.create(200, 60));
  		const paint = buttonNode.addComponent(Paint);
  		paint.setColor(new Color(0.2, 0.45, 0.85, 1));
  
  		const badgeNode = new WorldNode();
  		badgeNode.setPivot(Pivot.topLeft);
  		badgeNode.setAnchor(Pivot.topLeft);
  		badgeNode.setLocalPosition(Vector2.create(176, -8));
  		badgeNode.setContentSize(Vector2.create(24, 24));
  		const badgePaint = badgeNode.addComponent(Paint);
  		badgePaint.setColor(new Color(0.9, 0.2, 0.2, 1));
  		badgePaint.setRoundSize(12);
  		buttonNode.addChild(badgeNode);
  
  		const button = buttonNode.addComponent(UIButton);
  		button.excludeNodeFromTint(badgeNode);
  		const root = this.getRoot();
  		root.addChild(buttonNode);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `excludeComponentFromTint(component)` (method, since 0.2.1): 트랜지션 대상에서 특정 컴포넌트만 제외.
  - `component` Component: 틴트에서 뺄 컴포넌트.
- `clearTintExclusions()` (method, since 0.2.1): 제외 목록 초기화.
- `attach(node)` (method, since 0.2.0): 노드에 붙음. (노드의 isInteractable 을 자동 활성화, WorldNode 와 UINode)
  - `node` ComponentNode: 붙을 노드.
- `tick(timeDelta)` (method, since 0.2.0): 갱신.
  - `timeDelta` number: 지난 프레임부터의 시간. (초)
- `updateHoverState()` (method, since 0.3.0): 마우스 오버 상태 갱신.
  - 누르고 있는 중이거나 사용 불가일 때는 건드리지 않는다.
  - 엔진 인스턴스는 전역 접근자로 얻어 순환 참조를 만들지 않는다.
- `draw(graphic)` (method, since 0.2.0): 출력.
  - `graphic` Graphic: 그래픽.
- `isDrawnInsideContent()` (method, since 0.4.0): 내용 영역 안에서만 그리는지 반환. (버튼은 스스로 그리지 않는다, 화면 밖과 자르기 밖 거르기가 쓴다)
  - draw 를 덮어쓴 하위 클래스는 어디에 그리는지 모르므로 false. (그 클래스가 이 함수도 덮어써 알린다)
  - returns boolean: 내용 영역 안에서만 그리면 참.
- `touchPress(viewInputPosition)` (method, since 0.2.0): 터치 누름. (TouchRaycaster → WorldNode → Button)
  - `viewInputPosition` Vector2: 누른 자리. (뷰 좌표)
- `touchRelease(viewInputPosition)` (method, since 0.2.0): 터치 뗌. (TouchRaycaster → WorldNode → Button)
  - `viewInputPosition` Vector2: 뗀 자리. (뷰 좌표)
- `performRelease(viewInputPosition)` (method, since 0.3.0): 뗌 처리 본문.
  - `viewInputPosition` Vector2: 뗀 자리. (뷰 좌표, 노드 안이면 클릭으로 친다)
- `fireClickEvents()` (method, since 0.4.0): 클릭 알림만 부르기. (누르지 않고 클릭이 난 것처럼 clicked, click 차례로, UIHitArea 가 넓힌 자리의 클릭을 넘길 때)
- `touchCancel(viewInputPosition)` (method, since 0.2.0): 터치 취소. (TouchRaycaster → WorldNode → Button)
  - `viewInputPosition` Vector2: 취소된 때의 자리. (뷰 좌표)
- `applyTintProgress(progress)` (method, since 0.2.0): 틴트 적용.
  - `progress` number: 틴트 정도. (0 이면 원래 색, 1 이면 틴트 색을 다 씌운다)
- `collectColorTargets()` (method, since 0.2.0): 색상 대상 수집.
- `collectFromNode(node)` (method, since 0.2.0): 노드에서 색상 대상 재귀 수집.
  - excludeNodeFromTint 로 등록된 노드는 자신과 자손까지 통째로 건너뛴다.
  - excludeComponentFromTint 로 등록된 컴포넌트는 개별적으로 제외한다.
  - `node` ComponentNode: 훑을 노드. (자식들도 차례로 훑는다)
- `setButtonState(buttonState)` (method, since 0.2.0): 버튼 상태 변경.
  - `buttonState` ButtonState: 버튼 상태. (ButtonState 의 값)
- `getButtonState()` (method, since 0.2.0): 버튼 상태 반환.
  - returns ButtonState: 지금 버튼 상태. (ButtonState 의 값)
- `setLongPressedEvent(longPressedEvent)` (method, since 0.3.0): 길게 누름 알림 설정. (임계 시간을 넘기면 한 번 알리고, 그 누름의 클릭은 삼킨다)
  - `longPressedEvent` function(UIButton): void: 길게 누르면 한 번 부를 함수. (인자는 이 버튼, null 이면 길게 누름을 보지 않는다)

  예제: 길게 누르면 지우고 짧게 누르면 열기

  ```js
  import { Engine, EngineConfiguration, UIScene, UIButton, Paint, WorldNode, Pivot, Vector2, Color } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingMinDurationMs(0);
  		this.button = null;
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		const itemNode = new WorldNode();
  		itemNode.setPivot(Pivot.topLeft);
  		itemNode.setAnchor(Pivot.topLeft);
  		itemNode.setLocalPosition(Vector2.create(40, 40));
  		itemNode.setContentSize(Vector2.create(96, 96));
  		const paint = itemNode.addComponent(Paint);
  		paint.setColor(new Color(0.3, 0.3, 0.35, 1));
  		const button = itemNode.addComponent(UIButton);
  		button.setLongPressSeconds(0.8);
  		button.setLongPressedEvent(() => {
  			console.log("delete item");
  		});
  		button.setClickedEvent(() => {
  			console.log("open item");
  		});
  		this.button = button;
  		const root = this.getRoot();
  		root.addChild(itemNode);
  	}
  
  	tick(timeDelta) {
  		super.tick(timeDelta);
  		if (this.button !== null) {
  			const pressedSeconds = this.button.getPressedElapsedSeconds();
  			const longPressSeconds = this.button.getLongPressSeconds();
  			const gaugeRatio = Math.min(1, pressedSeconds / longPressSeconds);
  			if (gaugeRatio > 0) {
  				console.log("hold", gaugeRatio);
  			}
  		}
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `setLongPressSeconds(longPressSeconds)` (method, since 0.3.0): 길게 누름 판정 시간 설정. (초)
  - `longPressSeconds` number: 길게 누름으로 볼 시간. (초, 기본 0.5)
- `getPressedElapsedSeconds()` (method, since 0.3.0): 이번 누름이 이어진 시간 반환. (게이지 연출용)
  - returns number: 이번 누름이 이어진 시간. (초, 누르고 있지 않으면 0)
- `getLongPressSeconds()` (method, since 0.3.0): 길게 누름 판정 시간 반환.
  - returns number: 길게 누름 판정 시간. (초)
- `setMinimumPressedSeconds(minimumPressedSeconds)` (method, since 0.3.0): 최소 눌림 표시 시간 설정. (짧게 톡 눌러도 이 시간만큼 눌린 모습을 보인 뒤 클릭을 부른다)
  - `minimumPressedSeconds` number: 눌린 모습을 보여 줄 가장 짧은 시간. (초, 0 보다 작으면 0, 기본 0 이면 바로)
- `getMinimumPressedSeconds()` (method, since 0.3.0): 최소 눌림 표시 시간 반환.
  - returns number: 최소 눌림 표시 시간. (초)
- `setClickEvent(callback)` (method, since 0.2.0): 클릭 이벤트 설정.
  - `callback` function(UIButton): boolean: 클릭이 나면 클릭됨 이벤트 다음에 부를 함수. (인자는 이 버튼, 돌려준 값은 쓰지 않는다, null 이면 부르지 않는다)
- `getClickEvent()` (method, since 0.2.0): 클릭 이벤트 반환.
  - returns function(UIButton): boolean: 클릭 이벤트 함수. (없으면 null)
- `setPressedEvent(callback)` (method, since 0.2.0): 누름 이벤트 설정.
  - `callback` function(UIButton): void: 누르면 부를 함수. (인자는 이 버튼, 누를 수 없는 상태면 부르지 않는다)
- `getPressedEvent()` (method, since 0.2.0): 누름 이벤트 반환.
  - returns function(UIButton): void: 누름 이벤트 함수. (없으면 null)
- `setReleasedEvent(callback)` (method, since 0.2.0): 뗌 이벤트 설정.
  - `callback` function(UIButton): void: 누른 뒤 떼면 부를 함수. (인자는 이 버튼, 노드 밖에서 떼도 부른다)
- `getReleasedEvent()` (method, since 0.2.0): 뗌 이벤트 반환.
  - returns function(UIButton): void: 뗌 이벤트 함수. (없으면 null)
- `setClickedEvent(callback)` (method, since 0.2.0): 클릭됨 이벤트 설정.
  - `callback` function(UIButton): void: 누른 뒤 노드 안에서 떼면 부를 함수. (인자는 이 버튼, 길게 누름을 알렸으면 부르지 않는다, null 이면 부르지 않는다)
- `getClickedEvent()` (method, since 0.2.0): 클릭됨 이벤트 반환.
  - returns function(UIButton): void: 클릭됨 이벤트 함수. (없으면 null)
- `setHoverTintColor(color)` (method, since 0.3.0): 눌림 틴트 색상 설정.
  - `color` Color | string: 마우스가 올라 있을 때 덮을 틴트 색. (사본을 담는다, 기본 new Color(1, 1, 1, 0.12))
- `getHoverTintColor()` (method, since 0.3.0): 오버 틴트 색상 반환.
  - returns Color: 오버 틴트 색.
- `setHoverEvent(callback)` (method, since 0.3.0): 오버 진입 이벤트 설정.
  - `callback` function(UIButton): void: 마우스가 노드 위로 들어오면 부를 함수. (인자는 이 버튼)
- `getHoverEvent()` (method, since 0.3.0): 오버 진입 이벤트 반환.
  - returns function(UIButton): void: 오버 진입 이벤트 함수. (없으면 null)
- `setPressedTintColor(color)` (method, since 0.2.0): 눌림 틴트 색상 설정.
  - `color` Color | string: 누르는 동안 덮을 틴트 색. (기본 new Color(0, 0, 0, 0.3))
- `getPressedTintColor()` (method, since 0.2.0): 눌림 틴트 색상 반환.
  - returns Color: 눌림 틴트 색.
- `setTransitionDuration(duration)` (method, since 0.2.0): 트랜지션 지속 시간 설정.
  - `duration` number: 틴트가 다 씌워지거나 걷히는 데 걸리는 시간. (초, 기본 0.3)
- `getTransitionDuration()` (method, since 0.2.0): 트랜지션 지속 시간 반환.
  - returns number: 트랜지션 지속 시간. (초)
- `setInteractable(isInteractable)` (method, since 0.2.0): 활성화 여부 설정.
  - `isInteractable` boolean: 거짓이면 누름을 받지 않고 스프라이트에 비활성 틴트를 덮는다. (기본 참)
- `getInteractable()` (method, since 0.2.0): 활성화 여부 반환.
  - returns boolean: 누름을 받으면 참.

## ButtonState (enum)

버튼 상태.

- `normal` = `Enum.begin()`: 평상시 상태.
- `hover` = `Enum.auto()`: 포인터가 올라간 상태.
- `pressed` = `Enum.auto()`: 눌려 있는 상태.
- `released` = `Enum.auto()`: 막 뗀 상태.
- `disabled` = `Enum.auto()`: 눌러도 반응하지 않는 상태.
