| 1 |
/** |
| 2 |
* Internal dependencies |
| 3 |
*/ |
| 4 |
import { |
| 5 |
exposeComponent, |
| 6 |
reflow, |
| 7 |
executeAfterTransition, |
| 8 |
execute, |
| 9 |
} from "./utils"; |
| 10 |
|
| 11 |
/** |
| 12 |
* Backdrop class |
| 13 |
*/ |
| 14 |
class Backdrop { |
| 15 |
constructor(config = {}) { |
| 16 |
this._element = null; |
| 17 |
this._isAppended = false; |
| 18 |
|
| 19 |
// Default config |
| 20 |
const defaultConfig = { |
| 21 |
isVisible: true, |
| 22 |
rootElement: document.body, |
| 23 |
classBackdrop: "modal-backdrop fade", |
| 24 |
classShow: "show", |
| 25 |
clickCallback: null, |
| 26 |
}; |
| 27 |
|
| 28 |
// Get config values |
| 29 |
this._config = Object.assign(defaultConfig, config); |
| 30 |
} |
| 31 |
|
| 32 |
show(callback) { |
| 33 |
if (!this._config.isVisible) { |
| 34 |
execute(callback); |
| 35 |
return; |
| 36 |
} |
| 37 |
|
| 38 |
this._append(); |
| 39 |
|
| 40 |
reflow(this._getElement()); |
| 41 |
|
| 42 |
this._getElement().classList.add(this._config.classShow); |
| 43 |
|
| 44 |
// callback(); |
| 45 |
// Call a callback after transition |
| 46 |
executeAfterTransition(callback, this._getElement()); |
| 47 |
} |
| 48 |
|
| 49 |
hide(callback) { |
| 50 |
if (!this._config.isVisible) { |
| 51 |
execute(callback); |
| 52 |
return; |
| 53 |
} |
| 54 |
|
| 55 |
this._getElement().classList.remove(this._config.classShow); |
| 56 |
|
| 57 |
// Call a callback after transition |
| 58 |
executeAfterTransition(() => { |
| 59 |
this.dispose(); |
| 60 |
callback(); |
| 61 |
}, this._getElement()); |
| 62 |
} |
| 63 |
|
| 64 |
dispose() { |
| 65 |
if (!this._isAppended) { |
| 66 |
return; |
| 67 |
} |
| 68 |
|
| 69 |
this._element.remove(); |
| 70 |
this._isAppended = false; |
| 71 |
} |
| 72 |
|
| 73 |
_getElement() { |
| 74 |
if (!this._element) { |
| 75 |
const backdrop = document.createElement("div"); |
| 76 |
backdrop.className = this._config.classBackdrop; |
| 77 |
|
| 78 |
this._element = backdrop; |
| 79 |
} |
| 80 |
|
| 81 |
return this._element; |
| 82 |
} |
| 83 |
|
| 84 |
_append() { |
| 85 |
if (this._isAppended) { |
| 86 |
return; |
| 87 |
} |
| 88 |
|
| 89 |
this._config.rootElement.appendChild(this._getElement()); |
| 90 |
|
| 91 |
if (typeof this._config.clickCallback === "function") { |
| 92 |
this._getElement().addEventListener("click", (e) => { |
| 93 |
e.preventDefault(); |
| 94 |
|
| 95 |
this._config.clickCallback(); |
| 96 |
}); |
| 97 |
} |
| 98 |
|
| 99 |
this._isAppended = true; |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
exposeComponent("Backdrop", Backdrop); |
| 104 |
|
| 105 |
export { Backdrop }; |
| 106 |
|