tooltip.js 18.3 KB
Newer Older
1
2
import $ from 'jquery'
import Popper from 'popper.js'
3
4
5
6
import Util from './util'

/**
 * --------------------------------------------------------------------------
Mark Otto's avatar
Mark Otto committed
7
 * Bootstrap (v4.1.3): tooltip.js
8
9
10
11
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * --------------------------------------------------------------------------
 */

12
const Tooltip = (($) => {
13
14
15
16
17
18
  /**
   * ------------------------------------------------------------------------
   * Constants
   * ------------------------------------------------------------------------
   */

19
  const NAME               = 'tooltip'
Mark Otto's avatar
Mark Otto committed
20
  const VERSION            = '4.1.3'
21
22
23
24
  const DATA_KEY           = 'bs.tooltip'
  const EVENT_KEY          = `.${DATA_KEY}`
  const JQUERY_NO_CONFLICT = $.fn[NAME]
  const CLASS_PREFIX       = 'bs-tooltip'
Johann-S's avatar
Johann-S committed
25
  const BSCLS_PREFIX_REGEX = new RegExp(`(^|\\s)${CLASS_PREFIX}\\S+`, 'g')
26

fat's avatar
fat committed
27
  const DefaultType = {
28
29
30
31
32
33
34
35
36
37
    animation           : 'boolean',
    template            : 'string',
    title               : '(string|element|function)',
    trigger             : 'string',
    delay               : '(number|object)',
    html                : 'boolean',
    selector            : '(string|boolean)',
    placement           : '(string|function)',
    offset              : '(number|string)',
    container           : '(string|element|boolean)',
38
39
    fallbackPlacement   : '(string|array)',
    boundary            : '(string|element)'
40
41
  }

fat's avatar
fat committed
42
  const AttachmentMap = {
Johann-S's avatar
Johann-S committed
43
    AUTO   : 'auto',
44
45
46
47
    TOP    : 'top',
    RIGHT  : 'right',
    BOTTOM : 'bottom',
    LEFT   : 'left'
48
49
  }

50
51
  const Default = {
    animation           : true,
XhmikosR's avatar
XhmikosR committed
52
53
54
    template            : '<div class="tooltip" role="tooltip">' +
                        '<div class="arrow"></div>' +
                        '<div class="tooltip-inner"></div></div>',
55
56
57
58
59
60
61
62
    trigger             : 'hover focus',
    title               : '',
    delay               : 0,
    html                : false,
    selector            : false,
    placement           : 'top',
    offset              : 0,
    container           : false,
63
64
    fallbackPlacement   : 'flip',
    boundary            : 'scrollParent'
65
66
  }

67
  const HoverState = {
Starsam80's avatar
Starsam80 committed
68
69
    SHOW : 'show',
    OUT  : 'out'
70
71
72
  }

  const Event = {
fat's avatar
fat committed
73
74
75
76
77
78
79
80
81
82
    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}`
83
84
85
  }

  const ClassName = {
Starsam80's avatar
Starsam80 committed
86
87
    FADE : 'fade',
    SHOW : 'show'
88
89
90
91
  }

  const Selector = {
    TOOLTIP       : '.tooltip',
92
93
    TOOLTIP_INNER : '.tooltip-inner',
    ARROW         : '.arrow'
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
  }

  const Trigger = {
    HOVER  : 'hover',
    FOCUS  : 'focus',
    CLICK  : 'click',
    MANUAL : 'manual'
  }


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

  class Tooltip {
    constructor(element, config) {
112
113
114
115
116
      /**
       * Check for Popper dependency
       * Popper - https://popper.js.org
       */
      if (typeof Popper === 'undefined') {
XhmikosR's avatar
XhmikosR committed
117
        throw new TypeError('Bootstrap tooltips require Popper.js (https://popper.js.org)')
118
      }
119
120

      // private
121
122
123
124
      this._isEnabled     = true
      this._timeout       = 0
      this._hoverState    = ''
      this._activeTrigger = {}
125
      this._popper        = null
126

XhmikosR's avatar
XhmikosR committed
127
      // Protected
128
129
130
131
132
133
134
      this.element = element
      this.config  = this._getConfig(config)
      this.tip     = null

      this._setListeners()
    }

XhmikosR's avatar
XhmikosR committed
135
    // Getters
136
137
138
139
140
141
142
143
144

    static get VERSION() {
      return VERSION
    }

    static get Default() {
      return Default
    }

fat's avatar
fat committed
145
146
147
148
149
150
151
152
153
154
155
156
    static get NAME() {
      return NAME
    }

    static get DATA_KEY() {
      return DATA_KEY
    }

    static get Event() {
      return Event
    }

fat's avatar
fat committed
157
158
159
    static get EVENT_KEY() {
      return EVENT_KEY
    }
fat's avatar
fat committed
160

fat's avatar
fat committed
161
162
163
164
    static get DefaultType() {
      return DefaultType
    }

XhmikosR's avatar
XhmikosR committed
165
    // Public
166
167
168
169
170
171
172
173
174
175
176
177
178
179

    enable() {
      this._isEnabled = true
    }

    disable() {
      this._isEnabled = false
    }

    toggleEnabled() {
      this._isEnabled = !this._isEnabled
    }

    toggle(event) {
180
181
182
183
      if (!this._isEnabled) {
        return
      }

184
      if (event) {
185
        const dataKey = this.constructor.DATA_KEY
Jacob Thornton's avatar
Jacob Thornton committed
186
        let context = $(event.currentTarget).data(dataKey)
187
188
189
190
191
192

        if (!context) {
          context = new this.constructor(
            event.currentTarget,
            this._getDelegateConfig()
          )
fat's avatar
fat committed
193
          $(event.currentTarget).data(dataKey, context)
194
195
196
197
198
199
200
201
202
203
        }

        context._activeTrigger.click = !context._activeTrigger.click

        if (context._isWithActiveTrigger()) {
          context._enter(null, context)
        } else {
          context._leave(null, context)
        }
      } else {
Starsam80's avatar
Starsam80 committed
204
        if ($(this.getTipElement()).hasClass(ClassName.SHOW)) {
Jacob Thornton's avatar
Jacob Thornton committed
205
206
207
208
209
          this._leave(null, this)
          return
        }

        this._enter(null, this)
210
211
212
      }
    }

fat's avatar
fat committed
213
    dispose() {
214
      clearTimeout(this._timeout)
fat's avatar
fat committed
215

fat's avatar
fat committed
216
      $.removeData(this.element, this.constructor.DATA_KEY)
fat's avatar
fat committed
217

fat's avatar
fat committed
218
      $(this.element).off(this.constructor.EVENT_KEY)
219
      $(this.element).closest('.modal').off('hide.bs.modal')
fat's avatar
fat committed
220
221
222
223
224

      if (this.tip) {
        $(this.tip).remove()
      }

225
226
227
228
      this._isEnabled     = null
      this._timeout       = null
      this._hoverState    = null
      this._activeTrigger = null
229
230
231
      if (this._popper !== null) {
        this._popper.destroy()
      }
fat's avatar
fat committed
232

233
      this._popper = null
fat's avatar
fat committed
234
235
236
      this.element = null
      this.config  = null
      this.tip     = null
237
238
239
    }

    show() {
240
241
242
      if ($(this.element).css('display') === 'none') {
        throw new Error('Please use show on visible elements')
      }
243

244
      const showEvent = $.Event(this.constructor.Event.SHOW)
245
246
247
      if (this.isWithContent() && this._isEnabled) {
        $(this.element).trigger(showEvent)

248
        const isInTheDom = $.contains(
249
250
251
252
253
254
255
256
          this.element.ownerDocument.documentElement,
          this.element
        )

        if (showEvent.isDefaultPrevented() || !isInTheDom) {
          return
        }

257
258
        const tip   = this.getTipElement()
        const tipId = Util.getUID(this.constructor.NAME)
259
260
261
262
263
264
265
266
267
268

        tip.setAttribute('id', tipId)
        this.element.setAttribute('aria-describedby', tipId)

        this.setContent()

        if (this.config.animation) {
          $(tip).addClass(ClassName.FADE)
        }

XhmikosR's avatar
XhmikosR committed
269
270
271
        const placement  = typeof this.config.placement === 'function'
          ? this.config.placement.call(this, tip, this.element)
          : this.config.placement
272

273
        const attachment = this._getAttachment(placement)
Johann-S's avatar
Johann-S committed
274
        this.addAttachmentClass(attachment)
275

276
        const container = this.config.container === false ? document.body : $(document).find(this.config.container)
277

278
279
280
281
282
        $(tip).data(this.constructor.DATA_KEY, this)

        if (!$.contains(this.element.ownerDocument.documentElement, this.tip)) {
          $(tip).appendTo(container)
        }
283

fat's avatar
fat committed
284
        $(this.element).trigger(this.constructor.Event.INSERTED)
285

286
        this._popper = new Popper(this.element, tip, {
287
288
289
290
          placement: attachment,
          modifiers: {
            offset: {
              offset: this.config.offset
291
            },
292
293
294
295
296
            flip: {
              behavior: this.config.fallbackPlacement
            },
            arrow: {
              element: Selector.ARROW
297
298
299
            },
            preventOverflow: {
              boundariesElement: this.config.boundary
300
            }
301
          },
302
          onCreate: (data) => {
303
304
305
            if (data.originalPlacement !== data.placement) {
              this._handlePopperPlacementChange(data)
            }
306
          },
XhmikosR's avatar
XhmikosR committed
307
          onUpdate: (data) => {
308
            this._handlePopperPlacementChange(data)
309
          }
310
311
        })

Starsam80's avatar
Starsam80 committed
312
        $(tip).addClass(ClassName.SHOW)
313

XhmikosR's avatar
XhmikosR committed
314
        // If this is a touch-enabled device we add extra
Patrick H. Lauke's avatar
Patrick H. Lauke committed
315
316
317
        // 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
318
        if ('ontouchstart' in document.documentElement) {
319
          $(document.body).children().on('mouseover', null, $.noop)
Patrick H. Lauke's avatar
Patrick H. Lauke committed
320
321
        }

322
        const complete = () => {
323
324
325
          if (this.config.animation) {
            this._fixTransition()
          }
326
          const prevHoverState = this._hoverState
327
          this._hoverState     = null
328

fat's avatar
fat committed
329
          $(this.element).trigger(this.constructor.Event.SHOWN)
330
331
332
333
334
335

          if (prevHoverState === HoverState.OUT) {
            this._leave(null, this)
          }
        }

336
        if ($(this.tip).hasClass(ClassName.FADE)) {
337
338
          const transitionDuration = Util.getTransitionDurationFromElement(this.tip)

339
340
          $(this.tip)
            .one(Util.TRANSITION_END, complete)
341
            .emulateTransitionEnd(transitionDuration)
342
        } else {
343
344
          complete()
        }
345
346
347
348
      }
    }

    hide(callback) {
349
350
      const tip       = this.getTipElement()
      const hideEvent = $.Event(this.constructor.Event.HIDE)
XhmikosR's avatar
XhmikosR committed
351
      const complete = () => {
Starsam80's avatar
Starsam80 committed
352
        if (this._hoverState !== HoverState.SHOW && tip.parentNode) {
353
354
355
          tip.parentNode.removeChild(tip)
        }

Johann-S's avatar
Johann-S committed
356
        this._cleanTipClass()
357
        this.element.removeAttribute('aria-describedby')
fat's avatar
fat committed
358
        $(this.element).trigger(this.constructor.Event.HIDDEN)
359
360
361
362
        if (this._popper !== null) {
          this._popper.destroy()
        }

363
364
365
366
367
368
369
370
371
372
373
        if (callback) {
          callback()
        }
      }

      $(this.element).trigger(hideEvent)

      if (hideEvent.isDefaultPrevented()) {
        return
      }

Starsam80's avatar
Starsam80 committed
374
      $(tip).removeClass(ClassName.SHOW)
375

XhmikosR's avatar
XhmikosR committed
376
      // If this is a touch-enabled device we remove the extra
Patrick H. Lauke's avatar
Patrick H. Lauke committed
377
378
      // empty mouseover listeners we added for iOS support
      if ('ontouchstart' in document.documentElement) {
379
        $(document.body).children().off('mouseover', null, $.noop)
Patrick H. Lauke's avatar
Patrick H. Lauke committed
380
381
      }

382
383
384
385
      this._activeTrigger[Trigger.CLICK] = false
      this._activeTrigger[Trigger.FOCUS] = false
      this._activeTrigger[Trigger.HOVER] = false

386
      if ($(this.tip).hasClass(ClassName.FADE)) {
387
388
        const transitionDuration = Util.getTransitionDurationFromElement(tip)

389
390
        $(tip)
          .one(Util.TRANSITION_END, complete)
391
          .emulateTransitionEnd(transitionDuration)
392
393
394
395
396
397
398
      } else {
        complete()
      }

      this._hoverState = ''
    }

399
400
401
402
403
    update() {
      if (this._popper !== null) {
        this._popper.scheduleUpdate()
      }
    }
404

XhmikosR's avatar
XhmikosR committed
405
    // Protected
406
407

    isWithContent() {
Jacob Thornton's avatar
Jacob Thornton committed
408
      return Boolean(this.getTitle())
409
410
    }

Johann-S's avatar
Johann-S committed
411
412
413
414
    addAttachmentClass(attachment) {
      $(this.getTipElement()).addClass(`${CLASS_PREFIX}-${attachment}`)
    }

415
    getTipElement() {
416
417
      this.tip = this.tip || $(this.config.template)[0]
      return this.tip
418
419
420
    }

    setContent() {
421
422
423
      const tip = this.getTipElement()
      this.setElementContent($(tip.querySelectorAll(Selector.TOOLTIP_INNER)), this.getTitle())
      $(tip).removeClass(`${ClassName.FADE} ${ClassName.SHOW}`)
424
425
    }

426
    setElementContent($element, content) {
427
      const html = this.config.html
428
      if (typeof content === 'object' && (content.nodeType || content.jquery)) {
XhmikosR's avatar
XhmikosR committed
429
        // Content is a DOM node or a jQuery
430
431
432
433
434
435
436
437
438
439
440
441
        if (html) {
          if (!$(content).parent().is($element)) {
            $element.empty().append(content)
          }
        } else {
          $element.text($(content).text())
        }
      } else {
        $element[html ? 'html' : 'text'](content)
      }
    }

442
443
444
445
    getTitle() {
      let title = this.element.getAttribute('data-original-title')

      if (!title) {
XhmikosR's avatar
XhmikosR committed
446
447
448
        title = typeof this.config.title === 'function'
          ? this.config.title.call(this.element)
          : this.config.title
449
450
451
452
453
      }

      return title
    }

XhmikosR's avatar
XhmikosR committed
454
    // Private
455

fat's avatar
fat committed
456
457
458
459
    _getAttachment(placement) {
      return AttachmentMap[placement.toUpperCase()]
    }

460
    _setListeners() {
461
      const triggers = this.config.trigger.split(' ')
462
463
464
465

      triggers.forEach((trigger) => {
        if (trigger === 'click') {
          $(this.element).on(
fat's avatar
fat committed
466
            this.constructor.Event.CLICK,
467
            this.config.selector,
468
            (event) => this.toggle(event)
469
470
          )
        } else if (trigger !== Trigger.MANUAL) {
XhmikosR's avatar
XhmikosR committed
471
472
473
474
475
476
          const eventIn = trigger === Trigger.HOVER
            ? this.constructor.Event.MOUSEENTER
            : this.constructor.Event.FOCUSIN
          const eventOut = trigger === Trigger.HOVER
            ? this.constructor.Event.MOUSELEAVE
            : this.constructor.Event.FOCUSOUT
477
478
479
480
481

          $(this.element)
            .on(
              eventIn,
              this.config.selector,
482
              (event) => this._enter(event)
483
484
485
486
            )
            .on(
              eventOut,
              this.config.selector,
487
              (event) => this._leave(event)
488
489
            )
        }
490
491
492
493
494

        $(this.element).closest('.modal').on(
          'hide.bs.modal',
          () => this.hide()
        )
495
496
497
      })

      if (this.config.selector) {
498
499
        this.config = {
          ...this.config,
XhmikosR's avatar
XhmikosR committed
500
501
          trigger: 'manual',
          selector: ''
502
        }
503
504
505
506
507
508
      } else {
        this._fixTitle()
      }
    }

    _fixTitle() {
509
      const titleType = typeof this.element.getAttribute('data-original-title')
510
      if (this.element.getAttribute('title') ||
511
         titleType !== 'string') {
512
513
514
515
516
517
518
519
520
        this.element.setAttribute(
          'data-original-title',
          this.element.getAttribute('title') || ''
        )
        this.element.setAttribute('title', '')
      }
    }

    _enter(event, context) {
521
      const dataKey = this.constructor.DATA_KEY
fat's avatar
fat committed
522
523

      context = context || $(event.currentTarget).data(dataKey)
524
525
526
527
528
529

      if (!context) {
        context = new this.constructor(
          event.currentTarget,
          this._getDelegateConfig()
        )
fat's avatar
fat committed
530
        $(event.currentTarget).data(dataKey, context)
531
532
533
534
      }

      if (event) {
        context._activeTrigger[
Jacob Thornton's avatar
Jacob Thornton committed
535
          event.type === 'focusin' ? Trigger.FOCUS : Trigger.HOVER
536
537
538
        ] = true
      }

Starsam80's avatar
Starsam80 committed
539
540
541
      if ($(context.getTipElement()).hasClass(ClassName.SHOW) ||
         context._hoverState === HoverState.SHOW) {
        context._hoverState = HoverState.SHOW
542
543
544
545
546
        return
      }

      clearTimeout(context._timeout)

Starsam80's avatar
Starsam80 committed
547
      context._hoverState = HoverState.SHOW
548
549
550
551
552
553
554

      if (!context.config.delay || !context.config.delay.show) {
        context.show()
        return
      }

      context._timeout = setTimeout(() => {
Starsam80's avatar
Starsam80 committed
555
        if (context._hoverState === HoverState.SHOW) {
556
557
558
559
560
561
          context.show()
        }
      }, context.config.delay.show)
    }

    _leave(event, context) {
562
      const dataKey = this.constructor.DATA_KEY
fat's avatar
fat committed
563
564

      context = context || $(event.currentTarget).data(dataKey)
565
566
567
568
569
570

      if (!context) {
        context = new this.constructor(
          event.currentTarget,
          this._getDelegateConfig()
        )
fat's avatar
fat committed
571
        $(event.currentTarget).data(dataKey, context)
572
573
574
575
      }

      if (event) {
        context._activeTrigger[
Jacob Thornton's avatar
Jacob Thornton committed
576
          event.type === 'focusout' ? Trigger.FOCUS : Trigger.HOVER
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
        ] = false
      }

      if (context._isWithActiveTrigger()) {
        return
      }

      clearTimeout(context._timeout)

      context._hoverState = HoverState.OUT

      if (!context.config.delay || !context.config.delay.hide) {
        context.hide()
        return
      }

      context._timeout = setTimeout(() => {
        if (context._hoverState === HoverState.OUT) {
          context.hide()
        }
      }, context.config.delay.hide)
    }

    _isWithActiveTrigger() {
601
      for (const trigger in this._activeTrigger) {
602
603
604
605
606
607
608
609
610
        if (this._activeTrigger[trigger]) {
          return true
        }
      }

      return false
    }

    _getConfig(config) {
611
612
613
      config = {
        ...this.constructor.Default,
        ...$(this.element).data(),
614
        ...typeof config === 'object' && config ? config : {}
615
      }
616

617
      if (typeof config.delay === 'number') {
618
        config.delay = {
XhmikosR's avatar
XhmikosR committed
619
620
          show: config.delay,
          hide: config.delay
621
622
623
        }
      }

624
      if (typeof config.title === 'number') {
625
626
627
        config.title = config.title.toString()
      }

628
      if (typeof config.content === 'number') {
629
630
631
        config.content = config.content.toString()
      }

fat's avatar
fat committed
632
633
634
635
636
637
      Util.typeCheckConfig(
        NAME,
        config,
        this.constructor.DefaultType
      )

638
639
640
641
      return config
    }

    _getDelegateConfig() {
642
      const config = {}
643
644

      if (this.config) {
645
        for (const key in this.config) {
Jacob Thornton's avatar
Jacob Thornton committed
646
647
          if (this.constructor.Default[key] !== this.config[key]) {
            config[key] = this.config[key]
648
649
650
651
652
653
654
          }
        }
      }

      return config
    }

Johann-S's avatar
Johann-S committed
655
656
657
    _cleanTipClass() {
      const $tip = $(this.getTipElement())
      const tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX)
658
      if (tabClass !== null && tabClass.length) {
Johann-S's avatar
Johann-S committed
659
660
        $tip.removeClass(tabClass.join(''))
      }
Johann-S's avatar
Johann-S committed
661
662
    }

663
664
665
    _handlePopperPlacementChange(popperData) {
      const popperInstance = popperData.instance
      this.tip = popperInstance.popper
666
      this._cleanTipClass()
667
      this.addAttachmentClass(this._getAttachment(popperData.placement))
668
    }
669

670
    _fixTransition() {
XhmikosR's avatar
XhmikosR committed
671
      const tip = this.getTipElement()
672
673
      const initConfigAnimation = this.config.animation
      if (tip.getAttribute('x-placement') !== null) {
674
        return
675
676
677
678
679
680
681
682
      }
      $(tip).removeClass(ClassName.FADE)
      this.config.animation = false
      this.hide()
      this.show()
      this.config.animation = initConfigAnimation
    }

XhmikosR's avatar
XhmikosR committed
683
    // Static
684
685
686

    static _jQueryInterface(config) {
      return this.each(function () {
XhmikosR's avatar
XhmikosR committed
687
        let data = $(this).data(DATA_KEY)
688
        const _config = typeof config === 'object' && config
689

Johann-S's avatar
Johann-S committed
690
        if (!data && /dispose|hide/.test(config)) {
691
692
693
694
695
696
697
698
699
          return
        }

        if (!data) {
          data = new Tooltip(this, _config)
          $(this).data(DATA_KEY, data)
        }

        if (typeof config === 'string') {
XhmikosR's avatar
XhmikosR committed
700
          if (typeof data[config] === 'undefined') {
XhmikosR's avatar
XhmikosR committed
701
            throw new TypeError(`No method named "${config}"`)
702
          }
703
704
705
706
707
708
709
710
711
712
713
714
          data[config]()
        }
      })
    }
  }

  /**
   * ------------------------------------------------------------------------
   * jQuery
   * ------------------------------------------------------------------------
   */

XhmikosR's avatar
XhmikosR committed
715
  $.fn[NAME] = Tooltip._jQueryInterface
716
  $.fn[NAME].Constructor = Tooltip
XhmikosR's avatar
XhmikosR committed
717
  $.fn[NAME].noConflict = () => {
718
719
720
721
722
    $.fn[NAME] = JQUERY_NO_CONFLICT
    return Tooltip._jQueryInterface
  }

  return Tooltip
723
})($, Popper)
724
725

export default Tooltip