# web/pane/nodepane (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/web/pane/nodepane/

엔진 노드 화면 분할 패널. (원본 web/pane.js 의 PaneStyle, Pane 을 데스크탑에서 노드로 짓는 판, 공통 형과 셈은 web/pane.rs)
- 원본의 DOM 요소 자리가 노드다. 컨테이너는 노드(get_container)이고, 내용은 node_tree.add_child 로 그 자식에 붙인다. (원본 appendChild)
  데스크탑에는 전역 document 가 없어 노드를 만들고 고치는 함수는 NodeTree 를 받는다. 길이 단위는 원본의 CSS 픽셀 자리인 노드 좌표다.
  ```text
    let main_pane = Pane::new(node_tree, PaneOptions { direction: PaneDirection::Horizontal, ..Default::default() });
    let left_pane = Pane::new(node_tree, PaneOptions { size: PaneSize::Fixed(240.0), min_size: 170.0, ..Default::default() });
    main_pane.add_pane(node_tree, &left_pane);
    let panel_id = PaneStyle::create(node_tree, "div", "panel", &PaneStyleOptions::default());
    node_tree.add_child(left_pane.get_container(), panel_id);
    main_pane.attach_to(node_tree, root_id);
  ```
- 컨테이너는 원본처럼 바탕을 COLOR_BACKGROUND 로 칠하고 넘치는 자식을 자른다. (overflow: hidden, Mask)
- 리사이저는 원본처럼 끌 수 있으면 두께 5, 아니면 1 의 선이고 COLOR_RESIZER 로, 올려 두거나 끄는 동안 COLOR_RESIZER_HOVER 로 칠한다.
  눌러 끌면 잡은 자리와 경계 사이 간격을 지켜 앞이나 뒤 자식의 고정 크기를 바꾸고 뿌리부터 다시 놓는다. 올려 두거나 끄는 동안 col-resize, row-resize 커서다.
- attach_to 한 뿌리 패널은 부모 노드 크기가 바뀌면 다시 놓는다. (원본 창 resize 리스너와 다음 프레임의 refresh)
- PaneStyle::create 는 원본 프리셋과 같은 모양의 노드를 짓는다. (PaneElement 컴포넌트)
  공통: 왼쪽 위에 놓고 부모 크기를 채운다(position absolute, 100%), 글꼴 13px sans-serif, 글 색 COLOR_TEXT.
  panel: 바탕 COLOR_PANEL, 안쪽 여백 10. toolbar: 바탕 COLOR_TOOLBAR, 아래 테두리 1px COLOR_BORDER, 가로로 가운데 모아 10 씩 띄운다(flex).
  button: 제 크기(position relative, auto), 안쪽 여백 6 16, 모서리 4, 굵은 글, 바탕 COLOR_RESIZER(accent 면 COLOR_ACCENT, warning 이면 COLOR_WARNING),
  올려 두면 밝기 1.2 배와 pointer 커서, 누르고 떼면 set_on_click 의 함수. input: 엔진 입력 필드(UIInputField), 바탕 COLOR_INPUT_BACKGROUND, 안쪽 여백 4.
  textarea: 바탕 COLOR_BACKGROUND, 글 #d4d4d4, 고정폭 14px, 안쪽 여백 15, 탭 크기 4 의 여러 줄 입력 필드. text: 제 크기, 굵은 글.
  relative 요소는 부모 안쪽 여백 안에서 놓는다. 블록 부모는 세로로 차례로(div 는 폭을 채우고 그 밖은 제 폭), flex 부모는 CSS Flexbox 처럼
  주축(flex-direction row, column)으로 기준 크기(flex-basis, 없으면 width 나 height, 그것도 auto 면 제 크기)를 놓고 남는 자리를 flex-grow 비로 나누거나
  모자라면 flex-shrink 와 기준 크기를 곱한 비로 줄인다. (min, max 에 걸린 항목은 묶고 다시 나눈다, 넘침이 visible 인 항목의 자동 최소는 제 크기)
  교차축은 align-items(기본 stretch, flex-start, center, flex-end), 주축 늘어놓기는 justify-content(flex-start, center, flex-end, space-between, space-around, space-evenly)와 gap(줄 사이, 칸 사이).
  flex-wrap(wrap, wrap-reverse)이면 CSS Flexbox 9.3 처럼 바깥 가정 주축 크기를 차례로 더하다 넘치는 항목에서 새 줄을 열고, 줄마다 늘고 줄이며,
  줄의 교차 크기는 항목 바깥 교차 크기의 가장 큰 값이고 align-content(기본 stretch 는 남는 자리를 줄마다 고루 더한다)로 줄을 늘어놓는다. wrap-reverse 는 교차축의 시작과 끝을 바꾼다.
  auto 크기 요소의 제 크기는 글과 자식(블록은 세로 합, 가로 flex 는 가로 합)에 안쪽 여백과 테두리를 더한 것이다.
- overflow(overflow-x, overflow-y)가 visible 이 아니면 넘친 자식을 자르고(모서리 border-radius), auto, scroll 이면 휠로 넘기고 썸을 끌어 넘긴다.
  원본 스크롤 상자처럼 그 쪽으로 더 넘길 수 없으면 휠을 부모에게 넘긴다. 썸은 scrollbar-color 의 썸 색(원본 에디터의 rgba(121, 121, 121, 0.4))이다.
- 원본과 다른 점:
  - 원본 요소에 addEventListener("click") 으로 다는 것은 PaneElement::set_on_click 이다.
  - options.style 과 PaneStyle::apply 가 읽는 CSS 는 프리셋과 원본 도구(파티클, 타임라인, UI 에디터)가 쓰는 것이다:
    position(absolute, relative), left, top, right, bottom, width, height, min-width, min-height, max-width, max-height(px, %, auto),
    display(flex, block, none), flex-direction, flex, flex-grow, flex-shrink, flex-basis, justify-content, align-items, gap,
    padding, margin(1 ~ 4 값과 쪽마다), background, background-color, color, font-size, font-weight, font-family, line-height, text-align,
    border, border-top, border-right, border-bottom, border-left, border-width, border-color, border-radius, cursor(pointer),
    overflow, overflow-x, overflow-y, scrollbar-color, scrollbar-width, flex-wrap, flex-flow, align-content, row-gap, column-gap, white-space, text-overflow, opacity.
    opacity 는 크롬처럼 요소와 자손을 묶어 한 번에 얹는다. (노드 투명도와 투명도 층, WorldNode::set_opacity_layer)
    그 밖(user-select 같은 것)은 읽지 않는다. 글은 줄바꿈하지 않는다. (white-space: nowrap 과 text-overflow: ellipsis 에 overflow 가 visible 이 아니면 넘친 끝을 말줄임표로)
  - 스크롤 막대는 크롬처럼 운영체제를 따른다. 윈도우와 리눅스는 자리를 차지하는 Fluent 막대(두께 15, thin 10), 맥은 시스템 설정이 얹는 막대면 두께 8 의 얹는 썸,
    클래식이면 자리를 차지하는 막대(두께 15, thin 11)다. 자리를 차지하는 막대는 테두리 안, 안쪽 여백 밖에서 overflow: scroll 은 늘, auto 는 넘칠 때만 내용 폭을 던다.
    (web/pane.rs 의 read_classic_scrollbar_metrics, 단추 화살표는 그리지 않고 길은 scrollbar-color 의 둘째 값이 있을 때만 칠한다)
  - textarea 태그는 엔진 여러 줄 입력 필드(UIInputField::set_multiline)가 글을 받는다. 원본 DOM textarea 처럼 줄을 넣고, 폭에 맞춰 나누고, 위아래로 옮기고, 넘치면 휠로 넘긴다.
    프리셋의 탭 크기 4 를 쓴다. 글자, 색, 안쪽 여백은 만들 때의 스타일을 받는다. (PaneStyle::apply 로 나중에 바꾼 글꼴은 필드에 옮기지 않는다)
  - canvas 태그는 원본에서 미리보기 엔진의 캔버스가 들어가는 자리다. 데스크탑은 미리보기 장면을 렌더 타겟에 그려 PaneElement::set_canvas_texture 로 넣으면
    그 요소의 안쪽 상자에 그 화면을 그린다. (상자 크기는 calculate_canvas_box_size, 기기 픽셀 비를 곱해 렌더 타겟 크기를 맞춘다) 넣지 않으면 바탕과 테두리만 그린다.

## PaneClickCallback (type)

단추를 누르고 떼면 부르는 함수. (원본 click 리스너)

```rust
pub type PaneClickCallback = Box<dyn FnMut(&mut ComponentContext)>
```

## Pane (struct) (Clone)

화면 분할 패널. (원본 Pane, clone 은 같은 패널을 가리킨다)

예제: 왼쪽 목록과 오른쪽 화면으로 나누어 뿌리 노드에 붙이고, 목록을 숨기기

```rust
use vanilla::{NodeTree, Pane, PaneOptions, PaneSize, Vector2};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
node_tree[root_id].set_content_size(Vector2::create(1000.0, 600.0));
let main_pane = Pane::new(&mut node_tree, PaneOptions::default());
let left_pane = Pane::new(&mut node_tree, PaneOptions { size: PaneSize::Fixed(240.0), min_size: 170.0, ..Default::default() });
let view_pane = Pane::new(&mut node_tree, PaneOptions { min_size: 200.0, ..Default::default() });
main_pane.add_pane(&mut node_tree, &left_pane);
main_pane.add_pane(&mut node_tree, &view_pane);
main_pane.attach_to(&mut node_tree, root_id);
assert_eq!(node_tree[left_pane.get_container()].get_content_size(), Vector2::create(240.0, 600.0));
assert_eq!(node_tree[view_pane.get_container()].get_local_position(), Vector2::create(245.0, 0.0));
left_pane.set_visible(&mut node_tree, false);
assert_eq!(node_tree[view_pane.get_container()].get_local_position(), Vector2::create(0.0, 0.0));
assert_eq!(node_tree[view_pane.get_container()].get_content_size(), Vector2::create(1000.0, 600.0));
```

- `pub fn new(node_tree: &mut NodeTree, options: PaneOptions) -> Pane` (constructor, since 0.4.0): 생성. (떨어진 컨테이너 노드를 만든다. 바탕과 자르기)
  - `node_tree` &mut NodeTree: 컨테이너 노드를 만들 트리.
  - `options` PaneOptions: 패널 옵션.
  - returns Pane: 새 패널. (컨테이너 노드는 아직 어디에도 붙지 않았다, attach_to 나 부모의 add_pane 으로 붙인다)
- `pub fn add_pane(&self, node_tree: &mut NodeTree, pane: &Pane)` (method, since 0.4.0): 자식 추가. (앞 자식이 있으면 그 사이에 리사이저 노드를 둔다)
  - `node_tree` &mut NodeTree: 노드 트리.
  - `pane` &Pane: 붙일 자식 패널. (그 컨테이너 노드가 이 패널 컨테이너의 자식이 된다)
- `pub fn update_layout(&self, node_tree: &mut NodeTree, x: f64, y: f64, width: f64, height: f64)` (method, since 0.4.0): 배치. (자기 자리를 놓고, 같은 셈으로 자식과 리사이저를 놓는다. 원본 updateLayout)
  - `node_tree` &mut NodeTree: 노드 트리.
  - `x` f64: 컨테이너 왼쪽. (부모 노드 좌표)
  - `y` f64: 컨테이너 위. (부모 노드 좌표)
  - `width` f64: 컨테이너 폭.
  - `height` f64: 컨테이너 높이.
- `pub fn reset_layout(&self)` (method, since 0.4.0): 배치 초기화. (끌어서 바꾼 크기를 지운다, 자식까지)
- `pub fn refresh(&self, node_tree: &mut NodeTree)` (method, since 0.4.0): 부모 노드 크기에 맞춰 다시 놓는다. (부모가 없으면 아무것도 하지 않는다)
  - `node_tree` &mut NodeTree: 노드 트리.
- `pub fn attach_to(&self, node_tree: &mut NodeTree, parent_id: NodeId)` (method, since 0.4.0): 노드에 단다. (그 자리에서 놓고, 뒤로 부모 크기가 바뀌면 다시 놓는다. 원본 attachTo 의 창 resize 리스너)
  - `node_tree` &mut NodeTree: 노드 트리.
  - `parent_id` NodeId: 붙일 부모 노드.
- `pub fn set_visible(&self, node_tree: &mut NodeTree, is_visible: bool)` (method, since 0.4.0): 보이기 / 숨기기. (숨긴 패널은 자리를 차지하지 않고, 맞닿은 리사이저도 숨는다)
  - `node_tree` &mut NodeTree: 노드 트리.
  - `is_visible` bool: 보일지.
- `pub fn is_visible(&self) -> bool` (method, since 0.4.0): 보이는지.
  - returns bool: 보이면 true.
- `pub fn is_flex(&self) -> bool` (method, since 0.4.0): flex 인지. (처음 크기가 Flex)
  - returns bool: 처음 크기가 Flex 면 true.
- `pub fn get_initial_size(&self) -> PaneSize` (method, since 0.4.0): 처음 크기.
  - returns PaneSize: 만들 때 받은 처음 크기. (PaneOptions::size)
- `pub fn get_fixed_size(&self) -> f64` (method, since 0.4.0): 고정 크기. (픽셀, 0 이면 처음 크기로 잰다)
  - returns f64: 고정 크기. (픽셀, 끌어서 정했거나 처음 크기가 Fixed 면 그 값, reset_layout 뒤나 그 밖은 0)
- `pub fn set_fixed_size(&self, fixed_size: f64)` (method, since 0.4.0): 고정 크기 설정. (다음 배치부터 쓴다. flex 패널에는 쓰이지 않는다)
  - `fixed_size` f64: 새 고정 크기. (픽셀, 0 이면 처음 크기로 잰다)
- `pub fn get_min_size(&self) -> f64` (method, since 0.4.0): 최소 크기.
  - returns f64: 가장 작은 크기. (픽셀)
- `pub fn get_max_size(&self) -> f64` (method, since 0.4.0): 최대 크기.
  - returns f64: 가장 큰 크기. (픽셀)
- `pub fn get_container(&self) -> NodeId` (method, since 0.4.0): 컨테이너 노드. (내용을 여기의 자식으로 붙인다)
  - returns NodeId: 컨테이너 노드.
- `pub fn set_callback(&self, resize_callback: Option<PaneResizeCallback>)` (method, since 0.4.0): 배치 콜백 설정. (update_layout 이 끝날 때마다 부른다. None 이면 비운다)
  - `resize_callback` Option<PaneResizeCallback>: update_layout 이 끝날 때마다 부를 함수. (None 이면 비운다)
- `pub fn is_resizable(&self) -> bool` (method, since 0.4.0): 리사이저로 끌 수 있는지.
  - returns bool: 리사이저로 끌 수 있으면 true.
- `pub fn get_resizable_edges(&self) -> PaneResizableEdges` (method, since 0.4.0): 끌 수 있는 가장자리.
  - returns PaneResizableEdges: 끌 수 있는 가장자리.

## PaneElement (struct) (Component)

PaneStyle 이 지은 요소. (원본 DOM 요소의 스타일과 글, 블록과 flex 배치, 넘침 자르기와 스크롤, 단추 누르기)

예제: 패널 안의 단추를 누르고 떼면 함수 부르기

```rust
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, NodeTree, PaneElement, PaneStyle, PaneStyleOptions, TouchKind, 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(400.0, 300.0));
let panel_id = PaneStyle::create(&mut node_tree, "div", "panel", &PaneStyleOptions::default());
let button_id = PaneStyle::create(&mut node_tree, "button", "button", &PaneStyleOptions { text: "Save", ..Default::default() });
node_tree.add_child(root_id, panel_id);
node_tree.add_child(panel_id, button_id);
let click_count = Rc::new(Cell::new(0));
let click_count_for_callback = click_count.clone();
let button = node_tree[button_id].get_component_mut::<PaneElement>().unwrap();
assert_eq!(button.get_tag_name(), "button");
assert_eq!(button.get_text(), "Save");
button.set_on_click(Some(Box::new(move |_context| {
	click_count_for_callback.set(click_count_for_callback.get() + 1);
})));
node_tree.tick(&engine, 1.0 / 60.0);
node_tree.tick(&engine, 1.0 / 60.0);
assert_eq!(node_tree[button_id].get_local_position(), Vector2::create(10.0, 10.0));
let button_size = node_tree[button_id].get_content_size();
let button_center = Vector2::create(10.0 + button_size.x * 0.5, 10.0 + button_size.y * 0.5);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, button_center);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, button_center);
assert_eq!(click_count.get(), 1);
```

- `pub fn set_canvas_texture(&mut self, canvas_texture: Option<GlTexture>)` (method, since 0.4.0): canvas 태그가 그릴 화면 넣기. (원본 도구가 canvas 요소에 미리보기 엔진을 돌리는 자리, 데스크탑은 미리보기 장면을 그린 렌더 타겟의 색 텍스처를 넣는다)
  - canvas 태그 요소는 바탕과 테두리 위, 안쪽 여백과 테두리 안의 상자에 이 텍스처를 늘여 그린다. 렌더 타겟 텍스처처럼 아래가 0 행인 텍스처로 본다.
  - 렌더 타겟 크기는 원본 캔버스처럼 그 상자 크기에 기기 픽셀 비를 곱해 맞추면 1:1 로 그려진다. (calculate_canvas_box_size)
  - `canvas_texture` Option<GlTexture>: 그릴 색 텍스처. (None 이면 바탕과 테두리만 그린다)

  예제: 미리보기를 그린 렌더 타겟을 Pane 의 canvas 요소에 넣기

  ```rust
  use vanilla::{NodeId, NodeTree, PaneElement, RenderTarget};
  
  fn show_preview(node_tree: &mut NodeTree, canvas_id: NodeId, render_target: &RenderTarget) {
  	if let Some(element) = node_tree[canvas_id].get_component_mut::<PaneElement>() {
  		element.set_canvas_texture(render_target.get_color_texture(0));
  	}
  }
  ```

- `pub fn get_canvas_texture(&self) -> Option<GlTexture>` (method, since 0.4.0): canvas 태그가 그릴 화면.
  - returns Option<GlTexture>: set_canvas_texture 로 넣은 색 텍스처. (없으면 None)
- `pub fn calculate_canvas_box_size(&self, content_size: Vector2) -> Vector2` (method, since 0.4.0): canvas 태그가 화면을 그릴 상자 크기. (내용 크기에서 안쪽 여백과 테두리를 뺀 것, 노드 좌표이고 원본 canvas 요소의 clientWidth, clientHeight 자리)
  - `content_size` Vector2: 요소 노드의 내용 크기. (node_tree[노드].get_content_size())
  - returns Vector2: 그릴 상자의 가로, 세로. (기기 픽셀 비를 곱하면 렌더 타겟 크기)
- `pub fn set_on_click(&mut self, click_callback: Option<PaneClickCallback>)` (method, since 0.4.0): 누르고 떼면 부를 함수. (원본 요소의 addEventListener("click"))
  - `click_callback` Option<PaneClickCallback>: 누르고 떼면 부를 함수. (button 프리셋 요소만 부른다, None 이면 비운다)
- `pub fn set_text(&mut self, text: &str)` (method, since 0.4.0): 글 설정. (원본 innerText)
  - `text` &str: 보일 글.
- `pub fn get_text(&self) -> &str` (method, since 0.4.0): 글.
  - returns &str: 보이는 글. (textarea 의 글은 입력 필드가 들어 여기는 비어 있다)
- `pub fn get_tag_name(&self) -> &str` (method, since 0.4.0): 태그 이름. (소문자)
  - returns &str: 소문자 태그 이름.
- `pub fn get_scroll_offset(&self) -> Vector2` (method, since 0.4.0): 굴려 넘긴 만큼. (원본 scrollLeft, scrollTop)
  - returns Vector2: 굴려 넘긴 만큼. (x 가 scrollLeft, y 가 scrollTop)
- `pub fn set_scroll_offset(&mut self, scroll_offset: Vector2)` (method, since 0.4.0): 굴려 넘기기. (원본 scrollLeft, scrollTop 넣기. 다음 배치에서 내용 끝 안으로 줄인다)
  - `scroll_offset` Vector2: 굴려 넘길 만큼. (음수는 0 으로)
- `pub fn apply_style(&mut self, property_name: &str, property_value: &str)` (method, since 0.4.0): CSS 속성 하나 넣기. (머리 주석의 속성만 읽는다, 그 밖은 무시)
  - `property_name` &str: CSS 속성 이름. (background-color 같은 이름)
  - `property_value` &str: 값. (앞뒤 빈칸은 뗀다)

## PaneStyle (struct)

스타일 및 요소 생성 유틸리티. (원본 PaneStyle)

예제: 도구 막대에 단추를 놓고 스타일을 나중에 바꾸기

```rust
use vanilla::{Engine, EngineConfiguration, NodeTree, PaneStyle, PaneStyleOptions, 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(600.0, 40.0));
let toolbar_id = PaneStyle::create(&mut node_tree, "div", "toolbar", &PaneStyleOptions::default());
let play_button_id = PaneStyle::create(&mut node_tree, "button", "button", &PaneStyleOptions { text: "Play", accent: true, ..Default::default() });
node_tree.add_child(root_id, toolbar_id);
node_tree.add_child(toolbar_id, play_button_id);
PaneStyle::apply(&mut node_tree, toolbar_id, &[("justify-content", "flex-start"), ("padding", "0 8px")]);
node_tree.tick(&engine, 1.0 / 60.0);
node_tree.tick(&engine, 1.0 / 60.0);
assert_eq!(node_tree[toolbar_id].get_content_size(), Vector2::create(600.0, 40.0));
assert_eq!(node_tree[play_button_id].get_local_position().x, 8.0);
```

- `pub fn apply(node_tree: &mut NodeTree, node_id: NodeId, styles: &[(&str, &str)])` (static, since 0.4.0): 요소에 여러 스타일을 한꺼번에 넣는다. ((CSS 속성 이름, 값) 목록, PaneElement 가 없는 노드면 아무것도 하지 않는다)
  - `node_tree` &mut NodeTree: 노드 트리.
  - `node_id` NodeId: 스타일을 넣을 요소 노드.
  - `styles` &[(&str, &str)]: (CSS 속성 이름, 값) 목록.
- `pub fn create(node_tree: &mut NodeTree, tag_name: &str, preset: &str, options: &PaneStyleOptions) -> NodeId` (static, since 0.4.0): 스타일 프리셋을 넣은 요소 노드를 만든다. (떨어진 노드, node_tree.add_child 로 붙인다)
  (preset: "panel" | "toolbar" | "button" | "input" | "textarea" | "text", 그 밖은 공통 스타일만)
  - `node_tree` &mut NodeTree: 노드를 만들 트리.
  - `tag_name` &str: 태그 이름. (input 과 textarea 는 엔진 입력 필드가 글을 받는다)
  - `preset` &str: 스타일 프리셋. ("panel" | "toolbar" | "button" | "input" | "textarea" | "text")
  - `options` &PaneStyleOptions: id, 글, 덧붙이는 스타일, 안내 글, 단추 색.
  - returns NodeId: 만든 요소 노드. (떨어진 노드)
