@codexo/exojs-react 0.18.0 → 0.19.1

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 CHANGED
@@ -5,7 +5,7 @@ React 18 / 19 bindings for [ExoJS](https://exoridus.github.io/ExoJS/) - mount an
5
5
  ## Installation
6
6
 
7
7
  ```sh
8
- npm install @codexo/exojs @codexo/exojs-react react
8
+ npm install --save-exact @codexo/exojs @codexo/exojs-react react react-dom
9
9
  ```
10
10
 
11
11
  `@codexo/exojs` and `react` (>= 18) are peer dependencies; `react-dom` is an optional peer. The package ships pre-built ESM (`dist/esm`) with type declarations and works on both `@types/react` 18 and 19.
@@ -19,44 +19,73 @@ This package is intentionally layered:
19
19
 
20
20
  ## Quick start — `<ExoCanvas>`
21
21
 
22
+ The scene classes in `./scenes` are ordinary ExoJS scenes. Register their constructors in the application options; the React `<Scene>` declarations select from that registry rather than registering engine scenes themselves.
23
+
22
24
  ```tsx
23
- import { Color } from '@codexo/exojs';
24
- import { ExoCanvas, Scenes, Scene, useExoApp } from '@codexo/exojs-react';
25
- import { TitleScene, GameScene } from './scenes';
25
+ import { Color, FadeSceneTransition, FixedResolutionCanvasSizing, Time } from '@codexo/exojs';
26
+ import { ExoCanvas, Scene, Scenes } from '@codexo/exojs-react';
27
+ import { useState } from 'react';
28
+
29
+ import { GameScene, TitleScene } from './scenes';
30
+
31
+ const options = {
32
+ scenes: { TitleScene, GameScene },
33
+ canvas: { width: 1280, height: 720, sizing: new FixedResolutionCanvasSizing() },
34
+ clearColor: Color.black,
35
+ };
36
+ const transition = new FadeSceneTransition({ duration: Time.seconds(0.3) });
37
+
38
+ export function Game() {
39
+ const [active, setActive] = useState('title');
26
40
 
27
- function Game() {
28
41
  return (
29
- <ExoCanvas options={{ canvas: { width: 1280, height: 720 }, clearColor: Color.black }} style={{ width: 1280, height: 720 }}>
30
- <Scenes active="game" transition={{ type: 'fade', duration: 300 }}>
42
+ <ExoCanvas options={options} style={{ width: '100%', height: 480 }} onError={console.error}>
43
+ <Scenes active={active} transition={transition}>
31
44
  <Scene name="title" component={TitleScene} />
32
- <Scene name="game" component={GameScene}>
33
- <Hud /> {/* absolutely-positioned React overlay, over the canvas */}
34
- </Scene>
45
+ <Scene name="game" component={GameScene} />
35
46
  </Scenes>
47
+ <nav aria-label="Game screens" style={{ position: 'absolute', top: 8, left: 8 }}>
48
+ <button type="button" onClick={() => setActive('title')}>
49
+ Title
50
+ </button>
51
+ <button type="button" onClick={() => setActive('game')}>
52
+ Play
53
+ </button>
54
+ </nav>
36
55
  </ExoCanvas>
37
56
  );
38
57
  }
39
-
40
- function Hud() {
41
- const app = useExoApp();
42
- return <div style={{ position: 'absolute', top: 8, left: 8 }}>FPS overlay…</div>;
43
- }
44
58
  ```
45
59
 
46
- Layout props (`style`, `className`, …) apply to the **wrapper**; size it to drive `'fill'`/`'letterbox'` sizing. Style the canvas itself via `canvasProps`.
60
+ The first activation starts the engine; the transition applies to subsequent scene switches. Scene-load failures reach `onError`. For a production application, replace the console handler with the error presentation your interface needs.
61
+
62
+ Layout props (`style`, `className`, and other div attributes) apply to the **wrapper**. Give it a non-zero size and let the `FixedResolutionCanvasSizing` policy fit the logical canvas inside it. Use `canvasProps` for canvas attributes, but do not override the dimensions or styles owned by a sizing policy.
47
63
 
48
- ## Quick start — headless hook (full control)
64
+ ### Headless hook: your own canvas
65
+
66
+ The hook owns the application and its teardown, but does not choose a scene. Start a registered scene in `onReady`:
49
67
 
50
68
  ```tsx
51
69
  import { useExoApplication } from '@codexo/exojs-react';
52
70
 
53
- function Game() {
54
- const { app, canvasRef } = useExoApplication({ canvas: { width: 800, height: 600 } });
55
- // Render the canvas however and wherever you want.
56
- return <canvas ref={canvasRef} className="my-canvas" />;
71
+ import { GameScene } from './scenes';
72
+
73
+ const options = { scenes: { GameScene }, canvas: { width: 800, height: 600 } };
74
+
75
+ export function Game() {
76
+ const { canvasRef } = useExoApplication(
77
+ options,
78
+ app => {
79
+ void app.start(GameScene).catch(console.error);
80
+ },
81
+ console.error,
82
+ );
83
+ return <canvas ref={canvasRef} className="game-canvas" />;
57
84
  }
58
85
  ```
59
86
 
87
+ These are alternative hosting patterns, not two components to mount for one application. Use `<ExoCanvas>` for context and React overlays; use the hook for direct control over the canvas element.
88
+
60
89
  ## API
61
90
 
62
91
  | Export | Kind | Purpose |
@@ -68,7 +97,7 @@ function Game() {
68
97
  | `ExoContext` | context | The underlying context (advanced / testing). |
69
98
  | `useScene(SceneClass, deps?)` | hook | Instantiate + activate a single scene; returns it once live. Load failures route to `app.onError`. |
70
99
  | `Scenes` / `Scene` | components | Declarative scene switch over the one-active-scene model. Load failures route to `app.onError`. |
71
- | `useActiveScene()` | hook | The active scene instance from the nearest `<Scenes>`. |
100
+ | `useActiveScene(SceneClass?)` | hook | The active scene from the nearest `<Scenes>`; with `SceneClass`, only an instance of it, else `null`. |
72
101
  | `useSignal(signal, getSnapshot)` | hook | Subscribes to an engine `Signal` and re-renders on every dispatch (e.g. `app.onFrame`). |
73
102
 
74
103
  ### Reactivity model
@@ -82,6 +111,11 @@ Options without a live setter (`canvas.pixelRatio`, `seed`, `extensions`, …) a
82
111
 
83
112
  `canvas.sizing` is captured at creation as well: a sizing policy is an object, so a fresh instance on every render would detach and re-attach the previous one each time. Assign `app.sizing` yourself to switch strategies at runtime.
84
113
 
114
+ ## Learn more
115
+
116
+ - [React integration guide](https://exoridus.github.io/ExoJS/en/guide/integrations/react/)
117
+ - [Scene lifetimes and navigation](https://exoridus.github.io/ExoJS/en/guide/runtime/scenes-and-lifecycle/)
118
+
85
119
  ## License
86
120
 
87
121
  MIT © Codexo
@@ -4,8 +4,22 @@ import { type ReactElement, type ReactNode } from 'react';
4
4
  * Returns the currently-active scene instance from the nearest {@link Scenes},
5
5
  * or `null` while none is live. Useful for HUD/overlay components that need to
6
6
  * read scene state.
7
+ *
8
+ * Pass a scene class to narrow the result: the active scene is returned only
9
+ * when it is an instance of `SceneClass` (checked with `instanceof` at
10
+ * runtime), and `null` otherwise.
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * function Hud() {
15
+ * const scene = useActiveScene(GameScene);
16
+ * if (scene === null) return null;
17
+ * return <div>Score: {scene.score}</div>;
18
+ * }
19
+ * ```
7
20
  */
8
- export declare function useActiveScene<T extends ExoScene = ExoScene>(): T | null;
21
+ export declare function useActiveScene(): ExoScene | null;
22
+ export declare function useActiveScene<T extends ExoScene>(SceneClass: abstract new (...args: never[]) => T): T | null;
9
23
  /** Props for a {@link Scene} declaration. */
10
24
  export interface SceneProps {
11
25
  /** Unique name used to select this scene via {@link ScenesProps.active}. */
@@ -39,6 +53,13 @@ export interface ScenesProps {
39
53
  * scene's React children (HUD overlay) render alongside, and can read the
40
54
  * instance via {@link useActiveScene}.
41
55
  *
56
+ * Activations that run while startup is still in flight - React StrictMode
57
+ * double-mounts every effect in development, and `active` may change before
58
+ * the first scene has loaded - join that `app.start()` call instead of racing
59
+ * a second navigation against it, and only switch afterwards if startup did
60
+ * not already leave the requested scene active. A StrictMode double mount
61
+ * therefore activates the scene exactly once.
62
+ *
42
63
  * A failure in `app.start()`/`app.scenes.change()` (e.g. a scene's `load()`
43
64
  * rejects) is caught and routed to {@link Application.onError} rather than
44
65
  * left as an unhandled promise rejection - subscribe via `app.onError.add(...)`
@@ -1 +1 @@
1
- {"version":3,"file":"Scenes.d.ts","sourceRoot":"","sources":["../../src/Scenes.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,KAAK,IAAI,QAAQ,EAAE,KAAK,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACxG,OAAO,EAA2C,KAAK,YAAY,EAAE,KAAK,SAAS,EAA4C,MAAM,OAAO,CAAC;AAQ7I;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,QAAQ,GAAG,QAAQ,KAAK,CAAC,GAAG,IAAI,CAExE;AAED,6CAA6C;AAC7C,MAAM,WAAW,UAAU;IACzB,4EAA4E;IAC5E,QAAQ,CAA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Q,CAAC,SAAS,EAAE,UAAU,QAAQ,CAAC;IACvC,oEAAoE;IACpE,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC;CAC/B;AAED;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,MAAM,EAAE,UAAU,GAAG,YAAY,GAAG,IAAI,CAE7D;AAED,2CAA2C;AAC3C,MAAM,WAAW,WAAW;IAC1B,qEAAqE;IACrE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,wFAAwF;IACxF,QAAQ,CAAC,UAAU,CAAC,EAAE,wBAAwB,CAAC;IAC/C,kCAAkC;IAClC,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC;CAC/B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAgB,MAAM,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,EAAE,WAAW,GAAG,YAAY,CA4FlF"}
@@ -1,5 +1,5 @@
1
1
  import { useExoApp } from "./useExoApp.js";
2
- import { Children, createContext, isValidElement, useContext, useEffect, useMemo, useState } from "react";
2
+ import { Children, createContext, isValidElement, useContext, useEffect, useMemo, useRef, useState } from "react";
3
3
  import { ApplicationState } from "@codexo/exojs";
4
4
  import { jsx } from "react/jsx-runtime";
5
5
 
@@ -7,13 +7,10 @@ import { jsx } from "react/jsx-runtime";
7
7
  /** Carries the active {@link ExoScene} instance to descendants (HUD overlays). */
8
8
  const ActiveSceneContext = createContext(null);
9
9
  ActiveSceneContext.displayName = "ExoActiveScene";
10
- /**
11
- * Returns the currently-active scene instance from the nearest {@link Scenes},
12
- * or `null` while none is live. Useful for HUD/overlay components that need to
13
- * read scene state.
14
- */
15
- function useActiveScene() {
16
- return useContext(ActiveSceneContext);
10
+ function useActiveScene(SceneClass) {
11
+ const scene = useContext(ActiveSceneContext);
12
+ if (SceneClass === void 0) return scene;
13
+ return scene instanceof SceneClass ? scene : null;
17
14
  }
18
15
  /**
19
16
  * Declares one scene inside a {@link Scenes} switch. Renders nothing on its own -
@@ -32,6 +29,13 @@ function Scene(_props) {
32
29
  * scene's React children (HUD overlay) render alongside, and can read the
33
30
  * instance via {@link useActiveScene}.
34
31
  *
32
+ * Activations that run while startup is still in flight - React StrictMode
33
+ * double-mounts every effect in development, and `active` may change before
34
+ * the first scene has loaded - join that `app.start()` call instead of racing
35
+ * a second navigation against it, and only switch afterwards if startup did
36
+ * not already leave the requested scene active. A StrictMode double mount
37
+ * therefore activates the scene exactly once.
38
+ *
35
39
  * A failure in `app.start()`/`app.scenes.change()` (e.g. a scene's `load()`
36
40
  * rejects) is caught and routed to {@link Application.onError} rather than
37
41
  * left as an unhandled promise rejection - subscribe via `app.onError.add(...)`
@@ -54,6 +58,7 @@ function Scene(_props) {
54
58
  function Scenes({ active, transition, children }) {
55
59
  const app = useExoApp();
56
60
  const [instance, setInstance] = useState(null);
61
+ const generationRef = useRef(0);
57
62
  const entry = useMemo(() => {
58
63
  const map = /* @__PURE__ */ new Map();
59
64
  Children.forEach(children, (child) => {
@@ -66,19 +71,25 @@ function Scenes({ active, transition, children }) {
66
71
  }, [children]).get(active);
67
72
  const SceneClass = entry?.component ?? null;
68
73
  useEffect(() => {
74
+ const generation = ++generationRef.current;
69
75
  if (SceneClass === null) {
70
76
  console.warn(`<Scenes>: no <Scene name="${active}"> declaration found; the previously active scene (if any) keeps running.`);
71
77
  setInstance(null);
72
78
  return;
73
79
  }
74
80
  let cancelled = false;
81
+ const isStale = () => cancelled || generationRef.current !== generation;
82
+ const changeOptions = transition !== void 0 ? { transition } : {};
75
83
  const apply = async () => {
76
84
  try {
77
- if (app.state === ApplicationState.Stopped) await app.start(SceneClass);
78
- else await app.scenes.change(SceneClass, transition !== void 0 ? { transition } : {});
79
- if (!cancelled) setInstance(app.scenes.currentScene);
85
+ if (app.state === ApplicationState.Stopped || app.state === ApplicationState.Loading) {
86
+ await app.start(SceneClass);
87
+ if (isStale()) return;
88
+ if (app.scenes.currentScene?.constructor !== SceneClass) await app.scenes.change(SceneClass, changeOptions);
89
+ } else await app.scenes.change(SceneClass, changeOptions);
90
+ if (!isStale()) setInstance(app.scenes.currentScene);
80
91
  } catch (error) {
81
- app.onError.dispatch(error instanceof Error ? error : new Error(String(error)));
92
+ if (!isStale()) app.onError.dispatch(error instanceof Error ? error : new Error(String(error)));
82
93
  }
83
94
  };
84
95
  apply();
@@ -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, 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 */\nexport function useActiveScene<T extends ExoScene = ExoScene>(): T | null {\n return useContext(ActiveSceneContext) as T | 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 * 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\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 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\n const apply = async (): Promise<void> => {\n try {\n if (app.state === ApplicationState.Stopped) {\n // First activation initializes the backend and starts the frame loop;\n // transitions only apply to subsequent switches.\n await app.start(SceneClass);\n } else {\n await app.scenes.change(SceneClass, transition !== undefined ? { transition } : {});\n }\n if (!cancelled) {\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 app.onError.dispatch(error instanceof Error ? error : new Error(String(error)));\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":";;;;;;;AAMA,MAAM,qBAAqB,cAA+B,IAAI;AAC9D,mBAAmB,cAAc;;;;;;AAOjC,SAAgB,iBAA0D;CACxE,OAAO,WAAW,kBAAkB;AACtC;;;;;;AAiBA,SAAgB,MAAM,QAAyC;CAC7D,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,OAAO,EAAE,QAAQ,YAAY,YAAuC;CAClF,MAAM,MAAM,UAAU;CACtB,MAAM,CAAC,UAAU,eAAe,SAA0B,IAAI;CAc9D,MAAM,QAXW,cAAc;EAC7B,MAAM,sBAAM,IAAI,IAAwB;EACxC,SAAS,QAAQ,WAAU,UAAS;GAClC,IAAI,eAAe,KAAK,KAAK,MAAM,SAAS,OAAO;IACjD,MAAM,QAAQ,MAAM;IACpB,IAAI,IAAI,MAAM,MAAM,KAAK;GAC3B;EACF,CAAC;EACD,OAAO;CACT,GAAG,CAAC,QAAQ,CAES,CAAC,CAAC,IAAI,MAAM;CACjC,MAAM,aAAa,OAAO,aAAa;CAEvC,gBAAgB;EACd,IAAI,eAAe,MAAM;GAMvB,QAAQ,KAAK,6BAA6B,OAAO,0EAA0E;GAC3H,YAAY,IAAI;GAChB;EACF;EAEA,IAAI,YAAY;EAEhB,MAAM,QAAQ,YAA2B;GACvC,IAAI;IACF,IAAI,IAAI,UAAU,iBAAiB,SAGjC,MAAM,IAAI,MAAM,UAAU;SAE1B,MAAM,IAAI,OAAO,OAAO,YAAY,eAAe,SAAY,EAAE,WAAW,IAAI,CAAC,CAAC;IAEpF,IAAI,CAAC,WACH,YAAY,IAAI,OAAO,YAAY;GAEvC,SAAS,OAAO;IAId,IAAI,QAAQ,SAAS,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;GAChF;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 { 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":";;;;;;;AAMA,MAAM,qBAAqB,cAA+B,IAAI;AAC9D,mBAAmB,cAAc;AAsBjC,SAAgB,eAAmC,YAAoE;CACrH,MAAM,QAAQ,WAAW,kBAAkB;CAE3C,IAAI,eAAe,QACjB,OAAO;CAGT,OAAO,iBAAiB,aAAa,QAAQ;AAC/C;;;;;;AAiBA,SAAgB,MAAM,QAAyC;CAC7D,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,SAAgB,OAAO,EAAE,QAAQ,YAAY,YAAuC;CAClF,MAAM,MAAM,UAAU;CACtB,MAAM,CAAC,UAAU,eAAe,SAA0B,IAAI;CAG9D,MAAM,gBAAgB,OAAO,CAAC;CAc9B,MAAM,QAXW,cAAc;EAC7B,MAAM,sBAAM,IAAI,IAAwB;EACxC,SAAS,QAAQ,WAAU,UAAS;GAClC,IAAI,eAAe,KAAK,KAAK,MAAM,SAAS,OAAO;IACjD,MAAM,QAAQ,MAAM;IACpB,IAAI,IAAI,MAAM,MAAM,KAAK;G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,CAAC,SAAS,EAAE,GAAG,CAAC,iBAAiB,CAAC,CAAC;CAC5C;AAKD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,eAAO,MAAM,iBAAiB,aAClB,qBAAqB,YACrB,CAAC,GAAG,EAAE,WAAW,KAAK,IAAI,YAC1B,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,KACjC,uBAwFF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"useScene.d.ts","sourceRoot":"","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,EAAE,YAAY,UAAU,CAAC,EAAE,OAAM,cAAmB,KAAG,CAAC,GAAG,IAkFlG,CAAC"}
1
+ {"version":3,"file":"useScene.d.ts","sourceRoot":"","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,IAkFlG,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"useSignal.d.ts","sourceRoot":"","sources":["../../src/useSignal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAG5C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,SAAS,GAAI,IAAI,SAAS,OAAO,EAAE,EAAE,CAAC,EAAE,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,SAAS,EAAE,aAAa,MAAM,CAAC,KAAG,CAoBpH,CAAC"}
1
+ {"version":3,"file":"useSignal.d.ts","sourceRoot":"","sources":["../../src/useSignal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAG5C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codexo/exojs-react",
3
- "version": "0.18.0",
3
+ "version": "0.19.1",
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.18.x",
29
+ "@codexo/exojs": "0.19.x",
30
30
  "react": ">=18.0.0",
31
31
  "react-dom": ">=18.0.0"
32
32
  },
@@ -36,13 +36,13 @@
36
36
  }
37
37
  },
38
38
  "devDependencies": {
39
- "@testing-library/dom": "^10.4.1",
40
- "@testing-library/react": "^16.3.2",
41
- "@types/react": "^19.2.17",
42
- "eslint": "~10.9.1",
39
+ "@testing-library/dom": "^10.4.2",
40
+ "@testing-library/react": "^16.3.3",
41
+ "@types/react": "^19.3.0",
42
+ "eslint": "~10.11.0",
43
43
  "eslint-config-prettier": "^10.1.8",
44
- "@codexo/exojs-config": "0.0.0",
45
- "@codexo/exojs": "0.18.0"
44
+ "@codexo/exojs": "0.19.1",
45
+ "@codexo/exojs-config": "0.0.0"
46
46
  },
47
47
  "license": "MIT",
48
48
  "publishConfig": {
@@ -51,7 +51,7 @@
51
51
  "scripts": {
52
52
  "build": "tsx ../../scripts/build-extension.ts",
53
53
  "build:dev": "tsx ../../scripts/build-extension.ts --dev",
54
- "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json && tsc --noEmit -p tsconfig.examples.json",
54
+ "typecheck": "exo-tsc --noEmit && exo-tsc --noEmit -p tsconfig.test.json && exo-tsc --noEmit -p tsconfig.examples.json",
55
55
  "lint": "eslint --max-warnings=0 ."
56
56
  }
57
57
  }