dropdown.js 13.9 KB
Newer Older
1
2
import $ from 'jquery'
import Popper from 'popper.js'
fat's avatar
fat committed
3
4
5
6
import Util from './util'

/**
 * --------------------------------------------------------------------------
Mark Otto's avatar
Mark Otto committed
7
 * Bootstrap (v4.0.0): dropdown.js
fat's avatar
fat committed
8
9
10
11
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * --------------------------------------------------------------------------
 */

12
const Dropdown = (($) => {
fat's avatar
fat committed
13
14
15
16
17
18
  /**
   * ------------------------------------------------------------------------
   * Constants
   * ------------------------------------------------------------------------
   */

19
  const NAME                     = 'dropdown'
Mark Otto's avatar
Mark Otto committed
20
  const VERSION                  = '4.0.0'
21
22
23
24
25
  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
26
  const SPACE_KEYCODE            = 32 // KeyboardEvent.which value for space key
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
27
  const TAB_KEYCODE              = 9 // KeyboardEvent.which value for tab key
28
29
30
  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
31
  const REGEXP_KEYDOWN           = new RegExp(`${ARROW_UP_KEYCODE}|${ARROW_DOWN_KEYCODE}|${ESCAPE_KEYCODE}`)
fat's avatar
fat committed
32
33

  const Event = {
XhmikosR's avatar
XhmikosR committed
34
35
36
37
38
    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
39
    CLICK_DATA_API   : `click${EVENT_KEY}${DATA_API_KEY}`,
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
40
41
    KEYDOWN_DATA_API : `keydown${EVENT_KEY}${DATA_API_KEY}`,
    KEYUP_DATA_API   : `keyup${EVENT_KEY}${DATA_API_KEY}`
fat's avatar
fat committed
42
43
44
  }

  const ClassName = {
45
46
47
    DISABLED  : 'disabled',
    SHOW      : 'show',
    DROPUP    : 'dropup',
48
49
    DROPRIGHT : 'dropright',
    DROPLEFT  : 'dropleft',
50
    MENURIGHT : 'dropdown-menu-right',
51
52
    MENULEFT  : 'dropdown-menu-left',
    POSITION_STATIC : 'position-static'
fat's avatar
fat committed
53
54
55
56
57
  }

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

Johann-S's avatar
Johann-S committed
63
  const AttachmentMap = {
64
65
66
    TOP       : 'top-start',
    TOPEND    : 'top-end',
    BOTTOM    : 'bottom-start',
67
68
69
70
71
    BOTTOMEND : 'bottom-end',
    RIGHT     : 'right-start',
    RIGHTEND  : 'right-end',
    LEFT      : 'left-start',
    LEFTEND   : 'left-end'
Johann-S's avatar
Johann-S committed
72
73
  }

Johann-S's avatar
Johann-S committed
74
  const Default = {
75
    offset      : 0,
76
    flip        : true,
77
78
    boundary    : 'scrollParent',
    reference   : 'toggle'
Johann-S's avatar
Johann-S committed
79
80
81
  }

  const DefaultType = {
82
    offset      : '(number|string|function)',
83
    flip        : 'boolean',
84
85
    boundary    : '(string|element)',
    reference   : '(string|element)'
Johann-S's avatar
Johann-S committed
86
87
  }

fat's avatar
fat committed
88
89
90
91
92
93
94
  /**
   * ------------------------------------------------------------------------
   * Class Definition
   * ------------------------------------------------------------------------
   */

  class Dropdown {
Johann-S's avatar
Johann-S committed
95
    constructor(element, config) {
96
97
98
99
100
      this._element  = element
      this._popper   = null
      this._config   = this._getConfig(config)
      this._menu     = this._getMenuElement()
      this._inNavbar = this._detectNavbar()
fat's avatar
fat committed
101
102

      this._addEventListeners()
fat's avatar
fat committed
103
104
    }

XhmikosR's avatar
XhmikosR committed
105
    // Getters
106
107
108
109
110

    static get VERSION() {
      return VERSION
    }

Johann-S's avatar
Johann-S committed
111
112
113
114
115
116
117
118
    static get Default() {
      return Default
    }

    static get DefaultType() {
      return DefaultType
    }

XhmikosR's avatar
XhmikosR committed
119
    // Public
fat's avatar
fat committed
120
121

    toggle() {
122
123
      if (this._element.disabled || $(this._element).hasClass(ClassName.DISABLED)) {
        return
fat's avatar
fat committed
124
125
      }

126
127
      const parent   = Dropdown._getParentFromElement(this._element)
      const isActive = $(this._menu).hasClass(ClassName.SHOW)
fat's avatar
fat committed
128
129
130
131

      Dropdown._clearMenus()

      if (isActive) {
132
        return
fat's avatar
fat committed
133
134
      }

135
      const relatedTarget = {
XhmikosR's avatar
XhmikosR committed
136
        relatedTarget: this._element
137
      }
Johann-S's avatar
Johann-S committed
138
      const showEvent = $.Event(Event.SHOW, relatedTarget)
fat's avatar
fat committed
139
140
141
142

      $(parent).trigger(showEvent)

      if (showEvent.isDefaultPrevented()) {
143
        return
fat's avatar
fat committed
144
145
      }

146
147
148
149
150
151
152
      // Disable totally Popper.js for Dropdown in Navbar
      if (!this._inNavbar) {
        /**
         * Check for Popper dependency
         * Popper - https://popper.js.org
         */
        if (typeof Popper === 'undefined') {
XhmikosR's avatar
XhmikosR committed
153
          throw new TypeError('Bootstrap dropdown require Popper.js (https://popper.js.org)')
154
        }
155
156
157
158
159
160
161
162
163
164
165

        let referenceElement = this._element

        if (this._config.reference === 'parent') {
          referenceElement = parent
        } else if (Util.isElement(this._config.reference)) {
          referenceElement = this._config.reference

          // Check if it's jQuery element
          if (typeof this._config.reference.jquery !== 'undefined') {
            referenceElement = this._config.reference[0]
166
          }
167
        }
168

169
170
171
172
173
174
        // If boundary is not `scrollParent`, then set position to `static`
        // to allow the menu to "escape" the scroll parent's boundaries
        // https://github.com/twbs/bootstrap/issues/24251
        if (this._config.boundary !== 'scrollParent') {
          $(parent).addClass(ClassName.POSITION_STATIC)
        }
175
        this._popper = new Popper(referenceElement, this._menu, this._getPopperConfig())
176
      }
177

XhmikosR's avatar
XhmikosR committed
178
      // If this is a touch-enabled device we add extra
179
180
181
      // 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
182
      if ('ontouchstart' in document.documentElement &&
XhmikosR's avatar
XhmikosR committed
183
         $(parent).closest(Selector.NAVBAR_NAV).length === 0) {
184
        $('body').children().on('mouseover', null, $.noop)
185
186
      }

187
188
      this._element.focus()
      this._element.setAttribute('aria-expanded', true)
fat's avatar
fat committed
189

190
      $(this._menu).toggleClass(ClassName.SHOW)
Johann-S's avatar
Johann-S committed
191
192
193
      $(parent)
        .toggleClass(ClassName.SHOW)
        .trigger($.Event(Event.SHOWN, relatedTarget))
fat's avatar
fat committed
194
195
    }

fat's avatar
fat committed
196
197
198
199
    dispose() {
      $.removeData(this._element, DATA_KEY)
      $(this._element).off(EVENT_KEY)
      this._element = null
Johann-S's avatar
Johann-S committed
200
201
202
      this._menu = null
      if (this._popper !== null) {
        this._popper.destroy()
203
        this._popper = null
Johann-S's avatar
Johann-S committed
204
      }
fat's avatar
fat committed
205
206
    }

207
    update() {
208
      this._inNavbar = this._detectNavbar()
209
210
211
212
      if (this._popper !== null) {
        this._popper.scheduleUpdate()
      }
    }
fat's avatar
fat committed
213

XhmikosR's avatar
XhmikosR committed
214
    // Private
fat's avatar
fat committed
215
216

    _addEventListeners() {
217
218
219
220
221
      $(this._element).on(Event.CLICK, (event) => {
        event.preventDefault()
        event.stopPropagation()
        this.toggle()
      })
fat's avatar
fat committed
222
223
    }

Johann-S's avatar
Johann-S committed
224
    _getConfig(config) {
225
226
227
228
229
      config = {
        ...this.constructor.Default,
        ...$(this._element).data(),
        ...config
      }
Johann-S's avatar
Johann-S committed
230
231
232
233
234
235
236
237
238
239
240
241

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

      return config
    }

    _getMenuElement() {
      if (!this._menu) {
242
        const parent = Dropdown._getParentFromElement(this._element)
Johann-S's avatar
Johann-S committed
243
244
245
246
        this._menu = $(parent).find(Selector.MENU)[0]
      }
      return this._menu
    }
fat's avatar
fat committed
247

248
249
    _getPlacement() {
      const $parentDropdown = $(this._element).parent()
XhmikosR's avatar
XhmikosR committed
250
      let placement = AttachmentMap.BOTTOM
251
252

      // Handle dropup
253
      if ($parentDropdown.hasClass(ClassName.DROPUP)) {
254
255
256
        placement = AttachmentMap.TOP
        if ($(this._menu).hasClass(ClassName.MENURIGHT)) {
          placement = AttachmentMap.TOPEND
257
        }
258
259
260
261
      } else if ($parentDropdown.hasClass(ClassName.DROPRIGHT)) {
        placement = AttachmentMap.RIGHT
      } else if ($parentDropdown.hasClass(ClassName.DROPLEFT)) {
        placement = AttachmentMap.LEFT
Johann-S's avatar
Johann-S committed
262
263
      } else if ($(this._menu).hasClass(ClassName.MENURIGHT)) {
        placement = AttachmentMap.BOTTOMEND
264
      }
265
      return placement
266
267
    }

268
269
270
271
272
    _detectNavbar() {
      return $(this._element).closest('.navbar').length > 0
    }

    _getPopperConfig() {
273
274
275
      const offsetConf = {}
      if (typeof this._config.offset === 'function') {
        offsetConf.fn = (data) => {
276
277
278
279
          data.offsets = {
            ...data.offsets,
            ...this._config.offset(data.offsets) || {}
          }
280
281
282
283
284
          return data
        }
      } else {
        offsetConf.offset = this._config.offset
      }
285
      const popperConfig = {
XhmikosR's avatar
XhmikosR committed
286
287
288
289
290
        placement: this._getPlacement(),
        modifiers: {
          offset: offsetConf,
          flip: {
            enabled: this._config.flip
291
          },
XhmikosR's avatar
XhmikosR committed
292
293
          preventOverflow: {
            boundariesElement: this._config.boundary
294
295
296
297
298
299
300
          }
        }
      }

      return popperConfig
    }

XhmikosR's avatar
XhmikosR committed
301
    // Static
fat's avatar
fat committed
302
303
304

    static _jQueryInterface(config) {
      return this.each(function () {
305
        let data = $(this).data(DATA_KEY)
306
        const _config = typeof config === 'object' ? config : null
fat's avatar
fat committed
307
308

        if (!data) {
Johann-S's avatar
Johann-S committed
309
          data = new Dropdown(this, _config)
310
          $(this).data(DATA_KEY, data)
fat's avatar
fat committed
311
312
313
        }

        if (typeof config === 'string') {
XhmikosR's avatar
XhmikosR committed
314
          if (typeof data[config] === 'undefined') {
XhmikosR's avatar
XhmikosR committed
315
            throw new TypeError(`No method named "${config}"`)
316
          }
317
          data[config]()
fat's avatar
fat committed
318
319
320
321
322
        }
      })
    }

    static _clearMenus(event) {
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
323
324
      if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH ||
        event.type === 'keyup' && event.which !== TAB_KEYCODE)) {
fat's avatar
fat committed
325
326
327
        return
      }

328
      const toggles = $.makeArray($(Selector.DATA_TOGGLE))
fat's avatar
fat committed
329
      for (let i = 0; i < toggles.length; i++) {
XhmikosR's avatar
XhmikosR committed
330
331
        const parent = Dropdown._getParentFromElement(toggles[i])
        const context = $(toggles[i]).data(DATA_KEY)
332
        const relatedTarget = {
XhmikosR's avatar
XhmikosR committed
333
          relatedTarget: toggles[i]
334
        }
fat's avatar
fat committed
335

Johann-S's avatar
Johann-S committed
336
337
338
339
        if (!context) {
          continue
        }

340
        const dropdownMenu = context._menu
Starsam80's avatar
Starsam80 committed
341
        if (!$(parent).hasClass(ClassName.SHOW)) {
fat's avatar
fat committed
342
343
344
          continue
        }

345
        if (event && (event.type === 'click' &&
XhmikosR's avatar
XhmikosR committed
346
347
            /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE) &&
            $.contains(parent, event.target)) {
fat's avatar
fat committed
348
349
350
          continue
        }

351
        const hideEvent = $.Event(Event.HIDE, relatedTarget)
fat's avatar
fat committed
352
353
354
355
356
        $(parent).trigger(hideEvent)
        if (hideEvent.isDefaultPrevented()) {
          continue
        }

XhmikosR's avatar
XhmikosR committed
357
        // If this is a touch-enabled device we remove the extra
358
359
        // empty mouseover listeners we added for iOS support
        if ('ontouchstart' in document.documentElement) {
360
          $('body').children().off('mouseover', null, $.noop)
361
362
        }

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

Johann-S's avatar
Johann-S committed
365
        $(dropdownMenu).removeClass(ClassName.SHOW)
fat's avatar
fat committed
366
        $(parent)
Starsam80's avatar
Starsam80 committed
367
          .removeClass(ClassName.SHOW)
Jacob Thornton's avatar
Jacob Thornton committed
368
          .trigger($.Event(Event.HIDDEN, relatedTarget))
fat's avatar
fat committed
369
370
371
372
373
      }
    }

    static _getParentFromElement(element) {
      let parent
374
      const selector = Util.getSelectorFromElement(element)
fat's avatar
fat committed
375
376
377
378
379
380
381
382

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

      return parent || element.parentNode
    }

383
    // eslint-disable-next-line complexity
fat's avatar
fat committed
384
    static _dataApiKeydownHandler(event) {
385
386
387
388
      // If not input/textarea:
      //  - And not a key in REGEXP_KEYDOWN => not a dropdown command
      // If input/textarea:
      //  - If space key => not a dropdown command
Johann-S's avatar
Johann-S committed
389
      //  - If key is other than escape
390
391
      //    - If key is not up or down => not a dropdown command
      //    - If trigger inside the menu => not a dropdown command
XhmikosR's avatar
XhmikosR committed
392
393
      if (/input|textarea/i.test(event.target.tagName)
        ? event.which === SPACE_KEYCODE || event.which !== ESCAPE_KEYCODE &&
394
395
        (event.which !== ARROW_DOWN_KEYCODE && event.which !== ARROW_UP_KEYCODE ||
          $(event.target).closest(Selector.MENU).length) : !REGEXP_KEYDOWN.test(event.which)) {
fat's avatar
fat committed
396
397
398
399
400
401
402
403
404
405
        return
      }

      event.preventDefault()
      event.stopPropagation()

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

406
      const parent   = Dropdown._getParentFromElement(this)
Starsam80's avatar
Starsam80 committed
407
      const isActive = $(parent).hasClass(ClassName.SHOW)
fat's avatar
fat committed
408

409
410
      if (!isActive && (event.which !== ESCAPE_KEYCODE || event.which !== SPACE_KEYCODE) ||
           isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) {
411
        if (event.which === ESCAPE_KEYCODE) {
412
          const toggle = $(parent).find(Selector.DATA_TOGGLE)[0]
fat's avatar
fat committed
413
414
415
416
417
418
419
          $(toggle).trigger('focus')
        }

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

420
      const items = $(parent).find(Selector.VISIBLE_ITEMS).get()
fat's avatar
fat committed
421

XhmikosR's avatar
XhmikosR committed
422
      if (items.length === 0) {
fat's avatar
fat committed
423
424
425
426
427
        return
      }

      let index = items.indexOf(event.target)

XhmikosR's avatar
XhmikosR committed
428
      if (event.which === ARROW_UP_KEYCODE && index > 0) { // Up
Jacob Thornton's avatar
Jacob Thornton committed
429
430
431
        index--
      }

XhmikosR's avatar
XhmikosR committed
432
      if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) { // Down
Jacob Thornton's avatar
Jacob Thornton committed
433
434
435
        index++
      }

436
      if (index < 0) {
Jacob Thornton's avatar
Jacob Thornton committed
437
438
        index = 0
      }
fat's avatar
fat committed
439
440
441
442
443
444
445
446
447
448
449
450

      items[index].focus()
    }
  }

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

  $(document)
XhmikosR's avatar
XhmikosR committed
451
    .on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE, Dropdown._dataApiKeydownHandler)
452
    .on(Event.KEYDOWN_DATA_API, Selector.MENU, Dropdown._dataApiKeydownHandler)
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
453
    .on(`${Event.CLICK_DATA_API} ${Event.KEYUP_DATA_API}`, Dropdown._clearMenus)
454
455
456
457
458
    .on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
      event.preventDefault()
      event.stopPropagation()
      Dropdown._jQueryInterface.call($(this), 'toggle')
    })
Jacob Thornton's avatar
Jacob Thornton committed
459
460
461
    .on(Event.CLICK_DATA_API, Selector.FORM_CHILD, (e) => {
      e.stopPropagation()
    })
fat's avatar
fat committed
462
463
464
465
466
467
468

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

XhmikosR's avatar
XhmikosR committed
469
  $.fn[NAME] = Dropdown._jQueryInterface
fat's avatar
fat committed
470
  $.fn[NAME].Constructor = Dropdown
XhmikosR's avatar
XhmikosR committed
471
  $.fn[NAME].noConflict = function () {
fat's avatar
fat committed
472
473
474
475
476
    $.fn[NAME] = JQUERY_NO_CONFLICT
    return Dropdown._jQueryInterface
  }

  return Dropdown
477
})($, Popper)
fat's avatar
fat committed
478
479

export default Dropdown