eventHandler.js 11.6 KB
Newer Older
Johann-S's avatar
Johann-S committed
1
2
import Util from '../util'

Johann-S's avatar
Johann-S committed
3
4
/**
 * --------------------------------------------------------------------------
Johann-S's avatar
Johann-S committed
5
 * Bootstrap (v4.0.0-beta): dom/eventHandler.js
Johann-S's avatar
Johann-S committed
6
7
8
9
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * --------------------------------------------------------------------------
 */

Johann-S's avatar
Johann-S committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const EventHandler = (() => {
  /**
   * ------------------------------------------------------------------------
   * Polyfills
   * ------------------------------------------------------------------------
   */

  // defaultPrevented is broken in IE.
  // https://connect.microsoft.com/IE/feedback/details/790389/event-defaultprevented-returns-false-after-preventdefault-was-called
  const workingDefaultPrevented = (() => {
    const e = document.createEvent('CustomEvent')
    e.initEvent('Bootstrap', true, true)
    e.preventDefault()
    return e.defaultPrevented
  })()
25

Johann-S's avatar
Johann-S committed
26
  let defaultPreventedPreservedOnDispatch = true
27

Johann-S's avatar
Johann-S committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
  // CustomEvent polyfill for IE (see: https://mzl.la/2v76Zvn)
  if (typeof window.CustomEvent !== 'function') {
    window.CustomEvent = (event, params) => {
      params = params || {
        bubbles: false,
        cancelable: false,
        detail: null
      }
      const evt = document.createEvent('CustomEvent')
      evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
      if (!workingDefaultPrevented) {
        const origPreventDefault = Event.prototype.preventDefault
        evt.preventDefault = () => {
          if (!evt.cancelable) {
            return
          }

          origPreventDefault.call(evt)
          Object.defineProperty(evt, 'defaultPrevented', {
            get() {
              return true
            },
            configurable: true
          })
52
53
        }
      }
Johann-S's avatar
Johann-S committed
54
      return evt
55
56
    }

Johann-S's avatar
Johann-S committed
57
58
59
60
61
62
63
    window.CustomEvent.prototype = window.Event.prototype
  } else {
    // MSEdge resets defaultPrevented flag upon dispatchEvent call if at least one listener is attached
    defaultPreventedPreservedOnDispatch = (() => {
      const e = new CustomEvent('Bootstrap', {
        cancelable: true
      })
64

Johann-S's avatar
Johann-S committed
65
66
      const element = document.createElement('div')
      element.addEventListener('Bootstrap', () => null)
67

Johann-S's avatar
Johann-S committed
68
69
70
71
      e.preventDefault()
      element.dispatchEvent(e)
      return e.defaultPrevented
    })()
72
  }
Johann-S's avatar
Johann-S committed
73

Johann-S's avatar
Johann-S committed
74
75
76
77
78
79
80
81
82
83
84
  // Event constructor shim
  if (!window.Event || typeof window.Event !== 'function') {
    const origEvent = window.Event
    window.Event = (inType, params) => {
      params = params || {}
      const e = document.createEvent('Event')
      e.initEvent(inType, Boolean(params.bubbles), Boolean(params.cancelable))
      return e
    }
    window.Event.prototype = origEvent.prototype
  }
Johann-S's avatar
Johann-S committed
85

Johann-S's avatar
Johann-S committed
86
87
88
89
90
  /**
   * ------------------------------------------------------------------------
   * Constants
   * ------------------------------------------------------------------------
   */
Johann-S's avatar
Johann-S committed
91

Johann-S's avatar
Johann-S committed
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
  const namespaceRegex = /[^.]*(?=\..*)\.|.*/
  const stripNameRegex = /\..*/
  const keyEventRegex  = /^key/
  const stripUidRegex  = /::\d+$/
  const eventRegistry  = {}   // Events storage
  let uidEvent         = 1
  const customEvents   = {
    mouseenter: 'mouseover',
    mouseleave: 'mouseout'
  }
  const nativeEvents   = [
    'click', 'dblclick', 'mouseup', 'mousedown', 'contextmenu',
    'mousewheel', 'DOMMouseScroll',
    'mouseover', 'mouseout', 'mousemove', 'selectstart', 'selectend',
    'keydown', 'keypress', 'keyup',
    'orientationchange',
    'touchstart', 'touchmove', 'touchend', 'touchcancel',
    'gesturestart', 'gesturechange', 'gestureend',
    'focus', 'blur', 'change', 'reset', 'select', 'submit', 'focusin', 'focusout',
    'load', 'unload', 'beforeunload', 'resize', 'move', 'DOMContentLoaded', 'readystatechange',
    'error', 'abort', 'scroll'
  ]

  /**
   * ------------------------------------------------------------------------
   * Private methods
   * ------------------------------------------------------------------------
   */

  function getUidEvent(element, uid) {
122
    return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++
Johann-S's avatar
Johann-S committed
123
  }
Johann-S's avatar
Johann-S committed
124

Johann-S's avatar
Johann-S committed
125
126
  function getEvent(element) {
    const uid = getUidEvent(element)
127
128
    element.uidEvent = uid

Johann-S's avatar
Johann-S committed
129
130
    return eventRegistry[uid] = eventRegistry[uid] || {}
  }
Johann-S's avatar
Johann-S committed
131

132
  function fixEvent(event, element) {
Johann-S's avatar
Johann-S committed
133
134
135
136
    // Add which for key events
    if (event.which === null && keyEventRegex.test(event.type)) {
      event.which = event.charCode !== null ? event.charCode : event.keyCode
    }
137
138

    event.delegateTarget = element
Johann-S's avatar
Johann-S committed
139
140
  }

Johann-S's avatar
Johann-S committed
141
  function bootstrapHandler(element, fn) {
142
143
144
145
146
147
    return function handler(event) {
      fixEvent(event, element)
      if (handler.oneOff) {
        EventHandler.off(element, event.type, fn)
      }

Johann-S's avatar
Johann-S committed
148
149
      return fn.apply(element, [event])
    }
Johann-S's avatar
Johann-S committed
150
151
  }

Johann-S's avatar
Johann-S committed
152
  function bootstrapDelegationHandler(element, selector, fn) {
153
    return function handler(event) {
Johann-S's avatar
Johann-S committed
154
155
156
157
      const domElements = element.querySelectorAll(selector)
      for (let target = event.target; target && target !== this; target = target.parentNode) {
        for (let i = domElements.length; i--;) {
          if (domElements[i] === target) {
158
159
160
161
162
            fixEvent(event, target)
            if (handler.oneOff) {
              EventHandler.off(element, event.type, fn)
            }

Johann-S's avatar
Johann-S committed
163
164
            return fn.apply(target, [event])
          }
165
166
        }
      }
167

Johann-S's avatar
Johann-S committed
168
169
      // To please ESLint
      return null
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
  function findHandler(events, handler) {
    for (const uid in events) {
      if (!Object.prototype.hasOwnProperty.call(events, uid)) {
        continue
      }

      if (events[uid].originalHandler === handler) {
        return events[uid]
      }
    }

    return null
  }

  function addHandler(element, originalTypeEvent, handler, delegationFn, oneOff) {
    if (typeof originalTypeEvent !== 'string' || (typeof element === 'undefined' || element === null)) {
      return
    }

    if (!handler) {
      handler = delegationFn
      delegationFn = null
    }

    const delegation      = typeof handler === 'string'
    const originalHandler = delegation ? delegationFn : handler

    // allow to get the native events from namespaced events ('click.bs.button' --> 'click')
    let typeEvent = originalTypeEvent.replace(stripNameRegex, '')

    const custom = customEvents[typeEvent]
    if (custom) {
      typeEvent = custom
    }

    const isNative = nativeEvents.indexOf(typeEvent) > -1
    if (!isNative) {
      typeEvent = originalTypeEvent
    }

    const events     = getEvent(element)
    const handlers   = events[typeEvent] || (events[typeEvent] = {})
    const previousFn = findHandler(handlers, originalHandler)

    if (previousFn) {
      previousFn.oneOff = previousFn.oneOff && oneOff
      return
    }

    const uid = getUidEvent(originalHandler, originalTypeEvent.replace(namespaceRegex, ''))
    const fn  = !delegation ? bootstrapHandler(element, handler) : bootstrapDelegationHandler(element, handler, delegationFn)

    fn.isDelegation = delegation
    fn.originalHandler = originalHandler
    fn.oneOff = oneOff
    handlers[uid] = fn

    element.addEventListener(typeEvent, fn, delegation)
  }

Johann-S's avatar
Johann-S committed
233
  function removeHandler(element, events, typeEvent, handler) {
234
235
236
237
238
239
    const fn = findHandler(events[typeEvent], handler)
    if (fn === null) {
      return
    }

    element.removeEventListener(typeEvent, fn, fn.isDelegation)
Johann-S's avatar
Johann-S committed
240
241
    delete events[typeEvent][uidEvent]
  }
242

Johann-S's avatar
Johann-S committed
243
244
245
246
247
248
  function removeNamespacedHandlers(element, events, typeEvent, namespace) {
    const storeElementEvent = events[typeEvent] || {}
    for (const handlerKey in storeElementEvent) {
      if (!Object.prototype.hasOwnProperty.call(storeElementEvent, handlerKey)) {
        continue
      }
249

Johann-S's avatar
Johann-S committed
250
251
252
      if (handlerKey.indexOf(namespace) > -1) {
        removeHandler(element, events, typeEvent, storeElementEvent[handlerKey].originalHandler)
      }
253
254
255
    }
  }

Johann-S's avatar
Johann-S committed
256
  return {
257
258
    on(element, event, handler, delegationFn) {
      addHandler(element, event, handler, delegationFn, false)
Johann-S's avatar
Johann-S committed
259
260
    },

261
262
    one(element, event, handler, delegationFn) {
      addHandler(element, event, handler, delegationFn, true)
Johann-S's avatar
Johann-S committed
263
    },
Johann-S's avatar
Johann-S committed
264

Johann-S's avatar
Johann-S committed
265
266
267
268
269
    off(element, originalTypeEvent, handler) {
      if (typeof originalTypeEvent !== 'string' ||
        (typeof element === 'undefined' || element === null)) {
        return
      }
Johann-S's avatar
Johann-S committed
270

Johann-S's avatar
Johann-S committed
271
272
      const events      = getEvent(element)
      let typeEvent     = originalTypeEvent.replace(stripNameRegex, '')
273

Johann-S's avatar
Johann-S committed
274
275
276
277
278
      const inNamespace = typeEvent !== originalTypeEvent
      const custom      = customEvents[typeEvent]
      if (custom) {
        typeEvent = custom
      }
279

Johann-S's avatar
Johann-S committed
280
281
282
283
284
285
286
287
288
289
      const isNative = nativeEvents.indexOf(typeEvent) > -1
      if (!isNative) {
        typeEvent = originalTypeEvent
      }

      if (typeof handler !== 'undefined') {
        // Simplest case: handler is passed, remove that listener ONLY.
        if (!events || !events[typeEvent]) {
          return
        }
290

Johann-S's avatar
Johann-S committed
291
        removeHandler(element, events, typeEvent, handler)
292
293
294
        return
      }

Johann-S's avatar
Johann-S committed
295
296
297
298
299
300
      const isNamespace = originalTypeEvent.charAt(0) === '.'
      if (isNamespace) {
        for (const elementEvent in events) {
          if (!Object.prototype.hasOwnProperty.call(events, elementEvent)) {
            continue
          }
301

Johann-S's avatar
Johann-S committed
302
          removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.substr(1))
Johann-S's avatar
Johann-S committed
303
304
        }
      }
305

Johann-S's avatar
Johann-S committed
306
307
308
309
310
311
312
313
314
315
      const storeElementEvent = events[typeEvent] || {}
      for (const keyHandlers in storeElementEvent) {
        if (!Object.prototype.hasOwnProperty.call(storeElementEvent, keyHandlers)) {
          continue
        }

        const handlerKey = keyHandlers.replace(stripUidRegex, '')
        if (!inNamespace || originalTypeEvent.indexOf(handlerKey) > -1) {
          removeHandler(element, events, typeEvent, storeElementEvent[keyHandlers].originalHandler)
        }
Johann-S's avatar
Johann-S committed
316
      }
Johann-S's avatar
Johann-S committed
317
    },
Johann-S's avatar
Johann-S committed
318

Johann-S's avatar
Johann-S committed
319
320
321
322
    trigger(element, event, args) {
      if (typeof event !== 'string' ||
          (typeof element === 'undefined' || element === null)) {
        return null
323
      }
Johann-S's avatar
Johann-S committed
324

Johann-S's avatar
Johann-S committed
325
326
327
      const typeEvent   = event.replace(stripNameRegex, '')
      const inNamespace = event !== typeEvent
      const isNative    = nativeEvents.indexOf(typeEvent) > -1
Johann-S's avatar
Johann-S committed
328

Johann-S's avatar
Johann-S committed
329
330
      const $ = Util.jQuery
      let jQueryEvent
331

Johann-S's avatar
Johann-S committed
332
333
334
      let bubbles = true
      let nativeDispatch = true
      let defaultPrevented = false
335

Johann-S's avatar
Johann-S committed
336
337
      if (inNamespace && typeof $ !== 'undefined') {
        jQueryEvent = new $.Event(event, args)
338

Johann-S's avatar
Johann-S committed
339
340
341
342
343
        $(element).trigger(jQueryEvent)
        bubbles = !jQueryEvent.isPropagationStopped()
        nativeDispatch = !jQueryEvent.isImmediatePropagationStopped()
        defaultPrevented = jQueryEvent.isDefaultPrevented()
      }
344

Johann-S's avatar
Johann-S committed
345
      let evt           = null
346

Johann-S's avatar
Johann-S committed
347
348
349
350
351
352
353
354
355
      if (isNative) {
        evt = document.createEvent('HTMLEvents')
        evt.initEvent(typeEvent, bubbles, true)
      } else {
        evt = new CustomEvent(event, {
          bubbles,
          cancelable: true
        })
      }
Johann-S's avatar
Johann-S committed
356

Johann-S's avatar
Johann-S committed
357
358
359
360
      // merge custom informations in our event
      if (typeof args !== 'undefined') {
        evt = Util.extend(evt, args)
      }
Johann-S's avatar
Johann-S committed
361

Johann-S's avatar
Johann-S committed
362
363
      if (defaultPrevented) {
        evt.preventDefault()
364

Johann-S's avatar
Johann-S committed
365
366
367
368
369
370
        if (!defaultPreventedPreservedOnDispatch) {
          Object.defineProperty(evt, 'defaultPrevented', {
            get: () => true
          })
        }
      }
371

Johann-S's avatar
Johann-S committed
372
373
      if (nativeDispatch) {
        element.dispatchEvent(evt)
374
      }
375

Johann-S's avatar
Johann-S committed
376
377
378
      if (evt.defaultPrevented && typeof jQueryEvent !== 'undefined') {
        jQueryEvent.preventDefault()
      }
379

Johann-S's avatar
Johann-S committed
380
      return evt
381
    }
Johann-S's avatar
Johann-S committed
382
  }
Johann-S's avatar
Johann-S committed
383
})()
Johann-S's avatar
Johann-S committed
384

385
386
387
388
389
390
391
392
393
394
395
396
397
398
// focusin and focusout polyfill
if (typeof window.onfocusin === 'undefined') {
  (() => {
    function listenerFocus(event) {
      EventHandler.trigger(event.target, 'focusin')
    }
    function listenerBlur(event) {
      EventHandler.trigger(event.target, 'focusout')
    }
    EventHandler.on(document, 'focus', 'input', listenerFocus)
    EventHandler.on(document, 'blur', 'input', listenerBlur)
  })()
}

Johann-S's avatar
Johann-S committed
399
export default EventHandler