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.
68 lines (67 loc) • 2.26 kB
JavaScript
// Modifier descriptions courtesy of Svelte docs: https://svelte.dev/docs/element-directives#on-eventname
import { objectToEntries } from '../utils/objectToEntries.js';
import { pipe } from '../utils/pipe.js';
/** Calls `event.preventDefault()` before running the handler */
export function preventDefault(handler) {
return function (event) {
event.preventDefault();
handler.call(this, event);
};
}
/** Calls `event.stopPropagation()`, preventing the event reaching the next element */
export function stopPropagation(handler) {
return function (event) {
event.stopPropagation();
handler.call(this, event);
};
}
/** Calls `event.stopImmediatePropagation()`, preventing other listeners of the same event from being fired. */
export function stopImmediatePropagation(handler) {
return function (event) {
event.stopImmediatePropagation();
handler.call(this, event);
};
}
/** Only triggers handler if the `event.target` is the element itself */
export function self(handler) {
return function (event) {
if (event.target !== event.currentTarget) {
return;
}
handler.call(this, event);
};
}
/** Only trigger handler if event.isTrusted is true. I.e. if the event is triggered by a user action. */
export function trusted(handler) {
return function (event) {
if (!event.isTrusted) {
return;
}
handler.call(this, event);
};
}
/** Remove the handler after the first time it runs */
export function once(handler) {
let hasBeenCalled = false;
return function (event) {
if (hasBeenCalled) {
return;
}
handler.call(this, event);
hasBeenCalled = true;
};
}
const modifierFunctionsByKey = {
preventDefault,
stopPropagation,
stopImmediatePropagation,
self,
trusted,
once,
};
/** Wraps the handler with the modifiers specified in the second argument */
export function withModifiers(handler, modifiers) {
const enabledModifiers = objectToEntries(modifiers).filter(([key, value]) => value);
const modifierFunctions = enabledModifiers.map(([key]) => modifierFunctionsByKey[key]);
return pipe(handler, ...modifierFunctions);
}