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

twbs / bootstrap / 15237821870

25 May 2025 12:23PM CUT coverage: 96.07%. Remained the same
15237821870

push

github

julien-deramond
Fix lint warnings in `site/src/libs/path.ts`

666 of 726 branches covered (91.74%)

Branch coverage included in aggregate %.

2023 of 2073 relevant lines covered (97.59%)

187.58 hits per line

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

93.41
/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)) {
58✔
147
        EventHandler.on(element, 'mouseover', noop)
2,030✔
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
    // Explicitly return focus to the trigger element
212
    this._element.focus()
26✔
213
  }
214

215
  _getConfig(config) {
216
    config = super._getConfig(config)
90✔
217

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

225
    return config
88✔
226
  }
227

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

233
    let referenceElement = this._element
58✔
234

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

243
    const popperConfig = this._getPopperConfig()
58✔
244
    this._popper = Popper.createPopper(referenceElement, this._menu, popperConfig)
58✔
245
  }
246

247
  _isShown() {
248
    return this._menu.classList.contains(CLASS_NAME_SHOW)
137✔
249
  }
250

251
  _getPlacement() {
252
    const parentDropdown = this._parent
60✔
253

254
    if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) {
60✔
255
      return PLACEMENT_RIGHT
1✔
256
    }
257

258
    if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) {
59✔
259
      return PLACEMENT_LEFT
1✔
260
    }
261

262
    if (parentDropdown.classList.contains(CLASS_NAME_DROPUP_CENTER)) {
58✔
263
      return PLACEMENT_TOPCENTER
1✔
264
    }
265

266
    if (parentDropdown.classList.contains(CLASS_NAME_DROPDOWN_CENTER)) {
57✔
267
      return PLACEMENT_BOTTOMCENTER
1✔
268
    }
269

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

273
    if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) {
56✔
274
      return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP
2!
275
    }
276

277
    return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM
54!
278
  }
279

280
  _detectNavbar() {
281
    return this._element.closest(SELECTOR_NAVBAR) !== null
88✔
282
  }
283

284
  _getOffset() {
285
    const { offset } = this._config
62✔
286

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

291
    if (typeof offset === 'function') {
61✔
292
      return popperData => offset(popperData, this._element)
15✔
293
    }
294

295
    return offset
59✔
296
  }
297

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

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

324
    return {
60✔
325
      ...defaultBsPopperConfig,
326
      ...execute(this._config.popperConfig, [undefined, defaultBsPopperConfig])
327
    }
328
  }
329

330
  _selectMenuItem({ key, target }) {
331
    const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(element => isVisible(element))
18✔
332

333
    if (!items.length) {
10!
334
      return
×
335
    }
336

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

342
  // Static
343
  static jQueryInterface(config) {
344
    return this.each(function () {
3✔
345
      const data = Dropdown.getOrCreateInstance(this, config)
3✔
346

347
      if (typeof config !== 'string') {
3✔
348
        return
2✔
349
      }
350

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

355
      data[config]()
×
356
    })
357
  }
358

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

364
    const openToggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE_SHOWN)
147✔
365

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

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

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

387
      const relatedTarget = { relatedTarget: context._element }
14✔
388

389
      if (event.type === 'click') {
14✔
390
        relatedTarget.clickEvent = event
11✔
391
      }
392

393
      context._completeHide(relatedTarget)
14✔
394
    }
395
  }
396

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

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

405
    if (!isUpOrDownEvent && !isEscapeEvent) {
23✔
406
      return
2✔
407
    }
408

409
    if (isInput && !isEscapeEvent) {
21✔
410
      return
6✔
411
    }
412

413
    event.preventDefault()
15✔
414

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

422
    const instance = Dropdown.getOrCreateInstance(getToggleButton)
15✔
423

424
    if (isUpOrDownEvent) {
15✔
425
      event.stopPropagation()
10✔
426
      instance.show()
10✔
427
      instance._selectMenuItem(event)
10✔
428
      return
10✔
429
    }
430

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

439
/**
440
 * Data API implementation
441
 */
442

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

452
/**
453
 * jQuery
454
 */
455

456
defineJQueryPlugin(Dropdown)
1✔
457

458
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