tests for dropdown offsets

This commit is contained in:
joke2k 2020-12-12 01:27:54 +00:00 committed by Rohit Sharma
parent 5c8890687a
commit 5d22c10d08
3 changed files with 44 additions and 8 deletions

View file

@ -290,22 +290,22 @@ class Dropdown extends BaseComponent {
}
_getOffset() {
let offset = [0, 0]
let { offset } = this._config
if (!this._config.offset) {
return offset
if (!offset) {
return [0, 0]
}
if (typeof this._config.offset === 'number') {
offset[0] = this._config.offset
} else if (typeof this._config.offset === 'string') {
if (typeof offset === 'number') {
offset = [offset, 0]
} else if (typeof offset === 'string') {
offset = offset.split(',')
if (offset.length === 1) {
offset = [offset[0], 0]
}
offset = offset.map(val => Number.parseInt(val, 10))
} else if (typeof this._config.offset === 'function') {
} else if (typeof offset === 'function') {
offset = (popper, reference, placement) => {
return offset({ popper, reference, placement }, this._element)
}

View file

@ -54,6 +54,42 @@ describe('Dropdown', () => {
expect(dropdown.toggle).toHaveBeenCalled()
})
it('should create offset modifier correctly when offset option is a function', () => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
' <button class="btn dropdown-toggle" data-bs-toggle="dropdown">Dropdown</button>',
' <div class="dropdown-menu">',
' <a class="dropdown-item" href="#">Secondary link</a>',
' </div>',
'</div>'
].join('')
const getOffset = () => [10, 20]
const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]')
const dropdown = new Dropdown(btnDropdown, {
offset: getOffset
})
const offset = dropdown._getOffset()
expect(typeof offset).toEqual('function')
})
it('should create offset modifier correctly when offset option is a string into data attribute', () => {
fixtureEl.innerHTML = [
'<div class="dropdown">',
' <button class="btn dropdown-toggle" data-bs-toggle="dropdown" data-bs-offset="10,20">Dropdown</button>',
' <div class="dropdown-menu">',
' <a class="dropdown-item" href="#">Secondary link</a>',
' </div>',
'</div>'
].join('')
const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]')
const dropdown = new Dropdown(btnDropdown)
expect(dropdown._getOffset()).toEqual([10, 20])
})
it('should allow to pass config to Popper with `popperConfig`', () => {
fixtureEl.innerHTML = [
'<div class="dropdown">',

View file

@ -899,7 +899,7 @@ Options can be passed via data attributes or JavaScript. For data attributes, ap
<tr>
<td><code>offset</code></td>
<td>number | string | function</td>
<td><code>0</code></td>
<td><code>"0,0"</code></td>
<td>
<p>Offset of the dropdown relative to its target.</p>
<p>When a function is used to determine the offset, it is called with an object containing the popper offsets object data as its first argument. The function must return an array with two numbers: <code>[skidding, distance]</code>. The triggering element DOM node is passed as the second argument.</p>