vanilladocs
vanillapunch.com
API / ui/uilistview

ui/uilistview

재활용 리스트 뷰. (원본 ui/uilistview.js 의 UIListView)

  • 항목 수만 받아, 화면에 보이는 범위(앞뒤 여유 칸 포함)만 실제 노드로 만들고 벗어난 노드는 회수해 다시 쓴다. 수백 ~ 수천 건이어도 노드 수는 화면 분량에 머문다. 항목 내용은 set_bind_item_event 로 코드에서 채운다. (데이터 주도)
  • 끝 근처에 닿으면 set_reach_end_event 알림을 한 번 보낸다. (무한 스크롤 / 더 불러오기) set_item_count 로 항목 수가 늘면 다시 무장된다.
  • 원본처럼 스크롤 뷰와 같은 노드에 붙는다. 노드에 스크롤 뷰가 없으면 붙을 때 UIScrollView 를 함께 붙인다. (원본 require) UISnapScrollView 가 붙은 노드면 그 품은 뷰를 쓴다. (원본 getComponents(UIScrollView) 가 하위 클래스까지 잡는 자리) 스크롤 뷰가 먼저 붙어 먼저 tick 하므로, 이 위젯은 그 프레임의 스크롤 오프셋으로 보이는 범위를 고른다.
  • 사용:
let list_view = node_tree.add_component(list_id, UIListView::new()).expect("list view");
list_view.set_create_item_event(Box::new(|tree: &mut NodeTree| { let item_id = tree.create_node("item"); ...; item_id }));
list_view.set_bind_item_event(Box::new(|tree: &mut NodeTree, item_id: NodeId, item_index: usize| { ... }));
list_view.set_item_count(500);
  • 원본과 다른 것:
  • set_template_node 는 원본처럼 템플릿 노드를 UIDocument 로 직렬화해 두고 항목마다 복제한다. 원본은 반사로 모든 컴포넌트를 적지만, 러스트 판은 UIDocument 에 등록한 종류만 복제한다. (게임 컴포넌트는 set_template_node_with_document 에 등록을 마친 UIDocument 를 넘긴다)
  • 항목 노드를 만드는 함수(set_create_item_event)도 받는다. (러스트 판에서 먼저 생긴 범용 기능, 원본에도 넣었다) 만든 노드는 content 노드의 자식으로 옮겨 붙인다. 항목 크기를 정하지 않았으면(0) 원본이 템플릿 크기를 읽듯 처음 만든 항목 노드의 진행 축 content_size 를 읽는다.
  • 바인드 이벤트는 (트리, 항목 노드, 항목 번호) 를 받는다. 끝 알림은 리스트 뷰와 문맥을 받는다.
  • set_item_count, set_item_size, set_spacing, refresh 는 값을 정해 두고 다음 tick 에 스크롤 영역 갱신과 다시 바인딩을 한다. (원본은 그 자리에서 한다. 같은 노드의 스크롤 뷰는 씬 코드가 이 위젯을 쥐고 있는 동안 닿을 수 없다)
  • 활성 항목은 원본 Map 처럼 넣은 순서로 든다.

Recycling list view. (UIListView of the original ui/uilistview.js)

  • Takes only the item count, creates real nodes only for the visible range (including buffer slots before and after), and recovers and reuses nodes that leave it. Even with hundreds ~ thousands of items, the node count stays at one screenful. Item contents are filled in code with set_bind_item_event. (data driven)
  • When it gets near the end, it sends the set_reach_end_event notification once. (infinite scroll / load more) It is rearmed when set_item_count increases the item count.
  • As in the original, it attaches to the same node as the scroll view. If the node has no scroll view, a UIScrollView is attached along with it on attach. (original require) On a node with a UISnapScrollView, it uses that embedded view. (where the original getComponents(UIScrollView) also catches subclasses) The scroll view is attached first and ticks first, so this widget picks the visible range with that frame's scroll offset.
  • Usage:
let list_view = node_tree.add_component(list_id, UIListView::new()).expect("list view");
list_view.set_create_item_event(Box::new(|tree: &mut NodeTree| { let item_id = tree.create_node("item"); ...; item_id }));
list_view.set_bind_item_event(Box::new(|tree: &mut NodeTree, item_id: NodeId, item_index: usize| { ... }));
list_view.set_item_count(500);
  • Differences from the original:
  • set_template_node serializes the template node with UIDocument and clones it per item as in the original. The original records every component through reflection, but the Rust version clones only types registered with UIDocument. (for game components, pass a UIDocument with registration done to set_template_node_with_document)
  • It also takes a function that creates item nodes (set_create_item_event). (a general feature that appeared first in the Rust version, also added to the original) Created nodes are moved under the content node as children. If the item size is not set (0), it reads the progress axis content_size of the first created item node, like the original reads the template size.
  • The bind event takes (tree, item node, item index). The end notification takes the list view and the context.
  • set_item_count, set_item_size, set_spacing, refresh set the values and update the scroll area and rebind on the next tick. (the original does it on the spot. the scroll view on the same node cannot be reached while scene code is holding this widget)
  • Active items are held in insertion order like the original Map.

UIListViewCreateItemEventtype

소스source

항목 노드 만들기 함수. (트리를 받아 새 항목 노드를 돌려준다. 원본 템플릿 복제 자리)

Item node creation function. (takes the tree and returns a new item node. in place of the original template cloning)

pub type UIListViewCreateItemEvent = Box<dyn FnMut(&mut NodeTree) -> NodeId>

UIListViewBindItemEventtype

소스source

바인드 이벤트. (트리, 항목 노드, 항목 번호)

Bind event. (tree, item node, item index)

pub type UIListViewBindItemEvent = Box<dyn FnMut(&mut NodeTree, NodeId, usize)>

UIListViewReachEndEventtype

소스source

끝 알림. (리스트 뷰와 문맥을 받는다)

End notification. (takes the list view and the context)

pub type UIListViewReachEndEvent = Box<dyn FnMut(&mut UIListView, &mut ComponentContext)>

UIListViewstruct traits Default, Component

짝Counterpart: vanilla.js UIListView소스source

재활용 리스트 뷰.

  • 같은 노드의 스크롤 뷰(없으면 붙을 때 UIScrollView 를 함께 붙인다) 오프셋으로 보이는 항목만 content 노드 아래에 노드로 둔다.
  • 항목 노드를 만드는 함수(set_create_item_event 나 set_template_node)가 없으면 tick 에서 아무것도 하지 않는다.

Recycling list view.

  • Keeps only the items visible at the offset of the scroll view on the same node (a UIScrollView is attached along with it on attach if there is none) as nodes under the content node.
  • Does nothing in tick if there is no item node creation function (set_create_item_event or set_template_node).
예제Example항목 500 개 가운데 보이는 다섯 개만 노드로 만들기Create nodes only for the five visible items out of 500
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, NodeId, NodeTree, Pivot, UIListView, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let list_id = node_tree.create_child(root_id, "list");
node_tree[list_id].set_pivot(Pivot::TOP_LEFT);
node_tree[list_id].set_content_size(Vector2::create(200.0, 100.0));
let bound_index_list = Rc::new(RefCell::new(Vec::new()));
let bound_index_recorder = bound_index_list.clone();

let list_view = node_tree.add_component(list_id, UIListView::new()).expect("list view");
list_view.set_create_item_event(Box::new(|tree: &mut NodeTree| {
	let item_id = tree.create_node("item");
	tree[item_id].set_pivot(Pivot::TOP_LEFT);
	tree[item_id].set_content_size(Vector2::create(200.0, 30.0));
	item_id
}));
list_view.set_bind_item_event(Box::new(move |_tree: &mut NodeTree, _item_id: NodeId, item_index: usize| {
	bound_index_recorder.borrow_mut().push(item_index);
}));
list_view.set_item_count(500);
node_tree.tick(&engine, 0.016);

let list_view = node_tree[list_id].get_component::<UIListView>().expect("list view");
assert_eq!(list_view.get_item_size(), 30.0);
assert_eq!(list_view.get_active_item_count(), 5);
assert_eq!(*bound_index_list.borrow(), vec![0, 1, 2, 3, 4]);
let fourth_id = list_view.get_item_node(4).expect("item 4");
assert_eq!(node_tree[fourth_id].get_local_position(), Vector2::create(0.0, 120.0));
assert!(list_view.get_item_node(100).is_none());
생성자constructorpub fn new() -> UIListView#0.3.2 부터since 0.3.2소스source

생성. (세로, 여유 1 칸, 끝 알림 거리 120 픽셀)

  • 노드에 붙일 때는 node_tree.add_component 를 쓴다. (노드에 스크롤 뷰가 없으면 UIScrollView 를 함께 붙인다)

Constructor. (vertical, 1 buffer slot, end notification distance 120 pixels)

  • Use node_tree.add_component to attach it to a node. (a UIScrollView is attached along with it if the node has no scroll view)

반환ReturnsUIListView 항목 0 개, 항목 크기 0(처음 만든 항목에서 읽음), 간격 0 의 새 리스트 뷰.New list view with 0 items, item size 0 (read from the first created item), and spacing 0.

짝Counterpart: vanilla.js UIListView.constructor

메서드methodpub fn set_create_item_event(&mut self, create_item_event: UIListViewCreateItemEvent)#0.3.2 부터since 0.3.2소스source

항목 노드 만들기 함수 설정. (원본 setTemplateNode 자리)

Sets the item node creation function. (in place of the original setTemplateNode)

create_item_eventUIListViewCreateItemEvent
트리에 새 항목 노드를 지어 돌려주는 함수. 돌려준 노드는 content 노드의 자식으로 옮겨 붙인다. 트리에 없는 노드를 돌려주면 그 tick 의 항목 만들기를 멈춘다.Function that builds a new item node in the tree and returns it. The returned node is moved under the content node as a child. Returning a node not in the tree stops item creation for that tick.

짝Counterpart: vanilla.js UIListView.setCreateItemEvent

메서드methodpub fn set_template_node(&mut self, node_tree: &mut NodeTree, template_node_id: NodeId)#0.4.0 부터since 0.4.0소스source

템플릿 노드 설정. (UIDocument 로 직렬화해 두고 항목마다 복제한다, 템플릿은 끈다. 항목 크기가 0 이면 템플릿 크기로, 원본 setTemplateNode)

  • UIDocument 에 등록한 엔진 종류만 복제한다. 게임 컴포넌트가 든 템플릿은 set_template_node_with_document 를 쓴다.
  • 이 위젯을 트리에서 꺼내 불러야 해서 씬 코드에서는 node_tree.with_component_mut 안에서 부른다.

Sets the template node. (serializes it with UIDocument and clones it per item, the template is turned off. if the item size is 0, uses the template size. original setTemplateNode)

  • Clones only engine types registered with UIDocument. For a template with game components, use set_template_node_with_document.
  • This widget must be taken out of the tree to call it, so scene code calls it inside node_tree.with_component_mut.
node_tree&mut NodeTree
템플릿 노드가 든 트리.Tree that holds the template node.
template_node_idNodeId
복제할 템플릿 노드. 없는 노드면 아무것도 하지 않는다.Template node to clone. Does nothing if the node does not exist.

짝Counterpart: vanilla.js UIListView.setTemplateNode

예제Example템플릿 노드를 항목마다 복제하기Clone the template node per item
use vanilla::{Engine, EngineConfiguration, NodeTree, Pivot, UIListView, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let list_id = node_tree.create_child(root_id, "list");
node_tree[list_id].set_pivot(Pivot::TOP_LEFT);
node_tree[list_id].set_content_size(Vector2::create(200.0, 100.0));
node_tree.add_component(list_id, UIListView::new());
let template_id = node_tree.create_child(root_id, "template");
node_tree[template_id].set_pivot(Pivot::TOP_LEFT);
node_tree[template_id].set_content_size(Vector2::create(200.0, 40.0));

node_tree.with_component_mut::<UIListView, _>(list_id, |list_view, tree| {
	list_view.set_template_node(tree, template_id);
	list_view.set_item_count(20);
});
assert!(!node_tree[template_id].is_active());
node_tree.tick(&engine, 0.016);

let list_view = node_tree[list_id].get_component::<UIListView>().expect("list view");
assert_eq!(list_view.get_item_size(), 40.0);
assert_eq!(list_view.get_active_item_count(), 4);
let item_id = list_view.get_item_node(1).expect("item 1");
assert_eq!(node_tree[item_id].get_content_size(), Vector2::create(200.0, 40.0));
assert!(node_tree[item_id].is_active());
메서드methodpub fn set_template_node_with_document(&mut self, node_tree: &mut NodeTree, template_node_id: NodeId, ui_document: UIDocument)#0.4.0 부터since 0.4.0소스source

템플릿 노드 설정. (게임 컴포넌트를 등록한 UIDocument 로 직렬화하고 복제한다)

Sets the template node. (serialized and cloned with a UIDocument in which game components are registered)

node_tree&mut NodeTree
템플릿 노드가 든 트리.Tree that holds the template node.
template_node_idNodeId
복제할 템플릿 노드. 없는 노드면 아무것도 하지 않는다.Template node to clone. Does nothing if the node does not exist.
ui_documentUIDocument
템플릿을 쓰고 읽을 문서. (템플릿의 컴포넌트 종류를 등록해 둔 것, 항목을 만들 때마다 이 문서로 읽는다)Document to write and read the template with. (one with the template's component types registered, read with this document every time an item is created)

짝Counterpart: vanilla.js UIListView.setTemplateNodeWithDocument

메서드methodpub fn set_item_count(&mut self, item_count: usize)#0.3.2 부터since 0.3.2소스source

항목 수 설정. (늘면 끝 알림을 다시 무장한다. 스크롤 영역 갱신과 다시 바인딩은 다음 tick)

Sets the item count. (rearms the end notification if it increases. scroll area update and rebinding happen on the next tick)

item_countusize
전체 항목 수. (줄면 넘친 항목 노드는 다음 tick 에 회수한다)Total item count. (if it decreases, excess item nodes are recovered on the next tick)

짝Counterpart: vanilla.js UIListView.setItemCount

메서드methodpub fn refresh(&mut self)#0.3.2 부터since 0.3.2소스source

보이는 항목 모두 다시 바인딩. (데이터 내용이 바뀌었을 때. 다음 tick 에 한다)

Rebinds all visible items. (when the data contents change. done on the next tick)

짝Counterpart: vanilla.js UIListView.refresh

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

보이는 항목 모두 지금 다시 바인딩. (트리를 쥔 씬 코드용. 원본 refresh 그대로)

  • 바인드 이벤트가 없으면 아무것도 하지 않는다. 항목 수를 넘은 항목과 지워진 노드는 건너뛴다.

Rebinds all visible items right now. (for scene code holding the tree. the original refresh as is)

  • Does nothing if there is no bind event. Items beyond the item count and deleted nodes are skipped.
node_tree&mut NodeTree
항목 노드가 든 트리.Tree that holds the item nodes.
메서드methodpub fn get_item_node(&self, item_index: usize) -> Option<NodeId>#0.3.2 부터since 0.3.2소스source

특정 항목의 실제 노드. (화면 밖이면 None)

The real node of a specific item. (None if off screen)

item_indexusize
항목 번호. (0 부터)Item index. (from 0)

반환ReturnsOption<NodeId> 그 항목을 보이는 노드. 지금 만들어 둔 범위(보이는 범위와 여유 칸) 밖이면 None.The node showing that item. None if outside the currently created range (visible range and buffer slots).

짝Counterpart: vanilla.js UIListView.getItemNode

메서드methodpub fn set_bind_item_event(&mut self, bind_item_event: UIListViewBindItemEvent)#0.3.2 부터since 0.3.2소스source

바인드 이벤트 설정.

Sets the bind event.

bind_item_eventUIListViewBindItemEvent
(트리, 항목 노드, 항목 번호) 를 받아 항목 노드 내용을 채우는 함수. 노드를 새로 놓을 때(만들거나 다시 쓸 때)와 다시 바인딩할 때 부른다.Function that takes (tree, item node, item index) and fills in the item node contents. Called when a node is newly placed (created or reused) and when rebinding.

짝Counterpart: vanilla.js UIListView.setBindItemEvent

메서드methodpub fn set_reach_end_event(&mut self, reach_end_event: UIListViewReachEndEvent)#0.3.2 부터since 0.3.2소스source

끝 알림 설정.

Sets the end notification.

reach_end_eventUIListViewReachEndEvent
끝까지 남은 길이가 끝 알림 거리 이하가 되면 한 번 부를 함수. (리스트 뷰와 문맥을 받는다, 안에서 set_item_count 로 항목을 늘리면 다시 무장된다)Function called once when the remaining length to the end falls to the end notification distance or less. (takes the list view and the context, rearmed if set_item_count increases the items inside it)

짝Counterpart: vanilla.js UIListView.setReachEndEvent

예제Example끝 근처에 닿으면 항목 50 개 더 불러오기Load 50 more items when near the end
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, Pivot, UIListView, UIScrollView, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let list_id = node_tree.create_child(root_id, "list");
node_tree[list_id].set_pivot(Pivot::TOP_LEFT);
node_tree[list_id].set_content_size(Vector2::create(200.0, 100.0));
let reach_end_count = Rc::new(Cell::new(0));
let reach_end_counter = reach_end_count.clone();

let list_view = node_tree.add_component(list_id, UIListView::new()).expect("list view");
list_view.set_create_item_event(Box::new(|tree: &mut NodeTree| {
	tree.create_node("item")
}));
list_view.set_item_size(30.0);
list_view.set_item_count(100);
list_view.set_reach_end_event(Box::new(move |list_view: &mut UIListView, _context: &mut ComponentContext| {
	reach_end_counter.set(reach_end_counter.get() + 1);
	let item_count = list_view.get_item_count();
	list_view.set_item_count(item_count + 50);
}));
node_tree.tick(&engine, 0.016);
assert_eq!(reach_end_count.get(), 0);

node_tree[list_id].get_component_mut::<UIScrollView>().expect("scroll view").set_scroll_offset(Vector2::create(0.0, -2900.0));
node_tree.tick(&engine, 0.016);
assert_eq!(reach_end_count.get(), 1);
assert_eq!(node_tree[list_id].get_component::<UIListView>().expect("list view").get_item_count(), 150);
메서드methodpub fn set_reach_end_threshold(&mut self, reach_end_threshold: f64)#0.3.2 부터since 0.3.2소스source

끝 알림 거리 설정. (픽셀)

Sets the end notification distance. (pixels)

reach_end_thresholdf64
끝까지 남은 길이가 이 값 이하면 알린다. (픽셀, 기본 120)Notifies when the remaining length to the end is this value or less. (pixels, default 120)

짝Counterpart: vanilla.js UIListView.setReachEndThreshold

메서드methodpub fn set_item_size(&mut self, item_size: f64)#0.3.2 부터since 0.3.2소스source

진행 축 방향 항목 크기 설정. (스크롤 영역은 다음 tick 에 갱신)

Sets the item size along the progress axis. (the scroll area is updated on the next tick)

item_sizef64
항목 하나의 진행 축 길이. (픽셀, 0 이하면 처음 만든 항목 노드의 content_size 를 읽는다)Length of one item along the progress axis. (pixels, if 0 or less, reads the content_size of the first created item node)

짝Counterpart: vanilla.js UIListView.setItemSize

메서드methodpub fn set_spacing(&mut self, spacing: f64)#0.3.2 부터since 0.3.2소스source

항목 사이 간격 설정. (스크롤 영역은 다음 tick 에 갱신)

Sets the spacing between items. (the scroll area is updated on the next tick)

spacingf64
항목 사이 간격. (픽셀, 기본 0)Spacing between items. (pixels, default 0)

짝Counterpart: vanilla.js UIListView.setSpacing

메서드methodpub fn set_horizontal(&mut self, is_horizontal: bool)#0.3.2 부터since 0.3.2소스source

가로 진행 설정. (기본 세로)

  • 바뀌면 다음 tick 에 스크롤 영역을 다시 재고, 보이는 항목을 새 축에 다시 놓는다. (항목 크기를 읽기 전에 정한다, 스크롤 뷰의 축은 따로 정한다)

Sets horizontal progress. (vertical by default)

  • When changed, the scroll area is remeasured on the next tick and visible items are placed again on the new axis. (set it before item sizes are read, the scroll view's axis is set separately)
is_horizontalbool
true 면 항목을 x 축으로 늘어놓는다.If true, lays the items out along the x axis.

짝Counterpart: vanilla.js UIListView.setHorizontal

메서드methodpub fn set_buffer_item_count(&mut self, buffer_item_count: usize)#0.3.2 부터since 0.3.2소스source

화면 밖 여유 항목 수 설정.

Sets the off-screen buffer item count.

buffer_item_countusize
보이는 범위 앞뒤로 더 만들어 둘 항목 수. (기본 1)Number of extra items to create before and after the visible range. (default 1)

짝Counterpart: vanilla.js UIListView.setBufferItemCount

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

항목 수 반환.

Returns the item count.

반환Returnsusize 전체 항목 수.Total item count.

짝Counterpart: vanilla.js UIListView.getItemCount

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

항목 크기 반환.

Returns the item size.

반환Returnsf64 항목 하나의 진행 축 길이. (픽셀, 아직 읽지 않았으면 0)Length of one item along the progress axis. (pixels, 0 if not read yet)

짝Counterpart: vanilla.js UIListView.getItemSize

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

항목 사이 간격 반환.

Returns the spacing between items.

반환Returnsf64 항목 사이 간격. (픽셀)Spacing between items. (pixels)

짝Counterpart: vanilla.js UIListView.getSpacing

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

가로 진행 여부.

Whether progress is horizontal.

반환Returnsbool 가로로 늘어놓으면 true.true if laid out horizontally.

짝Counterpart: vanilla.js UIListView.isHorizontal

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

지금 만들어 둔(보이는) 항목 수.

Number of items currently created (visible).

반환Returnsusize 지금 노드로 만들어 둔 항목 수. (보이는 범위와 여유 칸)Number of items currently created as nodes. (visible range and buffer slots)

짝Counterpart: vanilla.js UIListView.getActiveItemCount