Last active
April 10, 2024 14:46
-
-
Save logaretm/281eb015ab41cb7a049aeeef84036570 to your computer and use it in GitHub Desktop.
Different ways to check if a keyDown or keyPress event is originating from a text element, usually to avoid processing it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// There are multiple ways to check for that, here are a couple that I use! | |
export function isComposableElement(element: Maybe<HTMLElement | Element>) { | |
if (!element) { | |
return false; | |
} | |
return ( | |
(element as HTMLElement).contentEditable === 'true' || element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' | |
); | |
} | |
export function isComposableEvent(event: KeyboardEvent): boolean { | |
const target = (event.composedPath?.()?.[0] || event.target) as HTMLElement; | |
const hasAttribute = typeof target?.hasAttribute === 'function' ? target.hasAttribute('contenteditable') : false; | |
// when an input field is focused we don't want to trigger deletion or movement of nodes | |
return ['INPUT', 'TEXTAREA'].includes(target?.tagName) || hasAttribute; | |
} | |
function onKeydown(e: KeyboardEvent) { | |
const shouldHandle = !isTextualElement(document.activeElement); | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment