From 9c8b6b893196c74971b499b2bf443c37d22e236e Mon Sep 17 00:00:00 2001 From: SeinopSys Date: Sun, 17 Apr 2022 15:12:21 +0200 Subject: [PATCH] replace wrapper function with delegate in draggable utils --- assets/js/utils/draggable.ts | 24 ++++++++---------------- assets/js/utils/events.ts | 6 +++--- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/assets/js/utils/draggable.ts b/assets/js/utils/draggable.ts index c5559e5d..71d0f8bf 100644 --- a/assets/js/utils/draggable.ts +++ b/assets/js/utils/draggable.ts @@ -1,4 +1,5 @@ import { $$ } from './dom'; +import { delegate } from './events'; let dragSrcEl: HTMLElement | null = null; @@ -60,23 +61,14 @@ function dragEnd(event: DragEvent, target: HTMLElement) { } } -function wrapper(func: (event: E, target: T) => void) { - return function(event: E) { - const evtTarget = event.target as EventTarget | Element | null; - if (evtTarget && 'closest' in evtTarget && typeof evtTarget.closest === 'function') { - const target: T | null = evtTarget.closest('.drag-container [draggable]'); - if (target) func(event, target); - } - }; -} - export function initDraggables() { - document.addEventListener('dragstart', wrapper(dragStart)); - document.addEventListener('dragover', wrapper(dragOver)); - document.addEventListener('dragenter', wrapper(dragEnter)); - document.addEventListener('dragleave', wrapper(dragLeave)); - document.addEventListener('dragend', wrapper(dragEnd)); - document.addEventListener('drop', wrapper(drop)); + const draggableSelector = '.drag-container [draggable]'; + delegate(document, 'dragstart', { [draggableSelector]: dragStart}); + delegate(document, 'dragover', { [draggableSelector]: dragOver}); + delegate(document, 'dragenter', { [draggableSelector]: dragEnter}); + delegate(document, 'dragleave', { [draggableSelector]: dragLeave}); + delegate(document, 'dragend', { [draggableSelector]: dragEnd}); + delegate(document, 'drop', { [draggableSelector]: drop}); } export function clearDragSource() { diff --git a/assets/js/utils/events.ts b/assets/js/utils/events.ts index f3db1206..6e290dc9 100644 --- a/assets/js/utils/events.ts +++ b/assets/js/utils/events.ts @@ -12,12 +12,12 @@ export function leftClick(func return (event: E, target: Target) => { if (event.button === 0) return func(event, target); }; } -export function delegate(node: GlobalEventHandlers, event: K, selectors: Record boolean)>) { +export function delegate(node: GlobalEventHandlers, event: K, selectors: Record void | boolean)>) { node.addEventListener(event, e => { for (const selector in selectors) { - const evtTarget = e.target as EventTarget | Element | null; + const evtTarget = e.target as EventTarget | Target | null; if (evtTarget && 'closest' in evtTarget && typeof evtTarget.closest === 'function') { - const target = evtTarget.closest(selector); + const target = evtTarget.closest(selector) as Target; if (target && selectors[selector](e, target) === false) break; } }