# ui/uidocument (vanilla-engine 0.4.0)

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

UI document. (UIDocument of vanilla.js ui/uidocument.js)
- Exports and reads a node tree as a JSON document (.scene.json). The vanilla.js visual editor (tools/visualeditor) saves scenes in this form, and
  games read the same file and build nodes and components in a NodeTree. Trees built in Rust are exported in the same form too.
- A document is { "version": 1, "root": node }, and a node has type, name, active, position, scale, rotation, opacity, pivot, anchor,
  contentSize, interactable, components, children. If there is a widget (a component that creates a content node), only the children inside content are kept separately as contentChildren.
  Unknown keys added by the editor, like frameSize, are ignored. Key order and indentation (tabs) are written the same as the original JSON.stringify. (serde_json preserve_order)
- Differences from the original:
  - The original is a static class and module global tables. The Rust version creates and uses a UIDocument value that holds the tables. (no global state, like the engine) new registers the engine components.
  - As in the original, types without write and read functions (propertyHandler of the original COMPONENT_PROPERTY_TABLE) are written and read through reflection. (saveByReflection, loadByReflection)
    The original scans an object's get, is, set functions at run time, while the Rust version uses the list built at compile time by the `#[reflect]` macro. (core/reflection.rs)
    The only types handled through reflection are components with `#[reflect]` attached. (attached to every engine component) In the original, every object is reflected.
    Outline, SoftShade, ShadowText, UIProgressRing, which the original table saves through reflection, are also written and read through reflection. Same keys as the original reflection result (capitalized: Color, LineWidth,
    GizmoVisible, Enable, ComponentType, etc.) and order. FontFace of the original ShadowText is a font object, so it is not written. The Rust version's font name text (get_font_family)
    is kept in the property list but left out of saving with `#[reflect(unsaved)]`.
  - Reflection setters that take the tree (like SnapCurrentIndex of UISnapScrollView) are also called on the spot while reading, as in the original. The component being read is briefly taken out of the tree and the read context is handed the tree.
  - Components with &mut self getters are also read ahead through the &mut branch and written by to_json_text and serialize_node. (the original getters make no &self, &mut self distinction, so like the original toJsonText and serializeNode they are single functions. The tree is taken as mutable)
  - Type registration: register_component_type(name, builder function) is the original registerComponentType. (written and read through reflection) Types with their own write and read functions
    are registered with register_component_type_with_handler, and widgets (components that create a content node) with register_widget_type, register_widget_type_with_handler.
  - Unregistered types are skipped when reading (node types are read as WorldNode) with a warning, as in the original. When writing, type is the registered name as in the original, and unregistered types are written by reflection with the type name as type. (the original constructor.name)
    Like the original, every component is reflected. (Reflect is a supertrait of Component, so a component without `#[reflect]` does not compile)
  - Even for types with write and read functions, reflection properties that point to nodes are added and read separately as { "$nodeRef": path }, as in the original. (saveNodeReferences, loadNodeReferences)
  - ShadowImage is also added at the end of the original table in the same form (the reflection save form after imagePath), so both engines are the same.
  - The original UIImageView attaches a Sprite to the host on attach, so the document has a Sprite after UIImageView. The Rust version embeds the Sprite, so it writes the embedded Sprite there as a Sprite and
    when reading, it reads the following Sprite into the embedded Sprite. (set_component_companions, the original reads into the Sprite that UIImageView attached when it was attached)
  - Original node types (WorldNode subclasses, registerNodeType) are components attached to nodes in the Rust version. Registered with register_node_type, they are written and read in the same form as the original document:
    the type of a node with that component attached is that name, and it is not listed in the component list.
    - Types that actually build children and components on attach like the original node constructor (UIWindow, UIConfirmWindow, UIDialog, UIDropdown, UIToast, UISpinner, UIContextMenu, etc.)
      have what they built written as is.
    - For self-drawing types (UIInputField, UIScrollBar), UIDocumentNode writes the original constructor's share in the original form, and reads that share back as settings.
    - The original turns the node off when hiding, but for types that only hide because tick must keep running in the Rust version (UIToast), UIDocumentNode converts active to the original meaning when writing and reading.
  - When reading, components and children already on the node (built when a node type or widget was attached, or attached together through require) are matched from the front of the document by order and type (name for children), and if they match,
    the document values are put into them without building them again. (same as the original fillNode) Writing again gives the same document.
  - The original editor (tools/uieditor) registers every Component and WorldNode subclass the engine exports and writes them to documents. As in the original, they are not in the default table, and
    the game registers the same types (35 components, 12 node types) with one line, register_editor_types (the original registerEditorTypes). (one line per type also works)
  - Nodes in the Rust version are just WorldNode. The type of a node without a component registered as a node type is always written as "WorldNode", and unregistered types are read as WorldNode.
  - The original getComponentType (name → constructor) cannot return a constructor as a value (the node tree attaches by concrete type), so create_component(tree, node, name)
    builds the component of that name, attaches it to the node, and returns the component order index. (in place of taking a constructor and calling addComponent in the original)
  - The image path (imagePath) is resolved with the image resolver (set_image_resolver) as in the original. Without a resolver, it is looked up in the asset store the document holds.
    load_images requests the document's imagePath values as ImageAsset (the scene can hand over the received load handles with track_load_handle),
    and images not loaded yet are attached by bind_pending_images once fully loaded. (Rust assets finish loading some time after the request)
  - The base root of node references ($nodeRef) is the root of to_json_text, from_json_text. When serialize_node, deserialize_node are called directly, that node is the root.
    (in the original, calling only serializeNode does not write references, and calling only deserializeNode does not connect them)
  - Numbers are written as the shortest decimal of f64. (0.22 as 0.22, integers without a decimal point, the same as the original JSON.stringify)
- Sprite nineSlice is read by reversing the form the original writes ([left, top, left + right, top + bottom], Rect's left, top, right, bottom), as in the original.

## UIDocumentNodeParts (struct) (Default)

Document values of the components and children that the original node constructor creates. (placed at the front of that node's components and children)
- Returned by UIDocumentNode::save_node_parts, and UIDocument puts them as is at the head of the node's document value.

Example: Parts holding one thumb child and one Paint

```rust
use serde_json::{Map, Value};
use vanilla::ui::uidocument::UIDocumentNodeParts;

let mut node_parts = UIDocumentNodeParts::new();
let mut paint_data = Map::new();
paint_data.insert(String::from("roundSize"), Value::from(4));
paint_data.insert(String::from("type"), Value::from("Paint"));
node_parts.component_data_list.push(paint_data);
node_parts.child_data_list.push(serde_json::json!({ "type": "WorldNode", "name": "thumb" }));

assert_eq!(node_parts.component_data_list[0]["type"], "Paint");
assert_eq!(node_parts.child_data_list[0]["name"], "thumb");
```

- `pub component_data_list: Vec<Map<String, Value>>` (field, since 0.4.0): Component document values placed at the front of the node's components. (each value carries its own "type" key)
  - returns Vec<Map<String, Value>>
- `pub child_data_list: Vec<Value>` (field, since 0.4.0): Child node document values placed at the front of the node's children.
  - returns Vec<Value>
- `pub fn new() -> UIDocumentNodeParts` (constructor, since 0.4.0): Empty parts. (node kinds whose constructor creates nothing)
  - returns UIDocumentNodeParts: Parts with both lists empty.

## UIDocumentNode (trait)

A component that stands in for an original node kind (a WorldNode subclass). (registered with register_node_type)
- In the original, that node's constructor creates its components and children itself, and the document records them as ordinary components and children.
  The Rust version's component draws or holds them itself, so when writing it writes them in the form the original would, and when reading it reads those parts as settings and does not build it again.
- Kinds whose constructor creates nothing get an empty implementation (impl UIDocumentNode for Type {}).

Example: Standing in for a node kind whose original constructor attaches a Paint with a component that draws directly

```rust
use serde_json::{Map, Value};
use vanilla::{Color, Component, ComponentBase, NodeId, NodeTree, Paint, UIDocument, UIDocumentSaveContext};
use vanilla::ui::uidocument::{UIDocumentNode, UIDocumentNodeParts};

struct Badge {
	component_base: ComponentBase,
	color: Color,
}

#[vanilla::reflect]
impl Badge {}

#[vanilla::reflect]
impl Component for Badge {
	fn get_component_base(&self) -> &ComponentBase {
		&self.component_base
	}

	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
		&mut self.component_base
	}

	fn get_component_type(&self) -> &'static str {
		"Badge"
	}
}

impl UIDocumentNode for Badge {
	fn save_node_parts(&self, _save_context: &UIDocumentSaveContext, _node_id: NodeId) -> UIDocumentNodeParts {
		let mut paint_data = Map::new();
		paint_data.insert(String::from("color"), UIDocument::color_to_array(self.color));
		paint_data.insert(String::from("type"), Value::from("Paint"));
		let mut node_parts = UIDocumentNodeParts::new();
		node_parts.component_data_list.push(paint_data);
		node_parts
	}

	fn load_node_parts(&mut self, component_data_list: &[Value], _child_data_list: &[Value]) -> (usize, usize) {
		match component_data_list.first().and_then(|component_data| UIDocument::array_to_color(&component_data["color"])) {
			Some(color) => {
				self.color = color;
				(1, 0)
			}
			None => {
				(0, 0)
			}
		}
	}
}

fn create_badge() -> Badge {
	Badge {
		component_base: ComponentBase::new(),
		color: Color::create(1.0, 1.0, 1.0, 1.0),
	}
}

let mut document = UIDocument::new();
document.register_node_type("Badge", create_badge);
let mut node_tree = NodeTree::new();
let badge_id = node_tree.create_node("badge");
node_tree[badge_id].add_component(create_badge()).color = Color::create(1.0, 0.0, 0.0, 1.0);

let json_text = document.to_json_text(&mut node_tree, badge_id, false);
let document_data: Value = serde_json::from_str(&json_text).expect("json");
assert_eq!(document_data["root"]["type"], "Badge");
assert_eq!(document_data["root"]["components"][0]["type"], "Paint");

let loaded_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
assert_eq!(node_tree[loaded_id].get_component::<Badge>().expect("badge").color, Color::create(1.0, 0.0, 0.0, 1.0));
assert!(node_tree[loaded_id].get_component::<Paint>().is_none());
```

- `fn save_node_parts(&self, _save_context: &UIDocumentSaveContext, _node_id: NodeId) -> UIDocumentNodeParts` (method, since 0.4.0): The components and children that the original node constructor creates, in document form. (node_id is the node this component is attached to)
  - `_save_context` &UIDocumentSaveContext: Write context. (the base of node reference paths when writing the parts' component values)
  - `_node_id` NodeId: The node this component is attached to.
  - returns UIDocumentNodeParts: Document values of the components and children the original constructor would have created. (default is empty parts)
- `fn load_node_parts(&mut self, _component_data_list: &[Value], _child_data_list: &[Value]) -> (usize, usize)` (method, since 0.4.0): Reads in the parts that the original node constructor created from the head of the document's component and child lists. (the number of components and children read, those parts are not built)
  - `_component_data_list` &[Value]: All components of the document node.
  - `_child_data_list` &[Value]: All children of the document node.
  - returns (usize, usize): (number of components read from the front, number of children read). UIDocument skips building that many. (default (0, 0))
- `fn get_document_content(&self) -> Option<NodeId>` (method, since 0.4.0): A content node not written to the document. (something the Rust version creates like a widget, not in the original node. Its children are written as contentChildren)
  - returns Option<NodeId>: The content node not to write to the document. None if none. (default None)
- `fn read_document_active(&self, is_node_active: bool, _is_node_visible: bool) -> bool` (method, since 0.4.0): The original node's active. (the original turns the node off when hiding, and some kinds in the Rust version hide instead of turning off because tick has to run. Default is the node's active)
  - `is_node_active` bool: The node's active.
  - `_is_node_visible` bool: The node's visibility.
  - returns bool: The active to write to the document.
- `fn convert_document_active(&self, is_active: bool) -> (bool, Option<bool>)` (method, since 0.4.0): The original active as this kind's node state. (the node's active and the visibility to change, default is unchanged and visibility is left alone)
  - `is_active` bool: The active written in the document.
  - returns (bool, Option<bool>): (active to set on the node, visibility to set on the node). If visibility is None, visibility is not changed. (default (is_active, None))

## UIDocumentSaveContext (struct)

Write context. (received by component write functions. Writes node references as paths from the root)
- Not built from outside. Received by write functions registered with register_component_type_with_handler and by UIDocumentNode::save_node_parts.

Example: Writing a node reference as a path in a write function

```rust
use serde_json::{Map, Value};
use vanilla::{Component, ComponentBase, NodeId, NodeTree, UIDocument, UIDocumentLoadContext, UIDocumentSaveContext};

struct Follow {
	component_base: ComponentBase,
	target: Option<NodeId>,
}

#[vanilla::reflect]
impl Follow {}

#[vanilla::reflect]
impl Component for Follow {
	fn get_component_base(&self) -> &ComponentBase {
		&self.component_base
	}

	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
		&mut self.component_base
	}

	fn get_component_type(&self) -> &'static str {
		"Follow"
	}
}

fn create_follow() -> Follow {
	Follow {
		component_base: ComponentBase::new(),
		target: None,
	}
}

fn save_follow(follow: &Follow, save_context: &UIDocumentSaveContext) -> Map<String, Value> {
	let mut component_data = Map::new();
	save_context.write_node_reference(&mut component_data, "target", follow.target);
	component_data
}

fn load_follow(_follow: &mut Follow, _component_data: &Map<String, Value>, _load_context: &mut UIDocumentLoadContext) {
}

let mut document = UIDocument::new();
document.register_component_type_with_handler("Follow", create_follow, save_follow, load_follow);
let mut node_tree = NodeTree::new();
let root_id = node_tree.create_node("root");
let leader_id = node_tree.create_child(root_id, "leader");
let follower_id = node_tree.create_child(root_id, "follower");
node_tree[follower_id].add_component(create_follow()).target = Some(leader_id);

let json_text = document.to_json_text(&mut node_tree, root_id, false);
let document_data: Value = serde_json::from_str(&json_text).expect("json");
let component_data = &document_data["root"]["children"][1]["components"][0];
assert_eq!(component_data["target"]["$nodeRef"], "/leader");
assert_eq!(component_data["type"], "Follow");
```

- `pub fn get_node_tree(&self) -> &NodeTree` (method, since 0.4.0): Node tree.
  - returns &NodeTree: The node tree being written.
- `pub fn get_node_id(&self) -> NodeId` (method, since 0.4.0): The node being written.
  - returns NodeId: The node being written. (root_id when called via serialize_component)
- `pub fn write_node_reference(&self, component_data: &mut Map<String, Value>, property_name: &str, node_id: Option<NodeId>)` (method, since 0.4.0): Writes a node reference. ({ "$nodeRef": path from the root }, not written if None or a node outside the root. Original saveNodeReferences)
  - `component_data` &mut Map<String, Value>: Component document value to put the value into.
  - `property_name` &str: Key to put.
  - `node_id` Option<NodeId>: Node to point to. If None or outside the root, the key is not put.
- `pub fn write_image_path(&self, component_data: &mut Map<String, Value>, image_path: &str, image: Option<&Rc<Image>>)` (method, since 0.4.0): Writes an image path. (writes the path to "imagePath", and when the path is not empty and there is an image, remembers that image by path. The original serializeNode #rememberSerializedImage)
  - A remembered image is put in when the same document reads it back and the resolver or load_images does not find one. (a copy written and read with the same document, as UIListView::set_template_node does, uses the original's image)
  - `component_data` &mut Map<String, Value>: Component document value to put the value into.
  - `image_path` &str: Image path. (an empty string is also written)
  - `image` Option<&Rc<Image>>: Image in the component. (not remembered if None)

## UIDocumentLoadContext (struct)

Read context. (received by component read functions. Images and node references are left here and put in after the whole tree is built)
- Not built from outside. Received by read functions registered with register_component_type_with_handler.

Example: Leaving a node reference in a read function and wiring it after the whole tree is built

```rust
use serde_json::{Map, Value};
use vanilla::{Component, ComponentBase, NodeId, NodeTree, UIDocument, UIDocumentLoadContext, UIDocumentSaveContext};

struct Follow {
	component_base: ComponentBase,
	target: Option<NodeId>,
}

#[vanilla::reflect]
impl Follow {}

#[vanilla::reflect]
impl Component for Follow {
	fn get_component_base(&self) -> &ComponentBase {
		&self.component_base
	}

	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
		&mut self.component_base
	}

	fn get_component_type(&self) -> &'static str {
		"Follow"
	}
}

fn create_follow() -> Follow {
	Follow {
		component_base: ComponentBase::new(),
		target: None,
	}
}

fn save_follow(follow: &Follow, save_context: &UIDocumentSaveContext) -> Map<String, Value> {
	let mut component_data = Map::new();
	save_context.write_node_reference(&mut component_data, "target", follow.target);
	component_data
}

fn load_follow(_follow: &mut Follow, component_data: &Map<String, Value>, load_context: &mut UIDocumentLoadContext) {
	load_context.bind_node_reference(component_data.get("target"), |follow: &mut Follow, node_id: NodeId| {
		follow.target = Some(node_id);
	});
}

let mut document = UIDocument::new();
document.register_component_type_with_handler("Follow", create_follow, save_follow, load_follow);
let json_text = r#"{"version":1,"root":{"name":"root","children":[
	{"name":"leader"},
	{"name":"follower","components":[{"target":{"$nodeRef":"/leader"},"type":"Follow"}]}
]}}"#;
let mut node_tree = NodeTree::new();
let root_id = document.from_json_text(&mut node_tree, json_text).expect("document");

let leader_id = node_tree.find_child_by_name(root_id, "leader").expect("leader");
let follower_id = node_tree.find_child_by_name(root_id, "follower").expect("follower");
assert_eq!(node_tree[follower_id].get_component::<Follow>().expect("follow").target, Some(leader_id));
```

- `pub fn get_node_tree_mut(&mut self) -> &mut NodeTree` (method, since 0.4.0): Node tree. (the component being read is temporarily taken out of the tree. An empty placeholder sits in its place)
  - returns &mut NodeTree: Mutable reference to the node tree. (the component being read cannot be found with get_component)
- `pub fn get_node_id(&self) -> NodeId` (method, since 0.4.0): The node being built.
  - returns NodeId: The node the component being read is attached to.
- `pub fn bind_image<T: Component + 'static>(&mut self, image_path: &str, read_image_path: fn(&T) -> &str, read_image: fn(&T) -> Option<&Rc<Image>>, apply_image: fn(&mut T, Rc<Image>))` (method, since 0.4.0): Leaves an image. (when the image at the path is found, puts it into this component with apply_image. Original UIDocument.resolveImage + setImage)
  - Images that can be found now are put in once the whole tree is built, and images still loading are put in by bind_pending_images.
  - Before putting it in, checks that slot with read_image_path and read_image. If the game set an image or changed the path in the meantime, it is dropped without being put in. (original bindPendingImages)
  - `image_path` &str: Image path. (not left if an empty string)
  - `read_image_path` fn(&T) -> &str: Function that reads the component's current image path. (for example Sprite::get_image_path)
  - `read_image` fn(&T) -> Option<&Rc<Image>>: Function that reads the component's current image. (for example Sprite::get_image)
  - `apply_image` fn(&mut T, Rc<Image>): Function that puts the found image into the component. (not called if the component in that slot is not T)
- `pub fn bind_node_reference<T: Component + 'static>(&mut self, stored_value: Option<&Value>, apply_node: fn(&mut T, NodeId))` (method, since 0.4.0): Leaves a node reference. (if the value is { "$nodeRef": path }, puts that node in with apply_node after the whole tree is built. Original loadNodeReferences)
  - `stored_value` Option<&Value>: The document's value for that key. Not left if None or not in { "$nodeRef": path } form.
  - `apply_node` fn(&mut T, NodeId): Function that puts the found node into the component. (not called if the node at the path is not found or the component in that slot is not T)

## UIDocument (struct) (Default)

UI document. (WorldNode tree ↔ JSON conversion)
- Holds the kind tables (component kinds, node kinds) and the image lookup state. Writing takes &self, reading takes &mut self.

Example: Exporting a tree built in Rust as document text and reading it back

```rust
use vanilla::{Color, NodeTree, Paint, UIDocument, Vector2};

let mut node_tree = NodeTree::new();
let panel_id = node_tree.create_node("panel");
node_tree[panel_id].set_content_size(Vector2::create(320.0, 200.0));
node_tree[panel_id].add_component(Paint::new()).set_color(Color::create(0.2, 0.4, 0.8, 1.0));
node_tree.create_child(panel_id, "title");

let mut document = UIDocument::new();
let json_text = document.to_json_text(&mut node_tree, panel_id, true);
let loaded_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
assert_eq!(node_tree[loaded_id].get_content_size(), Vector2::create(320.0, 200.0));
assert_eq!(node_tree[loaded_id].get_component::<Paint>().expect("paint").get_color(), Color::create(0.2, 0.4, 0.8, 1.0));
assert!(node_tree.find_child_by_name(loaded_id, "title").is_some());
assert_eq!(document.to_json_text(&mut node_tree, loaded_id, true), json_text);
```

Example: Reading a scene file and attaching it to the scene root

```rust
use vanilla::{NodeTree, UIDocument};

let json_text = std::fs::read_to_string("examples/assets/scenedocument.scene.json").expect("scene file");
let mut node_tree = NodeTree::new();
let mut document = UIDocument::new();
let scene_root_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
let root_id = node_tree.get_root_id();
node_tree.add_child(root_id, scene_root_id);
assert_eq!(node_tree.get_parent_id(scene_root_id), Some(root_id));
assert!(node_tree.find_child_by_name(scene_root_id, "Panel").is_some());
```

- `pub fn new() -> UIDocument` (constructor, since 0.4.0): Constructor. (registers the engine components of the original table)
  - returns UIDocument: A new document with the engine components (Paint, Sprite, Text, RichText, Mask, Outline, SoftShade, ShadowText, UIProgressRing, UILabel, UIImageView, UIButton, UIToggleButton, UIProgressView, UISlider, UIScrollView, ShadowImage) registered. No node kinds and no image resolver.
- `pub fn register_editor_types(&mut self)` (method, since 0.4.0): Registers all the types the original editor registers. (the original registerEditorTypes, the original tools/uieditor/uieditor.js registers every Component the engine exports with registerComponentType and every WorldNode subclass with registerNodeType)
  - Registers in exported name order (abc) as in the original. Names already registered (the original default table) keep their write and read functions as in the original.
  - In the original too they are not in the default table, so the game must register them to read them. A game reading documents saved by the editor calls this once.
- `pub fn register_component_type<T: Component + 'static>(&mut self, type_name: &str, create_component: fn() -> T)` (method, since 0.4.0): Registers a component kind. (original registerComponentType, replaces on the same name)
  - Without write and read functions, it writes and reads by reflection as in the original. (components with `#[reflect]`, or only the common Component properties if not)
  - Builds with create_component, attaches with node_tree.add_component, then puts in the document value. (attaches first, then reads, as in the original) When writing, "type" is added at the end of the value.
  - `type_name` &str: The document's "type" name. (replaces if the same name exists)
  - `create_component` fn() -> T: Function that builds the component when reading.

  Example: Writing and reading a game component with `#[vanilla::reflect]` through a one-line registration

  ```rust
  use vanilla::{Component, ComponentBase, NodeTree, UIDocument};
  
  struct Spin {
  	component_base: ComponentBase,
  	degrees_per_second: f64,
  }
  
  #[vanilla::reflect]
  impl Spin {
  	pub fn new() -> Spin {
  		Spin {
  			component_base: ComponentBase::new(),
  			degrees_per_second: 0.0,
  		}
  	}
  
  	pub fn set_degrees_per_second(&mut self, degrees_per_second: f64) {
  		self.degrees_per_second = degrees_per_second;
  	}
  
  	pub fn get_degrees_per_second(&self) -> f64 {
  		self.degrees_per_second
  	}
  }
  
  #[vanilla::reflect]
  impl Component for Spin {
  	fn get_component_base(&self) -> &ComponentBase {
  		&self.component_base
  	}
  
  	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
  		&mut self.component_base
  	}
  
  	fn get_component_type(&self) -> &'static str {
  		"Spin"
  	}
  }
  
  let mut document = UIDocument::new();
  document.register_component_type("Spin", Spin::new);
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.create_node("root");
  node_tree[root_id].add_component(Spin::new()).set_degrees_per_second(90.0);
  
  let json_text = document.to_json_text(&mut node_tree, root_id, false);
  assert!(json_text.contains("\"DegreesPerSecond\":90"));
  let loaded_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
  assert_eq!(node_tree[loaded_id].get_component::<Spin>().expect("spin").get_degrees_per_second(), 90.0);
  ```

- `pub fn register_component_type_with_handler<T: Component + 'static>(&mut self, type_name: &str, create_component: fn() -> T, save_component: fn(&T, &UIDocumentSaveContext) -> Map<String, Value>, load_component: fn(&mut T, &Map<String, Value>, &mut UIDocumentLoadContext))` (method, since 0.4.0): Registers a component kind with write and read functions. (one row of the original COMPONENT_TYPE_TABLE and COMPONENT_PROPERTY_TABLE, replaces on the same name)
  - Writes the value returned by save_component with "type" added at the end. Reflection properties pointing to nodes are added and read separately as in the original.
  - `type_name` &str: The document's "type" name. (replaces if the same name exists)
  - `create_component` fn() -> T: Function that builds the component when reading.
  - `save_component` fn(&T, &UIDocumentSaveContext) -> Map<String, Value>: Function that writes the component as a document value (key → value). ("type" is not included)
  - `load_component` fn(&mut T, &Map<String, Value>, &mut UIDocumentLoadContext): Function that reads the document value into the attached component. (images and node references are left to the read context)

  Example: A game component handled with write and read functions without reflection

  ```rust
  use serde_json::{Map, Value};
  use vanilla::{Component, ComponentBase, NodeTree, UIDocument, UIDocumentLoadContext, UIDocumentSaveContext};
  
  struct Spin {
  	component_base: ComponentBase,
  	degrees_per_second: f64,
  }
  
  #[vanilla::reflect]
  impl Spin {}
  
  #[vanilla::reflect]
  impl Component for Spin {
  	fn get_component_base(&self) -> &ComponentBase {
  		&self.component_base
  	}
  
  	fn get_component_base_mut(&mut self) -> &mut ComponentBase {
  		&mut self.component_base
  	}
  
  	fn get_component_type(&self) -> &'static str {
  		"Spin"
  	}
  }
  
  fn create_spin() -> Spin {
  	Spin {
  		component_base: ComponentBase::new(),
  		degrees_per_second: 0.0,
  	}
  }
  
  fn save_spin(spin: &Spin, _save_context: &UIDocumentSaveContext) -> Map<String, Value> {
  	let mut component_data = Map::new();
  	component_data.insert(String::from("degreesPerSecond"), UIDocument::number_to_value(spin.degrees_per_second));
  	component_data
  }
  
  fn load_spin(spin: &mut Spin, component_data: &Map<String, Value>, _load_context: &mut UIDocumentLoadContext) {
  	if let Some(degrees_per_second) = component_data.get("degreesPerSecond").and_then(|value| value.as_f64()) {
  		spin.degrees_per_second = degrees_per_second as f64;
  	}
  }
  
  let mut document = UIDocument::new();
  document.register_component_type_with_handler("Spin", create_spin, save_spin, load_spin);
  let json_text = r#"{"version":1,"root":{"name":"root","components":[{"degreesPerSecond":90,"type":"Spin"}]}}"#;
  let mut node_tree = NodeTree::new();
  let root_id = document.from_json_text(&mut node_tree, json_text).expect("document");
  assert_eq!(node_tree[root_id].get_component::<Spin>().expect("spin").degrees_per_second, 90.0);
  assert!(document.to_json_text(&mut node_tree, root_id, false).contains("{\"degreesPerSecond\":90,\"type\":\"Spin\"}"));
  ```

- `pub fn register_widget_type<T: Component + 'static>(&mut self, type_name: &str, create_component: fn() -> T, read_content: fn(&T) -> Option<NodeId>, generated_type_names: &[&str])` (method, since 0.4.0): Registers a widget kind. (the original UIView family, components that create a content node when attached. Written and read by reflection)
  - The content node returned by read_content is not written to the document, and only its children are written as contentChildren. When reading, they are attached to the content the widget recreated.
  - generated_type_names are the component kinds the widget attaches to its host by itself when attached. (original require, not written to the document)
  - `type_name` &str: The document's "type" name. (replaces if the same name exists)
  - `create_component` fn() -> T: Function that builds the widget when reading.
  - `read_content` fn(&T) -> Option<NodeId>: Function that returns the widget's content node.
  - `generated_type_names` &[&str]: Names of the component kinds the widget attaches to its host by itself when attached. (empty list if none, ["Mask"] for UIScrollView)

  Example: Registering UIView as a widget writes the children inside content as contentChildren

  ```rust
  use serde_json::Value;
  use vanilla::{NodeTree, UIDocument, UIView};
  
  let mut document = UIDocument::new();
  document.register_widget_type("UIView", UIView::new, UIView::get_content, &[]);
  let mut node_tree = NodeTree::new();
  let view_id = node_tree.create_node("view");
  let content_id = node_tree.add_component(view_id, UIView::new()).expect("view").get_content().expect("content");
  node_tree.create_child(content_id, "item");
  
  let json_text = document.to_json_text(&mut node_tree, view_id, false);
  let document_data: Value = serde_json::from_str(&json_text).expect("json");
  assert_eq!(document_data["root"]["children"], serde_json::json!([]));
  assert_eq!(document_data["root"]["contentChildren"][0]["name"], "item");
  
  let loaded_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
  let loaded_content_id = node_tree[loaded_id].get_component::<UIView>().expect("view").get_content().expect("content");
  assert!(node_tree.find_child_by_name(loaded_content_id, "item").is_some());
  ```

- `pub fn register_widget_type_with_handler<T: Component + 'static>(&mut self, type_name: &str, create_component: fn() -> T, save_component: fn(&T, &UIDocumentSaveContext) -> Map<String, Value>, load_component: fn(&mut T, &Map<String, Value>, &mut UIDocumentLoadContext), read_content: fn(&T) -> Option<NodeId>, generated_type_names: &[&str])` (method, since 0.4.0): Registers a widget kind with write and read functions.
  - Same as register_widget_type, but writes and reads with save_component and load_component instead of reflection.
  - `type_name` &str: The document's "type" name. (replaces if the same name exists)
  - `create_component` fn() -> T: Function that builds the widget when reading.
  - `save_component` fn(&T, &UIDocumentSaveContext) -> Map<String, Value>: Function that writes the widget as a document value. ("type" is not included)
  - `load_component` fn(&mut T, &Map<String, Value>, &mut UIDocumentLoadContext): Function that reads the document value into the attached widget.
  - `read_content` fn(&T) -> Option<NodeId>: Function that returns the widget's content node.
  - `generated_type_names` &[&str]: Names of the component kinds the widget attaches to its host by itself when attached.
- `pub fn register_node_type<T: Component + UIDocumentNode + 'static>(&mut self, type_name: &str, create_component: fn() -> T)` (method, since 0.4.0): Registers a node kind. (original registerNodeType, a Rust component standing in for an original WorldNode subclass, replaces on the same name)
  - A node with that component attached writes its type as this name and does not list that component among its components. When reading, it is attached right after the node is built (before the document's node values are put in).
    (the original builds the node with that kind's constructor and puts in the node values)
  - The components and children the original constructor creates are written and read by UIDocumentNode.
  - `type_name` &str: The document node's "type" name. (replaces if the same name exists)
  - `create_component` fn() -> T: Function that builds the component to attach right after the node is built when reading.

  Example: Writing and reading a UIScrollBar node in the original node form (track Paint, thumb child)

  ```rust
  use serde_json::Value;
  use vanilla::{NodeTree, UIDocument, UIScrollBar};
  
  let mut document = UIDocument::new();
  document.register_node_type("UIScrollBar", UIScrollBar::new);
  let mut node_tree = NodeTree::new();
  let scroll_bar_id = node_tree.create_node("scrollBar");
  node_tree.add_component(scroll_bar_id, UIScrollBar::new());
  
  let json_text = document.to_json_text(&mut node_tree, scroll_bar_id, false);
  let document_data: Value = serde_json::from_str(&json_text).expect("json");
  assert_eq!(document_data["root"]["type"], "UIScrollBar");
  assert_eq!(document_data["root"]["components"][0]["type"], "Paint");
  assert_eq!(document_data["root"]["children"][0]["name"], "thumb");
  
  let loaded_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
  assert!(node_tree[loaded_id].get_component::<UIScrollBar>().is_some());
  assert!(node_tree.get_child_ids(loaded_id).is_empty());
  ```

- `pub fn register_node_type_with_match<T: Component + UIDocumentNode + 'static>(&mut self, type_name: &str, create_component: fn() -> T, matches: fn(&T) -> bool)` (method, since 0.4.0): Registers a node kind. (when the component kind alone cannot tell, only those for which matches is true are this node kind. UIConfirmWindow is a UIWindow and is told apart by behavior)
  - Registrations with a telling function are matched before those without.
  - `type_name` &str: The document node's "type" name. (replaces if the same name exists)
  - `create_component` fn() -> T: Function that builds the component to attach right after the node is built when reading.
  - `matches` fn(&T) -> bool: Function that tells whether the component of that type attached to the node is this node kind.
- `pub fn get_node_type_name(&self, node: &WorldNode) -> &str` (method, since 0.4.0): Node type name. (in place of the original node.constructor.name, the same as the type written when saving)
  - The name of a registered node type (register_node_type; register_editor_types registers the engine types) if its component is on the node (the earlier one), otherwise "WorldNode".
  - `node` &WorldNode: Node to look at.
  - returns &str: Node type name.

  Example: A registered engine node type shows its name, a plain node shows WorldNode

  ```rust
  use vanilla::{FloatingText, UIDocument, WorldNode};
  
  let mut ui_document = UIDocument::new();
  ui_document.register_editor_types();
  let mut node = WorldNode::new("node");
  assert_eq!(ui_document.get_node_type_name(&node), "WorldNode");
  node.add_component(FloatingText::new());
  assert_eq!(ui_document.get_node_type_name(&node), "FloatingText");
  ```

- `pub fn get_component_type_names(&self) -> Vec<&str>` (method, since 0.4.0): List of supported component kind names. (original getComponentTypeNames, registration order)
  - returns Vec<&str>: Registered component kind names. (registration order, node kind names are not included)
- `pub fn create_component(&self, node_tree: &mut NodeTree, node_id: NodeId, type_name: &str) -> Option<usize>` (method, since 0.4.0): Builds a component by name and attaches it to the node. (where the original builds and attaches with the constructor from getComponentType, None if the name is not registered)
  - `node_tree` &mut NodeTree: Tree holding the node.
  - `node_id` NodeId: Node to attach the component to.
  - `type_name` &str: Registered component kind name.
  - returns Option<usize>: Index of the attached component. (within that node's component list) None if the name is not registered or the node does not exist.

  Example: Attaching a Paint by name

  ```rust
  use vanilla::{NodeTree, Paint, UIDocument};
  
  let document = UIDocument::new();
  let mut node_tree = NodeTree::new();
  let node_id = node_tree.create_node("node");
  assert_eq!(document.create_component(&mut node_tree, node_id, "Paint"), Some(0));
  assert!(node_tree[node_id].get_component::<Paint>().is_some());
  assert_eq!(document.create_component(&mut node_tree, node_id, "Unknown"), None);
  ```

- `pub fn set_image_resolver(&mut self, image_resolver: impl FnMut(&str) -> Option<Rc<Image>> + 'static)` (method, since 0.4.0): Registers an image path resolver. (original setImageResolver, path → image. When registered, images are looked up with it instead of the asset store)
  - `image_resolver` impl FnMut(&str) -> Option<Rc<Image>> + 'static: Function that takes an image path and returns the image. Returning None means that image was not found.

  Example: Putting in images held in advance by path

  ```rust
  use std::rc::Rc;
  use vanilla::{Image, NodeTree, Sprite, UIDocument};
  
  let star_image = Image::create_from_pixels(1, 1, vec![255, 255, 255, 255]);
  let resolved_image = star_image.clone();
  let mut document = UIDocument::new();
  document.set_image_resolver(move |image_path: &str| {
  	if image_path == "star.png" {
  		Some(resolved_image.clone())
  	}
  	else {
  		None
  	}
  });
  let json_text = r#"{"version":1,"root":{"name":"star","components":[{"imagePath":"star.png","type":"Sprite"}]}}"#;
  let mut node_tree = NodeTree::new();
  let star_id = document.from_json_text(&mut node_tree, json_text).expect("document");
  let sprite = node_tree[star_id].get_component::<Sprite>().expect("sprite");
  assert!(sprite.get_image().is_some_and(|image| Rc::ptr_eq(image, &star_image)));
  assert!(document.resolve_image("missing.png").is_none());
  ```

- `pub fn resolve_image(&mut self, image_path: &str) -> Option<Rc<Image>>` (method, since 0.4.0): Resolves an image path. (original resolveImage, None if not found or still loading)
  - `image_path` &str: Image path to look up.
  - returns Option<Rc<Image>>: The found image. None if the resolver returned None, or if there is no resolver and it was not requested with load_images, is still loading, or failed to load.
- `pub fn load_images(&mut self, engine: &Engine, json_text: &str) -> Vec<AssetLoadHandle>` (method, since 0.4.0): Requests loading the document's images. (requests an ImageAsset for each imagePath and holds it in the store. Paths already requested are skipped, and paths that failed to load are requested again)
  - Returns the load handles of newly requested assets. If a scene calls this in load, it can hand them to track_load_handle to make initialize wait.
  - On desktop they load on the spot, on the web later. Images of nodes built before loading are attached by bind_pending_images.
  - `engine` &Engine: Engine to load assets with. (on desktop, looked up in EngineConfiguration's asset_directory_paths)
  - `json_text` &str: Document text.
  - returns Vec<AssetLoadHandle>: List of load handles of newly requested assets. Empty list if not JSON or there are no new paths to request.

  Example: Loading the document's images from the asset folder and attaching them

  ```rust
  use std::path::PathBuf;
  use vanilla::{Engine, EngineConfiguration, NodeTree, Sprite, UIDocument};
  
  let mut engine_configuration = EngineConfiguration::new();
  engine_configuration.asset_directory_paths = vec![PathBuf::from("examples/assets")];
  let engine = Engine::new(engine_configuration);
  let json_text = r#"{"version":1,"root":{"name":"icons","components":[{"imagePath":"atlas/icons.png","type":"Sprite"}]}}"#;
  
  let mut document = UIDocument::new();
  let load_handle_list = document.load_images(&engine, json_text);
  assert_eq!(load_handle_list.len(), 1);
  let mut node_tree = NodeTree::new();
  let icons_id = document.from_json_text(&mut node_tree, json_text).expect("document");
  assert_eq!(document.bind_pending_images(&mut node_tree), 0);
  assert!(node_tree[icons_id].get_component::<Sprite>().expect("sprite").get_image().is_some());
  ```

- `pub fn bind_pending_images(&mut self, node_tree: &mut NodeTree) -> usize` (method, since 0.4.0): Attaches the held images. (puts in found images, keeps images still loading. Returns the remaining count)
  - from_json_text and deserialize_node call this once at the end. If images load later, as on the web, call it in the scene's tick until the remaining count becomes 0.
  - Images not found (resolver gave None, asset missing or failed) log a warning and are dropped. That component stays without an image as in the original.
  - A component whose image the game set (the image is not None) or whose path it changed in the meantime is left untouched and the image is dropped.
  - `node_tree` &mut NodeTree: Node tree to put the images into. (if the node they were left for has been removed, the image is dropped)
  - returns usize: Number of images remaining because they are still loading. (0 means all were attached or dropped)
- `pub fn serialize_node(&self, node_tree: &mut NodeTree, node_id: NodeId) -> Value` (method, since 0.4.0): Node tree → document data. (the original serializeNode, node references are written as paths relative to this node)
  - Also reads components with &mut self getters. (the original getters make no &self, &mut self distinction, so it is a single function. That is why the tree is taken as mutable)
  - When a component that writes an imagePath holds an image, remembers that image by path. Reading it back with the same document puts that image in without a resolver or load_images.
  - Warns when a node reference points to a node that has an earlier sibling with the same name. (paths are names only, so reading back links to the earlier sibling)
  - A hidden node (set_visible(false)) writes visible: false. (not written when visible; a node type that uses visibility as active writes only active)
  - `node_tree` &mut NodeTree: Tree holding the node. (taken as mutable to call &mut getters)
  - `node_id` NodeId: Node to write as a document value. (including descendants)
  - returns Value: Node document value. (node object without the "version" header) Value::Null if the node does not exist.

  Example: Building a copy by taking a node as a document value

  ```rust
  use vanilla::{NodeTree, UIDocument, Vector2};
  
  let mut node_tree = NodeTree::new();
  let card_id = node_tree.create_node("card");
  node_tree[card_id].set_content_size(Vector2::create(120.0, 80.0));
  node_tree.create_child(card_id, "icon");
  
  let mut document = UIDocument::new();
  let card_data = document.serialize_node(&mut node_tree, card_id);
  assert_eq!(card_data["name"], "card");
  let copy_id = document.deserialize_node(&mut node_tree, &card_data);
  assert_ne!(copy_id, card_id);
  assert_eq!(node_tree[copy_id].get_content_size(), Vector2::create(120.0, 80.0));
  assert!(node_tree.find_child_by_name(copy_id, "icon").is_some());
  assert_eq!(node_tree.get_parent_id(copy_id), None);
  ```

- `pub fn serialize_component(&self, node_tree: &NodeTree, root_id: NodeId, component: &dyn Component) -> Map<String, Value>` (method, since 0.4.0): One component to document data. ("type" is not added. A registered type uses its own form, an unregistered one uses reflection. Like the original, every component is reflected)
  - Node references are written as paths from root_id.
  - `node_tree` &NodeTree: Tree to look up node references in.
  - `root_id` NodeId: Base root of node reference paths.
  - `component` &dyn Component: Component to write.
  - returns Map<String, Value>: The component's document value. (no "type")

  Example: Document value of one Paint

  ```rust
  use vanilla::{NodeTree, Paint, UIDocument};
  
  let node_tree = NodeTree::new();
  let mut paint = Paint::new();
  paint.set_round_size(8.0);
  let document = UIDocument::new();
  let paint_data = document.serialize_component(&node_tree, node_tree.get_root_id(), &paint);
  assert_eq!(paint_data["roundSize"], 8);
  assert!(paint_data.get("type").is_none());
  ```

- `pub fn get_reflected_properties(component: &dyn Component) -> Vec<ReflectedProperty>` (static, since 0.4.0): List of the component's editable properties. (original getReflectedProperties, matching get or is and set pairs. Names pointing to other objects are excluded)
  - `component` &dyn Component: Component whose properties to view.
  - returns Vec<ReflectedProperty>: Reflected property list. (The order the reflection macro built, followed by the Component common properties GizmoVisible, Enable, ComponentType. A component without getters has only the common properties)
- `pub fn save_by_reflection(component: &dyn Component, save_context: &UIDocumentSaveContext) -> Map<String, Value>` (static, since 0.4.0): Saves a component through matching get / set properties. (original saveByReflection, holds only transferable values: number, bool, string, Color, Vector2, node)
  - `component` &dyn Component: Component to write.
  - `save_context` &UIDocumentSaveContext: Write context. (base of node reference paths)
  - returns Map<String, Value>: Property name (capitalized) → document value. (no "type", properties that are not saved and values that cannot be transferred are excluded)
- `pub fn load_by_reflection(component: &mut dyn Component, component_data: &Map<String, Value>, load_context: &mut UIDocumentLoadContext)` (static, since 0.4.0): Restores a component through matching get / set properties. (original loadByReflection, node references are wired after the whole tree is built)
  - The original decides by the form of the current value whether to accept it. The Rust version decides by the setter's form. (core/reflection.rs)
  - Setters that take the tree (like set_snap_current_index(tree, slot)) are also called on the spot with the read context's tree, as in the original.
  - `component` &mut dyn Component: Component to put the values into.
  - `component_data` &Map<String, Value>: Component document value. (property name keys)
  - `load_context` &mut UIDocumentLoadContext: Read context. (node references are left here)
- `pub fn collect_generated_component_types(&self, component_list: &[Box<dyn Component>]) -> HashSet<String>` (method, since 0.4.0): Collects the component kind names attached by widgets. (original collectGeneratedComponentTypes, the original require slot is the list given at registration)
  - `component_list` &[Box<dyn Component>]: The node's component list.
  - returns HashSet<String>: Set of component kind names that the registered widgets in the list attach by themselves.
- `pub fn deserialize_node(&mut self, node_tree: &mut NodeTree, node_data: &Value) -> NodeId` (method, since 0.4.0): Document data → node tree. (original deserializeNode, returns a node not attached to any parent)
  - Node references are wired as paths from this node, and images that can be found are put in.
  - `node_tree` &mut NodeTree: Tree to build the node in.
  - `node_data` &Value: Node document value. (serialize_node form, builds one empty node if not an object)
  - returns NodeId: The built node. (not attached to any parent)
- `pub fn to_json_text(&self, node_tree: &mut NodeTree, root_id: NodeId, is_pretty: bool) -> String` (method, since 0.4.0): Node tree → JSON text. (original toJsonText, indents with tabs if is_pretty)
  - Like serialize_node, also reads components with &mut self getters. (that is why the tree is taken as mutable)
  - `node_tree` &mut NodeTree: Tree holding the node. (taken as mutable to call &mut getters)
  - `root_id` NodeId: Root node of the document. (base for node reference paths)
  - `is_pretty` bool: If true, multiple lines indented with tabs, if false, one line.
  - returns String: Document text. ({ "version": 1, "root": node })
- `pub fn from_json_text(&mut self, node_tree: &mut NodeTree, json_text: &str) -> Result<NodeId, String>` (method, since 0.4.0): JSON text → node tree. (original fromJsonText, returns a root not attached to any parent. Attach it with add_child to show it in the scene)
  - `node_tree` &mut NodeTree: Tree to build the node in.
  - `json_text` &str: Document text.
  - returns Result<NodeId, String>: The built root node. Err(reason text) if not JSON or there is no "root" object.

  Example: An invalid document is Err

  ```rust
  use vanilla::{NodeTree, UIDocument};
  
  let mut node_tree = NodeTree::new();
  let mut document = UIDocument::new();
  assert!(document.from_json_text(&mut node_tree, "{\"version\":1}").is_err());
  assert!(document.from_json_text(&mut node_tree, "not json").is_err());
  let root_id = document.from_json_text(&mut node_tree, r#"{"version":1,"root":{"name":"panel"}}"#).expect("document");
  assert_eq!(node_tree[root_id].get_name(), "panel");
  ```

- `pub fn find_node_path(node_tree: &NodeTree, root_id: NodeId, node_id: NodeId) -> Option<String>` (static, since 0.4.0): Computes the absolute path from the root. (original findNodePath, "/" + names. None if the node is outside the root)
  - `node_tree` &NodeTree: Tree holding the node.
  - `root_id` NodeId: Base root of the path.
  - `node_id` NodeId: Node to compute the path for.
  - returns Option<String>: Name path starting with "/". (the root itself is "/") None if not a descendant of the root.

  Example: Computing a path and finding by path

  ```rust
  use vanilla::{NodeTree, UIDocument};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.create_node("root");
  let panel_id = node_tree.create_child(root_id, "panel");
  let button_id = node_tree.create_child(panel_id, "button");
  let outside_id = node_tree.create_node("outside");
  
  assert_eq!(UIDocument::find_node_path(&node_tree, root_id, button_id).as_deref(), Some("/panel/button"));
  assert_eq!(UIDocument::find_node_path(&node_tree, root_id, root_id).as_deref(), Some("/"));
  assert_eq!(UIDocument::find_node_path(&node_tree, root_id, outside_id), None);
  assert_eq!(UIDocument::find_node_by_path(&node_tree, root_id, "/panel/button"), Some(button_id));
  assert_eq!(UIDocument::find_node_by_path(&node_tree, root_id, "/panel/missing"), None);
  ```

- `pub fn find_node_by_path(node_tree: &NodeTree, root_id: NodeId, path_text: &str) -> Option<NodeId>` (static, since 0.4.0): Finds a node by its absolute path from the root. (original findNodeByPath, the earlier child on the same name)
  - `node_tree` &NodeTree: Tree holding the node.
  - `root_id` NodeId: Base root of the path.
  - `path_text` &str: Path in "/name/name" form. (the leading "/" is optional. The root if an empty string or "/")
  - returns Option<NodeId>: The found node. None if any segment has no child with a matching name.
- `pub fn number_to_value(number: f64) -> Value` (static, since 0.4.0): Number → document value. (f64 as the shortest decimal, without a decimal point if an integer. Produces the same text as the original JSON.stringify. null if not a number)
  - `number` f64: Number to write.
  - returns Value: JSON number. (null if NaN or infinite)

  Example: Shortest decimal

  ```rust
  use serde_json::Value;
  use vanilla::UIDocument;
  
  assert_eq!(UIDocument::number_to_value(0.22).to_string(), "0.22");
  assert_eq!(UIDocument::number_to_value(24.0).to_string(), "24");
  assert_eq!(UIDocument::number_to_value(f64::NAN), Value::Null);
  ```

- `pub fn color_to_array(color: Color) -> Value` (static, since 0.4.0): Color → array. (original colorToArray, [r, g, b, a])
  - `color` Color: Color to write.
  - returns Value: [r, g, b, a] array. (0 ~ 1 values as the shortest decimal)
- `pub fn array_to_color(value: &Value) -> Option<Color>` (static, since 0.4.0): Array → color. (the original arrayToColor, None if there are fewer than four elements or any of the first four is not a number)
  - `value` &Value: Document value in [r, g, b, a] form.
  - returns Option<Color>: Color. None if not an array, if it has fewer than four elements, or if any of the first four is not a number. (from the fifth on is not checked)

  Example: Color array round trip

  ```rust
  use vanilla::{Color, UIDocument};
  
  let color = Color::create(1.0, 0.5, 0.0, 1.0);
  let color_value = UIDocument::color_to_array(color);
  assert_eq!(color_value, serde_json::json!([1, 0.5, 0, 1]));
  assert_eq!(UIDocument::array_to_color(&color_value), Some(color));
  assert_eq!(UIDocument::array_to_color(&serde_json::json!([1, 0.5])), None);
  ```

- `pub fn vector2_to_array(vector: Vector2) -> Value` (static, since 0.4.0): Vector → array. ([x, y])
  - `vector` Vector2: Vector to write.
  - returns Value: [x, y] array.
- `pub fn array_to_vector2(value: &Value) -> Option<Vector2>` (static, since 0.4.0): Array → vector. (None if there are fewer than two elements or either of the first two is not a number)
  - `value` &Value: Document value in [x, y] form.
  - returns Option<Vector2>: Vector. None if not an array, if it has fewer than two elements, or if any of the first two is not a number. (from the third on is not checked)

## Functions and constants

- `pub const UIDOCUMENT_VERSION: u32 = 1` (field, since 0.4.0): UI document format version.
  - returns u32
