# ui/uidropdown (vanilla-engine 0.4.0)

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

Dropdown. (UIDropdown of the original ui/uidropdown.js, a combo box)
- The closed header button shows the current value, and pressing it expands a list of options downward. Pressing a row selects it and collapses.
- On expand, the list is moved to the last child of the tree root so it is not covered by sibling nodes drawn later. (moved back under the header button on collapse)
- The popup list node is excluded from the header button's tint targets. (exclude_node_from_tint, otherwise after selecting, the header button reapplies the old row colors it stored when pressed every tick and
  covers the selection highlight) After changing the highlight, the row buttons are made to store their original tint colors again. (on the spot in the original, on the next tick in the Rust version)
- The original is a node that inherits WorldNode. The Rust version is a component attached to a node (host), and on attach, like the original constructor, it
  sets up the host (top-left pivot, size, interactable), puts Paint + UIButton + UILabel (header text) on the host, and creates the arrow node and the popup list node as children.
  UIDropdown::create(node_tree, parent_id, options) takes the place of the original new UIDropdown(options) + add_child.
- Usage:
  ```text
    let dropdown_id = UIDropdown::create(node_tree, panel_id, UIDropdownOptions { width: 180.0, ..UIDropdownOptions::default() });
    node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| dropdown.set_option_list(tree, &["Dark", "Light", "System"]));
    node_tree[dropdown_id].get_component_mut::<UIDropdown>().unwrap().set_changed_event(Box::new(|dropdown, context| { dropdown.get_selected_text(); }));
  ```
- Differences from the original:
  - Functions that change the tree (set_option_list, set_open, set_selected_index) take the tree. Scene code calls them with node_tree.with_component_mut.
    select_index takes the context to pass it to the changed event. (row buttons call it with ComponentContext::with_component_mut)
  - The changed event takes the dropdown and the context. The options object is the UIDropdownOptions struct.
  - Row highlights are updated through the list of created row nodes instead of the popup list's child order. (when rebuilt during tick, deleted rows briefly remain as children)
  - The arrow characters are small triangles (▾ ▴, U+25BE / U+25B4) as in the original. Characters missing from the default fonts (Malgun Gothic, Segoe UI, Arial) are
    drawn with a system fallback font like Chrome does. (core/textshaping.rs)
  - Node names are "DropdownArrow", "DropdownPopup", "DropdownOption{index}" as in the original. The host name is chosen by the creator. ("UIDropdown" for create)

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

Dropdown settings. (original options = { width = 180, height = 30, option_height = 28, font_size = 12, base_color?, popup_color?, highlight_color?, text_color? })

Example: A wide header button and tall rows

```rust
use vanilla::{NodeTree, UIDropdown, UIDropdownOptions, Vector2};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let options = UIDropdownOptions {
	width: 220.0,
	option_height: 32.0,
	..UIDropdownOptions::default()
};
let dropdown_id = UIDropdown::create(&mut node_tree, root_id, options);
node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
	dropdown.set_option_list(tree, &["Low", "High"]);
});
assert_eq!(node_tree[dropdown_id].get_content_size(), Vector2::create(220.0, 30.0));
let popup_id = node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown").get_popup_node().expect("popup");
assert_eq!(node_tree[popup_id].get_content_size(), Vector2::create(220.0, 72.0));
```

- `pub width: f64` (field, since 0.3.2): Header button width. (default 180, the popup list has the same width)
  - returns f64
- `pub height: f64` (field, since 0.3.2): Header button height. (default 30)
  - returns f64
- `pub option_height: f64` (field, since 0.3.2): Option row height.
  - returns f64
- `pub font_size: f64` (field, since 0.3.2): Size of the header text and option text. (default 12)
  - returns f64
- `pub base_color: Color` (field, since 0.3.2): Header button background color.
  - returns Color
- `pub popup_color: Color` (field, since 0.3.2): Popup list background color.
  - returns Color
- `pub highlight_color: Color` (field, since 0.3.2): Highlight color of the selected row.
  - returns Color
- `pub text_color: Color` (field, since 0.3.2): Color of the header text, arrow, and option text.
  - returns Color

## UIDropdownEvent (type)

Dropdown event. (takes the dropdown and the context)

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

## UIDropdown (struct) (Default, Component, UIDocumentNode)

Dropdown.

Example: Put in options and read the selected text

```rust
use vanilla::{ComponentContext, NodeTree, UIDropdown, UIDropdownOptions, UILabel};

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 dropdown_id = UIDropdown::create(&mut node_tree, panel_id, UIDropdownOptions { width: 180.0, ..UIDropdownOptions::default() });
node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
	dropdown.set_option_list(tree, &["Dark", "Light", "System"]);
	dropdown.set_selected_index(tree, 1);
});
node_tree[dropdown_id].get_component_mut::<UIDropdown>().expect("dropdown").set_changed_event(Box::new(|dropdown: &mut UIDropdown, _context: &mut ComponentContext| {
	let _theme_name = dropdown.get_selected_text();
}));
let dropdown = node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown");
assert_eq!(dropdown.get_selected_text(), "Light");
assert_eq!(node_tree[dropdown_id].get_component::<UILabel>().expect("header").get_text(), "Light");
```

- `pub fn new() -> UIDropdown` (constructor, since 0.3.2): Constructor. (default settings)
  - returns UIDropdown: Dropdown before being attached. (UIDropdownOptions::default, no options)
- `pub fn create_with_options(options: UIDropdownOptions) -> UIDropdown` (static, since 0.3.2): Creates with settings. (attach to a node with node_tree.add_component)
  - `options` UIDropdownOptions: Dropdown settings.
  - returns UIDropdown: Dropdown before being attached. (no options)
- `pub fn create(node_tree: &mut NodeTree, parent_id: NodeId, options: UIDropdownOptions) -> NodeId` (static, since 0.3.2): Creates the node. (creates and attaches a "UIDropdown" node under parent_id. original new UIDropdown(options) + add_child)
  - `node_tree` &mut NodeTree: Node tree.
  - `parent_id` NodeId: Parent node.
  - `options` UIDropdownOptions: Dropdown settings.
  - returns NodeId: The created host node. (the header button)
- `pub fn set_option_list(&mut self, node_tree: &mut NodeTree, option_list: &[impl AsRef<str>])` (method, since 0.3.2): Sets the option list. (rebuilds the popup list rows)
  - The selected index is clamped to the range of the new list. Before being attached to a tree, only stores the list and creates the rows on attach.
  - `node_tree` &mut NodeTree: Node tree that holds the dropdown.
  - `option_list` &[impl AsRef<str>]: List of option texts. (a slice of `&str` or String)
- `pub fn select_index(&mut self, context: &mut ComponentContext, option_index: usize)` (method, since 0.3.2): Selects. (collapses, updates the header text and highlight, and calls the changed event if it changed. the context is the dropdown host's)
  - `context` &mut ComponentContext: Context of the dropdown host node. (passed to the changed event)
  - `option_index` usize: Index to select. (from 0, does nothing if not less than the option count)
- `pub fn set_open(&mut self, node_tree: &mut NodeTree, is_open: bool)` (method, since 0.3.2): Expands / collapses. (on expand, moves the list to the tree root, and moves it back on collapse)
  - `node_tree` &mut NodeTree: Node tree that holds the dropdown.
  - `is_open` bool: true to expand. (also changes the arrow character)

  Example: While expanded, the list is a child of the tree root

  ```rust
  use vanilla::{NodeTree, UIDropdown, UIDropdownOptions, Vector2};
  
  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 dropdown_id = UIDropdown::create(&mut node_tree, panel_id, UIDropdownOptions::default());
  node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
  	dropdown.set_option_list(tree, &["Small", "Large"]);
  	dropdown.set_open(tree, true);
  });
  let popup_id = node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown").get_popup_node().expect("popup");
  assert!(node_tree[popup_id].is_active());
  assert_eq!(node_tree.get_parent_id(popup_id), Some(root_id));
  node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
  	dropdown.set_open(tree, false);
  });
  assert_eq!(node_tree.get_parent_id(popup_id), Some(dropdown_id));
  assert_eq!(node_tree[popup_id].get_local_position(), Vector2::create(0.0, 34.0));
  ```

- `pub fn set_changed_event(&mut self, changed_event: UIDropdownEvent)` (method, since 0.3.2): Sets the changed event.
  - `changed_event` UIDropdownEvent: Event called when the selected index changes by pressing a row. (not called when the same row is selected again or when changed with set_selected_index)

  Example: Pressing a row in the expanded list selects it and collapses

  ```rust
  use std::cell::Cell;
  use std::rc::Rc;
  use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, TouchKind, UIDropdown, UIDropdownOptions, Vector2};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let dropdown_id = UIDropdown::create(&mut node_tree, root_id, UIDropdownOptions::default());
  let changed_count = Rc::new(Cell::new(0));
  let changed_counter = changed_count.clone();
  node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
  	dropdown.set_option_list(tree, &["Easy", "Normal", "Hard"]);
  	dropdown.set_changed_event(Box::new(move |dropdown: &mut UIDropdown, _context: &mut ComponentContext| {
  		assert_eq!(dropdown.get_selected_text(), "Hard");
  		changed_counter.set(changed_counter.get() + 1);
  	}));
  	dropdown.set_open(tree, true);
  });
  let row_id = node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown").get_option_nodes()[2];
  let row_center = node_tree.convert_node_position_to_view_position(row_id, Vector2::create(86.0, 14.0));
  node_tree.dispatch_touch(row_id, &engine, TouchKind::Press, row_center);
  node_tree.dispatch_touch(row_id, &engine, TouchKind::Release, row_center);
  assert_eq!(changed_count.get(), 1);
  assert!(!node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown").is_open());
  ```

- `pub fn set_selected_index(&mut self, node_tree: &mut NodeTree, selected_index: usize)` (method, since 0.3.2): Sets the selected index. (clamped to the range. does not call the changed event. same as the original)
  - `node_tree` &mut NodeTree: Node tree that holds the dropdown.
  - `selected_index` usize: Index to select. (from 0, clamped to option count - 1 if it exceeds that)
- `pub fn get_selected_index(&self) -> usize` (method, since 0.3.2): Returns the selected index.
  - returns usize: Selected index. (from 0, initially 0)
- `pub fn get_selected_text(&self) -> &str` (method, since 0.3.2): Returns the selected text. (empty text if there are no options)
  - returns &str: Text of the selected option. (empty text if there are no options)
- `pub fn get_option_list(&self) -> &[String]` (method, since 0.3.2): Returns the option list.
  - returns &[String]: List of option texts. (in set_option_list order)
- `pub fn is_open(&self) -> bool` (method, since 0.3.2): Whether it is expanded.
  - returns bool: true if expanded.
- `pub fn get_popup_node(&self) -> Option<NodeId>` (method, since 0.3.2): Popup list node handle. (a child of the tree root while expanded)
  - returns Option<NodeId>: Popup list node. (None before being attached to a tree)
- `pub fn get_option_nodes(&self) -> &[NodeId]` (method, since 0.3.2): List of option row node handles.
  - returns &[NodeId]: Row nodes. (in option order, rebuilt on every set_option_list)
