UNPKG

@fylgja/alpinejs-dialog

Version:

Bring the power of AlpineJs to the HTML dialog

2 lines (1 loc) 1.66 kB
(()=>{function h(s){s.directive("htmldialog",r);function r(t,{expression:n,modifiers:o},{evaluateLater:l,cleanup:m}){let c=n.length?l(n):()=>{},v=o.includes("noscroll"),w=o.includes("modeless"),a=t.getAttribute("closeby")||L(o,"closeby","closerequest");t.style.display=null,t.style.length===0&&t.removeAttribute("style"),t._x_isShown&&y();let b="closedBy"in HTMLDialogElement.prototype;function u(e=!0){document.body.style.overflow=e?"hidden":""}function d(e){(e.target.getAttribute("method")==="dialog"||e.submitter?.getAttribute("formmethod")==="dialog")&&(e.preventDefault(),c())}function f(e){e.key==="Escape"&&(e.preventDefault(),a!=="none"&&c())}function g(e){if(e.target!==t)return;let i=t.getBoundingClientRect();i.top<=e.clientY&&e.clientY<=i.top+i.height&&i.left<=e.clientX&&e.clientX<=i.left+i.width||a==="any"&&(b&&e.preventDefault(),c())}function p(){c()}function y(){t.hasAttribute("open")||(w?t.show():t.showModal(),u(v))}function E(){t.hasAttribute("open")&&(t.close(),u(!1))}t._x_doShow=()=>y(),t._x_doHide=()=>E(),t.addEventListener("keydown",f),t.addEventListener("submit",d),t.addEventListener("click",g),t.addEventListener("cancel",p),m(()=>{t.removeEventListener("keydown",f),t.removeEventListener("submit",d),t.removeEventListener("click",g),t.removeEventListener("cancel",p),u(!1)})}}function L(s,r,t){if(s.indexOf(r)===-1)return t;let n=s[s.indexOf(r)+1];if(!n)return t;if(r==="closeby"){let o=["auto","none","closerequest","any"],l=o.join(", ");if(!o.includes(n))return console.warn(`"${n}" is not one of the allowed values for closeby: ${l}`),t}return n}document.addEventListener("alpine:init",()=>{window.Alpine.plugin(h)});})();