Xyz
State ownership primitives, a declarative Tweakpane debug layer, and Three.js scene warmup to kill first-frame hitches.
JOYCO's 3D toolkit. Keyed state ownership, typed definitions, CDN asset routing, ordered teardown, a declarative controls layer for Tweakpane or DialKit, and Three.js scene warmup that forces every shader compile and texture upload to happen before the player ever sees a hitch.
Mental model
Xyz has three tree-shakeable entrypoints:
- Core (
@joycostudio/xyz) —Derivedandedgefor state that multiple owners write to and one policy resolves;defineAssetSourcefor Chopper-aware CDN paths;Disposerfor teardown that unwinds in reverse;ModuleandModuleHostfor ownership trees, selected-state sync, typed events, ticking, warmup, and inspection snapshots. - Controls (
@joycostudio/xyz/controls) —createControlsowns URL/keyboard activation and lazily loads Tweakpane or DialKit; each module describes its controls (slider,toggles,select,color,section,button, …) next to its own code.defineControlskeeps a module's controls next to its JSON defaults and shares the live values with every instance. - Three (
@joycostudio/xyz/three) —Warmupdiscovers a scene's full renderable graph, exposes it long enough to push every texture/shader through the driver once, then restores every mutation exactly as it found it.
Features
| Feature | Description |
|---|---|
Keyed ownership (Derived) | Independent writers claim a slot by key; value resolves all current intents through one explicit policy. |
Transition sync (edge) | Turns a selector into a callback that only fires when the selected value actually changes. |
Asset routing (defineAssetSource) | Keeps source names at call sites while selecting one output from a Chopper-compatible optimization plan. |
Ordered teardown (Disposer) | Registrations unwind in reverse order; disposal is idempotent and safe to register into after teardown. |
| Declarative controls schema | slider, sliders, bool, toggles, select, text, color, colorString, section, button build a ControlsSchema with no Tweakpane import required. |
| JSON-backed definitions | defineControls({ defaults, schema }) checks schema keys against the module's JSON at compile time, holds the live values, and pushes every edit to each bound instance. |
| URL + keyboard activation | ControlsManager lazy-mounts the pane on ?debug or Option+D, and stays in sync with popstate. |
| Survives enable/disable | Registrations remount from fresh definitions every cycle — no stale bindings after a toggle. |
| Scene warmup | Warmup inventories geometries, materials, and textures (including TSL node graphs), pauses the driver, and forces one representative render before restoring visibility, culling, and draw ranges. |
| Late-resource auditing | audit() warns once per resource introduced after warmup — a throttled dev-only diagnostic, never a runtime upload. |
| No R3F dependency | The Three.js utilities are raw Three.js — bring your own renderer/canvas ownership split. |
Install
pnpm add @joycostudio/xyzthree, @tweakpane/core, and dialkit are optional peer dependencies — install three for /three, and tweakpane or dialkit for /controls.
defineAssetSource accepts Chopper's resolve function structurally, so Xyz does not require Chopper as a peer. Install @joycostudio/chopper in the consuming app when its config supplies the optimization plan.
Quick start
import { Derived, edge, maxOf } from '@joycostudio/xyz'
const blur = new Derived(0, maxOf)
blur.set('loader', 0.8)
blur.set('inspect', 0.35)
blur.value // 0.8
const syncPhase = edge(
(state: { phase: string }) => state.phase,
(next, previous) => console.log(previous, '→', next)
)Asset routing
import chopper from './chopper.config'
import { defineAssetSource } from '@joycostudio/xyz'
export const asset = defineAssetSource({
url: new URL('https://r2.joyco.studio/jam/'),
planner: chopper.resolve,
optimize: () =>
typeof window === 'undefined' || new URLSearchParams(window.location.search).get('compressed') !== 'false',
segments: {
common: 'common',
escapeFromHell: 'escape-from-hell',
},
})
asset.common('textures/noise.png')
// https://r2.joyco.studio/jam/common/textures/compressed/noise.webpThe planner sees the stable source key without its query or hash. Exactly one planned output is selected; unmatched, failed, or multi-output plans fall back to the source path.
Quick start (modules)
import { Module, ModuleHost } from '@joycostudio/xyz'
class Counter extends Module<{ step: number }> {
private count = 0
advance() {
this.emit('step', ++this.count)
}
}
class Application extends Module {
readonly counter = this.attach(new Counter())
mount() {
this.listen(this.counter, 'step', (count) => console.log(count))
}
}
const host = new ModuleHost({
ticker: { add: () => undefined }, // Supply your frame scheduler when modules tick.
defaultTickPriority: 0,
})
const app = host.mount(new Application())
app.counter.advance()
host.dispose() // Stops listeners and disposes children before their owner.Declare store selections with this.select(store, selector); the host shares one
subscription per store and calls sync() when selected values change. Stores only
need getState() and subscribe(); Zustand works directly without becoming an XYZ
runtime dependency. Tickers supply milliseconds, and module tick(dt, time) receives
seconds. Root modules choose priority; their children tick in ownership order.
host.inspect() returns detached ownership snapshots. host.subscribeActivity()
captures bounded event/state traces on demand. Hosts register themselves with an
inspector's MODULE_DEVTOOLS_HOOK, like React DevTools, in development and production,
with no app code; publishModuleTree, the older development-only iframe bridge, is deprecated. See the module reference
and inspection reference.
Use named ESM imports so unused exports can be removed. Core utilities do not
pull in the module runtime, inspector bridge, React, Tweakpane, or Three.js when
bundled on their own. ModuleHost includes its snapshot and activity methods;
activity recording starts only with a subscriber, in development and production.
The iframe bridge is removable independently of the runtime.
Quick start (controls)
// src/controls.ts — the one place the UI library is chosen (tweakpane or dialkit)
import { createControls, tweakpane } from '@joycostudio/xyz/controls'
export const controls = createControls(tweakpane(() => import('tweakpane')))// src/scene/bloom.ts — each module describes its own controls
import { sliders, toggles, type Controllable } from '@joycostudio/xyz/controls'
import type { controls } from '../controls'
export class Bloom implements Controllable<typeof controls> {
settings = { enabled: true, strength: 0.8 }
controls() {
return {
title: 'Bloom',
schema: () => ({
...toggles(this.settings, { enabled: {} }),
...sliders(this.settings, { strength: { min: 0, max: 3, step: 0.01 } }),
}),
}
}
}
// src/main.ts
controls.register(new Bloom())Open with ?debug in the URL, or press Option+D. To use DialKit instead, create controls with dialkit(() => import('dialkit/vanilla')) from @joycostudio/xyz/controls/dialkit; modules stay the same.
To keep a module's values in its JSON, define its controls once at module level with defineControls. Every instance binds to the definition and follows its live values:
import { defineControls, slider, color, type Controllable } from '@joycostudio/xyz/controls'
import { uniform } from 'three/tsl'
import defaults from './bloom.json' // { "strength": 1.2, "tint": "#ff8000" }
export const bloomControls = defineControls({
defaults,
schema: { strength: slider({ min: 0, max: 3, step: 0.01 }), tint: color() },
})
export class Bloom implements Controllable {
readonly strength = uniform(bloomControls.values.strength)
private readonly bound = bloomControls.bind(this)
controls() {
return { title: 'Bloom', schema: () => this.bound }
}
}See the defineControls reference. Coming from @joycostudio/xyz/debug? See migrating from debug.
Quick start (three)
import { Warmup } from '@joycostudio/xyz/three'
const warmup = new Warmup({
pause: () => (clock.running = false),
resume: () => (clock.running = true),
initTexture: (texture) => renderer.initTexture(texture),
compile: (scene, camera) => renderer.compileAsync(scene, camera),
render: () => renderer.render(scene, camera),
nextFrame: () => new Promise((resolve) => requestAnimationFrame(() => resolve())),
})
await warmup.start(scene, camera) // one representative frame, then the scene is restored
warmup.audit(scene) // dev-only: warns about resources introduced after warmupArchitecture
| Layer | Responsibility |
|---|---|
Core state (Derived, edge) | State resolution primitives with no DOM or rendering dependency. |
Module ownership (Module, ModuleHost) | Renderer-independent lifecycle, shared store subscriptions, typed events, and one ticker callback per root. |
| Definitions and assets | Literal-preserving configuration and pure source-to-CDN URL planning. |
| Disposer | An owner-local teardown stack shared by the controls and three layers (and your own code). |
Controls schema (schema.ts) | Pure ControlField/ControlsFolderDefinition builders — no Tweakpane import, fully testable in isolation. |
Controls binding (bind.ts) | Binds a ControlsFolderDefinition into a live FolderApi: tracks live-refresh fields, nested sections, and computed sources for copy. |
| ControlsManager | Owns URL/keyboard activation and lazy pane creation; registrations survive disable/enable and remount fresh. |
| Warmup orchestration | Warmup pauses the driver, runs registered Warmable.warmup() hooks, uploads textures, compiles, renders once, then restores everything in reverse — even on failure. |
Core API
State
| Export | Description |
|---|---|
Derived<In, Out> | .set(key, value) / .clear(key) claim or release a slot; .value resolves through combine. |
maxOf | Resolve to the highest active value, never lower than the fallback. |
latestOf | Resolve to the most recently claimed slot. |
edge(select, onChange, equals?) | Returns a sync function: runs select every call, onChange only when the result changes. |
Disposer | .add(teardown), .listen(target, type, fn, options?), .dispose() — reverse-order, idempotent. |
defineAssetSource(definition) | Create a callable CDN resolver with typed builders for every declared segment. |
Controls
| Export | Description |
|---|---|
createControls(adapter, options?) | Create the app's controls object. .register(module) / .bind(definition) add controls; ?debug or Option+D shows them. |
tweakpane(load) / dialkit(load) | The UI library to draw with. dialkit is in @joycostudio/xyz/controls/dialkit. |
Controllable<typeof controls> | A module with controls: controls() returns a title and a schema. |
defineControls({ defaults, schema }) | A module's controls at module level, typed against its JSON. .bind(target) keeps an instance in sync and returns its schema. |
property(obj, key, changed?) | A reference to an object property for a control to edit. |
slider / sliders | One bounded numeric control, or several from an object's numeric keys at once. |
bool / toggles | One boolean control, or several from an object's boolean keys at once. |
text | A single-line text input. |
select | One value out of a fixed set of strings or numbers. |
color / colorString | An RGB color object (such as a three.js Color), or a CSS color string. |
section | A nested, collapsible group of controls. |
button | An action, with optional feedback text. |
Three
| Export | Description |
|---|---|
Warmup | .add(entity) registers a Warmable; .start(scene, camera) runs once; .audit(scene); .dispose(). |
Warmable | Interface for entities whose render state isn't already in the scene — implement a synchronous or asynchronous warmup() hook. |
WarmupDriver | Renderer-owned hooks the caller supplies: pause, resume, initTexture, compile, render, nextFrame. |
Package exports
| Import path | Contents |
|---|---|
@joycostudio/xyz | Disposer, Derived, maxOf, latestOf, edge, defineAssetSource, and their types. |
@joycostudio/xyz | Module, ModuleHost, store/ticker contracts, ownership snapshots, and activity types. |
@joycostudio/xyz | publishModuleTree, inspector protocol constants, ModuleTree, and TreeMessage. |
@joycostudio/xyz/controls | ControlsManager, createControls, tweakpane, bindControls, ControlsHost, tweakpaneHost, isControlsHost, ref, property, slider, sliders, bool, toggles, select, text, color, colorString, hexColor, enumField, folder, section, button, schemaValues, defineControls, and their types. |
@joycostudio/xyz/controls/dialkit | dialkit, dialkitHost, and their types. Needs the optional dialkit peer dependency. |
@joycostudio/xyz/three | Warmup, discoverScene, and their types. |
Docs
The Fumadocs Core-backed site in apps/docs keeps its authored pages in apps/docs/content/docs as Markdown/MDX. The site shell uses the JOYCO UI kit, while the content embeds React examples from apps/docs/demos, including raw Three.js examples with no React Three Fiber dependency.
pnpm docsOpen the printed local URL and choose a concept from the catalog. Each page starts with a live demo and its actual source files in tabs directly underneath, followed by the API reference. Source is read from the same files that run the demo, including supporting files for multi-file examples. Register examples in apps/docs/lib/demos.ts and embed them with <DemoPreview name="…" />. The controls runtime page demonstrates ControlsManager, URL semantics, and Option+D handling, while the declarative schemas page collects the live Tweakpane helpers. Use pnpm docs:build to verify the production integration.
Authored flow and seq code fences render as server-rendered SVG diagrams using
Trazo. Add title="Description" after the fence
language for an accessible title. Trazo validates syntax during the docs build;
Markdown endpoints retain the original fences. Readers can expand and copy the
source, and wide graphs scroll without shrinking their labels. Diagram colors
follow the site theme through CSS, without a client-side diagram renderer.
Development
pnpm install
pnpm test # Vitest suite (run); pnpm test:watch for watch mode
pnpm typecheck # tsc --noEmit, plus the docs app
pnpm build # tsup bundles for core, modules, controls, and three
pnpm lint # eslint --fixReleases go through Changesets:
pnpm changeset # describe the change and bump type in a feature PRAfter the feature PR merges, the Release workflow creates or updates Version Packages; merging that generated PR triggers publication. Beta releases use the same flow with Changesets prerelease mode. Follow the release guide; versioning and publishing commands are reserved for GitHub Actions.