dropdown.js 10.5 KB
Newer Older
1
2
/* global Popper */

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-alpha.6): dropdown.js
fat's avatar
fat committed
9
10
11
12
13
14
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * --------------------------------------------------------------------------
 */

const Dropdown = (($) => {

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

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

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

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

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

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

Johann-S's avatar
Johann-S committed
67
  const AttachmentMap = {
68
69
    TOP    : 'top-start',
    BOTTOM : 'bottom-start'
Johann-S's avatar
Johann-S committed
70
71
  }

Johann-S's avatar
Johann-S committed
72
  const Default = {
Johann-S's avatar
Johann-S committed
73
    placement   : AttachmentMap.BOTTOM,
74
    offset      : 0
Johann-S's avatar
Johann-S committed
75
76
77
  }

  const DefaultType = {
78
79
    placement   : 'string',
    offset      : '(number|string)'
Johann-S's avatar
Johann-S committed
80
81
  }

fat's avatar
fat committed
82
83
84
85
86
87
88
89
90

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

  class Dropdown {

Johann-S's avatar
Johann-S committed
91
    constructor(element, config) {
fat's avatar
fat committed
92
      this._element = element
Johann-S's avatar
Johann-S committed
93
94
95
      this._popper  = null
      this._config = this._getConfig(config)
      this._menu = this._getMenuElement()
fat's avatar
fat committed
96
97

      this._addEventListeners()
fat's avatar
fat committed
98
99
    }

100
101
102
103
104
105
106

    // getters

    static get VERSION() {
      return VERSION
    }

Johann-S's avatar
Johann-S committed
107
108
109
110
111
112
113
114
    static get Default() {
      return Default
    }

    static get DefaultType() {
      return DefaultType
    }

115

fat's avatar
fat committed
116
117
118
    // public

    toggle() {
Johann-S's avatar
Johann-S committed
119
120
121
122
123
124
125
      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
126
        return false
fat's avatar
fat committed
127
128
      }

129
      const parent   = Dropdown._getParentFromElement(this)
Johann-S's avatar
Johann-S committed
130
      const isActive = $(context._menu).hasClass(ClassName.SHOW)
fat's avatar
fat committed
131
132
133
134
135
136
137

      Dropdown._clearMenus()

      if (isActive) {
        return false
      }

138
139
140
      const relatedTarget = {
        relatedTarget : this
      }
Johann-S's avatar
Johann-S committed
141
      const showEvent = $.Event(Event.SHOW, relatedTarget)
fat's avatar
fat committed
142
143
144
145

      $(parent).trigger(showEvent)

      if (showEvent.isDefaultPrevented()) {
Jacob Thornton's avatar
Jacob Thornton committed
146
        return false
fat's avatar
fat committed
147
148
      }

Johann-S's avatar
Johann-S committed
149
150
      // Handle dropup
      const dropdownPlacement = $(this).parent().hasClass('dropup') ? AttachmentMap.TOP : context._config.placement
Johann-S's avatar
Johann-S committed
151
      this._popper = new Popper(this, context._menu, {
Johann-S's avatar
Johann-S committed
152
        placement : dropdownPlacement,
153
154
        modifiers : {
          offset : {
155
            offset : context._config.offset
156
          }
Johann-S's avatar
Johann-S committed
157
158
159
        }
      })

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

fat's avatar
fat committed
169
      this.focus()
170
      this.setAttribute('aria-expanded', true)
fat's avatar
fat committed
171

Johann-S's avatar
Johann-S committed
172
173
174
175
      $(context._menu).toggleClass(ClassName.SHOW)
      $(parent)
        .toggleClass(ClassName.SHOW)
        .trigger($.Event(Event.SHOWN, relatedTarget))
fat's avatar
fat committed
176
177
178
179

      return false
    }

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


    // private

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

Johann-S's avatar
Johann-S committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    _getConfig(config) {
      config = $.extend(
        {},
        this.constructor.Default,
        $(this._element).data(),
        config
      )

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

      return config
    }

    _getMenuElement() {
      if (!this._menu) {
216
        const parent = Dropdown._getParentFromElement(this._element)
Johann-S's avatar
Johann-S committed
217
218
219
220
        this._menu = $(parent).find(Selector.MENU)[0]
      }
      return this._menu
    }
fat's avatar
fat committed
221
222
223
224
225

    // static

    static _jQueryInterface(config) {
      return this.each(function () {
226
        let data = $(this).data(DATA_KEY)
227
        const _config = typeof config === 'object' ? config : null
fat's avatar
fat committed
228
229

        if (!data) {
Johann-S's avatar
Johann-S committed
230
          data = new Dropdown(this, _config)
231
          $(this).data(DATA_KEY, data)
fat's avatar
fat committed
232
233
234
        }

        if (typeof config === 'string') {
235
236
237
          if (data[config] === undefined) {
            throw new Error(`No method named "${config}"`)
          }
fat's avatar
fat committed
238
239
240
241
242
243
          data[config].call(this)
        }
      })
    }

    static _clearMenus(event) {
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
244
245
      if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH ||
        event.type === 'keyup' && event.which !== TAB_KEYCODE)) {
fat's avatar
fat committed
246
247
248
        return
      }

249
      const toggles = $.makeArray($(Selector.DATA_TOGGLE))
fat's avatar
fat committed
250
      for (let i = 0; i < toggles.length; i++) {
251
        const parent        = Dropdown._getParentFromElement(toggles[i])
252
        const context         = $(toggles[i]).data(DATA_KEY)
253
254
255
        const relatedTarget = {
          relatedTarget : toggles[i]
        }
fat's avatar
fat committed
256

Johann-S's avatar
Johann-S committed
257
258
259
260
        if (!context) {
          continue
        }

261
        const dropdownMenu = context._menu
Starsam80's avatar
Starsam80 committed
262
        if (!$(parent).hasClass(ClassName.SHOW)) {
fat's avatar
fat committed
263
264
265
          continue
        }

266
        if (event && (event.type === 'click' &&
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
267
            /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE)
268
            && $.contains(parent, event.target)) {
fat's avatar
fat committed
269
270
271
          continue
        }

272
        const hideEvent = $.Event(Event.HIDE, relatedTarget)
fat's avatar
fat committed
273
274
275
276
277
        $(parent).trigger(hideEvent)
        if (hideEvent.isDefaultPrevented()) {
          continue
        }

278
279
280
        // if this is a touch-enabled device we remove the extra
        // empty mouseover listeners we added for iOS support
        if ('ontouchstart' in document.documentElement) {
281
          $('body').children().off('mouseover', null, $.noop)
282
283
        }

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

Johann-S's avatar
Johann-S committed
286
        $(dropdownMenu).removeClass(ClassName.SHOW)
fat's avatar
fat committed
287
        $(parent)
Starsam80's avatar
Starsam80 committed
288
          .removeClass(ClassName.SHOW)
Jacob Thornton's avatar
Jacob Thornton committed
289
          .trigger($.Event(Event.HIDDEN, relatedTarget))
fat's avatar
fat committed
290
291
292
293
294
      }
    }

    static _getParentFromElement(element) {
      let parent
295
      const selector = Util.getSelectorFromElement(element)
fat's avatar
fat committed
296
297
298
299
300
301
302
303
304

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

      return parent || element.parentNode
    }

    static _dataApiKeydownHandler(event) {
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
305
      if (!REGEXP_KEYDOWN.test(event.which) || /button/i.test(event.target.tagName) && event.which === SPACE_KEYCODE ||
fat's avatar
fat committed
306
307
308
309
310
311
312
313
314
315
316
         /input|textarea/i.test(event.target.tagName)) {
        return
      }

      event.preventDefault()
      event.stopPropagation()

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

317
      const parent   = Dropdown._getParentFromElement(this)
Starsam80's avatar
Starsam80 committed
318
      const isActive = $(parent).hasClass(ClassName.SHOW)
fat's avatar
fat committed
319

320
321
      if (!isActive && (event.which !== ESCAPE_KEYCODE || event.which !== SPACE_KEYCODE) ||
           isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) {
fat's avatar
fat committed
322

323
        if (event.which === ESCAPE_KEYCODE) {
324
          const toggle = $(parent).find(Selector.DATA_TOGGLE)[0]
fat's avatar
fat committed
325
326
327
328
329
330
331
          $(toggle).trigger('focus')
        }

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

332
      const items = $(parent).find(Selector.VISIBLE_ITEMS).get()
fat's avatar
fat committed
333
334
335
336
337
338
339

      if (!items.length) {
        return
      }

      let index = items.indexOf(event.target)

340
      if (event.which === ARROW_UP_KEYCODE && index > 0) { // up
Jacob Thornton's avatar
Jacob Thornton committed
341
342
343
        index--
      }

344
      if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) { // down
Jacob Thornton's avatar
Jacob Thornton committed
345
346
347
        index++
      }

348
      if (index < 0) {
Jacob Thornton's avatar
Jacob Thornton committed
349
350
        index = 0
      }
fat's avatar
fat committed
351
352
353
354
355
356
357
358
359
360
361
362
363
364

      items[index].focus()
    }

  }


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

  $(document)
fat's avatar
fat committed
365
    .on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE,  Dropdown._dataApiKeydownHandler)
366
    .on(Event.KEYDOWN_DATA_API, Selector.MENU, Dropdown._dataApiKeydownHandler)
Pierre-Denis Vanduynslager's avatar
Pierre-Denis Vanduynslager committed
367
    .on(`${Event.CLICK_DATA_API} ${Event.KEYUP_DATA_API}`, Dropdown._clearMenus)
fat's avatar
fat committed
368
    .on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, Dropdown.prototype.toggle)
Jacob Thornton's avatar
Jacob Thornton committed
369
370
371
    .on(Event.CLICK_DATA_API, Selector.FORM_CHILD, (e) => {
      e.stopPropagation()
    })
fat's avatar
fat committed
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391


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