svelte-event
Version:
svelte-event provides a set of wrapper functions for adding modifiers to event handlers and a versatile `event` action for comprehensive event listener management in Svelte.
51 lines (50 loc) • 1.56 kB
JavaScript
import { objectToEntries } from '../utils/objectToEntries';
function checkModifiers(event, options) {
const { altKey = false, ctrlKey = false, metaKey = false, shiftKey = false, exact = false } = options ?? {};
const modifiersToCheck = { altKey, ctrlKey, metaKey, shiftKey };
for (const [modifierKey, modifierValue] of objectToEntries(modifiersToCheck)) {
if (exact && modifierValue !== event[modifierKey]) {
return false;
}
if (!exact && modifierValue && !event[modifierKey]) {
return false;
}
}
return true;
}
/** Only triggers handler if the left mouse button is clicked */
export function left(handler, options) {
return function (event) {
if (event.button !== 0) {
return;
}
if (!checkModifiers(event, options)) {
return;
}
handler.call(this, event);
};
}
/** Only triggers handler if the middle mouse button is clicked */
export function middle(handler, options) {
return function (event) {
if (event.button !== 1) {
return;
}
if (!checkModifiers(event, options)) {
return;
}
handler.call(this, event);
};
}
/** Only triggers handler if the right mouse button is clicked */
export function right(handler, options) {
return function (event) {
if (event.button !== 2) {
return;
}
if (!checkModifiers(event, options)) {
return;
}
handler.call(this, event);
};
}