import{Controller as e}from"@hotwired/stimulus";import{FetchRequest as t}from"@rails/request.js";import{useClickOutside as i}from"stimulus-use";import{delegate as r,abnegate as n}from"jquery-events-to-dom-events";import{isEqual as s,debounce as a}from"lodash";import o from"moment";import l from"jquery";import"daterangepicker";function d(e){const t=(e.match(/^(?:\.\/)?(.+)(?:[_-]controller\..+?)$/)||[])[1];if(t)return t.replace(/_/g,"-").replace(/\//g,"--")}class c extends e{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}async refreshFromServer(e={}){const{includeErrors:i}=e;this.state.startUpdate();const r=new t("GET",this.state.refreshUrlValue,{responseKind:"turbo-stream",query:{"refine_filters_builder[filter_class]":this.state.filterName,"refine_filters_builder[blueprint_json]":JSON.stringify(this.state.blueprint),"refine_filters_builder[client_id]":this.state.clientIdValue,include_errors:!!i}});await r.perform()}}class u extends c{async criterion(){const e=await this.validateBlueprint();e&&this.state.addCriterion(this.previousCriterionIdValue),this.refreshFromServer({includeErrors:!e})}async group(){const e=await this.validateBlueprint();e&&this.state.addGroup(),this.refreshFromServer({includeErrors:!e})}async validateBlueprint(e){const i=new t("GET",this.state.validateBlueprintUrlValue,{query:{"refine_filters_builder[filter_class]":this.state.filterName,"refine_filters_builder[blueprint_json]":JSON.stringify(this.state.blueprint),"refine_filters_builder[client_id]":this.state.clientIdValue}});return(await i.perform()).ok}}u.values={previousCriterionId:Number};class h extends e{async refresh(e){const i=document.getElementById(this.formIdValue),r=new FormData(i),n=new t("GET",this.urlValue,{query:r,responseKind:"turbo-stream"});await n.perform()}}h.values={url:String,formId:String};class p extends e{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}}p.values={criterionId:Number,input:Object};class m extends c{criterion(){const{state:e,criterionIdValue:t}=this;e.deleteCriterion(t),this.refreshFromServer()}}function f(){return f=Object.assign||function(e){for(var t=1;t{const r=new CustomEvent("blueprint-updated",{bubbles:!0,cancelable:!0,detail:{blueprint:t,formId:i}});e.dispatchEvent(r)},T=(e,t,i)=>{var r;const n=null==i?void 0:i.component,s=(null==i?void 0:i.meta)||{clauses:[],options:{}},a=(null==i?void 0:i.refinements)||[],{clauses:o,options:l}=s;let d;d="option-condition"===n?l[0]?[l[0].id]:[]:void 0;let c={clause:null==(r=o[0])?void 0:r.id,selected:d};return a.forEach(e=>{const{meta:t,component:i}=e,{clauses:r,options:n}=t;let s;s="option-condition"===i?n[0]?[n[0].id]:[]:void 0,c[e.id]={clause:r[0].id,selected:s}}),{depth:t,type:"criterion",condition_id:e,input:c}};class I extends e{connect(){this.element.refineStateController=this,this.changeDelegate=r("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(){n("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 i;this.blueprint.length>0&&this.blueprint.push({depth:i=void 0===i?0:i,type:"conjunction",word:"or"}),this.blueprint.push(T(t.id,1,t)),y(this.element,{blueprint:this.blueprint,formId:this.formIdValue})}addCriterion(e){const{blueprint:t,conditions:i}=this,r=i.find(e=>e.id==this.defaultConditionIdValue)||i[0];var n;t.splice(e+1,0,{depth:n=void 0===n?1:n,type:"conjunction",word:"and"},T(r.id,1,r)),y(this.element,{blueprint:this.blueprint,formId:this.formIdValue})}deleteCriterion(e){const{blueprint:t}=this,i=t[e-1],r=t[e+1],n=i&&"or"===i.word,s=r&&"or"===r.word||!r,a=n||!i,o=a&&s;i||r?t.splice(o&&n?e-1:o&&!i||a&&!s?e:e-1,2):this.blueprint=[],y(this.element,{blueprint:this.blueprint,formId:this.formIdValue})}replaceCriterion(e,t,i){const r=this.blueprint[e];if("criterion"!==r.type)throw new Error(`You can't call updateConditionId on a non-criterion type. Trying to update ${JSON.stringify(T)}`);const n=this.blueprint[e],a=T(t,r.depth,i);return!s(n,a)&&(this.blueprint[e]=a,y(this.element,{blueprint:this.blueprint,formId:this.formIdValue}),!0)}updateInput(e,t,i){const{blueprint:r}=this,n=r[e],s=(i=i||"input").split(", ");s.length>1?n[s[0]][s[1]]=f({},n[s[0]][s[1]],t):n[i]=f({},n[i],t),y(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 e{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:i}=t;this.blueprintFieldTarget.value=JSON.stringify(i),console.log("update blueprint",this.blueprintFieldTarget.value)}}S.targets=["blueprintField"],S.values={formId:String,stateDomId:String};class C extends e{submit(e){e.preventDefault(),this.element.requestSubmit()}}class V extends e{toggle(e){this.contentTargets.forEach(e=>{e.toggleAttribute("hidden")})}}V.targets=["content"];class E extends e{async submit(e){e.preventDefault();const i=new t(this.element.method||"POST",this.element.action,{responseKind:"turbo-stream",body:new FormData(this.element)});await i.perform()}}class F extends e{async visit(e){e.preventDefault();const i=new t(this.element.dataset.turboMethod||"GET",this.element.href,{responseKind:"turbo-stream"});await i.perform()}}class j extends e{filter(e){const t=e.currentTarget.value.toLowerCase(),i=new Set;this.listItemTargets.forEach(e=>{e.dataset.listItemValue.toLowerCase().includes(t)?(e.hidden=!1,i.add(e.dataset.category)):e.hidden=!0}),this.recommendedTargets.forEach(e=>{e.hidden=""!==t&&0===i.size}),this.categoryTargets.forEach(e=>{e.hidden=!i.has(e.innerHTML)})}}j.targets=["listItem","category","recommended"];class _ extends c{initialize(){this.updateBlueprint=a((e,t,i)=>{this.value(e,t,i)},500)}refinedFilter(e){const{criterionIdValue:t,state:i}=this;i.updateInput(t,{id:e.target.value},e.target.dataset.inputId),this.refreshFromServer()}clause(e){const{criterionIdValue:t,state:i}=this;i.updateInput(t,{clause:e.target.value},e.target.dataset.inputId),this.refreshFromServer()}selected(e){const{target:t}=e,i=Array.prototype.slice.call(t.options).filter(e=>e.selected).map(e=>e.value);this.value(e,i,"selected")}value(e,t,i){const{criterionIdValue:r,state:n}=this,s=e.target.dataset,a=s.inputId;i=i||s.inputKey||"value","string"==typeof(t=t||e.target.value)&&(t=t.trim()),n.updateInput(r,{[i]:t},a)}condition(e){const{criterionIdValue:t,state:i}=this,r=e.target;let n=r.value;n||(n=r.querySelector("select").value);const s=this.state.conditionConfigFor(n);i.replaceCriterion(t,n,s)&&this.refreshFromServer()}cancelEnter(e){"Enter"===e.code&&(e.preventDefault(),e.stopPropagation())}}_.values={criterionId:Number},require("daterangepicker/daterangepicker.css");class D extends e{connect(){this.initPluginInstance()}disconnect(){this.teardownPluginInstance()}clearDate(e){e.preventDefault(),window.$(this.fieldTarget).val(""),this.dispatch("value-cleared")}applyDateToField(e,t){const i=this.includeTimeValue?this.timeFormatValue:this.dateFormatValue,r=t?o(t.startDate.toISOString()):o(this.fieldTarget.value,"YYYY-MM-DDTHH:mm").format("YYYY-MM-DDTHH:mm"),n=r.format(i),s=this.includeTimeValue?r.toISOString(!0):r.format("YYYY-MM-DD");this.fieldTarget.value=n,this.hiddenFieldTarget.value=s,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:l(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=l(this.pluginMainEl).data("daterangepicker"),this.inlineValue&&this.element.classList.add("date-input--inline")}teardownPluginInstance(){void 0!==this.plugin&&(l(this.pluginMainEl).off("apply.daterangepicker"),l(this.pluginMainEl).off("cancel.daterangepicker"),l(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 k extends e{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 O extends e{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 i=e.toString();window.history.replaceState(null,"",[window.location.pathname,i?`?${i}`:"","#",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 P=[[u,"refine/add-controller.js"],[h,"refine/criterion-form-controller.js"],[p,"refine/defaults-controller.js"],[m,"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"],[c,"refine/server-refresh-controller.js"],[I,"refine/state-controller.js"],[S,"refine/stored-filter-controller.js"],[C,"refine/submit-form-controller.js"],[V,"refine/toggle-controller.js"],[E,"refine/turbo-stream-form-controller.js"],[F,"refine/turbo-stream-link-controller.js"],[j,"./refine/typeahead-list-controller.js"],[_,"refine/update-controller.js"],[D,"refine/date-controller.js"],[k,"refine/inline-advanced-modal-controller.js"],[O,"fields/shoelace/tab-group-controller.js"]].map(function(e){const t=e[0];return{identifier:d(e[1]),controllerConstructor:t}});export{u as AddController,h as CriterionFormController,D as DateController,p as DefaultsController,m as DeleteController,g as FilterPillsController,k as InlineAdvancedModalController,v as ModalController,b as PopupController,w as SearchFilterController,c as ServerRefreshController,I as StateController,S as StoredFilterController,C as SubmitForm,O as TabGroupController,V as ToggleController,E as TurboStreamFormController,F as TurboStreamLinkController,j as TypeaheadListController,_ as UpdateController,P as controllerDefinitions}; //# sourceMappingURL=refine-stimulus.modern.js.map