@carry0987/check-box
Advanced tools
Comparing version 2.0.13 to 2.1.0
@@ -56,3 +56,3 @@ function reportError(...error) { | ||
function isObject(item) { | ||
return typeof item === 'object' && item !== null && !Array.isArray(item); | ||
return typeof item === 'object' && item !== null && !isArray(item); | ||
} | ||
@@ -62,7 +62,21 @@ function isArray(item) { | ||
} | ||
function isEmpty(str) { | ||
if (typeof str === 'number') { | ||
function isEmpty(value) { | ||
// Check for number | ||
if (typeof value === 'number') { | ||
return false; | ||
} | ||
return !str || (typeof str === 'string' && str.length === 0); | ||
// Check for string | ||
if (typeof value === 'string' && value.length === 0) { | ||
return true; | ||
} | ||
// Check for array | ||
if (isArray(value) && value.length === 0) { | ||
return true; | ||
} | ||
// Check for object | ||
if (isObject(value) && Object.keys(value).length === 0) { | ||
return true; | ||
} | ||
// Check for any falsy values | ||
return !value; | ||
} | ||
@@ -81,3 +95,3 @@ function deepMerge(target, ...sources) { | ||
if (!target[targetKey] || typeof target[targetKey] !== 'object') { | ||
target[targetKey] = Array.isArray(value) ? [] : {}; | ||
target[targetKey] = isArray(value) ? [] : {}; | ||
} | ||
@@ -139,3 +153,10 @@ deepMerge(target[targetKey], value); | ||
function generateRandom(length = 8) { | ||
return Math.random().toString(36).substring(2, 2 + length); | ||
let result = ''; | ||
const characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; | ||
const charactersLength = characters.length; | ||
for (let i = 0; i < length; i++) { | ||
const randomIndex = Math.floor(Math.random() * charactersLength); | ||
result += characters[randomIndex]; | ||
} | ||
return result; | ||
} | ||
@@ -309,2 +330,12 @@ | ||
} | ||
static toggleDisableStatus(ele, disabled) { | ||
if (disabled) { | ||
ele.disabled = true; | ||
ele.setAttribute('disabled', 'disabled'); | ||
} | ||
else { | ||
ele.disabled = false; | ||
ele.removeAttribute('disabled'); | ||
} | ||
} | ||
static toggleCheckAll(eles, total) { | ||
@@ -374,35 +405,5 @@ if (eles.length === 0) | ||
function styleInject(css, ref) { | ||
if ( ref === void 0 ) ref = {}; | ||
var insertAt = ref.insertAt; | ||
if (typeof document === 'undefined') { return; } | ||
var head = document.head || document.getElementsByTagName('head')[0]; | ||
var style = document.createElement('style'); | ||
style.type = 'text/css'; | ||
if (insertAt === 'top') { | ||
if (head.firstChild) { | ||
head.insertBefore(style, head.firstChild); | ||
} else { | ||
head.appendChild(style); | ||
} | ||
} else { | ||
head.appendChild(style); | ||
} | ||
if (style.styleSheet) { | ||
style.styleSheet.cssText = css; | ||
} else { | ||
style.appendChild(document.createTextNode(css)); | ||
} | ||
} | ||
var css_248z = "/* Checkbox */\n.checkbox {\n display: flex;\n align-items: center;\n margin: 5px 0;\n}\n\n.checkbox input[type=\"checkbox\"] {\n position: relative;\n border: none;\n -webkit-appearance: none;\n appearance: none;\n cursor: pointer;\n margin: 0;\n width: auto;\n height: auto;\n}\n\n.checkbox input[type=\"checkbox\"]:focus + .checkmark {\n outline: none;\n border: 2px solid #2196f3;\n}\n\n.checkmark {\n cursor: pointer;\n width: 20px;\n min-width: 20px;\n height: 20px;\n min-height: 20px;\n border: 2px solid #666666;\n position: relative;\n background: white;\n border-radius: 3px;\n transition: background-color 0.2s linear;\n}\n\n.checkmark::after {\n content: '';\n display: block;\n position: absolute;\n width: 100%;\n height: 100%;\n background-repeat: no-repeat;\n background-position: center;\n background-size: contain;\n opacity: 0;\n transition: opacity 0.2s linear;\n}\n\n.checkbox input[type=\"checkbox\"]:checked + .checkmark::after,\n.checkbox input[type=\"checkbox\"]:disabled + .checkmark::after {\n opacity: 1;\n}\n\n.checkbox input[type=\"checkbox\"]:checked + .checkmark {\n border-color: #2196f3;\n background-color: #2196f3;\n}\n\n.checkbox input[type=\"checkbox\"]:disabled + .checkmark {\n cursor: not-allowed;\n border-color: #999999;\n}\n\n.checkbox input[type=\"checkbox\"]:disabled + .checkmark::after {\n background-color: #999999;\n}\n\n.checkbox-label {\n margin-left: 5px;\n}\n\n.checkbox-labeled {\n cursor: pointer;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n"; | ||
styleInject(css_248z); | ||
class CheckBox { | ||
static instances = []; | ||
static version = '2.0.13'; | ||
static version = '2.1.0'; | ||
static firstLoad = true; | ||
@@ -563,2 +564,6 @@ element = null; | ||
this.checkAllElement.push(cloneEle); | ||
// Disable check all if there are no input checkboxes | ||
if (this.total.input.length === 0) { | ||
Utils.toggleDisableStatus(cloneEle, true); | ||
} | ||
// Set the initial check status based on provided options | ||
@@ -565,0 +570,0 @@ if (this.options.checked === true || checkAll.checked) { |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).CheckBox=t()}(this,(function(){"use strict";function e(...e){console.error(...e)}function t(e){throw new Error(e)}var n=Object.freeze({__proto__:null,reportError:e,throwError:t});function l(e,t,n){if("string"!=typeof e)return e;let l=document;return null===t&&n?l=n:t&&t instanceof Node&&"querySelector"in t?l=t:n&&n instanceof Node&&"querySelector"in n&&(l=n),"all"===t?l.querySelectorAll(e):l.querySelector(e)}function i(e,t={},n=""){let l=document.createElement(e);for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&("textContent"===e||"innerText"===e?l.textContent=t[e]:l.setAttribute(e,t[e]));return n&&(l.textContent=n),l}let c="utils-style";const o={from:".utils",to:".utils-"};function s(e){return Array.isArray(e)}function h(e){return"number"!=typeof e&&(!e||"string"==typeof e&&0===e.length)}function a(e,...t){if(!t.length)return e;const n=t.shift();if(n)for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)){const i=n[t],c=t;"object"==typeof(l=i)&&null!==l&&!Array.isArray(l)||s(i)?(e[c]&&"object"==typeof e[c]||(e[c]=Array.isArray(i)?[]:{}),a(e[c],i)):e[c]=i}var l;return a(e,...t)}function r(e){c=e}function d(e,t){o.from=e,o.to=t}function u(e,t=null){t=h(t)?"":t;let n=i("style");n.id=c+t,n.textContent="",document.head.append(n);let l=n.sheet;for(let n in e)e.hasOwnProperty(n)&&p(l,n,k(e[n]),t)}function k(e){let t="";for(let[n,l]of Object.entries(e))n=n.replace(/([A-Z])/g,(e=>`-${e[0].toLowerCase()}`)),t+=`${n}:${l};`;return t}function p(e,t,n,l=null){l=h(l)?"":l;let i=t.replace(o.from,o.to+l);e.insertRule(i+"{"+n+"}",0)}function g(e=null){const t=h(e)?"":e;let n=l("#"+c+t);n&&n.parentNode&&n.parentNode.removeChild(n)}function f(e=8){return Math.random().toString(36).substring(2,2+e)}function m(e,t,n){return new CustomEvent(e,{detail:t,...n})}var C=Object.freeze({__proto__:null,addEventListener:function(e,t,n,l){e.addEventListener(t,n,l)},createEvent:m,dispatchEvent:function(n,l=document,i,c){try{if("string"==typeof n){let e=m(n,i,c);return l.dispatchEvent(e)}if(n instanceof Event)return l.dispatchEvent(n);t("Invalid event type")}catch(t){return e("Dispatch Event Error:",t),!1}},removeEventListener:function(e,t,n,l){e.removeEventListener(t,n,l)}});class b{static throwError=n.throwError;static getElem=l;static deepMerge=a;static generateRandom=f;static injectStylesheet=u;static removeStylesheet=g;static setStylesheetId=r;static setReplaceRule=d;static isEmpty=h;static createEvent=C.createEvent;static addEventListener=C.addEventListener;static dispatchEvent=C.dispatchEvent;static getTemplate(e){return`\n <div class="checkbox check-box-${e=e.toString()}">\n <span class="checkmark"></span>\n <label class="checkbox-label"></label>\n </div>\n `}static getCheckAllElements(e){if(!e)return[];let t=[];return Array.isArray(e)?e.forEach((e=>{"string"==typeof e?t.push(...b.getElem(e,"all")):e instanceof HTMLInputElement&&t.push(e)})):"string"==typeof e?t.push(...b.getElem(e,"all")):e instanceof HTMLInputElement&&t.push(e),t.filter((e=>null!==e))}static handleCheckboxTitle(e,t){let n,l=e.title||e.dataset.checkboxTitle||null,i=!1,c=null,o=!1;if(t instanceof HTMLLabelElement){const s=t.htmlFor,h=t.dataset.checkboxFor,a=e.dataset.checkboxId;i=!b.isEmpty(e.id)&&s===e.id,o=!b.isEmpty(e.id)&&h===e.id,b.isEmpty(a)||h!==a||(c=b.isEmpty(e.id)&&b.isEmpty(s)?"check-"+b.generateRandom(6):null,o=!0),(o||i)&&(n=t.cloneNode(!0),l=l||t.textContent,t.parentNode.removeChild(t))}return{title:l,remainLabel:i,randomID:c,labelToRestore:n}}static insertCheckbox(e,t,n,c){let o=b.getTemplate(e),s=i("div");s.innerHTML=o.trim();let h=l(".checkmark",s),a=l("label",s),r=t.cloneNode(!0);return r.withID=!0,n&&(r.id=n,r.withID=!1),!0===c&&(a.htmlFor=r.id),h.addEventListener("click",(e=>{e.preventDefault(),r.click(),e.shiftKey&&this.triggerShiftClick(r)})),h.parentNode&&h.parentNode.insertBefore(r,h),t.parentNode.replaceChild(s.firstElementChild||s,t),{cloneEle:r,templateNode:s,labelNode:a}}static insertCheckboxTitle(e,t,n,l){e?(n.textContent=e,!0===t&&(n.classList.add("checkbox-labeled"),n.addEventListener("click",(e=>{e.preventDefault(),l.click(),e.shiftKey&&this.triggerShiftClick(l)})))):n.parentNode.removeChild(n)}static toggleCheckStatus(e,t){t?(e.checked=!0,e.setAttribute("checked","checked")):(e.checked=!1,e.removeAttribute("checked"))}static toggleCheckAll(e,t){0!==e.length&&e.forEach((e=>{if(!t||!t.checked||!t.input)return void b.toggleCheckStatus(e,!1);const n=t.checked.length===t.input.length&&0!==t.checked.length;b.toggleCheckStatus(e,n)}))}static restoreElement(e){if("function"==typeof e.checkBoxChange&&e.removeEventListener("change",e.checkBoxChange),"function"==typeof e.checkAllChange&&e.removeEventListener("change",e.checkAllChange),!1===e.withID&&e.removeAttribute("id"),e.checkBoxChange=void 0,e.removeAttribute("data-checkbox"),e.parentNode){e.parentNode.replaceWith(e)}let t=e.labelToRestore;t&&t.nodeType===Node.ELEMENT_NODE&&e.parentNode?.insertBefore(t,e.nextSibling)}static triggerShiftClick(e){let t=b.createEvent("shift-click",{checkedElement:e});b.dispatchEvent(t,e)}}b.setStylesheetId("checkbox-style"),b.setReplaceRule(".check-box",".check-box-");const E=(e,t=!1)=>{!0===t?console.log("Data Type : "+typeof e,"\nValue : "+e):"boolean"!=typeof t?console.log(t):console.log(e)},y={checked:null,checkMark:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cG9seWxpbmUgcG9pbnRzPSIyMCA2IDkgMTcgNCAxMiI+PC9wb2x5bGluZT48L3N2Zz4=",checkAll:null,allowShiftKey:!1,bindLabel:!0,styles:{},onChange:()=>{},onCheckAll:()=>{}};class v{static instances=[];static version="2.0.13";static firstLoad=!0;element=null;options=y;id=0;allElement=[];total={input:[],checked:[],list:[]};checkAllElement=[];onChangeCallback;onCheckAllCallback;constructor(e,t){this.init(e,t,v.instances.length),v.instances.push(this),1===v.instances.length&&!0===v.firstLoad&&E(`CheckBox is loaded, version: ${v.version}`),v.firstLoad=!1}init(e,t,n){let l=null;return"string"==typeof e?l=b.getElem(e,"all"):e instanceof HTMLInputElement&&(l=[e]),l?(this.id=n,this.element=e,this.options=b.deepMerge({},this.options,t),this.injectStyles(),this.setupCallbacks(),l.forEach(((e,t)=>this.processCheckbox(e,t))),this.updateTotal(),this.options.checkAll&&this.processCheckAll(),this):b.throwError("Cannot find elements : "+e)}injectStyles(){let e={};this.options?.checkMark&&(e={".check-box input[type=checkbox] + .checkmark:after":{"background-image":"url("+this.options.checkMark+")"}}),this.options?.styles&&Object.keys(this.options.styles).length>0&&(e=b.deepMerge({},this.options.styles,e)),e&&b.injectStylesheet(e,this.id.toString())}setupCallbacks(){this.onChange=(e,t)=>{this.options?.onChange&&this.options.onChange(e,t)},this.onCheckAll=e=>{this.options?.onCheckAll&&this.options.onCheckAll(e)}}processCheckbox(e,t){if("checkbox"!==e.type)return;if(e.hasAttribute("data-checkbox"))return;e.setAttribute("data-checkbox","true");let n=e.nextElementSibling,l=this.options.bindLabel??!1,{title:i,remainLabel:c,randomID:o,labelToRestore:s}=b.handleCheckboxTitle(e,n);l=!!c||l,e.checked?b.toggleCheckStatus(e,!0):this.options.checked&&this.updateCheckboxStatus(e,t);let{cloneEle:h,labelNode:a}=b.insertCheckbox(this.id.toString(),e,o,c);b.insertCheckboxTitle(i,l,a,h);let r=this.checkBoxChange.bind(this,!0,h,void 0);h.addEventListener("change",r),h.checkBoxChange=r,this.options.allowShiftKey&&b.addEventListener(h,"shift-click",this.handleShiftClick),this.allElement.push(h),h.labelToRestore=s}updateCheckboxStatus(e,t){const n=this.options.checked;"boolean"==typeof n?b.toggleCheckStatus(e,n):"string"==typeof n||"number"==typeof n?e.value!==n.toString()&&t!==Number(n)||b.toggleCheckStatus(e,!0):Array.isArray(n)&&n.includes(e.value)&&b.toggleCheckStatus(e,!0)}processCheckAll(){const e=b.getCheckAllElements(this.options.checkAll);0!==e.length&&e.forEach((e=>{if(!e||"checkbox"!==e.type)return;if(e.hasAttribute("data-checkbox"))return;e.setAttribute("data-checkbox","true");const t=e.nextElementSibling;let{title:n,remainLabel:l,randomID:i,labelToRestore:c}=b.handleCheckboxTitle(e,t);n&&t&&"LABEL"===t.tagName&&(n=t.textContent||n,t.parentNode?.removeChild(t));const{cloneEle:o,templateNode:s,labelNode:h}=b.insertCheckbox(this.id.toString(),e,i,l);e.parentNode?.replaceChild(s.firstElementChild||s,e),b.insertCheckboxTitle(n,this.options.bindLabel??!1,h,o),o.addEventListener("change",this.checkAllChange),o.checkAllChange=this.checkAllChange,o.labelToRestore=c,this.checkAllElement.push(o),(!0===this.options.checked||e.checked)&&(b.toggleCheckStatus(o,!0),o.dispatchEvent(new Event("change")))}))}checkBoxChange(e,t,n){this.updateTotal(),e&&this.updateCheckAllStatus(),this.onChangeCallback?.(this.total,t),t&&b.toggleCheckStatus(t,n??t.checked),this.dispatchCheckboxChangeEvent()}checkAllChange=e=>{if(!(e.target instanceof HTMLInputElement))return;const t=e.target.checked;this.allElement.forEach((e=>{b.toggleCheckStatus(e,t)})),this.updateTotal(),this.updateCheckAllStatus(),this.checkBoxChange(!1),this.onCheckAllCallback&&this.onCheckAllCallback(t)};updateTotal(){this.total.input=[...this.allElement];const e=this.allElement.filter((e=>e.checked));this.total.checked=this.total.checked.filter((e=>e.checked));const t=e.filter((e=>!this.total.checked.includes(e)));this.total.checked.push(...t),this.total.list=this.total.checked.map((e=>e.value))}updateCheckAllStatus(){if(this.checkAllElement.length>0){const e=this.total.checked.length===this.total.input.length;this.checkAllElement.forEach((t=>{b.toggleCheckStatus(t,e)}))}}dispatchCheckboxChangeEvent(){const e=b.createEvent("checkbox-change",{detail:this.total});b.dispatchEvent(e)}handleShiftClick=e=>{const t=e.detail.checkedElement,n=this.getLastChecked(!0);if(!t||!n)return;let l=this.allElement.indexOf(n),i=this.allElement.indexOf(t);if(n&&-1!==l&&-1!==i){E("Shift-click event detected");const e=Math.min(l,i),n=Math.max(l,i);for(let l=e;l<=n;l++){const e=t.checked,n=this.allElement[l];b.toggleCheckStatus(n,e)}this.updateTotal(),this.updateCheckAllStatus(),this.dispatchCheckboxChangeEvent()}};getLastChecked(e=!1){const t=this.total.checked;let n=e?2:1;return 0===t.length?null:1===t.length?t[0]:t[t.length-n]}destroy(){v.firstLoad=!1,this.allElement.forEach((e=>{b.restoreElement(e)})),this.checkAllElement.length>0&&this.checkAllElement.forEach((e=>{e.checkAllChange&&(b.toggleCheckAll(this.checkAllElement),b.restoreElement(e))})),this.element=null,this.options=y,this.allElement=[],this.total={input:[],checked:[],list:[]},this.checkAllElement=[],b.removeStylesheet(this.id.toString());const e=v.instances.indexOf(this);-1!==e&&v.instances.splice(e,1)}set onChange(e){this.onChangeCallback=e}set onCheckAll(e){this.onCheckAllCallback=e}get elements(){return this.allElement}getCheckBox(){return this.total}refresh(){this.element&&this.init(this.element,this.options,this.id)}static destroyAll(){for(;v.instances.length;){v.instances[0].destroy()}}}return v})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).CheckBox=t()}(this,(function(){"use strict";function e(...e){console.error(...e)}function t(e){throw new Error(e)}var n=Object.freeze({__proto__:null,reportError:e,throwError:t});function l(e,t,n){if("string"!=typeof e)return e;let l=document;return null===t&&n?l=n:t&&t instanceof Node&&"querySelector"in t?l=t:n&&n instanceof Node&&"querySelector"in n&&(l=n),"all"===t?l.querySelectorAll(e):l.querySelector(e)}function i(e,t={},n=""){let l=document.createElement(e);for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&("textContent"===e||"innerText"===e?l.textContent=t[e]:l.setAttribute(e,t[e]));return n&&(l.textContent=n),l}let c="utils-style";const o={from:".utils",to:".utils-"};function s(e){return"object"==typeof e&&null!==e&&!h(e)}function h(e){return Array.isArray(e)}function a(e){return"number"!=typeof e&&("string"==typeof e&&0===e.length||(!(!h(e)||0!==e.length)||(!(!s(e)||0!==Object.keys(e).length)||!e)))}function r(e,...t){if(!t.length)return e;const n=t.shift();if(n)for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)){const l=n[t],i=t;s(l)||h(l)?(e[i]&&"object"==typeof e[i]||(e[i]=h(l)?[]:{}),r(e[i],l)):e[i]=l}return r(e,...t)}function d(e){c=e}function u(e,t){o.from=e,o.to=t}function k(e,t=null){t=a(t)?"":t;let n=i("style");n.id=c+t,n.textContent="",document.head.append(n);let l=n.sheet;for(let n in e)e.hasOwnProperty(n)&&g(l,n,p(e[n]),t)}function p(e){let t="";for(let[n,l]of Object.entries(e))n=n.replace(/([A-Z])/g,(e=>`-${e[0].toLowerCase()}`)),t+=`${n}:${l};`;return t}function g(e,t,n,l=null){l=a(l)?"":l;let i=t.replace(o.from,o.to+l);e.insertRule(i+"{"+n+"}",0)}function f(e=null){const t=a(e)?"":e;let n=l("#"+c+t);n&&n.parentNode&&n.parentNode.removeChild(n)}function b(e=8){let t="";const n="abcdefghijklmnopqrstuvwxyz0123456789";for(let l=0;l<e;l++){t+=n[Math.floor(36*Math.random())]}return t}function m(e,t,n){return new CustomEvent(e,{detail:t,...n})}var C=Object.freeze({__proto__:null,addEventListener:function(e,t,n,l){e.addEventListener(t,n,l)},createEvent:m,dispatchEvent:function(n,l=document,i,c){try{if("string"==typeof n){let e=m(n,i,c);return l.dispatchEvent(e)}if(n instanceof Event)return l.dispatchEvent(n);t("Invalid event type")}catch(t){return e("Dispatch Event Error:",t),!1}},removeEventListener:function(e,t,n,l){e.removeEventListener(t,n,l)}});class E{static throwError=n.throwError;static getElem=l;static deepMerge=r;static generateRandom=b;static injectStylesheet=k;static removeStylesheet=f;static setStylesheetId=d;static setReplaceRule=u;static isEmpty=a;static createEvent=C.createEvent;static addEventListener=C.addEventListener;static dispatchEvent=C.dispatchEvent;static getTemplate(e){return`\n <div class="checkbox check-box-${e=e.toString()}">\n <span class="checkmark"></span>\n <label class="checkbox-label"></label>\n </div>\n `}static getCheckAllElements(e){if(!e)return[];let t=[];return Array.isArray(e)?e.forEach((e=>{"string"==typeof e?t.push(...E.getElem(e,"all")):e instanceof HTMLInputElement&&t.push(e)})):"string"==typeof e?t.push(...E.getElem(e,"all")):e instanceof HTMLInputElement&&t.push(e),t.filter((e=>null!==e))}static handleCheckboxTitle(e,t){let n,l=e.title||e.dataset.checkboxTitle||null,i=!1,c=null,o=!1;if(t instanceof HTMLLabelElement){const s=t.htmlFor,h=t.dataset.checkboxFor,a=e.dataset.checkboxId;i=!E.isEmpty(e.id)&&s===e.id,o=!E.isEmpty(e.id)&&h===e.id,E.isEmpty(a)||h!==a||(c=E.isEmpty(e.id)&&E.isEmpty(s)?"check-"+E.generateRandom(6):null,o=!0),(o||i)&&(n=t.cloneNode(!0),l=l||t.textContent,t.parentNode.removeChild(t))}return{title:l,remainLabel:i,randomID:c,labelToRestore:n}}static insertCheckbox(e,t,n,c){let o=E.getTemplate(e),s=i("div");s.innerHTML=o.trim();let h=l(".checkmark",s),a=l("label",s),r=t.cloneNode(!0);return r.withID=!0,n&&(r.id=n,r.withID=!1),!0===c&&(a.htmlFor=r.id),h.addEventListener("click",(e=>{e.preventDefault(),r.click(),e.shiftKey&&this.triggerShiftClick(r)})),h.parentNode&&h.parentNode.insertBefore(r,h),t.parentNode.replaceChild(s.firstElementChild||s,t),{cloneEle:r,templateNode:s,labelNode:a}}static insertCheckboxTitle(e,t,n,l){e?(n.textContent=e,!0===t&&(n.classList.add("checkbox-labeled"),n.addEventListener("click",(e=>{e.preventDefault(),l.click(),e.shiftKey&&this.triggerShiftClick(l)})))):n.parentNode.removeChild(n)}static toggleCheckStatus(e,t){t?(e.checked=!0,e.setAttribute("checked","checked")):(e.checked=!1,e.removeAttribute("checked"))}static toggleDisableStatus(e,t){t?(e.disabled=!0,e.setAttribute("disabled","disabled")):(e.disabled=!1,e.removeAttribute("disabled"))}static toggleCheckAll(e,t){0!==e.length&&e.forEach((e=>{if(!t||!t.checked||!t.input)return void E.toggleCheckStatus(e,!1);const n=t.checked.length===t.input.length&&0!==t.checked.length;E.toggleCheckStatus(e,n)}))}static restoreElement(e){if("function"==typeof e.checkBoxChange&&e.removeEventListener("change",e.checkBoxChange),"function"==typeof e.checkAllChange&&e.removeEventListener("change",e.checkAllChange),!1===e.withID&&e.removeAttribute("id"),e.checkBoxChange=void 0,e.removeAttribute("data-checkbox"),e.parentNode){e.parentNode.replaceWith(e)}let t=e.labelToRestore;t&&t.nodeType===Node.ELEMENT_NODE&&e.parentNode?.insertBefore(t,e.nextSibling)}static triggerShiftClick(e){let t=E.createEvent("shift-click",{checkedElement:e});E.dispatchEvent(t,e)}}E.setStylesheetId("checkbox-style"),E.setReplaceRule(".check-box",".check-box-");const y=(e,t=!1)=>{!0===t?console.log("Data Type : "+typeof e,"\nValue : "+e):"boolean"!=typeof t?console.log(t):console.log(e)},v={checked:null,checkMark:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cG9seWxpbmUgcG9pbnRzPSIyMCA2IDkgMTcgNCAxMiI+PC9wb2x5bGluZT48L3N2Zz4=",checkAll:null,allowShiftKey:!1,bindLabel:!0,styles:{},onChange:()=>{},onCheckAll:()=>{}};class x{static instances=[];static version="2.1.0";static firstLoad=!0;element=null;options=v;id=0;allElement=[];total={input:[],checked:[],list:[]};checkAllElement=[];onChangeCallback;onCheckAllCallback;constructor(e,t){this.init(e,t,x.instances.length),x.instances.push(this),1===x.instances.length&&!0===x.firstLoad&&y(`CheckBox is loaded, version: ${x.version}`),x.firstLoad=!1}init(e,t,n){let l=null;return"string"==typeof e?l=E.getElem(e,"all"):e instanceof HTMLInputElement&&(l=[e]),l?(this.id=n,this.element=e,this.options=E.deepMerge({},this.options,t),this.injectStyles(),this.setupCallbacks(),l.forEach(((e,t)=>this.processCheckbox(e,t))),this.updateTotal(),this.options.checkAll&&this.processCheckAll(),this):E.throwError("Cannot find elements : "+e)}injectStyles(){let e={};this.options?.checkMark&&(e={".check-box input[type=checkbox] + .checkmark:after":{"background-image":"url("+this.options.checkMark+")"}}),this.options?.styles&&Object.keys(this.options.styles).length>0&&(e=E.deepMerge({},this.options.styles,e)),e&&E.injectStylesheet(e,this.id.toString())}setupCallbacks(){this.onChange=(e,t)=>{this.options?.onChange&&this.options.onChange(e,t)},this.onCheckAll=e=>{this.options?.onCheckAll&&this.options.onCheckAll(e)}}processCheckbox(e,t){if("checkbox"!==e.type)return;if(e.hasAttribute("data-checkbox"))return;e.setAttribute("data-checkbox","true");let n=e.nextElementSibling,l=this.options.bindLabel??!1,{title:i,remainLabel:c,randomID:o,labelToRestore:s}=E.handleCheckboxTitle(e,n);l=!!c||l,e.checked?E.toggleCheckStatus(e,!0):this.options.checked&&this.updateCheckboxStatus(e,t);let{cloneEle:h,labelNode:a}=E.insertCheckbox(this.id.toString(),e,o,c);E.insertCheckboxTitle(i,l,a,h);let r=this.checkBoxChange.bind(this,!0,h,void 0);h.addEventListener("change",r),h.checkBoxChange=r,this.options.allowShiftKey&&E.addEventListener(h,"shift-click",this.handleShiftClick),this.allElement.push(h),h.labelToRestore=s}updateCheckboxStatus(e,t){const n=this.options.checked;"boolean"==typeof n?E.toggleCheckStatus(e,n):"string"==typeof n||"number"==typeof n?e.value!==n.toString()&&t!==Number(n)||E.toggleCheckStatus(e,!0):Array.isArray(n)&&n.includes(e.value)&&E.toggleCheckStatus(e,!0)}processCheckAll(){const e=E.getCheckAllElements(this.options.checkAll);0!==e.length&&e.forEach((e=>{if(!e||"checkbox"!==e.type)return;if(e.hasAttribute("data-checkbox"))return;e.setAttribute("data-checkbox","true");const t=e.nextElementSibling;let{title:n,remainLabel:l,randomID:i,labelToRestore:c}=E.handleCheckboxTitle(e,t);n&&t&&"LABEL"===t.tagName&&(n=t.textContent||n,t.parentNode?.removeChild(t));const{cloneEle:o,templateNode:s,labelNode:h}=E.insertCheckbox(this.id.toString(),e,i,l);e.parentNode?.replaceChild(s.firstElementChild||s,e),E.insertCheckboxTitle(n,this.options.bindLabel??!1,h,o),o.addEventListener("change",this.checkAllChange),o.checkAllChange=this.checkAllChange,o.labelToRestore=c,this.checkAllElement.push(o),0===this.total.input.length&&E.toggleDisableStatus(o,!0),(!0===this.options.checked||e.checked)&&(E.toggleCheckStatus(o,!0),o.dispatchEvent(new Event("change")))}))}checkBoxChange(e,t,n){this.updateTotal(),e&&this.updateCheckAllStatus(),this.onChangeCallback?.(this.total,t),t&&E.toggleCheckStatus(t,n??t.checked),this.dispatchCheckboxChangeEvent()}checkAllChange=e=>{if(!(e.target instanceof HTMLInputElement))return;const t=e.target.checked;this.allElement.forEach((e=>{E.toggleCheckStatus(e,t)})),this.updateTotal(),this.updateCheckAllStatus(),this.checkBoxChange(!1),this.onCheckAllCallback&&this.onCheckAllCallback(t)};updateTotal(){this.total.input=[...this.allElement];const e=this.allElement.filter((e=>e.checked));this.total.checked=this.total.checked.filter((e=>e.checked));const t=e.filter((e=>!this.total.checked.includes(e)));this.total.checked.push(...t),this.total.list=this.total.checked.map((e=>e.value))}updateCheckAllStatus(){if(this.checkAllElement.length>0){const e=this.total.checked.length===this.total.input.length;this.checkAllElement.forEach((t=>{E.toggleCheckStatus(t,e)}))}}dispatchCheckboxChangeEvent(){const e=E.createEvent("checkbox-change",{detail:this.total});E.dispatchEvent(e)}handleShiftClick=e=>{const t=e.detail.checkedElement,n=this.getLastChecked(!0);if(!t||!n)return;let l=this.allElement.indexOf(n),i=this.allElement.indexOf(t);if(n&&-1!==l&&-1!==i){y("Shift-click event detected");const e=Math.min(l,i),n=Math.max(l,i);for(let l=e;l<=n;l++){const e=t.checked,n=this.allElement[l];E.toggleCheckStatus(n,e)}this.updateTotal(),this.updateCheckAllStatus(),this.dispatchCheckboxChangeEvent()}};getLastChecked(e=!1){const t=this.total.checked;let n=e?2:1;return 0===t.length?null:1===t.length?t[0]:t[t.length-n]}destroy(){x.firstLoad=!1,this.allElement.forEach((e=>{E.restoreElement(e)})),this.checkAllElement.length>0&&this.checkAllElement.forEach((e=>{e.checkAllChange&&(E.toggleCheckAll(this.checkAllElement),E.restoreElement(e))})),this.element=null,this.options=v,this.allElement=[],this.total={input:[],checked:[],list:[]},this.checkAllElement=[],E.removeStylesheet(this.id.toString());const e=x.instances.indexOf(this);-1!==e&&x.instances.splice(e,1)}set onChange(e){this.onChangeCallback=e}set onCheckAll(e){this.onCheckAllCallback=e}get elements(){return this.allElement}getCheckBox(){return this.total}refresh(){this.element&&this.init(this.element,this.options,this.id)}static destroyAll(){for(;x.instances.length;){x.instances[0].destroy()}}}return x})); |
{ | ||
"name": "@carry0987/check-box", | ||
"version": "2.0.13", | ||
"version": "2.1.0", | ||
"description": "A library for create and manage checkbox elements", | ||
@@ -8,7 +8,10 @@ "type": "module", | ||
"module": "dist/checkBox.esm.js", | ||
"types": "dist/checkBox.d.ts", | ||
"scripts": { | ||
"test": "echo \"Error: no test specified\" && exit 1", | ||
"start": "rollup --config rollup.config.js", | ||
"build": "rollup --config rollup.config.js --environment BUILD:production" | ||
"types": "dist/index.d.ts", | ||
"exports": { | ||
".": { | ||
"umd": "./dist/checkBox.min.js", | ||
"import": "./dist/checkBox.esm.js", | ||
"types": "./dist/index.d.ts" | ||
}, | ||
"./theme/checkBox.min.css": "./dist/theme/checkBox.min.css" | ||
}, | ||
@@ -32,13 +35,18 @@ "files": [ | ||
"devDependencies": { | ||
"@carry0987/utils": "^3.3.13", | ||
"@rollup/plugin-node-resolve": "^15.2.3", | ||
"@rollup/plugin-replace": "^5.0.5", | ||
"@carry0987/utils": "^3.7.4", | ||
"@rollup/plugin-node-resolve": "^15.3.0", | ||
"@rollup/plugin-replace": "^6.0.1", | ||
"@rollup/plugin-terser": "^0.4.4", | ||
"@rollup/plugin-typescript": "^11.1.6", | ||
"rollup": "^4.17.2", | ||
"rollup-plugin-delete": "^2.0.0", | ||
"@rollup/plugin-typescript": "^12.1.0", | ||
"rollup": "^4.22.5", | ||
"rollup-plugin-delete": "^2.1.0", | ||
"rollup-plugin-dts": "^6.1.1", | ||
"rollup-plugin-postcss": "^4.0.2", | ||
"tslib": "^2.6.2" | ||
"tslib": "^2.7.0" | ||
}, | ||
"scripts": { | ||
"test": "echo \"Error: no test specified\" && exit 1", | ||
"start": "rollup --config rollup.config.ts --configPlugin typescript", | ||
"build": "rollup --config rollup.config.ts --configPlugin typescript --environment BUILD:production" | ||
} | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
834
45434