UNPKG

2.85 kBJavaScriptView Raw
1import BaseComponent from 'bootstrap/js/src/base-component.js'
2
3import { reflow, getElementFromSelector } from 'bootstrap/js/src/util'
4import EventHandler from 'bootstrap/js/src/dom/event-handler'
5import SelectorEngine from 'bootstrap/js/src/dom/selector-engine'
6
7const NAME = 'dimmer'
8const DATA_KEY = 'bs.dimmer'
9const EVENT_KEY = `.${DATA_KEY}`
10//const DATA_API_KEY = '.data-api'
11
12const EVENT_CLICK = `click${EVENT_KEY}`
13
14const CLASS_NAME_FADE = 'fade'
15const CLASS_NAME_SHOW = 'show'
16
17const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="dimmer"]'
18
19class Dimmer extends BaseComponent {
20 constructor(element) {
21 super(element)
22
23 this._isShown = false
24 this._isTransitioning = false
25
26 this._init()
27 }
28
29 // Getters
30
31 static get NAME() {
32 return NAME
33 }
34
35 // Public
36
37 show() {
38 if (this._isShown || this._isTransitioning) {
39 return
40 }
41
42 this._isShown = true
43
44 if (this._isAnimated()) {
45 this._isTransitioning = true
46 }
47
48 this._showElement()
49 }
50
51 hide() {
52 if (!this._isShown || this._isTransitioning) {
53 return
54 }
55
56 this._isShown = false
57 const isAnimated = this._isAnimated()
58
59 if (isAnimated) {
60 this._isTransitioning = true
61 }
62
63 this._element.classList.remove(CLASS_NAME_SHOW)
64
65 this._queueCallback(() => this._hideElement(), this._element, isAnimated)
66 }
67
68 //Private
69 _init() {
70 if (this._element.classList.contains(CLASS_NAME_SHOW)) {
71 this.show()
72 }
73 }
74
75 _isAnimated() {
76 return this._element.classList.contains(CLASS_NAME_FADE)
77 }
78
79 _showElement() {
80 const isAnimated = this._isAnimated()
81
82 this._element.style.display = 'flex'
83 this._element.removeAttribute('aria-hidden')
84 //this._element.setAttribute('aria-modal', true)
85 //this._element.setAttribute('role', 'dialog')
86
87 if (isAnimated) {
88 reflow(this._element)
89 }
90
91 this._element.classList.add(CLASS_NAME_SHOW)
92
93 const transitionComplete = () => {
94 this._isTransitioning = false
95 }
96
97 this._queueCallback(transitionComplete, this._element, isAnimated)
98 }
99
100 _hideElement() {
101 this._element.style.display = 'none'
102 this._element.setAttribute('aria-hidden', true)
103 //this._element.removeAttribute('aria-modal')
104 //this._element.removeAttribute('role')
105 this._isTransitioning = false
106 }
107}
108
109/**
110 * ------------------------------------------------------------------------
111 * Data Api implementation
112 * ------------------------------------------------------------------------
113 */
114
115SelectorEngine.find(SELECTOR_DATA_TOGGLE).forEach((toggle) => {
116 const dimmerElement = getElementFromSelector(toggle)
117 const dimmer = Dimmer.getOrCreateInstance(dimmerElement)
118
119 EventHandler.on(toggle, EVENT_CLICK, () => {
120 toggle.checked ? dimmer.show() : dimmer.hide()
121 })
122
123 if (toggle.checked) {
124 dimmer.show()
125 }
126})
127
128export default Dimmer