easy-toggle-state
Version:
A tiny JavaScript library to easily toggle the state of any HTML element in any contexts, and create UI components in no time.
3 lines (2 loc) • 9.83 kB
JavaScript
/*! easy-toggle-state v1.16.0 | (c) 2020 Matthieu Bué <https://twikito.com> | MIT License | https://twikito.github.io/easy-toggle-state/ */
!function(){"use strict";function t(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function e(t){return function(t){if(Array.isArray(t))return n(t)}(t)||function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}(t)||function(t,e){if(!t)return;if("string"==typeof t)return n(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return n(t,e)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var r=document.documentElement.getAttribute("data-easy-toggle-state-custom-prefix")||"toggle",i=function(){return r},c=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i();return["data",e,t].filter(Boolean).join("-")},a=c("arrows"),o="aria-checked",u=c("class"),s=c("class-on-target"),l=c("class-on-trigger"),f="is-active",g=c("escape"),d=c("event"),h="aria-expanded",A=c("group"),b="aria-hidden",v=c("is-active"),m=c("modal"),p=c("outside"),y=c("outside-event"),w="aria-pressed",E=c("radio-group"),k="aria-selected",L=c("target"),S=c("target-all"),O=c("target-next"),x=c("target-parent"),I=c("target-previous"),D=c("target-self"),j=c("state"),z=c("trigger-off"),T=new Event("toggleAfter"),q=new Event("toggleBefore"),K=function(t,n){var r=t?"[".concat(t,"]"):"";if(n)return e(n.querySelectorAll(r));var i=["[".concat(u,"]").concat(r),"[".concat(l,"]").concat(r),"[".concat(s,"][").concat(L,"]").concat(r),"[".concat(s,"][").concat(S,"]").concat(r),"[".concat(s,"][").concat(O,"]").concat(r),"[".concat(s,"][").concat(I,"]").concat(r),"[".concat(s,"][").concat(x,"]").concat(r),"[".concat(s,"][").concat(D,"]").concat(r)].join().trim();return e(document.querySelectorAll(i))},B=function(t,e){return t.dispatchEvent(e)},Y=function(t){return"easyToggleState_".concat(t)},C=function(e){var n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(t(n={},o,e[Y("isActive")]),t(n,h,e[Y("isActive")]),t(n,b,!e[Y("isActive")]),t(n,w,e[Y("isActive")]),t(n,k,e[Y("isActive")]),n);return Object.keys(r).forEach((function(t){return e.hasAttribute(t)&&e.setAttribute(t,r[t])}))},M=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"This trigger has the class name '".concat(t,"' filled in both attributes '").concat(u,"' and '").concat(e,"'. As a result, this class will be toggled ").concat(n&&"on its target(s)"," twice at the same time.")},U=function(t,e){return(t.getAttribute(e)||"").split(" ").filter(Boolean)},H=function(t){var e=t.hasAttribute(A)?A:E;return K("".concat(e,'="').concat(t.getAttribute(e),'"')).filter((function(t){return t[Y("isActive")]}))},R=function(t,e){t||console.warn("You should fill the attribute '".concat(e,"' with a selector"))},P=function(t,n){if(0===n.length)return console.warn("There's no match with the selector '".concat(t,"' for this trigger")),[];var r=t.match(/#\w+/gi);return r&&r.forEach((function(t){var r=e(n).filter((function(e){return e.id===t.slice(1)}));r.length>1&&console.warn("There's ".concat(r.length," matches with the selector '").concat(t,"' for this trigger"))})),e(n)},$=function(t,e){return e.forEach((function(e){t.classList.toggle(e)}))},_={},F=function(t){return document.addEventListener(t.getAttribute(y)||t.getAttribute(d)||"click",G,!1)},G=function t(e){var n=e.target,r=e.type,i=!1;K(p).filter((function(t){return t.getAttribute(y)===r||t.getAttribute(d)===r&&!t.hasAttribute(y)||"click"===r&&!t.hasAttribute(d)&&!t.hasAttribute(y)})).forEach((function(t){var e=n.closest("[".concat(j,'="true"]'));e&&e[Y("trigger")]===t&&(i=!0),i||t===n||t.contains(n)||!t[Y("isActive")]||(t.hasAttribute(A)||t.hasAttribute(E)?V:Q)(t)})),i||document.removeEventListener(r,t,!1);var c=n.closest("[".concat(u,"][").concat(p,"],[").concat(l,"][").concat(p,"],[").concat(s,"][").concat(p,"]"));c&&c[Y("isActive")]&&F(n)},J=function(t){return Q(t.currentTarget[Y("target")])},N=function(t,n,r){return function(t){if(t.hasAttribute(L)||t.hasAttribute(S)){var e=t.getAttribute(L)||t.getAttribute(S);return R(e,t.hasAttribute(L)?L:S),P(e,document.querySelectorAll(e))}if(t.hasAttribute(x)){var n=t.getAttribute(x);return R(n,x),P(n,t.parentElement.querySelectorAll(n))}if(t.hasAttribute(D)){var r=t.getAttribute(D);return R(r,D),P(r,t.querySelectorAll(r))}return t.hasAttribute(I)?P("previous",[t.previousElementSibling].filter(Boolean)):t.hasAttribute(O)?P("next",[t.nextElementSibling].filter(Boolean)):[]}(t).forEach((function(i){var c;(B(i,q),i[Y("isActive")]=!i[Y("isActive")],C(i),r)?(c=i.classList).add.apply(c,e(n)):$(i,n);t.hasAttribute(p)&&(i.setAttribute(j,t[Y("isActive")]),i[Y("trigger")]=t),t.hasAttribute(m)&&(i[Y("isActive")]?(_[i]=function(t){return function(n){var r=e(t.querySelectorAll("a[href], area[href], input:not([type='hidden']):not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]"));if(r.length&&"Tab"===n.key){var i=n.target,c=r[0],a=r[r.length-1];return-1===r.indexOf(i)?(n.preventDefault(),c.focus()):n.shiftKey&&i===c?(n.preventDefault(),a.focus()):n.shiftKey||i!==a?void 0:(n.preventDefault(),c.focus())}}}(i),document.addEventListener("keydown",_[i],!1)):(document.removeEventListener("keydown",_[i],!1),delete _[i])),B(i,T),function(t,e){var n=K(z,t).filter((function(e){return!e.getAttribute(z)||t.matches(e.getAttribute(z))}));if(0!==n.length)e[Y("isActive")]?n.forEach((function(t){t[Y("target")]||(t[Y("target")]=e,t.addEventListener("click",J,!1))})):(n.forEach((function(t){t[Y("target")]===e&&(t[Y("target")]=null,t.removeEventListener("click",J,!1))})),e.focus())}(i,t)}))},Q=function(t){B(t,q);var n=function(t){if(t.hasAttribute(u)&&t.getAttribute(u)&&(t.hasAttribute(l)||t.hasAttribute(s))){var n=U(t,l),r=U(t,s);U(t,u).forEach((function(e){n.includes(e)&&console.warn(M(e,l),t),r.includes(e)&&console.warn(M(e,s,!0),t)}))}var i=[u,l,s].reduce((function(n,r){var i,c,a=U(t,r);return(r===u||r===l)&&(i=n.trigger).push.apply(i,e(a)),(r===u||r===s)&&(c=n.target).push.apply(c,e(a)),n}),{trigger:[],target:[]});return!i.trigger.length&&(t.hasAttribute(u)||t.hasAttribute(l))&&i.trigger.push(f),!i.target.length&&(t.hasAttribute(u)||t.hasAttribute(s))&&i.target.push(f),i}(t);return $(t,n.trigger),t[Y("isActive")]=!t[Y("isActive")],C(t),B(t,T),N(t,n.target,!1),function(t){if(t.hasAttribute(p))return t.hasAttribute(E)?console.warn("You can't use '".concat(p,"' on a radio grouped trigger")):t[Y("isActive")]?F(t):void 0}(t)},V=function(t){var e=H(t);return 0===e.length?Q(t):-1===e.indexOf(t)?(e.forEach(Q),Q(t)):-1===e.indexOf(t)||t.hasAttribute(E)?void 0:Q(t)},W=function(t){return(t[Symbol.iterator]?e(t):[t]).forEach((function(t){t[Y("unbind")]&&t[Y("unbind")]()})),t},X=function(){e(document.querySelectorAll("[".concat(s,"]:not([").concat(L,"]):not([").concat(S,"]):not([").concat(O,"]):not([").concat(I,"]):not([").concat(x,"]):not([").concat(D,"])"))).forEach((function(t){console.warn("This trigger has the attribute '".concat(s,"', but no specified target\n"),t)})),K(v).filter((function(t){return!t[Y("isDefaultInitialized")]})).forEach((function(t){if((t.hasAttribute(A)||t.hasAttribute(E))&&H(t).length>0)return console.warn("Toggle group '".concat(t.getAttribute(A)||t.getAttribute(E),"' must not have more than one trigger with '").concat(v,"'"));Q(t),t[Y("isDefaultInitialized")]=!0}));var t=K().filter((function(t){return!t[Y("isInitialized")]}));return t.forEach((function(t){var e=function(e){e.preventDefault(),(t.hasAttribute(A)||t.hasAttribute(E)?V:Q)(t)},n=t.getAttribute(d)||"click";t.addEventListener(n,e,!1),t[Y("unbind")]=function(){t.removeEventListener(n,e,!1),t[Y("isInitialized")]=!1},t[Y("isInitialized")]=!0})),K(g).length>0&&!document[Y("isEscapeKeyInitialized")]&&(document.addEventListener("keydown",(function(t){"Escape"!==t.key&&"Esc"!==t.key||K(g).forEach((function(t){if(t[Y("isActive")])return t.hasAttribute(E)?console.warn("You can't use '".concat(g,"' on a radio grouped trigger")):(t.hasAttribute(A)?V:Q)(t)}))}),!1),document[Y("isEscapeKeyInitialized")]=!0),K(a).length>0&&!document[Y("isArrowKeysInitialized")]&&(document.addEventListener("keydown",(function(t){var e=document.activeElement;if(-1!==["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"].indexOf(t.key)&&(e.hasAttribute(u)||e.hasAttribute(l)||e.hasAttribute(s))&&e.hasAttribute(a)){if(!e.hasAttribute(A)&&!e.hasAttribute(E))return console.warn("You can't use '".concat(a,"' on a trigger without '").concat(A,"' or '").concat(E,"'"));t.preventDefault();var n=e.hasAttribute(A)?K("".concat(A,"='").concat(e.getAttribute(A),"'")):K("".concat(E,"='").concat(e.getAttribute(E),"'")),r=e;switch(t.key){case"ArrowUp":case"ArrowLeft":r=n.indexOf(e)>0?n[n.indexOf(e)-1]:n[n.length-1];break;case"ArrowDown":case"ArrowRight":r=n.indexOf(e)<n.length-1?n[n.indexOf(e)+1]:n[0];break;case"Home":r=n[0];break;case"End":r=n[n.length-1]}return r.focus(),r.dispatchEvent(new Event(r.getAttribute(d)||"click"))}}),!1),document[Y("isArrowKeysInitialized")]=!0),t};document.addEventListener("DOMContentLoaded",(function t(){X(),document.removeEventListener("DOMContentLoaded",t)})),window.easyToggleState=Object.assign(X,{isActive:function(t){return!!t[Y("isActive")]},unbind:W,unbindAll:function(){return W(K().filter((function(t){return t[Y("isInitialized")]})))}})}();