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/inputs/checkbox.js
2021-08-30 11:17:03 +00:00

63 lines
1.8 KiB
JavaScript

import { Utility } from '../../core/utility';
import './checkbox.sass';
const CHECKBOX_CLASS = 'checkbox';
const RADIOBOX_CLASS = 'radiobox';
const CHECKBOX_INITIALIZED_CLASS = 'checkbox--initialized';
@Utility({
selector: 'input[type="checkbox"]:not([uw-no-checkbox]), input[type="radio"]:not([uw-no-radiobox])',
})
export class Checkbox {
_element;
_wrapperEl;
constructor(element) {
if (!element) {
throw new Error('Checkbox utility cannot be setup without an element!');
}
this._element = element;
const isRadio = this._element.type === 'radio';
const box_class = isRadio ? RADIOBOX_CLASS : CHECKBOX_CLASS;
if (isRadio && this._element.closest('.radio-group')) {
// Don't initialize radiobox, if radio is part of a group
return false;
}
if (this._element.classList.contains(CHECKBOX_INITIALIZED_CLASS)) {
// throw new Error('Checkbox utility already initialized!');
return false;
}
if (this._element.parentElement.classList.contains(box_class)) {
// throw new Error('Checkbox element\'s wrapper already has class '' + box_class + ''!');
return false;
}
const siblingEl = this._element.nextSibling;
const parentEl = this._element.parentElement;
this._wrapperEl = document.createElement('div');
this._wrapperEl.classList.add(box_class);
const labelEl = document.createElement('label');
labelEl.setAttribute('for', element.id);
this._wrapperEl.appendChild(element);
this._wrapperEl.appendChild(labelEl);
parentEl.insertBefore(this._wrapperEl, siblingEl);
this._element.classList.add(CHECKBOX_INITIALIZED_CLASS);
}
destroy() {
if (this._wrapperEl !== undefined)
this._wrapperEl.remove();
this._element.classList.remove(CHECKBOX_INITIALIZED_CLASS);
}
}