UNPKG

@viivue/easy-tab-accordion

Version:

Super light-weight JavaScript library to create a simple tab or accordion

6 lines 13.6 kB
/**! * Easy Tabs & Accordion v2.3.3 * @author phucbm * @homepage https://github.com/viivue/easy-tab-accordion * @license MIT 2025 */var t={d:(e,i)=>{for(var n in i)t.o(i,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:i[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},e={};function i({context:t,offset:e}){const i=t.wrapper;if("auto"===t.type)return void(t.options.dev&&console.log("Skip scrollIntoView for auto trigger."));e=e||(parseInt(t.options.scrollOffset)||0);const n=i.getBoundingClientRect().top+window.pageYOffset-e;"undefined"!=typeof jQuery?jQuery("html, body").animate({scrollTop:n},500):window.scrollTo({top:n,behavior:"smooth"})}function n(t){const e=getComputedStyle(t);return parseInt(e.getPropertyValue("margin-top")+e.getPropertyValue("margin-bottom"),10)}function o(t){return t.scrollHeight+n(t)+"px"}function s(t,e){Object.assign(t.style,e)}function r(t,e){s(t,{transitionProperty:"all",transitionDuration:e+"ms",overflow:"hidden"})}function a(t){s(t,{boxSizing:"",paddingTop:"",paddingBottom:"",marginTop:"",marginBottom:""})}function l(t=""){return t+(+new Date).toString(16)+(1e8*Math.random()|0).toString(16)}function c(t,e){return!!t.dataset.filter((t=>t.id===e)).length}function h(t,e){return e>=0&&e<t.count}function d(t,e){const i=e=>e?t.options.receiver:t.options.trigger,n=e=>e?t.options.receiverAttr:t.options.triggerAttr;if(e){return{previous:t.wrapper.querySelectorAll(`${i(!0)}:not([${n(!0)}="${e}"])`),current:t.wrapper.querySelectorAll(`[${n(!0)}="${e}"]`),previousTrigger:t.wrapper.querySelectorAll(`${i(!1)}:not([${n(!1)}="${e}"])`),currentTrigger:t.wrapper.querySelectorAll(`[${n(!1)}="${e}"]`)}}return{current:t.wrapper.querySelectorAll(`[${n(!0)}]`),currentTrigger:t.wrapper.querySelectorAll(`[${n(!1)}]`)}}function p(t,e){return t.dataset.findIndex((t=>t.id===e))}function u(t,e){return t.dataset[e].id}function f(t,e){const{current:i,currentTrigger:n}=d(t,e);i.forEach((e=>e.classList.remove(t.options.activeClass))),n.forEach((e=>e.classList.remove(t.options.activeClass)))}function g(t,e,...i){t.options.dev&&console?.[e](...i)}function v(t,e=500,i){s(t,{opacity:"0",visibility:"hidden"}),setTimeout((()=>{a(t),"function"==typeof i&&i()}),e)}function m(t,e=500,i){r(t.parentElement,e),s(t,{opacity:"1",visibility:"visible"}),s(t.parentElement,{height:`${t.scrollHeight+n(t)}px`}),setTimeout((()=>{a(t),a(t.parentElement),"function"==typeof i&&i()}),e)}function w(t=document.location){const e=new URL(t),i=e.hash.indexOf("?"),n=i>-1?e.hash.slice(0,i):e.hash;return{data:e,hash:n,id:n.slice(1)}}function y(t,e){A(t)&&b(t)!==t.enabled&&(t.enabled=b(t),t.enabled?t.init():t.destroy())}function b(t){return window.innerWidth<=t.options.liveBreakpoint[0]&&window.innerWidth>=t.options.liveBreakpoint[1]&&A(t)}function A(t){let e=function(t,e=!0){return t.sort((function(t,i){return e?t-i:i-t}))}(t.options.liveBreakpoint,!1);return e=e.slice(0,2),2===e.length}t.d(e,{v:()=>_});const E="easy-tab-accordion-enabled",S="assigned-trigger-event",T="data-eta",x="data-eta-hash",I="data-eta-hash-scroll",C="data-eta-animation",B={el:void 0,id:void 0,trigger:"[data-eta-trigger]",triggerAttr:"data-eta-trigger",receiver:"[data-eta-receiver]",receiverAttr:"data-eta-receiver",activeClass:"active",animation:"slide",duration:450,scrollIntoView:!1,scrollOffset:30,hash:!1,hashScroll:!1,liveBreakpoint:[],avoidDoubleClick:!0,dev:!1,activeSection:0,allowCollapseAll:!1,allowExpandAll:!1,isPreventDefault:!0};function L(t){t.events.fire("onBeforeInit"),t.wrapper.classList.add(E),t.wrapper.querySelectorAll(t.options.trigger).forEach((e=>{e.addEventListener("click",(e=>function(t,e){t.options.isPreventDefault&&e.preventDefault();e.stopPropagation();const i=e.target.getAttribute(t.options.triggerAttr)||e.target.closest(t.options.trigger).getAttribute(t.options.triggerAttr);t.toggle(i,"manual")}(t,e))),e.classList.add(S)})),t.dataset=[],t.wrapper.querySelectorAll(t.options.receiver).forEach((e=>{const i=e.getAttribute(t.options.receiverAttr);if(t.dataset.push({id:i,el:e,active:!1}),"fade"===t.options.animation){s(e.parentElement,{overflow:"hidden",position:"relative"!==getComputedStyle(e).position?"relative":""});const t={position:(()=>"absolute"!==getComputedStyle(e).position?"absolute":"")(),inset:"0 0 auto"};setTimeout((()=>{s(e,t)}),1)}r(e,t.options.duration)})),function(t){document.querySelectorAll('a[href^="#"]').forEach((e=>{const n=e.getAttribute("href"),o="#"===n[0]?n.slice(1):w(n).id;o?t.dataset.forEach((s=>{if(s.id===o){if(e.classList.contains(S))return void console.log(`Trigger href: ${n} is already assigned an event.`);e.addEventListener("click",(e=>{t.options.isPreventDefault&&e.preventDefault(),t.type="manual",t.options.scrollIntoView&&i({context:t}),t.toggle(o,"manual")})),e.classList.add(S)}})):t.options.dev&&console.log(`Invalid trigger href: ${n}`)}))}(t),t.enabled&&(function(t){const e=w(),i=e.hash,n=e.id;return t.options.hash&&i.length&&t.dataset.filter((t=>t.id===n)).length}(t)?t.toggle(w().id,"hash"):function(t){let e=[];const i=t.options.activeSection;switch(t.options.animation){case"slide":switch(typeof i){case"number":e.push(i);break;case"object":t.options.allowExpandAll&&"slide"===t.options.animation?e=i.filter((function(t,e,i){return i.indexOf(t)===e})):e.push(i[0])}break;case"fade":switch(typeof i){case"number":e.push(h(t,i)?i:0);break;case"object":const n=i[0];e.push(h(t,n)?n:0)}}e.forEach((e=>{h(t,e)&&t.toggle(u(t,e),"auto")})),t.dataset.filter((t=>!t.active)).forEach((e=>t.closePanel(e.id)))}(t)),t.hasInitialized=!0,t.events.fire("onAfterInit")}function P({target:t,attributeName:e="",defaultOptions:i={},numericValues:n=[],onIsString:o,dev:s=!1}){if(!t)return s&&console.warn("Target not found!",t),i;if(!t.hasAttribute(e))return s&&console.warn("Attribute not found from target",e),i;const r=t.getAttribute(e);if(!r.length)return i;if(!function(t){try{return JSON.parse(t)&&!!t}catch(t){return!1}}(r))return"function"==typeof o?o(r):console.warn("Not a JSON string",r),i;let a=JSON.parse(r);for(const[t,e]of Object.entries(a))"false"===e?a[t]=!1:"true"===e?a[t]=!0:n.includes(t)&&"string"==typeof e&&e.length>0?a[t]=parseFloat(e):a[t]=e;return{...i,...a}}class ${constructor(t,e){t&&(this.context=t,this.options={names:[],...e},this.eventNames=this.options.names,this.eventsList=[])}fire(t,e={}){if(!this.eventNames.includes(t))return void console.warn(`Cannot fire unrecognized event "${t}"`,this,e);const i={instance:this.context,eventName:t,...e},n=(this.context.config?this.context.config:this.context.options)[t];"function"==typeof n&&n(i);const o=this.eventsList[t];o?.length&&o.forEach((t=>{"function"==typeof t&&t(i)}))}add(t,e){t=function(t){let e=t;"on"!==t.slice(0,2)&&(e=e.charAt(0).toUpperCase()+e.slice(1),e="on"+e);return e}(t);this.eventNames.includes(t)?(void 0===this.eventsList[t]&&(this.eventsList[t]=[]),this.eventsList[t].push(e)):console.warn(`Cannot add unrecognized event "${t}"`)}}class _{constructor(t){this.options={...B,id:l("eta-"),...t},this.options.el?(this.options=P({target:this.options.el,defaultOptions:this.options,attributeName:T,numericValues:["duration","activeSection"],dev:B.dev}),this.events=new $(this,{names:["onBeforeInit","onAfterInit","onBeforeOpen","onBeforeClose","onAfterOpen","onAfterClose","onDestroy","onUpdate"]}),this.init(),this.isAnimating=!1):g(this,"warn","ETA Error, target not found!")}on(t,e){this.events.add(t,e)}init(){this.wrapper=this.options.el,this.id=this.options.id,this.current_id="",this.previous_id="",this.type="",this.hasInitialized=!1,this.enabled=!A(this)||b(this),this.count=this.wrapper.querySelectorAll(this.options.trigger).length;if(!!window.ETAController.get(this.id)&&console.warn(`Found duplicated ID: "${this.id}", the ID should be unique.`),this.wrapper.classList.contains(E))return void g(this,"ETA has initialized");this.isFirst=!0,this.options.hash=!0===this.wrapper.hasAttribute(x)||this.options.hash,this.options.hashScroll=!0===this.wrapper.hasAttribute(I)||this.options.hashScroll;const t=this.wrapper.getAttribute(C);this.options.animation=null!==t?t:this.options.animation,this.wrapper.setAttribute(T,this.id),this.count<1?g(this,"warn","Quit init due to child panels not found",this):(this.enabled&&!this.hasInitialized&&L(this),!this.enabled&&this.hasInitialized&&this.destroy(),window.addEventListener("resize",function(t,e=150){let i;return(...n)=>{clearTimeout(i),i=setTimeout((()=>{t.apply(this,n)}),e)}}((t=>{return(e=this).update(),void y(e);var e}),300)),window.addEventListener("load",(t=>{return(e=this).update(),void y(e);var e})),window.ETAController.add(this))}destroy(){switch(this.hasInitialized=!1,this.wrapper.classList.remove(E),this.wrapper.querySelectorAll(this.options.trigger).forEach((t=>{t.outerHTML=`${t.outerHTML}`})),this.dataset=[],this.options.animation){case"slide":(t=this).wrapper.querySelectorAll(t.options.receiver).forEach((t=>{s(t,{display:"",height:""}),a(t)})),f(t);break;case"fade":!function(t){t.wrapper.querySelectorAll(t.options.receiver).forEach((t=>{s(t,{opacity:"",visibility:"",position:"",inset:""}),s(t.parentElement,{height:"",position:""}),a(t),a(t.parentElement)})),f(t)}(this)}var t;window.ETAController.remove(this.id),this.events.fire("onDestroy")}update(){switch(this.options.animation){case"slide":break;case"fade":(t=this).dataset.forEach((e=>{const i=e.el,n=t.options.duration;e.active&&m(i,n),e.active||v(i,n)}))}var t;this.events.fire("onUpdate")}openPanel(t=this.current_id,e=!1){if(!c(this,t=`${t}`))return;const n=this.getPanelByID(t);if(e&&n.active)return void g(this,"warn",`openPanel(${t}) does not run as the panel is already opened!`);(()=>{this.getPanelByID(t).active=!0,function(t,e){if(!t.options.hash||"manual"!==t.type)return;const i=document.location.origin+document.location.pathname;document.location=i+"#"+e}(this,t),this.events.fire("onBeforeOpen",{type:this.type,current_id:this.current_id,previous_id:this.previous_id})})();const r=e=>{var n;"hash"===(n=this).type&&n.options.hashScroll&&window.addEventListener("load",(()=>setTimeout((()=>i({context:n})),100))),this.options.scrollIntoView&&i({context:this,target:e}),this.isAnimating=!1,g(this,"log","Stop animation."),this.events.fire("onAfterOpen",{target:e,type:this.type,current_id:this.current_id,previous_id:this.previous_id}),g(this,"log","after open",t)},{current:l}=d(this,t);switch(this.options.animation){case"slide":l.forEach((t=>function(t,e=500,i){0!==parseInt(o(t))&&"none"!==t.style.display.trim()||s(t,{boxSizing:"border-box",height:"0px",display:"block"}),setTimeout((()=>{s(t,{height:o(t),marginTop:"",marginBottom:"",paddingTop:"",paddingBottom:""})}),10),setTimeout((()=>{a(t),s(t,{height:""}),"function"==typeof i&&i()}),e+10)}(t,this.options.duration,(()=>r(t)))));break;case"fade":l.forEach((t=>m(t,this.options.duration,(()=>r(t)))))}!function(t,e){const{current:i,currentTrigger:n}=d(t,e||t.current_id);i&&i.forEach((e=>e.classList.add(t.options.activeClass))),n&&n.forEach((e=>e.classList.add(t.options.activeClass)))}(this,t);("fade"===this.options.animation||"slide"===this.options.animation&&!this.options.allowExpandAll)&&this.dataset.filter((e=>e.id!==t)).forEach((t=>{(t.active||this.isFirst)&&this.closePanel(t.id)})),this.isFirst&&(l[0].style.display="block",this.isFirst=!1)}closePanel(t=this.current_id,e=!1){if(!c(this,t))return;const i=this.getPanelByID(t);if(e&&!i.active)return void console.warn(`closePanel(${t}) does not run as the panel is already closed!`);this.events.fire("onBeforeClose",{type:this.type,current_id:this.current_id,previous_id:this.previous_id}),this.getPanelByID(t).active=!1;const n=e=>{this.events.fire("onAfterClose",{target:e}),this.isAnimating=!1,g(this,"log","Stop animation."),g(this,"log","after close",t)},{current:r}=d(this,t);switch(this.options.animation){case"slide":r.forEach((t=>function(t,e=500,i){const n=o(t);"0px"!==n?(s(t,{boxSizing:"border-box",height:n}),setTimeout((()=>{s(t,{height:"0px",marginTop:"0px",marginBottom:"0px",paddingTop:"0px",paddingBottom:"0px"})}),10),setTimeout((()=>{s(t,{display:"none",height:""}),a(t),"function"==typeof i&&i()}),e+10)):"function"==typeof i&&i()}(t,this.options.duration,(()=>n(t)))));break;case"fade":r.forEach((t=>v(t,this.options.duration,(()=>n(t)))))}f(this,t)}getPanelByID(t){return this.dataset[p(this,t)]}toggle(t,e="undefined",i=!1){if(!c(this,t))return void g(this,"warn","invalid id");const n=function(t,e){if(!c(t,e))return!1;if(t.hasInitialized&&t.options.avoidDoubleClick&&t.isAnimating)return g(t,"warn",`Block [${e}] to avoid double click on animating item.`),0;const i=t.dataset[p(t,e)].active,n="slide"===t.options.animation&&t.options.allowCollapseAll;return i&&"fade"===t.options.animation?0:i&&n||i&&!n?-1:!i&&n?1:i||n?i?1:-1:1}(this,t);0!==n&&(this.isAnimating=!0,g(this,"log","Start animation."),this.type=e,this.previous_id=this.current_id?this.current_id:u(this,0),this.current_id=t,1===n?this.openPanel(this.current_id):this.closePanel(t))}expandAll(){this.options.allowExpandAll&&this.dataset.forEach((({active:t,id:e})=>{t||this.openPanel(e)}))}toggleByIndex(t){this.toggle(u(this,t))}}window.ETAController=new class{constructor(){this.instances=[]}add(t){this.instances.filter((e=>e.id===t.id)).length>0||this.instances.push(t)}get(t){return this.instances.filter((e=>e.id===t))[0]}remove(t){this.instances=this.instances.filter((e=>e.id!==t||(e.hasInitialized&&e.destroy(),!1)))}},window.ETA={init:t=>{void 0!==t?new _(t):document.querySelectorAll("[data-eta]").forEach((e=>{new _({el:e,...t})}))},get:t=>window.ETAController.get(t)},window.ETA.init();var k=e.v;export{k as EasyTabAccordion};