refactor: context update
This commit is contained in:
parent
6c86a97c8f
commit
bf62805c38
|
|
@ -2,8 +2,9 @@ import Phaser from 'phaser';
|
||||||
import { signal, useSignal, useSignalEffect, type Signal } from '@preact/signals';
|
import { signal, useSignal, useSignalEffect, type Signal } from '@preact/signals';
|
||||||
import { createContext, h } from 'preact';
|
import { createContext, h } from 'preact';
|
||||||
import { useContext } from 'preact/hooks';
|
import { useContext } from 'preact/hooks';
|
||||||
|
import {ReadonlySignal} from "@preact/signals-core";
|
||||||
|
|
||||||
export const phaserContext = createContext<Signal<Phaser.Game | undefined>>(signal(undefined));
|
export const phaserContext = createContext<ReadonlySignal<Phaser.Game | undefined>>(signal(undefined));
|
||||||
|
|
||||||
export const defaultPhaserConfig: Phaser.Types.Core.GameConfig = {
|
export const defaultPhaserConfig: Phaser.Types.Core.GameConfig = {
|
||||||
type: Phaser.AUTO,
|
type: Phaser.AUTO,
|
||||||
|
|
@ -50,20 +51,25 @@ export interface PhaserSceneProps {
|
||||||
scene: Phaser.Scene;
|
scene: Phaser.Scene;
|
||||||
autoStart: boolean;
|
autoStart: boolean;
|
||||||
data?: object;
|
data?: object;
|
||||||
|
children?: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const phaserSceneContext = createContext<ReadonlySignal<Phaser.Scene | undefined>>(signal(undefined));
|
||||||
export function PhaserScene(props: PhaserSceneProps) {
|
export function PhaserScene(props: PhaserSceneProps) {
|
||||||
const context = useContext(phaserContext);
|
const context = useContext(phaserContext);
|
||||||
|
const sceneSignal = useSignal<Phaser.Scene>();
|
||||||
|
|
||||||
useSignalEffect(() => {
|
useSignalEffect(() => {
|
||||||
const game = context.value;
|
const game = context.value;
|
||||||
if (!game) return;
|
if (!game) return;
|
||||||
|
|
||||||
game.scene.add(props.sceneKey, props.scene, props.autoStart, props.data);
|
game.scene.add(props.sceneKey, props.scene, props.autoStart, props.data);
|
||||||
|
sceneSignal.value = game.scene.getScene(props.sceneKey);
|
||||||
return () => {
|
return () => {
|
||||||
|
sceneSignal.value = undefined;
|
||||||
game.scene.remove(props.sceneKey);
|
game.scene.remove(props.sceneKey);
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
return null;
|
return <phaserSceneContext.Provider value={sceneSignal}>{props.children}</phaserSceneContext.Provider>;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue