Files
myep/assets/controllers/drawer_controller.js
T

36 lines
999 B
JavaScript

import { Controller } from '@hotwired/stimulus'
/*
* The sidebar as a drawer on small screens: a modal <dialog> (target "dialog"), so focus stays inside
* and Escape closes it. A click on the dimmed page beside it closes it too, and so does widening the
* window until the sidebar shows (lg).
*/
export default class extends Controller {
static targets = ['dialog']
connect () {
this.wide = window.matchMedia('(min-width: 64rem)')
this.onWide = (event) => event.matches && this.close()
this.wide.addEventListener('change', this.onWide)
}
disconnect () {
this.wide.removeEventListener('change', this.onWide)
}
open () {
this.dialogTarget.showModal()
}
close () {
this.dialogTarget.close()
}
// a click on the dialog element itself, not on its content, is a click on the backdrop
closeOnBackdrop (event) {
if (event.target === this.dialogTarget) {
this.close()
}
}
}