From 527209e7408f40289d6e9d85d9c54c3c2bf79bd5 Mon Sep 17 00:00:00 2001 From: Kevin Viglucci Date: Fri, 3 Jan 2020 09:47:34 -0600 Subject: [PATCH] Add support for 'delete' key (#56) * add package-lock.json to gitignore as project appears to use yarn * add support for deleting elements with "delete" key + assign magic numbers and keycode values to named properties --- .gitignore | 1 + src/index.tsx | 45 ++++++++++++++++++++++++++++++++------------- 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/.gitignore b/.gitignore index a7904639..31d1c894 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ logs npm-debug.log* yarn-debug.log* yarn-error.log* +package-lock.json # Dependency directories node_modules/ diff --git a/src/index.tsx b/src/index.tsx index 5a16cbfd..49f097b0 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -418,6 +418,28 @@ type AppState = { viewBackgroundColor: string; }; +const KEYS = { + ARROW_LEFT: "ArrowLeft", + ARROW_RIGHT: "ArrowRight", + ARROW_DOWN: "ArrowDown", + ARROW_UP: "ArrowUp", + ESCAPE: "Escape", + DELETE: "Delete", + BACKSPACE: "Backspace" +}; + +function isArrowKey(keyCode: string) { + return ( + keyCode === KEYS.ARROW_LEFT || + keyCode === KEYS.ARROW_RIGHT || + keyCode === KEYS.ARROW_DOWN || + keyCode === KEYS.ARROW_UP + ); +} + +const ELEMENT_SHIFT_TRANSLATE_AMOUNT = 5; +const ELEMENT_TRANSLATE_AMOUNT = 1; + class App extends React.Component<{}, AppState> { public componentDidMount() { document.addEventListener("keydown", this.onKeyDown, false); @@ -443,27 +465,24 @@ class App extends React.Component<{}, AppState> { return; } - if (event.key === "Escape") { + if (event.key === KEYS.ESCAPE) { clearSelection(); this.forceUpdate(); event.preventDefault(); - } else if (event.key === "Backspace") { + } else if (event.key === KEYS.BACKSPACE || event.key === KEYS.DELETE) { deleteSelectedElements(); this.forceUpdate(); event.preventDefault(); - } else if ( - event.key === "ArrowLeft" || - event.key === "ArrowRight" || - event.key === "ArrowUp" || - event.key === "ArrowDown" - ) { - const step = event.shiftKey ? 5 : 1; + } else if (isArrowKey(event.key)) { + const step = event.shiftKey + ? ELEMENT_SHIFT_TRANSLATE_AMOUNT + : ELEMENT_TRANSLATE_AMOUNT; elements.forEach(element => { if (element.isSelected) { - if (event.key === "ArrowLeft") element.x -= step; - else if (event.key === "ArrowRight") element.x += step; - else if (event.key === "ArrowUp") element.y -= step; - else if (event.key === "ArrowDown") element.y += step; + if (event.key === KEYS.ARROW_LEFT) element.x -= step; + else if (event.key === KEYS.ARROW_RIGHT) element.x += step; + else if (event.key === KEYS.ARROW_UP) element.y -= step; + else if (event.key === KEYS.ARROW_DOWN) element.y += step; } }); this.forceUpdate();