1 | /**
|
---|
2 | * --------------------------------------------------------------------------
|
---|
3 | * Bootstrap button.js
|
---|
4 | * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
|
---|
5 | * --------------------------------------------------------------------------
|
---|
6 | */
|
---|
7 |
|
---|
8 | import BaseComponent from './base-component.js'
|
---|
9 | import EventHandler from './dom/event-handler.js'
|
---|
10 | import { defineJQueryPlugin } from './util/index.js'
|
---|
11 |
|
---|
12 | /**
|
---|
13 | * Constants
|
---|
14 | */
|
---|
15 |
|
---|
16 | const NAME = 'button'
|
---|
17 | const DATA_KEY = 'bs.button'
|
---|
18 | const EVENT_KEY = `.${DATA_KEY}`
|
---|
19 | const DATA_API_KEY = '.data-api'
|
---|
20 |
|
---|
21 | const CLASS_NAME_ACTIVE = 'active'
|
---|
22 | const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="button"]'
|
---|
23 | const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`
|
---|
24 |
|
---|
25 | /**
|
---|
26 | * Class definition
|
---|
27 | */
|
---|
28 |
|
---|
29 | class Button extends BaseComponent {
|
---|
30 | // Getters
|
---|
31 | static get NAME() {
|
---|
32 | return NAME
|
---|
33 | }
|
---|
34 |
|
---|
35 | // Public
|
---|
36 | toggle() {
|
---|
37 | // Toggle class and sync the `aria-pressed` attribute with the return value of the `.toggle()` method
|
---|
38 | this._element.setAttribute('aria-pressed', this._element.classList.toggle(CLASS_NAME_ACTIVE))
|
---|
39 | }
|
---|
40 |
|
---|
41 | // Static
|
---|
42 | static jQueryInterface(config) {
|
---|
43 | return this.each(function () {
|
---|
44 | const data = Button.getOrCreateInstance(this)
|
---|
45 |
|
---|
46 | if (config === 'toggle') {
|
---|
47 | data[config]()
|
---|
48 | }
|
---|
49 | })
|
---|
50 | }
|
---|
51 | }
|
---|
52 |
|
---|
53 | /**
|
---|
54 | * Data API implementation
|
---|
55 | */
|
---|
56 |
|
---|
57 | EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, event => {
|
---|
58 | event.preventDefault()
|
---|
59 |
|
---|
60 | const button = event.target.closest(SELECTOR_DATA_TOGGLE)
|
---|
61 | const data = Button.getOrCreateInstance(button)
|
---|
62 |
|
---|
63 | data.toggle()
|
---|
64 | })
|
---|
65 |
|
---|
66 | /**
|
---|
67 | * jQuery
|
---|
68 | */
|
---|
69 |
|
---|
70 | defineJQueryPlugin(Button)
|
---|
71 |
|
---|
72 | export default Button
|
---|