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

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

Johann-S's avatar
Johann-S committed
11
12
13
14
15
16
const EventHandler = (() => {
  /**
   * ------------------------------------------------------------------------
   * Constants
   * ------------------------------------------------------------------------
   */
Johann-S's avatar
Johann-S committed
17

Johann-S's avatar
Johann-S committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  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',
Johann-S's avatar
Johann-S committed
35
    'pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointercancel',
Johann-S's avatar
Johann-S committed
36
37
38
39
40
41
42
43
44
45
46
47
48
    '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) {
49
    return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++
Johann-S's avatar
Johann-S committed
50
  }
Johann-S's avatar
Johann-S committed
51

Johann-S's avatar
Johann-S committed
52
53
  function getEvent(element) {
    const uid = getUidEvent(element)
54
55
    element.uidEvent = uid

Johann-S's avatar
Johann-S committed
56
57
    return eventRegistry[uid] = eventRegistry[uid] || {}
  }
Johann-S's avatar
Johann-S committed
58

59
  function fixEvent(event, element) {
Johann-S's avatar
Johann-S committed
60
61
62
63
    // Add which for key events
    if (event.which === null && keyEventRegex.test(event.type)) {
      event.which = event.charCode !== null ? event.charCode : event.keyCode
    }
64
65

    event.delegateTarget = element
Johann-S's avatar
Johann-S committed
66
67
  }

Johann-S's avatar
Johann-S committed
68
  function bootstrapHandler(element, fn) {
69
70
71
72
73
74
    return function handler(event) {
      fixEvent(event, element)
      if (handler.oneOff) {
        EventHandler.off(element, event.type, fn)
      }

Johann-S's avatar
Johann-S committed
75
76
      return fn.apply(element, [event])
    }
Johann-S's avatar
Johann-S committed
77
78
  }

Johann-S's avatar
Johann-S committed
79
  function bootstrapDelegationHandler(element, selector, fn) {
80
    return function handler(event) {
Johann-S's avatar
Johann-S committed
81
82
83
84
      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) {
85
86
87
88
89
            fixEvent(event, target)
            if (handler.oneOff) {
              EventHandler.off(element, event.type, fn)
            }

Johann-S's avatar
Johann-S committed
90
91
            return fn.apply(target, [event])
          }
92
93
        }
      }
94

Johann-S's avatar
Johann-S committed
95
96
      // To please ESLint
      return null
97
98
99
    }
  }

100
  function findHandler(events, handler, delegationSelector = null) {
101
102
103
104
105
    for (const uid in events) {
      if (!Object.prototype.hasOwnProperty.call(events, uid)) {
        continue
      }

106
107
      const event = events[uid]
      if (event.originalHandler === handler && event.delegationSelector === delegationSelector) {
108
109
110
111
112
113
114
        return events[uid]
      }
    }

    return null
  }

115
  function normalizeParams(originalTypeEvent, handler, delegationFn) {
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    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
    }

132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    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)

147
148
    const events     = getEvent(element)
    const handlers   = events[typeEvent] || (events[typeEvent] = {})
149
    const previousFn = findHandler(handlers, originalHandler, delegation ? handler : null)
150
151
152
153
154
155
156
157
158

    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)

159
    fn.delegationSelector = delegation ? handler : null
160
161
    fn.originalHandler = originalHandler
    fn.oneOff = oneOff
162
    fn.uidEvent = uid
163
164
165
166
167
    handlers[uid] = fn

    element.addEventListener(typeEvent, fn, delegation)
  }

168
169
  function removeHandler(element, events, typeEvent, handler, delegationSelector) {
    const fn = findHandler(events[typeEvent], handler, delegationSelector)
170
171
172
173
    if (fn === null) {
      return
    }

174
175
    element.removeEventListener(typeEvent, fn, Boolean(delegationSelector))
    delete events[typeEvent][fn.uidEvent]
Johann-S's avatar
Johann-S committed
176
  }
177

Johann-S's avatar
Johann-S committed
178
179
180
181
182
183
  function removeNamespacedHandlers(element, events, typeEvent, namespace) {
    const storeElementEvent = events[typeEvent] || {}
    for (const handlerKey in storeElementEvent) {
      if (!Object.prototype.hasOwnProperty.call(storeElementEvent, handlerKey)) {
        continue
      }
184

Johann-S's avatar
Johann-S committed
185
      if (handlerKey.indexOf(namespace) > -1) {
186
187
        const event = storeElementEvent[handlerKey]
        removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector)
Johann-S's avatar
Johann-S committed
188
      }
189
190
191
    }
  }

Johann-S's avatar
Johann-S committed
192
  return {
193
194
    on(element, event, handler, delegationFn) {
      addHandler(element, event, handler, delegationFn, false)
Johann-S's avatar
Johann-S committed
195
196
    },

197
198
    one(element, event, handler, delegationFn) {
      addHandler(element, event, handler, delegationFn, true)
Johann-S's avatar
Johann-S committed
199
    },
Johann-S's avatar
Johann-S committed
200

201
202
    off(element, originalTypeEvent, handler, delegationFn) {
      if (typeof originalTypeEvent !== 'string' || (typeof element === 'undefined' || element === null)) {
Johann-S's avatar
Johann-S committed
203
204
        return
      }
Johann-S's avatar
Johann-S committed
205

206
      const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn)
207

Johann-S's avatar
Johann-S committed
208
      const inNamespace = typeEvent !== originalTypeEvent
209
      const events = getEvent(element)
Johann-S's avatar
Johann-S committed
210

211
      if (typeof originalHandler !== 'undefined') {
Johann-S's avatar
Johann-S committed
212
213
214
215
        // Simplest case: handler is passed, remove that listener ONLY.
        if (!events || !events[typeEvent]) {
          return
        }
216

217
        removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null)
218
219
220
        return
      }

Johann-S's avatar
Johann-S committed
221
222
223
224
225
226
      const isNamespace = originalTypeEvent.charAt(0) === '.'
      if (isNamespace) {
        for (const elementEvent in events) {
          if (!Object.prototype.hasOwnProperty.call(events, elementEvent)) {
            continue
          }
227

Johann-S's avatar
Johann-S committed
228
          removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.substr(1))
Johann-S's avatar
Johann-S committed
229
230
        }
      }
231

Johann-S's avatar
Johann-S committed
232
233
234
235
236
237
238
239
      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) {
240
241
          const event = storeElementEvent[keyHandlers]
          removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector)
Johann-S's avatar
Johann-S committed
242
        }
Johann-S's avatar
Johann-S committed
243
      }
Johann-S's avatar
Johann-S committed
244
    },
Johann-S's avatar
Johann-S committed
245

Johann-S's avatar
Johann-S committed
246
247
248
249
    trigger(element, event, args) {
      if (typeof event !== 'string' ||
          (typeof element === 'undefined' || element === null)) {
        return null
250
      }
Johann-S's avatar
Johann-S committed
251

Johann-S's avatar
Johann-S committed
252
253
254
      const typeEvent   = event.replace(stripNameRegex, '')
      const inNamespace = event !== typeEvent
      const isNative    = nativeEvents.indexOf(typeEvent) > -1
Johann-S's avatar
Johann-S committed
255

Johann-S's avatar
Johann-S committed
256
257
      const $ = Util.jQuery
      let jQueryEvent
258

Johann-S's avatar
Johann-S committed
259
260
261
      let bubbles = true
      let nativeDispatch = true
      let defaultPrevented = false
262

Johann-S's avatar
Johann-S committed
263
      if (inNamespace && typeof $ !== 'undefined') {
Johann-S's avatar
Johann-S committed
264
        jQueryEvent = $.Event(event, args)
265

Johann-S's avatar
Johann-S committed
266
267
268
269
270
        $(element).trigger(jQueryEvent)
        bubbles = !jQueryEvent.isPropagationStopped()
        nativeDispatch = !jQueryEvent.isImmediatePropagationStopped()
        defaultPrevented = jQueryEvent.isDefaultPrevented()
      }
271

Johann-S's avatar
Johann-S committed
272
      let evt = null
Johann-S's avatar
Johann-S committed
273
274
275
276
277
278
279
280
281
      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
282

Johann-S's avatar
Johann-S committed
283
284
      // merge custom informations in our event
      if (typeof args !== 'undefined') {
285
286
287
288
289
290
291
292
        Object.keys(args)
          .forEach((key) => {
            Object.defineProperty(evt, key, {
              get() {
                return args[key]
              }
            })
          })
Johann-S's avatar
Johann-S committed
293
      }
Johann-S's avatar
Johann-S committed
294

Johann-S's avatar
Johann-S committed
295
296
      if (defaultPrevented) {
        evt.preventDefault()
297

298
        if (!Polyfill.defaultPreventedPreservedOnDispatch) {
Johann-S's avatar
Johann-S committed
299
300
301
302
303
          Object.defineProperty(evt, 'defaultPrevented', {
            get: () => true
          })
        }
      }
304

Johann-S's avatar
Johann-S committed
305
306
      if (nativeDispatch) {
        element.dispatchEvent(evt)
307
      }
308

Johann-S's avatar
Johann-S committed
309
310
311
      if (evt.defaultPrevented && typeof jQueryEvent !== 'undefined') {
        jQueryEvent.preventDefault()
      }
312

Johann-S's avatar
Johann-S committed
313
      return evt
314
    }
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/* istanbul ignore next */
// focusin and focusout polyfill
if (Polyfill.focusIn) {
  (() => {
    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
333
export default EventHandler