diff --git a/ui/effects/use-active-element.js b/ui/effects/use-active-element.js new file mode 100644 index 00000000000..0265023e7f0 --- /dev/null +++ b/ui/effects/use-active-element.js @@ -0,0 +1,20 @@ +import { useEffect, useState } from 'react'; + +export const useActiveElement = () => { + const [active, setActive] = useState(document.activeElement); + + const handleFocus = (e) => { + setActive(document.activeElement); + }; + + useEffect(() => { + document.addEventListener('focusin', handleFocus); + document.addEventListener('focusout', handleFocus); + return () => { + document.removeEventListener('focusin', handleFocus); + document.removeEventListener('focusout', handleFocus); + }; + }, []); + + return active; +}; diff --git a/ui/effects/use-history-nav.js b/ui/effects/use-history-nav.js index aa82b40774c..a766cd3684e 100644 --- a/ui/effects/use-history-nav.js +++ b/ui/effects/use-history-nav.js @@ -1,8 +1,9 @@ import { useEffect } from 'react'; - +import { useActiveElement } from './use-active-element'; export default function useHistoryNav(history) { + const el = useActiveElement(); // disable if we're in a textarea. useEffect(() => { - const handleKeyPress = e => { + const handleKeyPress = (e) => { if ((e.metaKey || e.altKey) && !e.ctrlKey && !e.shiftKey) { switch (e.code) { case 'ArrowLeft': @@ -19,7 +20,9 @@ export default function useHistoryNav(history) { } } }; - window.addEventListener('keydown', handleKeyPress); + if (!el.type || (el.type && !el.type.startsWith('text'))) { + window.addEventListener('keydown', handleKeyPress); + } return () => window.removeEventListener('keydown', handleKeyPress); - }, []); + }, [el]); }