-
Notifications
You must be signed in to change notification settings - Fork 393
/
events.ts
272 lines (248 loc) · 10.4 KB
/
events.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
import {
ArrayIndexOf,
ArrayPush,
ArraySlice,
ArraySplice,
create,
defineProperty,
forEach,
isFalse,
isFunction,
isUndefined,
toString,
} from '@lwc/shared';
import { isInstanceOfNativeShadowRoot } from '../env/shadow-root';
import { eventCurrentTargetGetter, eventTargetGetter } from '../env/dom';
import { addEventListener, removeEventListener } from '../env/event-target';
import { shouldInvokeListener } from '../shared/event-target';
import { eventToShadowRootMap, getHost, getShadowRoot } from './shadow-root';
export const enum EventListenerContext {
CUSTOM_ELEMENT_LISTENER,
SHADOW_ROOT_LISTENER,
UNKNOWN_LISTENER,
}
export const eventToContextMap: WeakMap<Event, EventListenerContext> = new WeakMap();
interface WrappedListener extends EventListener {
placement: EventListenerContext;
original: EventListener;
}
interface ListenerMap {
[key: string]: WrappedListener[];
}
const customElementToWrappedListeners: WeakMap<EventTarget, ListenerMap> = new WeakMap();
function getEventMap(elm: EventTarget): ListenerMap {
let listenerInfo = customElementToWrappedListeners.get(elm);
if (isUndefined(listenerInfo)) {
listenerInfo = create(null) as ListenerMap;
customElementToWrappedListeners.set(elm, listenerInfo);
}
return listenerInfo;
}
/**
* Events dispatched on shadow roots actually end up being dispatched on their hosts. This means that the event.target
* property of events dispatched on shadow roots always resolve to their host. This function understands this
* abstraction and properly returns a reference to the shadow root when appropriate.
*/
export function getActualTarget(event: Event): EventTarget {
return eventToShadowRootMap.get(event) ?? eventTargetGetter.call(event);
}
const shadowRootEventListenerMap: WeakMap<EventListener, WrappedListener> = new WeakMap();
function getWrappedShadowRootListener(listener: EventListener): WrappedListener {
if (!isFunction(listener)) {
throw new TypeError(); // avoiding problems with non-valid listeners
}
let shadowRootWrappedListener = shadowRootEventListenerMap.get(listener);
if (isUndefined(shadowRootWrappedListener)) {
shadowRootWrappedListener = function (event: Event) {
// currentTarget is always defined inside an event listener
let currentTarget = eventCurrentTargetGetter.call(event)!;
// If currentTarget is not an instance of a native shadow root then we're dealing with a
// host element whose synthetic shadow root must be accessed via getShadowRoot().
if (!isInstanceOfNativeShadowRoot(currentTarget)) {
currentTarget = getShadowRoot(currentTarget as Element);
}
const actualTarget = getActualTarget(event);
if (shouldInvokeListener(event, actualTarget, currentTarget)) {
listener.call(currentTarget, event);
}
} as WrappedListener;
shadowRootWrappedListener.placement = EventListenerContext.SHADOW_ROOT_LISTENER;
shadowRootEventListenerMap.set(listener, shadowRootWrappedListener);
}
return shadowRootWrappedListener;
}
const customElementEventListenerMap: WeakMap<EventListener, WrappedListener> = new WeakMap();
function getWrappedCustomElementListener(listener: EventListener): WrappedListener {
if (!isFunction(listener)) {
throw new TypeError(); // avoiding problems with non-valid listeners
}
let customElementWrappedListener = customElementEventListenerMap.get(listener);
if (isUndefined(customElementWrappedListener)) {
customElementWrappedListener = function (event: Event) {
// currentTarget is always defined inside an event listener
const currentTarget = eventCurrentTargetGetter.call(event)!;
const actualTarget = getActualTarget(event);
if (shouldInvokeListener(event, actualTarget, currentTarget)) {
listener.call(currentTarget, event);
}
} as WrappedListener;
customElementWrappedListener.placement = EventListenerContext.CUSTOM_ELEMENT_LISTENER;
customElementEventListenerMap.set(listener, customElementWrappedListener);
}
return customElementWrappedListener;
}
function domListener(evt: Event) {
let immediatePropagationStopped = false;
let propagationStopped = false;
const { type, stopImmediatePropagation, stopPropagation } = evt;
// currentTarget is always defined
const currentTarget = eventCurrentTargetGetter.call(evt)!;
const listenerMap = getEventMap(currentTarget);
const listeners = listenerMap![type]; // it must have listeners at this point
defineProperty(evt, 'stopImmediatePropagation', {
value() {
immediatePropagationStopped = true;
stopImmediatePropagation.call(evt);
},
writable: true,
enumerable: true,
configurable: true,
});
defineProperty(evt, 'stopPropagation', {
value() {
propagationStopped = true;
stopPropagation.call(evt);
},
writable: true,
enumerable: true,
configurable: true,
});
// in case a listener adds or removes other listeners during invocation
const bookkeeping: WrappedListener[] = ArraySlice.call(listeners);
function invokeListenersByPlacement(placement: EventListenerContext) {
forEach.call(bookkeeping, (listener: WrappedListener) => {
if (isFalse(immediatePropagationStopped) && listener.placement === placement) {
// making sure that the listener was not removed from the original listener queue
if (ArrayIndexOf.call(listeners, listener) !== -1) {
// all handlers on the custom element should be called with undefined 'this'
listener.call(undefined, evt);
}
}
});
}
eventToContextMap.set(evt, EventListenerContext.SHADOW_ROOT_LISTENER);
invokeListenersByPlacement(EventListenerContext.SHADOW_ROOT_LISTENER);
if (isFalse(immediatePropagationStopped) && isFalse(propagationStopped)) {
// doing the second iteration only if the first one didn't interrupt the event propagation
eventToContextMap.set(evt, EventListenerContext.CUSTOM_ELEMENT_LISTENER);
invokeListenersByPlacement(EventListenerContext.CUSTOM_ELEMENT_LISTENER);
}
eventToContextMap.set(evt, EventListenerContext.UNKNOWN_LISTENER);
}
function attachDOMListener(elm: Element, type: string, wrappedListener: WrappedListener) {
const listenerMap = getEventMap(elm);
let cmpEventHandlers = listenerMap[type];
if (isUndefined(cmpEventHandlers)) {
cmpEventHandlers = listenerMap[type] = [];
}
// Prevent identical listeners from subscribing to the same event type.
// TODO [#1824]: Options will also play a factor when we introduce support for them (#1824).
if (ArrayIndexOf.call(cmpEventHandlers, wrappedListener) !== -1) {
return;
}
// only add to DOM if there is no other listener on the same placement yet
if (cmpEventHandlers.length === 0) {
// super.addEventListener() - this will not work on
addEventListener.call(elm, type, domListener);
}
ArrayPush.call(cmpEventHandlers, wrappedListener);
}
function detachDOMListener(elm: Element, type: string, wrappedListener: WrappedListener) {
const listenerMap = getEventMap(elm);
let p: number;
let listeners: EventListener[] | undefined;
if (
!isUndefined((listeners = listenerMap[type])) &&
(p = ArrayIndexOf.call(listeners, wrappedListener)) !== -1
) {
ArraySplice.call(listeners, p, 1);
// only remove from DOM if there is no other listener on the same placement
if (listeners.length === 0) {
removeEventListener.call(elm, type, domListener);
}
}
}
export function addCustomElementEventListener(
this: Element,
type: string,
listener: EventListenerOrEventListenerObject,
_options?: boolean | AddEventListenerOptions
) {
if (process.env.NODE_ENV !== 'production') {
if (!isFunction(listener)) {
throw new TypeError(
`Invalid second argument for Element.addEventListener() in ${toString(
this
)} for event "${type}". Expected an EventListener but received ${listener}.`
);
}
}
// TODO [#1824]: Lift this restriction on the option parameter
if (isFunction(listener)) {
const wrappedListener = getWrappedCustomElementListener(listener);
attachDOMListener(this, type, wrappedListener);
}
}
export function removeCustomElementEventListener(
this: Element,
type: string,
listener: EventListenerOrEventListenerObject,
_options?: boolean | AddEventListenerOptions
) {
// TODO [#1824]: Lift this restriction on the option parameter
if (isFunction(listener)) {
const wrappedListener = getWrappedCustomElementListener(listener);
detachDOMListener(this, type, wrappedListener);
}
}
export function addShadowRootEventListener(
sr: ShadowRoot,
type: string,
listener: EventListenerOrEventListenerObject,
_options?: boolean | AddEventListenerOptions
) {
if (process.env.NODE_ENV !== 'production') {
if (!isFunction(listener)) {
throw new TypeError(
`Invalid second argument for ShadowRoot.addEventListener() in ${toString(
sr
)} for event "${type}". Expected an EventListener but received ${listener}.`
);
}
}
// TODO [#1824]: Lift this restriction on the option parameter
if (isFunction(listener)) {
const elm = getHost(sr);
const wrappedListener = getWrappedShadowRootListener(listener);
attachDOMListener(elm, type, wrappedListener);
}
}
export function removeShadowRootEventListener(
sr: ShadowRoot,
type: string,
listener: EventListenerOrEventListenerObject,
_options?: boolean | AddEventListenerOptions
) {
// TODO [#1824]: Lift this restriction on the option parameter
if (isFunction(listener)) {
const elm = getHost(sr);
const wrappedListener = getWrappedShadowRootListener(listener);
detachDOMListener(elm, type, wrappedListener);
}
}