edbentley / replay

A cross-platform JS game engine inspired by React
https://replay.js.org
MIT License
298 stars 11 forks source link

Chrome Devtools state inspector #21

Open ejb opened 4 years ago

ejb commented 4 years ago

I'm working on a Chrome Devtools state inspector. The repo is here: https://github.com/ejb/replay-inspector

(You'll need to clone it, npm install, then npm run to install the Chrome plugin.)

My hacky way of exposing the game's state globally is to edit core.js like so:

function traverseSpriteContainer(spriteContainer, spriteProps, getDevice, initCreation, renderMethod, time) {

    if (window.__replay_state__ === undefined) {
      window.__replay_state__ = {};
    }
    if (spriteContainer.state) {
      window.__replay_state__[spriteProps.id] = spriteContainer.state;
    }

Any suggestions for a better way to expose the state for a plugin?

edbentley commented 4 years ago

This will be really helpful to have!

react-devtools mentions it uses a global __REACT_DEVTOOLS_GLOBAL_HOOK__, you can sort of see how that works here. So replay-core won't put anything on the global unless it detects the inspector exists.

Sprite ids aren't unique globally so you're better off keeping a nested tree-like structure to store state. In the replayCore function you could put gameContainer on the global - that's a SpriteContainer which contains a state field and all its children's state too.

ejb commented 4 years ago

I'm a typescript noob, how do I access the global window object? Webpack keeps throwing this error.

src/core.ts(142,44): error TS2304: Cannot find name 'window'.
src/core.ts(144,9): error TS2304: Cannot find name 'window'.
edbentley commented 4 years ago

You can satisfy TypeScript by adding "DOM" as a lib here:

https://github.com/edbentley/replay/blob/b77054071adf1a886c57f054fcb072f39df56439/packages/replay-core/tsconfig.json#L5

But replay-core isn't guaranteed to run on the web so this isn't ideal. I'd suggest using globalThis instead. It's relatively new but I'd presume anyone using devtools is going to be on the latest browser - but it's still worth checking it exists to avoid errors where it doesn't.