• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

twbs / bootstrap / 9856469587

09 Jul 2024 11:49AM CUT coverage: 96.07%. Remained the same
9856469587

Pull #40619

github

web-flow
Merge ac79a1794 into 7c392498f
Pull Request #40619: Docs: Fix a minor accessibility issue (checkout example missing h1)

666 of 726 branches covered (91.74%)

Branch coverage included in aggregate %.

2023 of 2073 relevant lines covered (97.59%)

249.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.38
/js/src/dropdown.js
1
/**
2
 * --------------------------------------------------------------------------
3
 * Bootstrap dropdown.js
4
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
5
 * --------------------------------------------------------------------------
6
 */
7

8
import * as Popper from '@popperjs/core'
9
import BaseComponent from './base-component.js'
10
import EventHandler from './dom/event-handler.js'
11
import Manipulator from './dom/manipulator.js'
12
import SelectorEngine from './dom/selector-engine.js'
13
import {
14
  defineJQueryPlugin,
15
  execute,
16
  getElement,
17
  getNextActiveElement,
18
  isDisabled,
19
  isElement,
20
  isRTL,
21
  isVisible,
22
  noop
23
} from './util/index.js'
24

25
/**
26
 * Constants
27
 */
28

29
const NAME = 'dropdown'
1✔
30
const DATA_KEY = 'bs.dropdown'
1✔
31
const EVENT_KEY = `.${DATA_KEY}`
1✔
32
const DATA_API_KEY = '.data-api'
1✔
33

34
const ESCAPE_KEY = 'Escape'
1✔
35
const TAB_KEY = 'Tab'
1✔
36
const ARROW_UP_KEY = 'ArrowUp'
1✔
37
const ARROW_DOWN_KEY = 'ArrowDown'
1✔
38
const RIGHT_MOUSE_BUTTON = 2 // MouseEvent.button value for the secondary button, usually the right button
1✔
39

40
const EVENT_HIDE = `hide${EVENT_KEY}`
1✔
41
const EVENT_HIDDEN = `hidden${EVENT_KEY}`
1✔
42
const EVENT_SHOW = `show${EVENT_KEY}`
1✔
43
const EVENT_SHOWN = `shown${EVENT_KEY}`
1✔
44
const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`
1✔
45
const EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY}${DATA_API_KEY}`
1✔
46
const EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY}${DATA_API_KEY}`
1✔
47

48
const CLASS_NAME_SHOW = 'show'
1✔
49
const CLASS_NAME_DROPUP = 'dropup'
1✔
50
const CLASS_NAME_DROPEND = 'dropend'
1✔
51
const CLASS_NAME_DROPSTART = 'dropstart'
1✔
52
const CLASS_NAME_DROPUP_CENTER = 'dropup-center'
1✔
53
const CLASS_NAME_DROPDOWN_CENTER = 'dropdown-center'
1✔
54

55
const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="dropdown"]:not(.disabled):not(:disabled)'
1✔
56
const SELECTOR_DATA_TOGGLE_SHOWN = `${SELECTOR_DATA_TOGGLE}.${CLASS_NAME_SHOW}`
1✔
57
const SELECTOR_MENU = '.dropdown-menu'
1✔
58
const SELECTOR_NAVBAR = '.navbar'
1✔
59
const SELECTOR_NAVBAR_NAV = '.navbar-nav'
1✔
60
const SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)'
1✔
61

62
const PLACEMENT_TOP = isRTL() ? 'top-end' : 'top-start'
1!
63
const PLACEMENT_TOPEND = isRTL() ? 'top-start' : 'top-end'
1!
64
const PLACEMENT_BOTTOM = isRTL() ? 'bottom-end' : 'bottom-start'
1!
65
const PLACEMENT_BOTTOMEND = isRTL() ? 'bottom-start' : 'bottom-end'
1!
66
const PLACEMENT_RIGHT = isRTL() ? 'left-start' : 'right-start'
1!
67
const PLACEMENT_LEFT = isRTL() ? 'right-start' : 'left-start'
1!
68
const PLACEMENT_TOPCENTER = 'top'
1✔
69
const PLACEMENT_BOTTOMCENTER = 'bottom'
1✔
70

71
const Default = {
1✔
72
  autoClose: true,
73
  boundary: 'clippingParents',
74
  display: 'dynamic',
75
  offset: [0, 2],
76
  popperConfig: null,
77
  reference: 'toggle'
78
}
79

80
const DefaultType = {
1✔
81
  autoClose: '(boolean|string)',
82
  boundary: '(string|element)',
83
  display: 'string',
84
  offset: '(array|string|function)',
85
  popperConfig: '(null|object|function)',
86
  reference: '(string|element|object)'
87
}
88

89
/**
90
 * Class definition
91
 */
92

93
class Dropdown extends BaseComponent {
94
  constructor(element, config) {
95
    super(element, config)
90✔
96

97
    this._popper = null
88✔
98
    this._parent = this._element.parentNode // dropdown wrapper
88✔
99
    // TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/
100
    this._menu = SelectorEngine.next(this._element, SELECTOR_MENU)[0] ||
88✔
101
      SelectorEngine.prev(this._element, SELECTOR_MENU)[0] ||
102
      SelectorEngine.findOne(SELECTOR_MENU, this._parent)
103
    this._inNavbar = this._detectNavbar()
88✔
104
  }
105

106
  // Getters
107
  static get Default() {
108
    return Default
91✔
109
  }
110

111
  static get DefaultType() {
112
    return DefaultType
91✔
113
  }
114

115
  static get NAME() {
116
    return NAME
197✔
117
  }
118

119
  // Public
120
  toggle() {
121
    return this._isShown() ? this.hide() : this.show()
50✔
122
  }
123

124
  show() {
125
    if (isDisabled(this._element) || this._isShown()) {
72✔
126
      return
12✔
127
    }
128

129
    const relatedTarget = {
60✔
130
      relatedTarget: this._element
131
    }
132

133
    const showEvent = EventHandler.trigger(this._element, EVENT_SHOW, relatedTarget)
60✔
134

135
    if (showEvent.defaultPrevented) {
60✔
136
      return
2✔
137
    }
138

139
    this._createPopper()
58✔
140

141
    // If this is a touch-enabled device we add extra
142
    // empty mouseover listeners to the body's immediate children;
143
    // only needed because of broken event delegation on iOS
144
    // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
145
    if ('ontouchstart' in document.documentElement && !this._parent.closest(SELECTOR_NAVBAR_NAV)) {
58✔
146
      for (const element of [].concat(...document.body.children)) {
55✔
147
        EventHandler.on(element, 'mouseover', noop)
1,925✔
148
      }
149
    }
150

151
    this._element.focus()
58✔
152
    this._element.setAttribute('aria-expanded', true)
58✔
153

154
    this._menu.classList.add(CLASS_NAME_SHOW)
58✔
155
    this._element.classList.add(CLASS_NAME_SHOW)
58✔
156
    EventHandler.trigger(this._element, EVENT_SHOWN, relatedTarget)
58✔
157
  }
158

159
  hide() {
160
    if (isDisabled(this._element) || !this._isShown()) {
16✔
161
      return
3✔
162
    }
163

164
    const relatedTarget = {
13✔
165
      relatedTarget: this._element
166
    }
167

168
    this._completeHide(relatedTarget)
13✔
169
  }
170

171
  dispose() {
172
    if (this._popper) {
2✔
173
      this._popper.destroy()
1✔
174
    }
175

176
    super.dispose()
2✔
177
  }
178

179
  update() {
180
    this._inNavbar = this._detectNavbar()
2✔
181
    if (this._popper) {
2✔
182
      this._popper.update()
1✔
183
    }
184
  }
185

186
  // Private
187
  _completeHide(relatedTarget) {
188
    const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE, relatedTarget)
27✔
189
    if (hideEvent.defaultPrevented) {
27✔
190
      return
1✔
191
    }
192

193
    // If this is a touch-enabled device we remove the extra
194
    // empty mouseover listeners we added for iOS support
195
    if ('ontouchstart' in document.documentElement) {
26✔
196
      for (const element of [].concat(...document.body.children)) {
26✔
197
        EventHandler.off(element, 'mouseover', noop)
910✔
198
      }
199
    }
200

201
    if (this._popper) {
26✔
202
      this._popper.destroy()
24✔
203
    }
204

205
    this._menu.classList.remove(CLASS_NAME_SHOW)
26✔
206
    this._element.classList.remove(CLASS_NAME_SHOW)
26✔
207
    this._element.setAttribute('aria-expanded', 'false')
26✔
208
    Manipulator.removeDataAttribute(this._menu, 'popper')
26✔
209
    EventHandler.trigger(this._element, EVENT_HIDDEN, relatedTarget)
26✔
210
  }
211

212
  _getConfig(config) {
213
    config = super._getConfig(config)
90✔
214

215
    if (typeof config.reference === 'object' && !isElement(config.reference) &&
90✔
216
      typeof config.reference.getBoundingClientRect !== 'function'
217
    ) {
218
      // Popper virtual elements require a getBoundingClientRect method
219
      throw new TypeError(`${NAME.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`)
2✔
220
    }
221

222
    return config
88✔
223
  }
224

225
  _createPopper() {
226
    if (typeof Popper === 'undefined') {
58!
227
      throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org/docs/v2/)')
×
228
    }
229

230
    let referenceElement = this._element
58✔
231

232
    if (this._config.reference === 'parent') {
58✔
233
      referenceElement = this._parent
1✔
234
    } else if (isElement(this._config.reference)) {
57✔
235
      referenceElement = getElement(this._config.reference)
3✔
236
    } else if (typeof this._config.reference === 'object') {
54!
237
      referenceElement = this._config.reference
×
238
    }
239

240
    const popperConfig = this._getPopperConfig()
58✔
241
    this._popper = Popper.createPopper(referenceElement, this._menu, popperConfig)
58✔
242
  }
243

244
  _isShown() {
245
    return this._menu.classList.contains(CLASS_NAME_SHOW)
137✔
246
  }
247

248
  _getPlacement() {
249
    const parentDropdown = this._parent
60✔
250

251
    if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) {
60✔
252
      return PLACEMENT_RIGHT
1✔
253
    }
254

255
    if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) {
59✔
256
      return PLACEMENT_LEFT
1✔
257
    }
258

259
    if (parentDropdown.classList.contains(CLASS_NAME_DROPUP_CENTER)) {
58✔
260
      return PLACEMENT_TOPCENTER
1✔
261
    }
262

263
    if (parentDropdown.classList.contains(CLASS_NAME_DROPDOWN_CENTER)) {
57✔
264
      return PLACEMENT_BOTTOMCENTER
1✔
265
    }
266

267
    // We need to trim the value because custom properties can also include spaces
268
    const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end'
56✔
269

270
    if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) {
56✔
271
      return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP
2!
272
    }
273

274
    return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM
54!
275
  }
276

277
  _detectNavbar() {
278
    return this._element.closest(SELECTOR_NAVBAR) !== null
88✔
279
  }
280

281
  _getOffset() {
282
    const { offset } = this._config
62✔
283

284
    if (typeof offset === 'string') {
62✔
285
      return offset.split(',').map(value => Number.parseInt(value, 10))
2✔
286
    }
287

288
    if (typeof offset === 'function') {
61✔
289
      return popperData => offset(popperData, this._element)
45✔
290
    }
291

292
    return offset
59✔
293
  }
294

295
  _getPopperConfig() {
296
    const defaultBsPopperConfig = {
60✔
297
      placement: this._getPlacement(),
298
      modifiers: [{
299
        name: 'preventOverflow',
300
        options: {
301
          boundary: this._config.boundary
302
        }
303
      },
304
      {
305
        name: 'offset',
306
        options: {
307
          offset: this._getOffset()
308
        }
309
      }]
310
    }
311

312
    // Disable Popper if we have a static display or Dropdown is in Navbar
313
    if (this._inNavbar || this._config.display === 'static') {
60✔
314
      Manipulator.setDataAttribute(this._menu, 'popper', 'static') // TODO: v6 remove
4✔
315
      defaultBsPopperConfig.modifiers = [{
4✔
316
        name: 'applyStyles',
317
        enabled: false
318
      }]
319
    }
320

321
    return {
60✔
322
      ...defaultBsPopperConfig,
323
      ...execute(this._config.popperConfig, [defaultBsPopperConfig])
324
    }
325
  }
326

327
  _selectMenuItem({ key, target }) {
328
    const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(element => isVisible(element))
18✔
329

330
    if (!items.length) {
10!
331
      return
×
332
    }
333

334
    // if target isn't included in items (e.g. when expanding the dropdown)
335
    // allow cycling to get the last item in case key equals ARROW_UP_KEY
336
    getNextActiveElement(items, target, key === ARROW_DOWN_KEY, !items.includes(target)).focus()
10✔
337
  }
338

339
  // Static
340
  static jQueryInterface(config) {
341
    return this.each(function () {
3✔
342
      const data = Dropdown.getOrCreateInstance(this, config)
3✔
343

344
      if (typeof config !== 'string') {
3✔
345
        return
2✔
346
      }
347

348
      if (typeof data[config] === 'undefined') {
1✔
349
        throw new TypeError(`No method named "${config}"`)
1✔
350
      }
351

352
      data[config]()
×
353
    })
354
  }
355

356
  static clearMenus(event) {
357
    if (event.button === RIGHT_MOUSE_BUTTON || (event.type === 'keyup' && event.key !== TAB_KEY)) {
149✔
358
      return
2✔
359
    }
360

361
    const openToggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE_SHOWN)
147✔
362

363
    for (const toggle of openToggles) {
147✔
364
      const context = Dropdown.getInstance(toggle)
41✔
365
      if (!context || context._config.autoClose === false) {
41✔
366
        continue
3✔
367
      }
368

369
      const composedPath = event.composedPath()
38✔
370
      const isMenuTarget = composedPath.includes(context._menu)
38✔
371
      if (
38✔
372
        composedPath.includes(context._element) ||
77✔
373
        (context._config.autoClose === 'inside' && !isMenuTarget) ||
374
        (context._config.autoClose === 'outside' && isMenuTarget)
375
      ) {
376
        continue
22✔
377
      }
378

379
      // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu
380
      if (context._menu.contains(event.target) && ((event.type === 'keyup' && event.key === TAB_KEY) || /input|select|option|textarea|form/i.test(event.target.tagName))) {
16!
381
        continue
2✔
382
      }
383

384
      const relatedTarget = { relatedTarget: context._element }
14✔
385

386
      if (event.type === 'click') {
14✔
387
        relatedTarget.clickEvent = event
11✔
388
      }
389

390
      context._completeHide(relatedTarget)
14✔
391
    }
392
  }
393

394
  static dataApiKeydownHandler(event) {
395
    // If not an UP | DOWN | ESCAPE key => not a dropdown command
396
    // If input/textarea && if key is other than ESCAPE => not a dropdown command
397

398
    const isInput = /input|textarea/i.test(event.target.tagName)
23✔
399
    const isEscapeEvent = event.key === ESCAPE_KEY
23✔
400
    const isUpOrDownEvent = [ARROW_UP_KEY, ARROW_DOWN_KEY].includes(event.key)
23✔
401

402
    if (!isUpOrDownEvent && !isEscapeEvent) {
23✔
403
      return
2✔
404
    }
405

406
    if (isInput && !isEscapeEvent) {
21✔
407
      return
6✔
408
    }
409

410
    event.preventDefault()
15✔
411

412
    // TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/
413
    const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE) ?
15✔
414
      this :
15✔
415
      (SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE)[0] ||
3!
416
        SelectorEngine.next(this, SELECTOR_DATA_TOGGLE)[0] ||
417
        SelectorEngine.findOne(SELECTOR_DATA_TOGGLE, event.delegateTarget.parentNode))
418

419
    const instance = Dropdown.getOrCreateInstance(getToggleButton)
15✔
420

421
    if (isUpOrDownEvent) {
15✔
422
      event.stopPropagation()
10✔
423
      instance.show()
10✔
424
      instance._selectMenuItem(event)
10✔
425
      return
10✔
426
    }
427

428
    if (instance._isShown()) { // else is escape and we check if it is shown
5✔
429
      event.stopPropagation()
4✔
430
      instance.hide()
4✔
431
      getToggleButton.focus()
4✔
432
    }
433
  }
434
}
435

436
/**
437
 * Data API implementation
438
 */
439

440
EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE, Dropdown.dataApiKeydownHandler)
1✔
441
EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown.dataApiKeydownHandler)
1✔
442
EventHandler.on(document, EVENT_CLICK_DATA_API, Dropdown.clearMenus)
1✔
443
EventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown.clearMenus)
1✔
444
EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {
1✔
445
  event.preventDefault()
29✔
446
  Dropdown.getOrCreateInstance(this).toggle()
29✔
447
})
448

449
/**
450
 * jQuery
451
 */
452

453
defineJQueryPlugin(Dropdown)
1✔
454

455
export default Dropdown
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc