1
0
mirror of https://github.com/twbs/bootstrap.git synced 2025-08-12 00:24:03 +02:00

Toggler compontent from upstrea PR

This commit is contained in:
Mark Otto
2025-04-04 10:49:32 -07:00
parent 142a16fe55
commit 24f2269928
8 changed files with 479 additions and 2 deletions

View File

@@ -16,4 +16,5 @@ export { default as Popover } from './src/popover.js'
export { default as ScrollSpy } from './src/scrollspy.js'
export { default as Tab } from './src/tab.js'
export { default as Toast } from './src/toast.js'
export { default as Toggler } from './src/toggler.js'
export { default as Tooltip } from './src/tooltip.js'

View File

@@ -16,6 +16,7 @@ import Popover from './src/popover.js'
import ScrollSpy from './src/scrollspy.js'
import Tab from './src/tab.js'
import Toast from './src/toast.js'
import Toggler from './src/toggler.js'
import Tooltip from './src/tooltip.js'
export default {
@@ -30,5 +31,6 @@ export default {
ScrollSpy,
Tab,
Toast,
Toggler,
Tooltip
}

98
js/src/toggler.js Normal file
View File

@@ -0,0 +1,98 @@
/**
* --------------------------------------------------------------------------
* Bootstrap (v5.1.3): toggler.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
import BaseComponent from './base-component.js'
import EventHandler from './dom/event-handler.js'
import { eventActionOnPlugin } from './util/component-functions.js'
/**
* Constants
*/
const NAME = 'toggler'
const DATA_KEY = 'bs.toggle'
const EVENT_KEY = `.${DATA_KEY}`
const EVENT_TOGGLE = `toggle${EVENT_KEY}`
const EVENT_TOGGLED = `toggled${EVENT_KEY}`
const EVENT_CLICK = 'click'
const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="toggler"]'
const DefaultType = {
attribute: 'string',
value: '(string|number|boolean)'
}
const Default = {
attribute: 'class',
value: null
}
/**
* Class definition
*/
class Toggler extends BaseComponent {
// Getters
static get Default() {
return Default
}
static get DefaultType() {
return DefaultType
}
static get NAME() {
return NAME
}
_configAfterMerge(config) {
return config
}
// Private
toggle() {
const toggleEvent = EventHandler.trigger(this._element, EVENT_TOGGLE)
if (toggleEvent.defaultPrevented) {
return
}
this._execute()
EventHandler.trigger(this._element, EVENT_TOGGLED)
}
_execute() {
const { attribute, value } = this._config
if (attribute === 'id') {
return // You have to be kidding
}
if (attribute === 'class') {
this._element.classList.toggle(value)
return
}
if (this._element.getAttribute(attribute) === value) {
this._element.removeAttribute(attribute)
return
}
this._element.setAttribute(attribute, value)
}
}
/**
* Data API implementation
*/
eventActionOnPlugin(Toggler, EVENT_CLICK, SELECTOR_DATA_TOGGLE, 'toggle')
export default Toggler

View File

@@ -30,6 +30,34 @@ const enableDismissTrigger = (component, method = 'hide') => {
})
}
export {
enableDismissTrigger
const eventActionOnPlugin = (Plugin, onEvent, stringSelector, method, callback = null) => {
eventAction(`${onEvent}.${Plugin.NAME}`, stringSelector, data => {
const instances = data.targets.filter(Boolean).map(element => Plugin.getOrCreateInstance(element))
if (typeof callback === 'function') {
callback({ ...data, instances })
}
for (const instance of instances) {
instance[method]()
}
})
}
const eventAction = (onEvent, stringSelector, callback) => {
const selector = `${stringSelector}:not(.disabled):not(:disabled)`
EventHandler.on(document, onEvent, selector, function (event) {
if (['A', 'AREA'].includes(this.tagName)) {
event.preventDefault()
}
const selector = SelectorEngine.getSelectorFromElement(this)
const targets = selector ? SelectorEngine.find(selector) : [this]
callback({ targets, event })
})
}
export {
enableDismissTrigger,
eventActionOnPlugin
}

View File

@@ -0,0 +1,195 @@
import Toggler from '../../src/toggler.js'
import { clearFixture, getFixture } from '../helpers/fixture.js'
describe('Toggler', () => {
let fixtureEl
beforeAll(() => {
fixtureEl = getFixture()
})
afterEach(() => {
clearFixture()
})
describe('VERSION', () => {
it('should return plugin version', () => {
expect(Toggler.VERSION).toEqual(jasmine.any(String))
})
})
describe('constructor', () => {
it('should take care of element either passed as a CSS selector or DOM element', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="bg-warning" data-bs-attribute="class"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
const togglerBySelector = new Toggler('[data-bs-toggle="toggler"]')
const togglerByElement = new Toggler(togglerEl)
expect(togglerBySelector._element).toEqual(togglerEl)
expect(togglerByElement._element).toEqual(togglerEl)
})
})
describe('toggle', () => {
it('should toggle class on the element', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="bg-warning" data-bs-attribute="class"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
const toggler = new Toggler(togglerEl)
toggler.toggle()
expect(togglerEl.classList.contains('bg-warning')).toBeTrue()
toggler.toggle()
expect(togglerEl.classList.contains('bg-warning')).toBeFalse()
})
it('should toggle attribute on the element', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="true" data-bs-attribute="hidden"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
const toggler = new Toggler(togglerEl)
toggler.toggle()
expect(togglerEl.getAttribute('hidden')).toEqual('true')
toggler.toggle()
expect(togglerEl.hasAttribute('hidden')).toBeFalse()
})
it('should not toggle id attribute', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="new-id" data-bs-attribute="id"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
const toggler = new Toggler(togglerEl)
toggler.toggle()
expect(togglerEl.getAttribute('id')).toBeNull()
})
it('should trigger events', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="bg-warning" data-bs-attribute="class"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
const toggler = new Toggler(togglerEl)
const toggleSpy = jasmine.createSpy()
const toggledSpy = jasmine.createSpy()
togglerEl.addEventListener('toggle.bs.toggler', toggleSpy)
togglerEl.addEventListener('toggled.bs.toggler', toggledSpy)
toggler.toggle()
expect(toggleSpy).toHaveBeenCalled()
expect(toggledSpy).toHaveBeenCalled()
})
it('should not trigger toggled event if toggle is prevented', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="bg-warning" data-bs-attribute="class"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
const toggler = new Toggler(togglerEl)
const toggledSpy = jasmine.createSpy()
togglerEl.addEventListener('toggle.bs.toggler', event => {
event.preventDefault()
})
togglerEl.addEventListener('toggled.bs.toggler', toggledSpy)
toggler.toggle()
expect(toggledSpy).not.toHaveBeenCalled()
})
})
describe('dispose', () => {
it('should dispose a toggler', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="bg-warning" data-bs-attribute="class"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
const toggler = new Toggler(togglerEl)
expect(Toggler.getInstance(togglerEl)).not.toBeNull()
toggler.dispose()
expect(Toggler.getInstance(togglerEl)).toBeNull()
})
})
describe('getInstance', () => {
it('should return null if there is no instance', () => {
expect(Toggler.getInstance(fixtureEl)).toBeNull()
})
it('should return this instance', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="bg-warning" data-bs-attribute="class"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
const toggler = new Toggler(togglerEl)
expect(Toggler.getInstance(togglerEl)).toEqual(toggler)
expect(Toggler.getInstance(togglerEl)).toBeInstanceOf(Toggler)
})
})
describe('getOrCreateInstance', () => {
it('should return toggler instance', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="bg-warning" data-bs-attribute="class"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
const toggler = new Toggler(togglerEl)
expect(Toggler.getOrCreateInstance(togglerEl)).toEqual(toggler)
expect(Toggler.getInstance(togglerEl)).toEqual(Toggler.getOrCreateInstance(togglerEl, {}))
expect(Toggler.getOrCreateInstance(togglerEl)).toBeInstanceOf(Toggler)
})
it('should return new instance when there is no toggler instance', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="bg-warning" data-bs-attribute="class"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
expect(Toggler.getInstance(togglerEl)).toBeNull()
expect(Toggler.getOrCreateInstance(togglerEl)).toBeInstanceOf(Toggler)
})
})
describe('data-api', () => {
it('should toggle class on click', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="bg-warning" data-bs-attribute="class"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
togglerEl.click()
expect(togglerEl.classList.contains('bg-warning')).toBeTrue()
togglerEl.click()
expect(togglerEl.classList.contains('bg-warning')).toBeFalse()
})
it('should toggle attribute on click', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="true" data-bs-attribute="hidden"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
togglerEl.click()
expect(togglerEl.getAttribute('hidden')).toEqual('true')
togglerEl.click()
expect(togglerEl.hasAttribute('hidden')).toBeFalse()
})
it('should not toggle id attribute on click', () => {
fixtureEl.innerHTML = '<div data-bs-toggle="toggler" data-bs-value="new-id" data-bs-attribute="id"></div>'
const togglerEl = fixtureEl.querySelector('[data-bs-toggle="toggler"]')
togglerEl.click()
expect(togglerEl.getAttribute('id')).toBeNull()
})
})
})

View File

@@ -42,6 +42,10 @@
description: Show and hide notifications to your visitors.
link: components/toasts/
- name: Toggler
description: Toggle attributes or classes, using simple html markup
link: components/toggler/
- name: Tooltip
description: Replace browser tooltips with custom ones. Built on Popper.
link: components/tooltips/

View File

@@ -94,6 +94,7 @@
- title: Scrollspy
- title: Spinners
- title: Toasts
- title: Toggler
- title: Tooltips
- title: Helpers

View File

@@ -0,0 +1,148 @@
---
title: Attribute Toggler
description: Toggle attributes or classes, using simple html markup
toc: true
---
## How it works
Attribute Toggler is a simple component, that preferable can be used to avoid writing small JavaScript snippets handle attributes toggling, during `click` events.
Manipulation id done on the same element or on a targeted element
**Heads up!** Toggler may handle all attributes, except `id's`
## Examples
### Toggle class
Below are some examples of class manipulation
<Example code={`<div class="card" data-bs-toggle="toggler" data-bs-value="bg-warning" data-bs-attribute="class">
<div class="card-body">Click this card, to change \`bg-color\`</div>
</div>
<div class="card mt-2" data-bs-toggle="toggler" data-bs-value="text-danger" data-bs-attribute="class">
<div class="card-body">Click this card, to change \`text-color\`</div>
</div>`} />
### Toggle class of another element
Using `data-bs-toggle`, combined with `data-bs-target`, can manipulate another element's attribute
<Example code={`<button class="btn btn-outline-primary" data-bs-toggle="toggler" data-bs-target="#togglerExample1">Click me</button>
<div id="togglerExample1" class="card mt-2" data-bs-value="bg-info" data-bs-attribute="class">
<div class="card-body">Click this card, to change \`bg-color\`</div>
</div>`} />
### Toggle class of multiple elements
Using `data-bs-toggle`, combined with `data-bs-target`, can manipulate another element's attribute
<Example code={`<button class="btn btn-outline-primary" data-bs-toggle="toggler" data-bs-target=".togglerExampleClass1">Click me</button>
<div class="card mt-2 togglerExampleClass1" data-bs-value="bg-info" data-bs-attribute="class">
<div class="card-body">Click this card, to change \`bg-color\`</div>
</div>
<div class="card mt-2 togglerExampleClass1" data-bs-value="bg-warning" data-bs-attribute="class">
<div class="card-body">Click this card, to change \`bg-color\`</div>
</div>
<div class="card mt-2 togglerExampleClass1" data-bs-value="bg-info" data-bs-attribute="class">
<div class="card-body">Click this card, to change \`bg-color\`</div>
</div>`} />
### Toggle attributes
Below are some examples of attributes manipulation
<Example code={`<div class="card" data-bs-toggle="toggler" data-bs-value="true" data-bs-attribute="hidden">
<div class="card-body">Click this card, to change \`hidden\` attribute</div>
</div>`} />
### Toggle attributes of another element
Using `data-bs-toggle`, combined with `data-bs-target`, can manipulate another element's attribute
<Example code={`<button class="btn btn-outline-primary" data-bs-toggle="toggler" data-bs-target="#togglerExample2">Click to toggle \`disabled\` attribute on fieldset</button>
<fieldset class="mt-3" id="togglerExample2" data-bs-value="disabled" data-bs-attribute="disabled">
<div class="mb-3">
<label for="disabledTextInput" class="form-label">Input</label>
<input type="text" id="disabledTextInput" class="form-control" placeholder="Disabled input">
</div>
<div class="mb-3">
<label for="disabledSelect" class="form-label">Disabled select menu</label>
<select id="disabledSelect" class="form-select">
<option>Select</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</fieldset>`} />
### Via data attributes
#### Toggle
Add `data-bs-toggle="toggler"` to the element to automatically.
The `data-bs-target` is optional, and attribute accepts a CSS selector to apply the toggler functionality to.
Be sure to add the `data-bs-attribute` and `data-bs-value` attributes on the toggled element's markup
### Via JavaScript
Using this component, programmatically is a bit of redundant, as the initial purpose of it is to avoid use js.
However, enable manually with:
```js
var togglerElementList = Array.prototype.slice.call(document.querySelectorAll('[data-bs-toggle="toggler"]'))
var togglerList = togglerElementList.map(function (togglerEl) {
return new bootstrap.Toggler(togglerEl)
})
```
### Options
Options can be passed via data attributes or JavaScript. For data attributes, append the option name to `data-bs-`, as in `data-bs-value="foo"`.
<BsTable>
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `attribute` | string | `class` | The attribute which will be toggled on each click |
| `value` | string | null | Allow body scrolling while toggler is open |
</BsTable>
### Methods
You can create a toggler instance using the constructor, for example:
```js
var myToggler = document.getElementById('myToggler')
var bsToggler = new bootstrap.Toggler(myToggler)
```
<BsTable>
| Method | Description |
| --- | --- |
| `toggle` | Toggles a toggler element chosen attribute |
| `getInstance` | *Static* method which allows you to get the toggler instance associated with a DOM element |
| `getOrCreateInstance` | *Static* method which allows you to get the toggler instance associated with a DOM element, or create a new one in case it wasn't initialized |
</BsTable>
### Events
Bootstrap's toggler class exposes a few events for hooking into toggler functionality.
<BsTable>
| Event type | Description |
| --- | --- |
| `toggle.bs.toggler` | This event fires immediately when the `toggle` instance method is called. |
| `toggled.bs.toggler` | This event is fired when the instance's element attribute has been changed. |
</BsTable>
```js
var myToggler = document.getElementById('myToggler')
myToggler.addEventListener('toggle.bs.toggler', function () {
// do something...
})
```