-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
173 lines (146 loc) · 5.1 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
import type {ParseSelector} from 'typed-query-selector/parser.d.js';
export type DelegateOptions = boolean | Omit<AddEventListenerOptions, 'once'>;
export type EventType = keyof GlobalEventHandlersEventMap;
export type DelegateEventHandler<
TEvent extends Event = Event,
TElement extends Element = Element,
> = (event: DelegateEvent<TEvent, TElement>) => void;
export type DelegateEvent<
TEvent extends Event = Event,
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<DelegateEventHandler, Set<string>>
>();
function editLedger(
wanted: boolean,
baseElement: EventTarget | Document,
callback: DelegateEventHandler<any, any>,
setup: string,
): boolean {
if (!wanted && !ledger.has(baseElement)) {
return false;
}
const elementMap
= ledger.get(baseElement)
?? new WeakMap<DelegateEventHandler, 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 | Iterable<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 | Iterable<Element> | string,
selector: Selector,
type: TEventType,
callback: DelegateEventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: DelegateOptions
): AbortController;
function delegate<
TElement extends Element = HTMLElement,
TEventType extends EventType = EventType,
>(
base: EventTarget | Document | Iterable<Element> | string,
selector: string,
type: TEventType,
callback: DelegateEventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: DelegateOptions
): AbortController;
// 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 | Iterable<Element> | string,
selector: string,
type: TEventType,
callback: DelegateEventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: DelegateOptions,
): AbortController {
const internalController = new AbortController();
const listenerOptions: AddEventListenerOptions = typeof options === 'object' ? options : {capture: options};
// Drop unsupported `once` option https://github.com/fregante/delegate-it/pull/28#discussion_r863467939
delete listenerOptions.once;
if (listenerOptions.signal) {
if (listenerOptions.signal.aborted) {
internalController.abort();
return internalController;
}
listenerOptions.signal.addEventListener('abort', () => {
internalController.abort();
});
} else {
listenerOptions.signal = internalController.signal;
}
// Handle Selector-based usage
if (typeof base === 'string') {
base = document.querySelectorAll(base);
}
// Handle Array-like based usage
if (!isEventTarget(base)) {
for (const element of base) {
delegate(element, selector, type, callback, listenerOptions);
}
return internalController;
}
// `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 = (event: Event): void => {
const delegateTarget = safeClosest(event, selector);
if (delegateTarget) {
const delegateEvent = Object.assign(event, {delegateTarget});
callback.call(baseElement, delegateEvent as DelegateEvent<GlobalEventHandlersEventMap[TEventType], TElement>);
}
};
const setup = JSON.stringify({selector, type, capture});
const isAlreadyListening = editLedger(true, baseElement, callback, setup);
if (!isAlreadyListening) {
baseElement.addEventListener(type, listenerFn, listenerOptions);
}
internalController.signal.addEventListener('abort', () => {
editLedger(false, baseElement, callback, setup);
});
return internalController;
}
export default delegate;