eventHandler.js 9.38 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
/**
 * --------------------------------------------------------------------------
6
 * Bootstrap (v4.1.1): 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
35
36
37
38
39
40
41
42
43
44
45
46
47
  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) {
48
    return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++
Johann-S's avatar
Johann-S committed
49
  }
Johann-S's avatar
Johann-S committed
50

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

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

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

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

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

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

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

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

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

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

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

    return null
  }

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

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

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

    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)

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

    element.addEventListener(typeEvent, fn, delegation)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

Johann-S's avatar
Johann-S committed
231
232
233
234
235
236
237
238
      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) {
239
240
          const event = storeElementEvent[keyHandlers]
          removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector)
Johann-S's avatar
Johann-S committed
241
        }
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
246
247
248
    trigger(element, event, args) {
      if (typeof event !== 'string' ||
          (typeof element === 'undefined' || element === null)) {
        return null
249
      }
Johann-S's avatar
Johann-S committed
250

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

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

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

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

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

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

Johann-S's avatar
Johann-S committed
282
283
      // merge custom informations in our event
      if (typeof args !== 'undefined') {
Johann-S's avatar
Johann-S committed
284
        evt = Object.assign(evt, args)
Johann-S's avatar
Johann-S committed
285
      }
Johann-S's avatar
Johann-S committed
286

Johann-S's avatar
Johann-S committed
287
288
      if (defaultPrevented) {
        evt.preventDefault()
289

290
        if (!Polyfill.defaultPreventedPreservedOnDispatch) {
Johann-S's avatar
Johann-S committed
291
292
293
294
295
          Object.defineProperty(evt, 'defaultPrevented', {
            get: () => true
          })
        }
      }
296

Johann-S's avatar
Johann-S committed
297
298
      if (nativeDispatch) {
        element.dispatchEvent(evt)
299
      }
300

Johann-S's avatar
Johann-S committed
301
302
303
      if (evt.defaultPrevented && typeof jQueryEvent !== 'undefined') {
        jQueryEvent.preventDefault()
      }
304

Johann-S's avatar
Johann-S committed
305
      return evt
306
    }
Johann-S's avatar
Johann-S committed
307
  }
Johann-S's avatar
Johann-S committed
308
})()
Johann-S's avatar
Johann-S committed
309

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