Skip to content

Commit

Permalink
feat(hooks): pass optional type generic to useScene
Browse files Browse the repository at this point in the history
  • Loading branch information
remarkablemark committed Apr 2, 2024
1 parent 532f59c commit 6d0d619
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 10 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,14 @@ const scene = useScene();
> [!WARNING]
> Don't use this hook if you start multiple Scenes.
To specify a Scene class in TypeScript:

```ts
class MyScene extends Phaser.Scene {}

const scene = useScene<typeof MyScene>();
```

## Release

Release is automated with [Release Please](https://github.com/googleapis/release-please).
Expand Down
15 changes: 11 additions & 4 deletions src/helpers/scene.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,15 @@ afterEach(() => {
setScene(undefined as unknown as Scene);
});

it('sets and gets scene', () => {
expect(getScene()).toEqual(undefined);
expect(setScene(scene)).toEqual(undefined);
expect(getScene()).toEqual(scene);
describe('getScene', () => {
it('gets scene', () => {
expect(getScene<typeof scene>()).toEqual(undefined);
});
});

describe('setScene', () => {
it('sets scene', () => {
expect(setScene(scene)).toEqual(undefined);
expect(getScene()).toEqual(scene);
});
});
4 changes: 2 additions & 2 deletions src/helpers/scene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import type { Scene } from 'phaser';

let _scene: Scene;

export function getScene() {
return _scene;
export function getScene<Type = Scene>() {
return _scene as Type;
}

export function setScene(scene: Scene) {
Expand Down
4 changes: 4 additions & 0 deletions src/hooks/useScene.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ it('returns scene', () => {
expect(useScene()).toEqual(scene);
expect(mockedGetScene).toHaveBeenCalledTimes(1);
});

it('returns undefined', () => {
expect(useScene<undefined>()).toEqual(undefined);
});
6 changes: 4 additions & 2 deletions src/hooks/useScene.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Scene } from 'phaser';

import { getScene } from '../helpers';

/**
Expand All @@ -7,6 +9,6 @@ import { getScene } from '../helpers';
*
* @returns Phaser.Scene
*/
export function useScene() {
return getScene();
export function useScene<Type = Scene>() {
return getScene<Type>();
}
4 changes: 2 additions & 2 deletions src/types/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
export type RecursivePartial<Type> = {
[Property in keyof Type]?: RecursivePartial<Type[Property]>;
};

0 comments on commit 6d0d619

Please sign in to comment.