# resource/visualasset (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/resource/visualasset/

Visual asset. (VisualAsset of the original resource/visualasset.js, reads a document file saved by the visual editor and makes a Visual)
- The file is the UIDocument JSON saved by the visual editor (vanilla.js tools/visualeditor). (Scene *.scene.json, prefab *.prefab.json, { version, root, frameSize? })
- load asks the engine's asset fetching for the bytes. When the bytes arrive, the first look checks that they are a JSON object with a root object; if so it counts as loaded and stores a Visual holding that text.
  A failed fetch or a malformed document stays unloaded. (The original rejects load)
- Visual::create_node builds the node tree. (A new tree on every call)
- Differences from the original:
  - The original load(path) returns a Promise, the Rust load(engine, path) returns a load handle that can be awaited. (Same as other assets)
  - The original static createVisualFromText(text) throws on failure, the Rust create_visual_from_text gives Err.
  - load_from_bytes exists for tests and bundle files. (Same as TextAsset)

## VisualAsset (struct) (Default, Asset)

Visual asset.
- Reads a visual editor document file and stores a Visual holding that text. A file that is not a document (a JSON object with a root object) stays unloaded.

Example: Read a visual editor prefab and build nodes

```rust
use vanilla::{Asset, AssetType, NodeTree, UIDocument, VisualAsset};

let document_text = r#"{"version":1,"root":{"type":"WorldNode","name":"Panel","contentSize":[200,120],"components":[],"children":[]},"frameSize":[960,540]}"#;
let mut visual_asset = VisualAsset::new();
assert!(!visual_asset.is_loaded());
visual_asset.load_from_bytes("panel.prefab.json", document_text.as_bytes().to_vec());
assert!(visual_asset.is_loaded());
assert_eq!(visual_asset.get_asset_base().get_asset_type(), AssetType::Visual);

let visual = visual_asset.get_visual().expect("visual");
let mut document = UIDocument::new();
let mut node_tree = NodeTree::new();
let panel_id = visual.create_node(&mut document, &mut node_tree).expect("document").expect("root");
assert_eq!(node_tree[panel_id].get_name(), "Panel");
```

- `pub fn new() -> VisualAsset` (constructor, since 0.3.2): Creates one. (asset type visual)
  - returns VisualAsset: An empty visual asset before any request. (Not loaded, no stored visual)
- `pub fn load(&mut self, engine: &Engine, asset_path: &str) -> AssetLoadHandle` (method, since 0.3.2): Request a load. (Original load, returns a load handle that can be awaited)
  - `engine` &Engine: Engine to load the asset with.
  - `asset_path` &str: Path of a document file saved by the visual editor.
  - returns AssetLoadHandle: Load handle. (Finishes when the bytes arrive, is_loaded and get_visual check the document shape)

  Example: Fetch a document from a data: URL

  ```rust
  use vanilla::{Asset, Engine, EngineConfiguration, VisualAsset};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut visual_asset = VisualAsset::new();
  visual_asset.load(&engine, r#"data:application/json,{"version":1,"root":{"type":"WorldNode","name":"Icon","components":[],"children":[]}}"#);
  assert!(visual_asset.is_loaded());
  assert!(visual_asset.get_visual().is_some());
  
  let mut broken_asset = VisualAsset::new();
  broken_asset.load(&engine, r#"data:application/json,{"version":1}"#);
  assert!(!broken_asset.is_loaded());
  assert!(broken_asset.get_visual().is_none());
  ```

- `pub fn load_from_bytes(&mut self, asset_path: &str, bytes: Vec<u8>)` (method, since 0.4.0): Load from bytes already in hand.
  - `asset_path` &str: Path to record.
  - `bytes` Vec<u8>: Document file bytes.
- `pub fn unload(&mut self)` (method, since 0.4.0): Unload. (Also clears the stored Visual)
- `pub fn create_visual_from_text(document_text: &str) -> Result<Visual, String>` (static, since 0.4.0): Make a Visual from document text.
  - `document_text` &str: UIDocument JSON text saved by the visual editor.
  - returns Result<Visual, String>: A Visual holding that text. Err when it is not a JSON object or has no root object.

  Example: Make one straight from document text

  ```rust
  use vanilla::{NodeTree, UIDocument, VisualAsset};
  
  let document_text = r#"{"version":1,"root":{"type":"WorldNode","name":"Icon","components":[],"children":[]}}"#;
  let visual = VisualAsset::create_visual_from_text(document_text).expect("visual");
  assert_eq!(visual.get_document_text(), Some(document_text));
  let mut document = UIDocument::new();
  let mut node_tree = NodeTree::new();
  let icon_id = visual.create_node(&mut document, &mut node_tree).expect("document").expect("root");
  assert_eq!(node_tree[icon_id].get_name(), "Icon");
  
  assert!(VisualAsset::create_visual_from_text("not json").is_err());
  assert!(VisualAsset::create_visual_from_text("[1, 2]").is_err());
  assert!(VisualAsset::create_visual_from_text(r#"{"version":1,"root":[1, 2]}"#).is_err());
  ```

- `pub fn set_visual(&mut self, visual: Option<Visual>)` (method, since 0.3.2): Sets the visual.
  - `visual` Option<Visual>: Visual to store. (None clears it, does not change the loaded state)
- `pub fn get_visual(&self) -> Option<&Visual>` (method, since 0.3.2): Returns the visual.
  - returns Option<&Visual>: Stored visual. (The one holding the read document, or the one set with set_visual) None when not loaded yet, or not a document and nothing was set.

  Example: Set a visual directly, clear it, and unload

  ```rust
  use vanilla::{Asset, Vector2, Visual, VisualAsset};
  
  let mut visual_asset = VisualAsset::new();
  assert!(visual_asset.get_visual().is_none());
  let mut visual = Visual::new();
  visual.set_location(Vector2::create(10.0, 20.0));
  visual_asset.set_visual(Some(visual));
  assert_eq!(visual_asset.get_visual().map(|visual| visual.get_location()), Some(Vector2::create(10.0, 20.0)));
  assert!(!visual_asset.is_loaded());
  
  visual_asset.load_from_bytes("coin.prefab.json", br#"{"version":1,"root":{"name":"Coin"}}"#.to_vec());
  assert!(visual_asset.get_visual().is_some_and(|visual| visual.get_document_text().is_some()));
  visual_asset.set_visual(None);
  assert!(visual_asset.get_visual().is_none());
  assert!(visual_asset.is_loaded());
  visual_asset.unload();
  assert!(!visual_asset.is_loaded());
  assert!(visual_asset.get_visual().is_none());
  ```

