Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@carry0987/check-box

Package Overview
Dependencies
Maintainers
1
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@carry0987/check-box - npm Package Compare versions

Comparing version 2.0.8 to 2.0.9

9

dist/checkBox.d.ts

@@ -5,3 +5,3 @@ type CheckedTargets = boolean | string | number | Array<string | number> | null;

interface OnChangeCallback {
(total: TotalCheckbox, target?: HTMLInputElement): void;
(total: TotalCheckbox, target?: EnhancedElement): void;
}

@@ -15,2 +15,3 @@ interface OnCheckAllCallback {

checkAll: CheckAllButtons;
allowShiftKey: boolean;
bindLabel: boolean;

@@ -22,4 +23,4 @@ styles: object;

interface TotalCheckbox {
input: HTMLInputElement[];
checked: HTMLInputElement[];
input: EnhancedElement[];
checked: EnhancedElement[];
list: string[];

@@ -44,3 +45,2 @@ }

private checkAllElement;
private lastChecked;
private onChangeCallback?;

@@ -61,2 +61,3 @@ private onCheckAllCallback?;

private handleShiftClick;
private getLastChecked;
private destroy;

@@ -63,0 +64,0 @@ set onChange(callback: OnChangeCallback);

@@ -182,2 +182,3 @@ function reportError(...error) {

static createEvent = eventUtils.createEvent;
static addEventListener = eventUtils.addEventListener;
static dispatchEvent = eventUtils.dispatchEvent;

@@ -262,4 +263,3 @@ static getTemplate(id) {

if (e.shiftKey) {
let event = Utils.createEvent('shift-click', { detail: { checkedElement: cloneEle } });
Utils.dispatchEvent(event, cloneEle);
this.triggerShiftClick(cloneEle);
}

@@ -287,4 +287,3 @@ });

if (e.shiftKey) {
let event = Utils.createEvent('shift-click', { detail: { checkedElement: cloneEle } });
Utils.dispatchEvent(event, cloneEle);
this.triggerShiftClick(cloneEle);
}

@@ -338,2 +337,6 @@ });

}
static triggerShiftClick(cloneEle) {
let event = Utils.createEvent('shift-click', { checkedElement: cloneEle });
Utils.dispatchEvent(event, cloneEle);
}
}

@@ -359,2 +362,3 @@ Utils.setStylesheetId('checkbox-style');

checkAll: null,
allowShiftKey: false,
bindLabel: true,

@@ -398,3 +402,3 @@ styles: {},

static instances = [];
static version = '2.0.8';
static version = '2.0.9';
static firstLoad = true;

@@ -407,3 +411,2 @@ element = null;

checkAllElement = [];
lastChecked = null;
// Methods for external use

@@ -434,2 +437,4 @@ onChangeCallback;

elem.forEach((ele, index) => this.processCheckbox(ele, index));
// Update the total and check all status
this.updateTotal();
// Set up the check all checkbox, if specified in options

@@ -494,6 +499,5 @@ if (this.options.checkAll) {

// Add event listener for shift-click
// cloneEle.addEventListener('shift-click', (e: Event) => this.handleShiftClick(cloneEle));
// if (!this.lastChecked) {
// this.lastChecked = cloneEle.checked ? cloneEle : null;
// }
if (this.options.allowShiftKey) {
Utils.addEventListener(cloneEle, 'shift-click', this.handleShiftClick);
}
// Store the cloned checkbox

@@ -567,3 +571,2 @@ this.allElement.push(cloneEle);

Utils.toggleCheckStatus(target, checkStatus ?? target.checked);
// this.lastChecked = (target.checked) ? target : null;
}

@@ -589,13 +592,14 @@ this.dispatchCheckboxChangeEvent();

updateTotal() {
const total = this.total;
total.list = [];
total.input = [];
total.checked = [];
this.allElement.forEach((checkbox) => {
total.input.push(checkbox);
if (checkbox.checked) {
total.list.push(checkbox.value);
total.checked.push(checkbox);
}
});
// Update total.input to reflect the current list of checkboxes
this.total.input = [...this.allElement];
// Get the current list of checked elements
const currentChecked = this.allElement.filter(checkbox => checkbox.checked);
// Keep the order of elements in total.checked the same, add new checked elements to the end
// And filter out elements that are no longer checked
this.total.checked = this.total.checked.filter(checkbox => checkbox.checked);
// Find new checked elements and add them to the end
const newChecked = currentChecked.filter(checkbox => !this.total.checked.includes(checkbox));
this.total.checked.push(...newChecked);
// Update total.list to reflect the new order of checked items
this.total.list = this.total.checked.map(checkbox => checkbox.value);
}

@@ -616,16 +620,34 @@ updateCheckAllStatus() {

}
handleShiftClick(target) {
if (!this.lastChecked) {
this.checkBoxChange(false, target);
handleShiftClick = (e) => {
const target = e.detail.checkedElement;
const lastChecked = this.getLastChecked(true);
if (!target || !lastChecked)
return;
}
let start = this.allElement.indexOf(this.lastChecked);
let start = this.allElement.indexOf(lastChecked);
let end = this.allElement.indexOf(target);
let from = Math.min(start, end);
let to = Math.max(start, end);
// Use this.lastChecked.checked to determine the state to apply between the range
for (let i = from; i <= to; i++) {
this.checkBoxChange(true, this.allElement[i], this.lastChecked.checked);
// If there's a last checked element and the shift key is being held down
// Check/uncheck all checkboxes from lastChecked to the target checkbox
if (lastChecked && start !== -1 && end !== -1) {
reportInfo('Shift-click event detected');
const min = Math.min(start, end);
const max = Math.max(start, end);
for (let i = min; i <= max; i++) {
const shouldBeChecked = target.checked; // Match the target's checked state
const checkbox = this.allElement[i];
// Update the checked status of the checkbox
Utils.toggleCheckStatus(checkbox, shouldBeChecked);
}
this.updateTotal();
this.updateCheckAllStatus();
this.dispatchCheckboxChangeEvent();
}
this.lastChecked = target; // Update the last checked item to current target
};
getLastChecked(excludeShift = false) {
const checkedElements = this.total.checked;
let offset = !excludeShift ? 1 : 2;
if (checkedElements.length === 0)
return null;
if (checkedElements.length === 1)
return checkedElements[0];
return checkedElements[checkedElements.length - offset];
}

@@ -632,0 +654,0 @@ destroy() {

@@ -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 c(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 i="utils-style";const o={from:".utils",to:".utils-"};function s(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 c=n[t],i=t;"object"!=typeof(l=c)||null===l||Array.isArray(l)?e[i]=c:(e[i]&&"object"==typeof e[i]||(e[i]={}),s(e[i],c))}var l;return s(e,...t)}function h(e){i=e}function a(e,t){o.from=e,o.to=t}function r(e,t=null){t=p(t)?"":t;let n=c("style");n.id=i+t,n.textContent="",document.head.append(n);let l=n.sheet;for(let n in e)e.hasOwnProperty(n)&&u(l,n,d(e[n]),t)}function d(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 u(e,t,n,l=null){l=p(l)?"":l;let c=t.replace(o.from,o.to+l);e.insertRule(c+"{"+n+"}",0)}function k(e=null){const t=p(e)?"":e;let n=l("#"+i+t);n&&n.parentNode&&n.parentNode.removeChild(n)}function p(e){return"number"!=typeof e&&(!e||"string"==typeof e&&0===e.length)}function g(e=8){return Math.random().toString(36).substring(2,2+e)}function f(e,t,n){return new CustomEvent(e,{detail:t,...n})}var m=Object.freeze({__proto__:null,addEventListener:function(e,t,n,l){e.addEventListener(t,n,l)},createEvent:f,dispatchEvent:function(n,l=document,c,i){try{if("string"==typeof n){let e=f(n,c,i);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 C{static throwError=n.throwError;static getElem=l;static deepMerge=s;static generateRandom=g;static injectStylesheet=r;static removeStylesheet=k;static setStylesheetId=h;static setReplaceRule=a;static isEmpty=p;static createEvent=m.createEvent;static dispatchEvent=m.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(...C.getElem(e,"all")):e instanceof HTMLInputElement&&t.push(e)})):"string"==typeof e?t.push(...C.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,c=!1,i=null,o=!1;if(t instanceof HTMLLabelElement){const s=t.htmlFor,h=t.dataset.checkboxFor,a=e.dataset.checkboxId;c=!C.isEmpty(e.id)&&s===e.id,o=!C.isEmpty(e.id)&&h===e.id,C.isEmpty(a)||h!==a||(i=C.isEmpty(e.id)&&C.isEmpty(s)?"check-"+C.generateRandom(6):null,o=!0),(o||c)&&(n=t.cloneNode(!0),l=l||t.textContent,t.parentNode.removeChild(t))}return{title:l,remainLabel:c,randomID:i,labelToRestore:n}}static insertCheckbox(e,t,n,i){let o=C.getTemplate(e),s=c("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===i&&(a.htmlFor=r.id),h.addEventListener("click",(e=>{if(e.preventDefault(),r.click(),e.shiftKey){let e=C.createEvent("shift-click",{detail:{checkedElement:r}});C.dispatchEvent(e,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=>{if(e.preventDefault(),l.click(),e.shiftKey){let e=C.createEvent("shift-click",{detail:{checkedElement:l}});C.dispatchEvent(e,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 C.toggleCheckStatus(e,!1);const n=t.checked.length===t.input.length&&0!==t.checked.length;C.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)}}C.setStylesheetId("checkbox-style"),C.setReplaceRule(".check-box",".check-box-");const b={checked:null,checkMark:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cG9seWxpbmUgcG9pbnRzPSIyMCA2IDkgMTcgNCAxMiI+PC9wb2x5bGluZT48L3N2Zz4=",checkAll:null,bindLabel:!0,styles:{},onChange:()=>{},onCheckAll:()=>{}};class E{static instances=[];static version="2.0.8";static firstLoad=!0;element=null;options=b;id=0;allElement=[];total={input:[],checked:[],list:[]};checkAllElement=[];lastChecked=null;onChangeCallback;onCheckAllCallback;constructor(e,t){this.init(e,t,E.instances.length),E.instances.push(this),1===E.instances.length&&!0===E.firstLoad&&((e,t=!1)=>{!0===t?console.log("Data Type : "+typeof e,"\nValue : "+e):"boolean"!=typeof t?console.log(t):console.log(e)})(`CheckBox is loaded, version: ${E.version}`),E.firstLoad=!1}init(e,t,n){let l=C.getElem(e,"all");return(!l||l.length<1)&&C.throwError("Cannot find elements : "+e),this.id=n,this.element=e,this.options=C.deepMerge({},this.options,t),this.injectStyles(),this.setupCallbacks(),l.forEach(((e,t)=>this.processCheckbox(e,t))),this.options.checkAll&&this.processCheckAll(),this}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=C.deepMerge({},this.options.styles,e)),e&&C.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:c,remainLabel:i,randomID:o,labelToRestore:s}=C.handleCheckboxTitle(e,n);l=!!i||l,e.checked?C.toggleCheckStatus(e,!0):this.options.checked&&this.updateCheckboxStatus(e,t);let{cloneEle:h,labelNode:a}=C.insertCheckbox(this.id.toString(),e,o,i);C.insertCheckboxTitle(c,l,a,h);let r=this.checkBoxChange.bind(this,!0,h,void 0);h.addEventListener("change",r),h.checkBoxChange=r,this.allElement.push(h),h.labelToRestore=s}updateCheckboxStatus(e,t){const n=this.options.checked;"boolean"==typeof n?C.toggleCheckStatus(e,n):"string"==typeof n||"number"==typeof n?e.value!==n.toString()&&t!==Number(n)||C.toggleCheckStatus(e,!0):Array.isArray(n)&&n.includes(e.value)&&C.toggleCheckStatus(e,!0)}processCheckAll(){const e=C.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:c,labelToRestore:i}=C.handleCheckboxTitle(e,t);n&&t&&"LABEL"===t.tagName&&(n=t.textContent||n,t.parentNode?.removeChild(t));const{cloneEle:o,templateNode:s,labelNode:h}=C.insertCheckbox(this.id.toString(),e,c,l);e.parentNode?.replaceChild(s.firstElementChild||s,e),C.insertCheckboxTitle(n,this.options.bindLabel??!1,h,o),o.addEventListener("change",this.checkAllChange),o.checkAllChange=this.checkAllChange,o.labelToRestore=i,this.checkAllElement.push(o),(!0===this.options.checked||e.checked)&&(C.toggleCheckStatus(o,!0),o.dispatchEvent(new Event("change")))}))}checkBoxChange(e,t,n){this.updateTotal(),e&&this.updateCheckAllStatus(),this.onChangeCallback?.(this.total,t),t&&C.toggleCheckStatus(t,n??t.checked),this.dispatchCheckboxChangeEvent()}checkAllChange=e=>{if(!(e.target instanceof HTMLInputElement))return;const t=e.target.checked;this.allElement.forEach((e=>{C.toggleCheckStatus(e,t)})),this.updateTotal(),this.updateCheckAllStatus(),this.checkBoxChange(!1),this.onCheckAllCallback&&this.onCheckAllCallback(t)};updateTotal(){const e=this.total;e.list=[],e.input=[],e.checked=[],this.allElement.forEach((t=>{e.input.push(t),t.checked&&(e.list.push(t.value),e.checked.push(t))}))}updateCheckAllStatus(){if(this.checkAllElement.length>0){const e=this.total.checked.length===this.total.input.length;this.checkAllElement.forEach((t=>{C.toggleCheckStatus(t,e)}))}}dispatchCheckboxChangeEvent(){const e=C.createEvent("checkbox-change",{detail:this.total});C.dispatchEvent(e)}handleShiftClick(e){if(!this.lastChecked)return void this.checkBoxChange(!1,e);let t=this.allElement.indexOf(this.lastChecked),n=this.allElement.indexOf(e),l=Math.min(t,n),c=Math.max(t,n);for(let e=l;e<=c;e++)this.checkBoxChange(!0,this.allElement[e],this.lastChecked.checked);this.lastChecked=e}destroy(){E.firstLoad=!1,this.allElement.forEach((e=>{C.restoreElement(e)})),this.checkAllElement.length>0&&this.checkAllElement.forEach((e=>{e.checkAllChange&&(C.toggleCheckAll(this.checkAllElement),C.restoreElement(e))})),this.element=null,this.options=b,this.allElement=[],this.total={input:[],checked:[],list:[]},this.checkAllElement=[],C.removeStylesheet(this.id.toString());const e=E.instances.indexOf(this);-1!==e&&E.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(;E.instances.length;){E.instances[0].destroy()}}}return E}));
!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,...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)?e[c]=i:(e[c]&&"object"==typeof e[c]||(e[c]={}),s(e[c],i))}var l;return s(e,...t)}function h(e){c=e}function a(e,t){o.from=e,o.to=t}function r(e,t=null){t=p(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)&&k(l,n,d(e[n]),t)}function d(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 k(e,t,n,l=null){l=p(l)?"":l;let i=t.replace(o.from,o.to+l);e.insertRule(i+"{"+n+"}",0)}function u(e=null){const t=p(e)?"":e;let n=l("#"+c+t);n&&n.parentNode&&n.parentNode.removeChild(n)}function p(e){return"number"!=typeof e&&(!e||"string"==typeof e&&0===e.length)}function g(e=8){return Math.random().toString(36).substring(2,2+e)}function f(e,t,n){return new CustomEvent(e,{detail:t,...n})}var m=Object.freeze({__proto__:null,addEventListener:function(e,t,n,l){e.addEventListener(t,n,l)},createEvent:f,dispatchEvent:function(n,l=document,i,c){try{if("string"==typeof n){let e=f(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 C{static throwError=n.throwError;static getElem=l;static deepMerge=s;static generateRandom=g;static injectStylesheet=r;static removeStylesheet=u;static setStylesheetId=h;static setReplaceRule=a;static isEmpty=p;static createEvent=m.createEvent;static addEventListener=m.addEventListener;static dispatchEvent=m.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(...C.getElem(e,"all")):e instanceof HTMLInputElement&&t.push(e)})):"string"==typeof e?t.push(...C.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=!C.isEmpty(e.id)&&s===e.id,o=!C.isEmpty(e.id)&&h===e.id,C.isEmpty(a)||h!==a||(c=C.isEmpty(e.id)&&C.isEmpty(s)?"check-"+C.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=C.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 C.toggleCheckStatus(e,!1);const n=t.checked.length===t.input.length&&0!==t.checked.length;C.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=C.createEvent("shift-click",{checkedElement:e});C.dispatchEvent(t,e)}}C.setStylesheetId("checkbox-style"),C.setReplaceRule(".check-box",".check-box-");const b=(e,t=!1)=>{!0===t?console.log("Data Type : "+typeof e,"\nValue : "+e):"boolean"!=typeof t?console.log(t):console.log(e)},E={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.9";static firstLoad=!0;element=null;options=E;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&&b(`CheckBox is loaded, version: ${v.version}`),v.firstLoad=!1}init(e,t,n){let l=C.getElem(e,"all");return(!l||l.length<1)&&C.throwError("Cannot find elements : "+e),this.id=n,this.element=e,this.options=C.deepMerge({},this.options,t),this.injectStyles(),this.setupCallbacks(),l.forEach(((e,t)=>this.processCheckbox(e,t))),this.updateTotal(),this.options.checkAll&&this.processCheckAll(),this}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=C.deepMerge({},this.options.styles,e)),e&&C.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}=C.handleCheckboxTitle(e,n);l=!!c||l,e.checked?C.toggleCheckStatus(e,!0):this.options.checked&&this.updateCheckboxStatus(e,t);let{cloneEle:h,labelNode:a}=C.insertCheckbox(this.id.toString(),e,o,c);C.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&&C.addEventListener(h,"shift-click",this.handleShiftClick),this.allElement.push(h),h.labelToRestore=s}updateCheckboxStatus(e,t){const n=this.options.checked;"boolean"==typeof n?C.toggleCheckStatus(e,n):"string"==typeof n||"number"==typeof n?e.value!==n.toString()&&t!==Number(n)||C.toggleCheckStatus(e,!0):Array.isArray(n)&&n.includes(e.value)&&C.toggleCheckStatus(e,!0)}processCheckAll(){const e=C.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}=C.handleCheckboxTitle(e,t);n&&t&&"LABEL"===t.tagName&&(n=t.textContent||n,t.parentNode?.removeChild(t));const{cloneEle:o,templateNode:s,labelNode:h}=C.insertCheckbox(this.id.toString(),e,i,l);e.parentNode?.replaceChild(s.firstElementChild||s,e),C.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)&&(C.toggleCheckStatus(o,!0),o.dispatchEvent(new Event("change")))}))}checkBoxChange(e,t,n){this.updateTotal(),e&&this.updateCheckAllStatus(),this.onChangeCallback?.(this.total,t),t&&C.toggleCheckStatus(t,n??t.checked),this.dispatchCheckboxChangeEvent()}checkAllChange=e=>{if(!(e.target instanceof HTMLInputElement))return;const t=e.target.checked;this.allElement.forEach((e=>{C.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=>{C.toggleCheckStatus(t,e)}))}}dispatchCheckboxChangeEvent(){const e=C.createEvent("checkbox-change",{detail:this.total});C.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){b("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];C.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=>{C.restoreElement(e)})),this.checkAllElement.length>0&&this.checkAllElement.forEach((e=>{e.checkAllChange&&(C.toggleCheckAll(this.checkAllElement),C.restoreElement(e))})),this.element=null,this.options=E,this.allElement=[],this.total={input:[],checked:[],list:[]},this.checkAllElement=[],C.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}));
{
"name": "@carry0987/check-box",
"version": "2.0.8",
"version": "2.0.9",
"description": "A library for create and manage checkbox elements",

@@ -31,3 +31,3 @@ "type": "module",

"devDependencies": {
"@carry0987/utils": "^3.2.8",
"@carry0987/utils": "^3.2.11",
"@rollup/plugin-node-resolve": "^15.2.3",

@@ -34,0 +34,0 @@ "@rollup/plugin-replace": "^5.0.5",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc