@codexo/exojs-react 0.19.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/esm/ExoCanvas.d.ts +1 -1
- package/dist/esm/ExoCanvas.d.ts.map +1 -1
- package/dist/esm/ExoCanvas.js +3 -4
- package/dist/esm/ExoCanvas.js.map +1 -1
- package/dist/esm/ExoContext.d.ts.map +1 -1
- package/dist/esm/ExoContext.js +1 -2
- package/dist/esm/Scenes.d.ts +5 -3
- package/dist/esm/Scenes.d.ts.map +1 -1
- package/dist/esm/Scenes.js +24 -10
- package/dist/esm/Scenes.js.map +1 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +3 -3
- package/dist/esm/useExoApp.d.ts.map +1 -1
- package/dist/esm/useExoApp.js +1 -2
- package/dist/esm/useExoApplication.d.ts +7 -6
- package/dist/esm/useExoApplication.d.ts.map +1 -1
- package/dist/esm/useExoApplication.js +39 -22
- package/dist/esm/useExoApplication.js.map +1 -1
- package/dist/esm/useScene.d.ts.map +1 -1
- package/dist/esm/useScene.js +13 -3
- package/dist/esm/useScene.js.map +1 -1
- package/dist/esm/useSignal.d.ts +4 -1
- package/dist/esm/useSignal.d.ts.map +1 -1
- package/dist/esm/useSignal.js +5 -3
- package/dist/esm/useSignal.js.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -102,7 +102,7 @@ These are alternative hosting patterns, not two components to mount for one appl
|
|
|
102
102
|
|
|
103
103
|
### Reactivity model
|
|
104
104
|
|
|
105
|
-
The `Application` is
|
|
105
|
+
The `Application` is created when the canvas attaches and recreated when that element or the render `backend` changes (WebGL2 and WebGPU cannot be hot-swapped). Detaching the canvas destroys the application. Other supported options are applied **live**:
|
|
106
106
|
|
|
107
107
|
- `canvas.width` / `canvas.height` → `app.resize(...)`
|
|
108
108
|
- `clearColor` → `app.clearColor`
|
package/dist/esm/ExoCanvas.d.ts
CHANGED
|
@@ -47,5 +47,5 @@ export interface ExoCanvasProps extends HTMLAttributes<HTMLDivElement> {
|
|
|
47
47
|
* </ExoCanvas>
|
|
48
48
|
* ```
|
|
49
49
|
*/
|
|
50
|
-
export declare
|
|
50
|
+
export declare const ExoCanvas: ({ options, onReady, onError, canvasProps, children, style, ...divProps }: ExoCanvasProps) => ReactElement;
|
|
51
51
|
//# sourceMappingURL=ExoCanvas.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExoCanvas.d.ts","
|
|
1
|
+
{"version":3,"file":"ExoCanvas.d.ts","sources":["../../src/ExoCanvas.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,KAAK,oBAAoB,EAAsB,KAAK,cAAc,EAAE,KAAK,YAAY,EAAE,MAAM,OAAO,CAAC;AAG9G,OAAO,EAAE,KAAK,qBAAqB,EAAqB,MAAM,qBAAqB,CAAC;AAKpF,MAAM,WAAW,cAAe,SAAQ,cAAc,CAAC,cAAc,CAAC;IACpE;;;;;OAKG;IACH,OAAO,CAAC,EAAE,qBAAqB,CAAC;IAChC;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,IAAI,CAAC;IACrC;;;;;OAKG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACnC;;;OAGG;IACH,WAAW,CAAC,EAAE,IAAI,CAAC,oBAAoB,CAAC,iBAAiB,CAAC,EAAE,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAC,CAAC;CACzF;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,SAAS,6EAA8E,cAAc,KAAG,YAepH,CAAC"}
|
package/dist/esm/ExoCanvas.js
CHANGED
|
@@ -3,7 +3,7 @@ import { useExoApplication } from "./useExoApplication.js";
|
|
|
3
3
|
import "react";
|
|
4
4
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
// src/ExoCanvas.tsx
|
|
7
7
|
/** Default canvas style: block layout avoids the inline-element baseline gap. */
|
|
8
8
|
const defaultCanvasStyle = { display: "block" };
|
|
9
9
|
/**
|
|
@@ -25,7 +25,7 @@ const defaultCanvasStyle = { display: "block" };
|
|
|
25
25
|
* </ExoCanvas>
|
|
26
26
|
* ```
|
|
27
27
|
*/
|
|
28
|
-
|
|
28
|
+
const ExoCanvas = ({ options, onReady, onError, canvasProps, children, style, ...divProps }) => {
|
|
29
29
|
const { app, canvasRef } = useExoApplication(options, onReady, onError);
|
|
30
30
|
const { style: canvasStyle, ...restCanvasProps } = canvasProps ?? {};
|
|
31
31
|
const wrapperStyle = {
|
|
@@ -48,8 +48,7 @@ function ExoCanvas({ options, onReady, onError, canvasProps, children, style, ..
|
|
|
48
48
|
}), app !== null && children]
|
|
49
49
|
})
|
|
50
50
|
});
|
|
51
|
-
}
|
|
51
|
+
};
|
|
52
52
|
|
|
53
|
-
//#endregion
|
|
54
53
|
export { ExoCanvas };
|
|
55
54
|
//# sourceMappingURL=ExoCanvas.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExoCanvas.js","names":[],"sources":["../../src/ExoCanvas.tsx"],"sourcesContent":["import type { Application } from '@codexo/exojs';\nimport { type CanvasHTMLAttributes, type CSSProperties, type HTMLAttributes, type ReactElement } from 'react';\n\nimport { ExoContext } from './ExoContext';\nimport { type ExoApplicationOptions, useExoApplication } from './useExoApplication';\n\n/** Default canvas style: block layout avoids the inline-element baseline gap. */\nconst defaultCanvasStyle: CSSProperties = { display: 'block' };\n\nexport interface ExoCanvasProps extends HTMLAttributes<HTMLDivElement> {\n /**\n * Options forwarded to the ExoJS {@link Application}. Pass\n * `canvas.width`/`height`/`sizing`/etc.; most options are captured at\n * creation, but `canvas.width`/`height` and `clearColor` are applied live\n * (see {@link useExoApplication}).\n */\n options?: ExoApplicationOptions;\n /**\n * Called once each time the {@link Application} is (re)created. The backend\n * (WebGL2 / WebGPU) is not yet initialized at this point - that happens when\n * the first {@link import('./useScene').useScene} child calls `app.start()`.\n */\n onReady?: (app: Application) => void;\n /**\n * Called for every {@link Application.onError} dispatch - async init or\n * scene-load failures (including the ones surfaced by\n * {@link import('./useScene').useScene} and {@link import('./Scenes').Scenes}\n * descendants) - while an Application exists.\n */\n onError?: (error: unknown) => void;\n /**\n * Props forwarded to the inner `<canvas>` (e.g. its own `style`/`className`).\n * `ref`, `width` and `height` are managed by the engine and cannot be set.\n */\n canvasProps?: Omit<CanvasHTMLAttributes<HTMLCanvasElement>, 'ref' | 'width' | 'height'>;\n}\n\n/**\n * Batteries-included canvas host. Renders a **positioned wrapper `<div>`**\n * containing a React-managed `<canvas>` bound to an ExoJS {@link Application},\n * and provides the app to descendant hooks via context. Because the wrapper is\n * `position: relative`, absolutely-positioned `children` (HUD overlays,\n * {@link import('./Scenes').Scenes}) sit over the canvas out of the box.\n *\n * Layout props (`style`, `className`, ...) apply to the **wrapper**, which is\n * the element a `canvas.sizing` policy measures - size it to size the canvas.\n * Use {@link canvasProps} to style the canvas itself. For full control with no\n * wrapper element, use the headless {@link useExoApplication} hook directly.\n *\n * @example\n * ```tsx\n * <ExoCanvas options={{ canvas: { width: 800, height: 600 } }} style={{ width: 800, height: 600 }}>\n * <Hud /> // absolutely-positioned overlay; works because the wrapper is relative\n * </ExoCanvas>\n * ```\n */\nexport
|
|
1
|
+
{"version":3,"file":"ExoCanvas.js","names":[],"sources":["../../src/ExoCanvas.tsx"],"sourcesContent":["import type { Application } from '@codexo/exojs';\nimport { type CanvasHTMLAttributes, type CSSProperties, type HTMLAttributes, type ReactElement } from 'react';\n\nimport { ExoContext } from './ExoContext';\nimport { type ExoApplicationOptions, useExoApplication } from './useExoApplication';\n\n/** Default canvas style: block layout avoids the inline-element baseline gap. */\nconst defaultCanvasStyle: CSSProperties = { display: 'block' };\n\nexport interface ExoCanvasProps extends HTMLAttributes<HTMLDivElement> {\n /**\n * Options forwarded to the ExoJS {@link Application}. Pass\n * `canvas.width`/`height`/`sizing`/etc.; most options are captured at\n * creation, but `canvas.width`/`height` and `clearColor` are applied live\n * (see {@link useExoApplication}).\n */\n options?: ExoApplicationOptions;\n /**\n * Called once each time the {@link Application} is (re)created. The backend\n * (WebGL2 / WebGPU) is not yet initialized at this point - that happens when\n * the first {@link import('./useScene').useScene} child calls `app.start()`.\n */\n onReady?: (app: Application) => void;\n /**\n * Called for every {@link Application.onError} dispatch - async init or\n * scene-load failures (including the ones surfaced by\n * {@link import('./useScene').useScene} and {@link import('./Scenes').Scenes}\n * descendants) - while an Application exists.\n */\n onError?: (error: unknown) => void;\n /**\n * Props forwarded to the inner `<canvas>` (e.g. its own `style`/`className`).\n * `ref`, `width` and `height` are managed by the engine and cannot be set.\n */\n canvasProps?: Omit<CanvasHTMLAttributes<HTMLCanvasElement>, 'ref' | 'width' | 'height'>;\n}\n\n/**\n * Batteries-included canvas host. Renders a **positioned wrapper `<div>`**\n * containing a React-managed `<canvas>` bound to an ExoJS {@link Application},\n * and provides the app to descendant hooks via context. Because the wrapper is\n * `position: relative`, absolutely-positioned `children` (HUD overlays,\n * {@link import('./Scenes').Scenes}) sit over the canvas out of the box.\n *\n * Layout props (`style`, `className`, ...) apply to the **wrapper**, which is\n * the element a `canvas.sizing` policy measures - size it to size the canvas.\n * Use {@link canvasProps} to style the canvas itself. For full control with no\n * wrapper element, use the headless {@link useExoApplication} hook directly.\n *\n * @example\n * ```tsx\n * <ExoCanvas options={{ canvas: { width: 800, height: 600 } }} style={{ width: 800, height: 600 }}>\n * <Hud /> // absolutely-positioned overlay; works because the wrapper is relative\n * </ExoCanvas>\n * ```\n */\nexport const ExoCanvas = ({ options, onReady, onError, canvasProps, children, style, ...divProps }: ExoCanvasProps): ReactElement => {\n const { app, canvasRef } = useExoApplication(options, onReady, onError);\n\n const { style: canvasStyle, ...restCanvasProps } = canvasProps ?? {};\n const wrapperStyle: CSSProperties = { position: 'relative', ...style };\n const mergedCanvasStyle: CSSProperties = { ...defaultCanvasStyle, ...canvasStyle };\n\n return (\n <ExoContext.Provider value={app}>\n <div style={wrapperStyle} {...divProps}>\n <canvas ref={canvasRef} style={mergedCanvasStyle} {...restCanvasProps} />\n {app !== null && children}\n </div>\n </ExoContext.Provider>\n );\n};\n"],"mappings":";;;;;;;AAOA,MAAM,qBAAoC,EAAE,SAAS,QAAQ;;;;;;;;;;;;;;;;;;;;AAiD7D,MAAa,aAAa,EAAE,SAAS,SAAS,SAAS,aAAa,UAAU,OAAO,GAAG,eAA6C;CACnI,MAAM,EAAE,KAAK,cAAc,kBAAkB,SAAS,SAAS,OAAO;CAEtE,MAAM,EAAE,OAAO,aAAa,GAAG,oBAAoB,eAAe,CAAC;CACnE,MAAM,eAA8B;EAAE,UAAU;EAAY,GAAG;CAAM;CACrE,MAAM,oBAAmC;EAAE,GAAG;EAAoB,GAAG;CAAY;CAEjF,OACE,oBAAC,WAAW,UAAZ;EAAqB,OAAO;YAC1B,qBAAC,OAAD;GAAK,OAAO;GAAc,GAAI;aAA9B,CACE,oBAAC,UAAD;IAAQ,KAAK;IAAW,OAAO;IAAmB,GAAI;GAAkB,IACvE,QAAQ,QAAQ,QACd;;CACc;AAEzB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExoContext.d.ts","
|
|
1
|
+
{"version":3,"file":"ExoContext.d.ts","sources":["../../src/ExoContext.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGjD;;;;;GAKG;AACH,eAAO,MAAM,UAAU,iDAA0C,CAAC;AAGlE;;;;;GAKG;AACH,eAAO,MAAM,aAAa,QAAO,WAAW,GAAG,IAA8B,CAAC"}
|
package/dist/esm/ExoContext.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createContext, useContext } from "react";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// src/ExoContext.ts
|
|
4
4
|
/**
|
|
5
5
|
* Internal React context that carries the active {@link Application} instance
|
|
6
6
|
* created by {@link ExoCanvas}. Consumers should use the {@link useExoApp}
|
|
@@ -17,6 +17,5 @@ ExoContext.displayName = "ExoContext";
|
|
|
17
17
|
*/
|
|
18
18
|
const useExoContext = () => useContext(ExoContext);
|
|
19
19
|
|
|
20
|
-
//#endregion
|
|
21
20
|
export { ExoContext, useExoContext };
|
|
22
21
|
//# sourceMappingURL=ExoContext.js.map
|
package/dist/esm/Scenes.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ export interface SceneProps {
|
|
|
34
34
|
* {@link Scenes} reads its props and renders its {@link SceneProps.children} only
|
|
35
35
|
* while the scene is active.
|
|
36
36
|
*/
|
|
37
|
-
export declare
|
|
37
|
+
export declare const Scene: (_props: SceneProps) => ReactElement | null;
|
|
38
38
|
/** Props for the {@link Scenes} switch. */
|
|
39
39
|
export interface ScenesProps {
|
|
40
40
|
/** Name of the active {@link Scene}. Changing it switches scenes. */
|
|
@@ -46,7 +46,9 @@ export interface ScenesProps {
|
|
|
46
46
|
}
|
|
47
47
|
/**
|
|
48
48
|
* Declarative scene switch over the one-active-scene model. Renders a set of
|
|
49
|
-
* {@link Scene} declarations
|
|
49
|
+
* {@link Scene} declarations - collected from this component's direct children
|
|
50
|
+
* only, so a fragment or wrapper element hides them - and activates the one
|
|
51
|
+
* whose `name` equals `active`
|
|
50
52
|
* via `app.start()` (first activation) or `app.scenes.change()` (subsequent
|
|
51
53
|
* switches, with the optional `transition`) - the declaration's `component`
|
|
52
54
|
* constructor must be registered in `ApplicationOptions.scenes`. The active
|
|
@@ -79,5 +81,5 @@ export interface ScenesProps {
|
|
|
79
81
|
* </ExoCanvas>
|
|
80
82
|
* ```
|
|
81
83
|
*/
|
|
82
|
-
export declare
|
|
84
|
+
export declare const Scenes: ({ active, transition, children }: ScenesProps) => ReactElement;
|
|
83
85
|
//# sourceMappingURL=Scenes.d.ts.map
|
package/dist/esm/Scenes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GED
|
@@ -3,7 +3,7 @@ import { Children, createContext, isValidElement, useContext, useEffect, useMemo
|
|
|
3
3
|
import { ApplicationState } from "@codexo/exojs";
|
|
4
4
|
import { jsx } from "react/jsx-runtime";
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
// src/Scenes.tsx
|
|
7
7
|
/** Carries the active {@link ExoScene} instance to descendants (HUD overlays). */
|
|
8
8
|
const ActiveSceneContext = createContext(null);
|
|
9
9
|
ActiveSceneContext.displayName = "ExoActiveScene";
|
|
@@ -17,12 +17,12 @@ function useActiveScene(SceneClass) {
|
|
|
17
17
|
* {@link Scenes} reads its props and renders its {@link SceneProps.children} only
|
|
18
18
|
* while the scene is active.
|
|
19
19
|
*/
|
|
20
|
-
|
|
21
|
-
return null;
|
|
22
|
-
}
|
|
20
|
+
const Scene = (_props) => null;
|
|
23
21
|
/**
|
|
24
22
|
* Declarative scene switch over the one-active-scene model. Renders a set of
|
|
25
|
-
* {@link Scene} declarations
|
|
23
|
+
* {@link Scene} declarations - collected from this component's direct children
|
|
24
|
+
* only, so a fragment or wrapper element hides them - and activates the one
|
|
25
|
+
* whose `name` equals `active`
|
|
26
26
|
* via `app.start()` (first activation) or `app.scenes.change()` (subsequent
|
|
27
27
|
* switches, with the optional `transition`) - the declaration's `component`
|
|
28
28
|
* constructor must be registered in `ApplicationOptions.scenes`. The active
|
|
@@ -55,10 +55,11 @@ function Scene(_props) {
|
|
|
55
55
|
* </ExoCanvas>
|
|
56
56
|
* ```
|
|
57
57
|
*/
|
|
58
|
-
|
|
58
|
+
const Scenes = ({ active, transition, children }) => {
|
|
59
59
|
const app = useExoApp();
|
|
60
60
|
const [instance, setInstance] = useState(null);
|
|
61
61
|
const generationRef = useRef(0);
|
|
62
|
+
const navigationRef = useRef(/* @__PURE__ */ new WeakMap());
|
|
62
63
|
const entry = useMemo(() => {
|
|
63
64
|
const map = /* @__PURE__ */ new Map();
|
|
64
65
|
Children.forEach(children, (child) => {
|
|
@@ -80,8 +81,14 @@ function Scenes({ active, transition, children }) {
|
|
|
80
81
|
let cancelled = false;
|
|
81
82
|
const isStale = () => cancelled || generationRef.current !== generation;
|
|
82
83
|
const changeOptions = transition !== void 0 ? { transition } : {};
|
|
84
|
+
const previous = navigationRef.current.get(app);
|
|
85
|
+
const joiningStartup = app.state === ApplicationState.Loading;
|
|
83
86
|
const apply = async () => {
|
|
84
87
|
try {
|
|
88
|
+
if (previous !== void 0 && !joiningStartup) {
|
|
89
|
+
await previous;
|
|
90
|
+
if (isStale()) return;
|
|
91
|
+
}
|
|
85
92
|
if (app.state === ApplicationState.Stopped || app.state === ApplicationState.Loading) {
|
|
86
93
|
await app.start(SceneClass);
|
|
87
94
|
if (isStale()) return;
|
|
@@ -92,18 +99,25 @@ function Scenes({ active, transition, children }) {
|
|
|
92
99
|
if (!isStale()) app.onError.dispatch(error instanceof Error ? error : new Error(String(error)));
|
|
93
100
|
}
|
|
94
101
|
};
|
|
95
|
-
apply();
|
|
102
|
+
const navigation = apply();
|
|
103
|
+
navigationRef.current.set(app, navigation);
|
|
104
|
+
navigation.then(() => {
|
|
105
|
+
if (navigationRef.current.get(app) === navigation) navigationRef.current.delete(app);
|
|
106
|
+
});
|
|
96
107
|
return () => {
|
|
97
108
|
cancelled = true;
|
|
98
109
|
setInstance(null);
|
|
99
110
|
};
|
|
100
|
-
}, [
|
|
111
|
+
}, [
|
|
112
|
+
app,
|
|
113
|
+
active,
|
|
114
|
+
SceneClass
|
|
115
|
+
]);
|
|
101
116
|
return /* @__PURE__ */ jsx(ActiveSceneContext.Provider, {
|
|
102
117
|
value: instance,
|
|
103
118
|
children: instance !== null && entry?.children
|
|
104
119
|
});
|
|
105
|
-
}
|
|
120
|
+
};
|
|
106
121
|
|
|
107
|
-
//#endregion
|
|
108
122
|
export { Scene, Scenes, useActiveScene };
|
|
109
123
|
//# sourceMappingURL=Scenes.js.map
|
package/dist/esm/Scenes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Scenes.js","names":[],"sources":["../../src/Scenes.tsx"],"sourcesContent":["import { ApplicationState, type Scene as ExoScene, type SceneTransitionSelection } from '@codexo/exojs';\nimport { Children, createContext, isValidElement, type ReactElement, type ReactNode, useContext, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { useExoApp } from './useExoApp';\n\n/** Carries the active {@link ExoScene} instance to descendants (HUD overlays). */\nconst ActiveSceneContext = createContext<ExoScene | null>(null);\nActiveSceneContext.displayName = 'ExoActiveScene';\n\n/**\n * Returns the currently-active scene instance from the nearest {@link Scenes},\n * or `null` while none is live. Useful for HUD/overlay components that need to\n * read scene state.\n *\n * Pass a scene class to narrow the result: the active scene is returned only\n * when it is an instance of `SceneClass` (checked with `instanceof` at\n * runtime), and `null` otherwise.\n *\n * @example\n * ```tsx\n * function Hud() {\n * const scene = useActiveScene(GameScene);\n * if (scene === null) return null;\n * return <div>Score: {scene.score}</div>;\n * }\n * ```\n */\nexport function useActiveScene(): ExoScene | null;\nexport function useActiveScene<T extends ExoScene>(SceneClass: abstract new (...args: never[]) => T): T | null;\nexport function useActiveScene<T extends ExoScene>(SceneClass?: abstract new (...args: never[]) => T): ExoScene | null {\n const scene = useContext(ActiveSceneContext);\n\n if (SceneClass === undefined) {\n return scene;\n }\n\n return scene instanceof SceneClass ? scene : null;\n}\n\n/** Props for a {@link Scene} declaration. */\nexport interface SceneProps {\n /** Unique name used to select this scene via {@link ScenesProps.active}. */\n readonly name: string;\n /** Scene class to instantiate when this scene becomes active. */\n readonly component: new () => ExoScene;\n /** React overlay (HUD) rendered only while this scene is active. */\n readonly children?: ReactNode;\n}\n\n/**\n * Declares one scene inside a {@link Scenes} switch. Renders nothing on its own -\n * {@link Scenes} reads its props and renders its {@link SceneProps.children} only\n * while the scene is active.\n */\nexport function Scene(_props: SceneProps): ReactElement | null {\n return null;\n}\n\n/** Props for the {@link Scenes} switch. */\nexport interface ScenesProps {\n /** Name of the active {@link Scene}. Changing it switches scenes. */\n readonly active: string;\n /** Optional transition (e.g. a `FadeSceneTransition`) applied when switching scenes. */\n readonly transition?: SceneTransitionSelection;\n /** {@link Scene} declarations. */\n readonly children?: ReactNode;\n}\n\n/**\n * Declarative scene switch over the one-active-scene model. Renders a set of\n * {@link Scene} declarations and activates the one whose `name` equals `active`\n * via `app.start()` (first activation) or `app.scenes.change()` (subsequent\n * switches, with the optional `transition`) - the declaration's `component`\n * constructor must be registered in `ApplicationOptions.scenes`. The active\n * scene's React children (HUD overlay) render alongside, and can read the\n * instance via {@link useActiveScene}.\n *\n * Activations that run while startup is still in flight - React StrictMode\n * double-mounts every effect in development, and `active` may change before\n * the first scene has loaded - join that `app.start()` call instead of racing\n * a second navigation against it, and only switch afterwards if startup did\n * not already leave the requested scene active. A StrictMode double mount\n * therefore activates the scene exactly once.\n *\n * A failure in `app.start()`/`app.scenes.change()` (e.g. a scene's `load()`\n * rejects) is caught and routed to {@link Application.onError} rather than\n * left as an unhandled promise rejection - subscribe via `app.onError.add(...)`\n * or the {@link import('./ExoCanvas').ExoCanvas} `onError` prop to observe it.\n *\n * @example\n * ```tsx\n * import { FadeSceneTransition } from '@codexo/exojs';\n *\n * <ExoCanvas>\n * <Scenes active={screen} transition={new FadeSceneTransition({ duration: 300 })}>\n * <Scene name=\"title\" component={TitleScene} />\n * <Scene name=\"game\" component={GameScene}>\n * <Hud />\n * </Scene>\n * </Scenes>\n * </ExoCanvas>\n * ```\n */\nexport function Scenes({ active, transition, children }: ScenesProps): ReactElement {\n const app = useExoApp();\n const [instance, setInstance] = useState<ExoScene | null>(null);\n // Bumped on every effect run so an async activation can tell whether a newer\n // run has taken over since it started.\n const generationRef = useRef(0);\n\n // Collect the <Scene> declarations from children (keyed by name).\n const registry = useMemo(() => {\n const map = new Map<string, SceneProps>();\n Children.forEach(children, child => {\n if (isValidElement(child) && child.type === Scene) {\n const props = child.props as SceneProps;\n map.set(props.name, props);\n }\n });\n return map;\n }, [children]);\n\n const entry = registry.get(active);\n const SceneClass = entry?.component ?? null;\n\n useEffect(() => {\n const generation = ++generationRef.current;\n\n if (SceneClass === null) {\n // No matching <Scene name={active}> declaration. No public API switches\n // the director back to scene-less mid-lifetime - the\n // last-active scene keeps running underneath; only the React-rendered\n // HUD overlay is cleared. This is a caller mismatch (an `active` name\n // with no matching <Scene>), not a supported \"show nothing\" path.\n console.warn(`<Scenes>: no <Scene name=\"${active}\"> declaration found; the previously active scene (if any) keeps running.`);\n setInstance(null);\n return;\n }\n\n let cancelled = false;\n // Only the newest, still-mounted run may touch component or app state: an\n // older run's activation is no longer what the caller asked for, and\n // neither is its failure.\n const isStale = (): boolean => cancelled || generationRef.current !== generation;\n const changeOptions = transition !== undefined ? { transition } : {};\n\n const apply = async (): Promise<void> => {\n try {\n if (app.state === ApplicationState.Stopped || app.state === ApplicationState.Loading) {\n // Loading means an earlier run's start() is still in flight,\n // including its initial navigation, which scenes.change() would\n // collide with (navigation rejects instead of queueing). start()\n // joins that run and ignores the target passed here. Transitions\n // only apply to switches, never to the first activation.\n await app.start(SceneClass);\n\n if (isStale()) {\n return;\n }\n\n // Exact class comparison rather than instanceof: one declared scene\n // may subclass another, and startup must not count as having\n // activated the base when it activated the subclass.\n if (app.scenes.currentScene?.constructor !== SceneClass) {\n await app.scenes.change(SceneClass, changeOptions);\n }\n } else {\n await app.scenes.change(SceneClass, changeOptions);\n }\n\n if (!isStale()) {\n setInstance(app.scenes.currentScene);\n }\n } catch (error) {\n // Route to Application.onError instead of leaving an unhandled\n // rejection - app.start()/change() reject rather than dispatching\n // onError themselves.\n if (!isStale()) {\n app.onError.dispatch(error instanceof Error ? error : new Error(String(error)));\n }\n }\n };\n\n void apply();\n\n return () => {\n cancelled = true;\n setInstance(null);\n };\n // Re-activate when the active name changes. SceneClass/transition derive\n // from `active`; keying on app + active avoids re-instantiating each render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [app, active]);\n\n return <ActiveSceneContext.Provider value={instance}>{instance !== null && entry?.children}</ActiveSceneContext.Provider>;\n}\n"],"mappings":";;;;;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O,YAAY,aAAa;IAErD,OACE,MAAM,IAAI,OAAO,OAAO,YAAY,aAAa;IAGnD,IAAI,CAAC,QAAQ,GACX,YAAY,IAAI,OAAO,YAAY;GAEvC,SAAS,OAAO;IAId,IAAI,CAAC,QAAQ,GACX,IAAI,QAAQ,SAAS,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;GAElF;EACF;EAEA,AAAK,MAAM;EAEX,aAAa;GACX,YAAY;GACZ,YAAY,IAAI;EAClB;CAIF,GAAG,CAAC,KAAK,MAAM,CAAC;CAEhB,OAAO,oBAAC,mBAAmB,UAApB;EAA6B,OAAO;YAAW,aAAa,QAAQ,OAAO;CAAsC;AAC1H"}
|
|
1
|
+
{"version":3,"file":"Scenes.js","names":[],"sources":["../../src/Scenes.tsx"],"sourcesContent":["import { ApplicationState, type Scene as ExoScene, type SceneTransitionSelection } from '@codexo/exojs';\nimport {\n Children,\n createContext,\n isValidElement,\n type ReactElement,\n type ReactNode,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nimport { useExoApp } from './useExoApp';\n\n/** Carries the active {@link ExoScene} instance to descendants (HUD overlays). */\nconst ActiveSceneContext = createContext<ExoScene | null>(null);\nActiveSceneContext.displayName = 'ExoActiveScene';\n\n/**\n * Returns the currently-active scene instance from the nearest {@link Scenes},\n * or `null` while none is live. Useful for HUD/overlay components that need to\n * read scene state.\n *\n * Pass a scene class to narrow the result: the active scene is returned only\n * when it is an instance of `SceneClass` (checked with `instanceof` at\n * runtime), and `null` otherwise.\n *\n * @example\n * ```tsx\n * function Hud() {\n * const scene = useActiveScene(GameScene);\n * if (scene === null) return null;\n * return <div>Score: {scene.score}</div>;\n * }\n * ```\n */\nexport function useActiveScene(): ExoScene | null;\nexport function useActiveScene<T extends ExoScene>(SceneClass: abstract new (...args: never[]) => T): T | null;\n\nexport function useActiveScene<T extends ExoScene>(SceneClass?: abstract new (...args: never[]) => T): ExoScene | null {\n const scene = useContext(ActiveSceneContext);\n\n if (SceneClass === undefined) {\n return scene;\n }\n\n return scene instanceof SceneClass ? scene : null;\n}\n\n/** Props for a {@link Scene} declaration. */\nexport interface SceneProps {\n /** Unique name used to select this scene via {@link ScenesProps.active}. */\n readonly name: string;\n /** Scene class to instantiate when this scene becomes active. */\n readonly component: new () => ExoScene;\n /** React overlay (HUD) rendered only while this scene is active. */\n readonly children?: ReactNode;\n}\n\n/**\n * Declares one scene inside a {@link Scenes} switch. Renders nothing on its own -\n * {@link Scenes} reads its props and renders its {@link SceneProps.children} only\n * while the scene is active.\n */\nexport const Scene = (_props: SceneProps): ReactElement | null => null;\n\n/** Props for the {@link Scenes} switch. */\nexport interface ScenesProps {\n /** Name of the active {@link Scene}. Changing it switches scenes. */\n readonly active: string;\n /** Optional transition (e.g. a `FadeSceneTransition`) applied when switching scenes. */\n readonly transition?: SceneTransitionSelection;\n /** {@link Scene} declarations. */\n readonly children?: ReactNode;\n}\n\n/**\n * Declarative scene switch over the one-active-scene model. Renders a set of\n * {@link Scene} declarations - collected from this component's direct children\n * only, so a fragment or wrapper element hides them - and activates the one\n * whose `name` equals `active`\n * via `app.start()` (first activation) or `app.scenes.change()` (subsequent\n * switches, with the optional `transition`) - the declaration's `component`\n * constructor must be registered in `ApplicationOptions.scenes`. The active\n * scene's React children (HUD overlay) render alongside, and can read the\n * instance via {@link useActiveScene}.\n *\n * Activations that run while startup is still in flight - React StrictMode\n * double-mounts every effect in development, and `active` may change before\n * the first scene has loaded - join that `app.start()` call instead of racing\n * a second navigation against it, and only switch afterwards if startup did\n * not already leave the requested scene active. A StrictMode double mount\n * therefore activates the scene exactly once.\n *\n * A failure in `app.start()`/`app.scenes.change()` (e.g. a scene's `load()`\n * rejects) is caught and routed to {@link Application.onError} rather than\n * left as an unhandled promise rejection - subscribe via `app.onError.add(...)`\n * or the {@link import('./ExoCanvas').ExoCanvas} `onError` prop to observe it.\n *\n * @example\n * ```tsx\n * import { FadeSceneTransition } from '@codexo/exojs';\n *\n * <ExoCanvas>\n * <Scenes active={screen} transition={new FadeSceneTransition({ duration: 300 })}>\n * <Scene name=\"title\" component={TitleScene} />\n * <Scene name=\"game\" component={GameScene}>\n * <Hud />\n * </Scene>\n * </Scenes>\n * </ExoCanvas>\n * ```\n */\nexport const Scenes = ({ active, transition, children }: ScenesProps): ReactElement => {\n const app = useExoApp();\n const [instance, setInstance] = useState<ExoScene | null>(null);\n // Bumped on every effect run so an async activation can tell whether a newer\n // run has taken over since it started.\n const generationRef = useRef(0);\n const navigationRef = useRef(new WeakMap<typeof app, Promise<void>>());\n\n // Collect the <Scene> declarations from children (keyed by name).\n const registry = useMemo(() => {\n const map = new Map<string, SceneProps>();\n Children.forEach(children, child => {\n if (isValidElement(child) && child.type === Scene) {\n const props = child.props as SceneProps;\n map.set(props.name, props);\n }\n });\n\n return map;\n }, [children]);\n\n const entry = registry.get(active);\n const SceneClass = entry?.component ?? null;\n\n useEffect(() => {\n const generation = ++generationRef.current;\n\n if (SceneClass === null) {\n // No matching <Scene name={active}> declaration. No public API switches\n // the director back to scene-less mid-lifetime - the\n // last-active scene keeps running underneath; only the React-rendered\n // HUD overlay is cleared. This is a caller mismatch (an `active` name\n // with no matching <Scene>), not a supported \"show nothing\" path.\n console.warn(`<Scenes>: no <Scene name=\"${active}\"> declaration found; the previously active scene (if any) keeps running.`);\n setInstance(null);\n\n return;\n }\n\n let cancelled = false;\n // Only the newest, still-mounted run may touch component or app state: an\n // older run's activation is no longer what the caller asked for, and\n // neither is its failure.\n const isStale = (): boolean => cancelled || generationRef.current !== generation;\n const changeOptions = transition !== undefined ? { transition } : {};\n\n const previous = navigationRef.current.get(app);\n const joiningStartup = app.state === ApplicationState.Loading;\n\n const apply = async (): Promise<void> => {\n try {\n if (previous !== undefined && !joiningStartup) {\n await previous;\n\n if (isStale()) {\n return;\n }\n }\n\n if (app.state === ApplicationState.Stopped || app.state === ApplicationState.Loading) {\n // Loading means an earlier run's start() is still in flight,\n // including its initial navigation, which scenes.change() would\n // collide with (navigation rejects instead of queueing). start()\n // joins that run and ignores the target passed here. Transitions\n // only apply to switches, never to the first activation.\n await app.start(SceneClass);\n\n if (isStale()) {\n return;\n }\n\n // Exact class comparison rather than instanceof: one declared scene\n // may subclass another, and startup must not count as having\n // activated the base when it activated the subclass.\n if (app.scenes.currentScene?.constructor !== SceneClass) {\n await app.scenes.change(SceneClass, changeOptions);\n }\n } else {\n await app.scenes.change(SceneClass, changeOptions);\n }\n\n if (!isStale()) {\n setInstance(app.scenes.currentScene);\n }\n } catch (error) {\n // Route to Application.onError instead of leaving an unhandled\n // rejection - app.start()/change() reject rather than dispatching\n // onError themselves.\n if (!isStale()) {\n app.onError.dispatch(error instanceof Error ? error : new Error(String(error)));\n }\n }\n };\n\n const navigation = apply();\n navigationRef.current.set(app, navigation);\n void navigation.then(() => {\n if (navigationRef.current.get(app) === navigation) {\n navigationRef.current.delete(app);\n }\n });\n\n return () => {\n cancelled = true;\n setInstance(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [app, active, SceneClass]);\n\n return <ActiveSceneContext.Provider value={instance}>{instance !== null && entry?.children}</ActiveSceneContext.Provider>;\n};\n"],"mappings":";;;;;;;AAiBA,MAAM,qBAAqB,cAA+B,IAAI;AAC9D,mBAAmB,cAAc;AAuBjC,SAAgB,eAAmC,YAAoE;CACrH,MAAM,QAAQ,WAAW,kBAAkB;CAE3C,IAAI,eAAe,QACjB,OAAO;CAGT,OAAO,iBAAiB,aAAa,QAAQ;AAC/C;;;;;;AAiBA,MAAa,SAAS,WAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDlE,MAAa,UAAU,EAAE,QAAQ,YAAY,eAA0C;CACrF,MAAM,MAAM,UAAU;CACtB,MAAM,CAAC,UAAU,eAAe,SAA0B,IAAI;CAG9D,MAAM,gBAAgB,OAAO,CAAC;CAC9B,MAAM,gBAAgB,uBAAO,IAAI,QAAmC,CAAC;CAerE,MAAM,QAZW,cAAc;EA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AQ,IAAI,KAAK,UAAU;EACzC,AAAK,WAAW,WAAW;GACzB,IAAI,cAAc,QAAQ,IAAI,GAAG,MAAM,YACrC,cAAc,QAAQ,OAAO,GAAG;EAEpC,CAAC;EAED,aAAa;GACX,YAAY;GACZ,YAAY,IAAI;EAClB;CAEF,GAAG;EAAC;EAAK;EAAQ;CAAU,CAAC;CAE5B,OAAO,oBAAC,mBAAmB,UAApB;EAA6B,OAAO;YAAW,aAAa,QAAQ,OAAO;CAAsC;AAC1H"}
|
package/dist/esm/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","
|
|
1
|
+
{"version":3,"file":"index.d.ts","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACzD,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,YAAY,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC1F,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC"}
|
package/dist/esm/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { ExoContext, useExoContext } from "./ExoContext.js";
|
|
2
|
-
import { useExoApplication } from "./useExoApplication.js";
|
|
3
1
|
import { ExoCanvas } from "./ExoCanvas.js";
|
|
4
|
-
import {
|
|
2
|
+
import { ExoContext, useExoContext } from "./ExoContext.js";
|
|
5
3
|
import { Scene, Scenes, useActiveScene } from "./Scenes.js";
|
|
4
|
+
import { useExoApp } from "./useExoApp.js";
|
|
5
|
+
import { useExoApplication } from "./useExoApplication.js";
|
|
6
6
|
import { useScene } from "./useScene.js";
|
|
7
7
|
import { useSignal } from "./useSignal.js";
|
|
8
8
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useExoApp.d.ts","
|
|
1
|
+
{"version":3,"file":"useExoApp.d.ts","sources":["../../src/useExoApp.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAIjD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,SAAS,QAAO,WAQ5B,CAAC"}
|
package/dist/esm/useExoApp.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useExoContext } from "./ExoContext.js";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// src/useExoApp.ts
|
|
4
4
|
/**
|
|
5
5
|
* Returns the {@link Application} instance from the nearest {@link ExoCanvas}
|
|
6
6
|
* ancestor. Throws an informative error when called outside of an
|
|
@@ -28,6 +28,5 @@ const useExoApp = () => {
|
|
|
28
28
|
return app;
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
-
//#endregion
|
|
32
31
|
export { useExoApp };
|
|
33
32
|
//# sourceMappingURL=useExoApp.js.map
|
|
@@ -35,10 +35,10 @@ export interface UseExoApplicationResult {
|
|
|
35
35
|
* }
|
|
36
36
|
* ```
|
|
37
37
|
*
|
|
38
|
-
* **Reactivity model.** The Application is
|
|
39
|
-
*
|
|
40
|
-
* WebGPU).
|
|
41
|
-
* app down:
|
|
38
|
+
* **Reactivity model.** The Application is created when the canvas attaches and
|
|
39
|
+
* recreated when that element or the render `backend` changes (you cannot
|
|
40
|
+
* hot-swap WebGL2 and WebGPU). Detaching the canvas destroys the Application.
|
|
41
|
+
* Other supported options are applied *live* without tearing the app down:
|
|
42
42
|
*
|
|
43
43
|
* - `canvas.width` / `canvas.height` → `app.resize(...)`
|
|
44
44
|
* - `clearColor` → `app.clearColor`
|
|
@@ -58,8 +58,9 @@ export interface UseExoApplicationResult {
|
|
|
58
58
|
* @param options - Application options (the canvas element is the one you render).
|
|
59
59
|
* @param onReady - Called once each time an Application is created.
|
|
60
60
|
* @param onError - Called for every {@link Application.onError} dispatch (async
|
|
61
|
-
* init/scene-load failures) while an Application exists
|
|
62
|
-
*
|
|
61
|
+
* init/scene-load failures) while an Application exists, and for failures
|
|
62
|
+
* during asynchronous replacement after teardown. Re-subscribed automatically
|
|
63
|
+
* whenever the Application is (re)created.
|
|
63
64
|
*/
|
|
64
65
|
export declare const useExoApplication: (options?: ExoApplicationOptions, onReady?: (app: Application) => void, onError?: (error: unknown) => void) => UseExoApplicationResult;
|
|
65
66
|
//# sourceMappingURL=useExoApplication.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useExoApplication.d.ts","
|
|
1
|
+
{"version":3,"file":"useExoApplication.d.ts","sources":["../../src/useExoApplication.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,KAAK,wBAAwB,EAAc,MAAM,eAAe,CAAC;AAChH,OAAO,EAAE,KAAK,GAAG,EAA+B,MAAM,OAAO,CAAC;AAE9D;;;;;;;GAOG;AACH,MAAM,MAAM,qBAAqB,GAAG,IAAI,CAAC,kBAAkB,EAAE,QAAQ,CAAC,GAAG;IACvE,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,SAAS,GAAG,OAAO,CAAC,CAAC;CACvE,CAAC;AAEF,iDAAiD;AACjD,MAAM,WAAW,uBAAuB;IACtC,qEAAqE;IACrE,QAAQ,CAAC,GAAG,EAAE,WAAW,GAAG,IAAI,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC,iBAAiB,CAAC,CAAC;CAC5C;AAMD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,eAAO,MAAM,iBAAiB,aAClB,qBAAqB,YACrB,CAAC,GAAG,EAAE,WAAW,KAAK,IAAI,YAC1B,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,KACjC,uBAkHF,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useEffect, useRef, useState } from "react";
|
|
2
2
|
import { Application } from "@codexo/exojs";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// src/useExoApplication.ts
|
|
5
5
|
/** Stable string key for the colour so the sync effect can depend on its value. */
|
|
6
6
|
const colorKey = (color) => color === void 0 ? void 0 : `${color.r},${color.g},${color.b},${color.a}`;
|
|
7
7
|
/**
|
|
@@ -17,10 +17,10 @@ const colorKey = (color) => color === void 0 ? void 0 : `${color.r},${color.g},$
|
|
|
17
17
|
* }
|
|
18
18
|
* ```
|
|
19
19
|
*
|
|
20
|
-
* **Reactivity model.** The Application is
|
|
21
|
-
*
|
|
22
|
-
* WebGPU).
|
|
23
|
-
* app down:
|
|
20
|
+
* **Reactivity model.** The Application is created when the canvas attaches and
|
|
21
|
+
* recreated when that element or the render `backend` changes (you cannot
|
|
22
|
+
* hot-swap WebGL2 and WebGPU). Detaching the canvas destroys the Application.
|
|
23
|
+
* Other supported options are applied *live* without tearing the app down:
|
|
24
24
|
*
|
|
25
25
|
* - `canvas.width` / `canvas.height` → `app.resize(...)`
|
|
26
26
|
* - `clearColor` → `app.clearColor`
|
|
@@ -40,12 +40,14 @@ const colorKey = (color) => color === void 0 ? void 0 : `${color.r},${color.g},$
|
|
|
40
40
|
* @param options - Application options (the canvas element is the one you render).
|
|
41
41
|
* @param onReady - Called once each time an Application is created.
|
|
42
42
|
* @param onError - Called for every {@link Application.onError} dispatch (async
|
|
43
|
-
* init/scene-load failures) while an Application exists
|
|
44
|
-
*
|
|
43
|
+
* init/scene-load failures) while an Application exists, and for failures
|
|
44
|
+
* during asynchronous replacement after teardown. Re-subscribed automatically
|
|
45
|
+
* whenever the Application is (re)created.
|
|
45
46
|
*/
|
|
46
47
|
const useExoApplication = (options, onReady, onError) => {
|
|
47
|
-
const
|
|
48
|
+
const [canvas, setCanvas] = useState(null);
|
|
48
49
|
const [app, setApp] = useState(null);
|
|
50
|
+
const teardownRef = useRef(null);
|
|
49
51
|
const onReadyRef = useRef(onReady);
|
|
50
52
|
useEffect(() => {
|
|
51
53
|
onReadyRef.current = onReady;
|
|
@@ -56,22 +58,38 @@ const useExoApplication = (options, onReady, onError) => {
|
|
|
56
58
|
});
|
|
57
59
|
const backendKey = options?.backend?.type ?? "auto";
|
|
58
60
|
useEffect(() => {
|
|
59
|
-
const canvas = canvasRef.current;
|
|
60
61
|
if (!canvas) return;
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
62
|
+
let cancelled = false;
|
|
63
|
+
let application = null;
|
|
64
|
+
const create = () => {
|
|
65
|
+
if (cancelled) return;
|
|
66
|
+
application = new Application({
|
|
67
|
+
...options,
|
|
68
|
+
canvas: {
|
|
69
|
+
...options?.canvas,
|
|
70
|
+
element: canvas
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
setApp(application);
|
|
74
|
+
onReadyRef.current?.(application);
|
|
75
|
+
};
|
|
76
|
+
const pending = teardownRef.current;
|
|
77
|
+
if (pending === null) create();
|
|
78
|
+
else pending.then(create).catch((error) => {
|
|
79
|
+
if (!cancelled) onErrorRef.current?.(error);
|
|
67
80
|
});
|
|
68
|
-
setApp(application);
|
|
69
|
-
onReadyRef.current?.(application);
|
|
70
81
|
return () => {
|
|
71
|
-
|
|
72
|
-
|
|
82
|
+
cancelled = true;
|
|
83
|
+
if (application !== null) {
|
|
84
|
+
const teardown = Promise.resolve(application.destroy());
|
|
85
|
+
teardownRef.current = teardown;
|
|
86
|
+
teardown.then(() => {
|
|
87
|
+
if (teardownRef.current === teardown) teardownRef.current = null;
|
|
88
|
+
}, () => void 0);
|
|
89
|
+
setApp(null);
|
|
90
|
+
}
|
|
73
91
|
};
|
|
74
|
-
}, [backendKey]);
|
|
92
|
+
}, [backendKey, canvas]);
|
|
75
93
|
useEffect(() => {
|
|
76
94
|
if (app === null) return;
|
|
77
95
|
const handleError = (error) => {
|
|
@@ -98,10 +116,9 @@ const useExoApplication = (options, onReady, onError) => {
|
|
|
98
116
|
}, [app, clearKey]);
|
|
99
117
|
return {
|
|
100
118
|
app,
|
|
101
|
-
canvasRef
|
|
119
|
+
canvasRef: setCanvas
|
|
102
120
|
};
|
|
103
121
|
};
|
|
104
122
|
|
|
105
|
-
//#endregion
|
|
106
123
|
export { useExoApplication };
|
|
107
124
|
//# sourceMappingURL=useExoApplication.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useExoApplication.js","names":[],"sources":["../../src/useExoApplication.ts"],"sourcesContent":["import { Application, type ApplicationOptions, type CanvasApplicationOptions, type Color } from '@codexo/exojs';\nimport { type Ref, useEffect, useRef, useState } from 'react';\n\n/**\n * Options for {@link useExoApplication} / {@link import('./ExoCanvas').ExoCanvas}.\n *\n * Same as {@link ApplicationOptions} but the `canvas.element` and `canvas.mount`\n * fields are managed for you (the Application binds to the canvas the hook\n * references), so they are omitted. You may still pass\n * `canvas.width`/`height`/`sizing`/etc.\n */\nexport type ExoApplicationOptions = Omit<ApplicationOptions, 'canvas'> & {\n readonly canvas?: Omit<CanvasApplicationOptions, 'element' | 'mount'>;\n};\n\n/** Return value of {@link useExoApplication}. */\nexport interface UseExoApplicationResult {\n /** The Application instance, or `null` until it has been created. */\n readonly app: Application | null;\n /**\n * Attach this to the `<canvas>` element the Application should bind to. Typed\n * as `Ref` (not `RefObject`) so the same code type-checks against both\n * `@types/react` 18 and 19, whose `useRef`/`RefObject` nullability differ.\n */\n readonly canvasRef: Ref<HTMLCanvasElement>;\n}\n\n/** Stable string key for the colour so the sync effect can depend on its value. */\nconst colorKey = (color: Color | undefined): string | undefined
|
|
1
|
+
{"version":3,"file":"useExoApplication.js","names":[],"sources":["../../src/useExoApplication.ts"],"sourcesContent":["import { Application, type ApplicationOptions, type CanvasApplicationOptions, type Color } from '@codexo/exojs';\nimport { type Ref, useEffect, useRef, useState } from 'react';\n\n/**\n * Options for {@link useExoApplication} / {@link import('./ExoCanvas').ExoCanvas}.\n *\n * Same as {@link ApplicationOptions} but the `canvas.element` and `canvas.mount`\n * fields are managed for you (the Application binds to the canvas the hook\n * references), so they are omitted. You may still pass\n * `canvas.width`/`height`/`sizing`/etc.\n */\nexport type ExoApplicationOptions = Omit<ApplicationOptions, 'canvas'> & {\n readonly canvas?: Omit<CanvasApplicationOptions, 'element' | 'mount'>;\n};\n\n/** Return value of {@link useExoApplication}. */\nexport interface UseExoApplicationResult {\n /** The Application instance, or `null` until it has been created. */\n readonly app: Application | null;\n /**\n * Attach this to the `<canvas>` element the Application should bind to. Typed\n * as `Ref` (not `RefObject`) so the same code type-checks against both\n * `@types/react` 18 and 19, whose `useRef`/`RefObject` nullability differ.\n */\n readonly canvasRef: Ref<HTMLCanvasElement>;\n}\n\n/** Stable string key for the colour so the sync effect can depend on its value. */\nconst colorKey = (color: Color | undefined): string | undefined =>\n color === undefined ? undefined : `${color.r},${color.g},${color.b},${color.a}`;\n\n/**\n * Creates and owns an ExoJS {@link Application}, binding it to a `<canvas>` you\n * render yourself and attach the returned `canvasRef` to. The hook renders no\n * DOM of its own - you keep full control over the canvas element, its container,\n * and its styling.\n *\n * ```tsx\n * function Game() {\n * const { app, canvasRef } = useExoApplication({ canvas: { width: 800, height: 600 } });\n * return <canvas ref={canvasRef} className=\"game\" />;\n * }\n * ```\n *\n * **Reactivity model.** The Application is created when the canvas attaches and\n * recreated when that element or the render `backend` changes (you cannot\n * hot-swap WebGL2 and WebGPU). Detaching the canvas destroys the Application.\n * Other supported options are applied *live* without tearing the app down:\n *\n * - `canvas.width` / `canvas.height` → `app.resize(...)`\n * - `clearColor` → `app.clearColor`\n *\n * Options without a live setter (e.g. `canvas.pixelRatio`, `seed`, `extensions`)\n * are captured at creation; change the `backend` or remount to apply them.\n *\n * `canvas.sizing` is captured at creation too, deliberately: a policy is an\n * object, so a new instance on every render would detach and re-attach the\n * previous one each time. Assign `app.sizing` yourself to switch strategies.\n *\n * Styling note: with no `canvas.sizing` the engine keeps the canvas at the base\n * resolution and writes only that size, so you may style it freely. A sizing\n * policy owns the canvas's `width`/`height` styles - don't fight it with a\n * `style` prop.\n *\n * @param options - Application options (the canvas element is the one you render).\n * @param onReady - Called once each time an Application is created.\n * @param onError - Called for every {@link Application.onError} dispatch (async\n * init/scene-load failures) while an Application exists, and for failures\n * during asynchronous replacement after teardown. Re-subscribed automatically\n * whenever the Application is (re)created.\n */\nexport const useExoApplication = (\n options?: ExoApplicationOptions,\n onReady?: (app: Application) => void,\n onError?: (error: unknown) => void,\n): UseExoApplicationResult => {\n const [canvas, setCanvas] = useState<HTMLCanvasElement | null>(null);\n const [app, setApp] = useState<Application | null>(null);\n const teardownRef = useRef<Promise<unknown> | null>(null);\n\n // Latest onReady without retriggering the lifecycle effect. Updated in an\n // effect (not during render) so the ref-write happens after commit.\n const onReadyRef = useRef(onReady);\n useEffect(() => {\n onReadyRef.current = onReady;\n });\n\n // Latest onError without retriggering the subscribe effect below.\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n });\n\n // Other option values are captured at creation or synchronized below.\n const backendKey = options?.backend?.type ?? 'auto';\n\n // Lifecycle follows the attached canvas and backend.\n useEffect(() => {\n if (!canvas) {\n return;\n }\n\n let cancelled = false;\n let application: Application | null = null;\n\n const create = (): void => {\n if (cancelled) {\n return;\n }\n\n application = new Application({\n ...options,\n canvas: { ...options?.canvas, element: canvas },\n });\n setApp(application);\n onReadyRef.current?.(application);\n };\n\n const pending = teardownRef.current;\n\n if (pending === null) {\n create();\n } else {\n void pending.then(create).catch((error: unknown) => {\n if (!cancelled) {\n onErrorRef.current?.(error);\n }\n });\n }\n\n return () => {\n cancelled = true;\n\n if (application !== null) {\n const teardown = Promise.resolve(application.destroy());\n teardownRef.current = teardown;\n void teardown.then(\n () => {\n if (teardownRef.current === teardown) {\n teardownRef.current = null;\n }\n },\n () => undefined,\n );\n setApp(null);\n }\n };\n // `options` is intentionally read at creation; live values are synced below.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [backendKey, canvas]);\n\n // ── Live sync: error reporting ─────────────────────────────────────────────\n useEffect(() => {\n if (app === null) {\n return;\n }\n\n const handleError = (error: Error): void => {\n onErrorRef.current?.(error);\n };\n\n app.onError.add(handleError);\n\n return () => {\n app.onError.remove(handleError);\n };\n }, [app]);\n\n // ── Live sync: size ───────────────────────────────────────────────────────\n const width = options?.canvas?.width;\n const height = options?.canvas?.height;\n useEffect(() => {\n if (app !== null && width !== undefined && height !== undefined) {\n app.resize(width, height);\n }\n }, [app, width, height]);\n\n // ── Live sync: clear colour ───────────────────────────────────────────────\n const clearColor = options?.clearColor;\n const clearKey = colorKey(clearColor);\n useEffect(() => {\n if (app !== null && clearColor !== undefined) {\n app.clearColor = clearColor;\n }\n // clearColor identity is unstable; depend on its value key instead.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [app, clearKey]);\n\n return { app, canvasRef: setCanvas };\n};\n"],"mappings":";;;;;AA4BA,MAAM,YAAY,UAChB,UAAU,SAAY,SAAY,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0C9E,MAAa,qBACX,SACA,SACA,YAC4B;CAC5B,MAAM,CAAC,QAAQ,aAAa,SAAmC,IAAI;CACnE,MAAM,CAAC,KAAK,UAAU,SAA6B,IAAI;CACvD,MAAM,cAAc,OAAgC,IAAI;CAIxD,MAAM,aAAa,OAAO,OAAO;CACjC,gBAAgB;EACd,WAAW,UAAU;CACvB,CAAC;CAGD,MAAM,aAAa,OAAO,OAAO;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,gBAAgB;EACd,IAAI,QAAQ,QAAQ,eAAe,QACjC,IAAI,aAAa;CAIrB,GAAG,CAAC,KAAK,QAAQ,CAAC;CAElB,OAAO;EAAE;EAAK,WAAW;CAAU;AACrC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useScene.d.ts","
|
|
1
|
+
{"version":3,"file":"useScene.d.ts","sources":["../../src/useScene.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,KAAK,EAAyB,MAAM,eAAe,CAAC;AACpF,OAAO,EAAE,KAAK,cAAc,EAA+B,MAAM,OAAO,CAAC;AAIzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,eAAO,MAAM,QAAQ,GAAI,CAAC,SAAS,KAAK,cAAc,UAAU,CAAC,SAAQ,cAAc,KAAQ,CAAC,GAAG,IAoGlG,CAAC"}
|
package/dist/esm/useScene.js
CHANGED
|
@@ -2,7 +2,7 @@ import { useExoApp } from "./useExoApp.js";
|
|
|
2
2
|
import { useEffect, useRef, useState } from "react";
|
|
3
3
|
import { ApplicationState } from "@codexo/exojs";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
// src/useScene.ts
|
|
6
6
|
/**
|
|
7
7
|
* Activates `SceneClass` on the ExoJS {@link Application} and returns the
|
|
8
8
|
* resulting instance once it is live. `SceneClass` must be registered in
|
|
@@ -45,13 +45,20 @@ const useScene = (SceneClass, deps = []) => {
|
|
|
45
45
|
const app = useExoApp();
|
|
46
46
|
const [scene, setScene] = useState(null);
|
|
47
47
|
const generationRef = useRef(0);
|
|
48
|
+
const navigationRef = useRef(/* @__PURE__ */ new WeakMap());
|
|
48
49
|
useEffect(() => {
|
|
49
50
|
let cancelled = false;
|
|
50
51
|
const generation = ++generationRef.current;
|
|
51
52
|
const isStale = () => cancelled || generationRef.current !== generation;
|
|
52
53
|
const target = SceneClass;
|
|
54
|
+
const previous = navigationRef.current.get(app);
|
|
55
|
+
const joiningStartup = app.state === ApplicationState.Loading;
|
|
53
56
|
const apply = async () => {
|
|
54
57
|
try {
|
|
58
|
+
if (previous !== void 0 && !joiningStartup) {
|
|
59
|
+
await previous;
|
|
60
|
+
if (isStale()) return;
|
|
61
|
+
}
|
|
55
62
|
if (app.state === ApplicationState.Stopped || app.state === ApplicationState.Loading) {
|
|
56
63
|
await app.start(target);
|
|
57
64
|
if (isStale()) return;
|
|
@@ -62,7 +69,11 @@ const useScene = (SceneClass, deps = []) => {
|
|
|
62
69
|
if (!isStale()) app.onError.dispatch(error instanceof Error ? error : new Error(String(error)));
|
|
63
70
|
}
|
|
64
71
|
};
|
|
65
|
-
apply();
|
|
72
|
+
const navigation = apply();
|
|
73
|
+
navigationRef.current.set(app, navigation);
|
|
74
|
+
navigation.then(() => {
|
|
75
|
+
if (navigationRef.current.get(app) === navigation) navigationRef.current.delete(app);
|
|
76
|
+
});
|
|
66
77
|
return () => {
|
|
67
78
|
cancelled = true;
|
|
68
79
|
setScene(null);
|
|
@@ -71,6 +82,5 @@ const useScene = (SceneClass, deps = []) => {
|
|
|
71
82
|
return scene;
|
|
72
83
|
};
|
|
73
84
|
|
|
74
|
-
//#endregion
|
|
75
85
|
export { useScene };
|
|
76
86
|
//# sourceMappingURL=useScene.js.map
|
package/dist/esm/useScene.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useScene.js","names":[],"sources":["../../src/useScene.ts"],"sourcesContent":["import { ApplicationState, type Scene, type SceneConstructor } from '@codexo/exojs';\nimport { type DependencyList, useEffect, useRef, useState } from 'react';\n\nimport { useExoApp } from './useExoApp';\n\n/**\n * Activates `SceneClass` on the ExoJS {@link Application} and returns the\n * resulting instance once it is live. `SceneClass` must be registered in\n * `ApplicationOptions.scenes` (passed to {@link import('./useExoApplication').useExoApplication}\n * / {@link import('./ExoCanvas').ExoCanvas}) - unregistered targets reject in\n * development builds.\n *\n * On first call (engine not yet started) this hook calls `app.start(SceneClass)`,\n * which initializes the render backend and begins the per-frame loop. On\n * subsequent dep-change remounts it calls `app.scenes.change(SceneClass)` to\n * switch scenes without restarting the engine, constructing a fresh instance.\n *\n * Effects that run while startup is still in flight - React StrictMode\n * double-mounts every effect in development - join that `app.start()` call\n * instead of racing a second navigation against it, and only activate\n * `SceneClass` afterwards if startup did not already leave it active. A\n * StrictMode double mount therefore activates the scene exactly once.\n *\n * A failure in `app.start()`/`app.scenes.change()` (e.g. a scene's `load()`\n * rejects) is caught and routed to {@link Application.onError} rather than\n * left as an unhandled promise rejection - subscribe via\n * `app.onError.add(...)` or the {@link import('./ExoCanvas').ExoCanvas}\n * `onError` prop to observe it.\n *\n * @param SceneClass - Constructor for the scene to activate.\n * @param deps - Extra deps that trigger scene replacement when changed, in\n * addition to the stable `app` reference (same semantics as `useEffect`).\n * @returns The active scene instance, or `null` while it is loading.\n *\n * @example\n * ```tsx\n * function GameScreen() {\n * const scene = useScene(MyGameScene);\n * if (!scene) return null;\n * return <ScoreHud scene={scene} />;\n * }\n * ```\n */\nexport const useScene = <T extends Scene>(SceneClass: new () => T, deps: DependencyList = []): T | null => {\n const app = useExoApp();\n const [scene, setScene] = useState<T | null>(null);\n // Bumped on every effect run so an async `apply()` can tell whether a newer\n // run has since taken over - the flag below only covers a run whose own\n // cleanup has fired.\n const generationRef = useRef(0);\n\n useEffect(() => {\n let cancelled = false;\n const generation = ++generationRef.current;\n // Only the newest, still-mounted run may touch component/app state: an\n // earlier one's activation result is no longer what the component asked\n // for, and neither is its failure.\n const isStale = (): boolean => cancelled || generationRef.current !== generation;\n // This hook's contract has always been zero-arg activation only (no data\n // parameter) - `T extends Scene` (Data defaults to void), but that generic\n // `T` can't be distributed through the navigation call's conditional types\n // (InferSceneData/ChangeSceneArgs) inside this function body, so it's pinned\n // to its concrete void-data instantiation here.\n const target = SceneClass as SceneConstructor;\n\n const apply = async (): Promise<void> => {\n try {\n if (app.state === ApplicationState.Stopped || app.state === ApplicationState.Loading) {\n // Stopped: first activation, which initializes the backend and starts\n // the frame loop. Loading: an earlier effect's `start()` is still in\n // flight - including its own initial scene navigation, which\n // `scenes.change()` would collide with (navigation never queues, it\n // rejects). `start()` joins that in-flight run instead, ignoring the\n // target passed here.\n await app.start(target);\n\n if (isStale()) {\n return;\n }\n\n // Startup activates its own target, which is this one whenever the\n // joined `start()` came from an effect for the same scene (the\n // StrictMode double-mount case) - activating again would needlessly\n // tear the scene down and rebuild it. A `start()` that targeted a\n // different scene, or none at all, still needs the switch.\n if (!(app.scenes.currentScene instanceof SceneClass)) {\n await app.scenes.change(target);\n }\n } else {\n // The engine is already running: a scene switch without a restart.\n await app.scenes.change(target);\n }\n\n if (!isStale()) {\n setScene(app.scenes.currentScene as T);\n }\n } catch (error) {\n // Route to Application.onError instead of leaving an unhandled\n // rejection - app.start()/change() reject rather than dispatching\n // onError themselves. A superseded run stays silent: its failure is no\n // longer this component's state, exactly like its success.\n if (!isStale()) {\n app.onError.dispatch(error instanceof Error ? error : new Error(String(error)));\n }\n }\n };\n\n
|
|
1
|
+
{"version":3,"file":"useScene.js","names":[],"sources":["../../src/useScene.ts"],"sourcesContent":["import { ApplicationState, type Scene, type SceneConstructor } from '@codexo/exojs';\nimport { type DependencyList, useEffect, useRef, useState } from 'react';\n\nimport { useExoApp } from './useExoApp';\n\n/**\n * Activates `SceneClass` on the ExoJS {@link Application} and returns the\n * resulting instance once it is live. `SceneClass` must be registered in\n * `ApplicationOptions.scenes` (passed to {@link import('./useExoApplication').useExoApplication}\n * / {@link import('./ExoCanvas').ExoCanvas}) - unregistered targets reject in\n * development builds.\n *\n * On first call (engine not yet started) this hook calls `app.start(SceneClass)`,\n * which initializes the render backend and begins the per-frame loop. On\n * subsequent dep-change remounts it calls `app.scenes.change(SceneClass)` to\n * switch scenes without restarting the engine, constructing a fresh instance.\n *\n * Effects that run while startup is still in flight - React StrictMode\n * double-mounts every effect in development - join that `app.start()` call\n * instead of racing a second navigation against it, and only activate\n * `SceneClass` afterwards if startup did not already leave it active. A\n * StrictMode double mount therefore activates the scene exactly once.\n *\n * A failure in `app.start()`/`app.scenes.change()` (e.g. a scene's `load()`\n * rejects) is caught and routed to {@link Application.onError} rather than\n * left as an unhandled promise rejection - subscribe via\n * `app.onError.add(...)` or the {@link import('./ExoCanvas').ExoCanvas}\n * `onError` prop to observe it.\n *\n * @param SceneClass - Constructor for the scene to activate.\n * @param deps - Extra deps that trigger scene replacement when changed, in\n * addition to the stable `app` reference (same semantics as `useEffect`).\n * @returns The active scene instance, or `null` while it is loading.\n *\n * @example\n * ```tsx\n * function GameScreen() {\n * const scene = useScene(MyGameScene);\n * if (!scene) return null;\n * return <ScoreHud scene={scene} />;\n * }\n * ```\n */\nexport const useScene = <T extends Scene>(SceneClass: new () => T, deps: DependencyList = []): T | null => {\n const app = useExoApp();\n const [scene, setScene] = useState<T | null>(null);\n // Bumped on every effect run so an async `apply()` can tell whether a newer\n // run has since taken over - the flag below only covers a run whose own\n // cleanup has fired.\n const generationRef = useRef(0);\n const navigationRef = useRef(new WeakMap<typeof app, Promise<void>>());\n\n useEffect(() => {\n let cancelled = false;\n const generation = ++generationRef.current;\n // Only the newest, still-mounted run may touch component/app state: an\n // earlier one's activation result is no longer what the component asked\n // for, and neither is its failure.\n const isStale = (): boolean => cancelled || generationRef.current !== generation;\n // This hook's contract has always been zero-arg activation only (no data\n // parameter) - `T extends Scene` (Data defaults to void), but that generic\n // `T` can't be distributed through the navigation call's conditional types\n // (InferSceneData/ChangeSceneArgs) inside this function body, so it's pinned\n // to its concrete void-data instantiation here.\n const target = SceneClass as SceneConstructor;\n\n const previous = navigationRef.current.get(app);\n const joiningStartup = app.state === ApplicationState.Loading;\n\n const apply = async (): Promise<void> => {\n try {\n if (previous !== undefined && !joiningStartup) {\n await previous;\n\n if (isStale()) {\n return;\n }\n }\n\n if (app.state === ApplicationState.Stopped || app.state === ApplicationState.Loading) {\n // Stopped: first activation, which initializes the backend and starts\n // the frame loop. Loading: an earlier effect's `start()` is still in\n // flight - including its own initial scene navigation, which\n // `scenes.change()` would collide with (navigation never queues, it\n // rejects). `start()` joins that in-flight run instead, ignoring the\n // target passed here.\n await app.start(target);\n\n if (isStale()) {\n return;\n }\n\n // Startup activates its own target, which is this one whenever the\n // joined `start()` came from an effect for the same scene (the\n // StrictMode double-mount case) - activating again would needlessly\n // tear the scene down and rebuild it. A `start()` that targeted a\n // different scene, or none at all, still needs the switch.\n if (!(app.scenes.currentScene instanceof SceneClass)) {\n await app.scenes.change(target);\n }\n } else {\n // The engine is already running: a scene switch without a restart.\n await app.scenes.change(target);\n }\n\n if (!isStale()) {\n setScene(app.scenes.currentScene as T);\n }\n } catch (error) {\n // Route to Application.onError instead of leaving an unhandled\n // rejection - app.start()/change() reject rather than dispatching\n // onError themselves. A superseded run stays silent: its failure is no\n // longer this component's state, exactly like its success.\n if (!isStale()) {\n app.onError.dispatch(error instanceof Error ? error : new Error(String(error)));\n }\n }\n };\n\n const navigation = apply();\n navigationRef.current.set(app, navigation);\n void navigation.then(() => {\n if (navigationRef.current.get(app) === navigation) {\n navigationRef.current.delete(app);\n }\n });\n\n return () => {\n cancelled = true;\n setScene(null);\n // No public API switches the director back to scene-less mid-lifetime\n // (navigation always targets a registered\n // constructor). Application.destroy() (called by ExoCanvas cleanup)\n // tears down whatever scene is still active.\n };\n // SceneClass is intentionally excluded from deps: a new class reference\n // (e.g. inline arrow class) on every render would recreate the scene\n // each frame. Pass an explicit deps array to react to changes - which is\n // also why the spread is here and why the lint rule can't verify this list.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [app, ...deps]);\n\n return scene;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAa,YAA6B,YAAyB,OAAuB,CAAC,MAAgB;CACzG,MAAM,MAAM,UAAU;CACtB,MAAM,CAAC,OAAO,YAAY,SAAmB,IAAI;CAIjD,MAAM,gBAAgB,OAAO,CAAC;CAC9B,MAAM,gBAAgB,uBAAO,IAAI,QAAmC,CAAC;CAErE,gBAAgB;EACd,IAAI,YAAY;EAChB,MAAM,aAAa,EAAE,cAAc;EAInC,MAAM,gBAAyB,aAAa,cAAc,YAAY;EAMtE,MAAM,SAAS;EAEf,MAAM,WAAW,cAAc,QAAQ,IAAI,GAAG;EAC9C,MAAM,iBAAiB,IAAI,UAAU,iBAAiB;EAEtD,MAAM,QAAQ,YAA2B;GACvC,IAAI;IACF,IAAI,aAAa,UAAa,CAAC,gBAAgB;KAC7C,MAAM;KAEN,IAAI,QAAQ,GACV;IAEJ;IAEA,IAAI,IAAI,UAAU,iBAAiB,WAAW,IAAI,UAAU,iBAAiB,SAAS;KAOpF,MAAM,IAAI,MAAM,MAAM;KAEtB,IAAI,QAAQ,GACV;KAQF,IAAI,EAAE,IAAI,OAAO,wBAAwB,aACvC,MAAM,IAAI,OAAO,OAAO,MAAM;IAElC,OAEE,MAAM,IAAI,OAAO,OAAO,MAAM;IAGhC,IAAI,CAAC,QAAQ,GACX,SAAS,IAAI,OAAO,YAAiB;GAEzC,SAAS,OAAO;IAKd,IAAI,CAAC,QAAQ,GACX,IAAI,QAAQ,SAAS,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;GAElF;EACF;EAEA,MAAM,aAAa,MAAM;EACzB,cAAc,QAAQ,IAAI,KAAK,UAAU;EACzC,AAAK,WAAW,WAAW;GACzB,IAAI,cAAc,QAAQ,IAAI,GAAG,MAAM,YACrC,cAAc,QAAQ,OAAO,GAAG;EAEpC,CAAC;EAED,aAAa;GACX,YAAY;GACZ,SAAS,IAAI;EAKf;CAMF,GAAG,CAAC,KAAK,GAAG,IAAI,CAAC;CAEjB,OAAO;AACT"}
|
package/dist/esm/useSignal.d.ts
CHANGED
|
@@ -23,7 +23,10 @@ import type { Signal } from '@codexo/exojs';
|
|
|
23
23
|
* (e.g. before an `Application` exists) - the hook simply does not subscribe
|
|
24
24
|
* to anything and `getSnapshot` still runs on every render.
|
|
25
25
|
* @param getSnapshot - Reads the current value. Called on mount and again after
|
|
26
|
-
* every dispatch of `signal`.
|
|
26
|
+
* every dispatch of `signal`. `useSyncExternalStore` compares consecutive
|
|
27
|
+
* results with `Object.is`, so return a primitive or a cached object that
|
|
28
|
+
* stays identical until the underlying data changes; a fresh object on every
|
|
29
|
+
* call re-renders without end.
|
|
27
30
|
*/
|
|
28
31
|
export declare const useSignal: <Args extends unknown[], T>(signal: Signal<Args> | null | undefined, getSnapshot: () => T) => T;
|
|
29
32
|
//# sourceMappingURL=useSignal.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSignal.d.ts","
|
|
1
|
+
{"version":3,"file":"useSignal.d.ts","sources":["../../src/useSignal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAG5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,eAAO,MAAM,SAAS,GAAI,IAAI,SAAS,OAAO,EAAE,EAAE,CAAC,UAAU,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,SAAS,eAAe,MAAM,CAAC,KAAG,CAoBpH,CAAC"}
|
package/dist/esm/useSignal.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useCallback, useSyncExternalStore } from "react";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// src/useSignal.ts
|
|
4
4
|
/**
|
|
5
5
|
* Subscribes to an ExoJS {@link Signal} and returns the latest value computed by
|
|
6
6
|
* `getSnapshot`, re-rendering the component every time the signal dispatches.
|
|
@@ -25,7 +25,10 @@ import { useCallback, useSyncExternalStore } from "react";
|
|
|
25
25
|
* (e.g. before an `Application` exists) - the hook simply does not subscribe
|
|
26
26
|
* to anything and `getSnapshot` still runs on every render.
|
|
27
27
|
* @param getSnapshot - Reads the current value. Called on mount and again after
|
|
28
|
-
* every dispatch of `signal`.
|
|
28
|
+
* every dispatch of `signal`. `useSyncExternalStore` compares consecutive
|
|
29
|
+
* results with `Object.is`, so return a primitive or a cached object that
|
|
30
|
+
* stays identical until the underlying data changes; a fresh object on every
|
|
31
|
+
* call re-renders without end.
|
|
29
32
|
*/
|
|
30
33
|
const useSignal = (signal, getSnapshot) => {
|
|
31
34
|
const subscribe = useCallback((onStoreChange) => {
|
|
@@ -38,6 +41,5 @@ const useSignal = (signal, getSnapshot) => {
|
|
|
38
41
|
return useSyncExternalStore(subscribe, getSnapshot);
|
|
39
42
|
};
|
|
40
43
|
|
|
41
|
-
//#endregion
|
|
42
44
|
export { useSignal };
|
|
43
45
|
//# sourceMappingURL=useSignal.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSignal.js","names":[],"sources":["../../src/useSignal.ts"],"sourcesContent":["import type { Signal } from '@codexo/exojs';\nimport { useCallback, useSyncExternalStore } from 'react';\n\n/**\n * Subscribes to an ExoJS {@link Signal} and returns the latest value computed by\n * `getSnapshot`, re-rendering the component every time the signal dispatches.\n * Built on `useSyncExternalStore`, so reads stay tear-free under concurrent\n * rendering.\n *\n * The signal itself is only used to know *when* to re-read - `getSnapshot` is\n * responsible for producing the actual value (usually a getter on the engine\n * object the signal lives on).\n *\n * @example\n * ```tsx\n * function FrameCounter() {\n * const app = useExoApp();\n * // Re-renders on every `onFrame` dispatch (i.e. every engine frame).\n * const frameCount = useSignal(app.onFrame, () => app.frameCount);\n * return <span>Frame: {frameCount}</span>;\n * }\n * ```\n *\n * @param signal - The signal to subscribe to. `null`/`undefined` is accepted\n * (e.g. before an `Application` exists) - the hook simply does not subscribe\n * to anything and `getSnapshot` still runs on every render.\n * @param getSnapshot - Reads the current value. Called on mount and again after\n * every dispatch of `signal
|
|
1
|
+
{"version":3,"file":"useSignal.js","names":[],"sources":["../../src/useSignal.ts"],"sourcesContent":["import type { Signal } from '@codexo/exojs';\nimport { useCallback, useSyncExternalStore } from 'react';\n\n/**\n * Subscribes to an ExoJS {@link Signal} and returns the latest value computed by\n * `getSnapshot`, re-rendering the component every time the signal dispatches.\n * Built on `useSyncExternalStore`, so reads stay tear-free under concurrent\n * rendering.\n *\n * The signal itself is only used to know *when* to re-read - `getSnapshot` is\n * responsible for producing the actual value (usually a getter on the engine\n * object the signal lives on).\n *\n * @example\n * ```tsx\n * function FrameCounter() {\n * const app = useExoApp();\n * // Re-renders on every `onFrame` dispatch (i.e. every engine frame).\n * const frameCount = useSignal(app.onFrame, () => app.frameCount);\n * return <span>Frame: {frameCount}</span>;\n * }\n * ```\n *\n * @param signal - The signal to subscribe to. `null`/`undefined` is accepted\n * (e.g. before an `Application` exists) - the hook simply does not subscribe\n * to anything and `getSnapshot` still runs on every render.\n * @param getSnapshot - Reads the current value. Called on mount and again after\n * every dispatch of `signal`. `useSyncExternalStore` compares consecutive\n * results with `Object.is`, so return a primitive or a cached object that\n * stays identical until the underlying data changes; a fresh object on every\n * call re-renders without end.\n */\nexport const useSignal = <Args extends unknown[], T>(signal: Signal<Args> | null | undefined, getSnapshot: () => T): T => {\n const subscribe = useCallback(\n (onStoreChange: () => void): (() => void) => {\n if (!signal) {\n // No signal to subscribe to (e.g. before an Application exists) - nothing to unsubscribe either.\n return () => {\n // Nothing was subscribed, so there is nothing to unsubscribe.\n };\n }\n\n signal.add(onStoreChange);\n\n return () => {\n signal.remove(onStoreChange);\n };\n },\n [signal],\n );\n\n return useSyncExternalStore(subscribe, getSnapshot);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,aAAwC,QAAyC,gBAA4B;CACxH,MAAM,YAAY,aACf,kBAA4C;EAC3C,IAAI,CAAC,QAEH,aAAa,CAEb;EAGF,OAAO,IAAI,aAAa;EAExB,aAAa;GACX,OAAO,OAAO,aAAa;EAC7B;CACF,GACA,CAAC,MAAM,CACT;CAEA,OAAO,qBAAqB,WAAW,WAAW;AACpD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codexo/exojs-react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.0",
|
|
4
4
|
"description": "React integration for ExoJS.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"LICENSE"
|
|
27
27
|
],
|
|
28
28
|
"peerDependencies": {
|
|
29
|
-
"@codexo/exojs": "0.
|
|
29
|
+
"@codexo/exojs": "0.20.x",
|
|
30
30
|
"react": ">=18.0.0",
|
|
31
31
|
"react-dom": ">=18.0.0"
|
|
32
32
|
},
|
|
@@ -41,17 +41,17 @@
|
|
|
41
41
|
"@types/react": "^19.3.0",
|
|
42
42
|
"eslint": "~10.11.0",
|
|
43
43
|
"eslint-config-prettier": "^10.1.8",
|
|
44
|
-
"@codexo/exojs
|
|
45
|
-
"@codexo/exojs": "0.
|
|
44
|
+
"@codexo/exojs": "0.20.0",
|
|
45
|
+
"@codexo/exojs-config": "0.0.0"
|
|
46
46
|
},
|
|
47
47
|
"license": "MIT",
|
|
48
48
|
"publishConfig": {
|
|
49
49
|
"access": "public"
|
|
50
50
|
},
|
|
51
51
|
"scripts": {
|
|
52
|
-
"build": "tsx ../../scripts/build-extension.ts",
|
|
52
|
+
"build": "node --import tsx ../../scripts/build-extension.ts",
|
|
53
53
|
"build:dev": "tsx ../../scripts/build-extension.ts --dev",
|
|
54
54
|
"typecheck": "exo-tsc --noEmit && exo-tsc --noEmit -p tsconfig.test.json && exo-tsc --noEmit -p tsconfig.examples.json",
|
|
55
|
-
"lint": "eslint --max-warnings=0 ."
|
|
55
|
+
"lint": "oxlint --config ../../scripts/ci/oxlint-react-shadow.json --max-warnings=0 src examples && eslint --max-warnings=0 ."
|
|
56
56
|
}
|
|
57
57
|
}
|