!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@hotwired/stimulus"),require("@rails/request.js"),require("stimulus-use"),require("jquery-events-to-dom-events"),require("lodash"),require("moment"),require("jquery"),require("daterangepicker")):"function"==typeof define&&define.amd?define(["exports","@hotwired/stimulus","@rails/request.js","stimulus-use","jquery-events-to-dom-events","lodash","moment","jquery","daterangepicker"],t):t((e||self).refineStimulus={},e.Stimulus,e.request_js,e.stimulusUse,e.jqueryEventsToDomEvents,e.lodash,e.moment,e.jquery)}(this,function(e,t,r,i,n,o,s,l){function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=a(s),c=a(l);function u(e){const t=(e.match(/^(?:\.\/)?(.+)(?:[_-]controller\..+?)$/)||[])[1];if(t)return t.replace(/_/g,"-").replace(/\//g,"--")}class h extends t.Controller{connect(){this.state.finishUpdate()}get state(){let e=this.element;for(;e!==document.body;){if(e.matches('[data-controller~="refine--state"]'))return this.application.getControllerForElementAndIdentifier(e,"refine--state");e=e.parentNode}return null}refreshFromServer(e){void 0===e&&(e={});try{const t=this,{includeErrors:i}=e;t.state.startUpdate();const n=new r.FetchRequest("GET",t.state.refreshUrlValue,{responseKind:"turbo-stream",query:{"refine_filters_builder[filter_class]":t.state.filterName,"refine_filters_builder[blueprint_json]":JSON.stringify(t.state.blueprint),"refine_filters_builder[client_id]":t.state.clientIdValue,include_errors:!!i}});return Promise.resolve(n.perform()).then(function(){})}catch(e){return Promise.reject(e)}}}class m extends h{criterion(){try{const e=this;return Promise.resolve(e.validateBlueprint()).then(function(t){t&&e.state.addCriterion(e.previousCriterionIdValue),e.refreshFromServer({includeErrors:!t})})}catch(e){return Promise.reject(e)}}group(){try{const e=this;return Promise.resolve(e.validateBlueprint()).then(function(t){t&&e.state.addGroup(),e.refreshFromServer({includeErrors:!t})})}catch(e){return Promise.reject(e)}}validateBlueprint(e){try{const e=this,t=new r.FetchRequest("GET",e.state.validateBlueprintUrlValue,{query:{"refine_filters_builder[filter_class]":e.state.filterName,"refine_filters_builder[blueprint_json]":JSON.stringify(e.state.blueprint),"refine_filters_builder[client_id]":e.state.clientIdValue}});return Promise.resolve(t.perform()).then(function(e){return e.ok})}catch(e){return Promise.reject(e)}}}m.values={previousCriterionId:Number};class p extends t.Controller{refresh(e){try{const e=this,t=document.getElementById(e.formIdValue),i=new FormData(t),n=new r.FetchRequest("GET",e.urlValue,{query:i,responseKind:"turbo-stream"});return Promise.resolve(n.perform()).then(function(){})}catch(e){return Promise.reject(e)}}}p.values={url:String,formId:String};class g extends t.Controller{connect(){this.state=this.getStateController(),this.state.updateInput(this.criterionIdValue,this.inputValue)}getStateController(){let e=this.element;for(;e!==document.body;){const t=this.application.getControllerForElementAndIdentifier(e,"refine--state");if(t)return t;e=e.parentNode}return null}}g.values={criterionId:Number,input:Object};class f extends h{criterion(){const{state:e,criterionIdValue:t}=this;e.deleteCriterion(t),this.refreshFromServer()}}f.values={criterionId:Number};class b extends t.Controller{connect(){const e=new URLSearchParams(window.location.search);this.existingParams=e,this.existingParams.delete("stable_id")}delete(e){const{criterionId:t}=e.currentTarget.dataset;var r=parseInt(t);this.stateController.deleteCriterion(r),this.reloadPage()}reloadPage(){try{const e=this,{blueprint:t}=e.stateController,i=new r.FetchRequest("POST",e.submitUrlValue,{responseKind:"turbo-stream",body:JSON.stringify({refine_filters_builder:{filter_class:e.stateController.filterName,blueprint_json:JSON.stringify(t),client_id:e.stateController.clientIdValue}})});return Promise.resolve(i.perform()).then(function(){})}catch(e){return Promise.reject(e)}}redirectToStableId(e){const t=new URLSearchParams;e&&t.append("stable_id",e);const r=new URLSearchParams({...Object.fromEntries(this.existingParams),...Object.fromEntries(t)}).toString(),i=window.location.pathname+"?"+r;history.pushState({},document.title,i),window.location.reload()}get stateController(){return this.element.refineStateController}get stabilizeFilterController(){return this.element.stabilizeFilterController}}b.values={submitUrl:String};class v extends t.Controller{connect(){i.useClickOutside(this),this.boundHandleKeyUp=this.handleKeyUp.bind(this),document.addEventListener("keyup",this.boundHandleKeyUp)}disconnect(){document.removeEventListener("keyup",this.boundHandleKeyUp)}show(e){e.preventDefault(),this.frameTarget.src=this.srcValue,this.isOpenValue=!0}hide(e){this.isOpenValue&&(null==e||e.preventDefault(),null==e||e.stopPropagation(),this.frameTarget.innerHTML="",this.isOpenValue=!1)}clickOutside(e){this.hide(e)}handleKeyUp(e){"Escape"!==e.key&&"Esc"!==e.key||this.hide(e)}}v.targets=["frame"],v.values={src:String,isOpen:{type:Boolean,default:!1}};class y extends t.Controller{connect(){i.useClickOutside(this)}disconnect(){}open(e){e.preventDefault(),this.frameTarget.src=this.srcValue,this.isOpenValue=!0}close(e){this.isOpenValue&&(null==e||e.preventDefault(),this.frameTarget.innerHTML="",this.isOpenValue=!1)}clickOutside(e){this.close(e)}}y.targets=["frame"],y.values={src:String,isOpen:{type:Boolean,default:!1}};class T extends t.Controller{search(e){e.preventDefault(),this.submitFilter(),document.activeElement.blur()}submitFilter(){try{const e=this,{blueprint:t}=e.stateController,i=new r.FetchRequest("POST",e.submitUrlValue,{responseKind:"turbo-stream",body:JSON.stringify({refine_filters_builder:{filter_class:e.stateController.filterName,blueprint_json:JSON.stringify(t),client_id:e.stateController.clientIdValue}})});return Promise.resolve(i.perform()).then(function(){})}catch(e){return Promise.reject(e)}}get stateController(){return this.element.querySelector('[data-controller~="refine--state"]').refineStateController}loadResults(e){let{detail:{url:t}}=e;console.log("filter submit success"),window.Turbo?window.Turbo.visit(t):window.location.href=t}}T.values={submitUrl:String},function(){if("function"==typeof window.CustomEvent)return!1;function e(e,t){t=t||{bubbles:!1,cancelable:!1,detail:void 0};var r=document.createEvent("CustomEvent");return r.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),r}e.prototype=window.Event.prototype,window.CustomEvent=e}();const C=(e,t)=>{let{blueprint:r,formId:i}=t;const n=new CustomEvent("blueprint-updated",{bubbles:!0,cancelable:!0,detail:{blueprint:r,formId:i}});e.dispatchEvent(n)},w=(e,t,r)=>{var i;const n=null==r?void 0:r.component,o=(null==r?void 0:r.meta)||{clauses:[],options:{}},s=(null==r?void 0:r.refinements)||[],{clauses:l,options:a}=o;let d;d="option-condition"===n?a[0]?[a[0].id]:[]:void 0;let c={clause:null==(i=l[0])?void 0:i.id,selected:d};return s.forEach(e=>{const{meta:t,component:r}=e,{clauses:i,options:n}=t;let o;o="option-condition"===r?n[0]?[n[0].id]:[]:void 0,c[e.id]={clause:i[0].id,selected:o}}),{depth:t,type:"criterion",condition_id:e,input:c}};class I extends t.Controller{connect(){this.element.refineStateController=this,this.changeDelegate=n.delegate("change",["event","picker"]),this.blueprint=this.blueprintValue,this.conditions=this.conditionsValue,this.filterName=this.classNameValue,this.conditionsLookup=this.conditions.reduce((e,t)=>(e[t.id]=t,e),{}),this.loadingTimeout=null,C(this.element,{blueprint:this.blueprint,formId:this.formIdValue})}disconnect(){n.abnegate("change",this.changeDelegate)}startUpdate(){this.loadingTimeout&&window.clearTimeout(this.loadingTimeout),this.loadingTimeout=window.setTimeout(()=>{this.loadingTarget.classList.remove("hidden")},1e3)}finishUpdate(){this.loadingTimeout&&window.clearTimeout(this.loadingTimeout),this.loadingTarget.classList.add("hidden")}conditionConfigFor(e){return this.conditionsLookup[e]}addGroup(){const{conditions:e}=this,t=e.find(e=>e.id==this.defaultConditionIdValue)||e[0];var r;this.blueprint.length>0&&this.blueprint.push({depth:r=void 0===r?0:r,type:"conjunction",word:"or"}),this.blueprint.push(w(t.id,1,t)),C(this.element,{blueprint:this.blueprint,formId:this.formIdValue})}addCriterion(e){const{blueprint:t,conditions:r}=this,i=r.find(e=>e.id==this.defaultConditionIdValue)||r[0];var n;t.splice(e+1,0,{depth:n=void 0===n?1:n,type:"conjunction",word:"and"},w(i.id,1,i)),C(this.element,{blueprint:this.blueprint,formId:this.formIdValue})}deleteCriterion(e){const{blueprint:t}=this,r=t[e-1],i=t[e+1],n=r&&"or"===r.word,o=i&&"or"===i.word||!i,s=n||!r,l=s&&o;r||i?t.splice(l&&n?e-1:l&&!r||s&&!o?e:e-1,2):this.blueprint=[],C(this.element,{blueprint:this.blueprint,formId:this.formIdValue})}replaceCriterion(e,t,r){const i=this.blueprint[e];if("criterion"!==i.type)throw new Error("You can't call updateConditionId on a non-criterion type. Trying to update "+JSON.stringify(w));const n=this.blueprint[e],s=w(t,i.depth,r);return!o.isEqual(n,s)&&(this.blueprint[e]=s,C(this.element,{blueprint:this.blueprint,formId:this.formIdValue}),!0)}updateInput(e,t,r){const{blueprint:i}=this,n=i[e],o=(r=r||"input").split(", ");o.length>1?n[o[0]][o[1]]={...n[o[0]][o[1]],...t}:n[r]={...n[r],...t},C(this.element,{blueprint:this.blueprint,formId:this.formIdValue})}}I.values={blueprint:Array,conditions:Array,className:String,refreshUrl:String,clientId:String,validateBlueprintUrl:String,defaultConditionId:String},I.targets=["loading"];class S extends t.Controller{connect(){const e=document.getElementById(this.stateDomIdValue).refineStateController;this.blueprintFieldTarget.value=JSON.stringify(e.blueprint),console.log("connect",this.blueprintFieldTarget.value)}updateBlueprintField(e){if(e.detail.formId!=this.formIdValue)return null;const{detail:t}=e,{blueprint:r}=t;this.blueprintFieldTarget.value=JSON.stringify(r),console.log("update blueprint",this.blueprintFieldTarget.value)}}S.targets=["blueprintField"],S.values={formId:String,stateDomId:String};class V extends t.Controller{submit(e){e.preventDefault(),this.element.requestSubmit()}}class E extends t.Controller{toggle(e){this.contentTargets.forEach(e=>{e.toggleAttribute("hidden")})}}E.targets=["content"];class F extends t.Controller{submit(e){try{const t=this;e.preventDefault();const i=new r.FetchRequest(t.element.method||"POST",t.element.action,{responseKind:"turbo-stream",body:new FormData(t.element)});return Promise.resolve(i.perform()).then(function(){})}catch(e){return Promise.reject(e)}}}class j extends t.Controller{visit(e){try{const t=this;e.preventDefault();const i=new r.FetchRequest(t.element.dataset.turboMethod||"GET",t.element.href,{responseKind:"turbo-stream"});return Promise.resolve(i.perform()).then(function(){})}catch(e){return Promise.reject(e)}}}class P extends t.Controller{filter(e){const t=e.currentTarget.value.toLowerCase();this.handleFilter(t)}clearSearch(){this.handleFilter("")}handleFilter(e){const t=new Set;this.listItemTargets.forEach(r=>{r.dataset.listItemValue.toLowerCase().includes(e)?(r.hidden=!1,t.add(r.dataset.category)):r.hidden=!0}),this.recommendedTargets.forEach(r=>{r.hidden=""!==e&&0===t.size}),this.categoryTargets.forEach(e=>{e.hidden=!t.has(e.innerHTML)})}}P.targets=["listItem","category","recommended"];class k extends h{initialize(){this.updateBlueprint=o.debounce((e,t,r)=>{this.value(e,t,r)},500)}refinedFilter(e){const{criterionIdValue:t,state:r}=this;r.updateInput(t,{id:e.target.value},e.target.dataset.inputId),this.refreshFromServer()}clause(e){const{criterionIdValue:t,state:r}=this;r.updateInput(t,{clause:e.target.value},e.target.dataset.inputId),this.refreshFromServer()}selected(e){const{target:t}=e,r=Array.prototype.slice.call(t.options).filter(e=>e.selected).map(e=>e.value);this.value(e,r,"selected")}value(e,t,r){const{criterionIdValue:i,state:n}=this,o=e.target.dataset,s=o.inputId;r=r||o.inputKey||"value","string"==typeof(t=t||e.target.value)&&(t=t.trim()),n.updateInput(i,{[r]:t},s)}condition(e){const{criterionIdValue:t,state:r}=this,i=e.target;let n=i.value;n||(n=i.querySelector("select").value);const o=this.state.conditionConfigFor(n);r.replaceCriterion(t,n,o)&&this.refreshFromServer()}cancelEnter(e){"Enter"===e.code&&(e.preventDefault(),e.stopPropagation())}}k.values={criterionId:Number},require("daterangepicker/daterangepicker.css");class D extends t.Controller{connect(){this.initPluginInstance()}disconnect(){this.teardownPluginInstance()}clearDate(e){e.preventDefault(),window.$(this.fieldTarget).val(""),this.dispatch("value-cleared")}applyDateToField(e,t){const r=this.includeTimeValue?this.timeFormatValue:this.dateFormatValue,i=t?d.default(t.startDate.toISOString()):d.default(this.fieldTarget.value,"YYYY-MM-DDTHH:mm").format("YYYY-MM-DDTHH:mm"),n=i.format(r),o=this.includeTimeValue?i.toISOString(!0):i.format("YYYY-MM-DD");this.fieldTarget.value=n,this.hiddenFieldTarget.value=o,window.$(this.fieldTarget).trigger("change",t),this.hiddenFieldTarget.dispatchEvent(new Event("change",{detail:t,bubbles:!0}))}initPluginInstance(){const e=this.pickerLocaleValue,t=this.isAmPmValue;e.format=this.includeTimeValue?this.timeFormatValue:this.dateFormatValue,window.$(this.fieldTarget).daterangepicker({singleDatePicker:!0,timePicker:this.includeTimeValue,timePickerIncrement:5,autoUpdateInput:!1,autoApply:!0,minDate:!!this.futureOnlyValue&&new Date,locale:e,parentEl:c.default(this.element),drops:this.dropsValue?this.dropsValue:"down",timePicker24Hour:!t}),window.$(this.fieldTarget).on("apply.daterangepicker",this.applyDateToField.bind(this)),window.$(this.fieldTarget).on("cancel.daterangepicker",this.clearDate.bind(this)),window.$(this.fieldTarget).on("showCalendar.daterangepicker",this.showCalendar.bind(this)),this.pluginMainEl=this.fieldTarget,this.plugin=c.default(this.pluginMainEl).data("daterangepicker"),this.inlineValue&&this.element.classList.add("date-input--inline")}teardownPluginInstance(){void 0!==this.plugin&&(c.default(this.pluginMainEl).off("apply.daterangepicker"),c.default(this.pluginMainEl).off("cancel.daterangepicker"),c.default(this.pluginMainEl).off("showCalendar.daterangepicker"),this.plugin.remove())}showCalendar(){this.dispatch("show-calendar")}}D.targets=["field","hiddenField","clearButton"],D.values={includeTime:Boolean,futureOnly:Boolean,drops:String,inline:Boolean,dateFormat:String,timeFormat:String,isAmPm:Boolean,locale:{type:String,default:"en"},datetimeFormat:{type:String,default:"MM/DD/YYYY h:mm A"},pickerLocale:{type:Object,default:{}}};class L extends t.Controller{connect(){this.observer=new IntersectionObserver(this.handleIntersection.bind(this),{root:this.scrollContainerTarget,threshold:1,rootMargin:"0px 0px -80% 0px"}),this.bottomObserver=new IntersectionObserver(this.handleBottomIntersection.bind(this),{root:this.scrollContainerTarget,threshold:1}),this.shouldHighlightCategories=!0,this.handleHighlightTimeout=null,this.bottomMarker=document.getElementById("refine--picker-bottom-marker"),this.categoryListItemTargets.forEach(e=>this.observer.observe(e)),this.bottomObserver.observe(this.bottomMarker)}disconnect(){this.bottomObserver.disconnect(),this.observer.disconnect()}handleIntersection(e){e.forEach(e=>{e.isIntersecting&&e.target!==this.bottomMarker&&1==e.intersectionRatio&&this.highlightCategory(e.target.dataset.categoryListItemValue)})}handleBottomIntersection(e){e.forEach(e=>{e.isIntersecting&&e.target===this.bottomMarker&&this.highlightCategory(this.categoryListItemTargets[this.categoryListItemTargets.length-1].dataset.categoryListItemValue)})}highlightCategory(e,t){void 0===t&&(t=!1),(this.shouldHighlightCategories||t)&&this.categoryShortcutItemTargets.forEach(t=>{t.dataset.inlineAdvancedModalValue===e?t.classList.add("active"):t.classList.remove("active")})}showSearchBar(){this.searchBarInputTarget.hidden=!1}hideSearchBar(){this.searchBarInputTarget.hidden=!0}findCategoryElementByName(e){return this.categoryListItemTargets.find(t=>t.dataset.categoryListItemValue===e)}clearSelection(){this.debounceScrollHighlights(),this.categoryShortcutItemTargets.forEach(e=>{e.classList.remove("active")})}clearSearch(){this.searchBarInputTarget.querySelector("input")&&(this.searchBarInputTarget.querySelector("input").value="")}scrollToCategory(e){const t=e.target.dataset.inlineAdvancedModalValue,r=this.findCategoryElementByName(t);r&&(this.shouldHighlightCategories=!1,r.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"}),setTimeout(()=>{this.shouldHighlightCategories=!0,this.highlightCategory(t,!0)},750))}debounceScrollHighlights(){this.shouldHighlightCategories=!1,clearTimeout(this.handleHighlightTimeout),this.handleHighlightTimeout=setTimeout(()=>{this.shouldHighlightCategories=!0},1e3)}}L.targets=["searchBarInput","categoryListItem","categoryBlockItem","categoryShortcutItem","scrollContainer"];class O extends t.Controller{connect(){this.currentScrollYPosition=0,this.navigateToTab=this.navigateToTab.bind(this),this.handleTabShow=this.handleTabShow.bind(this),this.navigateToTab(),document.addEventListener("turbo:load",this.navigateToTab),this.element.addEventListener("sl-tab-show",this.handleTabShow)}disconnect(){document.removeEventListener("turbo:load",this.navigateToTab),this.element.removeEventListener("sl-tab-show",this.handleTabShow)}handleTabShow(e){this.setLocationHash(e),this.keepScrollPositionValue&&this.handleTabChange()}setLocationHash(e){window.location.hash=e.detail.name}navigateToTab(){let e=window.location.hash.toString();if(e)this.element.show(e.slice(1));else{const e=new URLSearchParams(window.location.search),t=e.get("redirect_anchor");if(t){e.delete("redirect_anchor");let r=e.toString();window.history.replaceState(null,"",[window.location.pathname,r?"?"+r:"","#",t].join(""))}}}handleTabChange(){this.currentScrollYPosition=window.scrollY}show(e){const{showPanel:t}=e.params;this.element.show(t)}}O.values={keepScrollPosition:{type:Boolean,default:!1}};const _=[[m,"refine/add-controller.js"],[p,"refine/criterion-form-controller.js"],[g,"refine/defaults-controller.js"],[f,"refine/delete-controller.js"],[b,"refine/filter-pills-controller.js"],[v,"refine/popup-controller.js"],[y,"refine/modal-controller.js"],[T,"refine/search-filter-controller.js"],[h,"refine/server-refresh-controller.js"],[I,"refine/state-controller.js"],[S,"refine/stored-filter-controller.js"],[V,"refine/submit-form-controller.js"],[E,"refine/toggle-controller.js"],[F,"refine/turbo-stream-form-controller.js"],[j,"refine/turbo-stream-link-controller.js"],[P,"./refine/typeahead-list-controller.js"],[k,"refine/update-controller.js"],[D,"refine/date-controller.js"],[L,"refine/inline-advanced-modal-controller.js"],[O,"fields/shoelace/tab-group-controller.js"]].map(function(e){const t=e[0];return{identifier:u(e[1]),controllerConstructor:t}});e.AddController=m,e.CriterionFormController=p,e.DateController=D,e.DefaultsController=g,e.DeleteController=f,e.FilterPillsController=b,e.InlineAdvancedModalController=L,e.ModalController=y,e.PopupController=v,e.SearchFilterController=T,e.ServerRefreshController=h,e.StateController=I,e.StoredFilterController=S,e.SubmitForm=V,e.TabGroupController=O,e.ToggleController=E,e.TurboStreamFormController=F,e.TurboStreamLinkController=j,e.TypeaheadListController=P,e.UpdateController=k,e.controllerDefinitions=_}); //# sourceMappingURL=refine-stimulus.umd.js.map