UNPKG

@magic-spells/collapsible-content

Version:
2 lines (1 loc) 2.3 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).CollapsibleContent={})}(this,(function(t){"use strict";class CollapsibleComponent extends HTMLElement{#t;constructor(){super();const t=this;t.button=null,t.content=null,t.#t=e=>{e.preventDefault();const n="true"!==t.button.getAttribute("aria-expanded");t.button.setAttribute("aria-expanded",n),t.content.hidden=!n}}connectedCallback(){const t=this;if(t.button=t.querySelector("button"),t.content=t.querySelector("collapsible-content"),!t.button||!t.content)return void console.error("CollapsibleComponent requires a <button> and a <collapsible-content>.");t.button.id||=`collapsible-button-${crypto.randomUUID().slice(0,8)}`,t.content.id||=`collapsible-content-${crypto.randomUUID().slice(0,8)}`,t.button.setAttribute("aria-controls",t.content.id),t.content.setAttribute("role","region"),t.content.setAttribute("aria-labelledby",t.button.id);const e="true"===t.button.getAttribute("aria-expanded");t.content.hidden=!e,t.button.addEventListener("click",t.#t)}disconnectedCallback(){const t=this;t.button&&t.button.removeEventListener("click",t.#t)}}class CollapsibleContent extends HTMLElement{#e;constructor(){super();const t=this;t.#e=e=>{"height"==e.propertyName&&(t.hidden||(t.style.height="auto"))},t.addEventListener("transitionend",t.#e)}connectedCallback(){const t=this,e="true"===t.closest("collapsible-component").querySelector("button").getAttribute("aria-expanded");t.style.height=e?"auto":"0"}disconnectedCallback(){this.removeEventListener("transitionend",this.#e)}set hidden(t){const e=this;t?(e.style.height=`${e.scrollHeight}px`,setTimeout((()=>{e.style.height="0px"}),1),e.setAttribute("aria-hidden","true"),e.setAttribute("inert",""),e.setAttribute("hidden","")):("auto"!==e.style.height&&(e.style.height=`${e.scrollHeight}px`),e.removeAttribute("aria-hidden"),e.removeAttribute("inert"),e.removeAttribute("hidden"))}get hidden(){return this.hasAttribute("hidden")}}customElements.define("collapsible-content",CollapsibleContent),customElements.define("collapsible-component",CollapsibleComponent),t.CollapsibleComponent=CollapsibleComponent,t.CollapsibleContent=CollapsibleContent}));