0
0
mirror of https://github.com/twbs/bootstrap.git synced 2024-12-12 00:08:59 +01:00
Bootstrap/js/src/tooltip.js

642 lines
15 KiB
JavaScript
Raw Normal View History

/**
* --------------------------------------------------------------------------
2021-10-09 08:33:12 +02:00
* Bootstrap (v5.1.3): tooltip.js
2020-06-16 20:41:47 +02:00
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
2020-06-19 10:17:01 +02:00
import * as Popper from '@popperjs/core'
import {
defineJQueryPlugin,
findShadowRoot,
getElement,
getUID,
isRTL,
noop,
typeCheckConfig
} from './util/index'
import { DefaultAllowlist } from './util/sanitizer'
import EventHandler from './dom/event-handler'
import Manipulator from './dom/manipulator'
2019-09-04 16:58:29 +02:00
import BaseComponent from './base-component'
import TemplateFactory from './util/template-factory'
2018-09-26 10:39:01 +02:00
/**
* Constants
*/
2019-02-26 12:20:34 +01:00
const NAME = 'tooltip'
const DATA_KEY = 'bs.tooltip'
const EVENT_KEY = `.${DATA_KEY}`
2020-05-02 15:56:23 +02:00
const DISALLOWED_ATTRIBUTES = new Set(['sanitize', 'allowList', 'sanitizeFn'])
2018-09-26 10:39:01 +02:00
const CLASS_NAME_FADE = 'fade'
const CLASS_NAME_MODAL = 'modal'
const CLASS_NAME_SHOW = 'show'
const SELECTOR_TOOLTIP_INNER = '.tooltip-inner'
const SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`
const EVENT_MODAL_HIDE = 'hide.bs.modal'
const TRIGGER_HOVER = 'hover'
const TRIGGER_FOCUS = 'focus'
const TRIGGER_CLICK = 'click'
const TRIGGER_MANUAL = 'manual'
2018-09-26 10:39:01 +02:00
const AttachmentMap = {
2019-02-26 12:20:34 +01:00
AUTO: 'auto',
TOP: 'top',
RIGHT: isRTL() ? 'left' : 'right',
2019-02-26 12:20:34 +01:00
BOTTOM: 'bottom',
LEFT: isRTL() ? 'right' : 'left'
2018-09-26 10:39:01 +02:00
}
const Default = {
2019-02-26 12:20:34 +01:00
animation: true,
template: '<div class="tooltip" role="tooltip">' +
2020-12-02 05:45:15 +01:00
'<div class="tooltip-arrow"></div>' +
'<div class="tooltip-inner"></div>' +
'</div>',
2019-02-26 12:20:34 +01:00
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
selector: false,
placement: 'top',
offset: [0, 0],
2019-02-26 12:20:34 +01:00
container: false,
fallbackPlacements: ['top', 'right', 'bottom', 'left'],
2020-06-19 10:17:01 +02:00
boundary: 'clippingParents',
customClass: '',
2019-02-26 12:20:34 +01:00
sanitize: true,
sanitizeFn: null,
allowList: DefaultAllowlist,
popperConfig: null
2018-09-26 10:39:01 +02:00
}
const DefaultType = {
animation: 'boolean',
template: 'string',
title: '(string|element|function)',
trigger: 'string',
delay: '(number|object)',
html: 'boolean',
selector: '(string|boolean)',
placement: '(string|function)',
offset: '(array|string|function)',
container: '(string|element|boolean)',
fallbackPlacements: 'array',
boundary: '(string|element)',
customClass: '(string|function)',
sanitize: 'boolean',
sanitizeFn: '(null|function)',
allowList: 'object',
popperConfig: '(null|object|function)'
}
2018-09-26 10:39:01 +02:00
const Event = {
2019-02-26 12:20:34 +01:00
HIDE: `hide${EVENT_KEY}`,
HIDDEN: `hidden${EVENT_KEY}`,
SHOW: `show${EVENT_KEY}`,
SHOWN: `shown${EVENT_KEY}`,
INSERTED: `inserted${EVENT_KEY}`,
CLICK: `click${EVENT_KEY}`,
FOCUSIN: `focusin${EVENT_KEY}`,
FOCUSOUT: `focusout${EVENT_KEY}`,
MOUSEENTER: `mouseenter${EVENT_KEY}`,
MOUSELEAVE: `mouseleave${EVENT_KEY}`
2018-09-26 10:39:01 +02:00
}
/**
* Class definition
2018-09-26 10:39:01 +02:00
*/
2019-09-04 16:58:29 +02:00
class Tooltip extends BaseComponent {
2018-09-26 10:39:01 +02:00
constructor(element, config) {
if (typeof Popper === 'undefined') {
throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org)')
}
2019-09-04 16:58:29 +02:00
super(element)
// Private
2019-02-26 12:20:34 +01:00
this._isEnabled = true
this._timeout = 0
this._isHovered = false
2018-09-26 10:39:01 +02:00
this._activeTrigger = {}
2019-02-26 12:20:34 +01:00
this._popper = null
this._templateFactory = null
2018-09-26 10:39:01 +02:00
// Protected
this._config = this._getConfig(config)
2019-02-26 12:20:34 +01:00
this.tip = null
2015-05-12 23:28:11 +02:00
2018-09-26 10:39:01 +02:00
this._setListeners()
}
2015-05-12 23:28:11 +02:00
2018-09-26 10:39:01 +02:00
// Getters
static get Default() {
return Default
}
2015-05-13 23:46:50 +02:00
2018-09-26 10:39:01 +02:00
static get NAME() {
return NAME
}
2018-09-26 10:39:01 +02:00
static get Event() {
return Event
}
2018-09-26 10:39:01 +02:00
static get DefaultType() {
return DefaultType
}
2018-09-26 10:39:01 +02:00
// Public
enable() {
this._isEnabled = true
}
2018-09-26 10:39:01 +02:00
disable() {
this._isEnabled = false
}
2018-09-26 10:39:01 +02:00
toggleEnabled() {
this._isEnabled = !this._isEnabled
}
2015-08-19 04:22:46 +02:00
2018-09-26 10:39:01 +02:00
toggle(event) {
if (!this._isEnabled) {
return
}
2018-09-26 10:39:01 +02:00
if (event) {
const context = this._initializeOnDelegatedTarget(event)
2015-05-12 23:28:11 +02:00
2018-09-26 10:39:01 +02:00
context._activeTrigger.click = !context._activeTrigger.click
2015-05-13 21:48:34 +02:00
2018-09-26 10:39:01 +02:00
if (context._isWithActiveTrigger()) {
context._enter()
2018-09-26 10:39:01 +02:00
} else {
context._leave()
2015-05-13 21:48:34 +02:00
}
2018-09-26 10:39:01 +02:00
} else {
if (this._getTipElement().classList.contains(CLASS_NAME_SHOW)) {
this._leave()
2018-09-26 10:39:01 +02:00
return
}
2015-05-13 21:48:34 +02:00
this._enter()
}
2018-09-26 10:39:01 +02:00
}
2018-09-26 10:39:01 +02:00
dispose() {
clearTimeout(this._timeout)
EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler)
if (this.tip) {
this.tip.remove()
2018-09-26 10:39:01 +02:00
}
this._disposePopper()
2020-11-20 11:13:11 +01:00
super.dispose()
2018-09-26 10:39:01 +02:00
}
2018-09-26 10:39:01 +02:00
show() {
2019-09-04 16:58:29 +02:00
if (this._element.style.display === 'none') {
2018-09-26 10:39:01 +02:00
throw new Error('Please use show on visible elements')
}
if (!(this._isWithContent() && this._isEnabled)) {
return
}
const showEvent = EventHandler.trigger(this._element, this.constructor.Event.SHOW)
const shadowRoot = findShadowRoot(this._element)
const isInTheDom = shadowRoot === null ?
this._element.ownerDocument.documentElement.contains(this._element) :
shadowRoot.contains(this._element)
if (showEvent.defaultPrevented || !isInTheDom) {
return
}
const tip = this._getTipElement()
this._element.setAttribute('aria-describedby', tip.getAttribute('id'))
const { container } = this._config
if (!this._element.ownerDocument.documentElement.contains(this.tip)) {
container.append(tip)
EventHandler.trigger(this._element, this.constructor.Event.INSERTED)
}
if (this._popper) {
this._popper.update()
} else {
const placement = typeof this._config.placement === 'function' ?
this._config.placement.call(this, tip, this._element) :
this._config.placement
const attachment = AttachmentMap[placement.toUpperCase()]
this._popper = Popper.createPopper(this._element, tip, this._getPopperConfig(attachment))
}
tip.classList.add(CLASS_NAME_SHOW)
// 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
if ('ontouchstart' in document.documentElement) {
for (const element of [].concat(...document.body.children)) {
2021-03-27 17:08:45 +01:00
EventHandler.on(element, 'mouseover', noop)
}
}
const complete = () => {
const prevHoverState = this._isHovered
this._isHovered = false
EventHandler.trigger(this._element, this.constructor.Event.SHOWN)
if (prevHoverState) {
this._leave()
}
}
2021-11-26 01:15:24 +01:00
this._queueCallback(complete, this.tip, this._isAnimated())
2018-09-26 10:39:01 +02:00
}
2019-05-10 21:57:27 +02:00
hide() {
if (!this._popper) {
return
}
2019-09-04 16:58:29 +02:00
const hideEvent = EventHandler.trigger(this._element, this.constructor.Event.HIDE)
2017-09-21 18:04:47 +02:00
if (hideEvent.defaultPrevented) {
2018-09-26 10:39:01 +02:00
return
}
const tip = this._getTipElement()
tip.classList.remove(CLASS_NAME_SHOW)
2018-09-26 10:39:01 +02:00
// If this is a touch-enabled device we remove the extra
// empty mouseover listeners we added for iOS support
if ('ontouchstart' in document.documentElement) {
for (const element of [].concat(...document.body.children)) {
EventHandler.off(element, 'mouseover', noop)
}
}
this._activeTrigger[TRIGGER_CLICK] = false
this._activeTrigger[TRIGGER_FOCUS] = false
this._activeTrigger[TRIGGER_HOVER] = false
const complete = () => {
if (this._isWithActiveTrigger()) {
return
}
if (!this._isHovered) {
tip.remove()
}
this._element.removeAttribute('aria-describedby')
EventHandler.trigger(this._element, this.constructor.Event.HIDDEN)
this._disposePopper()
}
2021-11-26 01:15:24 +01:00
this._queueCallback(complete, this.tip, this._isAnimated())
this._isHovered = false
2018-09-26 10:39:01 +02:00
}
2018-09-26 10:39:01 +02:00
update() {
2021-11-28 13:18:59 +01:00
if (this._popper) {
2020-06-19 10:17:01 +02:00
this._popper.update()
2015-05-12 23:28:11 +02:00
}
2018-09-26 10:39:01 +02:00
}
2015-05-12 23:28:11 +02:00
2018-09-26 10:39:01 +02:00
// Protected
_isWithContent() {
return Boolean(this._getTitle())
2018-09-26 10:39:01 +02:00
}
_getTipElement() {
if (!this.tip) {
this.tip = this._createTipElement(this._getContentForTemplate())
2017-09-21 18:04:47 +02:00
}
return this.tip
}
_createTipElement(content) {
const tip = this._getTemplateFactory(content).toHtml()
// todo: remove this check on v6
if (!tip) {
return null
}
2017-09-21 18:04:47 +02:00
tip.classList.remove(CLASS_NAME_FADE, CLASS_NAME_SHOW)
// todo: on v6 the following can be achieved with CSS only
tip.classList.add(`bs-${this.constructor.NAME}-auto`)
const tipId = getUID(this.constructor.NAME).toString()
tip.setAttribute('id', tipId)
2021-11-26 01:15:24 +01:00
if (this._isAnimated()) {
tip.classList.add(CLASS_NAME_FADE)
}
return tip
2018-09-26 10:39:01 +02:00
}
setContent(content) {
let isShown = false
if (this.tip) {
isShown = this.tip.classList.contains(CLASS_NAME_SHOW)
this.tip.remove()
this.tip = null
2017-09-21 18:04:47 +02:00
}
this._disposePopper()
this.tip = this._createTipElement(content)
if (isShown) {
this.show()
}
}
_getTemplateFactory(content) {
if (this._templateFactory) {
this._templateFactory.changeContent(content)
2018-09-26 10:39:01 +02:00
} else {
this._templateFactory = new TemplateFactory({
...this._config,
// the `content` var has to be after `this._config`
// to override config.content in case of popover
content,
extraClass: this._resolvePossibleFunction(this._config.customClass)
})
}
return this._templateFactory
2018-09-26 10:39:01 +02:00
}
_getContentForTemplate() {
return {
[SELECTOR_TOOLTIP_INNER]: this._getTitle()
}
}
_getTitle() {
return this._resolvePossibleFunction(this._config.title) || this._element.getAttribute('title')
2018-09-26 10:39:01 +02:00
}
2015-05-12 23:28:11 +02:00
2018-09-26 10:39:01 +02:00
// Private
_initializeOnDelegatedTarget(event) {
return this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig())
}
2021-11-26 01:15:24 +01:00
_isAnimated() {
return this._config.animation || (this.tip && this.tip.classList.contains(CLASS_NAME_FADE))
}
_getOffset() {
const { offset } = this._config
if (typeof offset === 'string') {
return offset.split(',').map(val => Number.parseInt(val, 10))
}
if (typeof offset === 'function') {
return popperData => offset(popperData, this._element)
}
return offset
}
_resolvePossibleFunction(arg) {
return typeof arg === 'function' ? arg.call(this._element) : arg
}
_getPopperConfig(attachment) {
const defaultBsPopperConfig = {
placement: attachment,
2020-06-19 10:17:01 +02:00
modifiers: [
{
name: 'flip',
options: {
fallbackPlacements: this._config.fallbackPlacements
}
},
{
name: 'offset',
options: {
offset: this._getOffset()
}
},
2020-06-19 10:17:01 +02:00
{
name: 'preventOverflow',
options: {
boundary: this._config.boundary
2020-06-19 10:17:01 +02:00
}
},
2020-06-19 10:17:01 +02:00
{
name: 'arrow',
options: {
element: `.${this.constructor.NAME}-arrow`
2020-06-19 10:17:01 +02:00
}
}
]
}
return {
...defaultBsPopperConfig,
...(typeof this._config.popperConfig === 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig)
}
}
2018-09-26 10:39:01 +02:00
_setListeners() {
const triggers = this._config.trigger.split(' ')
2018-09-26 10:39:01 +02:00
for (const trigger of triggers) {
2018-09-26 10:39:01 +02:00
if (trigger === 'click') {
EventHandler.on(this._element, this.constructor.Event.CLICK, this._config.selector, event => this.toggle(event))
} else if (trigger !== TRIGGER_MANUAL) {
const eventIn = trigger === TRIGGER_HOVER ?
2019-02-26 12:20:34 +01:00
this.constructor.Event.MOUSEENTER :
this.constructor.Event.FOCUSIN
const eventOut = trigger === TRIGGER_HOVER ?
2019-02-26 12:20:34 +01:00
this.constructor.Event.MOUSELEAVE :
this.constructor.Event.FOCUSOUT
2018-09-26 10:39:01 +02:00
EventHandler.on(this._element, eventIn, this._config.selector, event => {
const context = this._initializeOnDelegatedTarget(event)
context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true
context._enter()
})
EventHandler.on(this._element, eventOut, this._config.selector, event => {
const context = this._initializeOnDelegatedTarget(event)
context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] =
context._element.contains(event.relatedTarget)
context._leave()
})
}
}
this._hideModalHandler = () => {
2019-09-04 16:58:29 +02:00
if (this._element) {
this.hide()
}
}
EventHandler.on(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler)
if (this._config.selector) {
this._config = {
...this._config,
2018-09-26 10:39:01 +02:00
trigger: 'manual',
selector: ''
}
2018-09-26 10:39:01 +02:00
} else {
this._fixTitle()
}
}
2018-09-26 10:39:01 +02:00
_fixTitle() {
2019-09-04 16:58:29 +02:00
const title = this._element.getAttribute('title')
if (title && !this._element.getAttribute('aria-label') && !this._element.textContent) {
this._element.setAttribute('aria-label', title)
2018-09-26 10:39:01 +02:00
}
}
_enter() {
if (this._getTipElement().classList.contains(CLASS_NAME_SHOW) || this._isHovered) {
this._isHovered = true
2018-09-26 10:39:01 +02:00
return
}
this._isHovered = true
2021-11-28 02:58:59 +01:00
this._setTimeout(() => {
if (this._isHovered) {
this.show()
2018-09-26 10:39:01 +02:00
}
}, this._config.delay.show)
2018-09-26 10:39:01 +02:00
}
_leave() {
if (this._isWithActiveTrigger()) {
2018-09-26 10:39:01 +02:00
return
}
this._isHovered = false
2021-11-28 02:58:59 +01:00
this._setTimeout(() => {
if (!this._isHovered) {
this.hide()
}
}, this._config.delay.hide)
2018-09-26 10:39:01 +02:00
}
2021-11-28 02:58:59 +01:00
_setTimeout(handler, timeout) {
clearTimeout(this._timeout)
this._timeout = setTimeout(handler, timeout)
}
2018-09-26 10:39:01 +02:00
_isWithActiveTrigger() {
return Object.values(this._activeTrigger).includes(true)
2018-09-26 10:39:01 +02:00
}
2018-09-26 10:39:01 +02:00
_getConfig(config) {
2019-09-04 16:58:29 +02:00
const dataAttributes = Manipulator.getDataAttributes(this._element)
for (const dataAttr of Object.keys(dataAttributes)) {
2020-05-02 15:56:23 +02:00
if (DISALLOWED_ATTRIBUTES.has(dataAttr)) {
2020-06-20 18:00:53 +02:00
delete dataAttributes[dataAttr]
}
}
2018-09-26 10:39:01 +02:00
config = {
...this.constructor.Default,
...dataAttributes,
...(typeof config === 'object' && config ? config : {})
}
config.container = config.container === false ? document.body : getElement(config.container)
2018-09-26 10:39:01 +02:00
if (typeof config.delay === 'number') {
config.delay = {
show: config.delay,
hide: config.delay
2017-04-08 21:13:15 +02:00
}
2017-04-07 13:20:34 +02:00
}
2018-09-26 10:39:01 +02:00
if (typeof config.title === 'number') {
config.title = config.title.toString()
}
2018-09-26 10:39:01 +02:00
if (typeof config.content === 'number') {
config.content = config.content.toString()
}
2020-06-10 17:40:52 +02:00
typeCheckConfig(NAME, config, this.constructor.DefaultType)
2018-09-26 10:39:01 +02:00
return config
}
2018-09-26 10:39:01 +02:00
_getDelegateConfig() {
const config = {}
for (const key in this._config) {
if (this.constructor.Default[key] !== this._config[key]) {
config[key] = this._config[key]
2018-09-26 10:39:01 +02:00
}
}
// In the future can be replaced with:
// const keysWithDifferentValues = Object.entries(this._config).filter(entry => this.constructor.Default[entry[0]] !== this._config[entry[0]])
// `Object.fromEntries(keysWithDifferentValues)`
2018-09-26 10:39:01 +02:00
return config
}
_disposePopper() {
if (this._popper) {
this._popper.destroy()
this._popper = null
}
}
2018-09-26 10:39:01 +02:00
// Static
2019-07-28 15:24:46 +02:00
static jQueryInterface(config) {
2018-09-26 10:39:01 +02:00
return this.each(function () {
const data = Tooltip.getOrCreateInstance(this, config)
2021-11-25 19:33:42 +01:00
if (typeof config !== 'string') {
return
}
2019-02-26 12:20:34 +01:00
2021-11-25 19:33:42 +01:00
if (typeof data[config] === 'undefined') {
throw new TypeError(`No method named "${config}"`)
2018-09-26 10:39:01 +02:00
}
2021-11-25 19:33:42 +01:00
data[config]()
2018-09-26 10:39:01 +02:00
})
}
2018-09-26 10:39:01 +02:00
}
/**
* jQuery
*/
defineJQueryPlugin(Tooltip)
export default Tooltip