Skip to content

Instantly share code, notes, and snippets.

@logaretm
Last active April 10, 2024 14:46
Show Gist options
  • Save logaretm/281eb015ab41cb7a049aeeef84036570 to your computer and use it in GitHub Desktop.
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.
// 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