var e=require("@hotwired/stimulus"),t=require("@rails/request.js"),r=require("stimulus-use"),i=require("jquery-events-to-dom-events"),n=require("lodash"),o=require("moment"),s=require("jquery");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("daterangepicker");var a=l(o),d=l(s);function c(e){const t=(e.match(/^(?:\.\/)?(.+)(?:[_-]controller\..+?)$/)||[])[1];if(t)return t.replace(/_/g,"-").replace(/\//g,"--")}class u extends e.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 r=this,{includeErrors:i}=e;r.state.startUpdate();const n=new t.FetchRequest("GET",r.state.refreshUrlValue,{responseKind:"turbo-stream",query:{"refine_filters_builder[filter_class]":r.state.filterName,"refine_filters_builder[blueprint_json]":JSON.stringify(r.state.blueprint),"refine_filters_builder[client_id]":r.state.clientIdValue,include_errors:!!i}});return Promise.resolve(n.perform()).then(function(){})}catch(e){return Promise.reject(e)}}}class h extends u{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,r=new t.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(r.perform()).then(function(e){return e.ok})}catch(e){return Promise.reject(e)}}}h.values={previousCriterionId:Number};class p extends e.Controller{refresh(e){try{const e=this,r=document.getElementById(e.formIdValue),i=new FormData(r),n=new t.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 m extends e.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}}m.values={criterionId:Number,input:Object};class f extends u{criterion(){const{state:e,criterionIdValue:t}=this;e.deleteCriterion(t),this.refreshFromServer()}}f.values={criterionId:Number};class g extends e.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:r}=e.stateController,i=new t.FetchRequest("POST",e.submitUrlValue,{responseKind:"turbo-stream",body:JSON.stringify({refine_filters_builder:{filter_class:e.stateController.filterName,blueprint_json:JSON.stringify(r),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}}g.values={submitUrl:String};class b extends e.Controller{connect(){r.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)}}b.targets=["frame"],b.values={src:String,isOpen:{type:Boolean,default:!1}};class v extends e.Controller{connect(){r.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)}}v.targets=["frame"],v.values={src:String,isOpen:{type:Boolean,default:!1}};class w extends e.Controller{search(e){e.preventDefault(),this.submitFilter(),document.activeElement.blur()}submitFilter(){try{const e=this,{blueprint:r}=e.stateController,i=new t.FetchRequest("POST",e.submitUrlValue,{responseKind:"turbo-stream",body:JSON.stringify({refine_filters_builder:{filter_class:e.stateController.filterName,blueprint_json:JSON.stringify(r),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}}w.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 y=(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)},C=(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 T extends e.Controller{connect(){this.element.refineStateController=this,this.changeDelegate=i.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,y(this.element,{blueprint:this.blueprint,formId:this.formIdValue})}disconnect(){i.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(C(t.id,1,t)),y(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"},C(i.id,1,i)),y(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=[],y(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(C));const o=this.blueprint[e],s=C(t,i.depth,r);return!n.isEqual(o,s)&&(this.blueprint[e]=s,y(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},y(this.element,{blueprint:this.blueprint,formId:this.formIdValue})}}T.values={blueprint:Array,conditions:Array,className:String,refreshUrl:String,clientId:String,validateBlueprintUrl:String,defaultConditionId:String},T.targets=["loading"];class I extends e.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)}}I.targets=["blueprintField"],I.values={formId:String,stateDomId:String};class S extends e.Controller{submit(e){e.preventDefault(),this.element.requestSubmit()}}class V extends e.Controller{toggle(e){this.contentTargets.forEach(e=>{e.toggleAttribute("hidden")})}}V.targets=["content"];class E extends e.Controller{submit(e){try{const r=this;e.preventDefault();const i=new t.FetchRequest(r.element.method||"POST",r.element.action,{responseKind:"turbo-stream",body:new FormData(r.element)});return Promise.resolve(i.perform()).then(function(){})}catch(e){return Promise.reject(e)}}}class F extends e.Controller{visit(e){try{const r=this;e.preventDefault();const i=new t.FetchRequest(r.element.dataset.turboMethod||"GET",r.element.href,{responseKind:"turbo-stream"});return Promise.resolve(i.perform()).then(function(){})}catch(e){return Promise.reject(e)}}}class P extends e.Controller{filter(e){const t=e.currentTarget.value.toLowerCase(),r=new Set;this.listItemTargets.forEach(e=>{e.dataset.listItemValue.toLowerCase().includes(t)?(e.hidden=!1,r.add(e.dataset.category)):e.hidden=!0}),this.recommendedTargets.forEach(e=>{e.hidden=""!==t&&0===r.size}),this.categoryTargets.forEach(e=>{e.hidden=!r.has(e.innerHTML)})}}P.targets=["listItem","category","recommended"];class j extends u{initialize(){this.updateBlueprint=n.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())}}j.values={criterionId:Number},require("daterangepicker/daterangepicker.css");class x extends e.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?a.default(t.startDate.toISOString()):a.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:d.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=d.default(this.pluginMainEl).data("daterangepicker"),this.inlineValue&&this.element.classList.add("date-input--inline")}teardownPluginInstance(){void 0!==this.plugin&&(d.default(this.pluginMainEl).off("apply.daterangepicker"),d.default(this.pluginMainEl).off("cancel.daterangepicker"),d.default(this.pluginMainEl).off("showCalendar.daterangepicker"),this.plugin.remove())}showCalendar(){this.dispatch("show-calendar")}}x.targets=["field","hiddenField","clearButton"],x.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 k extends e.Controller{connect(){this.observer=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:1}),this.categoryBlockItemTargets.forEach(e=>this.observer.observe(e))}disconnect(){this.observer.disconnect()}handleIntersection(e){e.forEach(e=>{e.isIntersecting&&this.highlightCategory(e.target.dataset.categoryListBlockValue)})}highlightCategory(e){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)}scrollToCategory(e){const t=this.findCategoryElementByName(e.target.dataset.inlineAdvancedModalValue);t&&t.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})}}k.targets=["searchBarInput","categoryListItem","categoryBlockItem","categoryShortcutItem"];class D extends e.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)}}D.values={keepScrollPosition:{type:Boolean,default:!1}};const _=[[h,"refine/add-controller.js"],[p,"refine/criterion-form-controller.js"],[m,"refine/defaults-controller.js"],[f,"refine/delete-controller.js"],[g,"refine/filter-pills-controller.js"],[b,"refine/popup-controller.js"],[v,"refine/modal-controller.js"],[w,"refine/search-filter-controller.js"],[u,"refine/server-refresh-controller.js"],[T,"refine/state-controller.js"],[I,"refine/stored-filter-controller.js"],[S,"refine/submit-form-controller.js"],[V,"refine/toggle-controller.js"],[E,"refine/turbo-stream-form-controller.js"],[F,"refine/turbo-stream-link-controller.js"],[P,"./refine/typeahead-list-controller.js"],[j,"refine/update-controller.js"],[x,"refine/date-controller.js"],[k,"refine/inline-advanced-modal-controller.js"],[D,"fields/shoelace/tab-group-controller.js"]].map(function(e){const t=e[0];return{identifier:c(e[1]),controllerConstructor:t}});exports.AddController=h,exports.CriterionFormController=p,exports.DateController=x,exports.DefaultsController=m,exports.DeleteController=f,exports.FilterPillsController=g,exports.InlineAdvancedModalController=k,exports.ModalController=v,exports.PopupController=b,exports.SearchFilterController=w,exports.ServerRefreshController=u,exports.StateController=T,exports.StoredFilterController=I,exports.SubmitForm=S,exports.TabGroupController=D,exports.ToggleController=V,exports.TurboStreamFormController=E,exports.TurboStreamLinkController=F,exports.TypeaheadListController=P,exports.UpdateController=j,exports.controllerDefinitions=_; //# sourceMappingURL=refine-stimulus.js.map