Skip to content

Commit

Permalink
feat: 🎸 return events from useKeyboardJs hook
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 28, 2019
1 parent c0658f6 commit aa277b8
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 6 deletions.
2 changes: 1 addition & 1 deletion docs/useEvent.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ const Demo = () => {

```js
useEvent('keydown', handler)
useEvent('scroll', handler, window, {useCapture: true})
useEvent('scroll', handler, window, {capture: true})
```
33 changes: 31 additions & 2 deletions src/__stories__/useKeyPressEvent.story.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { storiesOf } from "@storybook/react";
import * as React from "react";
import { useKeyPressEvent } from "..";
import { useKeyPressEvent, useKeyboardJs } from "..";
import ShowDocs from "../util/ShowDocs";

const Demo = () => {
Expand Down Expand Up @@ -31,6 +31,35 @@ const Demo = () => {
);
};

const DemoKeyboardJs = () => {
const [count, setCount] = React.useState(0);

const increment = () => {
console.log('INCREMENT');
setCount(count => ++count);
};
const decrement = () => {
console.log('DECREMENT');
setCount(count => --count);
};
const reset = () => setCount(() => 0);

useKeyPressEvent('q + ]', increment, increment, useKeyboardJs as any);
useKeyPressEvent('q + [', decrement, decrement, useKeyboardJs as any);
useKeyPressEvent('q + r', reset, null, useKeyboardJs as any);

return (
<div>
<style dangerouslySetInnerHTML={{__html: `code {color: red}`}} />
<p>
Try pressing <code>q + [</code>, <code>q + ]</code>, and <code>q + r</code> to
see the count incremented and decremented.</p>
<p>Count: {count}</p>
</div>
);
};

storiesOf("Sensors/useKeyPressEvent", module)
.add("Docs", () => <ShowDocs md={require("../../docs/useKeyPressEvent.md")} />)
.add("Demo", () => <Demo />);
.add("Demo", () => <Demo />)
.add("KeyboardJs", () => <DemoKeyboardJs />);
6 changes: 3 additions & 3 deletions src/useKeyboardJs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {useState, useEffect} from 'react';
import useMount from './useMount';

const useKeyboardJs = (combination: string) => {
const [state, set] = useState(false);
const [state, set] = useState<[boolean, null | KeyboardEvent]>([false, null]);
const [keyboardJs, setKeyboardJs] = useState<any>(null);

useMount(() => {
Expand All @@ -12,8 +12,8 @@ const useKeyboardJs = (combination: string) => {
useEffect(() => {
if (!keyboardJs) return;

const down = () => set(true);
const up = () => set(false);
const down = event => set([true, event]);
const up = event => set([false, event]);
keyboardJs.bind(combination, down, up);

return () => {
Expand Down

0 comments on commit aa277b8

Please sign in to comment.