This repository has been archived on 2024-10-24. You can view files and clone it, but cannot push or open issues or pull requests.
fradrive-old/frontend/src/utils/show-hide/show-hide.js
2019-12-18 11:47:25 +01:00

80 lines
2.2 KiB
JavaScript

import { Utility } from '../../core/utility';
import { StorageManager, LOCATION } from '../../lib/storage-manager/storage-manager';
import './show-hide.sass';
const SHOW_HIDE_LOCAL_STORAGE_KEY = 'SHOW_HIDE';
const SHOW_HIDE_INITIALIZED_CLASS = 'show-hide--initialized';
const SHOW_HIDE_COLLAPSED_CLASS = 'show-hide--collapsed';
const SHOW_HIDE_TOGGLE_CLASS = 'show-hide__toggle';
const SHOW_HIDE_TOGGLE_RIGHT_CLASS = 'show-hide__toggle--right';
@Utility({
selector: '[uw-show-hide]',
})
export class ShowHide {
_showHideId;
_element;
_storageManager = new StorageManager(SHOW_HIDE_LOCAL_STORAGE_KEY, '1.0.0', { location: LOCATION.LOCAL });
constructor(element) {
if (!element) {
throw new Error('ShowHide utility cannot be setup without an element!');
}
this._element = element;
if (this._element.classList.contains(SHOW_HIDE_INITIALIZED_CLASS)) {
return false;
}
// register click listener
this._addClickListener();
// param showHideId
if (this._element.dataset.showHideId) {
this._showHideId = this._element.dataset.showHideId;
}
// param showHideCollapsed
let collapsed = false;
if (this._element.dataset.showHideCollapsed !== undefined) {
collapsed = true;
}
if (this._showHideId) {
let storageCollapsed = this._storageManager.load(this._showHideId);
if (typeof storageCollapsed !== 'undefined') {
collapsed = storageCollapsed;
}
}
this._element.parentElement.classList.toggle(SHOW_HIDE_COLLAPSED_CLASS, collapsed);
// param showHideAlign
const alignment = this._element.dataset.showHideAlign;
if (alignment === 'right') {
this._element.classList.add(SHOW_HIDE_TOGGLE_RIGHT_CLASS);
}
// mark as initialized
this._element.classList.add(SHOW_HIDE_INITIALIZED_CLASS, SHOW_HIDE_TOGGLE_CLASS);
}
destroy() {
this._element.removeEventListener('click', this._clickHandler);
}
_addClickListener() {
this._element.addEventListener('click', this._clickHandler);
}
_clickHandler = () => {
const newState = this._element.parentElement.classList.toggle(SHOW_HIDE_COLLAPSED_CLASS);
if (this._showHideId) {
this._storageManager.save(this._showHideId, newState);
}
}
}