react-native-external-keyboard
Version:
Toolkit for improving physical keyboard support in React Native
55 lines • 2.07 kB
JavaScript
import { useCallback, useMemo, useRef } from 'react';
export const ANDROID_SPACE_KEY_CODE = 62;
export const ANDROID_DPAD_CENTER_CODE = 23;
export const ANDROID_ENTER_CODE = 66;
export const ANDROID_TRIGGER_CODES = [ANDROID_SPACE_KEY_CODE, ANDROID_DPAD_CENTER_CODE, ANDROID_ENTER_CODE];
const MILLISECOND_THRESHOLD = 20;
export const useKeyboardPress = ({
onKeyUpPress,
onKeyDownPress,
onPressIn,
onPressOut,
onPress,
onLongPress,
triggerCodes = ANDROID_TRIGGER_CODES
}) => {
const thresholdTime = useRef(0);
const onKeyUpPressHandler = useCallback(e => {
const {
nativeEvent: {
keyCode,
isLongPress
}
} = e;
onPressOut === null || onPressOut === void 0 || onPressOut(e);
onKeyUpPress === null || onKeyUpPress === void 0 || onKeyUpPress(e);
if (triggerCodes.includes(keyCode)) {
if (isLongPress) {
thresholdTime.current = e === null || e === void 0 ? void 0 : e.timeStamp;
onLongPress === null || onLongPress === void 0 || onLongPress({});
}
}
}, [onPressOut, onKeyUpPress, triggerCodes, onLongPress]);
const onKeyDownPressHandler = useMemo(() => {
if (!onPressIn) return onKeyDownPress;
return e => {
onKeyDownPress === null || onKeyDownPress === void 0 || onKeyDownPress(e);
if (triggerCodes.includes(e.nativeEvent.keyCode)) {
onPressIn === null || onPressIn === void 0 || onPressIn(e);
}
};
}, [onKeyDownPress, onPressIn, triggerCodes]);
const onPressHandler = useCallback(event => {
const pressThreshold = ((event === null || event === void 0 ? void 0 : event.timeStamp) ?? 0) - thresholdTime.current;
if (pressThreshold > MILLISECOND_THRESHOLD) {
onPress === null || onPress === void 0 || onPress(event);
}
}, [onPress]);
const hasHandler = onPressOut || onKeyUpPress || onLongPress || onPress;
return {
onKeyUpPressHandler: hasHandler && onKeyUpPressHandler,
onKeyDownPressHandler,
onPressHandler: onPress && onPressHandler
};
};
//# sourceMappingURL=useKeyboardPress.android.js.map