!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("morphdom")):"function"==typeof define&&define.amd?define(["exports","morphdom"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CableReady={},e.morphdom)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(t),r="5.0.0-pre9";const s={INPUT:!0,TEXTAREA:!0,SELECT:!0},a={INPUT:!0,TEXTAREA:!0,OPTION:!0},i={"datetime-local":!0,"select-multiple":!0,"select-one":!0,color:!0,date:!0,datetime:!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,textarea:!0,time:!0,url:!0,week:!0};let l;var c={get element(){return l},set(e){l=e}};const u=e=>s[e.tagName]&&i[e.type],d=e=>{const t=(e&&e.nodeType===Node.ELEMENT_NODE?e:document.querySelector(e))||c.element;t&&t.focus&&t.focus()},m=(e,t,n={})=>{const o=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:n});e.dispatchEvent(o),window.jQuery&&window.jQuery(e).trigger(t,n)},h=e=>document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue,p=e=>Array(e).flat(),f=(e,t)=>{Array.from(e.selectAll?e.element:[e.element]).forEach(t)},b=e=>e.split("").map(((e,t)=>e.toUpperCase()===e?`${0!==t?"-":""}${e.toLowerCase()}`:e)).join(""),y=(e,t)=>!e.cancel&&(e.delay?setTimeout(t,e.delay):t(),!0),g=(e,t)=>m(e,`cable-ready:before-${b(t.operation)}`,t),w=(e,t)=>m(e,`cable-ready:after-${b(t.operation)}`,t);function E(e,t){let n;return(...o)=>{clearTimeout(n),n=setTimeout((()=>e.apply(this,o)),t)}}function v(e){if(!e.ok)throw Error(e.statusText);return e}async function T(e,t){try{const n=await fetch(e,{headers:{"X-REQUESTED-WITH":"XmlHttpRequest",...t}});if(null==n)return;return v(n),n}catch(t){console.error(`Could not fetch ${e}`)}}var S=Object.freeze({__proto__:null,isTextInput:u,assignFocus:d,dispatch:m,xpathToElement:h,getClassNames:p,processElements:f,operate:y,before:g,after:w,debounce:E,handleErrors:v,graciouslyFetch:T,kebabize:b});const A=e=>(t,n)=>!k.map((o=>"function"!=typeof o||o(e,t,n))).includes(!1),C=e=>t=>{L.forEach((n=>{"function"==typeof n&&n(e,t)}))},x=(e,t,n)=>!(!a[t.tagName]&&t.isEqualNode(n)),M=(e,t,n)=>t!==c.element||!t.isContentEditable,O=(e,t,n)=>{const{permanentAttributeName:o}=e;if(!o)return!0;const r=t.closest(`[${o}]`);if(!r&&t===c.element&&u(t)){const e={value:!0};return Array.from(n.attributes).forEach((n=>{e[n.name]||t.setAttribute(n.name,n.value)})),!1}return!r},k=[x,O,M],L=[];var R=Object.freeze({__proto__:null,shouldMorphCallbacks:k,didMorphCallbacks:L,shouldMorph:A,didMorph:C,verifyNotMutable:x,verifyNotContentEditable:M,verifyNotPermanent:O}),P={append:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{html:n,focusSelector:o}=e;t.insertAdjacentHTML("beforeend",n||""),d(o)})),w(t,e)}))},graft:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{parent:n,focusSelector:o}=e,r=document.querySelector(n);r&&(r.appendChild(t),d(o))})),w(t,e)}))},innerHtml:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{html:n,focusSelector:o}=e;t.innerHTML=n||"",d(o)})),w(t,e)}))},insertAdjacentHtml:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{html:n,position:o,focusSelector:r}=e;t.insertAdjacentHTML(o||"beforeend",n||""),d(r)})),w(t,e)}))},insertAdjacentText:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{text:n,position:o,focusSelector:r}=e;t.insertAdjacentText(o||"beforeend",n||""),d(r)})),w(t,e)}))},morph:e=>{f(e,(t=>{const{html:n}=e,r=document.createElement("template");r.innerHTML=String(n).trim(),e.content=r.content;const s=t.parentElement,a=Array.from(s.children).indexOf(t);g(t,e),y(e,(()=>{const{childrenOnly:n,focusSelector:s}=e;o.default(t,n?r.content:r.innerHTML,{childrenOnly:!!n,onBeforeElUpdated:A(e),onElUpdated:C(e)}),d(s)})),w(s.children[a],e)}))},outerHtml:e=>{f(e,(t=>{const n=t.parentElement,o=Array.from(n.children).indexOf(t);g(t,e),y(e,(()=>{const{html:n,focusSelector:o}=e;t.outerHTML=n||"",d(o)})),w(n.children[o],e)}))},prepend:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{html:n,focusSelector:o}=e;t.insertAdjacentHTML("afterbegin",n||""),d(o)})),w(t,e)}))},remove:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{focusSelector:n}=e;t.remove(),d(n)})),w(document,e)}))},replace:e=>{f(e,(t=>{const n=t.parentElement,o=Array.from(n.children).indexOf(t);g(t,e),y(e,(()=>{const{html:n,focusSelector:o}=e;t.outerHTML=n||"",d(o)})),w(n.children[o],e)}))},textContent:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{text:n,focusSelector:o}=e;t.textContent=null!=n?n:"",d(o)})),w(t,e)}))},addCssClass:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{name:n}=e;t.classList.add(...p(n||""))})),w(t,e)}))},removeAttribute:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{name:n}=e;t.removeAttribute(n)})),w(t,e)}))},removeCssClass:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{name:n}=e;t.classList.remove(...p(n))})),w(t,e)}))},setAttribute:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{name:n,value:o}=e;t.setAttribute(n,o||"")})),w(t,e)}))},setDatasetProperty:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{name:n,value:o}=e;t.dataset[n]=o||""})),w(t,e)}))},setProperty:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{name:n,value:o}=e;n in t&&(t[n]=o||"")})),w(t,e)}))},setStyle:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{name:n,value:o}=e;t.style[n]=o||""})),w(t,e)}))},setStyles:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{styles:n}=e;for(let[e,o]of Object.entries(n))t.style[e]=o||""})),w(t,e)}))},setValue:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{value:n}=e;t.value=n||""})),w(t,e)}))},dispatchEvent:e=>{f(e,(t=>{g(t,e),y(e,(()=>{const{name:n,detail:o}=e;m(t,n,o)})),w(t,e)}))},setMeta:e=>{g(document,e),y(e,(()=>{const{name:t,content:n}=e;let o=document.head.querySelector(`meta[name='${t}']`);o||(o=document.createElement("meta"),o.name=t,document.head.appendChild(o)),o.content=n})),w(document,e)},clearStorage:e=>{g(document,e),y(e,(()=>{const{type:t}=e;("session"===t?sessionStorage:localStorage).clear()})),w(document,e)},go:e=>{g(window,e),y(e,(()=>{const{delta:t}=e;history.go(t)})),w(window,e)},pushState:e=>{g(window,e),y(e,(()=>{const{state:t,title:n,url:o}=e;history.pushState(t||{},n||"",o)})),w(window,e)},redirectTo:e=>{g(window,e),y(e,(()=>{let{url:t,action:n}=e;n=n||"advance",window.Turbo&&window.Turbo.visit(t,{action:n}),window.Turbolinks&&window.Turbolinks.visit(t,{action:n}),window.Turbo||window.Turbolinks||(window.location.href=t)})),w(window,e)},reload:e=>{g(window,e),y(e,(()=>{window.location.reload()})),w(window,e)},removeStorageItem:e=>{g(document,e),y(e,(()=>{const{key:t,type:n}=e;("session"===n?sessionStorage:localStorage).removeItem(t)})),w(document,e)},replaceState:e=>{g(window,e),y(e,(()=>{const{state:t,title:n,url:o}=e;history.replaceState(t||{},n||"",o)})),w(window,e)},scrollIntoView:e=>{const{element:t}=e;g(t,e),y(e,(()=>{t.scrollIntoView(e)})),w(t,e)},setCookie:e=>{g(document,e),y(e,(()=>{const{cookie:t}=e;document.cookie=t||""})),w(document,e)},setFocus:e=>{const{element:t}=e;g(t,e),y(e,(()=>{d(t)})),w(t,e)},setStorageItem:e=>{g(document,e),y(e,(()=>{const{key:t,value:n,type:o}=e;("session"===o?sessionStorage:localStorage).setItem(t,n||"")})),w(document,e)},consoleLog:e=>{g(document,e),y(e,(()=>{const{message:t,level:n}=e;n&&["warn","info","error"].includes(n)?console[n](t||""):console.log(t||"")})),w(document,e)},consoleTable:e=>{g(document,e),y(e,(()=>{const{data:t,columns:n}=e;console.table(t,n||[])})),w(document,e)},notification:e=>{g(document,e),y(e,(()=>{const{title:t,options:n}=e;Notification.requestPermission().then((o=>{e.permission=o,"granted"===o&&new Notification(t||"",n)}))})),w(document,e)}};let q=P;const H=e=>{q={...q,...e}};var N={get all(){return q}};const U=(e,t={emitMissingElementWarnings:!0})=>{const n={};e.forEach((e=>{e.batch&&(n[e.batch]=n[e.batch]?++n[e.batch]:1)})),e.forEach((e=>{const o=e.operation;try{if(e.selector?e.element=e.xpath?h(e.selector):document[e.selectAll?"querySelectorAll":"querySelector"](e.selector):e.element=document,e.element||t.emitMissingElementWarnings){c.set(document.activeElement);const t=N.all[o];t?(t(e),e.batch&&0==--n[e.batch]&&m(document,"cable-ready:batch-complete",{batch:e.batch})):console.error(`CableReady couldn't find the "${o}" operation. Make sure you use the camelized form when calling an operation method.`)}}catch(t){e.element?(console.error(`CableReady detected an error in ${o||"operation"}: ${t.message}. If you need to support older browsers make sure you've included the corresponding polyfills. https://docs.stimulusreflex.com/setup#polyfills-for-ie11.`),console.error(t)):console.warn(`CableReady ${o||"operation"} failed due to missing DOM element for selector: '${e.selector}'`)}}))};let _;const I=[25,50,75,100,200,250,500,800,1e3,2e3],$=async(e=0)=>{if(_)return _;if(e>=I.length)throw new Error("Couldn't obtain a Action Cable consumer within 5s");var t;return await(t=I[e],new Promise((e=>setTimeout(e,t)))),await $(e+1)};var j={setConsumer(e){_=e},get consumer(){return _},getConsumer:async()=>await $()};class F extends HTMLElement{disconnectedCallback(){this.channel&&this.channel.unsubscribe()}createSubscription(e,t,n){this.channel=e.subscriptions.create({channel:t,identifier:this.identifier},{received:n})}get preview(){return document.documentElement.hasAttribute("data-turbolinks-preview")||document.documentElement.hasAttribute("data-turbo-preview")}get identifier(){return this.getAttribute("identifier")}}class D extends F{async connectedCallback(){if(this.preview)return;const e=await j.getConsumer();e?this.createSubscription(e,"CableReady::Stream",this.performOperations):console.error("The `stream_from` helper cannot connect without an ActionCable consumer.\nPlease run `rails generate cable_ready:helpers` to fix this.")}performOperations(e){e.cableReady&&U(e.operations)}}class z extends F{constructor(){super();this.attachShadow({mode:"open"}).innerHTML="\n\n\n"}async connectedCallback(){if(this.preview)return;this.update=E(this.update.bind(this),this.debounce);const e=await j.getConsumer();e?this.createSubscription(e,"CableReady::Stream",this.update):console.error("The `updates-for` helper cannot connect without an ActionCable consumer.\nPlease run `rails generate cable_ready:helpers` to fix this.")}async update(e){const t=Array.from(document.querySelectorAll(this.query),(e=>new X(e)));if(t[0].element!==this)return;c.set(document.activeElement),this.html={};const n=[...new Set(t.map((e=>e.url)))];await Promise.all(n.map((async e=>{if(!this.html.hasOwnProperty(e)){const t=await T(e,{"X-Cable-Ready":"update"});this.html[e]=await t.text()}}))),this.index={},t.forEach((t=>{this.index.hasOwnProperty(t.url)?this.index[t.url]++:this.index[t.url]=0,t.process(e,this.html,this.index)}))}get query(){return`updates-for[identifier="${this.identifier}"]`}get identifier(){return this.getAttribute("identifier")}get debounce(){return this.hasAttribute("debounce")?parseInt(this.getAttribute("debounce")):20}}class X{constructor(e){this.element=e}async process(e,t,n){if(!this.shouldUpdate(e))return;const r=n[this.url],s=document.createElement("template");this.element.setAttribute("updating","updating"),s.innerHTML=String(t[this.url]).trim(),await this.resolveTurboFrames(s.content);const a=s.content.querySelectorAll(this.query);if(a.length<=r)return void console.warn(`Update aborted due to insufficient number of elements. The offending url is ${this.url}.`);const i={element:this.element,html:a[r],permanentAttributeName:"data-ignore-updates"};m(this.element,"cable-ready:before-update",i),o.default(this.element,a[r],{childrenOnly:!0,onBeforeElUpdated:A(i),onElUpdated:e=>{this.element.removeAttribute("updating"),m(this.element,"cable-ready:after-update",i),d(i.focusSelector)}})}async resolveTurboFrames(e){const t=[...e.querySelectorAll('turbo-frame[src]:not([loading="lazy"])')];return Promise.all(t.map((t=>new Promise((async n=>{const o=await T(t.getAttribute("src"),{"Turbo-Frame":t.id,"X-Cable-Ready":"update"}),r=document.createElement("template");r.innerHTML=await o.text(),await this.resolveTurboFrames(r.content),e.querySelector(`turbo-frame#${t.id}`).innerHTML=String(r.content.querySelector(`turbo-frame#${t.id}`).innerHTML).trim(),n()})))))}shouldUpdate(e){return!this.ignoresInnerUpdates&&this.hasChangesSelectedForUpdate(e)}hasChangesSelectedForUpdate(e){const t=this.element.getAttribute("only");return!(t&&e.changed&&!t.split(" ").some((t=>e.changed.includes(t))))}get ignoresInnerUpdates(){return this.element.hasAttribute("ignore-inner-updates")&&this.element.hasAttribute("performing-inner-update")}get url(){return this.element.hasAttribute("url")?this.element.getAttribute("url"):location.href}get identifier(){return this.element.identifier}get query(){return this.element.query}}const V=e=>{const t=e&&e.parentElement.closest("updates-for");t&&(t.setAttribute("performing-inner-update",""),V(t))},W=e=>{const t=e&&e.parentElement.closest("updates-for");t&&(t.removeAttribute("performing-inner-update"),W(t))},Q={perform:U,performAsync:(e,t={emitMissingElementWarnings:!0})=>new Promise(((n,o)=>{try{n(U(e,t))}catch(e){o(e)}})),shouldMorphCallbacks:k,didMorphCallbacks:L,initialize:(e={})=>{const{consumer:t}=e;document.addEventListener("stimulus-reflex:before",(e=>{V(e.detail.element)})),document.addEventListener("stimulus-reflex:after",(e=>{setTimeout((()=>{W(e.detail.element)}))})),document.addEventListener("turbo:submit-start",(e=>{V(e.target)})),document.addEventListener("turbo:submit-end",(e=>{setTimeout((()=>{W(e.target)}))})),t?j.setConsumer(t):console.error("CableReady requires a reference to your Action Cable `consumer` for its helpers to function.\nEnsure that you have imported the `CableReady` package as well as `consumer` from your `channels` folder, then call `CableReady.initialize({ consumer })`."),customElements.get("stream-from")||customElements.define("stream-from",D),customElements.get("updates-for")||customElements.define("updates-for",z)},addOperation:(e,t)=>{const n={};n[e]=t,H(n)},addOperations:e=>{H(e)},version:r,cable:j,get DOMOperations(){return console.warn("DEPRECATED: Please use `CableReady.operations` instead of `CableReady.DOMOperations`"),N.all},get operations(){return N.all},get consumer(){return j.consumer}};window.CableReady=Q,e.MorphCallbacks=R,e.StreamFromElement=D,e.SubscribingElement=F,e.UpdatesForElement=z,e.Utils=S,e.default=Q,Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=cable_ready.umd.min.js.map