@ebay/ebayui-core
Version:
Collection of core eBay components; considered to be the building blocks for all composite structures, pages & apps.
106 lines (105 loc) • 3.08 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.resizeUtil = void 0;
exports.debounce = debounce;
exports.handleEnterKeydown = handleEnterKeydown;
exports.handleActionKeydown = handleActionKeydown;
exports.handleEscapeKeydown = handleEscapeKeydown;
exports.handleUpDownArrowsKeydown = handleUpDownArrowsKeydown;
exports.handleLeftRightArrowsKeydown = handleLeftRightArrowsKeydown;
exports.handleArrowsKeydown = handleArrowsKeydown;
exports.handleTextInput = handleTextInput;
exports.preventDefaultIfHijax = preventDefaultIfHijax;
function handleKeydown(keyCodes, e, callback) {
const keyCode = e.key;
if (keyCodes.indexOf(keyCode) !== -1) {
callback();
}
}
// inverse of found keys
function handleNotKeydown(keyCodes, e, callback) {
const keyCode = e.key;
if (keyCodes.indexOf(keyCode) === -1) {
callback();
}
}
// enter key
function handleEnterKeydown(e, callback) {
handleKeydown(["Enter"], e, callback);
}
// space and enter keys
function handleActionKeydown(e, callback) {
handleKeydown(["Enter", " "], e, callback);
}
function handleEscapeKeydown(e, callback) {
handleKeydown(["Escape"], e, callback);
}
function handleUpDownArrowsKeydown(e, callback) {
handleKeydown(["ArrowUp", "ArrowDown"], e, callback);
}
function handleLeftRightArrowsKeydown(e, callback) {
handleKeydown(["ArrowLeft", "ArrowRight"], e, callback);
}
function handleArrowsKeydown(e, callback) {
handleKeydown(["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"], e, callback);
}
// only fire for character input, not modifier/meta keys (enter, escape, backspace, tab, etc.)
function handleTextInput(e, callback) {
const keys = [
"Tab",
"Enter",
"Shift",
"Escape",
"ArrowUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"Shift",
"Alt",
"Meta",
"Control",
"CapsLock",
];
handleNotKeydown(keys, e, callback);
}
function preventDefaultIfHijax(e, hijax) {
if (hijax) {
e.preventDefault();
}
}
const handlers = [];
function addEventListener(_, handler) {
if (handlers.length === 0) {
window.addEventListener("resize", handleResize);
}
handlers.push(handler);
}
function removeEventListener(_, handler) {
if (handlers.length === 1) {
window.removeEventListener("resize", handleResize);
}
handlers.splice(handlers.indexOf(handler), 1);
}
function handleResize(e) {
window.removeEventListener("resize", handleResize);
window.requestAnimationFrame(() => {
if (handlers.length) {
handlers.forEach((handler) => handler(e));
window.addEventListener("resize", handleResize);
}
});
}
const resizeUtil = {
addEventListener,
removeEventListener,
};
exports.resizeUtil = resizeUtil;
function debounce(func, timeout = 100) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
}