# ui/uidocument (vanilla.js 0.4.0)

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

UI document. (WorldNode tree ↔ JSON conversion)

## UIDocument extends Object

UI document. (WorldNode tree ↔ JSON conversion)
- A layer for restoring documents saved by the UI editing tool as is at runtime.
- UIView family widgets create their content node and dependent components themselves when attached.
  So the document records only the widgets, and children the user placed inside content
  are kept separately as contentChildren. (scroll view list items, etc)
- An instance without global state. Each document holds its own type tables (components, nodes) and image lookup state (resolver, requested image assets, pending images).
  new UIDocument() registers the engine's default types. Game types are added to that document with registerComponentType and registerNodeType.
- Images: found with the resolver (setImageResolver) when there is one, otherwise in the assets requested with loadImages. Images still loading
  are kept and set by bindPendingImages. (fromJsonText and deserializeNode call it once at the end)

Example: Loading a uiasset saved by UI Editor and wiring a button

```js
import { Engine, EngineConfiguration, UIScene, UIDocument, UIButton } from "./build/vanilla.js";

class DocumentScene extends UIScene {
	async loadAssets() {
		await super.loadAssets();
		const response = await fetch("examples/uisample/assets/title.uiasset.json");
		const jsonText = await response.text();
		const uiDocument = new UIDocument();
		await Promise.all(uiDocument.loadImages(jsonText));
		const documentRootNode = uiDocument.fromJsonText(jsonText);
		const root = this.getRoot();
		root.addChild(documentRootNode);
		const startButtonNode = UIDocument.findNodeByPath(documentRootNode, "/Panel/StartButton");
		const startButton = startButtonNode.getComponent(UIButton);
		startButton.setClickedEvent(() => {
			console.log("start");
		});
	}
}

const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
const scene = new DocumentScene();
scene.setLoadingMinDurationMs(0);
engine.run(scene);
```

- `constructor()` (constructor, since 0.3.0): Constructor. (registers the engine's default types)

  Example: Make one document, write a tree as text and restore it

  ```js
  import { UIDocument, WorldNode, Paint, Color, Vector2 } from "./build/vanilla.js";
  
  const panelNode = new WorldNode();
  panelNode.setName("Panel");
  panelNode.setContentSize(Vector2.create(320, 200));
  panelNode.addComponent(Paint).setColor(new Color(0.2, 0.4, 0.8, 1));
  const uiDocument = new UIDocument();
  const jsonText = uiDocument.toJsonText(panelNode, true);
  const loadedNode = uiDocument.fromJsonText(jsonText);
  console.log(loadedNode.getContentSize().x, uiDocument.toJsonText(loadedNode, true) === jsonText);
  ```

- `setImageResolver(resolver)` (method, since 0.3.0): Registers the image path resolver. (path → HTMLImageElement, once registered it is used instead of the assets requested with loadImages)
  - `resolver` function(string): HTMLImageElement | null: A function that takes an image path in the document and returns the image. (returning null means that image was not found)

  Example: Wiring image paths to preloaded images

  ```js
  import { UIDocument, Sprite } from "./build/vanilla.js";
  
  const imagePath = "examples/assets/spritesheet.png";
  const image = new Image();
  image.src = imagePath;
  await image.decode();
  const imageTable = new Map([[imagePath, image]]);
  const uiDocument = new UIDocument();
  uiDocument.setImageResolver((path) => {
  	const foundImage = imageTable.get(path);
  	return foundImage !== undefined ? foundImage : null;
  });
  const documentData = {
  	version: 1,
  	root: { type: "WorldNode", name: "Root", contentSize: [128, 128], components: [{ type: "Sprite", imagePath: imagePath }], children: [] },
  };
  const jsonText = JSON.stringify(documentData);
  const rootNode = uiDocument.fromJsonText(jsonText);
  const sprite = rootNode.getComponent(Sprite);
  console.log(sprite.getImagePath(), sprite.getImage() === image, uiDocument.resolveImage("missing.png"));
  ```

- `resolveImage(imagePath)` (method, since 0.3.0): Resolves an image path. (looks in the resolver, the assets requested with loadImages and the images this document wrote, in that order. null if not found or still loading)
  - `imagePath` string: Image path written in the document.
  - returns HTMLImageElement | null: The found image. (null if the resolver returned null, or there is no resolver and loadImages did not request it, it is still loading or it failed to load, and this document has not written an image for that path either)
- `loadImages(jsonText)` (method, since 0.4.0): Requests the document's images. (requests an ImageAsset for each imagePath and keeps it in the document. Paths already requested are skipped, paths that failed to load are requested again)
  - Returns a promise for each newly requested image that resolves once it has loaded (even if it failed). Wait for them with Promise.all in the scene's loadAssets and then call fromJsonText, and every image is attached.
  - If you build without waiting, images still loading are kept, so call bindPendingImages in the scene's update until the remaining count is 0.
  - `jsonText` string: Document text.
  - returns Promise<void>[]: List of load promises for the newly requested images. (resolved even when loading fails, an empty list when the text is not JSON or there is no new path to request)

  Example: Load the document's images, then build

  ```js
  import { UIDocument, Sprite } from "./build/vanilla.js";
  
  const jsonText = JSON.stringify({ version: 1, root: { name: "Icons", components: [{ type: "Sprite", imagePath: "examples/assets/spritesheet.png" }] } });
  const uiDocument = new UIDocument();
  const loadPromiseList = uiDocument.loadImages(jsonText);
  await Promise.all(loadPromiseList);
  const iconsNode = uiDocument.fromJsonText(jsonText);
  console.log(loadPromiseList.length, uiDocument.bindPendingImages(), iconsNode.getComponent(Sprite).getImage() !== null);
  ```

- `bindPendingImages()` (method, since 0.4.0): Attaches the kept images. (sets the images found, keeps those still loading, and returns the remaining count)
  - fromJsonText and deserializeNode call it once at the end. If you built without waiting for images, call it in the scene's update until the remaining count is 0.
  - An image that is not found (the resolver returned null, no asset, or it failed) gives a warning and is dropped. That component stays without an image.
  - A component whose image the game set in the meantime (getImage is not null) or whose path it changed is left alone and dropped.
  - returns number: Number of images still loading that remain. (0 when all were set or dropped)
- `serializeNode(node)` (method, since 0.3.0): Node tree → document data. (node references are written as paths from this node)
  - If a component that writes an imagePath holds an image, the image is remembered by path. Reading back with the same document sets that image without a resolver or loadImages.
  - A node reference to a node that has an earlier sibling with the same name gives a warning. (paths are names only, so reading back links to the earlier sibling)
  - A hidden node (setVisible(false)) writes visible: false. (not written when visible)
  - `node` WorldNode: The node to write. (including children)
  - returns object: Node data. ({ type, name, active, position, scale, rotation, opacity, pivot, anchor, contentSize, interactable, visible?, components, children, contentChildren? })

  Example: Copy a node as document data and build a clone

  ```js
  import { UIDocument, WorldNode, Vector2 } from "./build/vanilla.js";
  
  const cardNode = new WorldNode();
  cardNode.setName("Card");
  cardNode.setContentSize(Vector2.create(120, 80));
  const iconNode = new WorldNode();
  iconNode.setName("Icon");
  cardNode.addChild(iconNode);
  const uiDocument = new UIDocument();
  const cardData = uiDocument.serializeNode(cardNode);
  const copyNode = uiDocument.deserializeNode(cardData);
  console.log(cardData.name, copyNode !== cardNode, copyNode.getContentSize().x, UIDocument.findNodeByPath(copyNode, "/Icon") !== null);
  ```

- `collectGeneratedComponentTypes(componentList)` (method, since 0.3.0): Collects the component types a widget creates. (the require list of the UIView family)
  - `componentList` object[]: Component list of one node.
  - returns Set<string>: Set of document names of the components that UIView types attach together through require. (the registered name, or the class name if not registered)
- `deserializeNode(nodeData)` (method, since 0.3.0): Document data → node tree. (returns a node not attached to any parent)
  - Node references are connected as paths from this node, and the images that can be found are set. (bindPendingImages)
  - `nodeData` object: Node data in the serializeNode form. (unknown node types are created as WorldNode and unknown components are skipped, both with a warning)
  - returns WorldNode: The node made. (document values go into the components and children the node constructor made, without making them twice)
- `toJsonText(rootNode, isPretty = true)` (method, since 0.3.0): Node tree → JSON string.
  - `rootNode` WorldNode: Root node of the document. (base for node reference paths)
  - `isPretty` boolean: If true, indents with tabs. (default true)
  - returns string: JSON text in { version, root } form.

  Example: Writing a node tree to text and restoring it

  ```js
  import { UIDocument, UILabel, WorldNode, Paint, Color, Vector2 } from "./build/vanilla.js";
  
  const rootNode = new WorldNode();
  rootNode.setName("Root");
  const panelNode = new WorldNode();
  panelNode.setName("Panel");
  panelNode.setContentSize(Vector2.create(300, 200));
  const panelPaint = panelNode.addComponent(Paint);
  panelPaint.setColor(new Color(0.1, 0.12, 0.16, 1));
  rootNode.addChild(panelNode);
  const titleNode = new WorldNode();
  titleNode.setName("Title");
  const titleLabel = titleNode.addComponent(UILabel);
  titleLabel.setText("Hello");
  panelNode.addChild(titleNode);
  
  const uiDocument = new UIDocument();
  const jsonText = uiDocument.toJsonText(rootNode, false);
  const restoredRootNode = uiDocument.fromJsonText(jsonText);
  const restoredTitleNode = UIDocument.findNodeByPath(restoredRootNode, "/Panel/Title");
  const restoredTitleLabel = restoredTitleNode.getComponent(UILabel);
  const restoredText = restoredTitleLabel.getText();
  const restoredPath = UIDocument.findNodePath(restoredRootNode, restoredTitleNode);
  console.log(restoredText, restoredPath);
  ```

- `fromJsonText(jsonText)` (method, since 0.3.0): JSON string → node tree. (returns a root not attached to any parent, attach it with addChild to show it in a scene)
  - `jsonText` string: JSON text of the form { version, root }. (throws when it is not JSON or has no root)
  - returns WorldNode: The restored root node. (with node references connected and the images that can be found set)
- `getComponentTypeNames()` (method, since 0.3.0): Returns the list of supported component type names. (in registration order, for the add component menu of the editing tools)
  - returns string[]: List of component names this document handles. (including those added with registerComponentType, node type names are not included)
- `createComponent(node, typeName)` (method, since 0.4.0): Makes a component by name and attaches it to the node. (null for a name that is not registered)
  - `node` WorldNode: The node to attach the component to.
  - `typeName` string: A registered component type name.
  - returns *: The attached component. (null for a name that is not registered)

  Example: Attach a Paint by name

  ```js
  import { UIDocument, WorldNode, Paint } from "./build/vanilla.js";
  
  const uiDocument = new UIDocument();
  const node = new WorldNode();
  const paint = uiDocument.createComponent(node, "Paint");
  console.log(paint === node.getComponent(Paint), uiDocument.createComponent(node, "Unknown"));
  ```

- `getNodeTypeName(node)` (method, since 0.4.0): Returns the node's document type name. (the registered node type name, or the class name for a class that is not registered)
  - `node` WorldNode: Node to look at.
  - returns string: The node type name written in the document.

  Example: See node types in a document with the editor types registered

  ```js
  import { UIDocument, WorldNode, FloatingText } from "./build/vanilla.js";
  
  const uiDocument = new UIDocument();
  uiDocument.registerEditorTypes();
  console.log(uiDocument.getNodeTypeName(new WorldNode()), uiDocument.getNodeTypeName(new FloatingText()));
  ```

- `static getReflectedProperties(component)` (static, since 0.4.0): List of editable properties of a component. (static, matching get or is and set, used by the editor's inspector)
  - `component` *: The component to inspect.
  - returns Array<object>: An array of { name, getterName, setterName }.
- `static findNodePath(rootNode, node)` (static, since 0.3.0): Computes the absolute path from the UI root. (static, used when writing node references into the document)
  - `rootNode` WorldNode: Base root node. (not included in the path)
  - `node` WorldNode: The node to find the path of.
  - returns string | null: Path in /Panel/Title form. (/ for the root itself, null if not under the root)
- `static findNodeByPath(rootNode, pathText)` (static, since 0.3.0): Finds a node by its absolute path from the UI root. (static)
  - `rootNode` WorldNode: Base root node.
  - `pathText` string: Path in /Panel/Title form. (the leading / is optional, the first one if siblings share a name)
  - returns WorldNode | null: The found node. (the root for an empty path, null if none)
- `registerNodeType(typeName, nodeType)` (method, since 0.3.0): Registers a node type.
  - When the engine gains more nodes, registering is all it takes for the document to handle that type.
  - `typeName` string: Name written in documents. (looked up by this name when loading and written with this name when saving)
  - `nodeType` *: Node class. (created with new and no arguments)
- `registerComponentType(typeName, componentType)` (method, since 0.3.0): Registers a component type.
  - `typeName` string: Name written in documents. (looked up by this name when loading and written with this name when saving)
  - `componentType` *: Component class. (it has no dedicated save and load, so it is written and restored through matching get and set properties)

  Example: Putting a game component into a document

  ```js
  import { UIDocument, Component, WorldNode } from "./build/vanilla.js";
  
  class Blinker extends Component {
  	#speed = 1;
  
  	getSpeed() {
  		return this.#speed;
  	}
  
  	setSpeed(speed) {
  		this.#speed = speed;
  	}
  }
  
  const uiDocument = new UIDocument();
  uiDocument.registerComponentType("Blinker", Blinker);
  const rootNode = new WorldNode();
  const lampNode = new WorldNode();
  lampNode.setName("Lamp");
  const blinker = lampNode.addComponent(Blinker);
  blinker.setSpeed(3);
  rootNode.addChild(lampNode);
  const jsonText = uiDocument.toJsonText(rootNode);
  const restoredRootNode = uiDocument.fromJsonText(jsonText);
  const restoredLampNode = UIDocument.findNodeByPath(restoredRootNode, "/Lamp");
  const restoredBlinker = restoredLampNode.getComponent(Blinker);
  const speed = restoredBlinker.getSpeed();
  console.log(speed);
  ```

- `registerEditorTypes()` (method, since 0.4.0): Registers every type the editors use in this document.
  - UI Editor (tools/uieditor) registers every Component and WorldNode subclass the engine exports and write them into documents.
    The default tables hold only the types the runtime always uses, so a game that loads documents saved by the editor calls this once.
  - Registers in name order (abc) and leaves names that are already registered as they are. (keeps the dedicated save and load of the default tables and the types the game registered)

  Example: Load an input field and a snap scroll saved by the editor

  ```js
  import { UIDocument, UIInputField, UISnapScrollView, WorldNode } from "./build/vanilla.js";
  
  const uiDocument = new UIDocument();
  uiDocument.registerEditorTypes();
  const rootNode = new WorldNode();
  const inputFieldNode = new UIInputField();
  inputFieldNode.setName("Name");
  rootNode.addChild(inputFieldNode);
  const pageNode = new WorldNode();
  pageNode.setName("Pages");
  pageNode.addComponent(UISnapScrollView);
  rootNode.addChild(pageNode);
  const jsonText = uiDocument.toJsonText(rootNode);
  const restoredRootNode = uiDocument.fromJsonText(jsonText);
  const restoredInputFieldNode = UIDocument.findNodeByPath(restoredRootNode, "/Name");
  const restoredPageNode = UIDocument.findNodeByPath(restoredRootNode, "/Pages");
  const restoredSnapScrollView = restoredPageNode.getComponent(UISnapScrollView);
  console.log(restoredInputFieldNode instanceof UIInputField, restoredSnapScrollView !== null);
  ```

- `saveByReflection(component)` (method, since 0.3.0): Saves a component through matching get/set properties.
  - Used for components without a dedicated handler. Holds only transferable values.
  - Node references are written as paths from the root that serializeNode or toJsonText is writing. (called anywhere else, node references are left out)
  - `component` Component: The component to write.
  - returns object: Property names and values. (numbers, strings and booleans as is, Color and Vector2 as arrays, nodes as { $nodeRef })
- `loadByReflection(component, componentData)` (method, since 0.3.0): Restores a component through matching get/set properties.
  - Decides whether to accept a value by the type of the current value. When there is no current value (null), it accepts the type as saved. When the current value is a Color and the stored value is a string (an old document written before the field became a Color), it is read with Color.from.
    (saveByReflection writes only Color as an array of four numbers, only Vector2 as an array of two numbers, and everything else as a number, string or boolean as is)
  - Node references are kept and connected after deserializeNode or fromJsonText has built the whole tree. (called anywhere else, they are not connected)
  - `component` Component: The component to restore.
  - `componentData` object: Data in saveByReflection form. (only values whose type matches the current value are set)
