Coder Social home page Coder Social logo

glortho / react-keydown Goto Github PK

View Code? Open in Web Editor NEW
502.0 15.0 40.0 8.3 MB

Lightweight keydown wrapper for React components

Home Page: http://glortho.github.io/react-keydown/example/index.html

License: MIT License

JavaScript 92.63% HTML 1.93% CSS 5.44%

react-keydown's People

Contributors

antonovav avatar chelm avatar dariuszpaluch avatar dependabot[bot] avatar gauravtiwari avatar glortho avatar jacksonhoose avatar jeffijoe avatar salmanm avatar shicholas avatar staypuft3 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

react-keydown's Issues

Function gets called twice when input bound to multiple event handlers

Functions

  @keydown('shift+enter', 'ctrl+enter', 'alt+enter')
  handleInputKeydown(e) {    
    console.log('next line');
  }
  @keydown('enter')
  handleSubmit(e) {
    console.log('submit');
  }

Text Area

<textarea
                  name="content"
                  placeholder={placeholderText}
                  value={this.state.content}
                  onChange={this.handleInputChange}
                  onKeyDown={(e) => { this.handleInputKeydown(e); this.handleSubmit(e) }} />

Did the above instead of just one function since I couldn't find a way to discern between a regular Enter key and Shift+Enter. The event prop in the function just gives you one key (last pressed I assume), so I separated them into 2 functions.

It's working fine, however, the function seems to be called twice. When I hit enter, I see 'submit' in the console twice.

Disable repeat?

My users (mostly children) sometimes hold the key down (on purpose or because they can't lift their hand off the switch because of disability) thus triggering key repeat. I typically avoid this by binding keyup to clear a flag set on keydown and ignoring the keydown event if the flag is set.

I don't see that in your package but it looks like it would be simple to add. If you agree, I may try hacking it to produce a pull request.

Implementing a slack style enter entry

Hi, I'm trying to set up a textfield to, on enter, submit. But to support adding newlines, add a keybinding for ctrl + enter. Capturing ctrl+enter is simple using
`
@keydown('ctrl+enter', 'enter')
onKeyDown({ keyCode, ctrlKey }) {

}

render() {
return (

);
}
`
But, capturing just the simple 'enter' press, does not work. Instead it gets handled, I assume by the Textfield itself. What is the best way to approach this?

Having trouble getting this working in a este project (https://github.com/este/este)

I'm new to react so I could be doing something wrong. I'm trying to use the method decorator pattern which seems pretty straight forward, but my method is never firing. I stepped through some of your project code and from what I can tell in method_decorator.js (dist version) line 35, "var componentDidMount = target.componentDidMount;" is receiving undefined.

I realize this isn't much info, what can I do to debug this issue?

Add queue for instances?

Options could be:

  1. Refocus on previous if it is parent of current unmounting instance

  2. Auto focus on previous no matter what when current unmounts.

Etc.

Watch modifiers keys

Hi, can I watch only ctrl click?

I tried this:

@keydown(17)
class Test extends Component{
}

But, if I am not wrong, matchKeys waits modifier + key

Conditionally listen to key events

Let's say I have a list of items that I am rendering on a page. Each item is a component. Inside that component I am listening for key events, but I only want to listen when that component has a prop passed in called isSelected.

As it stands now, all of those components in the list are listening and I want to prevent that.

The following handler should only fire when this.props.isSelected === true:

@keydown('up','down') handleKeyDown(e){ console.log('handleKeyDown', e); e.preventDefault(); }

invalid version range according to semver

I am having trouble installing react-keydown via jspm, which converts version ranges down to ^ and ~ operators in an attempt to naturally enforce semver.

It seems that the the specified react-dom range of >=^0.14.0 is not a valid range according to https://github.com/npm/node-semver and thus fails to install.

Could you please consider changing the react-dom version range to ^0.14.0 to ensure compatibility with jspm?

Thanks in advance,

Max

Multiple instances of same components seems to goof up

I have a dropdown component which has the following

@keydown('esc')
  closeOnEscape (ev) {
    ev.preventDefault()
    this.close()
  }

and it seems that only the last one is ever called. Looks like its because of same handler passed to react-keydown and its only calling the last one.

Can anyone reproduce this issue?

Capture window keydown events

I'm wondering if it's possible to capture events that aren't specifically sent to the component, but to still trigger a component's method.

My usecase is I have a grid in the center of the page, and I'm moving a little box around within it using the arrow keys. This works perfectly when the grid has "focus" by clicking on it, but I'd like for it to be able to capture keydown events on the window/document overall.

Not a huge problem if it's not possible, just thought I'd check if it is. This is an awesome library, super well-crafted =)

babel 6 compatibility

The readme mentions that decorators are currently broken in Babel 6. Has anyone recently tried this library with the latest version of Babel?

NOTE: If react-keydown isn't working for you, be sure to check that you're not using Babel 6.x, as decorators are currently broken in Babel 6.

The link in that note (babel/babel#2645) is broken, and the Babel 6.0 release blog post mentions decorator support:

There are a couple of updated TC39 proposals that have come out. Babel 6 updates to the latest revisions of decorators, class properties, and others.

It seems like all you need to do is enable the stage 1 preset plugin to get decorator support.

Make compatible to react 0.14.0

Hi!

Since react 0.14.0 there is an error when I decorate a method in a react component with @keydown(key) (react-keydown 1.3.6):

class_decorator.js:19 Uncaught TypeError: Cannot call a class as a function

Worked for me with react 0.14.0-rc1.

Support React v15

Is there any plan to update the module to accept React v15 as a dependency. I did this locally, by updating package.json, but curious if it was something you were planning on doing.

Thanks.

v1.7.3 broke support for simulated event testing

To test our components and their interactive with react-keydown we usually write tests which simulate events, like so:

const event = document.createEvent('Event');
event.initEvent('keydown', true, true);
event.keyCode = 27;
event.which = 27;
document.dispatchEvent(event);

This then allows us to run tests to ensure react-keydown was bound correctly and fires the right callback.

However, after upgrading from 1.7.2 to 1.7.3 these tests are no longer working due to the changes in made here:

function _shouldConsider(_ref3) {
  var ctrlKey = _ref3.ctrlKey,
      target = _ref3.target;

  return ctrlKey || !~['INPUT', 'SELECT', 'TEXTAREA'].indexOf(target.tagName) && target.getAttribute('role') !== 'textbox';
}

The issue is that this code assumes target.getAttribute is a valid function, however, in a test environment the target will be the document object which is created in jsdom and which may not actually have getAttribute defined.

Would it be possible to update react-keydown to check for the existence of this function first? So the code would become:

return (
   ctrlKey ||
   !~['INPUT', 'SELECT', 'TEXTAREA'].indexOf(target.tagName) &&

   // Make sure the event target supports `getAttribute`
   target.getAttribute &&

   target.getAttribute('role') !== 'textbox'
);

Without this, we've had to revise our tests to do this in the meantime:

const event = document.createEvent('Event');
event.initEvent('keydown', true, true);
event.keyCode = 27;
event.which = 27;
document.getAttribute = () => null; // Hacky Fix
document.dispatchEvent(event);

Documentation without decorators

All the documentation for react-keydown is using the legacy decorator feature of Babel. I'd like to move away from this Babel plugin but I can't figure out how to use react-keydown without decorators. Everything I've tried seems to fail.

Can you please add some simple documentation about how to wrap classes and class methods without using decorators?

'Symbol' type checking didn't work with symbol polyfill

'react-keydon' uses symbol in lib/keys.js
method

export function allKeys( arg ) {  
 return arg ? typeof arg === 'symbol' : Symbol( 'allKeys' );  
}

But this typechecking didn't work with symbol polyfill. I use polyfill because i need to support ie10+, Safari 7+ browsers.
Symbol

For support this you can use:
Babel plugin

Programatically switching focus

The plugin generally works well for me as long as I use clicking to switch focus between components. But I'm making an app that is keyboard-only and would like to manually choose which component is currently active. For example:

  • I have a sidebar with menu items which I navigate with keys.
  • I press enter on an item, which renders a subpage on the right;
  • at this point I would like to switch focus to this subpage (without clicking on it, of course) so that it receives key events instead of the sidebar.

I have tried calling .focus() on the primary element of the component I'd like to focus, but it doesn't seem to do anything. Is there a way to do this?

Not working on IE11 ?!

Add a @keydown( 'right' );
Decorator to my function, it works on Chrome and Safari perfectly but on IE it doesnt do anything.
Is there a ways to debut it, for exaple get infrimations if the key event was triggered in the component when the key was pressed?

Usage with Stateless Functional Components?

Is there any way to use react-keydown with a stateless component?

I know ES7 decorators are only supported with classes and not functions. Is there any workaround to this? Or do I have to switch to some other library? I really like react-keydown and would want to stick to it.

Support for "delete" key?

I recently tried to do:

@keydown('delete')

but it doesn't appear to be supported. Of course:

@keydown(46) // 46 == delete

does still work, but if it's not too much trouble could you please add an "alias" for delete?

Feature request: add @keyup and @keyupScoped decorators

In my use case, Iโ€™d like to be able to toggle state based on if a modifier key is pressed, so it would be great to be able to do something like:

class MyComponent extends React.Component {

  @keydown('alt')
  setModeCopy(event) {
    this.setState({ mode: 'copy' });
  }

  @keyup('alt')
  setModeMove(event) {
    this.setState({ mode: 'move' });
  }
}

In actually use, I think I would use @keydownScoped and @keyupScoped.

Help With Enzyme-Based Testing

react-keydown has worked great for me in the browser, but when I try to use Enzyme to test it I can't figure out how to simulate a keydown event that react-keydown will actually respond to.

If I have a component ...

class SomeComponent extends React.Component {
    @keydown('ctrl+a')
    handler() {
        throw new Error(`Proof that we hit this line`);
    }
}

and then I try to test it with Enzyme:

const A_KEY = 65;
const component = new SomeComponent();
component.simulate('keyDown', {ctrlKey: true, keyCode: A_KEY})
// an error should have been thrown here

no error ever gets thrown, indicating that the handler never got hit.

I tried looking through the source but wasn't able to figure out where exactly react-keydown looks at the event and decides which handler to forward to, so any help either:

A) pointing me toward that place in the code

B) (ideally) providing an example of how to use Enzyme to test react-keydown

would be greatly appreciated.

EDIT
Two minor follow up issues (both related to testing react-keydown-decorated methods directly instead of via simulate)

  1. If you use Node.js + JSDom to run your tests things will break because

    ReferenceError: KeyboardEvent is not defined

That's easy enough to fix (global.KeyboardEvent = window.KeyboardEvent), but if react-keydown could just use window.KeyboardEvent it would save users from a potential pain point.

  1. Methods decorated with @keydown lose their return values. Obviously this doesn't matter normally, because event handlers don't normally return things, but it can be handy to have handlers return things for tests (eg. if the handler generates a promise, it can be handy for the test to get that promise back from the handler).

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.