vanilladocs
vanillapunch.com
API / ui/uidocument

ui/uidocument

UI 문서. (WorldNode 트리 ↔ JSON 상호 변환)

UI document. (WorldNode tree ↔ JSON conversion)

UIDocumentextends Object

짝Counterpart: vanilla-engine UIDocument

UI 문서. (WorldNode 트리 ↔ JSON 상호 변환)

  • UI 편집 도구가 저장한 문서를 런타임에서 그대로 복원하기 위한 계층이다.
  • UIView 계열 위젯은 부착 시 content 노드와 의존 컴포넌트를 스스로 만든다. 따라서 문서에는 위젯만 기록하고, 사용자가 content 안에 넣은 자식은 contentChildren 으로 따로 보존한다. (스크롤뷰의 목록 항목 등)
  • 전역 상태가 없는 인스턴스다. 문서마다 종류 표(컴포넌트, 노드)와 그림 찾기 상태(해석기, 요청한 그림 애셋, 맡아 둔 그림)를 든다. new UIDocument() 는 엔진 기본 종류를 등록해 둔다. 게임 종류는 그 문서에 registerComponentType, registerNodeType 으로 더한다.
  • 그림: 해석기(setImageResolver)가 있으면 그것으로, 없으면 loadImages 로 요청한 애셋에서 찾는다. 아직 읽히는 그림은 맡아 두었다가 bindPendingImages 가 넣는다. (fromJsonText, deserializeNode 가 끝에 한 번 부른다)

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)
예제ExampleUI Editor 가 저장한 uiasset 불러와 단추 잇기Loading a uiasset saved by UI Editor and wiring a button
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);
생성자constructorconstructor()#0.3.0 부터since 0.3.0소스source

생성. (엔진 기본 종류를 등록해 둔다)

Constructor. (registers the engine's default types)

짝Counterpart: vanilla-engine UIDocument.new

예제Example문서 하나를 지어 트리를 글로 적고 되살리기Make one document, write a tree as text and restore it
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);
정적staticstatic getReflectedProperties(component)#0.4.0 부터since 0.4.0소스source

컴포넌트의 편집할 수 있는 속성 목록. (정적, 짝이 맞는 get 또는 is 와 set, 에디터의 인스펙터가 쓴다)

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.

반환ReturnsArray<object> { name, getterName, setterName } 의 배열.An array of { name, getterName, setterName }.

짝Counterpart: vanilla-engine UIDocument.get_reflected_properties

정적staticstatic findNodePath(rootNode, node)#0.3.0 부터since 0.3.0소스source

UI 뿌리 기준 절대 경로 계산. (정적, 노드 참조를 문서에 적을 때 쓴다)

Computes the absolute path from the UI root. (static, used when writing node references into the document)

rootNodeWorldNode
기준 뿌리 노드. (경로에 넣지 않는다)Base root node. (not included in the path)
nodeWorldNode
경로를 구할 노드.The node to find the path of.

반환Returnsstring | null /Panel/Title 꼴의 경로. (뿌리 자신이면 /, 뿌리 아래가 아니면 null)Path in /Panel/Title form. (/ for the root itself, null if not under the root)

짝Counterpart: vanilla-engine UIDocument.find_node_path

정적staticstatic findNodeByPath(rootNode, pathText)#0.3.0 부터since 0.3.0소스source

UI 뿌리 기준 절대 경로로 노드 찾기. (정적)

Finds a node by its absolute path from the UI root. (static)

rootNodeWorldNode
기준 뿌리 노드.Base root node.
pathTextstring
/Panel/Title 꼴의 경로. (앞의 / 는 없어도 된다, 이름이 같은 형제가 있으면 앞의 것)Path in /Panel/Title form. (the leading / is optional, the first one if siblings share a name)

반환ReturnsWorldNode | null 찾은 노드. (빈 경로면 뿌리, 없으면 null)The found node. (the root for an empty path, null if none)

짝Counterpart: vanilla-engine UIDocument.find_node_by_path

메서드methodsetImageResolver(resolver)#0.3.0 부터since 0.3.0소스source

이미지 경로 해석기 등록. (경로 → HTMLImageElement, 등록하면 loadImages 로 요청한 애셋 대신 이것으로 찾는다)

Registers the image path resolver. (path → HTMLImageElement, once registered it is used instead of the assets requested with loadImages)

resolverfunction(string): HTMLImageElement | null
문서의 이미지 경로를 받아 그림을 돌려주는 함수. (null 을 돌려주면 그 그림은 찾지 못한 것이다)A function that takes an image path in the document and returns the image. (returning null means that image was not found)

짝Counterpart: vanilla-engine UIDocument.set_image_resolver

예제Example미리 받은 그림으로 이미지 경로 잇기Wiring image paths to preloaded images
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"));
메서드methodresolveImage(imagePath)#0.3.0 부터since 0.3.0소스source

이미지 경로 해석. (해석기, loadImages 로 요청한 애셋, 이 문서로 적은 그림 차례로 찾는다. 찾지 못했거나 아직 읽히는 중이면 null)

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)

imagePathstring
문서에 적힌 이미지 경로.Image path written in the document.

반환ReturnsHTMLImageElement | null 찾은 그림. (해석기가 null 을 주었거나, 해석기가 없고 loadImages 로 요청하지 않았거나 아직 읽히는 중이거나 읽기에 실패했고, 이 문서로 적은 그 경로의 그림도 없으면 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)

짝Counterpart: vanilla-engine UIDocument.resolve_image

메서드methodloadImages(jsonText)#0.4.0 부터since 0.4.0소스source

문서의 그림 읽기 요청. (imagePath 마다 ImageAsset 을 요청해 문서에 든다. 이미 요청한 경로는 건너뛰고, 읽지 못한 경로는 다시 요청한다)

  • 새로 요청한 그림마다 다 읽히면(읽지 못해도) 풀리는 프로미스를 돌려준다. 씬의 loadAssets 에서 Promise.all 로 기다린 뒤 fromJsonText 하면 그림이 다 붙는다.
  • 기다리지 않고 지으면 아직 읽히는 그림은 맡아 두므로, 씬의 update 에서 bindPendingImages 를 남은 수가 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.
jsonTextstring
문서 글.Document text.

반환ReturnsPromise<void>[] 새로 요청한 그림의 읽기 프로미스 목록. (읽지 못해도 풀린다, JSON 이 아니거나 새로 요청할 경로가 없으면 빈 목록)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)

짝Counterpart: vanilla-engine UIDocument.load_images

예제Example문서의 그림을 읽은 뒤 짓기Load the document's images, then build
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);
메서드methodbindPendingImages()#0.4.0 부터since 0.4.0소스source

맡아 둔 그림 붙이기. (찾은 그림은 넣고, 아직 읽히는 그림은 남긴다. 남은 수를 돌려준다)

  • fromJsonText, deserializeNode 가 끝에 한 번 부른다. 그림을 기다리지 않고 지었으면 씬의 update 에서 남은 수가 0 이 될 때까지 부른다.
  • 찾지 못한 그림(해석기가 null, 애셋이 없거나 실패)은 경고를 내고 버린다. 그 컴포넌트는 그림 없이 남는다.
  • 그사이 게임이 그림을 넣었거나(getImage 가 null 이 아님) 경로를 바꾼 컴포넌트는 건드리지 않고 버린다.

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.

반환Returnsnumber 아직 읽히는 중이라 남은 그림 수. (0 이면 다 붙였거나 버렸다)Number of images still loading that remain. (0 when all were set or dropped)

짝Counterpart: vanilla-engine UIDocument.bind_pending_images

메서드methodserializeNode(node)#0.3.0 부터since 0.3.0소스source

노드 트리 → 문서 데이터. (노드 참조는 이 노드 기준 경로로 적는다)

  • imagePath 를 적은 컴포넌트에 그림이 들었으면 그 그림을 경로로 기억한다. 같은 문서로 다시 읽으면 해석기나 loadImages 없이도 그 그림을 넣는다.
  • 노드 참조가 이름이 같은 앞 형제가 있는 노드를 가리키면 경고를 낸다. (경로는 이름으로만 적어 다시 읽으면 앞 형제에 이어진다)
  • 숨긴 노드(setVisible(false))는 visible: false 를 적는다. (보이면 적지 않는다)

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)
nodeWorldNode
적을 노드. (자식까지)The node to write. (including children)

반환Returnsobject 노드 데이터. ({ type, name, active, position, scale, rotation, opacity, pivot, anchor, contentSize, interactable, visible?, components, children, contentChildren? })Node data. ({ type, name, active, position, scale, rotation, opacity, pivot, anchor, contentSize, interactable, visible?, components, children, contentChildren? })

짝Counterpart: vanilla-engine UIDocument.serialize_node

예제Example노드를 문서 값으로 떠서 복제본 짓기Copy a node as document data and build a clone
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);
메서드methodcollectGeneratedComponentTypes(componentList)#0.3.0 부터since 0.3.0소스source

위젯이 생성한 컴포넌트 타입 수집. (UIView 계열의 require 목록)

Collects the component types a widget creates. (the require list of the UIView family)

componentListobject[]
한 노드의 컴포넌트 목록.Component list of one node.

반환ReturnsSet<string> UIView 계열이 require 로 함께 붙이는 컴포넌트의 문서 이름 모음. (등록한 이름, 등록하지 않았으면 클래스 이름)Set of document names of the components that UIView types attach together through require. (the registered name, or the class name if not registered)

짝Counterpart: vanilla-engine UIDocument.collect_generated_component_types

메서드methoddeserializeNode(nodeData)#0.3.0 부터since 0.3.0소스source

문서 데이터 → 노드 트리. (어느 부모에도 붙지 않은 노드를 돌려준다)

  • 노드 참조는 이 노드 기준 경로로 잇고, 찾을 수 있는 그림을 넣는다. (bindPendingImages)

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)
nodeDataobject
serializeNode 꼴의 노드 데이터. (모르는 노드 종류는 WorldNode 로 만들고, 모르는 컴포넌트는 건너뛴다, 둘 다 경고를 낸다)Node data in the serializeNode form. (unknown node types are created as WorldNode and unknown components are skipped, both with a warning)

반환ReturnsWorldNode 만든 노드. (노드 생성자가 만든 컴포넌트와 자식에는 문서 값을 넣고 겹쳐 만들지 않는다)The node made. (document values go into the components and children the node constructor made, without making them twice)

짝Counterpart: vanilla-engine UIDocument.deserialize_node

메서드methodtoJsonText(rootNode, isPretty = true)#0.3.0 부터since 0.3.0소스source

노드 트리 → JSON 문자열.

Node tree → JSON string.

rootNodeWorldNode
문서의 뿌리 노드. (노드 참조 경로의 기준)Root node of the document. (base for node reference paths)
isPrettyboolean
참이면 탭으로 들여 쓴다. (기본 참)If true, indents with tabs. (default true)

반환Returnsstring { version, root } 꼴의 JSON 글.JSON text in { version, root } form.

짝Counterpart: vanilla-engine UIDocument.to_json_text

예제Example노드 트리를 글로 적고 되살리기Writing a node tree to text and restoring it
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);
메서드methodfromJsonText(jsonText)#0.3.0 부터since 0.3.0소스source

JSON 문자열 → 노드 트리. (어느 부모에도 붙지 않은 뿌리를 돌려준다, 씬에 보이려면 addChild 로 붙인다)

JSON string → node tree. (returns a root not attached to any parent, attach it with addChild to show it in a scene)

jsonTextstring
{ version, root } 꼴의 JSON 글. (JSON 이 아니거나 root 가 없으면 예외를 던진다)JSON text of the form { version, root }. (throws when it is not JSON or has no root)

반환ReturnsWorldNode 되살린 뿌리 노드. (노드 참조까지 잇고, 찾을 수 있는 그림을 넣은 것)The restored root node. (with node references connected and the images that can be found set)

짝Counterpart: vanilla-engine UIDocument.from_json_text

메서드methodgetComponentTypeNames()#0.3.0 부터since 0.3.0소스source

지원 컴포넌트 타입 이름 목록 반환. (등록 차례, 편집 도구의 컴포넌트 추가 메뉴용)

Returns the list of supported component type names. (in registration order, for the add component menu of the editing tools)

반환Returnsstring[] 이 문서가 다루는 컴포넌트 이름 목록. (registerComponentType 으로 더한 것 포함, 노드 종류 이름은 들지 않는다)List of component names this document handles. (including those added with registerComponentType, node type names are not included)

짝Counterpart: vanilla-engine UIDocument.get_component_type_names

메서드methodcreateComponent(node, typeName)#0.4.0 부터since 0.4.0소스source

이름으로 컴포넌트를 지어 노드에 붙인다. (등록하지 않은 이름이면 null)

Makes a component by name and attaches it to the node. (null for a name that is not registered)

nodeWorldNode
컴포넌트를 붙일 노드.The node to attach the component to.
typeNamestring
등록한 컴포넌트 종류 이름.A registered component type name.

반환Returns* 붙인 컴포넌트. (등록하지 않은 이름이면 null)The attached component. (null for a name that is not registered)

짝Counterpart: vanilla-engine UIDocument.create_component

예제Example이름으로 Paint 붙이기Attach a Paint by name
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"));
메서드methodgetNodeTypeName(node)#0.4.0 부터since 0.4.0소스source

노드의 문서 종류 이름 반환. (등록한 노드 종류 이름, 등록하지 않은 클래스면 클래스 이름)

Returns the node's document type name. (the registered node type name, or the class name for a class that is not registered)

nodeWorldNode
볼 노드.Node to look at.

반환Returnsstring 문서에 적힐 노드 종류 이름.The node type name written in the document.

짝Counterpart: vanilla-engine UIDocument.get_node_type_name

예제Example에디터 종류를 등록한 문서에서 노드 종류 보기See node types in a document with the editor types registered
import { UIDocument, WorldNode, FloatingText } from "./build/vanilla.js";

const uiDocument = new UIDocument();
uiDocument.registerEditorTypes();
console.log(uiDocument.getNodeTypeName(new WorldNode()), uiDocument.getNodeTypeName(new FloatingText()));
메서드methodregisterNodeType(typeName, nodeType)#0.3.0 부터since 0.3.0소스source

노드 종류 등록.

  • 엔진에 노드가 늘어나면 등록만으로 문서가 그 종류를 다룬다.

Registers a node type.

  • When the engine gains more nodes, registering is all it takes for the document to handle that type.
typeNamestring
문서에 적힐 이름. (읽을 때 이 이름으로 찾고, 적을 때도 이 이름을 쓴다)Name written in documents. (looked up by this name when loading and written with this name when saving)
nodeType*
노드 클래스. (인자 없이 new 한다)Node class. (created with new and no arguments)

짝Counterpart: vanilla-engine UIDocument.register_node_type

메서드methodregisterComponentType(typeName, componentType)#0.3.0 부터since 0.3.0소스source

컴포넌트 종류 등록.

Registers a component type.

typeNamestring
문서에 적힐 이름. (읽을 때 이 이름으로 찾고, 적을 때도 이 이름을 쓴다)Name written in documents. (looked up by this name when loading and written with this name when saving)
componentType*
컴포넌트 클래스. (전용 입출력이 없으므로 짝이 맞는 get, set 속성으로 적고 되살린다)Component class. (it has no dedicated save and load, so it is written and restored through matching get and set properties)

짝Counterpart: vanilla-engine UIDocument.register_component_type

예제Example게임의 컴포넌트를 문서에 담기Putting a game component into a document
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);
메서드methodregisterEditorTypes()#0.4.0 부터since 0.4.0소스source

에디터가 다루는 종류 모두 이 문서에 등록.

  • UI 에디터(tools/uieditor)는 엔진이 내보내는 모든 Component 와 WorldNode 하위 클래스를 등록해 문서에 적는다. 기본 표에는 런타임이 늘 쓰는 종류만 있으므로, 에디터가 저장한 문서를 읽는 게임은 이것을 한 번 부른다.
  • 이름 차례(abc)로 등록하고, 이미 등록한 이름은 그대로 둔다. (기본 표의 전용 입출력과 게임이 등록한 종류를 지킨다)

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)

짝Counterpart: vanilla-engine UIDocument.register_editor_types

예제Example에디터가 저장한 입력 필드와 스냅 스크롤을 읽기Load an input field and a snap scroll saved by the editor
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);
메서드methodsaveByReflection(component)#0.3.0 부터since 0.3.0소스source

짝이 맞는 get/set 속성으로 컴포넌트 저장.

  • 전용 핸들러가 없는 컴포넌트에 쓴다. 옮길 수 있는 값만 담는다.
  • 노드 참조는 serializeNode, toJsonText 가 적고 있는 뿌리 기준 경로로 적는다. (그 밖에서 부르면 노드 참조는 빠진다)

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)
componentComponent
적을 컴포넌트.The component to write.

반환Returnsobject 속성 이름과 값. (수, 글, 참거짓은 그대로, Color 와 Vector2 는 배열, 노드는 { $nodeRef })Property names and values. (numbers, strings and booleans as is, Color and Vector2 as arrays, nodes as { $nodeRef })

짝Counterpart: vanilla-engine UIDocument.save_by_reflection

메서드methodloadByReflection(component, componentData)#0.3.0 부터since 0.3.0소스source

짝이 맞는 get/set 속성으로 컴포넌트 복원.

  • 지금 값의 꼴로 받을지 가린다. 지금 값이 없으면(null) 저장할 때의 꼴로 받는다. 지금 값이 Color 이고 적힌 값이 글이면(색 칸을 Color 로 바꾸기 전에 적은 옛 문서) Color.from 으로 읽는다. (saveByReflection 은 Color 만 수 넷 배열로, Vector2 만 수 둘 배열로, 그 밖은 수, 글, 불 그대로 적는다)
  • 노드 참조는 맡아 두었다가 deserializeNode, fromJsonText 가 트리를 다 지은 뒤 잇는다. (그 밖에서 부르면 잇지 않는다)

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)
componentComponent
되살릴 컴포넌트.The component to restore.
componentDataobject
saveByReflection 꼴의 데이터. (지금 값과 꼴이 같은 것만 넣는다)Data in saveByReflection form. (only values whose type matches the current value are set)

짝Counterpart: vanilla-engine UIDocument.load_by_reflection