From a3b8154b3e55ff16a70597fc78836bc7bcf48683 Mon Sep 17 00:00:00 2001 From: Luke Date: Sun, 19 Jun 2022 15:13:43 +0200 Subject: [PATCH] feat(web/input): submit on enter press --- web/src/features/dialog/InputDialog.tsx | 7 ++++- web/src/hooks/useKeyPress.ts | 35 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 web/src/hooks/useKeyPress.ts diff --git a/web/src/features/dialog/InputDialog.tsx b/web/src/features/dialog/InputDialog.tsx index a3e3521..e64d112 100644 --- a/web/src/features/dialog/InputDialog.tsx +++ b/web/src/features/dialog/InputDialog.tsx @@ -17,6 +17,7 @@ import InputNumber from "./components/number"; import Input from "./components/input"; import CheckboxField from "./components/checkbox"; import SelectField from "./components/select"; +import { useKeyPress } from "../../hooks/useKeyPress"; interface Props { heading: string; @@ -58,9 +59,13 @@ const InputDialog: React.FC = () => { >([]); const [passwordStates, setPasswordStates] = React.useState([]); const [visible, setVisible] = React.useState(false); - + const enterPressed = useKeyPress("Enter"); const { locale } = useLocales(); + React.useEffect(() => { + if (visible && enterPressed === false) handleConfirm(); + }, [enterPressed]); + const handlePasswordStates = (index: number) => { setPasswordStates({ ...passwordStates, diff --git a/web/src/hooks/useKeyPress.ts b/web/src/hooks/useKeyPress.ts new file mode 100644 index 0000000..9843d53 --- /dev/null +++ b/web/src/hooks/useKeyPress.ts @@ -0,0 +1,35 @@ +import React from "react"; + +export const useKeyPress = (targetKey: KeyboardEvent["key"]) => { + const [keyPressed, setKeyPressed] = React.useState(false); + + const downHandler = React.useCallback( + ({ key }: KeyboardEvent) => { + if (key === targetKey) { + setKeyPressed(true); + } + }, + [targetKey] + ); + + const upHandler = React.useCallback( + ({ key }: KeyboardEvent) => { + if (key === targetKey) { + setKeyPressed(false); + } + }, + [targetKey] + ); + + React.useEffect(() => { + window.addEventListener("keydown", downHandler); + window.addEventListener("keyup", upHandler); + + return () => { + window.removeEventListener("keydown", downHandler); + window.removeEventListener("keyup", upHandler); + }; + }, [downHandler, upHandler]); + + return keyPressed; +};