dropdown.js 8.37 KB
Newer Older
fat's avatar
fat committed
1
2
3
4
5
import Util from './util'


/**
 * --------------------------------------------------------------------------
Mark Otto's avatar
Mark Otto committed
6
 * Bootstrap (v4.0.0-alpha.6): dropdown.js
fat's avatar
fat committed
7
8
9
10
11
12
13
14
15
16
17
18
19
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * --------------------------------------------------------------------------
 */

const Dropdown = (($) => {


  /**
   * ------------------------------------------------------------------------
   * Constants
   * ------------------------------------------------------------------------
   */

20
  const NAME                     = 'dropdown'
Mark Otto's avatar
Mark Otto committed
21
  const VERSION                  = '4.0.0-alpha.6'
22
23
24
25
26
  const DATA_KEY                 = 'bs.dropdown'
  const EVENT_KEY                = `.${DATA_KEY}`
  const DATA_API_KEY             = '.data-api'
  const JQUERY_NO_CONFLICT       = $.fn[NAME]
  const ESCAPE_KEYCODE           = 27 // KeyboardEvent.which value for Escape (Esc) key
27
  const SPACE_KEYCODE            = 32 // KeyboardEvent.which value for space key
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
28
  const TAB_KEYCODE              = 9 // KeyboardEvent.which value for tab key
29
30
31
  const ARROW_UP_KEYCODE         = 38 // KeyboardEvent.which value for up arrow key
  const ARROW_DOWN_KEYCODE       = 40 // KeyboardEvent.which value for down arrow key
  const RIGHT_MOUSE_BUTTON_WHICH = 3 // MouseEvent.which value for the right button (assuming a right-handed mouse)
Pierre-Denis Vanduynslager's avatar
Indent    
Pierre-Denis Vanduynslager committed
32
  const REGEXP_KEYDOWN           = new RegExp(`${ARROW_UP_KEYCODE}|${ARROW_DOWN_KEYCODE}|${ESCAPE_KEYCODE}`)
fat's avatar
fat committed
33
34

  const Event = {
XhmikosR's avatar
XhmikosR committed
35
36
37
38
39
    HIDE             : `hide${EVENT_KEY}`,
    HIDDEN           : `hidden${EVENT_KEY}`,
    SHOW             : `show${EVENT_KEY}`,
    SHOWN            : `shown${EVENT_KEY}`,
    CLICK            : `click${EVENT_KEY}`,
fat's avatar
fat committed
40
    CLICK_DATA_API   : `click${EVENT_KEY}${DATA_API_KEY}`,
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
41
42
    KEYDOWN_DATA_API : `keydown${EVENT_KEY}${DATA_API_KEY}`,
    KEYUP_DATA_API   : `keyup${EVENT_KEY}${DATA_API_KEY}`
fat's avatar
fat committed
43
44
45
46
  }

  const ClassName = {
    DISABLED : 'disabled',
Starsam80's avatar
Starsam80 committed
47
    SHOW     : 'show'
fat's avatar
fat committed
48
49
50
51
52
  }

  const Selector = {
    DATA_TOGGLE   : '[data-toggle="dropdown"]',
    FORM_CHILD    : '.dropdown form',
53
    MENU          : '.dropdown-menu',
fat's avatar
fat committed
54
    NAVBAR_NAV    : '.navbar-nav',
55
    VISIBLE_ITEMS : '.dropdown-menu .dropdown-item:not(.disabled)'
fat's avatar
fat committed
56
57
58
59
60
61
62
63
64
65
66
67
  }


  /**
   * ------------------------------------------------------------------------
   * Class Definition
   * ------------------------------------------------------------------------
   */

  class Dropdown {

    constructor(element) {
fat's avatar
fat committed
68
69
70
      this._element = element

      this._addEventListeners()
fat's avatar
fat committed
71
72
    }

73
74
75
76
77
78
79
80

    // getters

    static get VERSION() {
      return VERSION
    }


fat's avatar
fat committed
81
82
83
84
    // public

    toggle() {
      if (this.disabled || $(this).hasClass(ClassName.DISABLED)) {
Jacob Thornton's avatar
Jacob Thornton committed
85
        return false
fat's avatar
fat committed
86
87
      }

88
      const parent   = Dropdown._getParentFromElement(this)
Starsam80's avatar
Starsam80 committed
89
      const isActive = $(parent).hasClass(ClassName.SHOW)
fat's avatar
fat committed
90
91
92
93
94
95
96

      Dropdown._clearMenus()

      if (isActive) {
        return false
      }

97
98
99
100
      const relatedTarget = {
        relatedTarget : this
      }
      const showEvent     = $.Event(Event.SHOW, relatedTarget)
fat's avatar
fat committed
101
102
103
104

      $(parent).trigger(showEvent)

      if (showEvent.isDefaultPrevented()) {
Jacob Thornton's avatar
Jacob Thornton committed
105
        return false
fat's avatar
fat committed
106
107
      }

108
109
110
111
      // if this is a touch-enabled device we add extra
      // empty mouseover listeners to the body's immediate children;
      // only needed because of broken event delegation on iOS
      // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
112
113
      if ('ontouchstart' in document.documentElement &&
         !$(parent).closest(Selector.NAVBAR_NAV).length) {
114
        $('body').children().on('mouseover', null, $.noop)
115
116
      }

fat's avatar
fat committed
117
      this.focus()
118
      this.setAttribute('aria-expanded', true)
fat's avatar
fat committed
119

Starsam80's avatar
Starsam80 committed
120
      $(parent).toggleClass(ClassName.SHOW)
Jacob Thornton's avatar
Jacob Thornton committed
121
      $(parent).trigger($.Event(Event.SHOWN, relatedTarget))
fat's avatar
fat committed
122
123
124
125

      return false
    }

fat's avatar
fat committed
126
127
128
129
130
131
132
133
134
135
136
137
138
    dispose() {
      $.removeData(this._element, DATA_KEY)
      $(this._element).off(EVENT_KEY)
      this._element = null
    }


    // private

    _addEventListeners() {
      $(this._element).on(Event.CLICK, this.toggle)
    }

fat's avatar
fat committed
139
140
141
142
143

    // static

    static _jQueryInterface(config) {
      return this.each(function () {
144
        let data = $(this).data(DATA_KEY)
fat's avatar
fat committed
145
146

        if (!data) {
147
148
          data = new Dropdown(this)
          $(this).data(DATA_KEY, data)
fat's avatar
fat committed
149
150
151
        }

        if (typeof config === 'string') {
152
153
154
          if (data[config] === undefined) {
            throw new Error(`No method named "${config}"`)
          }
fat's avatar
fat committed
155
156
157
158
159
160
          data[config].call(this)
        }
      })
    }

    static _clearMenus(event) {
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
161
162
      if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH ||
        event.type === 'keyup' && event.which !== TAB_KEYCODE)) {
fat's avatar
fat committed
163
164
165
        return
      }

166
      const toggles = $.makeArray($(Selector.DATA_TOGGLE))
fat's avatar
fat committed
167
168

      for (let i = 0; i < toggles.length; i++) {
169
170
171
172
        const parent        = Dropdown._getParentFromElement(toggles[i])
        const relatedTarget = {
          relatedTarget : toggles[i]
        }
fat's avatar
fat committed
173

Starsam80's avatar
Starsam80 committed
174
        if (!$(parent).hasClass(ClassName.SHOW)) {
fat's avatar
fat committed
175
176
177
          continue
        }

178
        if (event && (event.type === 'click' &&
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
179
            /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE)
180
            && $.contains(parent, event.target)) {
fat's avatar
fat committed
181
182
183
          continue
        }

184
        const hideEvent = $.Event(Event.HIDE, relatedTarget)
fat's avatar
fat committed
185
186
187
188
189
        $(parent).trigger(hideEvent)
        if (hideEvent.isDefaultPrevented()) {
          continue
        }

190
191
192
        // if this is a touch-enabled device we remove the extra
        // empty mouseover listeners we added for iOS support
        if ('ontouchstart' in document.documentElement) {
193
          $('body').children().off('mouseover', null, $.noop)
194
195
        }

fat's avatar
fat committed
196
197
198
        toggles[i].setAttribute('aria-expanded', 'false')

        $(parent)
Starsam80's avatar
Starsam80 committed
199
          .removeClass(ClassName.SHOW)
Jacob Thornton's avatar
Jacob Thornton committed
200
          .trigger($.Event(Event.HIDDEN, relatedTarget))
fat's avatar
fat committed
201
202
203
204
205
      }
    }

    static _getParentFromElement(element) {
      let parent
206
      const selector = Util.getSelectorFromElement(element)
fat's avatar
fat committed
207
208
209
210
211
212
213
214
215

      if (selector) {
        parent = $(selector)[0]
      }

      return parent || element.parentNode
    }

    static _dataApiKeydownHandler(event) {
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
216
      if (!REGEXP_KEYDOWN.test(event.which) || /button/i.test(event.target.tagName) && event.which === SPACE_KEYCODE ||
fat's avatar
fat committed
217
218
219
220
221
222
223
224
225
226
227
         /input|textarea/i.test(event.target.tagName)) {
        return
      }

      event.preventDefault()
      event.stopPropagation()

      if (this.disabled || $(this).hasClass(ClassName.DISABLED)) {
        return
      }

228
      const parent   = Dropdown._getParentFromElement(this)
Starsam80's avatar
Starsam80 committed
229
      const isActive = $(parent).hasClass(ClassName.SHOW)
fat's avatar
fat committed
230

231
232
      if (!isActive && (event.which !== ESCAPE_KEYCODE || event.which !== SPACE_KEYCODE) ||
           isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) {
fat's avatar
fat committed
233

234
        if (event.which === ESCAPE_KEYCODE) {
235
          const toggle = $(parent).find(Selector.DATA_TOGGLE)[0]
fat's avatar
fat committed
236
237
238
239
240
241
242
          $(toggle).trigger('focus')
        }

        $(this).trigger('click')
        return
      }

243
      const items = $(parent).find(Selector.VISIBLE_ITEMS).get()
fat's avatar
fat committed
244
245
246
247
248
249
250

      if (!items.length) {
        return
      }

      let index = items.indexOf(event.target)

251
      if (event.which === ARROW_UP_KEYCODE && index > 0) { // up
Jacob Thornton's avatar
Jacob Thornton committed
252
253
254
        index--
      }

255
      if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) { // down
Jacob Thornton's avatar
Jacob Thornton committed
256
257
258
        index++
      }

259
      if (index < 0) {
Jacob Thornton's avatar
Jacob Thornton committed
260
261
        index = 0
      }
fat's avatar
fat committed
262
263
264
265
266
267
268
269
270
271
272
273
274
275

      items[index].focus()
    }

  }


  /**
   * ------------------------------------------------------------------------
   * Data Api implementation
   * ------------------------------------------------------------------------
   */

  $(document)
fat's avatar
fat committed
276
    .on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE,  Dropdown._dataApiKeydownHandler)
277
    .on(Event.KEYDOWN_DATA_API, Selector.MENU, Dropdown._dataApiKeydownHandler)
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
278
    .on(`${Event.CLICK_DATA_API} ${Event.KEYUP_DATA_API}`, Dropdown._clearMenus)
fat's avatar
fat committed
279
    .on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, Dropdown.prototype.toggle)
Jacob Thornton's avatar
Jacob Thornton committed
280
281
282
    .on(Event.CLICK_DATA_API, Selector.FORM_CHILD, (e) => {
      e.stopPropagation()
    })
fat's avatar
fat committed
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302


  /**
   * ------------------------------------------------------------------------
   * jQuery
   * ------------------------------------------------------------------------
   */

  $.fn[NAME]             = Dropdown._jQueryInterface
  $.fn[NAME].Constructor = Dropdown
  $.fn[NAME].noConflict  = function () {
    $.fn[NAME] = JQUERY_NO_CONFLICT
    return Dropdown._jQueryInterface
  }

  return Dropdown

})(jQuery)

export default Dropdown