stylescape
Version:
Stylescape is a visual identity framework developed by Scape Agency.
100 lines • 3.38 kB
JavaScript
export class ToggleSwitchManager {
constructor(selectorOrElement, options = {}) {
this.labelElement = null;
this.handleChange = () => {
if (!this.element)
return;
if (this.options.persist) {
localStorage.setItem(this.options.storageKey, String(this.element.checked));
}
this.updateUI();
this.updateAriaState();
this.options.onChange(this.element.checked, this.element);
};
this.element =
typeof selectorOrElement === "string"
? document.querySelector(selectorOrElement)
: selectorOrElement;
this.options = {
checked: options.checked ?? false,
storageKey: options.storageKey ?? this.element?.id ?? "toggle-state",
persist: options.persist ?? false,
onChange: options.onChange ?? (() => { }),
onClass: options.onClass ?? "toggle--on",
offClass: options.offClass ?? "toggle--off",
onLabel: options.onLabel ?? "",
offLabel: options.offLabel ?? "",
};
if (!this.element) {
console.warn("[Stylescape] ToggleSwitchManager element not found");
return;
}
this.init();
}
get isOn() {
return this.element?.checked ?? false;
}
set isOn(value) {
if (!this.element)
return;
this.element.checked = value;
this.handleChange();
}
toggle() {
this.isOn = !this.isOn;
}
on() {
this.isOn = true;
}
off() {
this.isOn = false;
}
destroy() {
this.element?.removeEventListener("change", this.handleChange);
this.element = null;
}
init() {
if (!this.element)
return;
if (this.options.persist) {
const stored = localStorage.getItem(this.options.storageKey);
if (stored !== null) {
this.element.checked = stored === "true";
}
else {
this.element.checked = this.options.checked;
}
}
else {
this.element.checked = this.options.checked;
}
if (this.element.id) {
this.labelElement = document.querySelector(`label[for="${this.element.id}"]`);
}
this.element.setAttribute("role", "switch");
this.updateAriaState();
this.element.addEventListener("change", this.handleChange);
this.updateUI();
}
updateUI() {
if (!this.element)
return;
const parent = this.element.parentElement;
parent?.classList.toggle(this.options.onClass, this.element.checked);
parent?.classList.toggle(this.options.offClass, !this.element.checked);
if (this.labelElement &&
(this.options.onLabel || this.options.offLabel)) {
const label = this.element.checked
? this.options.onLabel
: this.options.offLabel;
if (label) {
this.labelElement.textContent = label;
}
}
}
updateAriaState() {
this.element?.setAttribute("aria-checked", String(this.element?.checked ?? false));
}
}
export default ToggleSwitchManager;
//# sourceMappingURL=ToggleSwitchManager.js.map