eventHandler.js 12.1 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
  function findHandler(events, handler, delegationSelector = null) {
174
175
176
177
178
    for (const uid in events) {
      if (!Object.prototype.hasOwnProperty.call(events, uid)) {
        continue
      }

179
180
      const event = events[uid]
      if (event.originalHandler === handler && event.delegationSelector === delegationSelector) {
181
182
183
184
185
186
187
        return events[uid]
      }
    }

    return null
  }

188
  function normalizeParams(originalTypeEvent, handler, delegationFn) {
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
    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
    }

205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
    return [delegation, originalHandler, typeEvent]
  }

  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, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn)

220
221
    const events     = getEvent(element)
    const handlers   = events[typeEvent] || (events[typeEvent] = {})
222
    const previousFn = findHandler(handlers, originalHandler, delegation ? handler : null)
223
224
225
226
227
228
229
230
231

    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)

232
    fn.delegationSelector = delegation ? handler : null
233
234
    fn.originalHandler = originalHandler
    fn.oneOff = oneOff
235
    fn.uidEvent = uid
236
237
238
239
240
    handlers[uid] = fn

    element.addEventListener(typeEvent, fn, delegation)
  }

241
242
  function removeHandler(element, events, typeEvent, handler, delegationSelector) {
    const fn = findHandler(events[typeEvent], handler, delegationSelector)
243
244
245
246
    if (fn === null) {
      return
    }

247
248
    element.removeEventListener(typeEvent, fn, Boolean(delegationSelector))
    delete events[typeEvent][fn.uidEvent]
Johann-S's avatar
Johann-S committed
249
  }
250

Johann-S's avatar
Johann-S committed
251
252
253
254
255
256
  function removeNamespacedHandlers(element, events, typeEvent, namespace) {
    const storeElementEvent = events[typeEvent] || {}
    for (const handlerKey in storeElementEvent) {
      if (!Object.prototype.hasOwnProperty.call(storeElementEvent, handlerKey)) {
        continue
      }
257

Johann-S's avatar
Johann-S committed
258
      if (handlerKey.indexOf(namespace) > -1) {
259
260
        const event = storeElementEvent[handlerKey]
        removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector)
Johann-S's avatar
Johann-S committed
261
      }
262
263
264
    }
  }

Johann-S's avatar
Johann-S committed
265
  return {
266
267
    on(element, event, handler, delegationFn) {
      addHandler(element, event, handler, delegationFn, false)
Johann-S's avatar
Johann-S committed
268
269
    },

270
271
    one(element, event, handler, delegationFn) {
      addHandler(element, event, handler, delegationFn, true)
Johann-S's avatar
Johann-S committed
272
    },
Johann-S's avatar
Johann-S committed
273

274
275
    off(element, originalTypeEvent, handler, delegationFn) {
      if (typeof originalTypeEvent !== 'string' || (typeof element === 'undefined' || element === null)) {
Johann-S's avatar
Johann-S committed
276
277
        return
      }
Johann-S's avatar
Johann-S committed
278

279
      const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn)
280

Johann-S's avatar
Johann-S committed
281
      const inNamespace = typeEvent !== originalTypeEvent
282
      const events = getEvent(element)
Johann-S's avatar
Johann-S committed
283

284
      if (typeof originalHandler !== 'undefined') {
Johann-S's avatar
Johann-S committed
285
286
287
288
        // Simplest case: handler is passed, remove that listener ONLY.
        if (!events || !events[typeEvent]) {
          return
        }
289

290
        removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null)
291
292
293
        return
      }

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

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

Johann-S's avatar
Johann-S committed
305
306
307
308
309
310
311
312
      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) {
313
314
          const event = storeElementEvent[keyHandlers]
          removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector)
Johann-S's avatar
Johann-S committed
315
        }
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
      if (inNamespace && typeof $ !== 'undefined') {
Johann-S's avatar
Johann-S committed
337
        jQueryEvent = $.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
Johann-S's avatar
Johann-S committed
346
347
348
349
350
351
352
353
354
      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
355

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

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

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

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

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

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

384
385
386
387
388
389
390
391
392
393
394
395
396
397
// 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
398
export default EventHandler