twbs--bootstrap/js/src/dropdown.js

495 lines
14 KiB
JavaScript
Raw Normal View History

import $ from 'jquery'
import Popper from 'popper.js'
2015-05-10 20:47:11 +00:00
import Util from './util'
/**
* --------------------------------------------------------------------------
2018-07-24 02:25:52 +00:00
* Bootstrap (v4.1.3): dropdown.js
2015-05-10 20:47:11 +00:00
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
const Dropdown = (($) => {
2015-05-10 20:47:11 +00:00
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
const NAME = 'dropdown'
2018-07-24 02:25:52 +00:00
const VERSION = '4.1.3'
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
const SPACE_KEYCODE = 32 // KeyboardEvent.which value for space key
2017-02-08 23:51:50 +00:00
const TAB_KEYCODE = 9 // KeyboardEvent.which value for tab key
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)
2017-04-12 13:41:27 +00:00
const REGEXP_KEYDOWN = new RegExp(`${ARROW_UP_KEYCODE}|${ARROW_DOWN_KEYCODE}|${ESCAPE_KEYCODE}`)
2015-05-10 20:47:11 +00:00
const Event = {
2015-11-12 19:21:32 +00:00
HIDE : `hide${EVENT_KEY}`,
HIDDEN : `hidden${EVENT_KEY}`,
SHOW : `show${EVENT_KEY}`,
SHOWN : `shown${EVENT_KEY}`,
CLICK : `click${EVENT_KEY}`,
2015-05-13 19:48:34 +00:00
CLICK_DATA_API : `click${EVENT_KEY}${DATA_API_KEY}`,
2017-02-08 23:51:50 +00:00
KEYDOWN_DATA_API : `keydown${EVENT_KEY}${DATA_API_KEY}`,
KEYUP_DATA_API : `keyup${EVENT_KEY}${DATA_API_KEY}`
2015-05-10 20:47:11 +00:00
}
const ClassName = {
DISABLED : 'disabled',
SHOW : 'show',
DROPUP : 'dropup',
DROPRIGHT : 'dropright',
DROPLEFT : 'dropleft',
MENURIGHT : 'dropdown-menu-right',
MENULEFT : 'dropdown-menu-left',
POSITION_STATIC : 'position-static'
2015-05-10 20:47:11 +00:00
}
const Selector = {
DATA_TOGGLE : '[data-toggle="dropdown"]',
FORM_CHILD : '.dropdown form',
MENU : '.dropdown-menu',
2015-05-10 20:47:11 +00:00
NAVBAR_NAV : '.navbar-nav',
VISIBLE_ITEMS : '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)'
2015-05-10 20:47:11 +00:00
}
2017-04-17 12:26:40 +00:00
const AttachmentMap = {
TOP : 'top-start',
TOPEND : 'top-end',
BOTTOM : 'bottom-start',
BOTTOMEND : 'bottom-end',
RIGHT : 'right-start',
RIGHTEND : 'right-end',
LEFT : 'left-start',
LEFTEND : 'left-end'
2017-04-17 12:26:40 +00:00
}
2017-04-14 09:25:53 +00:00
const Default = {
offset : 0,
flip : true,
boundary : 'scrollParent',
reference : 'toggle',
display : 'dynamic'
2017-04-14 09:25:53 +00:00
}
const DefaultType = {
offset : '(number|string|function)',
flip : 'boolean',
boundary : '(string|element)',
reference : '(string|element)',
display : 'string'
2017-04-14 09:25:53 +00:00
}
2015-05-10 20:47:11 +00:00
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
class Dropdown {
2017-04-14 09:25:53 +00:00
constructor(element, config) {
this._element = element
this._popper = null
this._config = this._getConfig(config)
this._menu = this._getMenuElement()
this._inNavbar = this._detectNavbar()
2015-05-13 19:48:34 +00:00
this._addEventListeners()
2015-05-10 20:47:11 +00:00
}
2017-12-16 12:00:38 +00:00
// Getters
static get VERSION() {
return VERSION
}
2017-04-14 09:25:53 +00:00
static get Default() {
return Default
}
static get DefaultType() {
return DefaultType
}
2017-12-16 12:00:38 +00:00
// Public
2015-05-10 20:47:11 +00:00
toggle() {
if (this._element.disabled || $(this._element).hasClass(ClassName.DISABLED)) {
return
2015-05-10 20:47:11 +00:00
}
const parent = Dropdown._getParentFromElement(this._element)
const isActive = $(this._menu).hasClass(ClassName.SHOW)
2015-05-10 20:47:11 +00:00
Dropdown._clearMenus()
if (isActive) {
return
2015-05-10 20:47:11 +00:00
}
const relatedTarget = {
2017-12-16 12:00:38 +00:00
relatedTarget: this._element
}
2017-04-14 09:25:53 +00:00
const showEvent = $.Event(Event.SHOW, relatedTarget)
2015-05-10 20:47:11 +00:00
$(parent).trigger(showEvent)
if (showEvent.isDefaultPrevented()) {
return
2015-05-10 20:47:11 +00:00
}
// Disable totally Popper.js for Dropdown in Navbar
if (!this._inNavbar) {
/**
* Check for Popper dependency
* Popper - https://popper.js.org
*/
if (typeof Popper === 'undefined') {
2017-12-16 12:00:38 +00:00
throw new TypeError('Bootstrap dropdown require Popper.js (https://popper.js.org)')
}
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]
}
}
// 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)
}
this._popper = new Popper(referenceElement, this._menu, this._getPopperConfig())
}
2017-12-16 12:00:38 +00:00
// If this is a touch-enabled device we add extra
Replace dropdown backdrop hack with cleaner JS-only hack * Replace backdrop with simple noop mouse listener As discussed in https://github.com/twbs/bootstrap/pull/22422 the current approach of injecting a backdrop (to work around iOS' broken event delegation for the `click` event) has annoying consequences on touch-enabled laptop/desktop devices. Instead of a backdrop `<div>`, here we simply add extra empty/noop mouse listeners to the immediate children of `<body>` (and remove them when the dropdown is closed) in order to force iOS to properly bubble a `click` resulting from a tap (essentially, method 2 from https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html) This is sufficient (except in rare cases where the user does manage to tap on the body itself, rather than any child elements of body - which is not very likely in an iOS phone/tablet scenario for most layouts) to get iOS to get a grip and do the correct event bubbling/delegation, meaning the regular "click" event will bubble back to the `<body>` when tapping outside of the dropdown, and the dropdown will close properly (just like it already does, even without this fix, in non-iOS touchscreen devices/browsers, like Chrome/Android and Windows on a touch laptop). This approach, though a bit hacky, has no impact on the DOM structure, and has no unforeseen side effects on touch-enabled laptops/desktops. And crucially, it works just fine in iOS. * Remove dropdown backdrop styles * Update doc for dropdowns and touch-enabled devices
2017-04-14 08:19:00 +00:00
// 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
if ('ontouchstart' in document.documentElement &&
2017-12-16 12:00:38 +00:00
$(parent).closest(Selector.NAVBAR_NAV).length === 0) {
$(document.body).children().on('mouseover', null, $.noop)
}
this._element.focus()
this._element.setAttribute('aria-expanded', true)
2015-05-10 20:47:11 +00:00
$(this._menu).toggleClass(ClassName.SHOW)
2017-04-14 09:25:53 +00:00
$(parent)
.toggleClass(ClassName.SHOW)
.trigger($.Event(Event.SHOWN, relatedTarget))
2015-05-10 20:47:11 +00:00
}
2015-05-13 19:48:34 +00:00
dispose() {
$.removeData(this._element, DATA_KEY)
$(this._element).off(EVENT_KEY)
this._element = null
2017-04-14 09:25:53 +00:00
this._menu = null
if (this._popper !== null) {
this._popper.destroy()
this._popper = null
2017-04-14 09:25:53 +00:00
}
2015-05-13 19:48:34 +00:00
}
update() {
this._inNavbar = this._detectNavbar()
if (this._popper !== null) {
this._popper.scheduleUpdate()
}
}
2015-05-13 19:48:34 +00:00
2017-12-16 12:00:38 +00:00
// Private
2015-05-13 19:48:34 +00:00
_addEventListeners() {
$(this._element).on(Event.CLICK, (event) => {
event.preventDefault()
event.stopPropagation()
this.toggle()
})
2015-05-13 19:48:34 +00:00
}
2017-04-14 09:25:53 +00:00
_getConfig(config) {
config = {
...this.constructor.Default,
...$(this._element).data(),
...config
}
2017-04-14 09:25:53 +00:00
Util.typeCheckConfig(
NAME,
config,
this.constructor.DefaultType
)
return config
}
_getMenuElement() {
if (!this._menu) {
const parent = Dropdown._getParentFromElement(this._element)
if (parent) {
this._menu = parent.querySelector(Selector.MENU)
}
2017-04-14 09:25:53 +00:00
}
return this._menu
}
2015-05-10 20:47:11 +00:00
_getPlacement() {
const $parentDropdown = $(this._element.parentNode)
2017-12-16 12:00:38 +00:00
let placement = AttachmentMap.BOTTOM
// Handle dropup
if ($parentDropdown.hasClass(ClassName.DROPUP)) {
placement = AttachmentMap.TOP
if ($(this._menu).hasClass(ClassName.MENURIGHT)) {
placement = AttachmentMap.TOPEND
}
} else if ($parentDropdown.hasClass(ClassName.DROPRIGHT)) {
placement = AttachmentMap.RIGHT
} else if ($parentDropdown.hasClass(ClassName.DROPLEFT)) {
placement = AttachmentMap.LEFT
2017-06-16 08:51:22 +00:00
} else if ($(this._menu).hasClass(ClassName.MENURIGHT)) {
placement = AttachmentMap.BOTTOMEND
}
return placement
}
_detectNavbar() {
return $(this._element).closest('.navbar').length > 0
}
_getPopperConfig() {
const offsetConf = {}
if (typeof this._config.offset === 'function') {
offsetConf.fn = (data) => {
data.offsets = {
...data.offsets,
...this._config.offset(data.offsets) || {}
}
return data
}
} else {
offsetConf.offset = this._config.offset
}
const popperConfig = {
2017-12-16 12:00:38 +00:00
placement: this._getPlacement(),
modifiers: {
offset: offsetConf,
flip: {
enabled: this._config.flip
},
2017-12-16 12:00:38 +00:00
preventOverflow: {
boundariesElement: this._config.boundary
}
}
}
// Disable Popper.js if we have a static display
if (this._config.display === 'static') {
popperConfig.modifiers.applyStyle = {
enabled: false
}
}
return popperConfig
}
2017-12-16 12:00:38 +00:00
// Static
2015-05-10 20:47:11 +00:00
static _jQueryInterface(config) {
return this.each(function () {
let data = $(this).data(DATA_KEY)
const _config = typeof config === 'object' ? config : null
2015-05-10 20:47:11 +00:00
if (!data) {
2017-04-14 09:25:53 +00:00
data = new Dropdown(this, _config)
$(this).data(DATA_KEY, data)
2015-05-10 20:47:11 +00:00
}
if (typeof config === 'string') {
2017-07-27 10:39:55 +00:00
if (typeof data[config] === 'undefined') {
2017-12-16 12:00:38 +00:00
throw new TypeError(`No method named "${config}"`)
}
data[config]()
2015-05-10 20:47:11 +00:00
}
})
}
static _clearMenus(event) {
2017-02-08 23:51:50 +00:00
if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH ||
event.type === 'keyup' && event.which !== TAB_KEYCODE)) {
2015-05-10 20:47:11 +00:00
return
}
const toggles = [].slice.call(document.querySelectorAll(Selector.DATA_TOGGLE))
for (let i = 0, len = toggles.length; i < len; i++) {
2017-12-16 12:00:38 +00:00
const parent = Dropdown._getParentFromElement(toggles[i])
const context = $(toggles[i]).data(DATA_KEY)
const relatedTarget = {
2017-12-16 12:00:38 +00:00
relatedTarget: toggles[i]
}
2015-05-10 20:47:11 +00:00
if (event && event.type === 'click') {
relatedTarget.clickEvent = event
}
2017-04-14 09:25:53 +00:00
if (!context) {
continue
}
const dropdownMenu = context._menu
2016-10-27 22:13:17 +00:00
if (!$(parent).hasClass(ClassName.SHOW)) {
2015-05-10 20:47:11 +00:00
continue
}
if (event && (event.type === 'click' &&
2017-12-16 12:00:38 +00:00
/input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE) &&
$.contains(parent, event.target)) {
2015-05-10 20:47:11 +00:00
continue
}
const hideEvent = $.Event(Event.HIDE, relatedTarget)
2015-05-10 20:47:11 +00:00
$(parent).trigger(hideEvent)
if (hideEvent.isDefaultPrevented()) {
continue
}
2017-12-16 12:00:38 +00:00
// If this is a touch-enabled device we remove the extra
Replace dropdown backdrop hack with cleaner JS-only hack * Replace backdrop with simple noop mouse listener As discussed in https://github.com/twbs/bootstrap/pull/22422 the current approach of injecting a backdrop (to work around iOS' broken event delegation for the `click` event) has annoying consequences on touch-enabled laptop/desktop devices. Instead of a backdrop `<div>`, here we simply add extra empty/noop mouse listeners to the immediate children of `<body>` (and remove them when the dropdown is closed) in order to force iOS to properly bubble a `click` resulting from a tap (essentially, method 2 from https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html) This is sufficient (except in rare cases where the user does manage to tap on the body itself, rather than any child elements of body - which is not very likely in an iOS phone/tablet scenario for most layouts) to get iOS to get a grip and do the correct event bubbling/delegation, meaning the regular "click" event will bubble back to the `<body>` when tapping outside of the dropdown, and the dropdown will close properly (just like it already does, even without this fix, in non-iOS touchscreen devices/browsers, like Chrome/Android and Windows on a touch laptop). This approach, though a bit hacky, has no impact on the DOM structure, and has no unforeseen side effects on touch-enabled laptops/desktops. And crucially, it works just fine in iOS. * Remove dropdown backdrop styles * Update doc for dropdowns and touch-enabled devices
2017-04-14 08:19:00 +00:00
// empty mouseover listeners we added for iOS support
if ('ontouchstart' in document.documentElement) {
$(document.body).children().off('mouseover', null, $.noop)
}
2015-05-10 20:47:11 +00:00
toggles[i].setAttribute('aria-expanded', 'false')
2017-04-14 09:25:53 +00:00
$(dropdownMenu).removeClass(ClassName.SHOW)
2015-05-10 20:47:11 +00:00
$(parent)
2016-10-27 22:13:17 +00:00
.removeClass(ClassName.SHOW)
2015-08-15 19:17:13 +00:00
.trigger($.Event(Event.HIDDEN, relatedTarget))
2015-05-10 20:47:11 +00:00
}
}
static _getParentFromElement(element) {
let parent
const selector = Util.getSelectorFromElement(element)
2015-05-10 20:47:11 +00:00
if (selector) {
parent = document.querySelector(selector)
2015-05-10 20:47:11 +00:00
}
return parent || element.parentNode
}
// eslint-disable-next-line complexity
2015-05-10 20:47:11 +00:00
static _dataApiKeydownHandler(event) {
// 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
2017-10-26 10:26:19 +00:00
// - If key is other than escape
// - If key is not up or down => not a dropdown command
// - If trigger inside the menu => not a dropdown command
2017-12-16 12:00:38 +00:00
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)) {
2015-05-10 20:47:11 +00:00
return
}
event.preventDefault()
event.stopPropagation()
if (this.disabled || $(this).hasClass(ClassName.DISABLED)) {
return
}
const parent = Dropdown._getParentFromElement(this)
2016-10-27 22:13:17 +00:00
const isActive = $(parent).hasClass(ClassName.SHOW)
2015-05-10 20:47:11 +00:00
if (!isActive && (event.which !== ESCAPE_KEYCODE || event.which !== SPACE_KEYCODE) ||
isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) {
if (event.which === ESCAPE_KEYCODE) {
const toggle = parent.querySelector(Selector.DATA_TOGGLE)
2015-05-10 20:47:11 +00:00
$(toggle).trigger('focus')
}
$(this).trigger('click')
return
}
const items = [].slice.call(parent.querySelectorAll(Selector.VISIBLE_ITEMS))
2015-05-10 20:47:11 +00:00
2017-12-16 12:00:38 +00:00
if (items.length === 0) {
2015-05-10 20:47:11 +00:00
return
}
let index = items.indexOf(event.target)
2017-12-16 12:00:38 +00:00
if (event.which === ARROW_UP_KEYCODE && index > 0) { // Up
2015-08-19 02:22:46 +00:00
index--
}
2017-12-16 12:00:38 +00:00
if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) { // Down
2015-08-19 02:22:46 +00:00
index++
}
if (index < 0) {
2015-08-19 02:22:46 +00:00
index = 0
}
2015-05-10 20:47:11 +00:00
items[index].focus()
}
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document)
2017-12-16 12:00:38 +00:00
.on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE, Dropdown._dataApiKeydownHandler)
.on(Event.KEYDOWN_DATA_API, Selector.MENU, Dropdown._dataApiKeydownHandler)
2017-02-08 23:51:50 +00:00
.on(`${Event.CLICK_DATA_API} ${Event.KEYUP_DATA_API}`, Dropdown._clearMenus)
.on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
event.preventDefault()
event.stopPropagation()
Dropdown._jQueryInterface.call($(this), 'toggle')
})
2015-08-19 02:22:46 +00:00
.on(Event.CLICK_DATA_API, Selector.FORM_CHILD, (e) => {
e.stopPropagation()
})
2015-05-10 20:47:11 +00:00
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
2017-12-16 12:00:38 +00:00
$.fn[NAME] = Dropdown._jQueryInterface
2015-05-10 20:47:11 +00:00
$.fn[NAME].Constructor = Dropdown
2018-08-12 18:24:45 +00:00
$.fn[NAME].noConflict = () => {
2015-05-10 20:47:11 +00:00
$.fn[NAME] = JQUERY_NO_CONFLICT
return Dropdown._jQueryInterface
}
return Dropdown
})($, Popper)
2015-05-10 20:47:11 +00:00
export default Dropdown