Giter Site home page Giter Site logo

pixijs / pixi-react Goto Github PK

View Code? Open in Web Editor NEW
2.1K 22.0 165.0 21.26 MB

Write PIXI apps using React declarative style

Home Page: https://pixijs.io/pixi-react/

License: MIT License

JavaScript 85.92% Shell 0.02% CSS 0.66% HTML 0.14% MDX 13.26%
react pixi renderer react-fiber

pixi-react's Introduction

pixi-react

Pixi React

Simply the best way to write PixiJS applications in React
Write PixiJS applications using React declarative style πŸ‘Œ


release downloads ci tests license react version pixi version


Pixi React is an open-source, production-ready library to render high performant PixiJS applications in React.

Features

  • React 17 and 18 support
  • PixiJS v6 and v7 support
  • react-spring compatible animated components

Get started

Quick start

If you want to start a new React project from scratch, we recommend Create React App. To add to an existing React application, just install the dependencies:

Start New React Project "my-app" with Create React App:

# for typescript add "--template typescript"
npx create-react-app my-app
cd my-app

Install Pixi React Dependencies:

npm install pixi.js @pixi/react

Usage:

import { BlurFilter } from 'pixi.js';
import { Stage, Container, Sprite, Text } from '@pixi/react';
import { useMemo } from 'react';

export const MyComponent = () =>
{
  const blurFilter = useMemo(() => new BlurFilter(4), []);

  return (
    <Stage options={{ background: 0xffffff }}>
      <Sprite
        image="https://pixijs.io/pixi-react/img/bunny.png"
        x={400}
        y={270}
        anchor={{ x: 0.5, y: 0.5 }}
      />

      <Container x={400} y={330}>
        <Text text="Hello World" anchor={{ x: 0.5, y: 0.5 }} filters={[blurFilter]} />
      </Container>
    </Stage>
  );
};

Docs

Check out our documentation for guides and a full API reference.

Or checkout our examples on codepen for inspiration.

Contribute

Want to contribute to Pixi React? Our contributing guide has you covered.

License

Pixi React is MIT licensed.

This project was originally created and maintained by @inlet. He graciously gave the Pixi team the keys to maintain and push the project forward. Big thanks for all the hard work on making this project so awesome.

This projects codebase was originally forked from @michalochman 's react-pixi-fiber.

Meet fellow developers

You have an amazing feature in mind or just want to get in touch with other developers? Feel free to join our Discord channel.

Join us on Discord

pixi-react's People

Contributors

adsko avatar aku11i avatar baco16g avatar baseten avatar cometkim avatar dependabot[bot] avatar effy-coding avatar elob avatar fabienjuif avatar goodboydigital avatar inlet avatar kiochan avatar ledzz avatar lunarraid avatar mattjennings avatar maximtwo avatar pablolion avatar pengx17 avatar queq1890 avatar rluncasu avatar rodrigohamuy avatar sabigara avatar spassvogel avatar vijayst avatar wtgtybhertgeghgtwtg avatar xaviergonz avatar ximing avatar zenios avatar zoadt avatar zyie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pixi-react's Issues

How to test react-pixi components

Description

It would be good if we can also write on the documentation about how to test our components.
(They print on a canvas, not change DOM elements. The changes can not be marked and asserted/checked using anything similar css rules or dom elements properties. Example: Graphics.draw method.)
It does not seem to be as straight forward as testing normal (dom) components.

Once I know how these can be tested, I can write a documentation page for it.

My problem

I'm investigating how I should test my components and I'm having a bit of trouble so far.
Once I get it working, I think I'm gonna save an image of the canvas to have something to compare it to in future tests/changes...similar to snapshots.

What I've tried

So far I tried using Jest and Enzyme (shallow), with and without wrapping it with .
What I'm getting all the time is Cannot set property 'fillStyle' of null.

Edit (): Clarification regarding the test of the components.

Wrong TS definition for anchor

image

Following works well
anchor={[0.5, 0]}
anchor={0.5}
anchor={[0.5]}

currently type comes from pixi.js.d.ts as anchor: PIXI.ObservablePoint;

Additional info

  • @inlet/react-pixi version: ^0.5.5
  • React version: ^16.8.2
  • ReactDOM version: ^16.6.1
  • PIXI version: ^5.0.0-rc.2

Implementation of docz

Description

I'd like to contribute to the project by creating a PR that contains the documentation of this awesome project :)
This would improve the use and readability of the library.

  • With documentation of each component
  • Examples of each component
  • Can be used as github page
  • Can be used as development environment for the library. While you create the components you can see the changes with hot reload and debug them if necessary.

I have implemented docz for my own project, which uses your components.
Altho it uses Pixi as a render layer, it's really easy to implement.

Additional info

Cheers

Unable to unset `cursor` property

Description

I am trying to temporarily set the cursor style of a child element during an interaction, and then to remove the child cursor style so that the cursor's appearance reverts to that set on the parent element when the interaction is completed. However, currently I'm unable to set the cursor property to null due to https://github.com/inlet/react-pixi/blob/master/src/utils/props.js#L113. I would expect to be warned in this case, but still be able to set the property to null if I wanted to.

This issue doesn't appear immediately (possibly indicating that the cursor default of 'auto' isn't applied initially). Initially, the parent's cursor styles are presented when mousing over the child element. However, once the child element's cursor property is set to anything (including 'auto'!), the parent's cursor style is never again presented.

I believe that setting the cursor property's value to 'auto' is incorrect, and that there should be no default for this property. Furthermore, as the developer, I shouldn't be prevented from setting any property to null if I so choose.

I am aware that I'll be able to work around this issue by setting the new overwriteProps property to true in future releases. However, there is no work-around for version 0.1.0. When is the next release scheduled?

Steps to reproduce

  1. Create a parent element with a single child element
  2. Set the parent's cursor property to e.g. 'crosshair', and observe that this style is presented when mousing over the child element
  3. Set the child element's cursor property to e.g. 'zoom-in', and observe that this style is now presented when mousing over the child element, rather than the parent's 'crosshair' style.
  4. Set the child element's cursor to null, observe a console warning indicating that ReactPixi won't set the cursor property to null but rather will use the default value of 'auto', and observe that the default cursor style of 'auto' is presented when mousing over the child element, rather than the parent's 'crosshair' style.
  5. Try setting the child element's cursor to 'inherit', 'default', 'initial', etc. and observe that the parent's cursor style isn't presented regardless of the value of the child's cursor property.

Additional info

  • @inlet/react-pixi version: 0.1.0
  • React version: 16.4.1
  • ReactDOM version: 16.4.1
  • PIXI version: 4.8.1

Discussion about be able to use Stage in Stage?

It would be kind of interesting to be able to use a Stage within a Stage. By doing so you should be able to turn off raf on a specific branch on your React tree. What do you think? πŸ˜ƒ

Feature request make resolution dynamic

Working with resolution really fits React. You can define components and set their sizes and let the resolution do it's magic.

Preferred solution would be to set the Stage to the desired dimension with static values (best practice to use the same dimension as the design files to be able to copy values) for instance 1920x1080 and use resolution to scale each object and canvas. On rare occasions you need the resolution so it would be good if it's being passed as a context.

Example
This is just an ugly hack with key.
http://jsbin.com/heyonevonu/1/edit?js,output

Using this plugin. You gain a lot of easy performance! :)
https://babeljs.io/docs/en/next/babel-plugin-transform-react-constant-elements.html

UglifyJs: Unexpected token: punc (})

Description

When I try to uglify the build I'm getting this:

ERROR in bundle.js from UglifyJs
Unexpected token: punc (}) [./node_modules/@inlet/react-pixi/dist/react-pixi.development.es5.js:9765,19][bundle.js:59126,28] 

That confusingly points to line:
console.log({hostFiber});

It didnt happen before i started using @inlet/react-pixi

Steps to reproduce

  1. clone the repo (https://github.com/smith-chris/poke/tree/d6d07a556accbef4962037789049a6cc592cb681) and follow the instructions (you probs just need to npm i
  2. run npm run prod to see the error appear

Additional info

I'll just link specific tree to reproduce: https://github.com/smith-chris/poke/tree/d6d07a556accbef4962037789049a6cc592cb681

You can also see that commit before that used react-pixi-fiber and it does not have the same problem: https://github.com/smith-chris/poke/tree/aa73b342232c83acb15a70abdf3e6b2150da0abb

I hope that all the info you need to reproduce that issue. BTW I really like how painless it was to switch to this lib from react-pixi-fiber and I find yours ~30% faster. Good stuff!

Cheers,
Chris

EDIT:
I've updated all my dependencies and error still appears.

Now I think about it the problem is that you have object literal property value shorthand which is ES6. I guess my uglifyjs is setup in a way that it expects es5 and I could change that but giving that the name of the file is react-pixi.development.es5.js it should be fixed somewhere within react-pixi build setup.

Update anchor type definition for Sprite

Description

The type definition for the anchor prop on Sprite is able to take an array, but the type definition requires an ObservablePoint. The following error occurs when using an array:

TS2740: Type 'number[]' is missing the following properties from type 'ObservablePoint': clone, equals, cb, scope, and 4 more.

An example shows using an array to set the anchor

Steps to reproduce

  1. Create a typescript project using @types/pixi.js
  2. Try to add an anchor prop to a Sprite as an array.

Additional info

  • @inlet/react-pixi version: 0.4.2
  • React version: 16.7.0-alpha.2
  • ReactDOM version: 16.7.0-alpha.2
  • PIXI version: 4.8.4

react-devtools support

Alo. Any plans to support react-devtools?

Currently it only shows up to the canvas element.

image

I think Izzimach version of react-pixi does support this:
react-pixi-devshot

More info: facebook/react-devtools#160

Keep it up with the great work!

./components/Rectangle.js

Description

I try to do a custom components.
I get an error:
Attempted to assign to readonly property.

Steps to reproduce

  1. I have juste add your example. (has is) to a simple React project.
  2. I add it to the stage.

Additional info

  • @inlet/react-pixi version: "^0.3.0",
  • React version: "^16.6.1"
  • ReactDOM version: "^16.6.1"
  • PIXI version: "^4.8.2"

Incompat with React 16.6.0

Description

version 0.2.0 works well with up to [email protected], but not with 16.6.0

Error printed:

Uncaught Error: Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.
    at invariant (MASKED/node_modules/@inlet/react-pixi/node_modules/react-reconciler/cjs/react-reconciler.development.js:52)
    at findCurrentUnmaskedContext (MASKED/node_modules/@inlet/react-pixi/node_modules/react-reconciler/cjs/react-reconciler.development.js:1484)
    at getContextForSubtree (MASKED/node_modules/@inlet/react-pixi/node_modules/react-reconciler/cjs/react-reconciler.development.js:9845)
    at updateContainerAtExpirationTime (MASKED/node_modules/@inlet/react-pixi/node_modules/react-reconciler/cjs/react-reconciler.development.js:9902)
    at Object.updateContainer (MASKED/node_modules/@inlet/react-pixi/node_modules/react-reconciler/cjs/react-reconciler.development.js:9936)
    at Stage.updateContainer [as componentDidMount] (MASKED/node_modules/@inlet/react-pixi/src/stage/index.js:120)
    at commitLifeCycles (MASKED/node_modules/react-dom/cjs/react-dom.development.js:15255)
    at commitAllLifeCycles (MASKED/node_modules/react-dom/cjs/react-dom.development.js:16523)
    at HTMLUnknownElement.callCallback (MASKED/node_modules/react-dom/cjs/react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (MASKED/node_modules/react-dom/cjs/react-dom.development.js:199)

It seems to me the cause is reconciler's update, but I'm not sure with little knowledge about how it works

Steps to reproduce

use this package with React 16.6.0, or simply update devDep's React and run the test

Additional info

  • @inlet/react-pixi version: 0.2.0
  • React version: 16.6.0
  • ReactDOM version: 16.6.0
  • PIXI version: 4.8.2

Feature request onDimensionChange

I'm not sure if it's possible to add (maybe because of performance reasons) but it would be nice to somehow listen to a prop onDimensionChange or add some example how to getting the dimension from an object πŸ˜ƒ

Here is one use case:

<Text text={someDynamicString} onDimensionChange={handleResize} />

How do I get the text dimension?

Update typescript definition

Description

In this example you show how work with interactive click. But if you try to do this in typescript you get an error about pointerdown and anchor. So I think that just need add pointerdown to index.d.ts for Sprite and change anchor to take number[], because when I've done this all worked.
And please add into documentation the section how works with different events in React style (mouseover, click, drag'n'drop, etc..)

Steps to reproduce

<Sprite
  texture={texture}
  x={25}
  y={680}
  interactive={true}
  pointerdown={this._onClick}
 >
    <Text text="CLICK"/>
</Sprite>

Give an error:
Property 'pointerdown' does not exist on type 'IntrinsicAttributes & SpriteProperties & { children?: ReactNode; }'

Additional info

screenshot from 2018-09-06 10-33-10

Incompatibility with Redux

I added Redux in my app but it doesn't seem to work; if I try to retrieve data from store in a children of I receive this error:

Could not find "store" in the context of "Connect(Section)". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to Connect(Section) in connect options.

Use Pixi Geometry in PixiComponent

Is it possible to feed PixiComponent with other then Graphics type?

image

Additional info

  • @inlet/react-pixi version: "^0.5.5"
  • React version: "^16.8.2"
  • ReactDOM version: "^16.6.1"
  • PIXI version: "^5.0.0-rc.2"

ParticleContainer not respecting maxSize prop

Description

I'm not able to get ParticleContainer component to work with maxSize. Setting the prop does not work. However using PixiComponent to instantiate a PIXI.ParticleContainer with maxSize works.

Steps to reproduce

class MyList extends PureComponent {
 render() {
   const { rows, cols } = {rows: 200, cols: 200};
   var elems = [];
   for (var row = 0; row < rows; row++) {
     for (var col = 0; col < cols; col++) {
       elems.push(
         <Sprite
           key={row * rows + col}
           x={col * 220}
           y={row * 250}
           image={someSprite}
         />
       );
     }
   }
   return (
     <ParticleContainer
       maxSize={40000}
     >
       {elems}
     </ParticleContainer>
   );
 }
}

This renders only the first 1500 sprites (8 rows in this example). Changing ParticleContainer to Container renders all. Also using a CustomParticleContainer made with PixiComponent works.

Additional info

  • @inlet/react-pixi version: 0.10
  • React version: 16.4.1
  • ReactDOM version: 16.4.1
  • PIXI version: 4.8.1

AppConsumer does not work if Pixi application not has been created using Stage

Description

The AppConsumer returns { app: undefined } when the app is not created using component.

Steps to reproduce

See example one: https://codepen.io/anon/pen/YJYxRZ?editors=0010 (Notice console.log on line 19)
See example two (original example): https://codepen.io/inlet/pen/aYLvrZ?editors=0010

Additional info

Consumer inside Stage

Description

Consumer inside Stage doesn't update.

Steps to reproduce

import * as React from 'react';
import { Stage, Text } from '@inlet/react-pixi';

const defaultValue = { 
    data: 0
};
const Context = React.createContext<any>(defaultValue);

export default class App extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = defaultValue
    }

    componentDidMount() {
        setInterval(() => {
            this.setState({
                data: this.state.data + 1
            })
        }, 1000)
    }

    render() {
        return (
            <Context.Provider
                value={this.state}
            >
                <Context.Consumer>
                    {({data}) => (
                        <>
                            <p>This works: {data}</p>
                            <Stage
                                options={{ 
                                    backgroundColor: 0xffffff,
                                    antialias: true,
                                    resolution: window.devicePixelRatio,
                                }}
                            >
                                <Context.Consumer>
                                    {({data}) => (
                                        <Text text={`This doesn't: ${data}`} />
                                    )}
                                </Context.Consumer>
                            </Stage>
                        </>
                    )}
                </Context.Consumer>
            </Context.Provider>
        );
    }
}

Additional info

  • @inlet/react-pixi version: 0.1.7
  • React version: 16.5.2
  • ReactDOM version: 16.5.2
  • PIXI version: 4.8.2

Custom Component example in readme incorrect

Description

Incorrect custom component example in readme. Should not instantiate custom component with var x = new PixiComponent(...), just do var x = PixiComponent(...) otherwise TypeError thrown by react.

Steps to reproduce

  1. Make component eg. var CustomComponent = new PixiComponent('MyComponent', {})

Additional info

  • @inlet/react-pixi version: 0.1.0
  • React version: 16.4.1
  • ReactDOM version: 16.4.1
  • PIXI version: 4.8.1

pixi.js dependency

Description

I might be missing something stupid (given my recent PR!) but npm install @inlet/react-pixi --save is not installing pixi.js

It's possible that yarn automatically installs peerDependencies (I didn't try) but npm no longer does. So maybe note this in "Install" section of README? An extra step is needed with npm.

Steps to reproduce

  1. npm install @inlet/react-pixi --save
  2. import { Stage, Text, Container } from '@inlet/react-pixi'
ERROR in ./node_modules/@inlet/react-pixi/dist/react-pixi.module-dev.js
Module not found: Error: Can't resolve 'pixi.js' in '/Users/matt/projects/xxx/node_modules/@inlet/react-pixi/dist'
resolve 'pixi.js' in '/Users/matt/projects/xxx/node_modules/@inlet/react-pixi/dist'
  Parsed request is a module
  using description file: /Users/matt/projects/xxx/node_modules/@inlet/react-pixi/package.json (relative path: ./dist)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      looking for modules in /Users/matt/projects/xxx/config
        using description file: /Users/matt/projects/xxx/package.json (relative path: ./config)
          Field 'browser' doesn't contain a valid alias configuration
          using description file: /Users/matt/projects/xxx/package.json (relative path: ./config/pixi.js)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/matt/projects/xxx/config/pixi.js doesn't exist
            *
              Field 'browser' doesn't contain a valid alias configuration
              /Users/matt/projects/xxx/config/pixi.js* doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/matt/projects/xxx/config/pixi.js.js doesn't exist
            as directory
              /Users/matt/projects/xxx/config/pixi.js doesn't exist
      /Users/matt/projects/xxx/node_modules/@inlet/react-pixi/dist/node_modules doesn't exist or is not a directory
      /Users/matt/projects/xxx/node_modules/@inlet/react-pixi/node_modules doesn't exist or is not a directory
      /Users/matt/projects/xxx/node_modules/@inlet/node_modules doesn't exist or is not a directory
      /Users/matt/projects/xxx/node_modules/node_modules doesn't exist or is not a directory
      /Users/matt/projects/node_modules doesn't exist or is not a directory
      /Users/node_modules doesn't exist or is not a directory
      /node_modules doesn't exist or is not a directory
      looking for modules in /Users/matt/projects/xxx/node_modules
        using description file: /Users/matt/projects/xxx/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
      looking for modules in /Users/matt/node_modules
        No description file found
        Field 'browser' doesn't contain a valid alias configuration
          using description file: /Users/matt/projects/xxx/package.json (relative path: ./node_modules/pixi.js)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/matt/projects/xxx/node_modules/pixi.js doesn't exist
            *
              Field 'browser' doesn't contain a valid alias configuration
              /Users/matt/projects/xxx/node_modules/pixi.js* doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
        No description file found
        no extension
          Field 'browser' doesn't contain a valid alias configuration
              /Users/matt/projects/xxx/node_modules/pixi.js.js doesn't exist
          /Users/matt/node_modules/pixi.js doesn't exist
        *
          Field 'browser' doesn't contain a valid alias configuration
            as directory
              /Users/matt/projects/xxx/node_modules/pixi.js doesn't exist
          /Users/matt/node_modules/pixi.js* doesn't exist
        .js
          Field 'browser' doesn't contain a valid alias configuration
          /Users/matt/node_modules/pixi.js.js doesn't exist
        as directory
          /Users/matt/node_modules/pixi.js doesn't exist
[/Users/matt/projects/xxx/config/pixi.js]
[/Users/matt/projects/xxx/config/pixi.js*]
[/Users/matt/projects/xxx/config/pixi.js.js]
[/Users/matt/projects/xxx/node_modules/@inlet/react-pixi/dist/node_modules]
[/Users/matt/projects/xxx/node_modules/@inlet/react-pixi/node_modules]
[/Users/matt/projects/xxx/node_modules/@inlet/node_modules]
[/Users/matt/projects/xxx/node_modules/node_modules]
[/Users/matt/projects/node_modules]
[/Users/node_modules]
[/node_modules]
[/Users/matt/node_modules/package.json]
[/Users/matt/projects/xxx/node_modules/pixi.js]
[/Users/matt/projects/xxx/node_modules/pixi.js*]
[/Users/matt/node_modules/pixi.js/package.json]
[/Users/matt/projects/xxx/node_modules/pixi.js.js]
[/Users/matt/node_modules/pixi.js]
[/Users/matt/node_modules/pixi.js*]
[/Users/matt/node_modules/pixi.js.js]
 @ ./node_modules/@inlet/react-pixi/dist/react-pixi.module-dev.js 1:0-146 394:26-31 394:52-67 519:11-18 522:33-40 534:14-27 574:13-19 578:13-22 582:14-22 608:27-31 648:22-31 658:19-25 680:13-17 689:15-21 726:46-50 727:20-24 747:17-21 12652:14-23 13387:21-32
 @ ./node_modules/@inlet/react-pixi/module.js
 @ ./src/modules/DonorWall/containers/App/index.js
 @ ./src/routes.js
 @ ./src/index.js
 @ multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src/index.js ./src/styles/main.scss webpack-dev-server/client?https://0.0.0.0:8080 webpack/hot/only-dev-server

Additional info

  • @inlet/react-pixi version: 0.3.0
  • React version: 16.4.1
  • ReactDOM version: 16.4.1
  • PIXI version: n/a

Can you provide more examples?

This isn't a direct issue but I would love to see some more examples. Right now I have a hard time figuring about how to use mask.

Feature request to add zIndex

I was thinking about pixi-display... Is there a easy way to use it?

https://github.com/pixijs/pixi-display

Right now I don't have that issue but it would be really good just be able to change zIndex without rearrange the react tree...

I'm not sure if this needs to be in core but it would be good to have some thoughts about it :)

Licensing and future plans

Hello Patrick,

I've noticed that you decided to implement your own version of React reconciler for Pixi based on michalochman/react-pixi-fiber.
Great! I have absolutely no problem with that, as I've released it under MIT license.
However, according to the license, you should have left the original copyright notice in any substantial portions of the original software (which is most of the code).
I had a look at the code in this repo and it is not that different from my original code – just a little reorganized and with some features added.

Is there a reason you decided to copy the code instead of forking it and submitting issues or pull requests to the original repo? Do you think we really need another library doing the same exact thing using the same exact API? Would you consider joining forces instead to collaborate on a single project? I think that would better benefit the community and would be less wasted effort.

Let me know what you think.

Cheers,
MichaΕ‚

Support React Hooks

It looks like this library does not support the new React Hooks, is it possible to support them?

When using hooks like useContext this is the error we're getting:

image

Thanks

Test: update state is failing

I forgot to tell this yesterday when I checked out master and ran npm install. The test update state is failing.

It failed even before my changes. c64cd79

Are there some definitions for typescript already obsolete?

Here is my test code:

// src/index.tsx
// import packages
import * as React from "react"
import * as Pixi from 'pixi.js'
import * as ReactPixi from "@inlet/react-pixi"

// make a canvas container
const container = document.createElement('canvas')
container.id = 'container'
document.body.appendChild(container)

// new pixi app
const app = new Pixi.Application(800, 600, {
  backgroundColor: 0xffffff,
  view: container
})

// call render
ReactPixi.render(
  <ReactPixi.Text text="hey" />, // i got error here
  app.stage
)

I try to use command tsc to compile it, then I got this error message below:

src/index.tsx(20,3): error TS2345: Argument of type 'Element' is not assignable to parameter of type 'DisplayObject | DisplayObject[]'.
  Type 'Element' is not assignable to type 'DisplayObject[]'.
    Property 'length' is missing in type 'Element'.

The definition for ReactPixi.render() is in index.d.ts:45

  function render(
    pixiElement: PIXI.DisplayObject | PIXI.DisplayObject[],
    pixiContainer: PIXI.Container,
    callback?: Function
  ): void

I think because React.createElement(ReactPixi.Text) dose not return something in PIXI.DisplayObject.

So I tried to convert it it into PIXI.DisplayObject just like below:

ReactPixi.render(
  <ReactPixi.Text text="aaa" /> as Pixi.DisplayObject, // i got error here
  app.stage
)

It dosen't work too, because:

src/index.tsx(20,3): error TS2352: Type 'Element' cannot be converted to type 'DisplayObject'.
  Property '_cacheAsBitmap' is missing in type 'Element'.

I'm sure there is no problems with code itself, because the javascript code work fine.
I think it's possible those definitions are obsolete.

Feature idea Ticker component

I was thinking about a Ticker component. This is just a concept. What do you think about it?

I've added reduce, initialValue and data as properties so you can simply add custom logic to your animation.

reduce is more or less the same type of idea of Array.prototype.reduce. Except that the third argument is data instead of index. I don't know if index is needed maybe could be added too.

Why do this?

To remove the need of using lifecycle hooks.

Example

https://jsbin.com/zenuroqaru/edit?js,output
This is using development mode dependencies so it will go much faster in production but still runs pretty good in development too :)

Usage

const SPRITES = 100;

const reducePositions = (accumulator, currentValue, data) =>
  Array.from({ length: SPRITES }, (_, i) => {
    const end = accumulator[i];
    const distanceX = data.x - end.x;
    const distanceY = data.y - end.y;
    const multiplier = ((i + 1) / (SPRITES + 1)) ** currentValue.deltaTime;
    return {
      ...end,
      x: end.x + (distanceX - distanceX * multiplier),
      y: end.y + (distanceY - distanceY * multiplier),
    };
  });

const initialPositions =
  Array.from({ length: SPRITES }, (_, i) => ({
    x: 0,
    y: 0,
    tint: +('0x' + tinycolor.fromRatio({ h: (i + 1) / (SPRITES + 1), s: 0.5, l: 0.5 }).toHex()),
    alpha: 0.2,
  }));

render(
  <Stage>
    {/* Without custom reducer */}
    <Ticker>
      {ticker => (
        <Sprite
          width={100}
          height={100}
          texture={Texture.WHITE}
          tint={0xff0000}
          x={ticker.lastTime / 10}
        />
      )}
    </Ticker>

    {/* With custom reducer */}
    <MousePosition>
      {mousePosition => (
        <Ticker
          reduce={reducePositions}
          initialValue={initialPositions}
          data={mousePosition}
        >
          {positions => positions.map((position, i) => (
            <Sprite
              key={i}
              width={100}
              height={100}
              texture={Texture.WHITE}
              {...position}
            />
          ))}
        </Ticker>
      )}
    </MousePosition>
  </Stage>,
  document.getElementById('app'),
);

Expose Provider and Consumer?

Right now it's like impossible to only use the render function from react-pixi and have compatibility between react-dom and react-pixi because it lacks the app context and the exposed Provider is actually the Consumer at the moment.

TS typings don't work with TS 2.8

Description

import { Stage } from '@inlet/react-pixi';

gives me an error that Stage is not exported

here's my tsconfig.json

{
  "include": ["src/**/*"],
  "compilerOptions": {
    /* Basic Options */
    "target":
      "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module":
      "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "lib": ["es2016", "dom", "dom.iterable", "es2017.object", "esnext.asynciterable"],
    "jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,
    "downlevelIteration": true /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */,

    /* Strict Type-Checking Options */
    "strict": true /* Enable all strict type-checking options. */,

    /* Additional Checks */
    "noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
    "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,

    /* Module Resolution Options */
    "moduleResolution":
      "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
    "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,

    /* Source Map Options */

    /* Experimental Options */
    "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
    "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,

    /* Extras */
    "suppressImplicitAnyIndexErrors": false,
    "forceConsistentCasingInFileNames": true,
    "noEmitOnError": false
  }
}

Additional info

  • @inlet/react-pixi version: latest
  • React version: 16.4
  • ReactDOM version: 16.4
  • PIXI version: latest

Video Textures

I'd like to use pixi fragment shaders on a video.

How can I replicate PIXI.Texture.fromVideo(video) in react-pixi ?

Thanks for your hard work!

TypeScript complains when using HTML attributes on a <Stage>

Description

As I understand it, any HTML attributes can be passed to a Stage and will become attributes on the canvas it creates. However, this isn't reflected in the TypeScript type definitions so the compiler raises an error when I try to add a classname to my stage.

(Note: I'm currently working around the problem with const HackyFixedStage = Stage as any and the classname is correctly set on the canvas)

Steps to reproduce

  1. Add react-pixi to a TypeScript project
  2. Try to add HTML attributes to a <Stage> element, for example: <Stage className="some-class" />
  3. The compiler will complain that Property 'className' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Stage> & Readonly<{ children?: ReactNode; }> & Readonly<IStageProps>'

Additional info

  • @inlet/react-pixi version: 0.1.6
  • React version: 16.5.1
  • ReactDOM version: 16.5.1

I seems like adding CanvasHTMLAttributes to the Stage class definition in index.d.ts solves the problem:

class Stage extends React.Component<_ReactPixi.IStageProps & React.CanvasHTMLAttributes<HTMLCanvasElement>> {}

Or I guess you could make IStageProps extend CanvasHTMLAttributes? I don't know TypeScript's type system super well ...

Thanks for making this and including type definitions btw! I'm having a lot of fun πŸ˜„

onUnMount for Stage

Description

Please provide an unmount hook to clean up resources

Steps to reproduce

Additional info

  • @inlet/react-pixi version:
  • React version:
  • ReactDOM version:
  • PIXI version:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.