dropdown.js 10.2 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
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * --------------------------------------------------------------------------
 */

const Dropdown = (($) => {

Johann-S's avatar
Johann-S committed
13
14
15
16
17
18
19
  /**
   * Check for Popper dependency
   * Popper - https://popper.js.org
   */
  if (typeof Popper === 'undefined') {
    throw new Error('Bootstrap dropdown require Popper (https://popper.js.org)')
  }
fat's avatar
fat committed
20
21
22
23
24
25
26

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

27
  const NAME                     = 'dropdown'
Mark Otto's avatar
Mark Otto committed
28
  const VERSION                  = '4.0.0-alpha.6'
29
30
31
32
33
  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
34
  const SPACE_KEYCODE            = 32 // KeyboardEvent.which value for space key
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
35
  const TAB_KEYCODE              = 9 // KeyboardEvent.which value for tab key
36
37
38
  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
39
  const REGEXP_KEYDOWN           = new RegExp(`${ARROW_UP_KEYCODE}|${ARROW_DOWN_KEYCODE}|${ESCAPE_KEYCODE}`)
fat's avatar
fat committed
40
41

  const Event = {
XhmikosR's avatar
XhmikosR committed
42
43
44
45
46
    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
47
    CLICK_DATA_API   : `click${EVENT_KEY}${DATA_API_KEY}`,
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
48
49
    KEYDOWN_DATA_API : `keydown${EVENT_KEY}${DATA_API_KEY}`,
    KEYUP_DATA_API   : `keyup${EVENT_KEY}${DATA_API_KEY}`
fat's avatar
fat committed
50
51
52
53
  }

  const ClassName = {
    DISABLED : 'disabled',
Starsam80's avatar
Starsam80 committed
54
    SHOW     : 'show'
fat's avatar
fat committed
55
56
57
58
59
  }

  const Selector = {
    DATA_TOGGLE   : '[data-toggle="dropdown"]',
    FORM_CHILD    : '.dropdown form',
60
    MENU          : '.dropdown-menu',
fat's avatar
fat committed
61
    NAVBAR_NAV    : '.navbar-nav',
62
    VISIBLE_ITEMS : '.dropdown-menu .dropdown-item:not(.disabled)'
fat's avatar
fat committed
63
64
  }

Johann-S's avatar
Johann-S committed
65
66
  const Default = {
    placement   : 'bottom',
67
    offset      : {}
Johann-S's avatar
Johann-S committed
68
69
70
71
  }

  const DefaultType = {
    placement       : 'string',
72
    offset          : 'number'
Johann-S's avatar
Johann-S committed
73
74
  }

fat's avatar
fat committed
75
76
77
78
79
80
81
82
83

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

  class Dropdown {

Johann-S's avatar
Johann-S committed
84
    constructor(element, config) {
fat's avatar
fat committed
85
      this._element = element
Johann-S's avatar
Johann-S committed
86
87
88
      this._popper  = null
      this._config = this._getConfig(config)
      this._menu = this._getMenuElement()
fat's avatar
fat committed
89
90

      this._addEventListeners()
fat's avatar
fat committed
91
92
    }

93
94
95
96
97
98
99

    // getters

    static get VERSION() {
      return VERSION
    }

Johann-S's avatar
Johann-S committed
100
101
102
103
104
105
106
107
    static get Default() {
      return Default
    }

    static get DefaultType() {
      return DefaultType
    }

108

fat's avatar
fat committed
109
110
111
    // public

    toggle() {
Johann-S's avatar
Johann-S committed
112
113
114
115
116
117
118
      let context = $(this).data(DATA_KEY)
      if (!context) {
        context = new Dropdown(this)
        $(this).data(DATA_KEY, context)
      }

      if (context.disabled || $(this).hasClass(ClassName.DISABLED)) {
Jacob Thornton's avatar
Jacob Thornton committed
119
        return false
fat's avatar
fat committed
120
121
      }

122
      const parent   = Dropdown._getParentFromElement(this)
Johann-S's avatar
Johann-S committed
123
      const isActive = $(context._menu).hasClass(ClassName.SHOW)
fat's avatar
fat committed
124
125
126
127
128
129
130

      Dropdown._clearMenus()

      if (isActive) {
        return false
      }

131
132
133
      const relatedTarget = {
        relatedTarget : this
      }
Johann-S's avatar
Johann-S committed
134
      const showEvent = $.Event(Event.SHOW, relatedTarget)
fat's avatar
fat committed
135
136
137
138

      $(parent).trigger(showEvent)

      if (showEvent.isDefaultPrevented()) {
Jacob Thornton's avatar
Jacob Thornton committed
139
        return false
fat's avatar
fat committed
140
141
      }

Johann-S's avatar
Johann-S committed
142
143
      this._popper = new Popper(this, context._menu, {
        placement : context._config.placement,
144
145
146
147
        modifiers : {
          offset : {
            offset : this.config.offset
          }
Johann-S's avatar
Johann-S committed
148
149
150
        }
      })

151
152
153
154
      // 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
155
156
      if ('ontouchstart' in document.documentElement &&
         !$(parent).closest(Selector.NAVBAR_NAV).length) {
157
        $('body').children().on('mouseover', null, $.noop)
158
159
      }

fat's avatar
fat committed
160
      this.focus()
161
      this.setAttribute('aria-expanded', true)
fat's avatar
fat committed
162

Johann-S's avatar
Johann-S committed
163
164
165
166
      $(context._menu).toggleClass(ClassName.SHOW)
      $(parent)
        .toggleClass(ClassName.SHOW)
        .trigger($.Event(Event.SHOWN, relatedTarget))
fat's avatar
fat committed
167
168
169
170

      return false
    }

fat's avatar
fat committed
171
172
173
174
    dispose() {
      $.removeData(this._element, DATA_KEY)
      $(this._element).off(EVENT_KEY)
      this._element = null
Johann-S's avatar
Johann-S committed
175
176
177
178
      this._menu = null
      if (this._popper !== null) {
        this._popper.destroy()
      }
fat's avatar
fat committed
179
180
181
182
183
184
185
186
187
    }


    // private

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

Johann-S's avatar
Johann-S committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    _getConfig(config) {
      config = $.extend(
        {},
        this.constructor.Default,
        $(this._element).data(),
        config
      )

      Util.typeCheckConfig(
        NAME,
        config,
        this.constructor.DefaultType
      )

      return config
    }

    _getMenuElement() {
      if (!this._menu) {
        let parent = Dropdown._getParentFromElement(this._element)
        this._menu = $(parent).find(Selector.MENU)[0]
      }
      return this._menu
    }
fat's avatar
fat committed
212
213
214
215
216

    // static

    static _jQueryInterface(config) {
      return this.each(function () {
217
        let data = $(this).data(DATA_KEY)
Johann-S's avatar
Johann-S committed
218
        let _config = typeof config === 'object' ? config : null
fat's avatar
fat committed
219
220

        if (!data) {
Johann-S's avatar
Johann-S committed
221
          data = new Dropdown(this, _config)
222
          $(this).data(DATA_KEY, data)
fat's avatar
fat committed
223
224
225
        }

        if (typeof config === 'string') {
226
227
228
          if (data[config] === undefined) {
            throw new Error(`No method named "${config}"`)
          }
fat's avatar
fat committed
229
230
231
232
233
234
          data[config].call(this)
        }
      })
    }

    static _clearMenus(event) {
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
235
236
      if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH ||
        event.type === 'keyup' && event.which !== TAB_KEYCODE)) {
fat's avatar
fat committed
237
238
239
        return
      }

240
      const toggles = $.makeArray($(Selector.DATA_TOGGLE))
fat's avatar
fat committed
241
      for (let i = 0; i < toggles.length; i++) {
242
        const parent        = Dropdown._getParentFromElement(toggles[i])
Johann-S's avatar
Johann-S committed
243
        let context         = $(toggles[i]).data(DATA_KEY)
244
245
246
        const relatedTarget = {
          relatedTarget : toggles[i]
        }
fat's avatar
fat committed
247

Johann-S's avatar
Johann-S committed
248
249
250
251
252
        if (!context) {
          continue
        }

        let dropdownMenu = context._menu
Starsam80's avatar
Starsam80 committed
253
        if (!$(parent).hasClass(ClassName.SHOW)) {
fat's avatar
fat committed
254
255
256
          continue
        }

257
        if (event && (event.type === 'click' &&
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
258
            /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE)
259
            && $.contains(parent, event.target)) {
fat's avatar
fat committed
260
261
262
          continue
        }

263
        const hideEvent = $.Event(Event.HIDE, relatedTarget)
fat's avatar
fat committed
264
265
266
267
268
        $(parent).trigger(hideEvent)
        if (hideEvent.isDefaultPrevented()) {
          continue
        }

269
270
271
        // if this is a touch-enabled device we remove the extra
        // empty mouseover listeners we added for iOS support
        if ('ontouchstart' in document.documentElement) {
272
          $('body').children().off('mouseover', null, $.noop)
273
274
        }

fat's avatar
fat committed
275
276
        toggles[i].setAttribute('aria-expanded', 'false')

Johann-S's avatar
Johann-S committed
277
        $(dropdownMenu).removeClass(ClassName.SHOW)
fat's avatar
fat committed
278
        $(parent)
Starsam80's avatar
Starsam80 committed
279
          .removeClass(ClassName.SHOW)
Jacob Thornton's avatar
Jacob Thornton committed
280
          .trigger($.Event(Event.HIDDEN, relatedTarget))
fat's avatar
fat committed
281
282
283
284
285
      }
    }

    static _getParentFromElement(element) {
      let parent
286
      const selector = Util.getSelectorFromElement(element)
fat's avatar
fat committed
287
288
289
290
291
292
293
294
295

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

      return parent || element.parentNode
    }

    static _dataApiKeydownHandler(event) {
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
296
      if (!REGEXP_KEYDOWN.test(event.which) || /button/i.test(event.target.tagName) && event.which === SPACE_KEYCODE ||
fat's avatar
fat committed
297
298
299
300
301
302
303
304
305
306
307
         /input|textarea/i.test(event.target.tagName)) {
        return
      }

      event.preventDefault()
      event.stopPropagation()

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

308
      const parent   = Dropdown._getParentFromElement(this)
Starsam80's avatar
Starsam80 committed
309
      const isActive = $(parent).hasClass(ClassName.SHOW)
fat's avatar
fat committed
310

311
312
      if (!isActive && (event.which !== ESCAPE_KEYCODE || event.which !== SPACE_KEYCODE) ||
           isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) {
fat's avatar
fat committed
313

314
        if (event.which === ESCAPE_KEYCODE) {
315
          const toggle = $(parent).find(Selector.DATA_TOGGLE)[0]
fat's avatar
fat committed
316
317
318
319
320
321
322
          $(toggle).trigger('focus')
        }

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

323
      const items = $(parent).find(Selector.VISIBLE_ITEMS).get()
fat's avatar
fat committed
324
325
326
327
328
329
330

      if (!items.length) {
        return
      }

      let index = items.indexOf(event.target)

331
      if (event.which === ARROW_UP_KEYCODE && index > 0) { // up
Jacob Thornton's avatar
Jacob Thornton committed
332
333
334
        index--
      }

335
      if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) { // down
Jacob Thornton's avatar
Jacob Thornton committed
336
337
338
        index++
      }

339
      if (index < 0) {
Jacob Thornton's avatar
Jacob Thornton committed
340
341
        index = 0
      }
fat's avatar
fat committed
342
343
344
345
346
347
348
349
350
351
352
353
354
355

      items[index].focus()
    }

  }


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

  $(document)
fat's avatar
fat committed
356
    .on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE,  Dropdown._dataApiKeydownHandler)
357
    .on(Event.KEYDOWN_DATA_API, Selector.MENU, Dropdown._dataApiKeydownHandler)
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
358
    .on(`${Event.CLICK_DATA_API} ${Event.KEYUP_DATA_API}`, Dropdown._clearMenus)
fat's avatar
fat committed
359
    .on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, Dropdown.prototype.toggle)
Jacob Thornton's avatar
Jacob Thornton committed
360
361
362
    .on(Event.CLICK_DATA_API, Selector.FORM_CHILD, (e) => {
      e.stopPropagation()
    })
fat's avatar
fat committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382


  /**
   * ------------------------------------------------------------------------
   * 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