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