convert event utils to typescript

This commit is contained in:
SeinopSys 2022-03-25 23:36:23 +01:00 committed by Luna D
parent 7f744a2a46
commit 6d85535abd
No known key found for this signature in database
GPG key ID: 4B1C63448394F688
4 changed files with 27 additions and 28 deletions

View file

@ -3,7 +3,7 @@ import { getRandomArrayItem } from '../../../test/randomness';
import { fireEvent } from '@testing-library/dom'; import { fireEvent } from '@testing-library/dom';
describe('Event utils', () => { describe('Event utils', () => {
const mockEvent = getRandomArrayItem(['click', 'blur', 'mouseleave']); const mockEvent = getRandomArrayItem(['click', 'blur', 'mouseleave'] as (keyof GlobalEventHandlersEventMap)[]);
describe('fire', () => { describe('fire', () => {
it('should call the native dispatchEvent method on the element', () => { it('should call the native dispatchEvent method on the element', () => {

View file

@ -1,6 +1,4 @@
/** // DOM Utils
* DOM Utils
*/
/** /**
* Get the first matching element * Get the first matching element

View file

@ -1,24 +0,0 @@
/**
* DOM events
*/
export function fire(el, event, detail) {
el.dispatchEvent(new CustomEvent(event, { detail, bubbles: true, cancelable: true }));
}
export function on(node, event, selector, func) {
delegate(node, event, { [selector]: func });
}
export function leftClick(func) {
return (event, target) => { if (event.button === 0) return func(event, target); };
}
export function delegate(node, event, selectors) {
node.addEventListener(event, e => {
for (const selector in selectors) {
const target = e.target.closest(selector);
if (target && selectors[selector](e, target) === false) break;
}
});
}

25
assets/js/utils/events.ts Normal file
View file

@ -0,0 +1,25 @@
// DOM events
export function fire<El extends Element, D>(el: El, event: string, detail: D) {
el.dispatchEvent(new CustomEvent<D>(event, { detail, bubbles: true, cancelable: true }));
}
export function on<K extends keyof GlobalEventHandlersEventMap>(node: GlobalEventHandlers, event: K, selector: string, func: ((e: GlobalEventHandlersEventMap[K], target: Element) => boolean)) {
delegate(node, event, { [selector]: func });
}
export function leftClick<E extends MouseEvent, Target extends EventTarget>(func: (e: E, t: Target) => void) {
return (event: E, target: Target) => { if (event.button === 0) return func(event, target); };
}
export function delegate<K extends keyof GlobalEventHandlersEventMap>(node: GlobalEventHandlers, event: K, selectors: { [k: string]: ((e: GlobalEventHandlersEventMap[K], target: Element) => boolean) }) {
node.addEventListener(event, e => {
for (const selector in selectors) {
const evtTarget = e.target as EventTarget | Element | null;
if (evtTarget && 'closest' in evtTarget && typeof evtTarget.closest === 'function') {
const target = evtTarget.closest(selector);
if (target && selectors[selector](e, target) === false) break;
}
}
});
}