# ui/uiscene (vanilla.js 0.4.0)

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

UI scene.

## UIScene extends Scene

UI scene.
- Standalone base scene that directly inherits Scene.
- Has its own common infrastructure identical to GameScene (developer tools / touch routing / loading screen /
  env() safe-area insets / automatic viewSize detection / canvas background clear).
- Has its own LayoutSolver instance. Calls updateVariables automatically every tick.
- Has its own screen guide UINode (screenNode). Fixed at top-left (0, 0), with width/height
  registered as edit variables and updated via suggestValue on resize.
  (same idea as UIKit's UIWindow.bounds)
- Has a separate safeAreaLayoutGuide UINode. Represents the area inset from screenNode by
  safeAreaInsets. (same idea as UIKit's UIView.safeAreaLayoutGuide)
  In the layout() phase, env() insets are automatically applied to setSafeAreaInsets.
- UINodes added to the tree are automatically attached to the solver on tick.

Example: Attach a header bar inside the safe area

```js
import { Engine, EngineConfiguration, UIScene, UINode, UILabel, Paint, Vector2, Color } from "./build/vanilla.js";

class MainScene extends UIScene {
	constructor() {
		super();
		this.setLoadingMinDurationMs(0);
		this.setSceneBackgroundColor(new Color(0.08, 0.09, 0.12, 1));
	}

	initialize(engine) {
		super.initialize(engine);
		const headerNode = new UINode();
		headerNode.setName("header");
		const paint = headerNode.addComponent(Paint);
		paint.setColor(new Color(0.2, 0.45, 0.85, 1));
		const label = headerNode.addComponent(UILabel);
		label.setText("Header");
		label.setFontSize(20);
		const root = this.getRoot();
		root.addChild(headerNode);

		const safeAreaGuide = this.getSafeAreaLayoutGuide();
		const safeLeftAnchor = safeAreaGuide.leftAnchor;
		const safeRightAnchor = safeAreaGuide.rightAnchor;
		const safeTopAnchor = safeAreaGuide.topAnchor;
		const headerLeftAnchor = headerNode.leftAnchor;
		const headerRightAnchor = headerNode.rightAnchor;
		const headerTopAnchor = headerNode.topAnchor;
		const headerHeightAnchor = headerNode.heightAnchor;
		const leftConstraint = headerLeftAnchor.equalTo(safeLeftAnchor.add(16));
		const rightConstraint = headerRightAnchor.equalTo(safeRightAnchor.subtract(16));
		const topConstraint = headerTopAnchor.equalTo(safeTopAnchor.add(16));
		const heightConstraint = headerHeightAnchor.equalTo(56);
		headerNode.addConstraint(leftConstraint);
		headerNode.addConstraint(rightConstraint);
		headerNode.addConstraint(topConstraint);
		headerNode.addConstraint(heightConstraint);
	}
}

const engineConfiguration = new EngineConfiguration();
engineConfiguration.canvasId = "mainCanvas";
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
engineConfiguration.autoResizeOnWindowResize = true;
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.2.1): Constructor.
- `setViewScaleMode(viewScaleMode)` (method, since 0.2.1): Sets the ViewScaleMode. Can be set freely per project.
  - Default is ViewScaleMode.none. Can be called anywhere before / after engine startup.
  - If the engine is already attached at call time, it is applied to viewManager immediately,
    otherwise it is applied all at once in initialize().
  - `viewScaleMode` string: View scale mode. (a ViewScaleMode value, default ViewScaleMode.none)
- `getViewScaleMode()` (method, since 0.2.1): Returns the current ViewScaleMode.
  - returns string: The current view scale mode. (a ViewScaleMode value)
- `setLoadingImageUrl(url)` (method, since 0.2.1): Sets the loading screen center image URL. (shows only the gauge without an image if empty string)
  - `url` string: URL of the image drawn at the center of the loading screen. (if null or empty, only the gauge is drawn)
- `setLoadingMinDurationMs(milliseconds)` (method, since 0.2.1): Sets the loading screen minimum display time (ms).
  - `milliseconds` number: Minimum time to show the loading screen. (milliseconds, default 3000, skipped at once when the screen is pressed)

  Example: Show a loading screen and load assets

  ```js
  import { Engine, EngineConfiguration, UIScene, ImageAsset, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingImageUrl("assets/icons/icon.png");
  		this.setLoadingMinDurationMs(500);
  		this.imageAsset = null;
  	}
  
  	async loadAssets() {
  		await super.loadAssets();
  		const imageAsset = new ImageAsset();
  		await imageAsset.load("examples/assets/spritesheet.png");
  		this.imageAsset = imageAsset;
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		console.log("loaded", this.imageAsset.isLoaded());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `create()` (method, since 0.2.1): Create. Sets up the solver / screenNode / safeAreaLayoutGuide.
- `async load(engine)` (method, since 0.2.1): Asynchronous load.
  - Loads its own assets (loadAssets), then guarantees the minimum display time.
  - Shortened immediately on screen touch. In the drawOnLoad phase there is no guarantee that the scene's touchPress
    is called, so it captures directly via window events.
  - After loading completes, applies viewSize to the solver immediately.
  - `engine` Engine: Engine.
- `async loadAssets()` (method, since 0.2.1): Asset loading hook.
  - Subclasses override it to load their own assets asynchronously. Calling super is required.
- `drawOnLoad(graphic)` (method, since 0.2.1): Draws the loading screen. (called every frame by the engine while isLoaded() === false)
  - Black background + center loading image + bottom gauge.
  - `graphic` Graphic: Graphics.
- `initialize(engine)` (method, since 0.2.1): Initialize. Sets up developer tools + touch raycaster.
  - `engine` Engine: Engine.
- `resize(canvasNativeSize)` (method, since 0.2.1): Screen size changed.
  - `canvasNativeSize` Vector2: Actual pixel size of the canvas.
- `layout()` (method, since 0.2.1): Layout.
  - Suggests viewSize to the solver, and syncs the view manager's safe area insets to its own safeAreaInsets.
  - Calls setSafeAreaInsets only when there is a change (saves constraint rebuild cost).
- `computeSafeAreaRect()` (method, since 0.2.1): Calculates the safe area rect. (view coordinate system)
  - Follows the view manager's getSafeAreaInsets. (setSafeAreaOverride > URL ?safeArea= > measured env(), sides excluded with setIgnoredSafeAreaSides are 0)
  - returns Rect: Safe area rectangle. (view coordinates, width and height are 0 or more)

  Example: Reading the safe area while simulating a notch on desktop

  ```js
  import { Engine, EngineConfiguration, UIScene, Vector2 } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
  const engine = new Engine(engineConfiguration);
  engine.getViewManager().setSafeAreaOverride({ top: 40, right: 0, bottom: 20, left: 10 });
  class MainScene extends UIScene {
  	initialize() {
  		super.initialize();
  		const safeAreaRect = this.computeSafeAreaRect();
  		console.log(safeAreaRect.position.x, safeAreaRect.position.y, safeAreaRect.size.x, safeAreaRect.size.y);
  	}
  }
  engine.run(new MainScene());
  ```

- `tick(timeDelta)` (method, since 0.2.1): Periodic update.
  - Detects viewSize changes → calls layout automatically.
    (in cases such as 100vh changing dynamically when the mobile address bar toggles, resize events alone
     can miss it, so it is corrected every tick.)
  - Automatically attaches UINodes newly added in the tree to the solver, then solves once.
  - DevTools tick.
  - `timeDelta` number: Time since the last frame. (Seconds)
- `attachPendingUINodes(node)` (method, since 0.2.1): Traverses the tree and attaches UINodes with no solver attached to this scene's solver.
  - `node` TransformNode: Node to start walking from. (does nothing if null or undefined)
- `suggestScreenSize(size)` (method, since 0.2.1): Suggests width/height values for the screen guide UINode.
  - `size` Vector2: Width and height to give the screen guide. (view units)
- `getSafeAreaInsets()` (method, since 0.2.1): Returns safeAreaInsets. (UIKit's UIView.safeAreaInsets)
  - returns { top: number, left: number, bottom: number, right: number }: A copy of the current safe area insets. (view units)
- `setSafeAreaInsets(insets)` (method, since 0.2.1): Sets safeAreaInsets. (defines the area for avoiding the mobile notch / home indicator)
  - Immediately updates the 4 constraints of safeAreaLayoutGuide.
  - `insets` { top: number, left: number, bottom: number, right: number }: Top, left, bottom and right insets. (view units)
- `rebuildSafeAreaLayoutGuideConstraints()` (method, since 0.2.1): Rebuilds the 4 constraints of safeAreaLayoutGuide.
  - Removes the existing constraints from the solver, rebuilds them with the current #safeAreaInsets and re-registers them.
- `getDevTools()` (method, since 0.4.0): Returns the developer tools. (null before initialize or when EngineConfiguration.useDevTools is off)
  - returns DevTools | null: Developer tools. (null if not created)

  Example: null on an engine with the developer tools turned off

  ```js
  import { Engine, EngineConfiguration, UIScene, Vector2 } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
  engineConfiguration.useDevTools = false;
  const engine = new Engine(engineConfiguration);
  class MainScene extends UIScene {
  	initialize() {
  		super.initialize();
  		console.log(this.getDevTools() === null);
  	}
  }
  engine.run(new MainScene());
  ```

- `isDevToolsCapturingInput()` (method, since 0.2.1): Whether DevTools is taking the input.
  - returns boolean: True if the developer tools panel is visible and the pointer is over it.
- `getTouchRaycaster()` (method, since 0.4.0): Returns the touch raycaster. (the TouchRecognizer that the touch hooks pass to nodes; the scene's default passing is turned off and this one is used)
  - returns TouchRecognizer: The TouchRecognizer that the touch hooks pass to. (undefined before initialize)
- `touchPress(viewInputPosition)` (method, since 0.2.1): touchPress.
  - `viewInputPosition` Vector2: Press position. (view coordinates)
- `touchMove(viewInputPosition)` (method, since 0.2.1): touchMove.
  - `viewInputPosition` Vector2: Moved position. (view coordinates)
- `touchRelease(viewInputPosition)` (method, since 0.2.1): touchRelease.
  - `viewInputPosition` Vector2: Release position. (view coordinates)
- `touchCancel(viewInputPosition)` (method, since 0.2.1): touchCancel.
  - `viewInputPosition` Vector2: Position at cancel. (view coordinates)
- `touchWheel(viewInputPosition, wheelDelta)` (method, since 0.2.1): touchWheel.
  - `viewInputPosition` Vector2: Position where the wheel was rolled. (view coordinates)
  - `wheelDelta` Vector2: Wheel amount accumulated this frame. (deltaX, deltaY of WheelEvent)
- `preDraw(graphic)` (method, since 0.2.1): preDraw. Fills the whole canvas with sceneBackgroundColor (including the area outside the safe area).
  - `graphic` Graphic: Graphics.
- `postDraw(graphic)` (method, since 0.2.1): postDraw. Draws DevTools over the screen.
  - `graphic` Graphic: Graphics.
- `getSolver()` (method, since 0.2.1): Returns the solver.
  - returns LayoutSolver: This scene's layout solver. (undefined before create)
- `getScreenNode()` (method, since 0.2.1): Returns the screen guide UINode.
  - Guide node not placed in the tree. left/top are fixed at 0, width/height are
    edit variables synced with the current viewSize.
  - Used as an anchor source when users write constraints for their UINodes relative to the screen.
  - returns UINode: Screen guide UINode.
- `getSafeAreaLayoutGuide()` (method, since 0.2.1): Returns safeAreaLayoutGuide. (same idea as UIKit's UIView.safeAreaLayoutGuide)
  - Guide UINode inset from screenNode by safeAreaInsets.
  - Used as an anchor source when users write constraints for their UINodes relative to the safeArea.
  - returns UINode: Safe area guide UINode.
