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


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

13
const Dropdown = (($) => {
fat's avatar
fat committed
14
15
16
17
18
19
20

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

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

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

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

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

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

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

  const DefaultType = {
81
    offset      : '(number|string|function)',
82
    flip        : 'boolean'
Johann-S's avatar
Johann-S committed
83
84
  }

fat's avatar
fat committed
85
86
87
88
89
90
91
92
93

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

  class Dropdown {

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

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

104
105
106
107
108
109
110

    // getters

    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
    }

fat's avatar
fat committed
119
120
121
    // public

    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 = {
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
153
      /**
       * Check for Popper dependency
       * Popper - https://popper.js.org
       */
      if (typeof Popper === 'undefined') {
        throw new Error('Bootstrap dropdown require Popper.js (https://popper.js.org)')
      }

154
155
156
157
158
159
160
      let element = this._element
      // for dropup with alignment we use the parent as popper container
      if ($(parent).hasClass(ClassName.DROPUP)) {
        if ($(this._menu).hasClass(ClassName.MENULEFT) || $(this._menu).hasClass(ClassName.MENURIGHT)) {
          element = parent
        }
      }
161
      this._popper = new Popper(element, this._menu, this._getPopperConfig())
Johann-S's avatar
Johann-S committed
162

163
164
165
166
      // 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
167
168
      if ('ontouchstart' in document.documentElement &&
         !$(parent).closest(Selector.NAVBAR_NAV).length) {
169
        $('body').children().on('mouseover', null, $.noop)
170
171
      }

172
173
      this._element.focus()
      this._element.setAttribute('aria-expanded', true)
fat's avatar
fat committed
174

175
      $(this._menu).toggleClass(ClassName.SHOW)
Johann-S's avatar
Johann-S committed
176
177
178
      $(parent)
        .toggleClass(ClassName.SHOW)
        .trigger($.Event(Event.SHOWN, relatedTarget))
fat's avatar
fat committed
179
180
    }

fat's avatar
fat committed
181
182
183
184
    dispose() {
      $.removeData(this._element, DATA_KEY)
      $(this._element).off(EVENT_KEY)
      this._element = null
Johann-S's avatar
Johann-S committed
185
186
187
188
      this._menu = null
      if (this._popper !== null) {
        this._popper.destroy()
      }
189
      this._popper = null
fat's avatar
fat committed
190
191
    }

192
    update() {
193
      this._inNavbar = this._detectNavbar()
194
195
196
197
      if (this._popper !== null) {
        this._popper.scheduleUpdate()
      }
    }
fat's avatar
fat committed
198
199
200
201

    // private

    _addEventListeners() {
202
203
204
205
206
      $(this._element).on(Event.CLICK, (event) => {
        event.preventDefault()
        event.stopPropagation()
        this.toggle()
      })
fat's avatar
fat committed
207
208
    }

Johann-S's avatar
Johann-S committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    _getConfig(config) {
      config = $.extend(
        {},
        this.constructor.Default,
        $(this._element).data(),
        config
      )

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

      return config
    }

    _getMenuElement() {
      if (!this._menu) {
228
        const parent = Dropdown._getParentFromElement(this._element)
Johann-S's avatar
Johann-S committed
229
230
231
232
        this._menu = $(parent).find(Selector.MENU)[0]
      }
      return this._menu
    }
fat's avatar
fat committed
233

234
235
    _getPlacement() {
      const $parentDropdown = $(this._element).parent()
236
      let placement         = AttachmentMap.BOTTOM
237
238

      // Handle dropup
239
      if ($parentDropdown.hasClass(ClassName.DROPUP)) {
240
241
242
        placement = AttachmentMap.TOP
        if ($(this._menu).hasClass(ClassName.MENURIGHT)) {
          placement = AttachmentMap.TOPEND
243
        }
244
245
246
247
      } 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
248
249
      } else if ($(this._menu).hasClass(ClassName.MENURIGHT)) {
        placement = AttachmentMap.BOTTOMEND
250
      }
251
      return placement
252
253
    }

254
255
256
257
258
    _detectNavbar() {
      return $(this._element).closest('.navbar').length > 0
    }

    _getPopperConfig() {
259
260
261
262
263
264
265
266
267
      const offsetConf = {}
      if (typeof this._config.offset === 'function') {
        offsetConf.fn = (data) => {
          data.offsets = $.extend({}, data.offsets, this._config.offset(data.offsets) || {})
          return data
        }
      } else {
        offsetConf.offset = this._config.offset
      }
268
269
270
      const popperConfig = {
        placement : this._getPlacement(),
        modifiers : {
271
          offset : offsetConf,
272
273
274
275
276
277
          flip : {
            enabled : this._config.flip
          }
        }
      }

278
      // Disable Popper.js for Dropdown in Navbar
279
      if (this._inNavbar) {
280
281
        popperConfig.modifiers.applyStyle = {
          enabled: !this._inNavbar
282
283
284
285
286
        }
      }
      return popperConfig
    }

fat's avatar
fat committed
287
288
289
290
    // static

    static _jQueryInterface(config) {
      return this.each(function () {
291
        let data = $(this).data(DATA_KEY)
292
        const _config = typeof config === 'object' ? config : null
fat's avatar
fat committed
293
294

        if (!data) {
Johann-S's avatar
Johann-S committed
295
          data = new Dropdown(this, _config)
296
          $(this).data(DATA_KEY, data)
fat's avatar
fat committed
297
298
299
        }

        if (typeof config === 'string') {
XhmikosR's avatar
XhmikosR committed
300
          if (typeof data[config] === 'undefined') {
301
302
            throw new Error(`No method named "${config}"`)
          }
303
          data[config]()
fat's avatar
fat committed
304
305
306
307
308
        }
      })
    }

    static _clearMenus(event) {
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
309
310
      if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH ||
        event.type === 'keyup' && event.which !== TAB_KEYCODE)) {
fat's avatar
fat committed
311
312
313
        return
      }

314
      const toggles = $.makeArray($(Selector.DATA_TOGGLE))
fat's avatar
fat committed
315
      for (let i = 0; i < toggles.length; i++) {
316
        const parent        = Dropdown._getParentFromElement(toggles[i])
317
        const context       = $(toggles[i]).data(DATA_KEY)
318
319
320
        const relatedTarget = {
          relatedTarget : toggles[i]
        }
fat's avatar
fat committed
321

Johann-S's avatar
Johann-S committed
322
323
324
325
        if (!context) {
          continue
        }

326
        const dropdownMenu = context._menu
Starsam80's avatar
Starsam80 committed
327
        if (!$(parent).hasClass(ClassName.SHOW)) {
fat's avatar
fat committed
328
329
330
          continue
        }

331
        if (event && (event.type === 'click' &&
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
332
            /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE)
333
            && $.contains(parent, event.target)) {
fat's avatar
fat committed
334
335
336
          continue
        }

337
        const hideEvent = $.Event(Event.HIDE, relatedTarget)
fat's avatar
fat committed
338
339
340
341
342
        $(parent).trigger(hideEvent)
        if (hideEvent.isDefaultPrevented()) {
          continue
        }

343
344
345
        // if this is a touch-enabled device we remove the extra
        // empty mouseover listeners we added for iOS support
        if ('ontouchstart' in document.documentElement) {
346
          $('body').children().off('mouseover', null, $.noop)
347
348
        }

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

Johann-S's avatar
Johann-S committed
351
        $(dropdownMenu).removeClass(ClassName.SHOW)
fat's avatar
fat committed
352
        $(parent)
Starsam80's avatar
Starsam80 committed
353
          .removeClass(ClassName.SHOW)
Jacob Thornton's avatar
Jacob Thornton committed
354
          .trigger($.Event(Event.HIDDEN, relatedTarget))
fat's avatar
fat committed
355
356
357
358
359
      }
    }

    static _getParentFromElement(element) {
      let parent
360
      const selector = Util.getSelectorFromElement(element)
fat's avatar
fat committed
361
362
363
364
365
366
367
368
369

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

      return parent || element.parentNode
    }

    static _dataApiKeydownHandler(event) {
370
371
372
373
      // 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
374
      //  - If key is other than escape
375
376
377
378
379
380
      //    - If key is not up or down => not a dropdown command
      //    - If trigger inside the menu => not a dropdown command
      if (/input|textarea/i.test(event.target.tagName) ?
        event.which === SPACE_KEYCODE || event.which !== ESCAPE_KEYCODE &&
        (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
381
382
383
384
385
386
387
388
389
390
        return
      }

      event.preventDefault()
      event.stopPropagation()

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

391
      const parent   = Dropdown._getParentFromElement(this)
Starsam80's avatar
Starsam80 committed
392
      const isActive = $(parent).hasClass(ClassName.SHOW)
fat's avatar
fat committed
393

394
395
      if (!isActive && (event.which !== ESCAPE_KEYCODE || event.which !== SPACE_KEYCODE) ||
           isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) {
fat's avatar
fat committed
396

397
        if (event.which === ESCAPE_KEYCODE) {
398
          const toggle = $(parent).find(Selector.DATA_TOGGLE)[0]
fat's avatar
fat committed
399
400
401
402
403
404
405
          $(toggle).trigger('focus')
        }

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

406
      const items = $(parent).find(Selector.VISIBLE_ITEMS).get()
fat's avatar
fat committed
407
408
409
410
411
412
413

      if (!items.length) {
        return
      }

      let index = items.indexOf(event.target)

414
      if (event.which === ARROW_UP_KEYCODE && index > 0) { // up
Jacob Thornton's avatar
Jacob Thornton committed
415
416
417
        index--
      }

418
      if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) { // down
Jacob Thornton's avatar
Jacob Thornton committed
419
420
421
        index++
      }

422
      if (index < 0) {
Jacob Thornton's avatar
Jacob Thornton committed
423
424
        index = 0
      }
fat's avatar
fat committed
425
426
427
428
429
430
431
432
433
434
435
436
437
438

      items[index].focus()
    }

  }


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

  $(document)
fat's avatar
fat committed
439
    .on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE,  Dropdown._dataApiKeydownHandler)
440
    .on(Event.KEYDOWN_DATA_API, Selector.MENU, Dropdown._dataApiKeydownHandler)
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
441
    .on(`${Event.CLICK_DATA_API} ${Event.KEYUP_DATA_API}`, Dropdown._clearMenus)
442
443
444
445
446
    .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
447
448
449
    .on(Event.CLICK_DATA_API, Selector.FORM_CHILD, (e) => {
      e.stopPropagation()
    })
fat's avatar
fat committed
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466


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

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

  return Dropdown

467
})($, Popper)
fat's avatar
fat committed
468
469

export default Dropdown