From 38c90ac9a28c455589d0002d095af06f0ec8c02d Mon Sep 17 00:00:00 2001 From: behoney Date: Tue, 21 Feb 2023 23:08:59 +0900 Subject: [PATCH] feat: add helper function to generate custom event. --- src/components/Keyboard/Key/index.tsx | 14 ++++++++++++++ src/index.tsx | 6 ++++++ 2 files changed, 20 insertions(+) diff --git a/src/components/Keyboard/Key/index.tsx b/src/components/Keyboard/Key/index.tsx index 788f727..98f882c 100644 --- a/src/components/Keyboard/Key/index.tsx +++ b/src/components/Keyboard/Key/index.tsx @@ -50,3 +50,17 @@ export default (props: KeyProps) => { ) } + +export const genCustomKeyEventFromCharacter = ( + char: string, +): CustomEvent => { + if (char.length !== 1) { + throw new Error( + `Invalid input for custom key event. Input should be single charater. Input is ${char}, though.`, + ) + } + + return new CustomEvent('threekeyboardevent', { + detail: { keyId: char.toLowerCase() }, + }) +} diff --git a/src/index.tsx b/src/index.tsx index 6ad9479..1ff3466 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -2,6 +2,12 @@ import React from 'react' import ReactDOM from 'react-dom/client' import './index.css' import App from './App' +import { genCustomKeyEventFromCharacter } from './components/Keyboard/Key' const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement) root.render() + +document.addEventListener('keydown', (evt) => { + const event = genCustomKeyEventFromCharacter(evt.key) + document.dispatchEvent(event) +})