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

8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 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
})()

// CustomEvent polyfill for IE (see: https://mzl.la/2v76Zvn)
if (typeof window.CustomEvent !== 'function') {
  window.CustomEvent = (event, params) => {
    params = params || {
      bubbles: false,
22
23
      cancelable: false,
      detail: null
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
    }
    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
        })
      }
    }
    return evt
  }

  window.CustomEvent.prototype = window.Event.prototype
}

// 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const namespaceRegex = /[^.]*(?=\..*)\.|.*/
const stripNameRegex = /\..*/

// Events storage
const eventRegistry = {}
let uidEvent = 1

function getUidEvent(element, uid) {
  return element.uidEvent = uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++
}

function getEvent(element) {
  const uid = getUidEvent(element)
  return eventRegistry[uid] = eventRegistry[uid] || {}
}

77
78
79
80
81
82
83
84
85
86
87
88
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',
  'load', 'unload', 'beforeunload', 'resize', 'move', 'DOMContentLoaded', 'readystatechange',
  'error', 'abort', 'scroll'
]
Johann-S's avatar
Johann-S committed
89
90
91
92
93
94
95

function bootstrapHandler(element, fn) {
  return function (event) {
    return fn.apply(element, [event])
  }
}

96
97
98
99
100
101
102
103
104
105
function bootstrapDelegationHandler(selector, fn) {
  return function (event) {
    const domElements = document.querySelectorAll(selector)
    for (let target = event.target; target && target !== this; target = target.parentNode) {
      for (let i = domElements.length; i--;) {
        if (domElements[i] === target) {
          return fn.apply(target, [event])
        }
      }
    }
106
107
    // To please ESLint
    return null
108
109
110
  }
}

Johann-S's avatar
Johann-S committed
111
const EventHandler = {
112
  on(element, originalTypeEvent, handler, delegationFn) {
Johann-S's avatar
Johann-S committed
113
114
115
116
117
    if (typeof originalTypeEvent !== 'string' ||
        (typeof element === 'undefined' || element === null)) {
      return
    }

Johann-S's avatar
Johann-S committed
118
119
    const delegation      = typeof handler === 'string'
    const originalHandler = delegation ? delegationFn : handler
Johann-S's avatar
Johann-S committed
120
121
122
123
124
125
126
127
    // allow to get the native events from namespaced events ('click.bs.button' --> 'click')
    let typeEvent = originalTypeEvent.replace(stripNameRegex, '')
    const isNative = nativeEvents.indexOf(typeEvent) > -1
    if (!isNative) {
      typeEvent = originalTypeEvent
    }
    const events    = getEvent(element)
    const handlers  = events[typeEvent] || (events[typeEvent] = {})
Johann-S's avatar
Johann-S committed
128
    const uid       = getUidEvent(originalHandler, originalTypeEvent.replace(namespaceRegex, ''))
Johann-S's avatar
Johann-S committed
129
    if (handlers[uid]) {
Johann-S's avatar
Johann-S committed
130
131
      return
    }
Johann-S's avatar
Johann-S committed
132

133
    const fn = !delegation ? bootstrapHandler(element, handler) : bootstrapDelegationHandler(handler, delegationFn)
Johann-S's avatar
Johann-S committed
134
    handlers[uid] = fn
Johann-S's avatar
Johann-S committed
135
    originalHandler.uidEvent = uid
136
    element.addEventListener(typeEvent, fn, delegation)
Johann-S's avatar
Johann-S committed
137
138
139
  },

  one(element, event, handler) {
Johann-S's avatar
Johann-S committed
140
141
142
143
144
145
    function complete(e) {
      const typeEvent = event.replace(stripNameRegex, '')
      const events = getEvent(element)
      if (!events || !events[typeEvent]) {
        return
      }
146
147
      handler.apply(element, [e])
      EventHandler.off(element, event, complete)
Johann-S's avatar
Johann-S committed
148
    }
Johann-S's avatar
Johann-S committed
149
    EventHandler.on(element, event, complete)
Johann-S's avatar
Johann-S committed
150
151
  },

Johann-S's avatar
Johann-S committed
152
153
154
155
  off(element, originalTypeEvent, handler) {
    if (typeof originalTypeEvent !== 'string' ||
       (typeof element === 'undefined' || element === null)) {
      return
Johann-S's avatar
Johann-S committed
156
157
    }

Johann-S's avatar
Johann-S committed
158
159
160
161
162
    const typeEvent = originalTypeEvent.replace(stripNameRegex, '')
    const events = getEvent(element)
    if (!events || !events[typeEvent]) {
      return
    }
163

Johann-S's avatar
Johann-S committed
164
165
166
167
168
    const uidEvent = handler.uidEvent
    const fn = events[typeEvent][uidEvent]
    element.removeEventListener(typeEvent, fn, false)
    delete events[typeEvent][uidEvent]
  },
Johann-S's avatar
Johann-S committed
169

170
  trigger(element, event, args) {
Johann-S's avatar
Johann-S committed
171
    if (typeof event !== 'string' ||
172
        (typeof element === 'undefined' || element === null)) {
Johann-S's avatar
Johann-S committed
173
174
175
176
177
178
179
      return null
    }
    const typeEvent = event.replace(stripNameRegex, '')
    const isNative = nativeEvents.indexOf(typeEvent) > -1
    let returnedEvent = null
    if (isNative) {
      const evt = document.createEvent('HTMLEvents')
180
      evt.initEvent(typeEvent, true, true, typeof args !== 'undefined' ? args : {})
Johann-S's avatar
Johann-S committed
181
182
183
184
185
      element.dispatchEvent(evt)
      returnedEvent = evt
    } else {
      const eventToDispatch = new CustomEvent(event, {
        bubbles: true,
186
187
        cancelable: true,
        detail: typeof args !== 'undefined' ? args : {}
Johann-S's avatar
Johann-S committed
188
189
190
191
192
      })
      element.dispatchEvent(eventToDispatch)
      returnedEvent = eventToDispatch
    }
    return returnedEvent
Johann-S's avatar
Johann-S committed
193
194
195
  }
}

196
197
198
199
200
201
202
203
204
205
206
207
208
209
// 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
210
export default EventHandler