-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsmart.filterbuilder.js
6 lines (4 loc) · 51.7 KB
/
smart.filterbuilder.js
1
2
3
4
5
6
/* Smart UI v15.2.0 (2023-04-20)
Copyright (c) 2011-2023 jQWidgets.
License: https://htmlelements.com/license/ */ //
Smart("smart-query-builder",class extends Smart.BaseElement{static get properties(){return{allowDrag:{value:!1,type:"boolean"},autoPrompt:{value:!1,type:"boolean"},applyMode:{allowValues:["immediately","change"],value:"change",type:"string"},autoApplyValue:{value:!1,type:"boolean"},customOperations:{value:[],type:"array",reflectToAttribute:!1},customOperators:{value:{},type:"object",reflectToAttribute:!1},dropDownWidth:{type:"any",value:"auto"},fields:{value:null,type:"array?",reflectToAttribute:!1},fieldsMode:{value:"dynamic",allowedValues:["dynamic","static"],type:"string"},formatStringDate:{value:"dd-MMM-yy",type:"string"},formatStringDateTime:{value:"dd-MMM-yy HH:mm:ss",type:"string"},getDynamicField:{value:null,type:"function?"},icons:{value:{"=":"equals","<>":"notequals",">":"greaterthan",">=":"greaterthanorequal","<":"lessthan","<=":"lessthanorequal",startswith:"startswith",endswith:"endswith",contains:"contains",notcontains:"notcontains",isblank:"isblank",isnotblank:"isnotblank"},type:"object",reflectToAttribute:!1},messages:{value:{en:{add:"Add",addCondition:"Add Condition",addGroup:"Add Group",and:"And",notand:"Not And",or:"Or",notor:"Not Or","=":"Equals","<>":"Does not equal",">":"Greater than",">=":"Greater than or equal to","<":"Less than","<=":"Less than or equal to",startswith:"Starts with",endswith:"Ends with",contains:"Contains",notcontains:"Does not contain",isblank:"Is blank",isnotblank:"Is not blank",wrongParentGroupIndex:'{{elementType}}: Wrong parent group index in "{{method}}" method.',wrongElementNode:'{{elementType}}: Incorect node / node Id in "{{method}}" method.',invalidDataStructure:"{{elementType}}: Used invalid data structure in updateCondition/updateGroup method.",dateTabLabel:"DATE",timeTabLabel:"TIME",queryLabel:"Query"}},type:"object",extend:!0},operatorPlaceholder:{value:"Operator",type:"string"},propertyPlaceholder:{value:"Property",type:"string"},showIcons:{value:!1,type:"boolean"},showFieldNameArrow:{value:!1,type:"boolean"},validateOnInput:{value:!1,type:"boolean"},validationTimeout:{value:100,type:"number"},value:{value:[],type:"any",reflectToAttribute:!1},valueFormatFunction:{value:null,type:"function?",reflectToAttribute:!1},valuePlaceholder:{value:"Value",type:"string"}}}static get requires(){const e={"Smart.Button":"smart.button.js","Smart.Calendar":"smart.calendar.js","Smart.CheckBox":"smart.checkbox.js","Smart.DateTimePicker":"smart.datetimepicker.js","Smart.DropDownList":"smart.dropdownlist.js","Smart.Input":"smart.input.js","Smart.ListBox":"smart.listbox.js","Smart.Menu":"smart.menu.js","Smart.NumericTextBox":"smart.numerictextbox.js","Smart.ScrollBar":"smart.scrollbar.js","Smart.TimePicker":"smart.timepicker.js","Smart.Tooltip":"smart.tooltip.js","Smart.Utilities.BigNumber":"smart.math.js","Smart.Utilities.DateTime":"smart.date.js","Smart.Utilities.Draw":"smart.draw.js","Smart.Utilities.NumericProcessor":"smart.numeric.js"};return window.NIComplex||(e["Smart.Utilities.Complex"]="smart.complex.js"),e}static get listeners(){return{down:"_downHandler",resize:"_resizeHandler","editorsContainer.keydown":"_editorsContainerKeydownHandler","editorsContainer.keyup":"_editorsContainerKeyUpHandler","conditionsMenu.close":"_menuCloseHandler","conditionsMenu.closing":"_menuClosingHandler","conditionsMenu.itemClick":"_menuItemClickHandler","contentContainer.change":"_contentContainerChangeHandler","contentContainer.itemClick":"_contentContainerChangeHandler","scrollableContainer.touchmove":"_scrollableContainerTouchmoveHandler","document.down":"_documentDownHandler","document.move":"_documentMoveHandler","document.up":"_documentUpHandler"}}static get styleUrls(){return["smart.querybuilder.css"]}template(){return'<div id="container" role="presentation">\n <smart-scroll-viewer id="scrollableContainer" class="smart-scrollable-container" animation="[[animation]]" right-to-left="[[rightToLeft]]">\n <div id="queryLabel" class="smart-query-builder-label smart-unselectable"></div>\n <div id="contentContainer" class="smart-content-container"></div>\n </smart-scroll-viewer>\n <div id="editorsContainer" class="smart-editors-container" role="presentation">\n <div id="customEditor" class="smart-custom-editor smart-hidden"></div>\n </div>\n <smart-menu id="conditionsMenu" mode="dropDown" class="smart-conditions-menu" theme="[[theme]]" animation="[[animation]]" right-to-left="[[rightToLeft]]"></smart-menu>\n </div>'}propertyChangedHandler(e,t,a){super.propertyChangedHandler(e,t,a);const i=this;switch(e){case"animation":case"theme":["textBoxEditor","numericTextBoxEditor","comboBoxEditor","dateTimePickerEditor","checkBoxEditor"].forEach((t=>i.$[t]&&(i.$[t][e]=a)));break;case"formatStringDate":case"formatStringDateTime":case"valueFormatFunction":i._refresh();break;case"operatorPlaceholder":Array.from((i.shadowRoot||i).querySelectorAll(".smart-filter-operation[placeholder]")).forEach((e=>e.firstElementChild.innerHTML=a));break;case"propertyPlaceholder":Array.from((i.shadowRoot||i).querySelectorAll(".smart-filter-field-name[placeholder]")).forEach((e=>e.firstElementChild.innerHTML=a));break;case"showIcons":i._closeEditor(),a?i._filterOperationDescriptions.map((e=>e.icon=i.icons[e.value])):i._filterOperationDescriptions.map((e=>delete e.icon));break;case"customOperations":case"fields":case"value":{const t=JSON.stringify(i._validValue),o=i._queryParser;"customOperations"===e?i._handleCustomOperations():""===e&&i._mapFieldsToMenu(),i._applyValue(),"customOperations"!==e&&"fields"!==e||(o[e]=a),i._oldValueAsString!==t&&(i._oldValueAsString=JSON.stringify(i._validValue),i.$.fireEvent("change",{value:JSON.parse(i._oldValueAsString),linq:o.toLinq(i._validValue)}));break}case"valuePlaceholder":Array.from((i.shadowRoot||i).querySelectorAll(".smart-filter-value[placeholder]")).forEach((e=>e.firstElementChild.innerHTML=a));break;case"locale":case"messages":i._localizeInitialValues(),i._refresh(),i._handleCustomOperations(),i.$.dateTimePickerEditor&&(i.$.dateTimePickerEditor.messages[i.locale]||(i.$.dateTimePickerEditor.messages[i.locale]={}),i.$.dateTimePickerEditor.messages[i.locale].dateTabLabel=i.localize("dateTabLabel"),i.$.dateTimePickerEditor.messages[i.locale].timeTabLabel=i.localize("timeTabLabel"),"locale"===e?i.$.dateTimePickerEditor.locale=i.locale:"messages"===e&&(i.$.dateTimePickerEditor.$.selectDate.innerHTML=i.$.dateTimePickerEditor.messages[i.locale].dateTabLabel,i.$.dateTimePickerEditor.$.selectTime.innerHTML=i.$.dateTimePickerEditor.messages[i.locale].timeTabLabel));break;case"icons":i._closeEditor()}}ready(){super.ready();const e=this;e.$.queryLabel.id||(e.$.queryLabel.id=e.id+"Label"),e.setAttribute("role","dialog"),e.setAttribute("aria-labelledby",e.$.queryLabel.id),-1!==navigator.platform.toLowerCase().lastIndexOf("mac")&&e.$.contentContainer.classList.add("mac"),e._queryParser=new Smart.Utilities.QueryParser,e._setInitialValues(),e._handleCustomOperations(),e._applyValue(),Object.defineProperty(e,"value",{get:function(){return e.context===e?e.properties.value.value:e._validValue},set(t){e.updateProperty(e,e._properties.value,t)}})}getLinq(){const e=this;if(e._validValue)return e._queryParser.customOperations=e.customOperations,e._queryParser.fields=e.fields,e._queryParser.dynamicField="dynamic"===e.fieldsMode?e.getDynamicField:void 0,e._queryParser.toLinq(e._validValue)}get validationStatus(){const e=this;return!e.isReady||void 0===e._validationStatus||e._validationStatus}_setInitialValues(){const e=this;e._autoScrollCoefficient=Smart.Utilities.Core.Browser.Firefox?4:Smart.Utilities.Core.Browser.Edge?8:2,e._isMobile=Smart.Utilities.Core.isMobile,e._manuallyAddedFields=[],e._localizeInitialValues(),e.$.conditionsMenu.dropDownAppendTo=e.$.container,e.$.conditionsMenu.dataSource=e._groupOperationDescriptions,e._valueFlat=[],e._lastProcessedItemInCurrentGroup={parentId:null,id:null,position:null}}_applyValue(){const e=this;e._emptyElementsStructure(!0),e._validateValue(),e._convertValueToFlat(e.value),e._getFieldsFromValue(),e._mapFieldsToMenu(),e._validateValueByType(),e._generateHTMLStructureFromFlatValue(!0),e._restrictNesting(),e._validValue=e._getValidValue(),e._oldValueAsString=JSON.stringify(e._validValue)}_validateValueByType(){const e=this;if(!e._valueFlat||!e._valueFlat.length)return;const t=e._valueFlat;for(let a=0;a<t.length;a++){const i=t[a];if("condition"!==i.type)continue;const o=i.data[0];!o||i.data.length<3||(i.data[2]=e._validateStoredValue(i.data[2],o))}e._generateValue(!0)}_applyValidationOnInput(){const e=this,t=e._editor;if(!t||!e._editorIsOpen)return;const a=t.closest(".filter-builder-item"),i=t.closest(".smart-filter-group-condition");a&&a.classList.contains("smart-filter-value")&&(clearTimeout(e._valueValidationTimeout),e._valueValidationTimeout=setTimeout((()=>{const a=i.getAttribute("node-id"),o=e.value.toString();clearTimeout(e._valueValidationTimeout),e._closeEditor(),o===e.value.toString()&&e._generateValue();const l=e._getItemById(a);l&&(t.setAttribute("focus",""),e._openEditor(l.htmlNode.querySelector(".smart-filter-value"))),delete e._valueValidationTimeout}),e.validationTimeout))}_contentContainerChangeHandler(e){const t=this,a=e.type,i=e.target,o=t._editor,l=t._editorIsOpen,r=t.applyMode;if(e.stopPropagation(),"change"===a&&t.validateOnInput&&l&&i===o&&t._applyValidationOnInput(),"itemClick"===a&&i.value!==e.detail.label||"immediately"!==r||!l||!o||"immediately"===r&&i!==o)return;const n=t._editor.closest(".filter-builder-item");n.classList.contains("smart-filter-value")||(t._closeEditor(),t._handleAutoPrompt(n))}_handleAutoPrompt(e){const t=this;if(e&&t.autoPrompt&&"immediately"===t.applyMode&&!e.classList.contains("smart-filter-value")){const a=e.closest(".smart-filter-group-condition")||e.closest(".smart-filter-nested-operator")||e.closest(".smart-filter-group");if(!a)return;const i=t._getItemById(a.getAttribute("node-id")),o=a.querySelector(".smart-filter-value");if(!i||!o)return;t._clickHandlerFilterButton(e.classList,i.nodeId,o)}}_mapFieldsToMenu(){const e=this;(e.fields||e._valueFields)&&(e._fields=(e.fields||e._valueFields).concat(e._manuallyAddedFields).map((e=>({label:e.label,value:e.dataField,dataType:e.dataType,filterOperations:e.filterOperations,lookup:e.lookup}))))}_localizeInitialValues(){const e=this;e.$.queryLabel.innerHTML=e.localize("queryLabel"),e._addOptions=[{label:e.localize("addCondition"),value:"addCondition"},{label:e.localize("addGroup"),value:"addGroup"}],e._groupOperationDescriptions=[{label:e.localize("and"),value:"and"},{label:e.localize("or"),value:"or"}],e._defaultFilterOperationDescriptions=e._filterOperationDescriptions=[{label:e.localize("="),value:"=",custom:!1},{label:e.localize("<>"),value:"<>",custom:!1},{label:e.localize(">"),value:">",custom:!1},{label:e.localize(">="),value:">=",custom:!1},{label:e.localize("<"),value:"<",custom:!1},{label:e.localize("<="),value:"<=",custom:!1},{label:e.localize("startswith"),value:"startswith",custom:!1},{label:e.localize("endswith"),value:"endswith",custom:!1},{label:e.localize("contains"),value:"contains",custom:!1},{label:e.localize("notcontains"),value:"notcontains",custom:!1},{label:e.localize("isblank"),value:"isblank",custom:!1},{label:e.localize("isnotblank"),value:"isnotblank",custom:!1}];const t=Smart.Utilities.DateTime.getLocalizedNames(e.locale);e._localizedDays=t.days,e._localizedMonths=t.months}_handleCustomOperations(){const e=this;e._filterOperationDescriptions=e._defaultFilterOperationDescriptions.slice(0);for(let t=0;t<e.customOperations.length;t++){let a=e.customOperations[t],i=e._filterOperationDescriptions.findIndex((e=>e.value===a.name)),o={label:a.label,value:a.name,custom:!0,index:t,editorTemplate:a.editorTemplate,valueTemplate:a.valueTemplate,handleValue:a.handleValue,hideValue:a.hideValue,validateValue:a.validateValue};i>-1?e._filterOperationDescriptions[i]=o:e._filterOperationDescriptions.push(o)}}_editorsContainerKeydownHandler(e){const t=this;if(t._editorIsOpen&&("Escape"===e.key||"Enter"===e.key)){t._closeEditor();const e=t._editor.closest(".filter-builder-item");e&&!e.classList.contains("smart-filter-value")&&t._handleAutoPrompt(e)}}_editorsContainerKeyUpHandler(e){const t=this,a=t._editor;a&&a.contains(e.target)&&t._editorIsOpen&&t.validateOnInput&&t._applyValidationOnInput()}_documentDownHandler(e){const t=this,a=t.shadowRoot||t.isInShadowDOM?e.originalEvent.composedPath()[0]:e.originalEvent.target;if(a.shadowParent&&a.shadowParent.closest(".smart-input-drop-down-menu")||a.closest(".smart-input-drop-down-menu")||t.$.conditionsMenu.contains(a))return;const i=a.closest(".smart-drop-down");if(a.getRootNode().host===t||a.closest("smart-query-builder")===t||i&&t.contains(i.ownerElement))if(t._isMobile){const a=t.$.scrollableContainer.scrollTop,i=t.getBoundingClientRect().top;setTimeout((function(){if(t.$.scrollableContainer.scrollTop===a&&t.getBoundingClientRect().top===i){const a=t.context;t.context=t,t._clickHandler(e.originalEvent),t.context=a}}),250)}else t._clickHandler(e.originalEvent);else t._editorIsOpen&&!t._scrollBarDown&&t._closeEditor(),delete t._scrollBarDown}_emptyElementsStructure(e){const t=this,a=t.$.contentContainer;for(;a.firstChild;)a.removeChild(a.firstChild);t._valueFlat=e?[]:t._valueFlat,t._lastProcessedItemInCurrentGroup={parentId:null,id:null,position:null}}_resizeHandler(){this.$.scrollableContainer.refresh()}_getTotalConditions(){return this.getElementsByClassName("smart-filter-group-condition").length}_parseLinqToValue(){const e=this,t=e._queryParser;t&&(t.customOperations=e.customOperations,t.fields=e.fields,t.dynamicField="dynamic"===e.fieldsMode?e.getDynamicField:void 0,e.set("value",t.toValue(e.value)))}_validateValue(){const e=this;"string"==typeof e.value&&e._parseLinqToValue();const t=e.properties.value.value;if(Array.isArray(t)&&""!==JSON.stringify(t).replace(/[\[\]]/g,"")){for(3===t.length&&"string"==typeof t[0]&&(e.value=[[t]]),Array.isArray(t[0])&&3===t[0].length&&"string"==typeof t[0][0]&&(e.value=[t]);"string"==typeof t[0];)t.shift();for(;"string"==typeof t[t.length-1];)t.pop();e.value.forEach((e=>{Array.isArray(e)&&0===e.length&&e.push([])}))}else e.value=[[[]]]}_convertValueToFlat(e){const t=this,a=["and","or","notAnd","notOr"];if(!e)return;let i=0,o=0;t._valueFlat=[],function e(l,r){let n;for(let s=0;s<l.length;s++){const d=l[s];let c={htmlNode:null};if("string"==typeof d&&(a.indexOf(d)>-1||t.customOperators[d]))n=(t.customOperators[d]||d).trim();else if(n=n||"and",Array.isArray(d)){let a=t._valueFlat.filter((e=>e.parentId+""==r+"")).length;if(d.find((e=>Array.isArray(e))))c.nodeId=(o+=1)+"",c.type="group",c.data=n,t._valueFlat.push(c),e(d,c.nodeId),n="";else{if(t.maxConditions&&i>=t.maxConditions||t.maxConditionsPerGroup&&a>=t.maxConditionsPerGroup)continue;0!==s&&(t._valueFlat.push({nodeId:r+"."+a,type:"operator",data:n,parentId:r+""}),n="",a++),c.nodeId=r+"."+a,c.parentId=r+"",c.type="condition",c.data=d,i++,t._valueFlat.push(c)}}}}(e,0),delete t._totalGroups}_getFieldsFromValue(){const e=this._valueFlat,t=[],a=[];for(let o=0;o<e.length;o++){const l=e[o];if("condition"===l.type){const e=l.data[0];if(e&&-1===t.indexOf(e)){const o={label:e,dataField:e,dataType:(i=l.data[2],"boolean"==typeof i?"boolean":i instanceof Date?i.getHours()>0||i.getMinutes()>0||i.getSeconds()>0?"dateTime":"date":isNaN(i)?"string":"number"),format:null};t.push(e),a.push(o)}}}var i;this._valueFields=a}_addElement(e,t,a,i){const o=this,l=o._valueFlat.filter((e=>e.parentId===t));let r=0,n="";if(a=a||("group"===e?"or":[]),l.length){let e=l.map((e=>{const t=e.nodeId.split(".");return parseInt(t[t.length-1])}));e=0===e.length?[0]:e,r=e.reduce(((e,t)=>Math.max(e,t)))+1}t&&t.length>0&&(n=".");let s=(t||"")+n+("group"===e?o._valueFlat.filter((e=>"group"===e.type)).length+1:r),d=l[0];if(l.length)for(let e=0;e<l.length;e++){const t=l[e],a=t.nodeId.split(".").pop();parseInt(a)>parseInt(d.nodeId.split(".").pop())&&(d=t)}else d=o._valueFlat.find((e=>e.nodeId===t));let c=d?o._valueFlat.indexOf(d)+1:o._valueFlat.length;"condition"===e&&l.length>0&&(o._valueFlat.splice(c,0,{nodeId:s,parentId:t,type:"operator",data:["and"],htmlNode:null}),s=(t||"")+n+(r+1),c++);const u={nodeId:s,parentId:t,type:e,data:a,htmlNode:null},p=o.autoPrompt;if("condition"===e&&p&&o._fields.length){const e=o._fields[0];if(e){const t=o._getFilterOperations(e);a[0]=e.value||e.label||"",t.length&&(a[1]=t[0].value)}}if(o._valueFlat.splice(c,0,u),"group"===e&&o._addElement("condition",s,[],!0),!i&&(o._refresh(),p&&u.htmlNode)){const e=u.htmlNode,t=e.querySelector(".smart-filter-value");t&&o._clickHandlerFilterButton(e.classList,u.nodeId,t)}}_deleteElement(e,t){const a=this,i="string"==typeof e?e:e.getAttribute("node-id");if(i&&1!==i.length&&("group"===t?r(i):l(i),!t||"condition"===t)){let e=i.split(".");if(e.pop(),e=e.join("."),!a._valueFlat.filter((t=>t.parentId===e)).length&&(a._valueFlat.filter((e=>"group"===e.type)).length>1&&r(e),"0"===e)){const e=a._valueFlat.find((e=>"group"===e.type)),t=e.nodeId;e.nodeId="0",e.htmlNode.setAttribute("node-id","0");const i=a._valueFlat.filter((e=>e.parentId===t));for(let e=0;e<i.length;e++){const t=i[e];t.parentId="0",t.nodeId="0."+e,t.htmlNode.setAttribute("node-id",t.nodeId)}}a._generateValue()}function o(e){const t=a._valueFlat[e];if(t&&"operator"===t.type)return a._valueFlat.splice(e,1),t.htmlNode.parentElement.removeChild(t.htmlNode),!0}function l(e){let t,i=0,l=e.split(".");l.pop(),l=l.join(".");for(let o=0;o<a._valueFlat.length;o++){const r=a._valueFlat[o];if("condition"===r.type){if(r.nodeId===e){t=r;break}r.parentId===l&&i++}}const r=a._valueFlat.indexOf(t);a._valueFlat.splice(r,1),t.htmlNode.parentElement.removeChild(t.htmlNode);const n=o(r-1);i||o(r-(n?1:0));const s=a._valueFlat.filter((e=>e.nodeId===l))[0].htmlNode;s.children[1].childElementCount>0&&s.children[2].hasAttribute("limit-selection")&&!s.children[1].lastElementChild.hasAttribute("limit-selection")&&s.children[2].removeAttribute("limit-selection")}function r(e){const t=a._valueFlat.filter((t=>e===t.nodeId&&"group"===t.type))[0];for(let t=0;t<a._valueFlat.length;t++){const i=a._valueFlat[t],o=i.nodeId;i.parentId===e&&("group"===i.type?r(o):l(o))}a._valueFlat.indexOf(t)>-1&&a._valueFlat.splice(a._valueFlat.indexOf(t),1),t.htmlNode.parentElement.removeChild(t.htmlNode)}}_generateHTMLStructureFromFlatValue(e){const t=this,a=document.createDocumentFragment();if(t._valueFlat&&0!==t._valueFlat.length){for(let e=0;e<t._valueFlat.length;e++){const i=t._valueFlat[e],o=!!t.customOperations&&t.customOperations.find((e=>e.name===i.data[1])),l=i.parentId?(t.shadowRoot||t).querySelector('[node-id="'+i.parentId+'"]').querySelector(".smart-filter-group-condition-container"):t.$.contentContainer;if("group"===i.type){const o=document.createElement("div"),l=t.localize(i.data)||"";o.className="smart-filter-group",o.innerHTML='<div class="smart-filter-group-operator" role="button" aria-expanded="false" aria-haspopup="menu">'+l+'</div><div class="smart-filter-group-condition-container" role="group"></div><div class="smart-filter-add-condition-btn" role="button" aria-label="Add condition"><div>'+t.localize("add")+'</div></div><div class="smart-filter-add-btn" role="button" aria-expanded="false" aria-haspopup="menu" aria-label="Add group"></div>',o.firstElementChild.data=l,a.appendChild(o),o.setAttribute("node-id",i.nodeId),t._valueFlat[e].htmlNode=o}else if("condition"===i.type){const l=t._newFilterConditionRow(i.data);if(l.setAttribute("node-id",i.nodeId),a.appendChild(l),t._valueFlat[e].htmlNode=l,void 0!==i.data[0]&&void 0===i.data[1]){const e=t._getFilterOperations(t._fields.find((e=>e.value===i.data[0])));t._handleOnlyOperation(e,i.data,l)}else(-1!==["isblank","isnotblank"].indexOf(i.data[1])||o&&o.hideValue)&&(i.data.splice(2,1),l.children[2].classList.add("smart-visibility-hidden"))}else{const o=document.createElement("div");o.className="smart-filter-nested-operator",o.setAttribute("node-id",i.nodeId),o.setAttribute("role","button"),o.setAttribute("aria-expanded",!1),o.setAttribute("aria-haspopup","menu"),o.innerHTML=t.localize(i.data),a.appendChild(o),t._valueFlat[e].htmlNode=o}l.appendChild(a)}e&&t._validateValueAdvanced(),t.$.scrollableContainer.refresh()}}_validateValueAdvanced(){const e=this,t=e.value;let a=!1,i=!1,o=0;for(let e=0;e<t.length;e++){const l=t[e];if("string"!=typeof l)for(let e=l.length-1;e>=0;e--){let t=l[e];if(Array.isArray(t)&&0===t.length&&e!==l.length-1)l.splice(e,1),0===e&&l.splice(0,1),a=!0;else if("string"==typeof t){t=t.toLowerCase(),o++,(o>1||"and"!==t&&"or"!==t)&&(i=!0);continue}o=0}}a&&(e._emptyElementsStructure(!0),e._convertValueToFlat(e.value),e._generateHTMLStructureFromFlatValue()),i&&e._generateValue(!0)}_restrictNesting(){Array.from(this.getElementsByClassName("smart-filter-add-condition-btn")).forEach((e=>{const t=e.previousElementSibling.lastElementChild;t&&t.hasAttribute("limit-selection")&&e.setAttribute("limit-selection","")}))}_clickHandler(e){const t=this,a=t.shadowRoot||t.isInShadowDOM?e.composedPath()[0]:e.target;if(t.disabled||!a||!a.closest||!t._isMobile&&0!==e.button)return;if(t._scrollBarDown)return void delete t._scrollBarDown;const i=a.closest(".smart-drop-down"),o=t._editor&&t._editor.contains(a)||i&&(t._editor.contains(i.ownerElement)||t._editor===i.ownerElement)||a.closest(".smart-custom-editor");t._editor&&t._editorIsOpen&&!o&&t._closeEditor();const l=a.closest(".smart-filter-group-condition")||a.closest(".smart-filter-nested-operator")||a.closest(".smart-filter-group");if(!l)return;const r=t._getItemById(l.getAttribute("node-id"));if(!r)return;if(t.$.fireEvent("itemClick",{id:r.nodeId,type:r.type,data:r.data}),a.closest(".smart-filter-delete-btn"))return void t._clickHandlerDeleteButton(r.htmlNode);const n=a.closest(".smart-filter-add-btn")||a.closest(".smart-filter-add-condition-btn");if(n){const e=n.closest(".smart-filter-group").getAttribute("node-id");return void(n.classList.contains("smart-filter-add-condition-btn")&&(t.maxConditions&&t._getTotalConditions()<t.maxConditions||!t.maxConditions)?t._addElement("condition",e,[]):t._clickHandlerFilterButton(n.classList,r.nodeId,a))}const s=a.closest(".filter-builder-item")||a.closest(".smart-filter-group-operator")||a.closest(".smart-filter-nested-operator");if(s){const e=s.classList;t._clickHandlerFilterButton(e,r.nodeId,a)}}_downHandler(e){const t=this;if(!e.originalEvent||!t._isMobile&&0!==e.button)return;const a=t.shadowRoot||t.isInShadowDOM?e.originalEvent.composedPath()[0]:e.originalEvent.target,i=t.rightToLeft?e.pageX>a.getBoundingClientRect().right:e.pageX<a.getBoundingClientRect().left;if(t.allowDrag&&a.classList.contains("smart-filter-group-condition")&&i){const i=t._valueFlat.filter((e=>"condition"===e.type));if(1===i.length||2===i.length&&i[0].parentId===i[1].parentId&&i[1].htmlNode.hasAttribute("limit-selection"))return;return t._dragDetails={coords:{x:e.pageX,y:e.pageY},item:a,originalEvent:e},t.$.scrollableContainer._scrollView.disableSwipeScroll=!0,t._hoveredCondition=a,void window.getSelection().removeAllRanges()}this._scrollBarDown=a.closest("smart-scroll-bar"),e.stopPropagation(),e.preventDefault()}_scrollableContainerTouchmoveHandler(e){this._dragDetails&&e.cancelable&&(e.preventDefault(),e.stopPropagation())}_documentMoveHandler(e){const t=this,a=t._dragDetails;if(!a)return;const i=a.item;if(!a.feedbackShown){if(!(Math.abs(a.coords.x-e.pageX)>5||Math.abs(a.coords.y-e.pageY)>5))return;{const o=t._valueFlat.filter((e=>e.htmlNode===i))[0];if(t.$.fireEvent("dragStart",{data:o.data,item:i,originalEvent:e}).defaultPrevented)return delete t._dragDetails,delete t._hoveredCondition,void(t.$.scrollableContainer._scrollView.disableSwipeScroll=!1);a.allConditions=Array.from((t.shadowRoot||t).querySelectorAll(".smart-filter-group-condition")),a.data=o,a.feedback=t._addDragFeedback(),a.feedbackShown=!0,i.classList.add("dragged")}}const o=e.clientY;let l,r=t.shadowRoot||t.isInShadowDOM?e.originalEvent.composedPath()[0]:e.originalEvent.target;if(t.$.fireEvent("dragging",{data:a.data,item:i,originalEvent:e}),t.setAttribute("dragging",""),a.feedback.style.left=e.pageX+10+"px",a.feedback.style.top=e.pageY+10+"px",t._isMobile){const a=t._hoveredCondition;a&&(a.classList.remove("drop-target","top","bottom"),delete t._hoveredCondition);const i=document.elementFromPoint(e.clientX,o);i&&(r=i)}let n,s=r.closest(".smart-filter-group-condition");if(s){l=s;const e=l.getBoundingClientRect(),t=Math.abs(o-e.top),a=Math.abs(o-e.bottom);n=t<a?"top":"bottom"}else{let e,t;a.allConditions.forEach((a=>{const i=a.getBoundingClientRect(),l=Math.abs(o-i.top),r=Math.abs(o-i.bottom),s=Math.min(l,r);(void 0===t||s<t)&&(e=a,t=s,n=l<r?"top":"bottom")})),s=e}if(s===i||s.hasAttribute("limit-selection")&&"bottom"===n)s=void 0;else{const e=Array.from(s.parentElement.getElementsByClassName("smart-filter-group-condition")),t=e.indexOf(i);-1!==t&&("top"===n&&s===e[t+1]||"bottom"===n&&s===e[t-1])&&(s=void 0)}if(l=s,a.side=n,clearInterval(t._dragInterval),t._dragInterval=setInterval((function(){const a=t.getBoundingClientRect();t.$.scrollableContainer.scrollHeight>0&&a.left<=e.clientX&&a.left+a.width>=e.clientX?o>=a.top&&o<=a.top+36?t.$.scrollableContainer.scrollTop-=t._autoScrollCoefficient:o>=a.top+a.height-36&&o<=a.top+a.height?t.$.scrollableContainer.scrollTop+=t._autoScrollCoefficient:clearInterval(t._dragInterval):clearInterval(t._dragInterval)}),1),l){t._hoveredCondition&&l!==t._hoveredCondition&&t._hoveredCondition.classList.remove("drop-target","top","bottom");const e=l.closest(".smart-filter-group");if(e&&e.hasAttribute("restricted"))return void(t._hoveredCondition=void 0);t._hoveredCondition=l,l.classList.remove("top","bottom"),l.classList.add(n,"drop-target")}else t._hoveredCondition&&(t._hoveredCondition.classList.remove("drop-target","top","bottom"),delete t._hoveredCondition)}_addDragFeedback(){const e=this,t=document.createElement("div");return e.rightToLeft?t.setAttribute("right-to-left",""):t.removeAttribute("right-to-left"),t.className="smart-query-builder-drag-feedback",e.theme&&t.setAttribute("theme",e.theme),document.body.appendChild(t),t}_documentUpHandler(e){const t=this,a=t._dragDetails;if(!a)return void(t.$.conditionsMenu.opened&&t._selectedElement&&!t._selectedElement.classList.contains("smart-filter-add-btn")&&t.$.conditionsMenu._hoverViaKeyboard(t.$.conditionsMenu.querySelector('smart-menu-item[value="'+t._editedItem.data+'"]')));const i=a.item,o=a.data,l=t._hoveredCondition;if(delete t._dragDetails,delete t._hoveredCondition,t.$.scrollableContainer._scrollView.disableSwipeScroll=!1,!t.hasAttribute("dragging"))return;if(clearInterval(t._dragInterval),window.getSelection().removeAllRanges(),t.removeAttribute("dragging"),i.classList.remove("dragged"),a.feedback.remove(),!l)return void t.$.fireEvent("dragEnd",{data:o.data,item:i,originalEvent:e,target:null,targetData:null,targetSide:null});const r=t._valueFlat.filter((e=>e.htmlNode===l))[0],n=t.$.fireEvent("dragEnd",{data:o.data,item:i,originalEvent:e,target:l,targetData:r.data,targetSide:a.side});if(l.classList.remove("drop-target","top","bottom"),n.defaultPrevented)return;const s=t.value,d=o.nodeId.split(".").map((e=>parseFloat(e))),c=s[2*(d[0]-1)],u=r.nodeId.split(".").map((e=>parseFloat(e))),p=s[2*(u[0]-1)];let m="and";c.length>1&&(0===d[1]?(m=c[1],c[1]="!remove!"):(m=c[d[1]-1],c[d[1]-1]="!remove!")),c[d[1]]="!remove!","top"===a.side?p.splice(u[1],0,o.data,m):p.splice(u[1]+1,0,m,o.data);for(let e=0;e<s.length;e++)Array.isArray(s[e])&&(s[e]=s[e].filter((e=>"!remove!"!==e)));for(let e=s.length-1;e>=0;e--)Array.isArray(s[e])&&0===s[e].length&&(0===e?s.splice(0,2):(s.splice(e-1,2),e--));t._emptyElementsStructure(!0),t._convertValueToFlat(s),t._generateHTMLStructureFromFlatValue(),t._validValue=t._getValidValue();const f=JSON.stringify(t._validValue);t._oldValueAsString!==f&&(t._oldValueAsString=f,t.$.fireEvent("change",{value:JSON.parse(f),linq:t._queryParser.toLinq(t._validValue)}))}_clickHandlerDeleteButton(e,t){const a=this;if(e&&e.classList){if(a._closeEditor(),1===a.getElementsByClassName("smart-filter-group-condition").length){const e=a._valueFlat[1].htmlNode.children;a.value=[[[]]],a._validValue=a._getValidValue(),a._valueFlat[1].data=[],a._valueFlat[1].htmlNode.setAttribute("limit-selection",""),e[0].setAttribute("placeholder",""),e[1].setAttribute("placeholder",""),e[2].setAttribute("placeholder",""),e[2].removeAttribute("invalid-value"),e[0].firstElementChild.innerHTML=a.propertyPlaceholder,e[1].firstElementChild.innerHTML=a.operatorPlaceholder,e[2].firstElementChild.innerHTML=a.valuePlaceholder;const t=JSON.stringify(a._validValue);return a._oldValueAsString!==t&&(a._oldValueAsString=t,a.$.fireEvent("change",{value:JSON.parse(t),linq:a._queryParser.toLinq(a._validValue)})),void a._restrictNesting()}if(e.classList.contains("smart-filter-group")){if(t&&a._valueFlat.filter((t=>t.parentId===e.getAttribute("node-id"))).length>0)return;a._deleteElement(e,"group")}else a._deleteElement(e);a._generateValue(),a.$.scrollableContainer.refresh(),Array.from(a.$.contentContainer.children).forEach(((e,t)=>{const i=(t+1).toString();e.setAttribute("node-id",i),a._valueFlat.filter((t=>t.htmlNode===e))[0].nodeId=i,Array.from(e.children[1].children).forEach(((e,t)=>{const o=a._valueFlat.filter((t=>t.htmlNode===e))[0],l=i+"."+t;e.setAttribute("node-id",l),o.parentId=i,o.nodeId=l}))}))}}_menuCloseHandler(){const e=this.$.conditionsMenu.controlledBy;e.setAttribute("aria-expanded",!1),e.removeAttribute("aria-controls"),delete this.$.conditionsMenu.controlledBy}_menuClosingHandler(e){const t=e.detail;"interaction"===t.trigger&&this._selectedElement===t.target&&e.preventDefault()}_menuItemClickHandler(e){const t=this,a=t._selectedElement.closest(".smart-filter-group-operator, .smart-filter-nested-operator"),i=e.detail,o=i.value;let l;if(a){a.innerHTML=t.localize(o)||i.label,a.value=o,l=a.classList.contains("smart-filter-nested-operator")?a.getAttribute("node-id"):a.parentElement.getAttribute("node-id");for(let e=0;e<t._valueFlat.length;e++)if(t._valueFlat[e].nodeId===l){t._valueFlat[e].data=a.value;break}t._generateValue()}else l=t._selectedElement.parentElement.getAttribute("node-id"),t._addElement("group",null,o);t.$.scrollableContainer.refresh()}_newFilterConditionRow(e=[]){const t=this,a=e[0];let i,o=t._fields.find((e=>e.value===a)),l=o?o.label:void 0;void 0===a||!l&&"static"===t.fieldsMode?e.length=0:(l||(o=t._getDynamicFieldInfo(a),l=o.label,e[0]=o.dataField),i=t._getFilterOperations(o).find((t=>t.value===e[1])),i&&(i=i.label));const r=t._formatValueStringRepresentation(e[2],e),n=t._validateValueField(void 0,e[1],e[2]);let s=document.createElement("div"),d="condition"+Math.floor(65536*(1+Math.random())).toString(16).substring(1),c='<div class="filter-builder-item smart-filter-field-name" id="'+d+'Field" '+(l?'><div class="smart-value-container" role="presentation">'+l:'placeholder><div class="smart-value-container" role="presentation">'+t.propertyPlaceholder)+'</div></div><div class="filter-builder-item smart-filter-operation" id="'+d+'Operation" '+(i?'><div class="smart-value-container" role="presentation">'+i:'placeholder><div class="smart-value-container" role="presentation">'+t.operatorPlaceholder)+'</div></div><div class="filter-builder-item smart-filter-value" id="'+d+'Value" '+(n?"":"invalid-value")+(void 0!==e[2]?'><div class="smart-value-container" role="presentation">'+r:'placeholder><div class="smart-value-container" role="presentation">'+t.valuePlaceholder)+'</div></div><div class="smart-filter-delete-btn" role="button" aria-label="Close"></div>';return s.className="smart-filter-group-condition",s.setAttribute("role","group"),s.innerHTML=c,t._setAriaLabel(s),e.length||s.setAttribute("limit-selection",""),s}_setAriaLabel(e){const t=[];for(let a=0;a<e.children.length-1;a++){const i=e.children[a];i.classList.contains("smart-visibility-hidden")||i.hasAttribute("placeholder")||t.push(e.children[a].innerText)}0!==t.length?e.setAttribute("aria-label",t.join(" ")):e.setAttribute("aria-label","Empty condition row")}_formatValueStringRepresentation(e,t){const a=this,i=t[2],o=t[0],l=a._getFieldByFieldName(o);let r,n=t[1];if(!l||!l.dataType)return e;if(null==e)return a.valuePlaceholder;if(void 0!==n&&a.customOperations&&a.customOperations.length>0&&(n=a.customOperations.find((e=>e.name===n)),n&&n.valueTemplate))return"<span>"+n.valueTemplate(a._editor,e)+"</span>";switch(l.dataType.toLowerCase()){case"date":case"datetime":(e=e instanceof Date||"string"==typeof e||"number"==typeof e&&!isNaN(e)?new Smart.Utilities.DateTime(e):e).calendar.days=a._localizedDays,e.calendar.months=a._localizedMonths,e.calendar.locale=a.locale,r=e.toString("date"===l.dataType?a.formatStringDate:a.formatStringDateTime);break;case"array":r="string"==typeof e?e.split(","):e;break;case"object":r="string"==typeof e?e:JSON.stringify(e);break;case"number":r=e;break;case"boolean":r=!!e;break;default:r=e+"",r=r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,""")}if(!a.valueFormatFunction)return"<span>"+r+"</span>";const s={label:r,value:i,dataField:o,dataType:l.dataType||"string"};return"<span>"+a.valueFormatFunction(s)+"</span>"}_getFieldByFieldName(e){return Object.assign({},this._fields.find((t=>t.value===e)))}_refresh(){const e=this;e._generateValue(),e._emptyElementsStructure(),e._generateHTMLStructureFromFlatValue(),e._restrictNesting()}_generateValue(e){const t=this;let a=[],i=t._valueFlat.slice(0),o=[];for(let e=0;e<i.length;e++){const t=i[e];let o={};"group"===t.type&&(o.nodeId=t.nodeId,o.parentId=t.parentId,o.data=t.data,o.structure=[],a.push(o))}for(let e=0;e<a.length;e++){const t=a[e];for(let e=0;e<i.length;e++){const a=i[e];if(a.parentId===t.nodeId&&"condition"===a.type){const o=i[e-1];o&&o.parentId===t.nodeId&&"operator"===o.type&&t.structure.push(o.data.toString()),t.structure.push(a.data)}}}a=a.filter((e=>e.structure.length>0)),a.sort((function(e,t){return t.nodeId.split(".").length-e.nodeId.split(".").length}));for(let e=0;e<a.length;e++){const t=a[e],i=a.filter((e=>e.nodeId===t.parentId))[0];i&&i.structure?i.structure.push(t.structure):"0"!==t.nodeId?t.data&&(e>0&&o.push(t.data),o.push(t.structure)):o=o.concat(t.structure)}if(t.set("value",o),t._validateValue(),t._validValue=t._getValidValue(),t._updateValidationStatus(),!e){const e=JSON.stringify(t._validValue);t._oldValueAsString!==e&&(t._oldValueAsString=e,t.$.fireEvent("change",{value:JSON.parse(e),linq:t._queryParser.toLinq(t._validValue)}))}}_updateValidationStatus(){const e=this,t=e.customOperations.filter((e=>"function"==typeof e.validateValue)),a=e._valueFlat,i=!!e._validationStatus;let o=!0;for(let e=0,i=a.length;e<i;e+=1){const i=a[e];if("condition"!==i.type)continue;const l=i.data[1],r=t.find((e=>e.name===l));if(r&&0==!!r.validateValue(i.data[2])){o=!1;break}}if(e._validationStatus!==o){const t=void 0!==e._validationStatus;e._validationStatus=o,t&&e.$.fireEvent("validationChange",{oldValue:i,newValue:o})}}_getItemById(e,t){const a=this._valueFlat.filter((a=>t?a.parentId===e:a.nodeId===e));return a.length>0?a[0]:null}_validateStoredValue(e,t){const a=this;if(!t&&!a._editedItem)return e;if(!t&&!(t=a._editedItem.data[0]))return e;const i=a._getFieldByFieldName(t).dataType;if(void 0===i)return e+"";switch(i.toLowerCase()){case"date":case"datetime":e=new Smart.Utilities.DateTime(e).toDate();break;case"number":"number"!=typeof e&&(e=parseFloat(e));break;case"boolean":"boolean"!=typeof e&&(e=!!e);break;case"object":"object"!=typeof e&&(e={});break;case"array":Array.isArray(e)||(e=[e]);break;default:"string"!=typeof e&&(e+="")}return e}_closeEditor(e,t){const a=this;let i;if(!a._editedItem||!a._editorIsOpen)return;const o=a._editedItem,l=a._editor.closest(".filter-builder-item"),r=l.querySelector(".smart-value-container"),n=l.parentElement,s=n.children[2];if(a._editor===a.$.dateTimePickerEditor)a._editor._inputChangeHandler(),i=a._editor.value,i&&(i=i.toDate());else if(a._editor===a.$.checkBoxEditor)i=a._editor.checked;else if(a._editor===a.$.customEditor)a._editor&&Array.from(a._editor.getElementsByTagName("smart-numeric-text-box")).forEach((e=>e._inputBlurHandler())),i=a._validateStoredValue(a._selectedCustomCondition.handleValue(a._editor));else if(a._editor===a.$.numericTextBoxEditor)a._editor._inputBlurHandler(),i=a._editor.value;else if(l.classList.contains("smart-filter-value")){const e=a._getFieldByFieldName(a._editedItem.data[0]);if("array"===e.dataType)i=a._editor.value.split(",");else if("object"===e.dataType)i=JSON.parse(a._editor.value);else{const t=a._editor.value;i=e.lookup&&e.lookup.dataSource?{label:t,value:a._editor.dataset.value||t}:t}}else i=a._editor.value;if(l.classList.contains("smart-filter-field-name")){if(""===i.trim())return void a._hideEditor(l,void 0===o.data[0]);n.hasAttribute("limit-selection")&&(n.removeAttribute("limit-selection"),n.parentElement.nextElementSibling.removeAttribute("limit-selection"));const e=a._fields.find((e=>e.label===i)),t=o.data[0];if(e)o.data[0]=e.value;else{if("dynamic"!==a.fieldsMode){const e=a._fields.find((e=>e.value===t));return e&&(r.innerHTML=e.label),void a._hideEditor(l)}{const e=a._getDynamicFieldInfo(i);i=e.label,o.data[0]=e.dataField}}r.innerHTML=i,a._handleFieldChange([t,o.data[0]],[s,o,n])}else if(l.classList.contains("smart-filter-operation"))a._handleOperationChange([o,i,a._editor.$.input.dataValue],[r,s]);else{let e,t;"object"==typeof i&&void 0!==i.value?(e=i.label,t=i.value,void 0===e&&(e=t)):e=t=i,o.data[2]=t,r.innerHTML=a._formatValueStringRepresentation(e,o.data)}a._validateValueField(s,o.data[1],o.data[2]),a._generateValue(e),!1!==t&&a._hideEditor(l)}_validateValueField(e,t,a){const i=this.customOperations;let o=!0;if(e&&e.removeAttribute("invalid-value"),i&&i.length>0){const l=i.find((e=>e.name===t));l&&"function"==typeof l.validateValue&&(o=!!l.validateValue(a),!o&&e&&e.setAttribute("invalid-value",""))}return o}_getDynamicFieldInfo(e){const t=this,a={label:e,dataField:e,dataType:"string"};if(t.getDynamicField){const i=t.getDynamicField(e);i.label&&(a.label=i.label),i.dataField&&(a.dataField=i.dataField),i.dataType&&(a.dataType=i.dataType),i.filterOperations&&Array.isArray(i.filterOperations)&&i.filterOperations.length>0&&(a.filterOperations=i.filterOperations),i.lookup&&(a.lookup=i.lookup)}return t._manuallyAddedFields.push(a),t._mapFieldsToMenu(),a}_handleFieldChange(e,t){const a=this,i=e[0],o=t[1],l=t[2],r=t[0],n=a._fields.find((t=>t.value===e[1])),s=a._getFilterOperations(n),d=function(){n.value!==i&&a.$.fireEvent("propertySelected",{label:n.label,value:n.value})};if(!i||void 0===o.data[1])return a._handleOnlyOperation(s,o.data,l),void d();const c=a._fields.find((e=>e.value===i)),u=c.dataType,p=n.dataType;if(n!==c&&(p!==u||"enum"===p||n.filterOperations||c.filterOperations)){if(s.find((e=>e.value===o.data[1]))){if(p===u&&"enum"!==p)return;return"date"===p&&"dateTime"===u||"dateTime"===p&&"date"===u?(r.firstElementChild.innerHTML=a._formatValueStringRepresentation(o.data),void d()):(o.data.splice(2,1),r.setAttribute("placeholder",""),r.firstElementChild.innerHTML=a.valuePlaceholder,void d())}o.data.splice(1,2),l.children[1].setAttribute("placeholder",""),l.children[1].firstElementChild.innerHTML=a.operatorPlaceholder,r.setAttribute("placeholder",""),r.firstElementChild.innerHTML=a.valuePlaceholder,r.classList.remove("smart-visibility-hidden"),a._handleOnlyOperation(s,o.data,l),d()}}_handleOnlyOperation(e,t,a){const i=this.autoPrompt;if(1===e.length||i&&"immediately"===this.applyMode&&e.length>1){const i=e[0];t[1]=i.value,a.children[1].removeAttribute("placeholder",""),a.children[1].firstElementChild.innerHTML=e[0].label,("isblank"===i.value||"isnotblank"===i.value||i.custom&&i.hideValue)&&(t.splice(2,1),a.children[2].classList.add("smart-visibility-hidden"))}}_handleOperationChange(e,t){const a=this,i=e[0],o=e[1],l=e[2],r=t[0],n=t[1],s=void 0!==i.data[1]?a._filterOperationDescriptions.find((e=>e.value===i.data[1])):void 0,d=a._filterOperationDescriptions.find((e=>e.value===l));if(!d||d===s)return;const c=d.value;i.data[1]=c;const u=i.data[0],p=i.data[1],m=i.data[2];if(r.innerHTML=o,"isblank"===c||"isnotblank"===c||d.custom&&d.hideValue)i.data.splice(2,1),n.classList.add("smart-visibility-hidden");else if(n.classList.contains("smart-visibility-hidden"))n.setAttribute("placeholder",""),n.classList.remove("smart-visibility-hidden"),n.firstElementChild.innerHTML=a.valuePlaceholder;else if(d.custom){const e=a._getFieldByFieldName(u);if(d.editorTemplate){const t=d.editorTemplate(e.dataType,p,e);t&&(a.$.customEditor.innerHTML="",a.$.customEditor.appendChild(t))}d.valueTemplate?n.firstElementChild.innerHTML=d.valueTemplate(a.$.customEditor,m):void 0===m?(n.setAttribute("placeholder",""),n.firstElementChild.innerHTML=a.valuePlaceholder):n.firstElementChild.innerHTML=m}else void 0===m?(i.data.splice(2,1),n.setAttribute("placeholder",""),n.firstElementChild.innerHTML=a.valuePlaceholder):d.custom||(n.firstElementChild.innerHTML=a._formatValueStringRepresentation(m,i.data))}_hideEditor(e,t){const a=this;t&&e.setAttribute("placeholder",""),e.removeAttribute("edited"),a.$.editorsContainer.removeAttribute("open"),a._editor.close&&a._editor.close(),a._editor.classList.add("smart-hidden"),a._editorIsOpen=a._enterIsPressedInEditor=!1,a.$.scrollableContainer.refresh(),a._setAriaLabel(e.parentElement)}_clickHandlerFilterButton(e,t,a){const i=this;function o(e,t,a){i._contextMenuOptions=0===t.length?i._defaultFilterOperationDescriptions:t,i._handleContextMenu(e),i.$.conditionsMenu.opened&&(i.$.conditionsMenu._discardKeyboardHover(),i.$.conditionsMenu._hoverViaKeyboard(i.$.conditionsMenu.querySelector('smart-menu-item[value="'+a+'"]')))}a.closest(".smart-editors-container")||(i._closeEditor(),i._editedItem=i._getItemById(t),e.contains("smart-filter-add-btn")?o(a,i._groupOperationDescriptions):(e.contains("smart-filter-field-name")||i._editedItem.data&&i._editedItem.data.length)&&(e.contains("smart-filter-group-operator")||e.contains("smart-filter-nested-operator")?o(a,i._groupOperationDescriptions,i._editedItem.data):(a.closest(".filter-builder-item").removeAttribute("placeholder"),i._openEditor(a))))}_handleContextMenu(e){const t=this;if(t._selectedElement===e&&t.$.conditionsMenu.opened)return void t.$.conditionsMenu.close();if(t._closeEditor(),t.disableContextMenu)return void(t._selectedElement=e);const a=e.getBoundingClientRect(),i=t.getBoundingClientRect(),o=a.left+t.$.contentContainer.scrollLeft-i.left,l=a.top+t.$.contentContainer.scrollTop-i.top+a.height;e.hasAttribute("aria-haspopup")&&(t.$.conditionsMenu.controlledBy&&(t.$.conditionsMenu.controlledBy.setAttribute("aria-expanded",!1),t.$.conditionsMenu.controlledBy.removeAttribute("aria-controls")),e.setAttribute("aria-controls",t.$.conditionsMenu.id),e.setAttribute("aria-expanded",!0),t.$.conditionsMenu.controlledBy=e),t.$.conditionsMenu.dataSource=t._contextMenuOptions,t.$.conditionsMenu.open(o,l+3),t._selectedElement=e,t.$.scrollableContainer.refresh()}_openEditor(e){const t=this,a=e&&e.closest(".smart-filter-group-condition")?e.closest(".smart-filter-group-condition").getAttribute("node-id"):null,i=e.closest(".filter-builder-item"),o=t._getItemById(a);let l="";void 0!==o.data[0]?l=o.data[0]:t._fields.length&&(l=t._fields[0].value);let r,n,s=t._getFieldByFieldName(l),d="";if(i.classList.contains("smart-filter-field-name"))n=0,t._fields||t._mapFieldsToMenu(),s.lookup={dataSource:t._fields.slice(),readonly:!1},d=s.label||"",r=s.value;else if(i.classList.contains("smart-filter-operation")){n=1;let e=t._getFilterOperations(s);s.lookup={dataSource:e,readonly:!0};let a=e.find((e=>e.value===o.data[n]))||e[0];d=a.label,r=a.value}else n=2,d=o.data[n],void 0===d&&(d="");t._editorIsOpen&&t._closeEditor(),i.setAttribute("edited",""),t._editedItem=o;const c=t._fields.filter((e=>e.value===l)),u=t._filterOperationDescriptions.filter((e=>e.value===o.data[1]&&e.custom)),p=c.length>0?c[0]:null,m=s.lookup&&s.lookup.dataSource?"lookup":p?p.dataType:void 0;if(2===n&&0!==u.length&&u[0].editorTemplate?(t._selectedCustomCondition=u[0],t._openCustomEditor(m,d,s)):t._openEditorByFieldType(m,d,s,r),i.appendChild(t.$.editorsContainer),t._editor.classList.remove("smart-hidden"),t._editorIsOpen=!0,t.$.editorsContainer.setAttribute("open",""),t.$.scrollableContainer.refresh(),t._editor.classList.contains("smart-custom-editor")){const e=t.customOperations[t._selectedCustomCondition.index].onEditorOpen;e&&e(t._editor)}else"immediately"===t.applyMode?requestAnimationFrame((()=>{t.autoApplyValue&&t._editor.closest(".smart-filter-value")?setTimeout((()=>{t._closeEditor(!1,!1),t._editor.querySelector("input").blur()})):t._editor.focus()})):requestAnimationFrame((()=>t._editor.focus()));s.lookup&&!t._valueValidationTimeout&&t._editor.open()}_getFilterOperations(e){const t=this;let a=t._filterOperationDescriptions.slice();if(e.filterOperations)a=t._filterOperationDescriptions.filter((t=>e.filterOperations.indexOf(t.value)>-1));else{let i;switch(e.dataType){case"date":case"dateTime":case"number":i=["=","<>","<",">","<=",">=","isblank","isnotblank"];break;case"boolean":i=["=","<>","isblank","isnotblank"];break;case"object":i=["isblank","isnotblank"];break;case"string":i=["contains","notcontains","startswith","endswith","=","<>","isblank","isnotblank"];break;default:i=["contains","notcontains","startswith","endswith","=","<>","<",">","<=",">=","isblank","isnotblank"]}a=t._filterOperationDescriptions.filter((e=>i.indexOf(e.value)>-1))}return t.showIcons&&a.map((e=>e.icon=t.icons[e.value])),a}_openCustomEditor(e,t,a){const i=this,o=i.customOperations[i._selectedCustomCondition.index].editorTemplate(e,t,a);i.$.customEditor.innerHTML="",o&&i.$.customEditor.appendChild(o),i._editor=i.$.customEditor}_openEditorByFieldType(e,t,a,i){const o=this;if(e)switch(e.toLowerCase()){case"boolean":return o._initializeEditor("checkBox"),void(o._editor.checked=!!t);case"date":case"datetime":return o._initializeEditor("dateTimePicker"),o._editor.formatString="date"===e?o.formatStringDate:o.formatStringDateTime,void(o._editor.value=t);case"number":return o._initializeEditor("numericTextBox"),void(o._editor.value=t||0)}if(o._initializeEditor("input"),o._editor.dropDownWidth=o.dropDownWidth,"lookup"===e){const i=a.lookup.minLength,l=a.lookup.dataSource;if(o._editor.autoCompleteDelay=a.lookup.autoCompleteDelay||100,o._editor.dropDownAppendTo=o.$.container,o._editor.dropDownButtonPosition=o.rightToLeft?"left":"right",o._editor.minLength=isNaN(i)||null===i?1:i,o._editor.readonly=!!a.lookup.readonly,"function"==typeof l?o._editor.dataSource=l:l instanceof Promise?l.then((e=>{if(!(o._editor instanceof Smart.Input))return;const a=o._editor.opened;o._editor.dataSource=e,e.length<12?o._editor.dropDownHeight="auto":o._editor.dropDownHeight=200,a&&(o._editor.open(),""===t&&o._editor.readonly&&e.length&&(o._editor.value=e[0].label||e[0]))})):(o._editor.dataSource=l,l.length<12?o._editor.dropDownHeight="auto":o._editor.dropDownHeight=200),"object"===e)t=JSON.stringify(t||{});else if(""===t&&o._editor.readonly){const e=o._editor.dataSource;if(Array.isArray(e)){const a=e[0];t=a&&(a.value||a.label)||""}else t=""}if(o._editor.isRendered){const e=o._editor.$.input.dataValue;null!=e&&e===t||(o._editor.value=void 0!==t?t+"":"")}else o._editor.value=void 0!==t?t+"":""}else o._editor.dataSource=[],o._editor.dropDownButtonPosition="none",o._editor.readonly=!1,o._editor.value=void 0!==t?t+"":"";i&&"object"!==e&&o._editor.isRendered&&(o._editor.$.input.dataValue=i)}_initializeEditor(e){const t=this;if(t.$[e+"Editor"])return void(t._editor=t.$[e+"Editor"]);const a=document.createElement("smart-"+Smart.Utilities.Core.toDash(e));"numericTextBox"===e?(a.spinButtons=!0,a.inputFormat="floatingPoint"):"dateTimePicker"===e&&(a.dropDownAppendTo=t.$.container,a.calendarButton=!0,a.dropDownDisplayMode="auto",a.enableMouseWheelAction=!0,a.locale=t.locale,a.autoClose=!0,a.messages[t.locale]||(a.messages[t.locale]={}),a.messages[t.locale].dateTabLabel=t.localize("dateTabLabel"),a.messages[t.locale].timeTabLabel=t.localize("timeTabLabel")),a.rightToLeft=t.rightToLeft,a.theme=t.theme,a.animation=t.animation,a.$.addClass("smart-hidden underlined"),t.$.editorsContainer.appendChild(a),t._editor=t.$[e+"Editor"]=a}_getValidValue(){const e=this,t=e.properties.value.value,a=[];let i=!1;return t.forEach((t=>{if(Array.isArray(t)){let o=!1,l=!1;const r=[];t.forEach((t=>{if(Array.isArray(t)){const a=t[0],i=t[1],n=t[2];if(void 0===a||void 0===i)return void(l=!0);if(void 0!==n||"isblank"===i||"isnotblank"===i)return o=!0,void r.push(t);const s=e._filterOperationDescriptions.find((e=>e.value===i));s.custom&&s.hideValue?(o=!0,r.push(t)):l=!0}else l?l=!1:r.push(t)})),o?("string"==typeof r[r.length-1]&&r.pop(),a.push(r)):i=!0}else i?i=!1:a.push(t)})),"string"==typeof a[a.length-1]&&a.pop(),a}}),Smart.Utilities.Assign("QueryParser",class{constructor(e,t,a){const i=this;i.customOperations=t||[],i.fields=e||[],i.dynamicField=a}toLinq(e){return Array.isArray(e)&&this._arePropertiesValid()?this._parseQueryToLinq(e):""}toValue(e){return"string"==typeof e&&this._arePropertiesValid()?this._parseLinqToValue(e):[]}_arePropertiesValid(){return Array.isArray(this.customOperations)?!!Array.isArray(this.fields)||(console.log('Invalid "fields" property.'),!1):(console.log('Invalid "customOperations" property.'),!1)}_parseQueryToLinq(e){const t=this,a={and:"&&",or:"||"};let i="";for(let o=0;o<e.length;o++){const l=e[o];if(Array.isArray(l))if(l.indexOf("and")>-1||l.indexOf("or")>-1||1===l.length&&Array.isArray(l[0])){const e=t._parseQueryToLinq(l);e?i+=l.length>1?"("+e+")":e:/\s(&|\|){2}\s$/gm.test(i)&&(i=i.replace(/\s(&|\|){2}\s$/gm,""))}else i+=t._getExpressionFromQuery(l)||"";else i&&(i+=" "+a[l]+" ")}return i}_getExpressionFromQuery(e){const t=e[0],a=e[1];let i=e[2];const o=this.customOperations.find((e=>e.name===a));return o&&o.expressionTemplate?("string"==typeof i&&i.includes('"')&&o.expressionTemplate.includes('"')&&(i=JSON.stringify(i).slice(1,-1)),o.expressionBuilderCallback?o.expressionBuilderCallback(t,a,i):o.expressionTemplate.replace("{0}",t).replace("{1}",i)):""}_parseLinqToValue(e){const t=this;let a,i=0,o=[];for(let t=0;t<e.length;t++)if("("===e[t])i++,void 0===a&&(a=t);else if(")"===e[t]&&i>0&&(i--,0===i)){let i=e.substring(a,t+1).trim();i.length&&(i.includes("&&")||i.includes("||"))&&o.push({expr:i}),a=void 0}let l,r=[];if(o.length)for(let a=0;a<o.length;a++){let i;o[a].query=t._getQueryFromExpression(o[a].expr),i=l?e.substring(e.indexOf(l)+l.length,e.indexOf(o[a].expr)).trim():e.substring(0,e.indexOf(o[a].expr)).trim(),i&&r.push(i),l=o[a].expr}l?r.push(e.substring(e.indexOf(l)+l.length).trim()):r.push(e.trim());for(let e=0;e<r.length;e++){const a=r[e].replace(/^&{2}|^\|{2}|&{2}$|\|{2}$/gm,"").trim();a.length&&o.push({expr:a,query:t._getQueryFromExpression(a),outher:!0})}return t._constructValueFromQueries(e,o)}_getQueryFromExpression(e){const t=this,a=t.fields,i=t.dynamicField;let o=[],l=e;const r=function(e){let l=[];const r=t.customOperations.filter((e=>e.expressionTemplate));r.sort(((e,t)=>t.expressionTemplate.length-e.expressionTemplate.length));for(let t=0;t<r.length;t++){const a=r[t],i=new RegExp(a.expressionTemplate.replace(/\(/gm,"\\(").replace(/\)/gm,"\\)").replace(/\[/gm,"\\[").replace(/\]/gm,"\\]").replace(/"{\d+}"/gm,'\\W*"([^"]*)[^a-zA-Z0-9-\\s\\)]+').replace(/{\d+}/gm,"([@|$]*\\w+[.]*\\w+(?!\\s)*)\\s{0}").replace(/ /gm,"\\s"),"gm");if(i.test(e)){i.lastIndex=0;let t,o,r=i.exec(e);if(r=r.filter(((e,t)=>r.indexOf(e)===t)),a.expressionReaderCallback){let e=a.expressionReaderCallback(r[0],r.slice(1));e&&(t=e.fieldName,o=e.value)}void 0===t&&(t=r[1]||""),void 0===o&&(o=r[2]||""),l.push({operator:a.name,field:t,value:o,query:r[0]})}}let n=l.find((e=>a.find((t=>t.filterOperations.indexOf(e.operator)>-1&&t.dataField===e.field))));if(!n&&i)for(let e=0;e<l.length;e++){const t=l[e],a=i(t.field);if(a&&Array.isArray(a.filterOperations)&&a.filterOperations.indexOf(t.operator)>-1){n=t;break}}if(n)return o.push({expr:n.query,query:[n.field,n.operator,n.value]}),n.query};if(l){for(;l.length;){l&&(l=l.trim(),"("===l[0]&&")"===l[l.length-1]&&(l=l.trim().replace(/^\(|\)$/gm,"")),l=l.replace(/^&{2}|^\|{2}|&{2}$|\|{2}$/gm,"").trim());const e=r(l);if(!e)break;l=l.replace(e,"").trim()}return t._constructValueFromQueries(e,o)}}_constructValueFromQueries(e,t){let a=[];t.sort(((t,a)=>e.indexOf(t.expr)-e.indexOf(a.expr)));for(let i=0;i<t.length;i++){let o=t[i-1];if(o){const l=e.substring(e.indexOf(o.expr)+o.expr.length,e.indexOf(t[i].expr)).trim();a.push("||"===l?"or":"and")}t[i].outher?t[i].query.forEach((e=>a.push(Array.isArray(e)?[e]:e))):a.push(t[i].query)}return a}});