-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
183 lines (157 loc) · 5.08 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import type {ParseSelector} from 'typed-query-selector/parser';
export type DelegateOptions = boolean | Omit<AddEventListenerOptions, 'once'>;
export type EventType = keyof GlobalEventHandlersEventMap;
type GlobalEvent = Event;
namespace delegate {
export type Subscription = {
destroy: VoidFunction;
};
export type EventHandler<
TEvent extends GlobalEvent = GlobalEvent,
TElement extends Element = Element,
> = (event: Event<TEvent, TElement>) => void;
export type Event<
TEvent extends GlobalEvent = GlobalEvent,
TElement extends Element = Element,
> = TEvent & {
delegateTarget: TElement;
};
}
/** Keeps track of raw listeners added to the base elements to avoid duplication */
const ledger = new WeakMap<
EventTarget,
WeakMap<delegate.EventHandler, Set<string>>
>();
function editLedger(
wanted: boolean,
baseElement: EventTarget | Document,
callback: delegate.EventHandler<any, any>,
setup: string,
): boolean {
if (!wanted && !ledger.has(baseElement)) {
return false;
}
const elementMap
= ledger.get(baseElement)
?? new WeakMap<delegate.EventHandler, Set<string>>();
ledger.set(baseElement, elementMap);
if (!wanted && !ledger.has(baseElement)) {
return false;
}
const setups = elementMap.get(callback) ?? new Set<string>();
elementMap.set(callback, setups);
const existed = setups.has(setup);
if (wanted) {
setups.add(setup);
} else {
setups.delete(setup);
}
return existed && wanted;
}
function isEventTarget(
elements: EventTarget | Document | ArrayLike<Element> | string,
): elements is EventTarget {
return typeof (elements as EventTarget).addEventListener === 'function';
}
function safeClosest(event: Event, selector: string): Element | void {
let target = event.target;
if (target instanceof Text) {
target = target.parentElement;
}
if (target instanceof Element && event.currentTarget instanceof Element) {
// `.closest()` may match ancestors of `currentTarget` but we only need its children
const closest = target.closest(selector);
if (closest && event.currentTarget.contains(closest)) {
return closest;
}
}
}
/**
* Delegates event to a selector.
* @param options A boolean value setting options.capture or an options object of type AddEventListenerOptions without the `once` option
*/
function delegate<
Selector extends string,
TElement extends Element = ParseSelector<Selector, HTMLElement>,
TEventType extends EventType = EventType,
>(
base: EventTarget | Document | ArrayLike<Element> | string,
selector: Selector,
type: TEventType,
callback: delegate.EventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: DelegateOptions
): delegate.Subscription;
function delegate<
TElement extends Element = HTMLElement,
TEventType extends EventType = EventType,
>(
base: EventTarget | Document | ArrayLike<Element> | string,
selector: string,
type: TEventType,
callback: delegate.EventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: DelegateOptions
): delegate.Subscription;
// This type isn't exported as a declaration, so it needs to be duplicated above
function delegate<
TElement extends Element,
TEventType extends EventType = EventType,
>(
base: EventTarget | Document | ArrayLike<Element> | string,
selector: string,
type: TEventType,
callback: delegate.EventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: DelegateOptions,
): delegate.Subscription {
// Handle Selector-based usage
if (typeof base === 'string') {
base = document.querySelectorAll(base);
}
// Handle Array-like based usage
if (!isEventTarget(base)) {
const subscriptions = Array.prototype.map.call(
base,
(element: EventTarget) => delegate(
element,
selector,
type,
callback,
options,
),
) as delegate.Subscription[];
return {
destroy(): void {
for (const subscription of subscriptions) {
subscription.destroy();
}
},
};
}
// `document` should never be the base, it's just an easy way to define "global event listeners"
const baseElement = base instanceof Document ? base.documentElement : base;
// Handle the regular Element usage
const capture = Boolean(typeof options === 'object' ? options.capture : options);
const listenerFn: EventListener = (event: Event): void => {
const delegateTarget = safeClosest(event, selector);
if (delegateTarget) {
(event as any).delegateTarget = delegateTarget;
callback.call(baseElement, event as delegate.Event<GlobalEventHandlersEventMap[TEventType], TElement>);
}
};
// Drop unsupported `once` option https://github.com/fregante/delegate-it/pull/28#discussion_r863467939
if (typeof options === 'object') {
delete (options as AddEventListenerOptions).once;
}
const setup = JSON.stringify({selector, type, capture});
const isAlreadyListening = editLedger(true, baseElement, callback, setup);
const delegateSubscription = {
destroy() {
baseElement.removeEventListener(type, listenerFn, options);
editLedger(false, baseElement, callback, setup);
},
};
if (!isAlreadyListening) {
baseElement.addEventListener(type, listenerFn, options);
}
return delegateSubscription;
}
export default delegate;