!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";var n="5.0.0-pre10";const o={INPUT:!0,TEXTAREA:!0,SELECT:!0},r={INPUT:!0,TEXTAREA:!0,OPTION:!0},s={"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 a;var i={get element(){return a},set(e){a=e}};const l=e=>o[e.tagName]&&s[e.type],c=e=>{const t=(e&&e.nodeType===Node.ELEMENT_NODE?e:document.querySelector(e))||i.element;t&&t.focus&&t.focus()},u=(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)},d=e=>document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue,m=(e,t=!1)=>{const n=document.evaluate(e,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null),o=[];for(let e=0;eArray.from(e).flat(),p=(e,t)=>{Array.from(e.selectAll?e.element:[e.element]).forEach(t)},f=(b=function(e,t,n){return e+(n?"-":"")+t.toLowerCase()},function(e){return g(e).reduce(b,"")});var b;const g=e=>(e=null==e?"":e).match(/([A-Z]{2,}|[0-9]+|[A-Z]?[a-z]+|[A-Z])/g)||[],y=(e,t)=>!e.cancel&&(e.delay?setTimeout(t,e.delay):t(),!0),w=(e,t)=>u(e,`cable-ready:before-${f(t.operation)}`,t),E=(e,t)=>u(e,`cable-ready:after-${f(t.operation)}`,t);function v(e,t=250){let n;return(...o)=>{n&&clearTimeout(n),n=setTimeout((()=>e.apply(this,o)),t)}}function A(e){if(!e.ok)throw Error(e.statusText);return e}function T(e){return void 0===e||["string","number","boolean"].includes(typeof e)||console.warn(`Operation expects a string, number or boolean, but got ${e} (${typeof e})`),null!=e?e:""}function S(e){return void 0!==e&&"string"!=typeof e&&console.warn(`Operation expects a string, but got ${e} (${typeof e})`),null!=e?String(e):""}function C(e){return void 0===e||Array.isArray(e)||console.warn(`Operation expects an array, but got ${e} (${typeof e})`),null!=e?Array.from(e):[]}function M(e){return void 0!==e&&"object"!=typeof e&&console.warn(`Operation expects an object, but got ${e} (${typeof e})`),null!=e?Object(e):{}}function x(e){return void 0===e||Array.isArray(e)||"string"==typeof e||console.warn(`Operation expects an Array or a String, but got ${e} (${typeof e})`),null==e?"":Array.isArray(e)?Array.from(e):String(e)}async function O(e,t){try{const n=await fetch(e,{headers:{"X-REQUESTED-WITH":"XmlHttpRequest",...t}});if(null==n)return;return A(n),n}catch(t){console.error(`Could not fetch ${e}`)}}var L=Object.freeze({__proto__:null,after:E,assignFocus:c,before:w,debounce:v,dispatch:u,fragmentToString:function(e){return(new XMLSerializer).serializeToString(e)},getClassNames:h,graciouslyFetch:O,handleErrors:A,isTextInput:l,kebabize:f,operate:y,processElements:p,safeArray:C,safeObject:M,safeScalar:T,safeString:S,safeStringOrArray:x,xpathToElement:d,xpathToElementArray:m});const R=e=>(t,n)=>!q.map((o=>"function"!=typeof o||o(e,t,n))).includes(!1),$=e=>t=>{_.forEach((n=>{"function"==typeof n&&n(e,t)}))},N=(e,t,n)=>!(!r[t.tagName]&&t.isEqualNode(n)),U=(e,t,n)=>t!==i.element||!t.isContentEditable,k=(e,t,n)=>{const{permanentAttributeName:o}=e;if(!o)return!0;const r=t.closest(`[${o}]`);if(!r&&t===i.element&&l(t)){const e={value:!0};return Array.from(n.attributes).forEach((n=>{e[n.name]||t.setAttribute(n.name,n.value)})),!1}return!r},q=[N,k,U],_=[];var P=Object.freeze({__proto__:null,didMorph:$,didMorphCallbacks:_,shouldMorph:R,shouldMorphCallbacks:q,verifyNotContentEditable:U,verifyNotMutable:N,verifyNotPermanent:k}),D={append:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{html:n,focusSelector:o}=e;t.insertAdjacentHTML("beforeend",T(n)),c(o)})),E(t,e)}))},graft:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{parent:n,focusSelector:o}=e,r=document.querySelector(n);r&&(r.appendChild(t),c(o))})),E(t,e)}))},innerHtml:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{html:n,focusSelector:o}=e;t.innerHTML=T(n),c(o)})),E(t,e)}))},insertAdjacentHtml:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{html:n,position:o,focusSelector:r}=e;t.insertAdjacentHTML(o||"beforeend",T(n)),c(r)})),E(t,e)}))},insertAdjacentText:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{text:n,position:o,focusSelector:r}=e;t.insertAdjacentText(o||"beforeend",T(n)),c(r)})),E(t,e)}))},outerHtml:e=>{p(e,(t=>{const n=t.parentElement,o=n&&Array.from(n.children).indexOf(t);w(t,e),y(e,(()=>{const{html:n,focusSelector:o}=e;t.outerHTML=T(n),c(o)})),E(n?n.children[o]:document.documentElement,e)}))},prepend:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{html:n,focusSelector:o}=e;t.insertAdjacentHTML("afterbegin",T(n)),c(o)})),E(t,e)}))},remove:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{focusSelector:n}=e;t.remove(),c(n)})),E(document,e)}))},replace:e=>{p(e,(t=>{const n=t.parentElement,o=n&&Array.from(n.children).indexOf(t);w(t,e),y(e,(()=>{const{html:n,focusSelector:o}=e;t.outerHTML=T(n),c(o)})),E(n?n.children[o]:document.documentElement,e)}))},textContent:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{text:n,focusSelector:o}=e;t.textContent=T(n),c(o)})),E(t,e)}))},addCssClass:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{name:n}=e;t.classList.add(...h([x(n)]))})),E(t,e)}))},removeAttribute:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{name:n}=e;t.removeAttribute(S(n))})),E(t,e)}))},removeCssClass:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{name:n}=e;t.classList.remove(...h([x(n)])),0===t.classList.length&&t.removeAttribute("class")})),E(t,e)}))},setAttribute:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{name:n,value:o}=e;t.setAttribute(S(n),T(o))})),E(t,e)}))},setDatasetProperty:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{name:n,value:o}=e;t.dataset[S(n)]=T(o)})),E(t,e)}))},setProperty:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{name:n,value:o}=e;n in t&&(t[S(n)]=T(o))})),E(t,e)}))},setStyle:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{name:n,value:o}=e;t.style[S(n)]=T(o)})),E(t,e)}))},setStyles:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{styles:n}=e;for(let[e,o]of Object.entries(n))t.style[S(e)]=T(o)})),E(t,e)}))},setValue:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{value:n}=e;t.value=T(n)})),E(t,e)}))},dispatchEvent:e=>{p(e,(t=>{w(t,e),y(e,(()=>{const{name:n,detail:o}=e;u(t,S(n),M(o))})),E(t,e)}))},setMeta:e=>{w(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=S(t),document.head.appendChild(o)),o.content=T(n)})),E(document,e)},setTitle:e=>{w(document,e),y(e,(()=>{const{title:t}=e;document.title=T(t)})),E(document,e)},clearStorage:e=>{w(document,e),y(e,(()=>{const{type:t}=e;("session"===t?sessionStorage:localStorage).clear()})),E(document,e)},go:e=>{w(window,e),y(e,(()=>{const{delta:t}=e;history.go(t)})),E(window,e)},pushState:e=>{w(window,e),y(e,(()=>{const{state:t,title:n,url:o}=e;history.pushState(M(t),S(n),S(o))})),E(window,e)},redirectTo:e=>{w(window,e),y(e,(()=>{let{url:t,action:n,turbo:o}=e;n=n||"advance",t=S(t),void 0===o&&(o=!0),o?(window.Turbo&&window.Turbo.visit(t,{action:n}),window.Turbolinks&&window.Turbolinks.visit(t,{action:n}),window.Turbo||window.Turbolinks||(window.location.href=t)):window.location.href=t})),E(window,e)},reload:e=>{w(window,e),y(e,(()=>{window.location.reload()})),E(window,e)},removeStorageItem:e=>{w(document,e),y(e,(()=>{const{key:t,type:n}=e;("session"===n?sessionStorage:localStorage).removeItem(S(t))})),E(document,e)},replaceState:e=>{w(window,e),y(e,(()=>{const{state:t,title:n,url:o}=e;history.replaceState(M(t),S(n),S(o))})),E(window,e)},scrollIntoView:e=>{const{element:t}=e;w(t,e),y(e,(()=>{t.scrollIntoView(e)})),E(t,e)},setCookie:e=>{w(document,e),y(e,(()=>{const{cookie:t}=e;document.cookie=T(t)})),E(document,e)},setFocus:e=>{const{element:t}=e;w(t,e),y(e,(()=>{c(t)})),E(t,e)},setStorageItem:e=>{w(document,e),y(e,(()=>{const{key:t,value:n,type:o}=e;("session"===o?sessionStorage:localStorage).setItem(S(t),T(n))})),E(document,e)},consoleLog:e=>{w(document,e),y(e,(()=>{const{message:t,level:n}=e;n&&["warn","info","error"].includes(n)?console[n](t):console.log(t)})),E(document,e)},consoleTable:e=>{w(document,e),y(e,(()=>{const{data:t,columns:n}=e;console.table(t,C(n))})),E(document,e)},notification:e=>{w(document,e),y(e,(()=>{const{title:t,options:n}=e;Notification.requestPermission().then((o=>{e.permission=o,"granted"===o&&new Notification(S(t),M(n))}))})),E(document,e)},morph:e=>{p(e,(n=>{const{html:o}=e,r=document.createElement("template");r.innerHTML=String(T(o)).trim(),e.content=r.content;const s=n.parentElement,a=s&&Array.from(s.children).indexOf(n);w(n,e),y(e,(()=>{const{childrenOnly:o,focusSelector:s}=e;t(n,o?r.content:r.innerHTML,{childrenOnly:!!o,onBeforeElUpdated:R(e),onElUpdated:$(e)}),c(s)})),E(s?s.children[a]:document.documentElement,e)}))}};let H=D;const I=e=>{H={...H,...e}};var j={get all(){return H}};let F="warn";var z={get behavior(){return F},set(e){["warn","ignore","event","exception"].includes(e)?F=e:console.warn("Invalid 'onMissingElement' option. Defaulting to 'warn'.")}};const X=(e,t={onMissingElement:z.behavior})=>{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.xpath?e.element=e.selectAll?m(e.selector):d(e.selector):e.element=e.selectAll?document.querySelectorAll(e.selector):document.querySelector(e.selector):e.element=document,e.element||"ignore"!==t.onMissingElement){i.set(document.activeElement);const t=j.all[o];t?(t(e),e.batch&&0==--n[e.batch]&&u(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(n){if(e.element)console.error(`CableReady detected an error in ${o||"operation"}: ${n.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(n);else{const n=`CableReady ${o||""} operation failed due to missing DOM element for selector: '${e.selector}'`;switch(t.onMissingElement){case"ignore":break;case"event":u(document,"cable-ready:missing-element",{warning:n,operation:e});break;case"exception":throw n;default:console.warn(n)}}}}))};class V extends HTMLElement{static get tagName(){throw new Error("Implement the tagName() getter in the inheriting class")}static define(){customElements.get(this.tagName)||customElements.define(this.tagName,this)}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")}}let Y;const Q=[25,50,75,100,200,250,500,800,1e3,2e3],Z=async(e=0)=>{if(Y)return Y;if(e>=Q.length)throw new Error("Couldn't obtain a Action Cable consumer within 5s");var t;return await(t=Q[e],new Promise((e=>setTimeout(e,t)))),await Z(e+1)};var B={setConsumer(e){Y=e},get consumer(){return Y},getConsumer:async()=>await Z()};class W extends V{static get tagName(){return"cable-ready-stream-from"}async connectedCallback(){if(this.preview)return;const e=await B.getConsumer();e?this.createSubscription(e,"CableReady::Stream",this.performOperations.bind(this)):console.error("The `cable_ready_stream_from` helper cannot connect. You must initialize CableReady with an Action Cable consumer.")}performOperations(e){e.cableReady&&X(e.operations,{onMissingElement:this.onMissingElement})}get onMissingElement(){const e=this.getAttribute("missing")||z.behavior;return["warn","ignore","event"].includes(e)?e:(console.warn("Invalid 'missing' attribute. Defaulting to 'warn'."),"warn")}}let G=!1;var J={get enabled(){return G},get disabled(){return!G},get value(){return G},set(e){G=!!e},set debug(e){G=!!e}};var K=(e,t)=>{J.disabled||console.log(`↑ Updatable request affecting ${t.length} element(s): `,{elements:t.map((e=>e.element)),identifiers:t.map((e=>e.element.getAttribute("identifier"))),data:e})},ee=(e,t)=>{if(J.disabled)return;const n=new Date-e;console.log(`❌ Updatable request canceled after ${n}ms: ${t}`)},te=(e,t,n)=>{if(J.disabled)return;const o=new Date-e;console.log(`↓ Updatable response: All URLs fetched in ${o}ms`,{element:t,urls:n})},ne=(e,t)=>{if(J.disabled)return;const n=new Date-e;console.log(`↻ Updatable morph: starting after ${n}ms`,{element:t})},oe=(e,t)=>{if(J.disabled)return;const n=new Date-e;console.log(`↺ Updatable morph: completed after ${n}ms`,{element:t})};class re extends V{static get tagName(){return"cable-ready-updates-for"}constructor(){super();this.attachShadow({mode:"open"}).innerHTML="\n\n\n"}async connectedCallback(){if(this.preview)return;this.update=v(this.update.bind(this),this.debounce);const e=await B.getConsumer();e?this.createSubscription(e,"CableReady::Stream",this.update):console.error("The `cable_ready_updates_for` helper cannot connect. You must initialize CableReady with an Action Cable consumer.")}async update(e){this.lastUpdateTimestamp=new Date;const t=Array.from(document.querySelectorAll(this.query),(e=>new se(e))).filter((t=>t.shouldUpdate(e)));if(K(e,t),0===t.length)return void ee(this.lastUpdateTimestamp,"All elements filtered out");if(t[0].element!==this)return void ee(this.lastUpdateTimestamp,"Update already requested");i.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 O(e,{"X-Cable-Ready":"update"});this.html[e]=await t.text()}}))),te(this.lastUpdateTimestamp,this,n),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,this.lastUpdateTimestamp)}))}get query(){return`${this.tagName}[identifier="${this.identifier}"]`}get identifier(){return this.getAttribute("identifier")}get debounce(){return this.hasAttribute("debounce")?parseInt(this.getAttribute("debounce")):20}}class se{constructor(e){this.element=e}async process(e,n,o,r){const s=o[this.url],a=document.createElement("template");this.element.setAttribute("updating","updating"),a.innerHTML=String(n[this.url]).trim(),await this.resolveTurboFrames(a.content);const i=a.content.querySelectorAll(this.query);if(i.length<=s)return void console.warn(`Update aborted due to insufficient number of elements. The offending url is ${this.url}.`);const l={element:this.element,html:i[s],permanentAttributeName:"data-ignore-updates"};u(this.element,"cable-ready:before-update",l),ne(r,this.element),t(this.element,i[s],{childrenOnly:!0,onBeforeElUpdated:R(l),onElUpdated:e=>{this.element.removeAttribute("updating"),u(this.element,"cable-ready:after-update",l),c(l.focusSelector)}}),oe(r,this.element)}async resolveTurboFrames(e){const t=[...e.querySelectorAll('turbo-frame[src]:not([loading="lazy"])')];return Promise.all(t.map((e=>new Promise((async t=>{const n=await O(e.getAttribute("src"),{"Turbo-Frame":e.id,"X-Cable-Ready":"update"}),o=document.createElement("template");o.innerHTML=await n.text(),await this.resolveTurboFrames(o.content);const r=`turbo-frame#${e.id}`,s=o.content.querySelector(r),a=s?s.innerHTML.trim():"";docFragment.querySelector(r).innerHTML=a,t()})))))}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 ae=e=>{const t=e&&e.parentElement&&e.parentElement.closest("cable-ready-updates-for");t&&(t.setAttribute("performing-inner-update",""),ae(t))},ie=e=>{const t=e&&e.parentElement&&e.parentElement.closest("cable-ready-updates-for");t&&(t.removeAttribute("performing-inner-update"),ie(t))},le=()=>{document.addEventListener("stimulus-reflex:before",(e=>{ae(e.detail.element)})),document.addEventListener("stimulus-reflex:after",(e=>{setTimeout((()=>{ie(e.detail.element)}))})),document.addEventListener("turbo:submit-start",(e=>{ae(e.target)})),document.addEventListener("turbo:submit-end",(e=>{setTimeout((()=>{ie(e.target)}))})),document.addEventListener("turbo-boost:command:start",(e=>{ae(e.target)})),document.addEventListener("turbo-boost:command:finish",(e=>{setTimeout((()=>{ie(e.target)}))})),document.addEventListener("turbo-boost:command:error",(e=>{setTimeout((()=>{ie(e.target)}))})),W.define(),re.define()},ce={perform:X,performAsync:(e,t={onMissingElement:z.behavior})=>new Promise(((n,o)=>{try{n(X(e,t))}catch(e){o(e)}})),shouldMorphCallbacks:q,didMorphCallbacks:_,initialize:(e={})=>{const{consumer:t,onMissingElement:n,debug:o}=e;J.set(!!o),t?B.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 })`."),n&&MissingElement.set(n),le()},addOperation:(e,t)=>{const n={};n[e]=t,I(n)},addOperations:e=>{I(e)},version:n,cable:B,get DOMOperations(){return console.warn("DEPRECATED: Please use `CableReady.operations` instead of `CableReady.DOMOperations`"),j.all},get operations(){return j.all},get consumer(){return B.consumer}};window.CableReady=ce,e.MorphCallbacks=P,e.StreamFromElement=W,e.SubscribingElement=V,e.UpdatesForElement=re,e.Utils=L,e.default=ce,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=cable_ready.umd.min.js.map