Aperture UI
Content development

React

Building a game UI with React and Vite for Aperture UI. The build, how a host pushes state in, how the page calls the game, and the CitySlice HUD as the model.

Nothing in the engine is specific to React. Aperture UI runs a page's JavaScript in V8 against its own DOM, so a React app is a page like any other. This page shows how a React UI is put together for a game, using the HUD of the CitySlice sample as the model. CitySlice is a city-builder slice that draws its world with Vulkan and its whole interface, toolbars, panels and a developer console, with a React 19 and Vite 7 app written in TypeScript. The Aperture UI view draws the HUD on top of the world.

The code on this page is modelled on the sample's store.ts, not copied from it. The sample's host calls window.__cityStats and the map and history functions; the examples here use a generic window.__stats with made-up fields, and a game namespace like the sample's, so that they read on their own.

How it fits together

game loop ──callJavaScriptFunctionJson("__stats", json)──▶ window.__stats  ─▶ store ─▶ React
game logic ◀──────────── game.setTool("road") ◀───────────── event handlers

The app is built with Vite into a folder of static files. The host loads dist/index.html like any document. From then on there are two channels:

  • Host to page. The page defines a global function, window.__stats, and the host calls it with a JSON object. The function stores the object and tells React to render.
  • Page to host. The host registers native functions in a game namespace with the binder facade. Event handlers in React call them: game.setTool("road").

The Vite build

A reduced version of the sample's vite.config.ts produces the shape the engine loads most simply:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  base: "./", // document-relative URLs
  build: {
    outDir: "dist",
    target: "es2020",
    modulePreload: false,
    cssCodeSplit: false, // one stylesheet
    rollupOptions: {
      output: {
        entryFileNames: "assets/app.js", // stable file names
        chunkFileNames: "assets/[name].js",
        assetFileNames: "assets/[name][extname]",
      },
    },
  },
});

The output is an index.html that loads one module script and one stylesheet from ./assets/:

<script type="module" crossorigin src="./assets/app.js"></script>
<link rel="stylesheet" crossorigin href="./assets/style.css">

base: "./" makes every URL relative to the document, which is how the engine resolves them. Fixed file names, without content hashes, keep the output the same shape on every build. The engine runs type="module" scripts and dynamic import(), so a build with several chunks also loads. The sample keeps to one script and one stylesheet because that is the smallest thing to get right.

Author the UI in a browser with Vite's dev server first, which gives you hot reload and the browser's React tooling (see Getting started), and load the built folder in the engine to check it. The engine is tested page by page against Chrome, but a page you have not run in the engine is a page you have not tested.

Load it in the host

view.loadHtmlFromFile("ui/dist/index.html");

Scripts and styles load through IAPCFileSystem, from the document's own folder, so the built folder needs no extra trusted root. See File system.

State from the game to React

The page owns a small store that React subscribes to with useSyncExternalStore. The host pushes into it:

// bridge.ts
import { useSyncExternalStore } from "react";

export interface Stats { health: number; ammo: number; objective: string }

let state: Stats = { health: 100, ammo: 0, objective: "" };
const listeners = new Set<() => void>();

export function installBridge() {
  (window as unknown as { __stats: (s: Stats) => void }).__stats = (next) => {
    state = next;
    listeners.forEach((listener) => listener());
  };
}

export function useStats(): Stats {
  return useSyncExternalStore(
    (listener) => { listeners.add(listener); return () => listeners.delete(listener); },
    () => state,
  );
}
// main.tsx
import { createRoot } from "react-dom/client";
import { App } from "./App";
import { installBridge } from "./bridge";

installBridge();
createRoot(document.getElementById("root")!).render(<App />);
view.callJavaScriptFunctionJson("__stats", R"({"health":72,"ammo":18,"objective":"Hold the bridge"})");

callJavaScriptFunctionJson finds the global function, parses the JSON in V8 into a JavaScript object and calls the function with it, so no source text is compiled per update. A function that does not exist yet makes the call return false and log nothing, so you can push before the app has mounted. Scripting has the details.

Push one object for the whole screen, at the rate the screen needs and not once per frame. The sample sends its state a few times a second, and React renders only when the object changes. A component that calls useStats() re-renders on every push, so return just the one field a panel needs from the snapshot function if that panel is expensive.

Calls from React to the game

Register the functions before the document loads, then call them from event handlers:

using namespace aperture::binder;
// Only for a view loading content trusted with this binder.
view.setNativeBinderAccessAllowed(true);
APUIRequestNativeFunction(binder, "game", "setTool",
    [](const std::vector<std::string>& args) { if (!args.empty()) SetTool(args[0]); });
<button onClick={() => (window as any).game.setTool("road")}>Road</button>

CitySlice is built from the engine source, so it binds its game functions with APUIBinder::BindNamespacedFunction. The facade function above is the one a title that builds against the SDK package uses, and it does the same job. Every argument arrives as a string and a native function returns nothing to the page, so reply by pushing state back. See Scripting.

Threads and input

Script runs on the thread that ticks the view. CitySlice gives its HUD view a thread of its own, so React work does not stall the world, and every call into the view, including the pushes above, is posted to that thread. Treat a view as single-threaded either way (see Threads).

Forward mouse, wheel and keyboard events to the view first and look at what was hit. In CitySlice a click on an element inside a data-ui container belongs to the HUD, and any other click goes to the world. See Input.

Keeping a React UI fast

  • Let React skip work. Push only when data changes, keep props stable and memoize panels that are costly to render.
  • Prefer CSS state to inline style churn. A class change that selects a different style is cheaper to restyle than rewriting many inline properties. See Rendering.
  • Tune the JavaScript tier-up budget. A React render runs briefly and a few times a second, which is the case JSEngineConfig::tierUpBudget was added for: V8's defaults assume long-running hot loops. See Scripting performance.
  • Mind the DOM size. A large, constantly rebuilt list costs style and layout every time. Keep hidden screens out of the DOM instead of hiding them.

Debugging

React's browser extension is not available in the engine. Use the browser while you build, and the page's console output, which reaches your IAPCLoggingSystem, in the engine. In a full engine build you can attach Chrome DevTools to the running view. See DevTools.

On this page