# misc/nodelayout (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/misc/nodelayout/

Node layout.
- A port of the original misc/nodelayout.js. A fluent builder that lays out node hierarchies declaratively without local variables.
- Positions and sizes are set with number pairs (x, y) without Vector2.
- Usage:
  ```text
    let panel_id = NodeLayout::create()
        .pivot(Pivot::MIDDLE_CENTER)
        .content_size(680.0, 900.0)
        .component_with(Paint::new(), |paint| { paint.set_color(Color::create(0.1, 0.1, 0.1, 1.0)); })
        .children([
            NodeLayout::create()
                .content_size(120.0, 70.0)
                .component_with(Text::new(), |text| { text.set_text("OK"); }),
        ])
        .build(node_tree, Some(parent_id));
  ```
- Differences from the original:
  In the Rust version nodes live only inside the tree (NodeTree), so the builder collects settings in order and, at build(node_tree, parent_id), creates the nodes and applies them in that order.
  So components are also attached with node_tree.add_component at build. (components whose attach_to_tree creates child nodes work too)
  There is no node class, so it is create() instead of create(nodeClass).
  component(type, callback) is split into component(value) and component_with(value, callback). (Rust has no optional arguments)
  The variadic arguments of children(...layouts) are taken as one array or Vec.
  Like the original, anchored_position is applied at build after attaching to the parent, relative to the anchor point of the parent content_size. (the anchor is the one at the time the setting is applied, a local_position set later wins)
  Like the original, mask_enabled(false) removes all Masks of that node, not only the first mask.

## NodeLayoutFanOptions (struct) (Clone, Copy, Debug, PartialEq, Default)

Fan layout settings. (original options = { center_x, center_y, radius, angle_step_radian = 0.12, base_angle_radian = -PI/2, rotate_nodes = true })

Example: Set only the center and radius and leave the rest at defaults

```rust
use vanilla::NodeLayoutFanOptions;

let fan_options = NodeLayoutFanOptions {
	center_x: 640.0,
	center_y: 900.0,
	radius: 400.0,
	..NodeLayoutFanOptions::default()
};
assert_eq!(fan_options.angle_step_radian, 0.12);
assert!(fan_options.rotate_nodes);
```

- `pub center_x: f64` (field, since 0.3.2): Center of the arc.
  - returns f64
- `pub center_y: f64` (field, since 0.3.2): Center y of the arc. (paired with center_x, local coordinates relative to the parent area)
  - returns f64
- `pub radius: f64` (field, since 0.3.2): Radius of the arc.
  - returns f64
- `pub angle_step_radian: f64` (field, since 0.3.2): Angle between neighboring items. (radians)
  - returns f64
- `pub base_angle_radian: f64` (field, since 0.3.2): Direction the middle item faces. (radians, up by default)
  - returns f64
- `pub rotate_nodes: bool` (field, since 0.3.2): Whether to also align item rotation to the arc tangent.
  - returns bool

## NodeLayout (struct) (Default)

Node layout.
- Setting methods take and return self so they chain, and build at the end creates the node.

Example: Build a panel and the text node inside it at once

```rust
use vanilla::{Color, NodeLayout, NodeTree, Paint, Pivot, Text, Vector2};

let mut node_tree = NodeTree::new();
let parent_id = node_tree.get_root_id();
let panel_id = NodeLayout::create()
	.pivot(Pivot::MIDDLE_CENTER)
	.content_size(680.0, 900.0)
	.component_with(Paint::new(), |paint| {
		paint.set_color(Color::create(0.1, 0.1, 0.1, 1.0));
	})
	.children([
		NodeLayout::create()
			.name("label")
			.content_size(120.0, 70.0)
			.component_with(Text::new(), |text| {
				text.set_text("OK");
			}),
	])
	.build(&mut node_tree, Some(parent_id));

assert_eq!(node_tree[panel_id].get_content_size(), Vector2::create(680.0, 900.0));
let label_id = node_tree.find_child_by_name(panel_id, "label").unwrap();
assert_eq!(node_tree[label_id].get_component::<Text>().unwrap().get_text(), "OK");
```

- `pub fn new() -> NodeLayout` (constructor, since 0.3.2): Constructor. (empty settings)
  - returns NodeLayout: A new layout with no settings and no children.
- `pub fn create() -> NodeLayout` (static, since 0.3.2): Creates a layout. (original NodeLayout.create(WorldNode))
  - returns NodeLayout: A new layout with no settings and no children. (same as new)
- `pub fn arrange_fan(node_tree: &mut NodeTree, node_ids: &[NodeId], options: NodeLayoutFanOptions)` (static, since 0.3.2): Fan layout. (spreads nodes on an arc, like cards in a hand)
  - Spreads symmetrically left and right so the middle item faces the base_angle_radian direction.
  - If rotate_nodes, also aligns each node's rotation (degrees) to the arc tangent.
  - Changes the nodes' local positions directly. (a static function used separately from the builder)
  - `node_tree` &mut NodeTree: Tree holding the node.
  - `node_ids` &[NodeId]: List of nodes to spread. (left to right in this order, nodes not in the tree are skipped)
  - `options` NodeLayoutFanOptions: Arc center, radius, spacing, direction, whether to rotate.

  Example: Spread three cards on an upward arc

  ```rust
  use vanilla::{NodeId, NodeLayout, NodeLayoutFanOptions, NodeTree};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let card_ids: Vec<NodeId> = (0..3).map(|_| node_tree.create_child(root_id, "card")).collect();
  NodeLayout::arrange_fan(&mut node_tree, &card_ids, NodeLayoutFanOptions {
  	center_x: 100.0,
  	center_y: 500.0,
  	radius: 200.0,
  	..NodeLayoutFanOptions::default()
  });
  let middle_position = node_tree[card_ids[1]].get_local_position();
  assert!((middle_position.x - 100.0).abs() < 0.001);
  assert!((middle_position.y - 300.0).abs() < 0.001);
  assert_eq!(node_tree[card_ids[1]].get_local_rotation(), 0.0);
  assert!(node_tree[card_ids[2]].get_local_rotation() > 0.0);
  ```

- `pub fn apply(self, callback: impl FnOnce(&mut WorldNode) + 'static) -> NodeLayout` (method, since 0.3.2): Direct node access. (for setting properties the builder lacks)
  - `callback` impl FnOnce(&mut WorldNode) + 'static: Function that receives and modifies the node created at build. (called in the order it was attached among the other settings)
  - returns NodeLayout: The layout with one more setting attached.

  Example: Make a pressable node

  ```rust
  use vanilla::{NodeLayout, NodeTree};
  
  let mut node_tree = NodeTree::new();
  let button_id = NodeLayout::create()
  	.apply(|node| {
  		node.set_interactable(true);
  	})
  	.build(&mut node_tree, None);
  assert!(node_tree[button_id].is_interactable());
  ```

- `pub fn active(self, is_active: bool) -> NodeLayout` (method, since 0.3.2): Sets active.
  - `is_active` bool: Whether to enable the node.
  - returns NodeLayout: The layout with one more setting attached.
- `pub fn name(self, name: &str) -> NodeLayout` (method, since 0.3.2): Sets the name.
  - `name` &str: Node name. (the initial name of a built node is an empty string)
  - returns NodeLayout: The layout with one more setting attached.
- `pub fn component<T: Component + 'static>(self, component: T) -> NodeLayout` (method, since 0.3.2): Adds a component. (configure the value before passing it)
  - `component` T: Component to attach with node_tree.add_component at build.
  - returns NodeLayout: The layout with one more setting attached.
- `pub fn component_with<T: Component + 'static>(self, component: T, callback: impl FnOnce(&mut T) + 'static) -> NodeLayout` (method, since 0.3.2): Adds a component and configures it with a callback. (original component(type, callback))
  - `component` T: Component to attach at build.
  - `callback` impl FnOnce(&mut T) + 'static: Function that receives and configures that component after attaching. (not called if it could not be attached)
  - returns NodeLayout: The layout with one more setting attached.
- `pub fn children(mut self, layouts: impl IntoIterator<Item = NodeLayout>) -> NodeLayout` (method, since 0.3.2): Adds child layouts. (several at once, drawn in the order attached)
  - `layouts` impl IntoIterator<Item = NodeLayout>: Array or Vec of child layouts. (recursively built with this node as the parent at build)
  - returns NodeLayout: The layout with the children added.
- `pub fn local_position(self, x: f64, y: f64) -> NodeLayout` (method, since 0.3.2): Sets the local position.
  - `x` f64: Local position x. (relative to the parent area, pixels)
  - `y` f64: Local position y. (pixels)
  - returns NodeLayout: The layout with one more setting attached.
- `pub fn pivot(self, pivot: Vector2) -> NodeLayout` (method, since 0.3.2): Sets the pivot.
  - `pivot` Vector2: Pivot. (0 ~ 1, a constant like Pivot::MIDDLE_CENTER)
  - returns NodeLayout: The layout with one more setting attached.
- `pub fn content_size(self, x: f64, y: f64) -> NodeLayout` (method, since 0.3.2): Sets the content size.
  - `x` f64: Width. (pixels)
  - `y` f64: Height. (pixels)
  - returns NodeLayout: The layout with one more setting attached.
- `pub fn local_scale(self, x: f64, y: f64) -> NodeLayout` (method, since 0.3.2): Sets the local scale.
  - `x` f64: Horizontal scale. (1 is the original size)
  - `y` f64: Vertical scale.
  - returns NodeLayout: The layout with one more setting attached.
- `pub fn parent(mut self, parent_id: NodeId) -> NodeLayout` (method, since 0.3.2): Sets the parent node. (if no parent is passed to build, attaches as a child of this parent)
  - `parent_id` NodeId: Parent node to attach to.
  - returns NodeLayout: The layout with the parent set.
- `pub fn anchor(self, x: f64, y: f64) -> NodeLayout` (method, since 0.3.2): Sets the anchor.
  - `x` f64: Horizontal anchor. (0 ~ 1, ratio of the parent content_size)
  - `y` f64: Vertical anchor. (0 ~ 1)
  - returns NodeLayout: The layout with one more setting attached.
- `pub fn anchored_position(self, x: f64, y: f64) -> NodeLayout` (method, since 0.3.2): Sets the anchored position. (relative to the anchor point of the parent content_size if there is a parent, otherwise the local position as is)
  - Computed at build from the anchor and parent size at the moment it is applied. So attach anchor before this.
  - `x` f64: Horizontal distance from the anchor point. (pixels)
  - `y` f64: Vertical distance from the anchor point. (pixels)
  - returns NodeLayout: The layout with one more setting attached.

  Example: Inward from the parent's bottom right corner

  ```rust
  use vanilla::{NodeLayout, NodeTree, Pivot, Vector2};
  
  let mut node_tree = NodeTree::new();
  let panel_id = NodeLayout::create()
  	.pivot(Pivot::TOP_LEFT)
  	.content_size(680.0, 900.0)
  	.children([
  		NodeLayout::create().name("corner").anchor(1.0, 1.0).anchored_position(-10.0, -20.0),
  	])
  	.build(&mut node_tree, None);
  let corner_id = node_tree.find_child_by_name(panel_id, "corner").unwrap();
  assert_eq!(node_tree[corner_id].get_local_position(), Vector2::create(670.0, 880.0));
  ```

- `pub fn mask_enabled(self, is_enabled: bool) -> NodeLayout` (method, since 0.3.2): Turns the mask on / off. (on attaches a Mask only if there is none, off removes it)
  - `is_enabled` bool: true attaches a Mask, false removes all of the node's Masks.
  - returns NodeLayout: The layout with one more setting attached.
- `pub fn build(self, node_tree: &mut NodeTree, parent_id: Option<NodeId>) -> NodeId` (method, since 0.3.2): Build. (creates the node and attaches it to the parent, applies the collected settings in order, then recursively builds the child layouts)
  - Attaches to parent_id if passed, otherwise to the parent set with parent(). If neither, it is attached nowhere.
  - Returns the handle of the created node.
  - `node_tree` &mut NodeTree: Tree to create the node in.
  - `parent_id` Option<NodeId>: Parent to attach to. None uses the parent set with parent().
  - returns NodeId: The created node. (the child layouts' nodes are beneath it)

  Example: Set the parent beforehand with parent() and build with None

  ```rust
  use vanilla::{NodeLayout, NodeTree};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_id = NodeLayout::create().name("hud").parent(root_id).build(&mut node_tree, None);
  assert_eq!(node_tree.get_parent_id(node_id), Some(root_id));
  
  let detached_id = NodeLayout::create().build(&mut node_tree, None);
  assert_eq!(node_tree.get_parent_id(detached_id), None);
  ```

