UNPKG

ultimate_turbo_modal

Version:

The ultimate Turbo / Stimulus / Hotwire modal window for Rails

11 lines (10 loc) 30.7 kB
import{Controller as e}from"@hotwired/stimulus";async function t(e,t=null){e.classList.remove("hidden"),await o("enter",e,t)}async function n(e,t=null){await o("leave",e,t),e.classList.add("hidden")}async function o(e,t,n){const o=t.dataset,i=n?`${n}-${e}`:e;let s=`transition${e.charAt(0).toUpperCase()+e.slice(1)}`;const l=o[s]?o[s].split(" "):[i],c=o[`${s}Start`]?o[`${s}Start`].split(" "):[`${i}-start`],u=o[`${s}End`]?o[`${s}End`].split(" "):[`${i}-end`];r(t,l),r(t,c),await new Promise((e=>{requestAnimationFrame((()=>{requestAnimationFrame(e)}))})),a(t,c),r(t,u),await function(e){return new Promise((t=>{const n=getComputedStyle(e).transitionDuration.split(",")[0],o=1e3*Number(n.replace("s",""));setTimeout((()=>{t()}),o)}))} /*! * tabbable 6.2.0 * @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE */(t),a(t,u),a(t,l)}function r(e,t){e.classList.add(...t)}function a(e,t){e.classList.remove(...t)}var i=["input:not([inert])","select:not([inert])","textarea:not([inert])","a[href]:not([inert])","button:not([inert])","[tabindex]:not(slot):not([inert])","audio[controls]:not([inert])","video[controls]:not([inert])",'[contenteditable]:not([contenteditable="false"]):not([inert])',"details>summary:first-of-type:not([inert])","details:not([inert])"],s=i.join(","),l="undefined"==typeof Element,c=l?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,u=!l&&Element.prototype.getRootNode?function(e){var t;return null==e||null===(t=e.getRootNode)||void 0===t?void 0:t.call(e)}:function(e){return null==e?void 0:e.ownerDocument},d=function e(t,n){var o;void 0===n&&(n=!0);var r=null==t||null===(o=t.getAttribute)||void 0===o?void 0:o.call(t,"inert");return""===r||"true"===r||n&&t&&e(t.parentNode)},f=function(e,t,n){if(d(e))return[];var o=Array.prototype.slice.apply(e.querySelectorAll(s));return t&&c.call(e,s)&&o.unshift(e),o=o.filter(n)},v=function e(t,n,o){for(var r=[],a=Array.from(t);a.length;){var i=a.shift();if(!d(i,!1))if("SLOT"===i.tagName){var l=i.assignedElements(),u=e(l.length?l:i.children,!0,o);o.flatten?r.push.apply(r,u):r.push({scopeParent:i,candidates:u})}else{c.call(i,s)&&o.filter(i)&&(n||!t.includes(i))&&r.push(i);var f=i.shadowRoot||"function"==typeof o.getShadowRoot&&o.getShadowRoot(i),v=!d(f,!1)&&(!o.shadowRootFilter||o.shadowRootFilter(i));if(f&&v){var h=e(!0===f?i.children:f.children,!0,o);o.flatten?r.push.apply(r,h):r.push({scopeParent:i,candidates:h})}else a.unshift.apply(a,i.children)}}return r},h=function(e){return!isNaN(parseInt(e.getAttribute("tabindex"),10))},p=function(e){if(!e)throw new Error("No node provided");return e.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(e.tagName)||function(e){var t,n=null==e||null===(t=e.getAttribute)||void 0===t?void 0:t.call(e,"contenteditable");return""===n||"true"===n}(e))&&!h(e)?0:e.tabIndex},m=function(e,t){return e.tabIndex===t.tabIndex?e.documentOrder-t.documentOrder:e.tabIndex-t.tabIndex},b=function(e){return"INPUT"===e.tagName},y=function(e){return function(e){return b(e)&&"radio"===e.type}(e)&&!function(e){if(!e.name)return!0;var t,n=e.form||u(e),o=function(e){return n.querySelectorAll('input[type="radio"][name="'+e+'"]')};if("undefined"!=typeof window&&void 0!==window.CSS&&"function"==typeof window.CSS.escape)t=o(window.CSS.escape(e.name));else try{t=o(e.name)}catch(e){return console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s",e.message),!1}var r=function(e,t){for(var n=0;n<e.length;n++)if(e[n].checked&&e[n].form===t)return e[n]}(t,e.form);return!r||r===e}(e)},g=function(e){var t=e.getBoundingClientRect(),n=t.width,o=t.height;return 0===n&&0===o},w=function(e,t){var n=t.displayCheck,o=t.getShadowRoot;if("hidden"===getComputedStyle(e).visibility)return!0;var r=c.call(e,"details>summary:first-of-type")?e.parentElement:e;if(c.call(r,"details:not([open]) *"))return!0;if(n&&"full"!==n&&"legacy-full"!==n){if("non-zero-area"===n)return g(e)}else{if("function"==typeof o){for(var a=e;e;){var i=e.parentElement,s=u(e);if(i&&!i.shadowRoot&&!0===o(i))return g(e);e=e.assignedSlot?e.assignedSlot:i||s===e.ownerDocument?i:s.host}e=a}if(function(e){var t,n,o,r,a=e&&u(e),i=null===(t=a)||void 0===t?void 0:t.host,s=!1;if(a&&a!==e)for(s=!!(null!==(n=i)&&void 0!==n&&null!==(o=n.ownerDocument)&&void 0!==o&&o.contains(i)||null!=e&&null!==(r=e.ownerDocument)&&void 0!==r&&r.contains(e));!s&&i;){var l,c,d;s=!(null===(c=i=null===(l=a=u(i))||void 0===l?void 0:l.host)||void 0===c||null===(d=c.ownerDocument)||void 0===d||!d.contains(i))}return s}(e))return!e.getClientRects().length;if("legacy-full"!==n)return!0}return!1},E=function(e,t){return!(t.disabled||d(t)||function(e){return b(e)&&"hidden"===e.type}(t)||w(t,e)||function(e){return"DETAILS"===e.tagName&&Array.prototype.slice.apply(e.children).some((function(e){return"SUMMARY"===e.tagName}))}(t)||function(e){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(e.tagName))for(var t=e.parentElement;t;){if("FIELDSET"===t.tagName&&t.disabled){for(var n=0;n<t.children.length;n++){var o=t.children.item(n);if("LEGEND"===o.tagName)return!!c.call(t,"fieldset[disabled] *")||!o.contains(e)}return!0}t=t.parentElement}return!1}(t))},S=function(e,t){return!(y(t)||p(t)<0||!E(e,t))},T=function(e){var t=parseInt(e.getAttribute("tabindex"),10);return!!(isNaN(t)||t>=0)},N=function e(t){var n=[],o=[];return t.forEach((function(t,r){var a=!!t.scopeParent,i=a?t.scopeParent:t,s=function(e,t){var n=p(e);return n<0&&t&&!h(e)?0:n}(i,a),l=a?e(t.candidates):i;0===s?a?n.push.apply(n,l):n.push(i):o.push({documentOrder:r,tabIndex:s,item:t,isScope:a,content:l})})),o.sort(m).reduce((function(e,t){return t.isScope?e.push.apply(e,t.content):e.push(t.content),e}),[]).concat(n)},A=function(e,t){if(t=t||{},!e)throw new Error("No node provided");return!1!==c.call(e,s)&&S(t,e)},k=i.concat("iframe").join(","),M=function(e,t){if(t=t||{},!e)throw new Error("No node provided");return!1!==c.call(e,k)&&E(t,e)}; /*! * focus-trap 7.6.5 * @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE */ function P(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function F(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t);if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function O(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function x(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?O(Object(n),!0).forEach((function(t){F(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):O(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function L(e){return function(e){if(Array.isArray(e))return P(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return P(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?P(e,t):void 0}}(e)||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.")}()}var R=function(e,t){if(e.length>0){var n=e[e.length-1];n!==t&&n._setPausedState(!0)}var o=e.indexOf(t);-1===o||e.splice(o,1),e.push(t)},I=function(e,t){var n=e.indexOf(t);-1!==n&&e.splice(n,1),e.length>0&&!e[e.length-1]._isManuallyPaused()&&e[e.length-1]._setPausedState(!1)},C=function(e){return"Tab"===(null==e?void 0:e.key)||9===(null==e?void 0:e.keyCode)},D=function(e){return C(e)&&!e.shiftKey},H=function(e){return C(e)&&e.shiftKey},B=function(e){return setTimeout(e,0)},j=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return"function"==typeof e?e.apply(void 0,n):e},G=function(e){return e.target.shadowRoot&&"function"==typeof e.composedPath?e.composedPath()[0]:e.target},V=[],$=function(e,t){var n,o=(null==t?void 0:t.document)||document,r=(null==t?void 0:t.trapStack)||V,a=x({returnFocusOnDeactivate:!0,escapeDeactivates:!0,delayInitialFocus:!0,isKeyForward:D,isKeyBackward:H},t),i={containers:[],containerGroups:[],tabbableGroups:[],nodeFocusedBeforeActivation:null,mostRecentlyFocusedNode:null,active:!1,paused:!1,manuallyPaused:!1,delayInitialFocusTimer:void 0,recentNavEvent:void 0},s=function(e,t,n){return e&&void 0!==e[t]?e[t]:a[n||t]},l=function(e,t){var n="function"==typeof(null==t?void 0:t.composedPath)?t.composedPath():void 0;return i.containerGroups.findIndex((function(t){var o=t.container,r=t.tabbableNodes;return o.contains(e)||(null==n?void 0:n.includes(o))||r.find((function(t){return t===e}))}))},c=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.hasFallback,r=void 0!==n&&n,i=t.params,s=void 0===i?[]:i,l=a[e];if("function"==typeof l&&(l=l.apply(void 0,L(s))),!0===l&&(l=void 0),!l){if(void 0===l||!1===l)return l;throw new Error("`".concat(e,"` was specified but was not a node, or did not return a node"))}var c=l;if("string"==typeof l){try{c=o.querySelector(l)}catch(t){throw new Error("`".concat(e,'` appears to be an invalid selector; error="').concat(t.message,'"'))}if(!c&&!r)throw new Error("`".concat(e,"` as selector refers to no known node"))}return c},u=function(){var e=c("initialFocus",{hasFallback:!0});if(!1===e)return!1;if(void 0===e||e&&!M(e,a.tabbableOptions))if(l(o.activeElement)>=0)e=o.activeElement;else{var t=i.tabbableGroups[0];e=t&&t.firstTabbableNode||c("fallbackFocus")}else null===e&&(e=c("fallbackFocus"));if(!e)throw new Error("Your focus-trap needs to have at least one focusable element");return e},d=function(){if(i.containerGroups=i.containers.map((function(e){var t=function(e,t){var n;return n=(t=t||{}).getShadowRoot?v([e],t.includeContainer,{filter:S.bind(null,t),flatten:!1,getShadowRoot:t.getShadowRoot,shadowRootFilter:T}):f(e,t.includeContainer,S.bind(null,t)),N(n)}(e,a.tabbableOptions),n=function(e,t){return(t=t||{}).getShadowRoot?v([e],t.includeContainer,{filter:E.bind(null,t),flatten:!0,getShadowRoot:t.getShadowRoot}):f(e,t.includeContainer,E.bind(null,t))}(e,a.tabbableOptions),o=t.length>0?t[0]:void 0,r=t.length>0?t[t.length-1]:void 0,i=n.find((function(e){return A(e)})),s=n.slice().reverse().find((function(e){return A(e)})),l=!!t.find((function(e){return p(e)>0}));return{container:e,tabbableNodes:t,focusableNodes:n,posTabIndexesFound:l,firstTabbableNode:o,lastTabbableNode:r,firstDomTabbableNode:i,lastDomTabbableNode:s,nextTabbableNode:function(e){var o=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=t.indexOf(e);return r<0?o?n.slice(n.indexOf(e)+1).find((function(e){return A(e)})):n.slice(0,n.indexOf(e)).reverse().find((function(e){return A(e)})):t[r+(o?1:-1)]}}})),i.tabbableGroups=i.containerGroups.filter((function(e){return e.tabbableNodes.length>0})),i.tabbableGroups.length<=0&&!c("fallbackFocus"))throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times");if(i.containerGroups.find((function(e){return e.posTabIndexesFound}))&&i.containerGroups.length>1)throw new Error("At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.")},h=function(e){var t=e.activeElement;if(t)return t.shadowRoot&&null!==t.shadowRoot.activeElement?h(t.shadowRoot):t},m=function(e){!1!==e&&e!==h(document)&&(e&&e.focus?(e.focus({preventScroll:!!a.preventScroll}),i.mostRecentlyFocusedNode=e,function(e){return e.tagName&&"input"===e.tagName.toLowerCase()&&"function"==typeof e.select}(e)&&e.select()):m(u()))},b=function(e){var t=c("setReturnFocus",{params:[e]});return t||!1!==t&&e},y=function(e){var t=e.target,n=e.event,o=e.isBackward,r=void 0!==o&&o;t=t||G(n),d();var s=null;if(i.tabbableGroups.length>0){var u=l(t,n),f=u>=0?i.containerGroups[u]:void 0;if(u<0)s=r?i.tabbableGroups[i.tabbableGroups.length-1].lastTabbableNode:i.tabbableGroups[0].firstTabbableNode;else if(r){var v=i.tabbableGroups.findIndex((function(e){var n=e.firstTabbableNode;return t===n}));if(v<0&&(f.container===t||M(t,a.tabbableOptions)&&!A(t,a.tabbableOptions)&&!f.nextTabbableNode(t,!1))&&(v=u),v>=0){var h=0===v?i.tabbableGroups.length-1:v-1,m=i.tabbableGroups[h];s=p(t)>=0?m.lastTabbableNode:m.lastDomTabbableNode}else C(n)||(s=f.nextTabbableNode(t,!1))}else{var b=i.tabbableGroups.findIndex((function(e){var n=e.lastTabbableNode;return t===n}));if(b<0&&(f.container===t||M(t,a.tabbableOptions)&&!A(t,a.tabbableOptions)&&!f.nextTabbableNode(t))&&(b=u),b>=0){var y=b===i.tabbableGroups.length-1?0:b+1,g=i.tabbableGroups[y];s=p(t)>=0?g.firstTabbableNode:g.firstDomTabbableNode}else C(n)||(s=f.nextTabbableNode(t))}}else s=c("fallbackFocus");return s},g=function(e){var t=G(e);l(t,e)>=0||(j(a.clickOutsideDeactivates,e)?n.deactivate({returnFocus:a.returnFocusOnDeactivate}):j(a.allowOutsideClick,e)||e.preventDefault())},w=function(e){var t=G(e),n=l(t,e)>=0;if(n||t instanceof Document)n&&(i.mostRecentlyFocusedNode=t);else{var o;e.stopImmediatePropagation();var r=!0;if(i.mostRecentlyFocusedNode)if(p(i.mostRecentlyFocusedNode)>0){var s=l(i.mostRecentlyFocusedNode),c=i.containerGroups[s].tabbableNodes;if(c.length>0){var d=c.findIndex((function(e){return e===i.mostRecentlyFocusedNode}));d>=0&&(a.isKeyForward(i.recentNavEvent)?d+1<c.length&&(o=c[d+1],r=!1):d-1>=0&&(o=c[d-1],r=!1))}}else i.containerGroups.some((function(e){return e.tabbableNodes.some((function(e){return p(e)>0}))}))||(r=!1);else r=!1;r&&(o=y({target:i.mostRecentlyFocusedNode,isBackward:a.isKeyBackward(i.recentNavEvent)})),m(o||(i.mostRecentlyFocusedNode||u()))}i.recentNavEvent=void 0},k=function(e){(a.isKeyForward(e)||a.isKeyBackward(e))&&function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];i.recentNavEvent=e;var n=y({event:e,isBackward:t});n&&(C(e)&&e.preventDefault(),m(n))}(e,a.isKeyBackward(e))},P=function(e){var t;"Escape"!==(null==(t=e)?void 0:t.key)&&"Esc"!==(null==t?void 0:t.key)&&27!==(null==t?void 0:t.keyCode)||!1===j(a.escapeDeactivates,e)||(e.preventDefault(),n.deactivate())},F=function(e){var t=G(e);l(t,e)>=0||j(a.clickOutsideDeactivates,e)||j(a.allowOutsideClick,e)||(e.preventDefault(),e.stopImmediatePropagation())},O=function(){if(i.active)return R(r,n),i.delayInitialFocusTimer=a.delayInitialFocus?B((function(){m(u())})):m(u()),o.addEventListener("focusin",w,!0),o.addEventListener("mousedown",g,{capture:!0,passive:!1}),o.addEventListener("touchstart",g,{capture:!0,passive:!1}),o.addEventListener("click",F,{capture:!0,passive:!1}),o.addEventListener("keydown",k,{capture:!0,passive:!1}),o.addEventListener("keydown",P),n},$=function(){if(i.active)return o.removeEventListener("focusin",w,!0),o.removeEventListener("mousedown",g,!0),o.removeEventListener("touchstart",g,!0),o.removeEventListener("click",F,!0),o.removeEventListener("keydown",k,!0),o.removeEventListener("keydown",P),n},U="undefined"!=typeof window&&"MutationObserver"in window?new MutationObserver((function(e){e.some((function(e){return Array.from(e.removedNodes).some((function(e){return e===i.mostRecentlyFocusedNode}))}))&&m(u())})):void 0,q=function(){U&&(U.disconnect(),i.active&&!i.paused&&i.containers.map((function(e){U.observe(e,{subtree:!0,childList:!0})})))};return n={get active(){return i.active},get paused(){return i.paused},activate:function(e){if(i.active)return this;var t=s(e,"onActivate"),n=s(e,"onPostActivate"),r=s(e,"checkCanFocusTrap");r||d(),i.active=!0,i.paused=!1,i.nodeFocusedBeforeActivation=h(o),null==t||t();var a=function(){r&&d(),O(),q(),null==n||n()};return r?(r(i.containers.concat()).then(a,a),this):(a(),this)},deactivate:function(e){if(!i.active)return this;var t=x({onDeactivate:a.onDeactivate,onPostDeactivate:a.onPostDeactivate,checkCanReturnFocus:a.checkCanReturnFocus},e);clearTimeout(i.delayInitialFocusTimer),i.delayInitialFocusTimer=void 0,$(),i.active=!1,i.paused=!1,q(),I(r,n);var o=s(t,"onDeactivate"),l=s(t,"onPostDeactivate"),c=s(t,"checkCanReturnFocus"),u=s(t,"returnFocus","returnFocusOnDeactivate");null==o||o();var d=function(){B((function(){u&&m(b(i.nodeFocusedBeforeActivation)),null==l||l()}))};return u&&c?(c(b(i.nodeFocusedBeforeActivation)).then(d,d),this):(d(),this)},pause:function(e){return i.active?(i.manuallyPaused=!0,this._setPausedState(!0,e)):this},unpause:function(e){return i.active?(i.manuallyPaused=!1,r[r.length-1]!==this?this:this._setPausedState(!1,e)):this},updateContainerElements:function(e){var t=[].concat(e).filter(Boolean);return i.containers=t.map((function(e){return"string"==typeof e?o.querySelector(e):e})),i.active&&d(),q(),this}},Object.defineProperties(n,{_isManuallyPaused:{value:function(){return i.manuallyPaused}},_setPausedState:{value:function(e,t){if(i.paused===e)return this;if(i.paused=e,e){var n=s(t,"onPause"),o=s(t,"onPostPause");null==n||n(),$(),q(),null==o||o()}else{var r=s(t,"onUnpause"),a=s(t,"onPostUnpause");null==r||r(),d(),O(),q(),null==a||a()}return this}}}),n.updateContainerElements(e),n};const U="2.2.1";class q extends e{static targets=["container","content","overlay","outer"];static values={advanceUrl:String,allowedClickOutsideSelector:String};connect(){let e=this;this.#e(),this.focusTrapInstance=null,this.originalBodyOverflow=null,this.scrollPosition=0,this.showModal(),this.turboFrame=this.element.closest("turbo-frame"),window.addEventListener("popstate",(function(t){e.#t()&&e.#n()})),window.modal=this}disconnect(){this.focusTrapInstance&&this.#o(),window.modal=void 0}showModal(){this.#r(),Promise.all([t(this.overlayTarget),t(this.outerTarget)]).then((()=>{this.#a()})),this.advanceUrlValue&&!this.#t()&&(this.#i(),history.pushState({},"",this.advanceUrlValue))}hideModal(){if(this.hidingModal)return;this.hidingModal=!0;let e=new Event("modal:closing",{cancelable:!0});this.turboFrame.dispatchEvent(e),e.defaultPrevented?this.hidingModal=!1:(this.focusTrapInstance&&this.#o(),this.#n(),e=new Event("modal:closed",{cancelable:!1}),this.turboFrame.dispatchEvent(e),this.#t()&&history.back())}hide(){this.hideModal()}refreshPage(){window.Turbo.visit(window.location.href,{action:"replace"})}submitEnd(e){e.detail.success&&this.hideModal()}closeWithKeyboard(e){"Escape"==e.code&&this.hideModal()}outsideModalClicked(e){let t=!document.contains(e.target)||this.contentTarget.contains(e.target)||this.contentTarget==e.target,n=this.allowedClickOutsideSelectorValue&&""!==this.allowedClickOutsideSelectorValue&&null!=e.target.closest(this.allowedClickOutsideSelectorValue);t||n||this.hideModal()}#n(){this.#s(),Promise.all([n(this.overlayTarget),n(this.outerTarget)]).then((()=>{this.turboFrame.removeAttribute("src"),this.containerTarget.remove(),this.#l()}))}#t(){return"true"==document.body.getAttribute("data-turbo-modal-history-advanced")}#i(){return document.body.setAttribute("data-turbo-modal-history-advanced","true")}#l(){document.body.removeAttribute("data-turbo-modal-history-advanced")}#e(){const e=this.element.dataset.utmrVersion;e&&e!==U&&console.warn(`[UltimateTurboModal] Version Mismatch!\n\nGem Version: ${e}\nJS Version: ${U}\n\nPlease ensure both the 'ultimate_turbo_modal' gem and the 'ultimate-turbo-modal' npm package are updated to the same version.\nElement:`,this.element)}#a(){try{this.focusTrapInstance||(this.focusTrapInstance=$(this.contentTarget,{allowOutsideClick:!0,escapeDeactivates:!1,fallbackFocus:this.contentTarget,returnFocusOnDeactivate:!0,clickOutsideDeactivates:!1,preventScroll:!1,initialFocus:()=>this.contentTarget.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')||this.contentTarget})),this.focusTrapInstance.activate()}catch(e){console.error("[UltimateTurboModal] Failed to activate focus trap:",e),this.focusTrapInstance=null}}#o(){try{this.focusTrapInstance&&this.focusTrapInstance.active&&this.focusTrapInstance.deactivate()}catch(e){console.error("[UltimateTurboModal] Failed to deactivate focus trap:",e)}finally{this.focusTrapInstance=null}}#r(){this.scrollPosition=window.pageYOffset||document.documentElement.scrollTop,this.originalBodyOverflow=document.body.style.overflow,document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${this.scrollPosition}px`,document.body.style.width="100%"}#s(){null!==this.originalBodyOverflow?document.body.style.overflow=this.originalBodyOverflow:document.body.style.removeProperty("overflow"),document.body.style.removeProperty("position"),document.body.style.removeProperty("top"),document.body.style.removeProperty("width"),window.scrollTo(0,this.scrollPosition)}}var _=function(){const e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:e=>"true"===e.getAttribute("im-preserve"),shouldReAppend:e=>"true"===e.getAttribute("im-re-append"),shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};const n=function(){function e(e,t,n,r){if(!1===r.callbacks.beforeNodeAdded(t))return null;if(r.idMap.has(t)){const a=document.createElement(t.tagName);return e.insertBefore(a,n),o(a,t,r),r.callbacks.afterNodeAdded(a),a}{const o=document.importNode(t,!0);return e.insertBefore(o,n),r.callbacks.afterNodeAdded(o),o}}const t=function(){function e(e,t,n){let o=e.idMap.get(t),r=e.idMap.get(n);if(!r||!o)return!1;for(const e of o)if(r.has(e))return!0;return!1}function t(e,t){const n=e,o=t;return n.nodeType===o.nodeType&&n.tagName===o.tagName&&(!n.id||n.id===o.id)}return function(n,o,r,a){let i=null,s=o.nextSibling,l=0,c=r;for(;c&&c!=a;){if(t(c,o)){if(e(n,c,o))return c;null===i&&(n.idMap.has(c)||(i=c))}if(null===i&&s&&t(c,s)&&(l++,s=s.nextSibling,l>=2&&(i=void 0)),c.contains(document.activeElement))break;c=c.nextSibling}return i||null}}();function n(e,t){if(e.idMap.has(t))i(e.pantry,t,null);else{if(!1===e.callbacks.beforeNodeRemoved(t))return;t.parentNode?.removeChild(t),e.callbacks.afterNodeRemoved(t)}}function r(e,t,o){let r=t;for(;r&&r!==o;){let t=r;r=r.nextSibling,n(e,t)}return r}function a(e,t,n,o){const r=o.target.id===t&&o.target||o.target.querySelector(`[id="${t}"]`)||o.pantry.querySelector(`[id="${t}"]`);return function(e,t){const n=e.id;for(;e=e.parentNode;){let o=t.idMap.get(e);o&&(o.delete(n),o.size||t.idMap.delete(e))}}(r,o),i(e,r,n),r}function i(e,t,n){if(e.moveBefore)try{e.moveBefore(t,n)}catch(o){e.insertBefore(t,n)}else e.insertBefore(t,n)}return function(i,s,l,c=null,u=null){s instanceof HTMLTemplateElement&&l instanceof HTMLTemplateElement&&(s=s.content,l=l.content),c||=s.firstChild;for(const n of l.childNodes){if(c&&c!=u){const e=t(i,n,c,u);if(e){e!==c&&r(i,c,e),o(e,n,i),c=e.nextSibling;continue}}if(n instanceof Element&&i.persistentIds.has(n.id)){const e=a(s,n.id,c,i);o(e,n,i),c=e.nextSibling;continue}const l=e(s,n,c,i);l&&(c=l.nextSibling)}for(;c&&c!=u;){const e=c;c=c.nextSibling,n(i,e)}}}(),o=function(){function e(e,n,o,r){const a=n[o];if(a!==e[o]){const i=t(o,e,"update",r);i||(e[o]=n[o]),a?i||e.setAttribute(o,""):t(o,e,"remove",r)||e.removeAttribute(o)}}function t(e,t,n,o){return!("value"!==e||!o.ignoreActiveValue||t!==document.activeElement)||!1===o.callbacks.beforeAttributeUpdated(e,t,n)}function o(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(a,i,s){return s.ignoreActive&&a===document.activeElement?null:(!1===s.callbacks.beforeNodeMorphed(a,i)||(a instanceof HTMLHeadElement&&s.head.ignore||(a instanceof HTMLHeadElement&&"morph"!==s.head.style?r(a,i,s):(!function(n,r,a){let i=r.nodeType;if(1===i){const i=n,s=r,l=i.attributes,c=s.attributes;for(const e of c)t(e.name,i,"update",a)||i.getAttribute(e.name)!==e.value&&i.setAttribute(e.name,e.value);for(let e=l.length-1;0<=e;e--){const n=l[e];if(n&&!s.hasAttribute(n.name)){if(t(n.name,i,"remove",a))continue;i.removeAttribute(n.name)}}o(i,a)||function(n,o,r){if(n instanceof HTMLInputElement&&o instanceof HTMLInputElement&&"file"!==o.type){let a=o.value,i=n.value;e(n,o,"checked",r),e(n,o,"disabled",r),o.hasAttribute("value")?i!==a&&(t("value",n,"update",r)||(n.setAttribute("value",a),n.value=a)):t("value",n,"remove",r)||(n.value="",n.removeAttribute("value"))}else if(n instanceof HTMLOptionElement&&o instanceof HTMLOptionElement)e(n,o,"selected",r);else if(n instanceof HTMLTextAreaElement&&o instanceof HTMLTextAreaElement){let e=o.value,a=n.value;if(t("value",n,"update",r))return;e!==a&&(n.value=e),n.firstChild&&n.firstChild.nodeValue!==e&&(n.firstChild.nodeValue=e)}}(i,s,a)}8!==i&&3!==i||n.nodeValue!==r.nodeValue&&(n.nodeValue=r.nodeValue)}(a,i,s),o(a,s)||n(s,a,i))),s.callbacks.afterNodeMorphed(a,i)),a)}}();function r(e,t,n){let o=[],r=[],a=[],i=[],s=new Map;for(const e of t.children)s.set(e.outerHTML,e);for(const t of e.children){let e=s.has(t.outerHTML),o=n.head.shouldReAppend(t),l=n.head.shouldPreserve(t);e||l?o?r.push(t):(s.delete(t.outerHTML),a.push(t)):"append"===n.head.style?o&&(r.push(t),i.push(t)):!1!==n.head.shouldRemove(t)&&r.push(t)}i.push(...s.values());let l=[];for(const t of i){let r=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==n.callbacks.beforeNodeAdded(r)){if("href"in r&&r.href||"src"in r&&r.src){let e,t=new Promise((function(t){e=t}));r.addEventListener("load",(function(){e()})),l.push(t)}e.appendChild(r),n.callbacks.afterNodeAdded(r),o.push(r)}}for(const t of r)!1!==n.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),n.callbacks.afterNodeRemoved(t));return n.head.afterHeadMorphed(e,{added:o,kept:a,removed:r}),l}const a=function(){function e(){const e=document.createElement("div");return e.hidden=!0,document.body.insertAdjacentElement("afterend",e),e}function n(e){let t=Array.from(e.querySelectorAll("[id]"));return e.id&&t.push(e),t}function o(e,t,n,o){for(const r of o)if(t.has(r.id)){let t=r;for(;t;){let o=e.get(t);if(null==o&&(o=new Set,e.set(t,o)),o.add(r.id),t===n)break;t=t.parentElement}}}return function(r,a,i){const{persistentIds:s,idMap:l}=function(e,t){const r=n(e),a=n(t),i=function(e,t){let n=new Set,o=new Map;for(const{id:t,tagName:r}of e)o.has(t)?n.add(t):o.set(t,r);let r=new Set;for(const{id:e,tagName:a}of t)r.has(e)?n.add(e):o.get(e)===a&&r.add(e);for(const e of n)r.delete(e);return r}(r,a);let s=new Map;o(s,i,e,r);const l=t.__idiomorphRoot||t;return o(s,i,l,a),{persistentIds:i,idMap:s}}(r,a),c=function(e){let n=Object.assign({},t);return Object.assign(n,e),n.callbacks=Object.assign({},t.callbacks,e.callbacks),n.head=Object.assign({},t.head,e.head),n}(i),u=c.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(u))throw`Do not understand how to morph style ${u}`;return{target:r,newContent:a,config:c,morphStyle:u,ignoreActive:c.ignoreActive,ignoreActiveValue:c.ignoreActiveValue,restoreFocus:c.restoreFocus,idMap:l,persistentIds:s,pantry:e(),callbacks:c.callbacks,head:c.head}}}(),{normalizeElement:i,normalizeParent:s}=function(){const e=new WeakSet;class t{constructor(e){this.originalNode=e,this.realParentNode=e.parentNode,this.previousSibling=e.previousSibling,this.nextSibling=e.nextSibling}get childNodes(){const e=[];let t=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;t&&t!=this.nextSibling;)e.push(t),t=t.nextSibling;return e}querySelectorAll(e){return this.childNodes.reduce(((t,n)=>{if(n instanceof Element){n.matches(e)&&t.push(n);const o=n.querySelectorAll(e);for(let e=0;e<o.length;e++)t.push(o[e])}return t}),[])}insertBefore(e,t){return this.realParentNode.insertBefore(e,t)}moveBefore(e,t){return this.realParentNode.moveBefore(e,t)}get __idiomorphRoot(){return this.originalNode}}return{normalizeElement:function(e){return e instanceof Document?e.documentElement:e},normalizeParent:function n(o){if(null==o)return document.createElement("div");if("string"==typeof o)return n(function(t){let n=new DOMParser,o=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(o.match(/<\/html>/)||o.match(/<\/head>/)||o.match(/<\/body>/)){let r=n.parseFromString(t,"text/html");if(o.match(/<\/html>/))return e.add(r),r;{let t=r.firstChild;return t&&e.add(t),t}}{let o=n.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(o),o}}(o));if(e.has(o))return o;if(o instanceof Node){if(o.parentNode)return new t(o);{const e=document.createElement("div");return e.append(o),e}}{const e=document.createElement("div");for(const t of[...o])e.append(t);return e}}}}();return{morph:function(e,t,o={}){e=i(e);const l=s(t),c=a(e,l,o),u=function(e,t){if(!e.config.restoreFocus)return t();let n=document.activeElement;if(!(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement))return t();const{id:o,selectionStart:r,selectionEnd:a}=n,i=t();o&&o!==document.activeElement?.id&&(n=e.target.querySelector(`[id="${o}"]`),n?.focus());n&&!n.selectionEnd&&a&&n.setSelectionRange(r,a);return i}(c,(()=>function(e,t,n,o){if(e.head.block){const a=t.querySelector("head"),i=n.querySelector("head");if(a&&i){const t=r(a,i,e);return Promise.all(t).then((()=>{const t=Object.assign(e,{head:{block:!1,ignore:!0}});return o(t)}))}}return o(e)}(c,e,l,(t=>"innerHTML"===t.morphStyle?(n(t,e,l),Array.from(e.childNodes)):function(e,t,o){const r=s(t);return n(e,r,o,t,t.nextSibling),Array.from(r.childNodes)}(t,e,l)))));return c.pantry.remove(),u},defaults:t}}();Turbo.StreamActions.modal=function(){const e=this.getAttribute("message");"hide"==e&&window.modal?.hide(),"close"==e&&window.modal?.hide()};const K=e=>{const t=e?.target;return t instanceof Element&&"turbo-frame"===t.tagName.toLowerCase()&&("modal"===t.id||"modal-inner"===t.id)},z=e=>{e.detail.response.redirected&&K(e)&&(e.preventDefault(),e.detail.visit(e.detail.response))},Y=e=>{K(e)&&(e.detail.render=(e,t)=>{_.morph(e,t,{morphstyle:"innerHTML"})})};document.removeEventListener("turbo:frame-missing",z),document.addEventListener("turbo:frame-missing",z),document.removeEventListener("turbo:before-frame-render",Y),document.addEventListener("turbo:before-frame-render",Y);export{q as UltimateTurboModalController};