2023-10-21 18:14:33 +11:00
|
|
|
import { isKeyHotkey } from 'is-hotkey';
|
2023-06-12 21:15:23 +10:00
|
|
|
import { KeyboardEventHandler } from 'react';
|
|
|
|
|
|
|
|
|
|
export interface KeyboardEventLike {
|
|
|
|
|
key: string;
|
|
|
|
|
which: number;
|
|
|
|
|
altKey: boolean;
|
|
|
|
|
ctrlKey: boolean;
|
|
|
|
|
metaKey: boolean;
|
|
|
|
|
shiftKey: boolean;
|
|
|
|
|
preventDefault(): void;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const onTabPress = (evt: KeyboardEventLike, callback: () => void) => {
|
2023-10-21 18:14:33 +11:00
|
|
|
if (isKeyHotkey('tab', evt)) {
|
2023-06-12 21:15:23 +10:00
|
|
|
evt.preventDefault();
|
|
|
|
|
callback();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const preventScrollWithArrowKey: KeyboardEventHandler = (evt) => {
|
2023-10-21 18:14:33 +11:00
|
|
|
if (isKeyHotkey(['arrowup', 'arrowright', 'arrowdown', 'arrowleft'], evt)) {
|
2023-06-12 21:15:23 +10:00
|
|
|
evt.preventDefault();
|
|
|
|
|
}
|
|
|
|
|
};
|
2024-05-31 19:49:46 +05:30
|
|
|
|
2024-07-30 17:48:59 +05:30
|
|
|
export const onEnterOrSpace =
|
|
|
|
|
<T>(callback: (evt: T) => void) =>
|
|
|
|
|
(evt: KeyboardEventLike) => {
|
|
|
|
|
if (isKeyHotkey('enter', evt) || isKeyHotkey('space', evt)) {
|
|
|
|
|
evt.preventDefault();
|
|
|
|
|
callback(evt as T);
|
|
|
|
|
}
|
|
|
|
|
};
|
2024-07-18 18:50:20 +05:30
|
|
|
|
|
|
|
|
export const stopPropagation = (evt: KeyboardEvent): boolean => {
|
2025-02-10 16:49:47 +11:00
|
|
|
const ae = document.activeElement;
|
|
|
|
|
const editableActiveElement = ae
|
|
|
|
|
? ae.nodeName.toLowerCase() === 'input' ||
|
|
|
|
|
ae.nodeName.toLowerCase() === 'textarea' ||
|
|
|
|
|
ae.getAttribute('contenteditable') === 'true'
|
|
|
|
|
: false;
|
|
|
|
|
|
|
|
|
|
if (editableActiveElement) return false;
|
|
|
|
|
|
2024-07-18 18:50:20 +05:30
|
|
|
evt.stopPropagation();
|
|
|
|
|
return true;
|
|
|
|
|
};
|