-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(useKeyPress): allow complex bindings via key combos
- Loading branch information
1 parent
6ffebb6
commit e53a20f
Showing
1 changed file
with
43 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,63 @@ | ||
import * as React from 'react'; | ||
import * as React from "react"; | ||
const { useState, useEffect } = React; | ||
|
||
const {useState, useEffect} = React; | ||
interface Options { | ||
useKeyboardJS: boolean; | ||
} | ||
|
||
const defaults: Options = { | ||
useKeyboardJS: false | ||
}; | ||
|
||
// kudos: https://usehooks.com | ||
const useKeyPress = (targetKey: string) => { | ||
const useKeyPress = (targetKey: string, config: Options = defaults) => { | ||
const [state, setState] = useState(false); | ||
const { useKeyboardJS } = config; | ||
|
||
const downHandler = ({key}: KeyboardEvent) => { | ||
let keyboardjs; | ||
|
||
if (useKeyboardJS) { | ||
import("keyboardjs").then(module => { | ||
keyboardjs = module; | ||
}); | ||
} | ||
|
||
const regularDownHandler = ({ key }: KeyboardEvent) => { | ||
if (key === targetKey) { | ||
setState(true); | ||
} | ||
} | ||
const upHandler = ({key}: KeyboardEvent) => { | ||
}; | ||
|
||
const regularUpHandler = ({ key }: KeyboardEvent) => { | ||
if (key === targetKey) { | ||
setState(false); | ||
} | ||
}; | ||
|
||
const customDownHandler = () => { | ||
setState(true); | ||
}; | ||
const customUpHandler = () => { | ||
setState(false); | ||
}; | ||
|
||
useEffect(() => { | ||
window.addEventListener('keydown', downHandler); | ||
window.addEventListener('keyup', upHandler); | ||
if (useKeyboardJS) { | ||
keyboardjs.bind(targetKey, customDownHandler, customUpHandler); | ||
} else { | ||
window.addEventListener("keydown", regularDownHandler); | ||
window.addEventListener("keyup", regularUpHandler); | ||
} | ||
return () => { | ||
window.removeEventListener('keydown', downHandler); | ||
window.removeEventListener('keyup', upHandler); | ||
if (useKeyboardJS) { | ||
keyboardjs.unbind(targetKey, customDownHandler, customUpHandler); | ||
} else { | ||
window.removeEventListener("keydown", regularDownHandler); | ||
window.removeEventListener("keyup", regularUpHandler); | ||
} | ||
}; | ||
}, []); | ||
|
||
return state; | ||
} | ||
}; | ||
|
||
export default useKeyPress; |