vanilladocs
vanillapunch.com
API / ui/uidropdown

ui/uidropdown

드롭다운. (원본 ui/uidropdown.js 의 UIDropdown, 콤보박스)

  • 닫힌 머리 단추에 지금 값이 보이고, 누르면 아래로 선택지 목록이 펼쳐진다. 행을 누르면 고르고 접힌다.
  • 펼칠 때 목록을 트리 뿌리의 마지막 자식으로 옮겨, 나중에 그려지는 형제 노드에 가리지 않게 한다. (접으면 머리 단추 아래로 되돌린다)
  • 머리 단추의 틴트 대상에서 펼침 목록 노드를 뺀다. (exclude_node_from_tint, 빼지 않으면 고른 뒤 머리 단추가 매 tick 눌렀을 때 담아 둔 옛 행 색을 다시 써서 선택 강조가 덮인다) 강조를 바꾼 뒤에는 행 단추들이 틴트 원래 색을 다시 담게 한다. (원본은 그 자리에서, 러스트 판은 다음 tick 에)
  • 원본은 WorldNode 를 상속한 노드다. 러스트 판은 노드(호스트)에 붙는 컴포넌트이고, 붙을 때 원본 생성자처럼 호스트를 꾸미고(왼쪽 위 피봇, 크기, interactable) Paint + UIButton + UILabel(머리 글)을 호스트에, 화살표 노드와 펼침 목록 노드를 자식으로 만든다. UIDropdown::create(node_tree, parent_id, options) 가 원본 new UIDropdown(options) + add_child 자리다.
  • 사용:
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(); }));
  • 원본과 다른 것:
  • 트리를 바꾸는 함수(set_option_list, set_open, set_selected_index)는 트리를 받는다. 씬 코드는 node_tree.with_component_mut 로 부른다. select_index 는 바뀜 이벤트에 문맥을 넘기려고 문맥을 받는다. (행 단추가 ComponentContext::with_component_mut 로 부른다)
  • 바뀜 이벤트는 드롭다운과 문맥을 받는다. options 객체는 UIDropdownOptions 구조체다.
  • 행 강조는 펼침 목록의 자식 순서 대신 만든 행 노드 목록으로 고친다. (tick 중에 다시 만들면 지운 행이 잠깐 자식으로 남는다)
  • 화살표 글자는 원본처럼 작은 삼각형(▾ ▴, U+25BE / U+25B4)이다. 기본 글꼴(맑은 고딕, Segoe UI, Arial)에 없는 글자는 크롬처럼 시스템 대체 글꼴로 그린다. (core/textshaping.rs)
  • 노드 이름은 원본처럼 "DropdownArrow", "DropdownPopup", "DropdownOption{번호}" 다. 호스트 이름은 만든 쪽이 정한다. (create 는 "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:
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)

UIDropdownOptionsstruct traits Clone, Copy, Debug, PartialEq, Default

소스source

드롭다운 설정. (원본 options = { width = 180, height = 30, option_height = 28, font_size = 12, base_color?, popup_color?, highlight_color?, text_color? })

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
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));
필드fieldpub width: f64#0.3.2 부터since 0.3.2소스source

머리 단추 가로. (기본 180, 펼침 목록도 같은 가로)

Header button width. (default 180, the popup list has the same width)

반환Returnsf64

필드fieldpub height: f64#0.3.2 부터since 0.3.2소스source

머리 단추 세로. (기본 30)

Header button height. (default 30)

반환Returnsf64

필드fieldpub option_height: f64#0.3.2 부터since 0.3.2소스source

선택지 행 높이.

Option row height.

반환Returnsf64

필드fieldpub font_size: f64#0.3.2 부터since 0.3.2소스source

머리 글과 선택지 글의 크기. (기본 12)

Size of the header text and option text. (default 12)

반환Returnsf64

필드fieldpub base_color: Color#0.3.2 부터since 0.3.2소스source

머리 단추 바탕색.

Header button background color.

반환ReturnsColor

필드fieldpub popup_color: Color#0.3.2 부터since 0.3.2소스source

펼침 목록 바탕색.

Popup list background color.

반환ReturnsColor

필드fieldpub highlight_color: Color#0.3.2 부터since 0.3.2소스source

고른 행 강조색.

Highlight color of the selected row.

반환ReturnsColor

필드fieldpub text_color: Color#0.3.2 부터since 0.3.2소스source

머리 글, 화살표, 선택지 글의 색.

Color of the header text, arrow, and option text.

반환ReturnsColor

UIDropdownEventtype

소스source

드롭다운 이벤트. (드롭다운과 문맥을 받는다)

Dropdown event. (takes the dropdown and the context)

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

UIDropdownstruct traits Default, Component, UIDocumentNode

짝Counterpart: vanilla.js UIDropdown소스source

드롭다운.

Dropdown.

예제Example선택지를 넣고 고른 글 읽기Put in options and read the selected text
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");
생성자constructorpub fn new() -> UIDropdown#0.3.2 부터since 0.3.2소스source

생성. (기본 설정)

Constructor. (default settings)

반환ReturnsUIDropdown 붙기 전의 드롭다운. (UIDropdownOptions::default, 선택지 없음)Dropdown before being attached. (UIDropdownOptions::default, no options)

짝Counterpart: vanilla.js UIDropdown.constructor

정적staticpub fn create_with_options(options: UIDropdownOptions) -> UIDropdown#0.3.2 부터since 0.3.2소스source

설정으로 생성. (노드에는 node_tree.add_component 로 붙인다)

Creates with settings. (attach to a node with node_tree.add_component)

optionsUIDropdownOptions
드롭다운 설정.Dropdown settings.

반환ReturnsUIDropdown 붙기 전의 드롭다운. (선택지 없음)Dropdown before being attached. (no options)

정적staticpub fn create(node_tree: &mut NodeTree, parent_id: NodeId, options: UIDropdownOptions) -> NodeId#0.3.2 부터since 0.3.2소스source

노드 만들기. (parent_id 밑에 "UIDropdown" 노드를 만들어 붙인다. 원본 new UIDropdown(options) + add_child)

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_idNodeId
부모 노드.Parent node.
optionsUIDropdownOptions
드롭다운 설정.Dropdown settings.

반환ReturnsNodeId 만든 호스트 노드. (머리 단추)The created host node. (the header button)

메서드methodpub fn set_option_list(&mut self, node_tree: &mut NodeTree, option_list: &[impl AsRef<str>])#0.3.2 부터since 0.3.2소스source

선택지 목록 설정. (펼침 목록 행을 다시 만든다)

  • 고른 번호는 새 목록의 범위로 자른다. 트리에 붙기 전이면 목록만 담아 두고 붙을 때 행을 만든다.

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>]
선택지 글 목록. (&str 이나 String 조각)List of option texts. (a slice of &str or String)

짝Counterpart: vanilla.js UIDropdown.setOptionList

메서드methodpub fn select_index(&mut self, context: &mut ComponentContext, option_index: usize)#0.3.2 부터since 0.3.2소스source

고르기. (접고, 머리 글과 강조를 고치고, 바뀌었으면 바뀜 이벤트를 부른다. 문맥은 드롭다운 호스트의 것)

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_indexusize
고를 번호. (0 부터, 선택지 수 이상이면 아무 일도 없다)Index to select. (from 0, does nothing if not less than the option count)

짝Counterpart: vanilla.js UIDropdown.selectIndex

메서드methodpub fn set_open(&mut self, node_tree: &mut NodeTree, is_open: bool)#0.3.2 부터since 0.3.2소스source

펼침 / 접힘. (펼치면 목록을 트리 뿌리로 옮기고, 접으면 되돌린다)

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_openbool
true 면 펼친다. (화살표 글자도 바꾼다)true to expand. (also changes the arrow character)

짝Counterpart: vanilla.js UIDropdown.setOpen

예제Example펼친 동안 목록은 트리 뿌리의 자식이다While expanded, the list is a child of the tree root
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));
메서드methodpub fn set_changed_event(&mut self, changed_event: UIDropdownEvent)#0.3.2 부터since 0.3.2소스source

바뀜 이벤트 설정.

Sets the changed event.

changed_eventUIDropdownEvent
행을 눌러 고른 번호가 바뀌면 부르는 이벤트. (같은 행을 다시 고르거나 set_selected_index 로 바꾸면 부르지 않는다)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)

짝Counterpart: vanilla.js UIDropdown.setChangedEvent

예제Example펼친 목록의 행을 누르면 고르고 접힌다Pressing a row in the expanded list selects it and collapses
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());
메서드methodpub fn set_selected_index(&mut self, node_tree: &mut NodeTree, selected_index: usize)#0.3.2 부터since 0.3.2소스source

고른 번호 설정. (범위로 자른다. 바뀜 이벤트는 부르지 않는다. 원본과 같음)

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_indexusize
고를 번호. (0 부터, 선택지 수 - 1 을 넘으면 그 값으로 자른다)Index to select. (from 0, clamped to option count - 1 if it exceeds that)

짝Counterpart: vanilla.js UIDropdown.setSelectedIndex

메서드methodpub fn get_selected_index(&self) -> usize#0.3.2 부터since 0.3.2소스source

고른 번호 반환.

Returns the selected index.

반환Returnsusize 고른 번호. (0 부터, 처음은 0)Selected index. (from 0, initially 0)

짝Counterpart: vanilla.js UIDropdown.getSelectedIndex

메서드methodpub fn get_selected_text(&self) -> &str#0.3.2 부터since 0.3.2소스source

고른 글 반환. (선택지가 없으면 빈 글)

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)

짝Counterpart: vanilla.js UIDropdown.getSelectedText

메서드methodpub fn get_option_list(&self) -> &[String]#0.3.2 부터since 0.3.2소스source

선택지 목록 반환.

Returns the option list.

반환Returns&[String] 선택지 글 목록. (set_option_list 의 차례)List of option texts. (in set_option_list order)

짝Counterpart: vanilla.js UIDropdown.getOptionList

메서드methodpub fn is_open(&self) -> bool#0.3.2 부터since 0.3.2소스source

펼쳐져 있는지.

Whether it is expanded.

반환Returnsbool 펼쳐져 있으면 true.true if expanded.

짝Counterpart: vanilla.js UIDropdown.isOpen

메서드methodpub fn get_popup_node(&self) -> Option<NodeId>#0.3.2 부터since 0.3.2소스source

펼침 목록 노드 핸들. (펼친 동안은 트리 뿌리의 자식)

Popup list node handle. (a child of the tree root while expanded)

반환ReturnsOption<NodeId> 펼침 목록 노드. (트리에 붙기 전이면 None)Popup list node. (None before being attached to a tree)

짝Counterpart: vanilla.js UIDropdown.getPopupNode

메서드methodpub fn get_option_nodes(&self) -> &[NodeId]#0.3.2 부터since 0.3.2소스source

선택지 행 노드 핸들 목록.

List of option row node handles.

반환Returns&[NodeId] 행 노드. (선택지 차례, set_option_list 마다 다시 만든다)Row nodes. (in option order, rebuilt on every set_option_list)

짝Counterpart: vanilla.js UIDropdown.getOptionNodes