minsky-kit
Version:
Kit of components for MINSKY web agency
95 lines (78 loc) • 2.17 kB
JavaScript
// imports
import Component from "./Component";
import { strToCssClass } from "../utils/css";
// static const
// class definition
export default class Hamburger extends Component {
// static properties
// constructor
constructor(args = {}, objectName = "Hamburger") {
// preprocess args
if (args instanceof Element) args = { $el: args };
if (args instanceof NodeList) args = { $el: args[0] };
if (typeof args === "string" || !args)
args = {
$el: document.querySelector(args || ".hamburger:not(.hamburger--ready"),
};
// call super
super(args, objectName);
// set properties
this._skipStateChangeOnClick = !!args.skipStateChangeOnClick;
// add listeners
if (this.$el)
this.$el.addEventListener(
"click",
this.blm.add("hamburger.click", onHamburgerClick)
);
}
// methods
activate(silent = false) {
if (!this.active) {
this.$el.classList.add(strToCssClass("hamburger", null, "active"));
if (!silent) this.dispatch("activate");
this.$el.setAttribute('aria-expanded', true);
}
}
deactivate(silent = false) {
if (this.active) {
this.$el.classList.remove(strToCssClass("hamburger", null, "active"));
if (!silent) this.dispatch("deactivate");
this.$el.setAttribute('aria-expanded', false);
}
}
toggle(silent = false) {
this.active = !this.active;
if (!silent) this.dispatch("toggle", { active: this.active });
}
destroy() {
// remove listeners
this.$el.removeEventListener("click", this.blm.remove("hamburger.click"));
this.deactivate(true);
// destroy super
super.destroy();
}
// getters & setters
get active() {
return this.$el.classList.contains("hamburger--active");
}
set active(value) {
if (this.active !== value) {
if (value === true) {
this.activate();
} else {
this.deactivate();
}
}
}
// static methods
}
// event lsiteners
function onHamburgerClick(e) {
e.preventDefault();
this.dispatch("click", {
originalEvent: e,
});
if (!this._skipStateChangeOnClick) {
this.toggle();
}
}