From 3a9285fa9ec72a99a471ac672f660b6f407e475f Mon Sep 17 00:00:00 2001 From: Aria Minaei Date: Mon, 9 Aug 2021 11:30:44 +0200 Subject: [PATCH] Right click menus now close on 'Escape' --- .../RightClickMenu/RightClickMenu.tsx | 5 +++++ theatre/studio/src/uiComponents/useOnKeyDown.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 theatre/studio/src/uiComponents/useOnKeyDown.ts diff --git a/theatre/studio/src/uiComponents/simpleContextMenu/RightClickMenu/RightClickMenu.tsx b/theatre/studio/src/uiComponents/simpleContextMenu/RightClickMenu/RightClickMenu.tsx index 8eac686..0f8a942 100644 --- a/theatre/studio/src/uiComponents/simpleContextMenu/RightClickMenu/RightClickMenu.tsx +++ b/theatre/studio/src/uiComponents/simpleContextMenu/RightClickMenu/RightClickMenu.tsx @@ -9,6 +9,7 @@ import useWindowSize from 'react-use/esm/useWindowSize' import styled from 'styled-components' import Item, {height as itemHeight} from './Item' import {PortalContext} from 'reakit' +import useOnKeyDown from '@theatre/studio/uiComponents/useOnKeyDown' const minWidth = 190 @@ -94,6 +95,10 @@ const RightClickMenu: React.FC<{ }, [rect, container, props.rightClickPoint, windowSize, props.onRequestClose]) const portalLayer = useContext(PortalContext) + useOnKeyDown((ev) => { + if (ev.key === 'Escape') props.onRequestClose() + }) + const items = Array.isArray(props.items) ? props.items : props.items() return createPortal( diff --git a/theatre/studio/src/uiComponents/useOnKeyDown.ts b/theatre/studio/src/uiComponents/useOnKeyDown.ts new file mode 100644 index 0000000..90fc9d4 --- /dev/null +++ b/theatre/studio/src/uiComponents/useOnKeyDown.ts @@ -0,0 +1,13 @@ +import {useEffect, useRef} from 'react' + +export default function useOnKeyDown(callback: (ev: KeyboardEvent) => void) { + const ref = useRef(callback) + ref.current = callback + useEffect(() => { + const onKeyDown = (ev: KeyboardEvent) => ref.current(ev) + window.addEventListener('keydown', onKeyDown) + return () => { + window.removeEventListener('keydown', onKeyDown) + } + }, []) +}