Giter Club home page Giter Club logo

react-event-components's Introduction

React Event Components

Join the chat at https://gitter.im/pagarme/react-event-components

A set of components designed as an idiomatic way of working with global, raw input (keyboard, mouse, touch, etc) in React.

Example

A live demo can be found at https://pagarme.github.io/react-event-components

Install

yarn add react-event-components

or

npm install react-event-components --save

Usage

Key Events

Call the handler everytime a key event happen.

import { KeyDown } from './react-event-components'
import React, { Component } from 'react'

export default class KeyDownExample extends Component {
  constructor() {
    super()
    this.state = {
      x: 0,
      y: 0,
      totalTime: 0,
      color: 'rgb(0,0,0)',
      lastKeyPressed: 'None'
      }
  }

  move(position) {
    this.setState(position)
  }

  render() {
    const {x, y, color} = this.state
    return (
      <div>
        <p>Total time: {Math.floor(this.state.totalTime * 100)/100}</p>
        <p>Last key pressed: {this.state.lastKeyPressed}</p>

        <h1 style={{
          transform: `translate(${x}px, ${y}px)`,
          color: color
        }}>
          Try WASD or QEZC
        </h1>

        <KeyDown when="*" do={(key) => this.setState({ lastKeyPressed: key })} />
        <KeyDown when="w" do={() => this.move({ y: y - 10 })} />
        <KeyDown when="a" do={() => this.move({ x: x - 10 })} />
        <KeyDown when="s" do={() => this.move({ y: y + 10 })} />
        <KeyDown when="d" do={() => this.move({ x: x + 10 })} />
        <KeyDown when="q" do={() => this.move({ x: x - 10, y: y - 10})} />
        <KeyDown when="e" do={() => this.move({ x: x + 10, y: y - 10})} />
        <KeyDown when="z" do={() => this.move({ x: x - 10, y: y + 10})} />
        <KeyDown when="c" do={() => this.move({ x: x + 10, y: y + 10})} />
      </div>
    )
  }
}

Timer Events

Runs a function recurrently. Passes the delta time to handler.

import React, { Component } from 'react'
import { Every } from './react-event-components'

export default class EveryExample extends Component {
  constructor() {
    super()
    this.state = {
      totalTime: 0,
      color: 'rgb(0,0,0)'
    }
  }

  handleTotalTime(dt) {
    const totalTime = this.state.totalTime + dt
    this.setState({
      totalTime: totalTime,
      displayTime: Math.floor(totalTime * 100)/100
    })
  }

  handleColor() {
    const randomHex = () => Math.round(Math.random() * 255)
    this.setState({
      color: `rgb(${randomHex()},${randomHex()},${randomHex()})`
    })
  }

  render() {
    return (
      <div>
        <p style={{ color: this.state.color }}>Total time: { this.state.displayTime }</p>

        <Every frame do={(dt) => this.handleTotalTime(dt)} />
        <Every s="1" ms="500" do={() => this.handleColor()} />
      </div>
    )
  }
}

DeviceOrientation

Call do property every time device orientation changes

import React, {Component} from 'react'
import {DeviceOrientation} from './react-event-components'

export default class DeviceOrientationExample extends Component {
  constructor() {
    super()
    this.state = {
      deviceOrientation: {}
    }
  }

  handleDeviceOrientation = ({beta, gamma, alpha, absolute}) => {
    this.setState({
      deviceOrientation: {
        beta,
        gamma,
        alpha,
        absolute
      }
    })
  }

  render() {
    return (
      <div>
        <DeviceOrientation do={this.handleDeviceOrientation} />

        <h2>DeviceOrientation</h2>

        <p>
          beta: {this.state.deviceOrientation.beta}
          <br />
          gamma: {this.state.deviceOrientation.gamma}
          <br />
          alpha: {this.state.deviceOrientation.alpha}
          <br />
          absolute: {this.state.deviceOrientation.absolute}
        </p>
      </div>
    )
  }
}

WindowResize

Triggered when the user resizes the window, it can be called when the user changes the orientation from portrait to landscape.

import React, { Component } from 'react'
import { WindowResize } from './react-event-components'

export default class WindowResizeExample extends Component {
  constructor() {
    super()
    this.state = {
      title: 'Resize Your Window',
      innerWidth: window.innerWidth
    }
  }

  handleWindowResize(window) {
    this.setState(Object.assign({}, this.state, {
      innerWidth: window.innerWidth
    }))
  }

  render() {
    return (
      <div>
        <WindowResize do={this.handleWindowResize.bind(this)} />

        <p>{this.state.title} {this.state.innerWidth}px</p>
      </div>
    )
  }
}

Battery Status

It will give you the battery status of the user API, if it is available

import { BatteryStatus } from './react-event-components'
import React, { Component } from 'react'

export default class BatteryStatusExample extends Component {
  constructor() {
    super()
    this.state = { }
  }

  render() {
    const {
      charging,
      chargingTime,
      dischargingTime,
      level
    } = this.state

    return (
      <section>
        <BatteryStatus do={this.handleBatteryChange.bind(this)} />

        <h2>BatteryStatus</h2>
        <div>charging: {charging}</div>
        <div>chargingTime: {chargingTime}</div>
        <div>level: {level}%</div>
      </section>
    )
  }

  handleBatteryChange (battery) {
    this.setState({ ...battery })
  }
}

react-event-components's People

Contributors

derekstavis avatar felquis avatar ggviana avatar gitter-badger avatar grvcoelho avatar marcoworms avatar rodrigooler 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  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

react-event-components's Issues

KeyDown modifier keys

Would a PR be welcome to add options for modifier keys like:

<KeyDown when="c" ctrl do={...} />

Cannot use this package from npm with create-react-app

To simulate, run these commands:

  1. create-react-app test
  2. cd test
  3. npm install react-event-components
  4. Go to App.js
  5. write import { Every } from 'react-event-components'

Then try to run the project,

It happens with version 0.1.6
I tested it with yarn, but I think it happens too with npm.

๐Ÿ‘

WindowResize example does not make sense

Object.assign(window, {})... WTF??

handleWindowResize(window) {
    this.setState(Object.assign(window, {
      innerWidth: window.innerWidth,
      innerWidth: window.innerWidth
    }))
  }

And there's also two alerts in the linter...

./src/WindowResizeExample.js
  Line 3:   'styles' is defined but never used  no-unused-vars
  Line 17:  Duplicate key 'innerWidth'          no-dupe-keys

We should fix it..

Which components are we missing?

Let's list what we have to do:

  • LocalStorage (the spec for listening this is really shitty, I think we won't implement it. The spec is designed so you can only listen when other tabs manipulate it.)
  • Gamepad

to be continued, just post here and I'll update this list

@grvcoelho @felquis @derekstavis :)

`do` is a reserved word in javascript

great work on this library ๐Ÿ‘

one note... since do is a reserved identifier in javascript, it is probably a good idea to use an alternative like run or execute or exec or something

Multiple keys pressed at once support

Description

Would be nice to have a behavior like this.

Scenario: I want to do something, when the user presses shitf + a.

Proposal

This is a simple and straightforward implementation. Don't know how the component interface to this might look like, though.

const keysPressed = {}

document.addEventListener('keydown', e => keysPressed[e.keyCode] = true)
document.addEventListener('keyup', e => keysPressed[e.keyCode] = false)

if (keysPressed[16] && keysPressed[65]) {
  // do something
}

Please make a new release

It looks like the existing release on NPM (v1.0.0) still references React.PropTypes. The code in this repository does not. Can you make a new release on NPM, so that we can upgrade and avoid the deprecation warnings?

All tests are failing

When I run npm test I saw this messages

jest-haste-map: Watchman crawl failed. Retrying once with node crawler.
  Usually this happens when watchman isn't running. Create an empty `.watchmanconfig` file in your project's root folder or initialize a git or hg repository in your project.
  Error: Watchman error: unknown command watch-project. Make sure watchman is running for this project. See https://facebook.github.io/watchman/docs/troubleshooting.html.
No tests found related to files changed since last commit.

If I uninstall watchman with brew uninstall watchman then installing it again fixed the problem, but it does't throw erros, but the tests fail with

Couldn't find preset "es2015" relative to directory "/Users/felquis/project"

This is happening for any app created with create-react-app right now!

Can we elect a maintainer?

As co-creator of this project, I have a deep interest to maintain it on my spare time.

The main requirement is to allow me to merge pull requests so I can move the PRs forward.

Maybe @lucianopf or @grvcoelho can help me as insiders.

Thanks.

Improve code coverage

This is the current coverage report, the column Uncovered Lines is the most important it show what need to be called. I can use enzyme to improve it http://airbnb.io/enzyme/docs/api/mount.html

------------------------------|----------|----------|----------|----------|----------------|
File                          |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
------------------------------|----------|----------|----------|----------|----------------|
All files                     |    62.69 |       45 |    54.93 |     62.9 |                |
 src                          |    54.17 |       50 |    47.06 |    56.52 |                |
  DeviceOrientationExample.js |       75 |      100 |    66.67 |       75 |             13 |
  EveryExample.js             |       60 |      100 |    57.14 |    66.67 |       22,23,34 |
  GeolocationExample.js       |       75 |       75 |       50 |       75 |              8 |
  KeyDownExample.js           |    30.77 |      100 |    18.18 |    30.77 |... 33,34,35,36 |
  TouchExample.js             |       50 |       40 |     62.5 |    54.55 | 18,23,25,31,51 |
  WindowResizeExample.js      |       75 |      100 |    66.67 |       75 |             15 |
  setupTests.js               |      100 |      100 |      100 |      100 |                |
 src/react-event-components   |    67.44 |    42.31 |    62.16 |    66.67 |                |
  DeviceOrientation.js        |       60 |      100 |       50 |       60 |           9,13 |
  Every.js                    |    76.19 |       70 |    83.33 |       80 |    33,34,35,37 |
  GeolocationChange.js        |    36.36 |       25 |       40 |    36.36 |... 18,23,24,29 |
  KeyDown.js                  |      100 |      100 |      100 |      100 |                |
  KeyEvent.js                 |    55.56 |        0 |       50 |    55.56 |    10,11,20,24 |
  KeyUp.js                    |      100 |      100 |      100 |      100 |                |
  TouchCancel.js              |      100 |      100 |      100 |      100 |                |
  TouchEnd.js                 |      100 |      100 |      100 |      100 |                |
  TouchEvent.js               |       50 |    33.33 |       60 |       50 |... 18,20,23,31 |
  TouchMove.js                |      100 |      100 |      100 |      100 |                |
  TouchStart.js               |      100 |      100 |      100 |      100 |                |
  WindowResize.js             |     62.5 |      100 |       40 |    71.43 |           9,13 |
  index.js                    |      100 |      100 |      100 |      100 |                |
------------------------------|----------|----------|----------|----------|----------------|

Test Suites: 17 passed, 17 total
Tests:       17 passed, 17 total
Snapshots:   0 total
Time:        5.199s
Ran all test suites.

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.