# UI

This chapter covers putting UI such as buttons, labels, and sliders on screen. It goes through the UI scene `UIScene`, widget components you attach to nodes, complete widgets that build their own child nodes when attached, `UIDocument` for reading UI documents, two ways to lay things out (`NodeLayout` and the constraint-based `LayoutSolver`), window stacking (`UIWindowLayer`), and button feedback (`ButtonMotion`). Nodes and components themselves are covered in the "Nodes and Components" chapter, and how a touch reaches a node is covered in the "Input" chapter.

## Two kinds of UI

The engine's UI comes in two kinds, depending on how a node's place is decided. The Rust version has only one node type, `WorldNode`, so the widgets that were nodes in the original and `UINode` are all components you attach to a node.

- **Placing directly.** Attach widget components (the `UIView` family, such as `UILabel`, `UIButton`, and `UISlider`) to a node, and set its place and size yourself with the pivot, `set_local_position`, and `set_content_size`. Complete widgets such as `UIDropdown`, `UIDialog`, `UIToast`, and `UIWindow` are created and attached with `create(node_tree, parent_id, ...)`.
- **Placing with constraints.** Attaching a `UINode` component to a node gives it eight variables: left, right, top, bottom, width, height, center X, and center Y. When you add constraints, `LayoutSolver` solves those values. The solved values are copied into the node's local position and content size. Use this for layouts that grow and shrink with the screen size and the safe area.

Both kinds are used in a `UIScene`. Because `UINode` sets the node's place and size, a `UIButton` attached to the same node can be pressed as is, unlike in the original.

## UIScene

`UIScene` is the scene for UI. Rust has no inheritance, so the scene struct holds a `UISceneBase` as a field, implements the `UIScene` trait, and gets a `Scene` implementation from the one line `vanilla::ui_scene!(SceneType);`. `UISceneBase` provides the following by itself.

- Touch delivery. The `GameSceneBase` it holds owns a `TouchRecognizer` and passes touches to the node tree every tick. This is where the gesture that scrolls even when you drag a button inside a scroll view comes from.
- Loading screen. It draws a black background, an image in the middle (`set_loading_image_url`), and a bar at the bottom. By default it stays up for at least 3000 milliseconds, and tapping the screen skips it right away. Change this with `set_loading_min_duration_ms(milliseconds)`.
- An asset loading hook, `load_assets(&mut self)` (the original `loadAssets()`). It is called right after the base's `load`. If you hand requested assets to the scene with `get_scene_base_mut().track_asset(...)`, `initialize` is called after they have all loaded.
- Background color `set_scene_background_color(color)` (black by default) and view scale mode `set_view_scale_mode(mode, engine)` (`ViewScaleMode::None` by default; passing `None` for the engine applies it in `initialize`).
- The constraint solver (`get_solver()`), the screen guide (`get_screen_node()`), and the safe area guide (`get_safe_area_layout_guide()`). These are used in the "Constraint layout" section below.
- Developer tools. They are not created when `EngineConfiguration::use_dev_tools` is off.
- In the Rust version `UISceneBase` holds a `GameSceneBase`, so `GameSceneBase` features such as the screen fade and play input are also available through `get_game_scene_base_mut()`. (The original `UIScene` does not have them)

Functions of the `UIScene` trait such as `load_assets`, `initialize`, `layout`, `tick`, `pre_draw`, `draw`, `post_draw`, `destroy`, and `touch_press` all have default implementations, so you override only the ones you need. The `Scene` functions generated by `ui_scene!` call the base first and then the trait function of the same name (an override that calls `super` first in the original). Only `post_draw` calls the scene's first and draws the base (developer tools) on top. `layout` is called on the first tick and whenever the view size changes.

Below is a scene with a title label and one button. The button node gets `Paint` (background), `UILabel` (text), and `UIButton` (press handling) together.

```rust,no_run
use vanilla::{Color, ComponentContext, Engine, EngineConfiguration, NodeId, NodeTree, Paint, Pivot, UIButton, UILabel, UIScene, UISceneBase, Vector2};

struct MenuScene {
	ui_scene_base: UISceneBase,
}

impl MenuScene {
	fn set_title(node_tree: &mut NodeTree, title_id: NodeId, text: &str) {
		if let Some(title_label) = node_tree[title_id].get_component_mut::<UILabel>() {
			title_label.set_text(text);
		}
	}
}

impl UIScene for MenuScene {
	fn get_ui_scene_base(&self) -> &UISceneBase {
		&self.ui_scene_base
	}

	fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase {
		&mut self.ui_scene_base
	}

	fn initialize(&mut self, _engine: &Engine) {
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		let root_id = node_tree.get_root_id();

		let title_id = node_tree.create_child(root_id, "Title");
		node_tree[title_id].set_pivot(Pivot::TOP_LEFT);
		node_tree[title_id].set_local_position(Vector2::create(40.0, 40.0));
		node_tree[title_id].set_content_size(Vector2::create(400.0, 48.0));
		let title_label = node_tree.add_component(title_id, UILabel::create_with_text("Main Menu", 32.0)).expect("label");
		title_label.set_text_color(Color::create(0.95, 0.96, 1.0, 1.0));

		let button_id = node_tree.create_child(root_id, "StartButton");
		node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
		node_tree[button_id].set_local_position(Vector2::create(40.0, 120.0));
		node_tree[button_id].set_content_size(Vector2::create(200.0, 56.0));
		let button_paint = node_tree[button_id].add_component(Paint::create_with_color(Color::create(0.23, 0.51, 0.96, 1.0)));
		button_paint.set_round_size(12.0);
		node_tree.add_component(button_id, UILabel::create_with_text("Start", 22.0));
		let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
		button.set_clicked_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
			MenuScene::set_title(context.get_node_tree_mut(), title_id, "Started");
		}));
		button.set_long_press_seconds(0.8);
		button.set_long_pressed_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
			MenuScene::set_title(context.get_node_tree_mut(), title_id, "Long pressed");
		}));
	}
}

vanilla::ui_scene!(MenuScene);

fn main() {
	let mut engine_configuration = EngineConfiguration::new();
	engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
	engine_configuration.auto_resize_on_window_resize = true;
	let engine = Engine::new(engine_configuration);
	let mut ui_scene_base = UISceneBase::new();
	ui_scene_base.set_loading_min_duration_ms(0.0);
	ui_scene_base.set_scene_background_color(Color::create(0.08, 0.09, 0.12, 1.0));
	let menu_scene = MenuScene {
		ui_scene_base,
	};
	if let Err(error) = engine.run(Box::new(menu_scene)) {
		eprintln!("{}", error);
	}
}
```

- Widget events receive the widget and the component context, as in `Box<dyn FnMut(&mut UIButton, &mut ComponentContext)>`. Callbacks in the original receive only the widget, but the Rust version lets you find and change other nodes through the context's `get_node_tree_mut()`. Other nodes are referred to by `NodeId`, and since `NodeId` is `Copy` it goes into a `move` closure as is.
- A plain `Scene` also presses widgets, because `SceneBase::tick` passes touches to the frontmost pressable node (the original base scene does the same). It does not have the gesture that hands a drag over to a scroll view, though. If you need that gesture, use `UIScene`, or have the scene own a `TouchRecognizer` and call the node tree's `tick` and `touch_recognizer.tick_touch(node_tree, engine)` instead of `SceneBase::tick` (`examples/uigallery.rs` does this).

## Widget components

These are widgets you attach to a node. They use the node's content size (`set_content_size`) as their area.

![uigallery example: UIButton, UIToggleButton, UISlider, UIProgressView, UIImageView, UIScrollView and UIScrollBar](https://vanillapunch.com/docs/vanilla-engine/0.4.0/images/ui-gallery.webp)

| Type | What it does |
| --- | --- |
| `UIView` | A panel with a background color (`set_background_color`) and a content node (`get_content()`). The base held by the widgets below |
| `UIControl` | The base of widgets that take input. It holds a `UIView` |
| `UILabel` | Text. It holds a `RichText`, and the `RichText` holds a `Text` |
| `UIImageView` | An image. It holds a `Sprite` |
| `UIButton` | Press handling and pressed color |
| `UIToggleButton` | A button that turns on and off (holds a `UIButton`) |
| `UISlider` | A bar you drag or tap to pick a value |
| `UIProgressView` | A progress bar (no input) |
| `UIScrollView` | An area you drag to scroll. When attached it also attaches a `Mask` so its children are clipped |

- In the original, widgets inherit from `UIView`. In the Rust version, a widget holds a `UIView` (or `UIControl`) as a field and forwards the content node and background color. So there is no way to find derived widgets all at once with `get_component::<UIView>()`; find them by concrete type, as in `get_component::<UIButton>()`.
- Attach widgets to the tree, as in `node_tree.add_component(node_id, UIButton::new())`. That way, when attached, the widget creates a content node (`content`) under the node and, for widgets you press, turns the node `interactable`. Attaching with `node_tree[node_id].add_component(...)` skips this, so the widget cannot be pressed. Children that go inside a widget are attached to the node returned by `get_content()`.
- `UILabel` and `UIImageView` hold their text components and sprite, so `get_component::<Text>()` on a label node and `get_component::<Sprite>()` on an image view node return `None`. Get the held ones with `get_text_component()`, `get_rich_text_component()`, and `get_sprite()`.

### UIButton

- `UIButton` draws nothing by itself. It covers `Sprite` and `UIImageView` on the same node and the nodes below it with the pressed color, and blends `Paint`, `Text`, and `UILabel` from their original color toward the pressed color. The pressed color defaults to `(0, 0, 0, 0.3)`, the hover color to `(1, 1, 1, 0.12)`, and the transition time to 0.3 seconds; change them with `set_pressed_tint_color`, `set_hover_tint_color`, and `set_transition_duration`. Exclude things from the tint with `exclude_node_from_tint(node_id)` and `exclude_component_from_tint::<UILabel>(node_id)`. The original excludes component objects, while the Rust version excludes by (node, component type).
- Events: `set_clicked_event`, `set_click_event` (a click calls these two in order), `set_pressed_event`, `set_released_event`, `set_hover_event` (once when the mouse enters), and `set_long_pressed_event`. A click happens only when the release position is inside the button.
- A long press fires once the moment it passes `set_long_press_seconds` (0.5 seconds by default), and swallows the click of that press.
- With `set_interactable(false)` the button cannot be pressed and is covered dark (`(0, 0, 0, 0.5)`). The color is applied on the next tick.
- Giving `set_minimum_pressed_seconds(seconds)` shows the pressed look for that long even on a short tap before handling the release (0 by default).
- `get_button_state()` reports the current state as `ButtonState::Normal`, `Hover`, `Pressed`, `Released`, or `Disabled`.

Below is an example that presses a button with just a node tree and no window. `dispatch_touch` is the same function the engine uses to pass touches.

```rust
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, Paint, Pivot, TouchKind, UIButton, UILabel, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();

let status_id = node_tree.create_child(root_id, "Status");
node_tree.add_component(status_id, UILabel::create_with_text("Ready", 20.0));

let button_id = node_tree.create_child(root_id, "OkButton");
node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
node_tree[button_id].set_local_position(Vector2::create(100.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"));
let long_press_count = Rc::new(Cell::new(0));
let long_press_count_for_event = long_press_count.clone();
let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
button.set_clicked_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
	if let Some(status_label) = context.get_node_tree_mut()[status_id].get_component_mut::<UILabel>() {
		status_label.set_text("Clicked");
	}
}));
button.set_long_pressed_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
	long_press_count_for_event.set(long_press_count_for_event.get() + 1);
}));
assert!(node_tree[button_id].is_interactable());

let inside = Vector2::create(180.0, 124.0);
let outside = Vector2::create(400.0, 124.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, outside);
assert_eq!(node_tree[status_id].get_component::<UILabel>().expect("label").get_text(), "Ready");

node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, inside);
assert_eq!(node_tree[status_id].get_component::<UILabel>().expect("label").get_text(), "Clicked");

node_tree[status_id].get_component_mut::<UILabel>().expect("label").set_text("Ready");
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.tick(&engine, 0.6);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, inside);
assert_eq!(long_press_count.get(), 1);
assert_eq!(node_tree[status_id].get_component::<UILabel>().expect("label").get_text(), "Ready");
```

### Other widgets

- `UILabel`: `create_with_text(text, font_size)`, `set_text`, `set_font_size`, `set_text_color`, `set_text_align` (`TextAlign`), `set_text_baseline` (`TextBaseline`), `set_bold`, `set_italic`, `set_underline`, `set_strikethrough`, `set_word_wrap_width` (0 splits only at newline characters), `set_wrap_mode`, `set_line_spacing`, and `set_fit_width(width, minimum_ratio)` (shrinks the font size so a single line fits that width, but not below the ratio; not applied in rich text mode). Instead of the original `setFont(FontFace)`, give the name of a registered font with `set_font_family`. A new label's text is 32 pixels, white, center aligned, with a middle baseline. With `use_rich_text(true)` it reads the markup `<b>`, `<i>`, `<u>`, `<s>`, `<color=#RRGGBB[AA]>`, `<color=name>`, and `<size=N>`.
- `UIImageView`: `create_with_image(image)`, `set_image(Option<Rc<Image>>)`, `set_image_asset(&mut ImageAsset)` (the original `setImage` takes both), `set_image_rect`, `set_color` (tint), `set_draw_mode` (`SpriteDrawMode::Simple`, `Sliced`, `Tiled`), `set_nine_slice`, `set_horizontal_flip`, `set_vertical_flip`, and `set_blend_mode`.
- `UIToggleButton`: `set_toggled_event`, `get_is_on`, and `set_on_tint_color` (`(0, 0, 0, 0.3)` by default). `set_is_on(is_on)` changes only the state without calling the event, and the color is applied on the next tick. Button settings such as long press or interactable are made on the held `UIButton` through `get_uibutton_mut()`. The event order differs slightly from the original: the original goes release, flip, toggled event, clicked event, click event, while the Rust version goes release, click event, flip, toggled event, clicked event.
- `UISlider`: `set_range(min_value, max_value)` (0 to 1 by default), `set_value` (clamped to the range, no event), `get_value`, `get_ratio`, and `set_value_changed_event`. For the look: `set_track_color`, `set_fill_color`, `set_thumb_color`, `set_thumb_radius` (16 by default), `set_track_thickness` (0 means the whole node area), `set_corner_radius`, and `set_direction(ProgressDirection::Horizontal or Vertical)`. Setting a thumb node with `set_thumb_node(Some(node_id))` stops drawing the circle and moves that node to the thumb position (keep the thumb node as a child of the slider node). To make it unpressable, use `set_interactable(false)`.
- `UIProgressView`: `set_range`, `set_value`, `set_track_color` (same as the background color), `set_fill_color`, `set_corner_radius`, and `set_direction`. Giving `set_secondary_value(Some(value))` draws a second fill (`set_secondary_fill_color`) that fills from the opposite end. The value is changed only from code.

Below is an example that copies a slider's value to a label and a progress bar, and blocks the slider with a toggle button.

```rust
use vanilla::{Color, ComponentContext, Engine, EngineConfiguration, NodeId, NodeTree, Paint, Pivot, TouchKind, UILabel, UIProgressView, UISlider, UIToggleButton, Vector2};

fn create_box_node(node_tree: &mut NodeTree, parent_id: NodeId, name: &str, position: Vector2, size: Vector2) -> NodeId {
	let node_id = node_tree.create_child(parent_id, name);
	node_tree[node_id].set_pivot(Pivot::TOP_LEFT);
	node_tree[node_id].set_local_position(position);
	node_tree[node_id].set_content_size(size);
	node_id
}

fn main() {
	let engine = Engine::new(EngineConfiguration::new());
	let mut node_tree = NodeTree::new();
	let root_id = node_tree.get_root_id();

	let value_id = create_box_node(&mut node_tree, root_id, "VolumeLabel", Vector2::create(240.0, 40.0), Vector2::create(320.0, 32.0));
	let value_label = node_tree.add_component(value_id, UILabel::create_with_text("Volume <b>50</b>", 20.0)).expect("label");
	value_label.use_rich_text(true);

	let progress_id = create_box_node(&mut node_tree, root_id, "VolumeBar", Vector2::create(240.0, 140.0), Vector2::create(320.0, 12.0));
	let progress_view = node_tree.add_component(progress_id, UIProgressView::new()).expect("progress");
	progress_view.set_track_color(Color::create(1.0, 1.0, 1.0, 0.15));
	progress_view.set_fill_color(Color::create(0.3, 0.8, 0.5, 1.0));
	progress_view.set_corner_radius(6.0);
	progress_view.set_value(0.5);

	let slider_id = create_box_node(&mut node_tree, root_id, "VolumeSlider", Vector2::create(240.0, 90.0), Vector2::create(320.0, 32.0));
	let slider = node_tree.add_component(slider_id, UISlider::new()).expect("slider");
	slider.set_range(0.0, 100.0);
	slider.set_value(50.0);
	slider.set_track_thickness(6.0);
	slider.set_corner_radius(3.0);
	slider.set_value_changed_event(Box::new(move |slider: &mut UISlider, context: &mut ComponentContext| {
		let value = slider.get_value().round();
		let node_tree = context.get_node_tree_mut();
		if let Some(value_label) = node_tree[value_id].get_component_mut::<UILabel>() {
			value_label.set_text(&format!("Volume <b>{}</b>", value));
		}
		if let Some(progress_view) = node_tree[progress_id].get_component_mut::<UIProgressView>() {
			progress_view.set_value(value / 100.0);
		}
	}));

	let toggle_id = create_box_node(&mut node_tree, root_id, "MuteToggle", Vector2::create(240.0, 180.0), Vector2::create(160.0, 48.0));
	let toggle_paint = node_tree[toggle_id].add_component(Paint::create_with_color(Color::create(0.25, 0.6, 0.35, 1.0)));
	toggle_paint.set_round_size(10.0);
	node_tree.add_component(toggle_id, UILabel::create_with_text("Mute", 18.0));
	let toggle_button = node_tree.add_component(toggle_id, UIToggleButton::new()).expect("toggle");
	toggle_button.set_on_tint_color(Color::create(0.0, 0.0, 0.0, 0.4));
	toggle_button.set_toggled_event(Box::new(move |toggle_button: &mut UIToggleButton, context: &mut ComponentContext| {
		let is_on = toggle_button.get_is_on();
		if let Some(slider) = context.get_node_tree_mut()[slider_id].get_component_mut::<UISlider>() {
			slider.set_interactable(!is_on);
		}
	}));

	let slider_position = Vector2::create(480.0, 106.0);
	node_tree.dispatch_touch(slider_id, &engine, TouchKind::Press, slider_position);
	node_tree.dispatch_touch(slider_id, &engine, TouchKind::Release, slider_position);
	assert_eq!(node_tree[value_id].get_component::<UILabel>().expect("label").get_text(), "Volume <b>75</b>");
	assert_eq!(node_tree[progress_id].get_component::<UIProgressView>().expect("progress").get_value(), 0.75);

	let toggle_position = Vector2::create(300.0, 200.0);
	node_tree.dispatch_touch(toggle_id, &engine, TouchKind::Press, toggle_position);
	node_tree.dispatch_touch(toggle_id, &engine, TouchKind::Release, toggle_position);
	assert!(node_tree[toggle_id].get_component::<UIToggleButton>().expect("toggle").get_is_on());
	assert!(!node_tree[slider_id].get_component::<UISlider>().expect("slider").get_interactable());
}
```

### UIScrollView

The content size of the node with the scroll view is the visible area, and items are attached to the node returned by `get_content()`. You must tell it the full draggable size with `set_scroll_content_size(size)`, and it scrolls only when that is larger than the visible area.

- Turn an axis off with `set_horizontal(false)` or `set_vertical(false)`.
- `set_scroll_mode(ScrollMode::Clamp)` never goes past the edges (default), and with `ScrollMode::Elastic` going past them creates a pulling force and it bounces back on release.
- Show scroll bars (nodes with a `UIScrollBar`) with `set_shows_vertical_scroll_bar(true)` and `set_shows_horizontal_scroll_bar(true)`. The scroll bar node is created on the next tick; to create it on the spot, call `UIScrollView::set_shows_vertical_scroll_bar_in_tree(node_tree, scroll_node_id, true)` (it returns the created node).
- `set_scroll_offset(offset)` moves the position. y becomes negative as you scroll down. The value is clamped to the range right away, but the content node moves on the next tick. To move it in the same frame, use `UIScrollView::set_scroll_offset_in_tree(node_tree, scroll_node_id, offset)`.
- There are also `set_drag_sensitivity` (drag multiplier, 1 by default), `set_wheel_scroll_scale` (wheel multiplier, 1 by default), and `set_passes_cross_axis_drag(true)` (a finger dragged further along the non-scrolling axis is handed to the inner widget, for places like a horizontal slider inside a vertical list).
- When you press inside a scroll view, `TouchRecognizer` delays delivering the press by 150 milliseconds, and once you drag more than 10 pixels it cancels the inner widget's press and hands the drag to scrolling.

```rust
use vanilla::{Color, Engine, EngineConfiguration, NodeTree, Paint, Pivot, ScrollMode, UILabel, UIScrollView, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let viewport_id = node_tree.create_child(root_id, "List");
node_tree[viewport_id].set_pivot(Pivot::TOP_LEFT);
node_tree[viewport_id].set_local_position(Vector2::create(160.0, 60.0));
node_tree[viewport_id].set_content_size(Vector2::create(320.0, 240.0));

let row_count = 20;
let row_height = 40.0;
let content_id = {
	let scroll_view = node_tree.add_component(viewport_id, UIScrollView::new()).expect("scroll view");
	scroll_view.set_background_color(Color::create(0.1, 0.12, 0.16, 1.0));
	scroll_view.set_horizontal(false);
	scroll_view.set_scroll_mode(ScrollMode::Elastic);
	scroll_view.set_shows_vertical_scroll_bar(true);
	scroll_view.set_scroll_content_size(Vector2::create(320.0, row_count as f64 * row_height));
	scroll_view.get_content().expect("content")
};
for row_index in 0..row_count {
	let row_id = node_tree.create_child(content_id, "Row");
	node_tree[row_id].set_pivot(Pivot::TOP_LEFT);
	node_tree[row_id].set_local_position(Vector2::create(8.0, row_index as f64 * row_height + 2.0));
	node_tree[row_id].set_content_size(Vector2::create(296.0, row_height - 4.0));
	node_tree[row_id].add_component(Paint::create_with_color(Color::create(1.0, 1.0, 1.0, 0.06)));
	let row_text = format!("Row {}", row_index);
	node_tree.add_component(row_id, UILabel::create_with_text(&row_text, 18.0));
}

let scroll_view = node_tree[viewport_id].get_component_mut::<UIScrollView>().expect("scroll view");
scroll_view.set_scroll_offset(Vector2::create(0.0, -2000.0));
assert_eq!(scroll_view.get_scroll_offset(), Vector2::create(0.0, -560.0));
node_tree.tick(&engine, 0.016);
assert_eq!(node_tree[content_id].get_local_position(), Vector2::create(0.0, -560.0));
let scroll_view = node_tree[viewport_id].get_component::<UIScrollView>().expect("scroll view");
assert!(scroll_view.get_vertical_scroll_bar().is_some());
```

## Complete widgets

These widgets decorate the node and build their own child nodes and components when attached, like the original constructors. In the original they are nodes that inherit from `WorldNode`, created with `new` and attached with `addChild`. In the Rust version they are components, and a function that creates and attaches a node, such as `UIDropdown::create(node_tree, parent_id, options)`, takes that role. The original options object is an options struct you fill with `..Default::default()`. Functions that change the tree take the tree, so scene code calls them with `node_tree.with_component_mut::<UIDropdown, _>(node_id, |dropdown, tree| ...)`.

![uigallery2 example: UIListView, UISnapScrollView, UIDropdown, UIDraggable, UILineChart, UIBarChart, UISpinner, UIToast](https://vanillapunch.com/docs/vanilla-engine/0.4.0/images/ui-gallery2.webp)

- `UIInputField`: a text input box drawn on the canvas. Like other widgets it is attached with `node_tree.add_component(node_id, UIInputField::new())`, and when attached it sets the node's pivot to the top left. Call `attach()` to start receiving input and `detach()` to stop. By default the field takes the keyboard directly. If you need IME input such as Korean, turn on `set_use_dom_input(true)` (on desktop it turns on the winit IME while that field has focus, and on the web it uses a hidden DOM `<input>` like the original). There is no `setEngine` from the original. It has `set_placeholder`, `set_text` (no change event), `get_text`, `set_max_length` (in UTF-16 units, 0 means unlimited), `set_font_size` (28 by default), `set_font_family`, `set_on_change`, `set_on_submit` (Enter), `focus`, `blur`, `select_all`, `cut`, `copy`, and `paste`. Events receive the field and the context, and the value is read with `field.get_text()`. A right press opens a cut, copy, and paste menu (drawn on the canvas on desktop, a DOM menu on the web). Turning off or destroying the node also drops the focus and the IME.
- `UIDropdown`: shows the current value on a header button and opens a list when pressed. `UIDropdown::create(node_tree, parent_id, UIDropdownOptions { width, height, option_height, font_size, base_color, popup_color, highlight_color, text_color })` (default width 180, height 30, row height 28, font 12). It has `set_option_list(tree, &[...])`, `get_selected_index`, `get_selected_text`, `set_changed_event`, and `set_open(tree, is_open)`, and `set_selected_index(tree, index)` changes only the selection without an event. The opened list is moved to the last child of the root so other nodes do not cover it.
- `UIToast`: `show(message)` brings up a pill shaped notice from below, shows it briefly, and removes it. Calling it several times queues the messages. `UIToast::create(node_tree, parent_id, UIToastOptions { width, height, rest_y, rest_x, hold_seconds, font_size, background_color, text_color })` (default 400 x 48, `rest_y` 560, `rest_x` of `None` centers it horizontally on the parent, hold time 1.8 seconds). `show` only queues the message; it becomes visible from the next tick.
- `UIDialog`: brings up a darkening overlay, a card in the middle, and confirm and cancel buttons with a single `show(tree, message, UIDialogShowOptions { on_confirm, on_cancel, confirm_text, cancel_text })`. Without `on_cancel` it becomes a notice with only a confirm button, and pressing the overlay counts as cancel. The handlers are one-shot functions (`FnOnce`) that receive the dialog and the context. To close it from scene code that has no context, call `request_dismiss(is_confirmed)` and it closes on the next tick. The default button texts of `UIDialogOptions` are Korean (confirm and cancel), so pass your own texts for other languages. It uses the parent's content size as the overlay size (960 x 640 if there is none).

Create `UIToast` and `UIDialog` as the last children of the root so they draw on top of everything else. There are also widgets such as `UIContextMenu`, `UISpinner`, `UIListView`, `UISnapScrollView`, `UIDraggable`, `UILineChart`, `UIBarChart`, `UIProgressRing`, and `UIHitArea` (see `examples/uigallery2.rs`).

```rust
use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, TouchKind, UIDialog, UIDialogOptions, UIDialogShowOptions, UIDropdown, UIDropdownOptions, UIInputField, UILabel, UIToast, UIToastOptions, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
node_tree[root_id].set_content_size(Vector2::create(640.0, 360.0));

let field_id = node_tree.create_child(root_id, "NameField");
node_tree[field_id].set_local_position(Vector2::create(40.0, 40.0));
node_tree[field_id].set_content_size(Vector2::create(360.0, 56.0));
let input_field = node_tree.add_component(field_id, UIInputField::new()).expect("input field");
input_field.set_placeholder("Player name");
input_field.set_max_length(16);
input_field.attach();
input_field.set_text("Player");

let dropdown_options = UIDropdownOptions {
	width: 200.0,
	height: 36.0,
	font_size: 16.0,
	..UIDropdownOptions::default()
};
let dropdown_id = UIDropdown::create(&mut node_tree, root_id, dropdown_options);
node_tree[dropdown_id].set_local_position(Vector2::create(420.0, 50.0));
node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
	dropdown.set_option_list(tree, &["Low", "Medium", "High"]);
	dropdown.set_selected_index(tree, 1);
});

let toast_options = UIToastOptions {
	width: 320.0,
	height: 40.0,
	rest_y: 320.0,
	..UIToastOptions::default()
};
let toast_id = UIToast::create(&mut node_tree, root_id, toast_options);
let dialog_id = UIDialog::create(&mut node_tree, root_id, UIDialogOptions::default());

node_tree[dropdown_id].get_component_mut::<UIDropdown>().expect("dropdown").set_changed_event(Box::new(move |dropdown: &mut UIDropdown, context: &mut ComponentContext| {
	let message = format!("Quality: {}", dropdown.get_selected_text());
	if let Some(toast) = context.get_node_tree_mut()[toast_id].get_component_mut::<UIToast>() {
		toast.show(&message);
	}
}));

node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
	dropdown.set_open(tree, true);
});
let high_option_id = node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown").get_option_nodes()[2];
let option_size = node_tree[high_option_id].get_content_size();
let option_center = node_tree.convert_node_position_to_view_position(high_option_id, option_size.multiply_scalar(0.5));
node_tree.dispatch_touch(high_option_id, &engine, TouchKind::Press, option_center);
node_tree.dispatch_touch(high_option_id, &engine, TouchKind::Release, option_center);
assert_eq!(node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown").get_selected_text(), "High");
node_tree.tick(&engine, 0.016);
assert_eq!(node_tree[toast_id].get_component::<UILabel>().expect("label").get_text(), "Quality: High");

let player_name = node_tree[field_id].get_component::<UIInputField>().expect("input field").get_text().to_string();
let show_options = UIDialogShowOptions {
	on_confirm: Some(Box::new(move |_dialog: &mut UIDialog, context: &mut ComponentContext| {
		if let Some(toast) = context.get_node_tree_mut()[toast_id].get_component_mut::<UIToast>() {
			toast.show("Saved");
		}
	})),
	on_cancel: Some(Box::new(|_dialog: &mut UIDialog, _context: &mut ComponentContext| {})),
	confirm_text: Some(String::from("Save")),
	cancel_text: Some(String::from("Cancel")),
};
node_tree.with_component_mut::<UIDialog, _>(dialog_id, |dialog, tree| {
	dialog.show(tree, &format!("Save as {}?", player_name), show_options);
});
node_tree.tick(&engine, 0.4);
node_tree[dialog_id].get_component_mut::<UIDialog>().expect("dialog").request_dismiss(true);
node_tree.tick(&engine, 0.016);
node_tree.tick(&engine, 0.3);
assert!(!node_tree[dialog_id].is_active());
```

## Reading UI documents with UIDocument

A UI document is text that describes a node tree in JSON (`{ "version": 1, "root": node }`). The vanilla.js authoring tools save in this format (authoring tools are covered in the "Authoring Tools and Files Shared by Both Engines" chapter), and trees built in the Rust version are exported in the same format.

- The original is a static class with module global tables, while the Rust version uses a `UIDocument` value holding the tables, created with `UIDocument::new()`. `new` registers the engine components `Paint`, `Sprite`, `Text`, `RichText`, `Mask`, `Outline`, `SoftShade`, `ShadowText`, `UIProgressRing`, `UILabel`, `UIImageView`, `UIButton`, `UIToggleButton`, `UIProgressView`, `UISlider`, `UIScrollView`, and `ShadowImage` (`get_component_type_names()`). All the types the authoring tools register (35 components, 12 node types) are added with the single line `register_editor_types()`; your game's components are added with `register_component_type(name, constructor)`, and what were node types in the original are added with `register_node_type`. Unregistered types are skipped with a warning when reading.
- `from_json_text(&mut node_tree, json_text)` builds the document into the node tree and returns the root node. The root is not attached anywhere, so attach it with `add_child` to show it in the scene. If the text is not JSON or has no `root` object, it returns `Err(reason)` (the original throws).
- `to_json_text(&mut node_tree, root_id, is_pretty)` does the reverse and writes the node tree as JSON text. With `is_pretty` it indents with tabs.
- A document does not contain image data, only paths (`imagePath`). If you set a function that turns a path into `Option<Rc<Image>>` with `set_image_resolver(|image_path| ...)`, images are looked up with it. Otherwise they are looked up in the document's own asset store: `load_images(&engine, json_text)` requests the document's images as `ImageAsset`s (on desktop from `EngineConfiguration::asset_directory_paths`), and for images that load later, as on the web, `bind_pending_images(&mut node_tree)` attaches them in tick until the remaining count reaches 0. Set the resolver and call `load_images` before `from_json_text`.
- Components in a document are written and read through reflection only if their type has the reflection macro `#[reflect]`. All engine components have it (see the "Reflection Macro `#[reflect]`" chapter).

Below is an example that reads document text, finds a button by name, and gives it behavior.

```rust
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, TouchKind, UIButton, UIDocument, Vector2};

let json_text = r#"{
	"version": 1,
	"root": {
		"name": "Menu",
		"children": [
			{
				"name": "StartButton",
				"position": [120, 40],
				"contentSize": [200, 56],
				"interactable": true,
				"components": [
					{ "color": [0.23, 0.51, 0.96, 1], "roundSize": 12, "type": "Paint" },
					{ "type": "UIButton" }
				]
			}
		]
	}
}"#;

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let mut document = UIDocument::new();
let menu_id = document.from_json_text(&mut node_tree, json_text).expect("document");
let root_id = node_tree.get_root_id();
node_tree.add_child(root_id, menu_id);

let start_id = node_tree.find_descendant_by_name(menu_id, "StartButton").expect("start button");
let start_count = Rc::new(Cell::new(0));
let start_count_for_event = start_count.clone();
let start_button = node_tree[start_id].get_component_mut::<UIButton>().expect("button");
start_button.set_clicked_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
	start_count_for_event.set(start_count_for_event.get() + 1);
}));
let center = Vector2::create(120.0, 40.0);
node_tree.dispatch_touch(start_id, &engine, TouchKind::Press, center);
node_tree.dispatch_touch(start_id, &engine, TouchKind::Release, center);
assert_eq!(start_count.get(), 1);

assert!(document.from_json_text(&mut node_tree, "{\"version\":1}").is_err());
```

In a scene, read the document file as a `TextAsset` and build the tree in `initialize` after it has loaded. Below is a scene that reads the repository's `examples/assets/scenedocument.scene.json` and moves its progress bar.

```rust,no_run
use std::path::PathBuf;
use vanilla::{Engine, EngineConfiguration, NodeId, TextAsset, UIDocument, UIProgressView, UIScene, UISceneBase, Vector2};

struct DocumentScene {
	ui_scene_base: UISceneBase,
	document: UIDocument,
	scene_asset: TextAsset,
	progress_id: Option<NodeId>,
	elapsed_seconds: f64,
}

impl UIScene for DocumentScene {
	fn get_ui_scene_base(&self) -> &UISceneBase {
		&self.ui_scene_base
	}

	fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase {
		&mut self.ui_scene_base
	}

	fn load_assets(&mut self) {
		let engine = Engine::get_engine().unwrap();
		self.scene_asset.load(engine, "scenedocument.scene.json");
		self.ui_scene_base.get_scene_base_mut().track_asset(&self.scene_asset);
	}

	fn initialize(&mut self, engine: &Engine) {
		let scene_text = match self.scene_asset.get_text() {
			Some(scene_text) => {
				scene_text.to_string()
			}
			None => {
				return;
			}
		};
		self.document.load_images(engine, &scene_text);
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		let document_root_id = match self.document.from_json_text(node_tree, &scene_text) {
			Ok(document_root_id) => {
				document_root_id
			}
			Err(error) => {
				eprintln!("{}", error);
				return;
			}
		};
		let root_id = node_tree.get_root_id();
		node_tree.add_child(root_id, document_root_id);
		self.progress_id = node_tree.find_descendant_by_name(document_root_id, "progress");
	}

	fn tick(&mut self, time_delta: f64) {
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		self.document.bind_pending_images(node_tree);
		self.elapsed_seconds += time_delta;
		let progress = (self.elapsed_seconds.sin() * 0.5 + 0.5) * 100.0;
		if let Some(progress_id) = self.progress_id {
			if let Some(progress_view) = node_tree[progress_id].get_component_mut::<UIProgressView>() {
				progress_view.set_value(progress);
			}
		}
	}
}

vanilla::ui_scene!(DocumentScene);

fn main() {
	let mut engine_configuration = EngineConfiguration::new();
	engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
	engine_configuration.asset_directory_paths = vec![PathBuf::from("examples/assets")];
	let engine = Engine::new(engine_configuration);
	let mut ui_scene_base = UISceneBase::new();
	ui_scene_base.set_loading_min_duration_ms(0.0);
	let document_scene = DocumentScene {
		ui_scene_base,
		document: UIDocument::new(),
		scene_asset: TextAsset::new(),
		progress_id: None,
		elapsed_seconds: 0.0,
	};
	if let Err(error) = engine.run(Box::new(document_scene)) {
		eprintln!("{}", error);
	}
}
```

## Building declaratively with NodeLayout

Instead of creating nodes one by one and keeping them in local variables, this builder lets you write a node hierarchy as a chain. Start with `NodeLayout::create()` (there is only one node type, so the original `create(nodeClass)` argument does not exist). Chain `name`, `active`, `pivot(pivot)`, `anchor(x, y)`, `anchored_position(x, y)`, `local_position(x, y)`, `content_size(x, y)`, `local_scale(x, y)`, `mask_enabled(is_enabled)`, `component(component)`, `component_with(component, callback)`, `children([...])`, `apply(callback)` (settings the builder lacks; it receives `&mut WorldNode`), and `parent(parent_id)`, and `build(node_tree, Some(parent_id))` creates the node, attaches it to the parent, and returns its `NodeId`. Positions and sizes are given as two numbers without `Vector2`.

- The builder collects settings in order and, at `build`, creates the node and applies them in that order. Components are also attached with `node_tree.add_component` at `build`, so widgets that create child nodes when attached work too.
- The original `component(type, callback)` is split into `component(value)` and `component_with(value, callback)`, and the variadic arguments of `children(...layouts)` are taken as a single array or `Vec`.
- `anchored_position` is applied at `build` relative to the parent's content size.

```rust
use vanilla::{Color, ComponentContext, Engine, EngineConfiguration, NodeLayout, NodeTree, Paint, Pivot, TouchKind, UIButton, UILabel, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let panel_id = NodeLayout::create()
	.name("Panel")
	.pivot(Pivot::TOP_LEFT)
	.local_position(170.0, 60.0)
	.content_size(300.0, 240.0)
	.component_with(Paint::create_with_color(Color::create(0.13, 0.15, 0.2, 1.0)), |paint| {
		paint.set_round_size(16.0);
	})
	.children([
		NodeLayout::create()
			.name("Title")
			.pivot(Pivot::TOP_LEFT)
			.local_position(24.0, 20.0)
			.content_size(252.0, 40.0)
			.component(UILabel::create_with_text("Settings", 24.0)),
		NodeLayout::create()
			.name("CloseButton")
			.pivot(Pivot::TOP_LEFT)
			.local_position(24.0, 168.0)
			.content_size(252.0, 48.0)
			.component_with(Paint::create_with_color(Color::create(0.23, 0.51, 0.96, 1.0)), |paint| {
				paint.set_round_size(10.0);
			})
			.component(UILabel::create_with_text("Close", 18.0))
			.component_with(UIButton::new(), |button| {
				button.set_clicked_event(Box::new(|_button: &mut UIButton, context: &mut ComponentContext| {
					let button_id = context.get_node_id();
					let node_tree = context.get_node_tree_mut();
					if let Some(panel_id) = node_tree.get_parent_id(button_id) {
						node_tree[panel_id].set_visible(false);
					}
				}));
			}),
	])
	.build(&mut node_tree, Some(root_id));

let close_id = node_tree.find_descendant_by_name(panel_id, "CloseButton").expect("close button");
assert!(node_tree[close_id].is_interactable());
let center = Vector2::create(320.0, 252.0);
node_tree.dispatch_touch(close_id, &engine, TouchKind::Press, center);
node_tree.dispatch_touch(close_id, &engine, TouchKind::Release, center);
assert!(!node_tree[panel_id].is_visible());
```

`NodeLayout::arrange_fan(node_tree, &node_ids, NodeLayoutFanOptions { center_x, center_y, radius, angle_step_radian, base_angle_radian, rotate_nodes })` spreads several nodes along an arc like cards in a hand (default spacing 0.12 radians, facing up, with rotation).

## Constraint layout: UINode and LayoutSolver

`UINode` is a component that decides place and size with constraints (the same idea as UIKit Auto Layout). Attach it with `node_tree.add_component(node_id, UINode::new())` and add constraints inside `node_tree.with_component_mut::<UINode, _>(node_id, |ui_node, _tree| ...)`.

![uiscenelayout example: a header bar pinned to the safe area, a side panel with a width constraint and three buttons of equal width](https://vanillapunch.com/docs/vanilla-engine/0.4.0/images/ui-scene-layout.webp)

- The anchor functions `left_anchor()`, `right_anchor()`, `top_anchor()`, `bottom_anchor()`, `width_anchor()`, `height_anchor()`, `center_x_anchor()`, `center_y_anchor()` (and `leading_anchor()`, `trailing_anchor()`, `first_baseline_anchor()`, `last_baseline_anchor()`) return a new `LayoutExpression` on every call. The original has getter properties (`leftAnchor`), while the Rust version has functions.
- Expressions make new expressions with `add`, `subtract`, `multiply`, and `divide`, and make a `LayoutConstraint` with `equal_to`, `less_than_or_equal_to`, and `greater_than_or_equal_to`. The right side can be a number (`f64`, `i32`), a `LayoutVariable`, or a `LayoutExpression`.
- Constraints made this way are required constraints. For a constraint that may yield, use a new constraint with a different strength, as in `constraint.with_strength(LayoutStrength::STRONG)`. The strengths are `LayoutStrength::REQUIRED`, `STRONG`, `MEDIUM`, and `WEAK`, and the stronger one wins in a conflict. To build a strength from a priority, use `LayoutStrength::from_priority(LayoutPriority::DEFAULT_LOW)`.
- Add a constraint with `ui_node.add_constraint(&constraint)`. Where the original throws (duplicate constraints, required constraints that cannot be satisfied), you get the `Err` of `Result<(), LayoutError>`.
- Every tick, `UIScene` attaches its solver to the `UINode`s in the tree, solves the values, and copies them to the nodes. Read the solved values with `get_left()`, `get_top()`, `get_width()`, `get_height()`, `get_center_x()`, and `get_center_y()` (`f64`); the node's pivot becomes the top left, and its local position and content size become the solved values.
- `get_screen_node()` is a guide fixed at the top left (0, 0) whose width and height follow the view size. `get_safe_area_layout_guide()` is a guide inset from it by the safe area. In the desktop app and in desktop browsers the safe area is 0, so the two guides are the same; for testing, simulate one with `engine.get_view_manager_mut().set_safe_area_override(Some(SafeAreaInsets::create(top, right, bottom, left)))`.
- The left and top values of a `UINode` are absolute coordinates relative to the root of the UI tree. If the parent is also a `UINode`, the child node is placed at the local position (child left - parent left, child top - parent top), so on screen it ends up exactly at the values.
- Nodes with a size of their own, such as text, have an intrinsic content size (`get_intrinsic_content_size`), and `set_content_hugging_priority(priority, axis)` and `set_content_compression_resistance_priority(priority, axis)` decide how much they resist growing and shrinking (`LayoutPriority::DEFAULT_LOW` 250, `DEFAULT_HIGH` 750, `REQUIRED` 1000, `FITTING_SIZE_LEVEL` 50; the axis is `LayoutConstraintAxis::Horizontal` or `Vertical`). In the original, `UILabel` asks the node to remeasure its intrinsic size when the text changes; in the Rust version, `UINode` rereads the values of the components on the same node every tick and remeasures by itself when they change.
- Use the inner margin guide with `set_layout_margins(LayoutMargins::create(top, left, bottom, right))` (all 8 by default) and `get_layout_margins_guide()`.

Below is what a scene does in `initialize`, run with a `UISceneBase` and no window. The header bar sticks inside the safe area, and the card aims for half the screen width without exceeding 480 and stands in the middle of the screen. The `UIButton` attached to the card can also be pressed at its solved place.

```rust
use vanilla::{Engine, EngineConfiguration, LayoutStrength, Paint, UIButton, UINode, UISceneBase, Vector2};

let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(640, 360, 1.0);
let mut ui_scene_base = UISceneBase::new();
ui_scene_base.initialize(engine);

let safe_area_guide = ui_scene_base.get_safe_area_layout_guide();
let safe_left = safe_area_guide.left_anchor();
let safe_right = safe_area_guide.right_anchor();
let safe_top = safe_area_guide.top_anchor();
let screen_node = ui_scene_base.get_screen_node();
let screen_width = screen_node.width_anchor();
let screen_center_x = screen_node.center_x_anchor();
let screen_center_y = screen_node.center_y_anchor();

let node_tree = ui_scene_base.get_scene_base_mut().get_node_tree_mut();
let root_id = node_tree.get_root_id();

let header_id = node_tree.create_child(root_id, "Header");
node_tree[header_id].add_component(Paint::create_with_color("#3366cc"));
node_tree.add_component(header_id, UINode::new());
node_tree.with_component_mut::<UINode, _>(header_id, |header, _tree| {
	header.add_constraint(&header.left_anchor().equal_to(safe_left.add(16))).unwrap();
	header.add_constraint(&header.right_anchor().equal_to(safe_right.subtract(16))).unwrap();
	header.add_constraint(&header.top_anchor().equal_to(safe_top.add(16))).unwrap();
	header.add_constraint(&header.height_anchor().equal_to(56)).unwrap();
});

let card_id = node_tree.create_child(root_id, "Card");
node_tree[card_id].add_component(Paint::create_with_color("#222833"));
node_tree.add_component(card_id, UINode::new());
node_tree.add_component(card_id, UIButton::new());
node_tree.with_component_mut::<UINode, _>(card_id, |card, _tree| {
	let half_width = card.width_anchor().equal_to(screen_width.multiply(0.5));
	card.add_constraint(&half_width.with_strength(LayoutStrength::STRONG)).unwrap();
	card.add_constraint(&card.width_anchor().less_than_or_equal_to(480)).unwrap();
	card.add_constraint(&card.height_anchor().equal_to(160)).unwrap();
	card.add_constraint(&card.center_x_anchor().equal_to(screen_center_x.clone())).unwrap();
	card.add_constraint(&card.center_y_anchor().equal_to(screen_center_y.clone())).unwrap();
});

ui_scene_base.tick(0.016);
let node_tree = ui_scene_base.get_scene_base().get_node_tree();
assert_eq!(node_tree[header_id].get_local_position(), Vector2::create(16.0, 16.0));
assert_eq!(node_tree[header_id].get_content_size(), Vector2::create(608.0, 56.0));
assert_eq!(node_tree[card_id].get_local_position(), Vector2::create(160.0, 100.0));
assert_eq!(node_tree[card_id].get_content_size(), Vector2::create(320.0, 160.0));
assert_eq!(node_tree.find_topmost_interactable_node(Vector2::create(320.0, 180.0)), Some(card_id));
```

The solver can also be used alone without the engine. Create variables with `LayoutVariable::new(name)` and expressions with `LayoutExpression::from_variable(&variable)`. Register variables whose values are pushed in from outside with `add_edit_variable(&variable, strength)` and give them values with `suggest_value(&variable, value)`. Calling `update_variables()` puts the solved values into the variables, which you read with `get_value()`. `LayoutSolver` is a cheaply cloned handle, so all its functions take `&self`.

```rust
use vanilla::{LayoutExpression, LayoutSolver, LayoutStrength, LayoutVariable};

let solver = LayoutSolver::new();
let view_width = LayoutVariable::new("viewWidth");
let left = LayoutVariable::new("left");
let width = LayoutVariable::new("width");
let view_width_expression = LayoutExpression::from_variable(&view_width);
let left_expression = LayoutExpression::from_variable(&left);
let right_expression = left_expression.add(&width);
let right_margin_expression = view_width_expression.subtract(16);
solver.add_constraint(&left_expression.equal_to(16)).unwrap();
solver.add_constraint(&right_expression.equal_to(right_margin_expression)).unwrap();
solver.add_edit_variable(&view_width, LayoutStrength::STRONG).unwrap();

solver.suggest_value(&view_width, 640.0).unwrap();
solver.update_variables();
assert_eq!(width.get_value(), 608.0);

solver.suggest_value(&view_width, 360.0).unwrap();
solver.update_variables();
assert_eq!(width.get_value(), 328.0);

assert!(solver.add_constraint(&left_expression.equal_to(20)).is_err());
```

## Window stacking

`UIWindowLayer` is a layer that stacks `UIWindow`s over an area. Only the top window is visible, and when the window above closes, the one below becomes visible again. In the original both are nodes, but in the Rust version they are components attached to a layer node and window nodes, and the window nodes are children of the layer node.

![windowshowcase example: a confirm window with scrolling text on top, dimming everything behind it](https://vanillapunch.com/docs/vanilla-engine/0.4.0/images/window-stack.webp)

- `UIWindowLayer::create(node_tree, parent_id)` creates the layer node and returns it. Keep the layer as the last child of the area node (usually the root), and every time the area size changes, report it with `set_view_size(tree, width, height, css_pixel_scale)`. The CSS scale is `engine.get_view_manager().get_css_pixel_scale()`. To darken all the way into the safe area, also report `set_view_bleed(tree, top, right, bottom, left)`.
- `open_window(tree, window_id)` (in scene code, `UIWindowLayer::open_window_in_tree(node_tree, layer_id, window_id)`) stacks a window on top (or raises it to the top if it is already open), and `close_window(tree, window_id)`, `close_top_window(tree)` (the place for the device's back action; `true` if it closed one), and `close_all_windows(tree)` close windows. Read the state with `has_open_window()`, `get_window_count()`, `get_top_window()`, and `find_window(tree, name)`; `set_window_change_event(Some(Box::new(|window_count| ...)))` is called with the number of open windows whenever a window opens or closes. Use it to pause the game while a window is open.
- A closed window node is only detached from the layer, not destroyed, so it can be opened again. Destroy windows you will not use again with `destroy_node`.
- The layer grows by the UI scale (`UIScale::read`) so text stays readable on small screens. With `set_ui_scale_options(tree, None)` it does not grow.

`UIWindow` darkens the whole area (presses do not reach what is behind it) and brings up a panel in the middle. Create it with `UIWindow::create(node_tree, layer_id, name, Box::new(UIWindowDefaultBehavior))`; the created window node stays off until it is opened. Attach content to the node returned by `get_panel_node()`. The panel's width grows with the area but does not exceed `set_maximum_width` (480 by default), and it keeps `set_margin` (16 by default) away from the area's edges. Its height is `set_panel_height` (240 by default). The places that derived classes overrode in the original, such as `layoutContent`, are the `UIWindowBehavior` trait (`build`, `layout_content(tree, parts, panel_width)` which returns the panel height, `layout_panel`, `apply_motion`, `set_covered`, `handle_wheel`, `handle_closed`, and so on), and its default implementation is `UIWindowDefaultBehavior`. Pressing outside (the dark area) closes the window; turn this off with `set_outside_close_enabled(false)`. There are also `set_panel_color`, `set_dim_color`, and `set_close_event(Some(Box::new(|| ...)))`, and to close from scene or event code call `UIWindow::close_in_tree(node_tree, window_id)`. It moves with `PopupMotion` when it opens and closes.

`UIConfirmWindow` is a window with a title, a question, and cancel and confirm buttons. Create it with `UIConfirmWindow::create(node_tree, layer_id, name, UIConfirmWindowOptions { title, message, cancel_text, confirm_text })` (the default button texts are Korean words for cancel and confirm), take it out of the window node's `UIWindow` with `get_behavior_mut::<UIConfirmWindow>()`, and set `set_confirm_event` and `set_cancel_event`. The events are functions with no arguments. Pressing confirm fires the confirm event and then closes the window; closing it with the cancel button, an outside press, `close_top_window`, or `close_all_windows` fires the cancel event. If the text is long, only the text area scrolls. With `set_right_to_left(true)` the button order is reversed.

```rust,no_run
use vanilla::{Engine, EngineConfiguration, NodeId, Pivot, UIConfirmWindow, UIConfirmWindowOptions, UILabel, UIScene, UISceneBase, UIWindow, UIWindowDefaultBehavior, UIWindowLayer, Vector2};

struct WindowScene {
	ui_scene_base: UISceneBase,
	layer_id: Option<NodeId>,
}

impl UIScene for WindowScene {
	fn get_ui_scene_base(&self) -> &UISceneBase {
		&self.ui_scene_base
	}

	fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase {
		&mut self.ui_scene_base
	}

	fn initialize(&mut self, _engine: &Engine) {
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		let root_id = node_tree.get_root_id();
		let layer_id = UIWindowLayer::create(node_tree, root_id);
		if let Some(window_layer) = node_tree[layer_id].get_component_mut::<UIWindowLayer>() {
			window_layer.set_window_change_event(Some(Box::new(|window_count: usize| {
				println!("open windows: {}", window_count);
			})));
		}

		let settings_id = UIWindow::create(node_tree, layer_id, "settings", Box::new(UIWindowDefaultBehavior));
		let panel_id = {
			let settings_window = node_tree[settings_id].get_component_mut::<UIWindow>().expect("window");
			settings_window.set_panel_height(200.0);
			settings_window.get_panel_node().expect("panel")
		};
		let label_id = node_tree.create_child(panel_id, "SettingsTitle");
		node_tree[label_id].set_pivot(Pivot::TOP_LEFT);
		node_tree[label_id].set_local_position(Vector2::create(24.0, 24.0));
		node_tree[label_id].set_content_size(Vector2::create(300.0, 40.0));
		node_tree.add_component(label_id, UILabel::create_with_text("Settings", 24.0));
		UIWindowLayer::open_window_in_tree(node_tree, layer_id, settings_id);

		let confirm_options = UIConfirmWindowOptions {
			title: String::from("Quit"),
			message: String::from("Do you really want to quit?"),
			cancel_text: String::from("Cancel"),
			confirm_text: String::from("Quit"),
		};
		let quit_id = UIConfirmWindow::create(node_tree, layer_id, "quit", confirm_options);
		if let Some(confirm_window) = node_tree[quit_id].get_component_mut::<UIWindow>().and_then(|window| window.get_behavior_mut::<UIConfirmWindow>()) {
			confirm_window.set_confirm_event(Some(Box::new(|| {
				println!("quit");
			})));
			confirm_window.set_cancel_event(Some(Box::new(|| {
				println!("stay");
			})));
		}
		UIWindowLayer::open_window_in_tree(node_tree, layer_id, quit_id);
		self.layer_id = Some(layer_id);
	}

	fn layout(&mut self) {
		let engine = Engine::get_engine().unwrap();
		let layer_id = match self.layer_id {
			Some(layer_id) => {
				layer_id
			}
			None => {
				return;
			}
		};
		let view_manager = engine.get_view_manager();
		let view_size = view_manager.get_view_size();
		let css_pixel_scale = view_manager.get_css_pixel_scale();
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		node_tree.with_component_mut::<UIWindowLayer, _>(layer_id, |window_layer, tree| {
			window_layer.set_view_size(tree, view_size.x, view_size.y, css_pixel_scale);
		});
	}
}

vanilla::ui_scene!(WindowScene);

fn main() {
	let mut engine_configuration = EngineConfiguration::new();
	engine_configuration.reference_resolution_size = Vector2::create(640.0, 360.0);
	engine_configuration.auto_resize_on_window_resize = true;
	let engine = Engine::new(engine_configuration);
	let mut ui_scene_base = UISceneBase::new();
	ui_scene_base.set_loading_min_duration_ms(0.0);
	let window_scene = WindowScene {
		ui_scene_base,
		layer_id: None,
	};
	if let Err(error) = engine.run(Box::new(window_scene)) {
		eprintln!("{}", error);
	}
}
```

## ButtonMotion

This adds size feedback to a button. Calling `attach_button_motion(node_tree, node_id)` on a node with a `UIButton` attaches `ButtonMotion` as the component after the `UIButton`; every frame it reads the button state and grows and shrinks the node around its center. It does not touch colors. When there is no feedback to show, it leaves the node's place and size alone.

- The styles are `ButtonMotionStyle::Normal` (1.06 times on hover, 0.92 times while pressed, a 1.04 times bounce on release) and `ButtonMotionStyle::Inset` (a button inside a window; it does not grow, the background `Paint` brightens with a white inner ring on hover, and it goes to 0.96 times when pressed).
- Set it per button with `button_motion.set_style(Some(style))`, or set the style of every button under a node with `set_button_motion_area(node_tree, node_id, style)`. If neither is set, it is `Normal`.
- `shake_button(node_tree, node_id)` shakes the button left and right for 0.25 seconds when it cannot be pressed.
- Hover feedback is not used on devices where touch is primary.
- The original computes the center assuming only a top left pivot, while the Rust version reads the node's pivot. The brightened background and white ring of `Inset` are drawn directly rather than kept as child nodes; to let decorations brighten in their own way, set a function with `set_lit_handler`.

```rust
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{attach_button_motion, shake_button, ButtonMotionStyle, Color, ComponentContext, Engine, EngineConfiguration, NodeTree, Paint, Pivot, TouchKind, UIButton, UILabel, 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, "BuyButton");
node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
node_tree[button_id].set_local_position(Vector2::create(240.0, 156.0));
node_tree[button_id].set_content_size(Vector2::create(160.0, 48.0));
let button_paint = node_tree[button_id].add_component(Paint::create_with_color(Color::create(0.36, 0.42, 1.0, 1.0)));
button_paint.set_round_size(10.0);
node_tree.add_component(button_id, UILabel::create_with_text("Buy", 18.0));

let coin_count = Rc::new(Cell::new(40));
let coin_count_for_event = coin_count.clone();
let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
button.set_clicked_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
	if coin_count_for_event.get() < 100 {
		let button_id = context.get_node_id();
		shake_button(context.get_node_tree_mut(), button_id);
		return;
	}
	coin_count_for_event.set(coin_count_for_event.get() - 100);
}));
let button_motion = attach_button_motion(&mut node_tree, button_id).expect("button motion");
button_motion.set_style(Some(ButtonMotionStyle::Normal));

let center = Vector2::create(320.0, 180.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, center);
node_tree.tick(&engine, 0.1);
assert!(node_tree[button_id].get_local_scale().x < 1.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, center);
assert_eq!(coin_count.get(), 40);
```

## Things to watch out for

- The `UIScene` loading screen stays up for 3 seconds by default. To skip it, give `set_loading_min_duration_ms(0.0)`.
- Attach widgets with `node_tree.add_component(node_id, ...)`. Attaching with `node_tree[node_id].add_component(...)` creates no content node and does not turn the node `interactable`, so it cannot be pressed.
- A plain `Scene` also passes presses to widgets, but it lacks the gesture that hands a drag over to a scroll view. If you put buttons inside a scroll view, use `UIScene` or run a `TouchRecognizer` yourself.
- Among values that scene code changes while holding only a component, those that must reach other nodes (scroll offset and scroll bars, the colors of `set_interactable` and `set_is_on`, showing a toast) take effect on the next tick. To apply them in the same frame, use the `*_in_tree` functions such as `set_scroll_offset_in_tree`.
- `UIButton` does not draw a background. Attach a `Paint` or `UIImageView` to the same node to give it a shape.
- Widget events are closures in a `Box`, so they cannot borrow the scene's fields directly. Put values shared with code outside the event in `Rc<Cell<T>>` or `Rc<RefCell<T>>`, and change other nodes through their `NodeId` and the context.
- `UIInputField` receives key input only after you call `attach()`. IME input such as Korean works only with `set_use_dom_input(true)`.
- The default button texts of `UIDialogOptions` and `UIConfirmWindowOptions` are Korean.
- The root returned by `UIDocument::from_json_text` is not attached anywhere. Set the image resolver and call `load_images` before `from_json_text`.

## Related types

UIScene, UISceneBase, UINode, UIView, UIControl, UILabel, UIImageView, UIButton, ButtonState, UIToggleButton, UISlider, UIProgressView, ProgressDirection, UIScrollView, ScrollMode, UIScrollBar, TouchRecognizer, UIInputField, UIDropdown, UIDropdownOptions, UIToast, UIToastOptions, UIDialog, UIDialogOptions, UIDialogShowOptions, UIContextMenu, UISpinner, UIListView, UISnapScrollView, UIDraggable, UILineChart, UIBarChart, UIProgressRing, UIHitArea, UIDocument, NodeLayout, NodeLayoutFanOptions, LayoutSolver, LayoutVariable, LayoutExpression, LayoutConstraint, LayoutStrength, LayoutPriority, LayoutConstraintAxis, LayoutMargins, LayoutError, UIWindowLayer, UIWindow, UIWindowBehavior, UIWindowDefaultBehavior, UIConfirmWindow, UIConfirmWindowOptions, UIScale, UIScaleOptions, PopupMotion, ButtonMotion, ButtonMotionStyle, ButtonMotionArea


> https://vanillapunch.com/docs/vanilla-engine/0.4.0/guide/ui/ (vanilla-engine 0.4.0)
