Skip to content

Commit

Permalink
Feat: add resize handler to Offcanvas.js.
Browse files Browse the repository at this point in the history
If we could use as default the `.offcanvas` class without modifiers, we then, could add a simplified selector
The selector itself, ignores the .offcanvas class as it doesn't have any responsive behavior
The `aria-modal` addon is to protect us, selection backdrop elements
  • Loading branch information
GeoSot authored and mdo committed Apr 16, 2022
1 parent a6c2a61 commit 9db4f62
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
17 changes: 9 additions & 8 deletions js/src/offcanvas.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const EVENT_SHOWN = `shown${EVENT_KEY}`
const EVENT_HIDE = `hide${EVENT_KEY}`
const EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY}`
const EVENT_HIDDEN = `hidden${EVENT_KEY}`
const EVENT_RESIZE = `resize${EVENT_KEY}`
const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`
const EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY}`

Expand Down Expand Up @@ -205,14 +206,6 @@ class Offcanvas extends BaseComponent {

this.hide()
})

EventHandler.on(window, 'resize', () => {
// Add this check to help js be aligned with css changes on responsive offcanvas
if (this._isShown && getComputedStyle(this._element).position !== 'fixed') {
// this._backdrop.hide()
this.hide()
}
})
}

// Static
Expand Down Expand Up @@ -271,6 +264,14 @@ EventHandler.on(window, EVENT_LOAD_DATA_API, () => {
}
})

EventHandler.on(window, EVENT_RESIZE, () => {
for (const element of SelectorEngine.find('[aria-modal][class*=show][class*=offcanvas-]')) {
if (getComputedStyle(element).position !== 'fixed') {
Offcanvas.getOrCreateInstance(element).hide()
}
}
})

enableDismissTrigger(Offcanvas)

/**
Expand Down
22 changes: 22 additions & 0 deletions js/tests/unit/offcanvas.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,28 @@ describe('Offcanvas', () => {
offCanvas.show()
})
})

it('should call `hide` on resize, if element\'s position is not fixed any more', () => {
return new Promise(resolve => {
fixtureEl.innerHTML = '<div class="offcanvas-lg"></div>'

const offCanvasEl = fixtureEl.querySelector('div')
const offCanvas = new Offcanvas(offCanvasEl)

spyOn(offCanvas, 'hide').and.callThrough()

offCanvasEl.addEventListener('shown.bs.offcanvas', () => {
const resizeEvent = createEvent('resize')
offCanvasEl.style.removeProperty('position')

window.dispatchEvent(resizeEvent)
expect(offCanvas.hide).toHaveBeenCalled()
resolve()
})

offCanvas.show()
})
})
})

describe('config', () => {
Expand Down

0 comments on commit 9db4f62

Please sign in to comment.