bodmas-formula-engine
Version:
A powerful React component for building mathematical formulas with visual interface, real-time validation, and comprehensive function library
1 lines • 688 kB
JavaScript
import e,{memo as t,useState as r,useRef as n,useCallback as a,useEffect as i,forwardRef as o,useImperativeHandle as s,useMemo as u}from"react";import{Box as c,Typography as l,Tooltip as f,IconButton as p,Alert as m,TextField as d,InputAdornment as h,Chip as g,Button as y,Accordion as v,AccordionSummary as x,AccordionDetails as b,Dialog as w,DialogTitle as N,DialogContent as D,Paper as E,DialogActions as A,FormControl as C,InputLabel as S,Select as M,MenuItem as T,Menu as F,Divider as O,List as B,ListItem as _,ListItemText as R,Pagination as I,Tabs as z,Tab as k,ListItemIcon as q}from"@mui/material";import{Clear as P,Undo as j,Redo as U,ContentCopy as L,ContentPaste as H,Functions as V,Search as W,ExpandMore as $,Info as G,Close as Y,Build as Z,AccountBalance as X,DateRange as J,TrendingUp as K,Calculate as Q,Code as ee,GetApp as te,Publish as re,Edit as ne,Delete as ae,Storage as ie,Error as oe,Warning as se,CheckCircle as ue,PlayArrow as ce}from"@mui/icons-material";import{jsxs as le,jsx as fe}from"react/jsx-runtime";function pe(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function me(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function de(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?me(Object(r),!0).forEach(function(t){pe(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):me(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function he(e,t){if(null==e)return{};var r,n,a=function(e,t){if(null==e)return{};var r,n,a={},i=Object.keys(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)>=0||(a[r]=e[r]);return a}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function ge(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function ye(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ve(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function xe(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ve(Object(r),!0).forEach(function(t){ye(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ve(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function be(e){return function t(){for(var r=this,n=arguments.length,a=new Array(n),i=0;i<n;i++)a[i]=arguments[i];return a.length>=e.length?e.apply(this,a):function(){for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];return t.apply(r,[].concat(a,n))}}}function we(e){return{}.toString.call(e).includes("Object")}function Ne(e){return"function"==typeof e}var De=be(function(e,t){throw new Error(e[t]||e.default)})({initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"}),Ee={changes:function(e,t){return we(t)||De("changeType"),Object.keys(t).some(function(t){return r=e,n=t,!Object.prototype.hasOwnProperty.call(r,n);var r,n})&&De("changeField"),t},selector:function(e){Ne(e)||De("selectorType")},handler:function(e){Ne(e)||we(e)||De("handlerType"),we(e)&&Object.values(e).some(function(e){return!Ne(e)})&&De("handlersType")},initial:function(e){var t;e||De("initialIsRequired"),we(e)||De("initialType"),t=e,Object.keys(t).length||De("initialContent")}};function Ae(e,t){return Ne(t)?t(e.current):t}function Ce(e,t){return e.current=xe(xe({},e.current),t),t}function Se(e,t,r){return Ne(t)?t(e.current):Object.keys(r).forEach(function(r){var n;return null===(n=t[r])||void 0===n?void 0:n.call(t,e.current[r])}),r}var Me={create:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ee.initial(e),Ee.handler(t);var r={current:e},n=be(Se)(r,t),a=be(Ce)(r),i=be(Ee.changes)(e),o=be(Ae)(r);return[function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:function(e){return e};return Ee.selector(e),e(r.current)},function(e){!function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e){return t.reduceRight(function(e,t){return t(e)},e)}}(n,a,i,o)(e)}]}};var Te,Fe={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:"Deprecation warning!\n You are using deprecated way of configuration.\n\n Instead of using\n monaco.config({ urls: { monacoBase: '...' } })\n use\n monaco.config({ paths: { vs: '...' } })\n\n For more please check the link https://github.com/suren-atoyan/monaco-loader#config\n "},Oe=(Te=function(e,t){throw new Error(e[t]||e.default)},function e(){for(var t=this,r=arguments.length,n=new Array(r),a=0;a<r;a++)n[a]=arguments[a];return n.length>=Te.length?Te.apply(this,n):function(){for(var r=arguments.length,a=new Array(r),i=0;i<r;i++)a[i]=arguments[i];return e.apply(t,[].concat(n,a))}})(Fe),Be={config:function(e){var t;return e||Oe("configIsRequired"),t=e,{}.toString.call(t).includes("Object")||Oe("configType"),e.urls?(console.warn(Fe.deprecation),{paths:{vs:e.urls.monacoBase}}):e}};function _e(e,t){return Object.keys(t).forEach(function(r){t[r]instanceof Object&&e[r]&&Object.assign(t[r],_e(e[r],t[r]))}),de(de({},e),t)}var Re={type:"cancelation",msg:"operation is manually canceled"};function Ie(e){var t=!1,r=new Promise(function(r,n){e.then(function(e){return t?n(Re):r(e)}),e.catch(n)});return r.cancel=function(){return t=!0},r}var ze,ke,qe=Me.create({config:{paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}},isInitialized:!1,resolve:null,reject:null,monaco:null}),Pe=(ke=2,function(e){if(Array.isArray(e))return e}(ze=qe)||function(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var r=[],n=!0,a=!1,i=void 0;try{for(var o,s=e[Symbol.iterator]();!(n=(o=s.next()).done)&&(r.push(o.value),!t||r.length!==t);n=!0);}catch(e){a=!0,i=e}finally{try{n||null==s.return||s.return()}finally{if(a)throw i}}return r}}(ze,ke)||function(e,t){if(e){if("string"==typeof e)return ge(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ge(e,t):void 0}}(ze,ke)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),je=Pe[0],Ue=Pe[1];function Le(e){return document.body.appendChild(e)}function He(e){var t,r,n=je(function(e){return{config:e.config,reject:e.reject}}),a=(t="".concat(n.config.paths.vs,"/loader.js"),r=document.createElement("script"),t&&(r.src=t),r);return a.onload=function(){return e()},a.onerror=n.reject,a}function Ve(){var e=je(function(e){return{config:e.config,resolve:e.resolve,reject:e.reject}}),t=window.require;t.config(e.config),t(["vs/editor/editor.main"],function(t){We(t),e.resolve(t)},function(t){e.reject(t)})}function We(e){je().monaco||Ue({monaco:e})}var $e=new Promise(function(e,t){return Ue({resolve:e,reject:t})}),Ge={config:function(e){var t=Be.config(e),r=t.monaco,n=he(t,["monaco"]);Ue(function(e){return{config:_e(e.config,n),monaco:r}})},init:function(){var e=je(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(Ue({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Ie($e);if(window.monaco&&window.monaco.editor)return We(window.monaco),e.resolve(window.monaco),Ie($e);!function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e){return t.reduceRight(function(e,t){return t(e)},e)}}(Le,He)(Ve)}return Ie($e)},__getMonacoInstance:function(){return je(function(e){return e.monaco})}},Ye={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},Ze={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}};var Xe=function({children:t}){return e.createElement("div",{style:Ze.container},t)},Je=Xe;var Ke=function({width:t,height:r,isEditorReady:n,loading:a,_ref:i,className:o,wrapperProps:s}){return e.createElement("section",{style:{...Ye.wrapper,width:t,height:r},...s},!n&&e.createElement(Je,null,a),e.createElement("div",{ref:i,style:{...Ye.fullWidth,...!n&&Ye.hide},className:o}))},Qe=t(Ke);var et=function(e){i(e,[])};var tt=function(e,t,r=!0){let a=n(!0);i(a.current||!r?()=>{a.current=!1}:e,t)};function rt(){}function nt(e,t,r,n){return function(e,t){return e.editor.getModel(at(e,t))}(e,n)||function(e,t,r,n){return e.editor.createModel(t,r,n?at(e,n):void 0)}(e,t,r,n)}function at(e,t){return e.Uri.parse(t)}var it=function({original:t,modified:o,language:s,originalLanguage:u,modifiedLanguage:c,originalModelPath:l,modifiedModelPath:f,keepCurrentOriginalModel:p=!1,keepCurrentModifiedModel:m=!1,theme:d="light",loading:h="Loading...",options:g={},height:y="100%",width:v="100%",className:x,wrapperProps:b={},beforeMount:w=rt,onMount:N=rt}){let[D,E]=r(!1),[A,C]=r(!0),S=n(null),M=n(null),T=n(null),F=n(N),O=n(w),B=n(!1);et(()=>{let e=Ge.init();return e.then(e=>(M.current=e)&&C(!1)).catch(e=>"cancelation"!==e?.type&&console.error("Monaco initialization: error:",e)),()=>S.current?function(){let e=S.current?.getModel();p||e?.original?.dispose(),m||e?.modified?.dispose(),S.current?.dispose()}():e.cancel()}),tt(()=>{if(S.current&&M.current){let e=S.current.getOriginalEditor(),r=nt(M.current,t||"",u||s||"text",l||"");r!==e.getModel()&&e.setModel(r)}},[l],D),tt(()=>{if(S.current&&M.current){let e=S.current.getModifiedEditor(),t=nt(M.current,o||"",c||s||"text",f||"");t!==e.getModel()&&e.setModel(t)}},[f],D),tt(()=>{let e=S.current.getModifiedEditor();e.getOption(M.current.editor.EditorOption.readOnly)?e.setValue(o||""):o!==e.getValue()&&(e.executeEdits("",[{range:e.getModel().getFullModelRange(),text:o||"",forceMoveMarkers:!0}]),e.pushUndoStop())},[o],D),tt(()=>{S.current?.getModel()?.original.setValue(t||"")},[t],D),tt(()=>{let{original:e,modified:t}=S.current.getModel();M.current.editor.setModelLanguage(e,u||s||"text"),M.current.editor.setModelLanguage(t,c||s||"text")},[s,u,c],D),tt(()=>{M.current?.editor.setTheme(d)},[d],D),tt(()=>{S.current?.updateOptions(g)},[g],D);let _=a(()=>{if(!M.current)return;O.current(M.current);let e=nt(M.current,t||"",u||s||"text",l||""),r=nt(M.current,o||"",c||s||"text",f||"");S.current?.setModel({original:e,modified:r})},[s,o,c,t,u,l,f]),R=a(()=>{!B.current&&T.current&&(S.current=M.current.editor.createDiffEditor(T.current,{automaticLayout:!0,...g}),_(),M.current?.editor.setTheme(d),E(!0),B.current=!0)},[g,d,_]);return i(()=>{D&&F.current(S.current,M.current)},[D]),i(()=>{!A&&!D&&R()},[A,D,R]),e.createElement(Qe,{width:v,height:y,isEditorReady:D,loading:h,_ref:T,className:x,wrapperProps:b})};t(it);var ot=function(e){let t=n();return i(()=>{t.current=e},[e]),t.current},st=new Map;var ut=function({defaultValue:t,defaultLanguage:o,defaultPath:s,value:u,language:c,path:l,theme:f="light",line:p,loading:m="Loading...",options:d={},overrideServices:h={},saveViewState:g=!0,keepCurrentModel:y=!1,width:v="100%",height:x="100%",className:b,wrapperProps:w={},beforeMount:N=rt,onMount:D=rt,onChange:E,onValidate:A=rt}){let[C,S]=r(!1),[M,T]=r(!0),F=n(null),O=n(null),B=n(null),_=n(D),R=n(N),I=n(),z=n(u),k=ot(l),q=n(!1),P=n(!1);et(()=>{let e=Ge.init();return e.then(e=>(F.current=e)&&T(!1)).catch(e=>"cancelation"!==e?.type&&console.error("Monaco initialization: error:",e)),()=>O.current?(I.current?.dispose(),y?g&&st.set(l,O.current.saveViewState()):O.current.getModel()?.dispose(),void O.current.dispose()):e.cancel()}),tt(()=>{let e=nt(F.current,t||u||"",o||c||"",l||s||"");e!==O.current?.getModel()&&(g&&st.set(k,O.current?.saveViewState()),O.current?.setModel(e),g&&O.current?.restoreViewState(st.get(l)))},[l],C),tt(()=>{O.current?.updateOptions(d)},[d],C),tt(()=>{!O.current||void 0===u||(O.current.getOption(F.current.editor.EditorOption.readOnly)?O.current.setValue(u):u!==O.current.getValue()&&(P.current=!0,O.current.executeEdits("",[{range:O.current.getModel().getFullModelRange(),text:u,forceMoveMarkers:!0}]),O.current.pushUndoStop(),P.current=!1))},[u],C),tt(()=>{let e=O.current?.getModel();e&&c&&F.current?.editor.setModelLanguage(e,c)},[c],C),tt(()=>{void 0!==p&&O.current?.revealLine(p)},[p],C),tt(()=>{F.current?.editor.setTheme(f)},[f],C);let j=a(()=>{if(B.current&&F.current&&!q.current){R.current(F.current);let e=l||s,r=nt(F.current,u||t||"",o||c||"",e||"");O.current=F.current?.editor.create(B.current,{model:r,automaticLayout:!0,...d},h),g&&O.current.restoreViewState(st.get(e)),F.current.editor.setTheme(f),void 0!==p&&O.current.revealLine(p),S(!0),q.current=!0}},[t,o,s,u,c,l,d,h,g,f,p]);return i(()=>{C&&_.current(O.current,F.current)},[C]),i(()=>{!M&&!C&&j()},[M,C,j]),z.current=u,i(()=>{C&&E&&(I.current?.dispose(),I.current=O.current?.onDidChangeModelContent(e=>{P.current||E(O.current.getValue(),e)}))},[C,E]),i(()=>{if(C){let e=F.current.editor.onDidChangeMarkers(e=>{let t=O.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=F.current.editor.getModelMarkers({resource:t});A?.(e)}});return()=>{e?.dispose()}}return()=>{}},[C,A]),e.createElement(Qe,{width:v,height:x,isEditorReady:C,loading:m,_ref:B,className:b,wrapperProps:w})},ct=t(ut);const lt=o(({value:e,onChange:t,validation:o,engine:u},d)=>{const h=n(null),[g,y]=r({line:1,column:1}),[v,x]=r(!1),b=a(e=>{if(h.current){const t=h.current.getSelection();h.current.executeEdits("insert",[{range:t,text:e,forceMoveMarkers:!0}]),h.current.focus()}},[]);s(d,()=>({insertAtCursor:b,focus:()=>h.current?.focus(),getSelection:()=>h.current?.getSelection(),getValue:()=>h.current?.getValue(),getEditor:()=>h.current}),[b]);const w=a((e,t)=>{h.current=e,window.monaco=t,t.languages.register({id:"formula"}),t.languages.setMonarchTokensProvider("formula",{tokenizer:{root:[[/[a-zA-Z_]\w*(?=\()/,"function"],[/[a-zA-Z_]\w*/,"variable"],[/\d+\.?\d*/,"number"],[/"[^"]*"/,"string"],[/'[^']*'/,"string"],[/[+\-*/()]/,"operator"],[/[<>=!&|]/,"operator"],[/,/,"delimiter"],[/\s+/,"white"]]}}),t.editor.defineTheme("formulaTheme",{base:"vs",inherit:!0,rules:[{token:"function",foreground:"0066cc",fontStyle:"bold"},{token:"variable",foreground:"008000",fontStyle:"italic"},{token:"number",foreground:"098658"},{token:"string",foreground:"a31515"},{token:"operator",foreground:"0000ff",fontStyle:"bold"},{token:"delimiter",foreground:"000000"},{token:"white",foreground:"000000"}],colors:{"editor.background":"#ffffff","editor.selectionBackground":"#add6ff4d","editor.lineHighlightBackground":"#f5f5f5","editorCursor.foreground":"#0066cc"}}),t.languages.registerCompletionItemProvider("formula",{provideCompletionItems:(e,r)=>{const n=[],a=e.getWordUntilPosition(r),i={startLineNumber:r.lineNumber,endLineNumber:r.lineNumber,startColumn:a.startColumn,endColumn:a.endColumn};u.getFunctionSuggestions().forEach(e=>{n.push({label:e.name,kind:t.languages.CompletionItemKind.Function,insertText:e.insertText,insertTextRules:t.languages.CompletionItemInsertTextRule.InsertAsSnippet,documentation:{value:`**${e.signature}**\n\n${e.description}\n\n*Example:* \`${e.example}\``},detail:e.signature,range:i,sortText:"1"+e.name})});return[{label:"+",insertText:" + ",detail:"Addition",sortText:"2+"},{label:"-",insertText:" - ",detail:"Subtraction",sortText:"2-"},{label:"*",insertText:" * ",detail:"Multiplication",sortText:"2*"},{label:"/",insertText:" / ",detail:"Division",sortText:"2/"},{label:"(",insertText:"(${1})",detail:"Parentheses",sortText:"2("},{label:"==",insertText:" == ",detail:"Equal to",sortText:"3=="},{label:"!=",insertText:" != ",detail:"Not equal to",sortText:"3!="},{label:">",insertText:" > ",detail:"Greater than",sortText:"3>"},{label:"<",insertText:" < ",detail:"Less than",sortText:"3<"},{label:">=",insertText:" >= ",detail:"Greater than or equal",sortText:"3>="},{label:"<=",insertText:" <= ",detail:"Less than or equal",sortText:"3<="}].forEach(e=>{n.push({label:e.label,kind:t.languages.CompletionItemKind.Operator,insertText:e.insertText,insertTextRules:t.languages.CompletionItemInsertTextRule.InsertAsSnippet,detail:e.detail,range:i,sortText:e.sortText})}),{suggestions:n}}}),t.languages.registerHoverProvider("formula",{provideHover:(e,r)=>{const n=e.getWordAtPosition(r);if(n){const e=u.getFunctionInfo(n.word);if(e)return{range:new t.Range(r.lineNumber,n.startColumn,r.lineNumber,n.endColumn),contents:[{value:`**${e.signature}**`},{value:e.description},{value:`*Example:* \`${e.example}\``},{value:`*Returns:* ${e.returnType}`}]}}return null}}),e.onDidChangeCursorPosition(e=>{y({line:e.position.lineNumber,column:e.position.column})}),e.onDidChangeCursorSelection(e=>{x(!e.selection.isEmpty())}),e.addCommand(t.KeyMod.CtrlCmd|t.KeyCode.KeyK,()=>{e.trigger("keyboard","editor.action.triggerSuggest",{})}),e.focus()},[u]),N=a(e=>{t(e||"")},[t]);return i(()=>{if(h.current&&!o.valid&&window.monaco){const t=[{severity:8,message:o.error,startLineNumber:1,startColumn:1,endLineNumber:1,endColumn:e.length+1}];window.monaco.editor.setModelMarkers(h.current.getModel(),"formula",t)}else h.current&&o.valid&&window.monaco&&window.monaco.editor.setModelMarkers(h.current.getModel(),"formula",[])},[o,e]),le(c,{sx:{width:"100%",minHeight:"clamp(200px, 30vh, 350px)",display:"flex",flexDirection:"column",position:"relative"},children:[le(c,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:1,sx:{flexShrink:0,flexWrap:"wrap",gap:1},children:[fe(l,{variant:"h6",sx:{flexShrink:0},children:"Formula Editor"}),le(c,{display:"flex",gap:.5,sx:{flexWrap:"wrap"},children:[fe(f,{title:"Clear all (Ctrl+A, Delete)",children:fe(p,{size:"small",onClick:()=>{h.current&&(h.current.setValue(""),h.current.focus())},children:fe(P,{fontSize:"small"})})}),fe(f,{title:"Undo (Ctrl+Z)",children:fe(p,{size:"small",onClick:()=>{h.current&&(h.current.trigger("keyboard","undo",{}),h.current.focus())},children:fe(j,{fontSize:"small"})})}),fe(f,{title:"Redo (Ctrl+Y)",children:fe(p,{size:"small",onClick:()=>{h.current&&(h.current.trigger("keyboard","redo",{}),h.current.focus())},children:fe(U,{fontSize:"small"})})}),fe(f,{title:"Copy (Ctrl+C)",children:fe(p,{size:"small",onClick:()=>{if(h.current){const e=h.current.getSelection();if(e.isEmpty())navigator.clipboard.writeText(h.current.getValue());else{const t=h.current.getModel().getValueInRange(e);navigator.clipboard.writeText(t)}}},children:fe(L,{fontSize:"small"})})}),fe(f,{title:"Paste (Ctrl+V)",children:fe(p,{size:"small",onClick:async()=>{if(h.current)try{const e=await navigator.clipboard.readText(),t=h.current.getSelection();h.current.executeEdits("paste",[{range:t,text:e,forceMoveMarkers:!0}]),h.current.focus()}catch(e){console.warn("Failed to paste from clipboard:",e)}},children:fe(H,{fontSize:"small"})})})]})]}),!o.valid&&fe(m,{severity:"error",sx:{mb:2,flexShrink:0},children:o.error}),fe(c,{border:1,borderColor:o.valid?"grey.300":"error.main",borderRadius:1,sx:{width:"100%",maxWidth:"100%",height:"clamp(150px, 25vh, 300px)",minHeight:"clamp(150px, 25vh, 300px)",maxHeight:"clamp(150px, 25vh, 300px)",overflow:"hidden",flexShrink:0,position:"relative","& .monaco-editor":{borderRadius:1,width:"100% !important",maxWidth:"100% !important",height:"100% !important",minHeight:"100% !important",maxHeight:"100% !important"},"& .monaco-editor .cursor":{animation:"blink 1s infinite"},"& .monaco-editor .overflow-guard":{width:"100% !important",height:"100% !important"},"& .monaco-editor .monaco-scrollable-element":{width:"100% !important",height:"100% !important"}},children:fe(ct,{height:"100%",width:"100%",language:"formula",theme:"formulaTheme",value:e,onChange:N,onMount:w,options:{minimap:{enabled:!1},lineNumbers:"off",folding:!1,wordWrap:"on",fontSize:18,fontFamily:'Monaco, Menlo, "Ubuntu Mono", monospace',padding:{top:"2rem",bottom:"2rem"},suggestOnTriggerCharacters:!0,quickSuggestions:{other:!0,comments:!1,strings:!1},parameterHints:{enabled:!0},hover:{enabled:!0,delay:500},scrollBeyondLastLine:!1,overviewRulerLanes:0,hideCursorInOverviewRuler:!0,overviewRulerBorder:!1,renderLineHighlight:"line",selectOnLineNumbers:!0,roundedSelection:!1,cursorStyle:"line",cursorWidth:2,cursorBlinking:"blink",automaticLayout:!0,lineHeight:2,bracketPairColorization:{enabled:!0},guides:{bracketPairs:!0,bracketPairsHorizontal:!0},scrollbar:{horizontal:"auto",vertical:"auto",horizontalScrollbarSize:"clamp(8px, 1.5vw, 12px)",verticalScrollbarSize:"clamp(8px, 1.5vw, 12px)"},wordWrapColumn:120,rulers:[],glyphMargin:!1,lineDecorationsWidth:0,lineNumbersMinChars:3,showFoldingControls:"never",matchBrackets:"never",fixedOverflowWidgets:!0,contextmenu:!1}})}),le(c,{display:"flex",justifyContent:"space-between",alignItems:"center",sx:{mt:1,flexShrink:0,minHeight:"1.25rem",flexWrap:"wrap",gap:1},children:[fe(l,{variant:"caption",color:"textSecondary",sx:{fontSize:"clamp(0.65rem, 1.8vw, 0.75rem)",flexShrink:0},children:"Press Ctrl+Space for autocomplete • Ctrl+K for suggestions • Hover for help"}),le(l,{variant:"caption",color:"textSecondary",sx:{fontSize:"clamp(0.65rem, 1.8vw, 0.75rem)",flexShrink:0},children:["Line ",g.line,", Column ",g.column,v&&" • Text selected"]})]})]})});lt.displayName="FormulaEditor";const ft=({onFunctionInsert:e,onVariableInsert:t,variables:n=[],engine:a,showVariables:i=!0,showHeader:o=!0})=>{const[s,m]=r(""),[C,S]=r("string"),[M,T]=r(!1),[F,O]=r(null),B=u(()=>{if(!a)return{};const e=a.getFunctionSuggestions(),t={},r={string:{name:"String Functions",icon:fe(ee,{}),order:1},math:{name:"Math Functions",icon:fe(Q,{}),order:2},statistical:{name:"Statistical Functions",icon:fe(K,{}),order:3},logical:{name:"Logical Functions",icon:fe(V,{}),order:4},date:{name:"Date Functions",icon:fe(J,{}),order:5},financial:{name:"Financial Functions",icon:fe(X,{}),order:6},utility:{name:"Utility Functions",icon:fe(Z,{}),order:7}};return e.forEach(e=>{const n=e.category||"utility";t[n]||(t[n]={...r[n]||{name:n.charAt(0).toUpperCase()+n.slice(1)+" Functions",icon:fe(V,{}),order:99},functions:[]}),t[n].functions.push({name:e.name,signature:e.signature,description:e.description,insertText:e.insertText,example:e.example})}),Object.values(t).forEach(e=>{e.functions.sort((e,t)=>e.name.localeCompare(t.name))}),t},[a]),_=u(()=>{if(!s)return B;const e={},t=s.toLowerCase();return Object.entries(B).forEach(([r,n])=>{const a=n.functions.filter(e=>e.name.toLowerCase().includes(t)||e.description.toLowerCase().includes(t)||e.signature.toLowerCase().includes(t));a.length>0&&(e[r]={...n,functions:a})}),e},[B,s]),R=t=>{e(t.insertText)},I=()=>{T(!1),O(null)},z=Object.entries(_).sort(([,e],[,t])=>(e.order||99)-(t.order||99));return le(c,{className:"function-palette",children:[o&&fe(l,{variant:"h6",gutterBottom:!0,children:"Function Palette"}),fe(d,{fullWidth:!0,size:"small",placeholder:"Search functions...",value:s,onChange:e=>m(e.target.value),slotProps:{input:{startAdornment:fe(h,{position:"start",children:fe(W,{})})}},sx:{mb:2}}),i&&n.length>0&&le(c,{mb:2,children:[fe(l,{variant:"subtitle2",gutterBottom:!0,children:"Variables"}),fe(c,{display:"flex",flexWrap:"wrap",gap:1,children:n.map(e=>fe(g,{label:e,size:"small",onClick:()=>(e=>{t(e)})(e),clickable:!0,color:"secondary",variant:"outlined"},e))})]}),le(c,{mb:2,children:[fe(l,{variant:"subtitle2",gutterBottom:!0,children:"Operators"}),fe(c,{display:"flex",flexWrap:"wrap",gap:1,children:[{symbol:"+",name:"Addition",insertText:" + "},{symbol:"-",name:"Subtraction",insertText:" - "},{symbol:"*",name:"Multiplication",insertText:" * "},{symbol:"/",name:"Division",insertText:" / "},{symbol:"^",name:"Exponentiation",insertText:" ^ "},{symbol:"%",name:"Modulo",insertText:" % "},{symbol:"(",name:"Open Parenthesis",insertText:"("},{symbol:")",name:"Close Parenthesis",insertText:")"},{symbol:"=",name:"Equal",insertText:" = "},{symbol:">",name:"Greater Than",insertText:" > "},{symbol:"<",name:"Less Than",insertText:" < "},{symbol:">=",name:"Greater Than or Equal",insertText:" >= "},{symbol:"<=",name:"Less Than or Equal",insertText:" <= "},{symbol:"!=",name:"Not Equal",insertText:" != "}].map(t=>fe(f,{title:t.name,placement:"bottom",children:fe(y,{size:"small",variant:"outlined",onClick:()=>(t=>{e(t.insertText)})(t),sx:{minWidth:"auto",px:1},children:t.symbol})},t.symbol))})]}),le(c,{children:[fe(l,{variant:"subtitle2",gutterBottom:!0,children:"Functions"}),fe(c,{sx:{maxHeight:"270px",overflow:"auto",pr:1},children:z.map(([e,t])=>{return le(v,{expanded:C===e,onChange:(r=e,(e,t)=>{S(!!t&&r)}),sx:{mb:1},children:[fe(x,{expandIcon:fe($,{}),children:le(c,{display:"flex",alignItems:"center",gap:1,children:[t.icon,le(l,{variant:"body2",fontWeight:"medium",children:[t.name," (",t.functions.length,")"]})]})}),fe(b,{children:fe(c,{display:"flex",flexDirection:"column",gap:1,children:t.functions.map(e=>le(c,{sx:{position:"relative"},children:[fe(y,{fullWidth:!0,size:"small",variant:"outlined",onClick:()=>R(e),sx:{justifyContent:"flex-start",textTransform:"none",mb:.5,pr:5},children:le(c,{sx:{textAlign:"left",width:"100%"},children:[fe(l,{variant:"body2",component:"div",sx:{fontWeight:"bold"},children:e.name}),fe(l,{variant:"caption",component:"div",color:"text.secondary",children:e.description})]})}),fe(f,{title:"Function Help",placement:"top",children:fe(p,{size:"small",onClick:t=>((e,t)=>{t.stopPropagation(),O(e),T(!0)})(e,t),className:"function-help-icon",sx:{position:"absolute",top:4,right:4,zIndex:1},children:fe(G,{fontSize:"small"})})})]},e.name))})})]},e);var r})})]}),le(w,{open:M,onClose:I,maxWidth:"md",fullWidth:!0,children:[fe(N,{children:le(c,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[le(l,{variant:"h6",children:["Function Help: ",F?.name]}),fe(p,{onClick:I,size:"small",children:fe(Y,{})})]})}),fe(D,{children:F&&le(c,{children:[le(E,{elevation:1,sx:{p:2,mb:2},children:[fe(l,{variant:"subtitle1",gutterBottom:!0,sx:{fontWeight:"bold"},children:"Signature"}),fe(l,{variant:"body1",sx:{fontFamily:"monospace",backgroundColor:"grey.100",p:1,borderRadius:1},children:F.signature})]}),le(E,{elevation:1,sx:{p:2,mb:2},children:[fe(l,{variant:"subtitle1",gutterBottom:!0,sx:{fontWeight:"bold"},children:"Description"}),fe(l,{variant:"body1",children:F.description})]}),F.example&&le(E,{elevation:1,sx:{p:2,mb:2},children:[fe(l,{variant:"subtitle1",gutterBottom:!0,sx:{fontWeight:"bold"},children:"Example"}),fe(l,{variant:"body1",sx:{fontFamily:"monospace",backgroundColor:"grey.100",p:1,borderRadius:1},children:F.example})]}),F.returnType&&le(E,{elevation:1,sx:{p:2,mb:2},children:[fe(l,{variant:"subtitle1",gutterBottom:!0,sx:{fontWeight:"bold"},children:"Return Type"}),fe(g,{label:F.returnType,size:"small",color:"primary",variant:"outlined"})]}),le(E,{elevation:1,sx:{p:2},children:[fe(l,{variant:"subtitle1",gutterBottom:!0,sx:{fontWeight:"bold"},children:"Parameters"}),fe(l,{variant:"body2",color:"text.secondary",children:F.signature?.match(/\((.*?)\)/)?.[1]||"No parameters"})]})]})}),le(A,{children:[fe(y,{onClick:()=>{R(F),I()},variant:"contained",disabled:!F,children:"Insert Function"}),fe(y,{onClick:I,children:"Close"})]})]})]})},pt=({variableManager:e,onVariableInsert:t,onVariableEdit:n,onVariableDelete:o,onVariableAdd:s})=>{const[m,w]=r(""),[N,D]=r("all"),[E,A]=r("all"),[z,k]=r(1),[q,P]=r(new Set(["user"])),[j,U]=r(null),[L,H]=r("categorized"),V=u(()=>e?.getCategories()||[],[e]),G=u(()=>{if(!e)return[];if(m.trim())return e.searchVariables(m,{category:"all"!==N?N:null,type:"all"!==E?E:null,limit:1e3});if("all"!==N)return e.getVariablesByCategory(N).filter(e=>"all"===E||e.type===E);const t=[];for(const r of V){const n=e.getVariablesByCategory(r).filter(e=>"all"===E||e.type===E);t.push(...n)}return t},[e,m,N,E,V]),Y=u(()=>{const e=50*(z-1),t=e+50;return G.slice(e,t)},[G,z]),Z=Math.ceil(G.length/50);i(()=>{e&&e.getStats()},[e,G]);const X=a(e=>{w(e.target.value),k(1)},[]),J=a(e=>{D(e.target.value),k(1)},[]),K=a(e=>{A(e.target.value),k(1)},[]),Q=a((e,t)=>{k(t)},[]),ee=a(e=>{t?.(e.name)},[t]),ie=a(e=>{P(t=>{const r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]),oe=a(()=>{w(""),D("all"),A("all"),k(1)},[]),se=()=>fe(c,{children:V.map(t=>{const r=e.getVariablesByCategory(t).filter(e=>("all"===E||e.type===E)&&(""===m||e.name.toLowerCase().includes(m.toLowerCase())||e.metadata.description.toLowerCase().includes(m.toLowerCase())));return 0===r.length?null:le(v,{expanded:q.has(t),onChange:()=>ie(t),children:[fe(x,{expandIcon:fe($,{}),children:fe(c,{display:"flex",alignItems:"center",gap:1,children:fe(l,{variant:"subtitle2",children:t.charAt(0).toUpperCase()+t.slice(1)})})}),fe(b,{sx:{p:0},children:le(B,{dense:!0,children:[r.slice(0,20).map(e=>fe(_,{button:!0,onClick:()=>ee(e),children:fe(R,{primary:le(c,{display:"flex",alignItems:"center",gap:1,children:[fe(l,{variant:"body2",fontFamily:"monospace",children:e.name}),fe(g,{label:e.type,size:"small",variant:"outlined"})]}),secondary:ce(e.value)})},e.name)),r.length>20&&fe(_,{children:fe(R,{primary:le(l,{variant:"caption",color:"textSecondary",children:["... and ",r.length-20," more. Use search to find specific variables."]})})})]})})]},t)})}),ue=()=>le(c,{sx:{maxHeight:"300px",overflow:"auto"},children:[fe(B,{dense:!0,children:Y.map(e=>fe(_,{button:!0,onClick:()=>ee(e),sx:{borderBottom:"1px solid rgba(0,0,0,0.1)","&:hover":{backgroundColor:"rgba(25, 118, 210, 0.08)"}},secondaryAction:le(c,{display:"flex",gap:.5,children:[fe(f,{title:"Edit Variable",children:fe(p,{size:"small",onClick:t=>{t.stopPropagation(),n?.(e)},children:fe(ne,{fontSize:"small"})})}),fe(f,{title:"Delete Variable",children:fe(p,{size:"small",onClick:t=>{t.stopPropagation(),o?.(e.name)},children:fe(ae,{fontSize:"small"})})})]}),children:fe(R,{primary:le(c,{display:"flex",alignItems:"center",gap:1,children:[fe(l,{variant:"body2",fontFamily:"monospace",fontWeight:"bold",children:e.name}),fe(g,{label:e.type,size:"small",variant:"outlined",sx:{minWidth:60,height:20,fontSize:"0.7rem"}})]}),secondary:le(c,{children:[fe(l,{variant:"caption",color:"textSecondary",children:e.metadata.description||"No description"}),fe(c,{display:"flex",alignItems:"center",gap:1,mt:.5,children:fe(l,{variant:"caption",fontFamily:"monospace",children:ce(e.value)})})]})})},e.name))}),Z>1&&fe(c,{display:"flex",justifyContent:"center",mt:2,children:fe(I,{count:Z,page:z,onChange:Q,size:"small"})})]}),ce=e=>null==e?"null":"string"==typeof e?`"${e.length>20?e.slice(0,20)+"...":e}"`:"number"==typeof e||"boolean"==typeof e?e.toString():e instanceof Date?e.toLocaleDateString():"object"==typeof e?JSON.stringify(e).slice(0,30)+"...":String(e);return le(c,{className:"variable-palette",sx:{height:"100%",display:"flex",flexDirection:"column"},children:[fe(c,{mb:2,children:fe(d,{fullWidth:!0,size:"small",placeholder:"Search variables...",value:m,onChange:X,InputProps:{startAdornment:fe(h,{position:"start",children:fe(W,{})})}})}),le(c,{display:"flex",gap:1,mb:2,children:[le(C,{size:"small",sx:{minWidth:120},children:[fe(S,{children:"Category"}),le(M,{value:N,onChange:J,label:"Category",children:[fe(T,{value:"all",children:"All Categories"}),V.map(e=>fe(T,{value:e,children:e.charAt(0).toUpperCase()+e.slice(1)},e))]})]}),le(C,{size:"small",sx:{minWidth:100},children:[fe(S,{children:"Type"}),le(M,{value:E,onChange:K,label:"Type",children:[fe(T,{value:"all",children:"All Types"}),fe(T,{value:"number",children:"Number"}),fe(T,{value:"string",children:"String"}),fe(T,{value:"boolean",children:"Boolean"}),fe(T,{value:"date",children:"Date"}),fe(T,{value:"array",children:"Array"}),fe(T,{value:"object",children:"Object"})]})]}),(m||"all"!==N||"all"!==E)&&fe(y,{size:"small",onClick:oe,children:"Clear"})]}),le(l,{variant:"caption",color:"textSecondary",mb:1,children:[G.length," variable",1!==G.length?"s":""," found"]}),fe(c,{flex:1,minHeight:0,children:fe("categorized"!==L||m?ue:se,{})}),le(F,{anchorEl:j,open:Boolean(j),onClose:()=>U(null),children:[fe(T,{onClick:()=>H("categorized"),children:"Categorized View"}),fe(T,{onClick:()=>H("list"),children:"List View"}),fe(O,{}),le(T,{onClick:()=>console.log("Export variables"),children:[fe(te,{sx:{mr:1}}),"Export Variables"]}),le(T,{onClick:()=>console.log("Import variables"),children:[fe(re,{sx:{mr:1}}),"Import Variables"]})]})]})};class mt{constructor(e={}){this.variables=new Map,this.categories=new Map,Object.entries(e).forEach(([e,t])=>{this.addVariable(e,t,"user",{description:`Variable: ${e}`})})}addVariable(e,t,r="user",n={}){const a={name:e,value:t,category:r,type:this.inferType(t),metadata:{description:"",tags:[],lastModified:new Date,...n}};this.variables.set(e,a),this.categories.has(r)||this.categories.set(r,new Set),this.categories.get(r).add(e)}inferType(e){return null==e?"null":"number"==typeof e?"number":"string"==typeof e?"string":"boolean"==typeof e?"boolean":e instanceof Date?"date":Array.isArray(e)?"array":"object"==typeof e?"object":"unknown"}getCategories(){return Array.from(this.categories.keys())}getVariablesByCategory(e){const t=this.categories.get(e)||new Set;return Array.from(t).map(e=>this.variables.get(e)).filter(Boolean)}searchVariables(e,t={}){const r=[],n=e.toLowerCase();for(const e of this.variables.values()){const a=e.name.toLowerCase().includes(n),i=e.metadata.description.toLowerCase().includes(n),o=!t.category||e.category===t.category,s=!t.type||e.type===t.type;(a||i)&&o&&s&&r.push(e)}return r.slice(0,t.limit||100)}getStats(){return{totalVariables:this.variables.size,categories:this.categories.size,byType:this.getTypeStats()}}getTypeStats(){const e={};for(const t of this.variables.values())e[t.type]=(e[t.type]||0)+1;return e}updateVariables(e){(this.categories.get("user")||new Set).forEach(e=>{this.variables.delete(e)}),this.categories.set("user",new Set),Object.entries(e).forEach(([e,t])=>{this.addVariable(e,t,"user",{description:`Variable: ${e}`})})}}const dt=({onFunctionInsert:e,onVariableInsert:t,variables:n={},engine:a,customVariableComponent:o=null})=>{const[s,u]=r(0),[f]=r(()=>new mt(n));i(()=>{f.updateVariables(n)},[n,f]);const p=Object.keys(n).length,m=({children:e,value:t,index:r,...n})=>fe("div",{role:"tabpanel",hidden:t!==r,id:`palette-tabpanel-${r}`,"aria-labelledby":`palette-tab-${r}`,...n,children:t===r&&fe(c,{sx:{pt:2,height:"calc(100% - 48px)",overflow:"hidden",px:2},children:e})});return le(c,{className:"palette-container",sx:{height:"100%",display:"flex",flexDirection:"column",background:"#fafafa",borderRadius:2,overflow:"hidden"},children:[le(c,{sx:{borderBottom:1,borderColor:"divider",px:2,pt:2},children:[fe(l,{variant:"h6",gutterBottom:!0,children:"Formula Builder"}),le(z,{value:s,onChange:(e,t)=>{u(t)},variant:"fullWidth",sx:{minHeight:40},children:[fe(k,{icon:fe(V,{}),label:"Functions",iconPosition:"start",sx:{minHeight:40,fontSize:"0.875rem"}}),fe(k,{icon:fe(ie,{}),label:"Variables",iconPosition:"start",sx:{minHeight:40,fontSize:"0.875rem"}})]})]}),le(c,{sx:{flex:1,overflow:"hidden"},children:[fe(m,{value:s,index:0,children:fe(ft,{onFunctionInsert:e,onVariableInsert:t,variables:Object.keys(n),engine:a,showVariables:!1,showHeader:!1})}),fe(m,{value:s,index:1,children:o?fe(o,{variables:n,onVariableInsert:t,onFunctionInsert:e,engine:a}):p>0?fe(pt,{variableManager:f,onVariableInsert:t,onVariableEdit:e=>{console.log("Edit variable:",e)},onVariableDelete:e=>{console.log("Delete variable:",e)},onVariableAdd:()=>{console.log("Add variable clicked")}}):le(c,{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",sx:{height:"100%",p:3,textAlign:"center"},children:[fe(ie,{sx:{fontSize:48,color:"text.secondary",mb:2}}),fe(l,{variant:"h6",color:"text.secondary",gutterBottom:!0,children:"No Variables Available"}),fe(l,{variant:"body2",color:"text.secondary",sx:{mb:2},children:"Variables will appear here when you provide them to the Formula Builder."}),fe(l,{variant:"caption",color:"text.secondary",children:"Variables can be numbers, text, dates, or other data types that you want to reference in your formulas."})]})})]})]})},ht=({validation:e})=>{const t=(()=>{if(e.valid)return[];const t=[],r=e.error?.toLowerCase()||"";return r.includes("unexpected")&&t.push({type:"error",message:"Check for missing or extra parentheses, commas, or operators",icon:fe(oe,{color:"error"})}),r.includes("function")&&r.includes("not defined")&&t.push({type:"warning",message:"Function name might be misspelled or not available",icon:fe(se,{color:"warning"})}),r.includes("parenthes")&&t.push({type:"error",message:"Check that all parentheses are properly matched",icon:fe(oe,{color:"error"})}),(r.includes("comma")||r.includes("argument"))&&t.push({type:"info",message:"Verify function parameters are separated by commas",icon:fe(G,{color:"info"})}),(r.includes("string")||r.includes("quote"))&&t.push({type:"warning",message:"Ensure text values are enclosed in quotes",icon:fe(se,{color:"warning"})}),0!==t.length||e.valid||t.push({type:"info",message:"Check function names and parameter count",icon:fe(G,{color:"info"})},{type:"info",message:"Ensure proper use of operators and parentheses",icon:fe(G,{color:"info"})}),t})();return le(c,{children:[fe(l,{variant:"h6",gutterBottom:!0,children:"Validation"}),le(E,{variant:"outlined",sx:{p:2},children:[fe(m,{severity:e.valid?"success":"error",icon:e.valid?fe(ue,{color:"success"}):fe(oe,{color:"error"}),sx:{mb:t.length>0?2:0},children:fe(l,{variant:"body2",children:e.valid?"Formula is valid and ready to use":e.error||"Invalid formula syntax"})}),t.length>0&&le(c,{children:[fe(l,{variant:"subtitle2",gutterBottom:!0,sx:{mt:1},children:"Suggestions:"}),fe(B,{dense:!0,children:t.map((e,t)=>le(_,{sx:{py:.5},children:[fe(q,{sx:{minWidth:32},children:e.icon}),fe(R,{children:fe(l,{variant:"body2",color:"textSecondary",children:e.message})})]},t))})]}),e.valid&&e.ast&&le(c,{mt:2,children:[fe(l,{variant:"subtitle2",gutterBottom:!0,children:"Formula Analysis:"}),le(c,{display:"flex",flexWrap:"wrap",gap:1,children:[fe(g,{size:"small",label:`${gt(e.ast)} operations`,variant:"outlined",color:"info"}),yt(e.ast)&&fe(g,{size:"small",label:"Nested functions",variant:"outlined",color:"warning"}),vt(e.ast)&&fe(g,{size:"small",label:"Conditional logic",variant:"outlined",color:"primary"})]})]}),e.valid&&xt(e.ast)&&fe(c,{mt:2,children:fe(m,{severity:"info",sx:{fontSize:"0.875rem"},children:le(l,{variant:"caption",children:[fe("strong",{children:"BODMAS Order:"})," Brackets → Orders (powers) → Division/Multiplication → Addition/Subtraction"]})})})]})]})},gt=e=>e?"string"==typeof e||"number"==typeof e?1:"OperatorNode"===e.type||"FunctionNode"===e.type?1+(e.args||[]).reduce((e,t)=>e+gt(t),0):1:0,yt=e=>!(!e||"string"==typeof e||"number"==typeof e)&&("FunctionNode"===e.type?(e.args||[]).some(e=>"FunctionNode"===e.type||yt(e)):!!e.args&&e.args.some(e=>yt(e))),vt=e=>!(!e||"string"==typeof e||"number"==typeof e)&&(!("FunctionNode"!==e.type||!["IF","AND","OR","NOT"].includes(e.fn?.name))||!!e.args&&e.args.some(e=>vt(e))),xt=e=>!(!e||"string"==typeof e||"number"==typeof e)&&(!("OperatorNode"!==e.type||!["+","-","*","/","^"].includes(e.op))||!!e.args&&e.args.some(e=>xt(e))),bt=({result:e,formula:t,variables:r={}})=>{const n=null!=e,a="string"==typeof e&&e.startsWith("Error:");return le(c,{children:[fe(l,{variant:"h6",gutterBottom:!0,children:"Preview"}),le(E,{variant:"outlined",sx:{p:2},children:[le(c,{mb:2,children:[fe(l,{variant:"subtitle2",gutterBottom:!0,children:"Current Formula:"}),fe(E,{variant:"outlined",sx:{p:1.5,backgroundColor:"grey.50",fontFamily:"monospace",fontSize:"0.875rem",minHeight:"40px",display:"flex",alignItems:"center"},children:t||fe(l,{color:"textSecondary",children:"No formula entered"})})]}),le(c,{mb:2,children:[fe(l,{variant:"subtitle2",gutterBottom:!0,children:"Result:"}),fe(m,{severity:a?"error":n?"success":"info",icon:a?fe(oe,{color:"error"}):n?fe(ue,{color:"success"}):fe(ce,{color:"action"}),sx:{"& .MuiAlert-message":{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between"}},children:le(c,{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",children:[fe(l,{variant:"body2",component:"span",sx:{fontFamily:n&&!a?"monospace":"inherit",fontWeight:n&&!a?"bold":"normal"},children:n?(i=e,null==i?"null":"boolean"==typeof i?i.toString():"number"==typeof i?Number.isInteger(i)?i.toString():i.toFixed(6).replace(/\.?0+$/,""):"string"==typeof i?`"${i}"`:i instanceof Date?i.toISOString():"object"==typeof i?JSON.stringify(i,null,2):String(i)):t?"Enter a valid formula to see the result":"No formula to evaluate"}),n&&!a&&fe(g,{size:"small",label:(e=>null==e?"null":"boolean"==typeof e?"boolean":"number"==typeof e?"number":"string"!=typeof e||e.startsWith("Error:")?e instanceof Date?"date":"object"==typeof e?"object":"unknown":"string")(e),variant:"outlined",sx:{ml:1}})]})})]}),n&&!a&&le(c,{mt:2,children:[fe(O,{sx:{my:2}}),fe(l,{variant:"caption",color:"textSecondary",children:"Formula evaluated successfully. Results update in real-time as you type."})]})]})]});var i};function wt(){return wt=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},wt.apply(null,arguments)}var Nt={epsilon:1e-12,matrix:"Matrix",number:"number",precision:64,predictable:!1,randomSeed:null};function Dt(e){return"number"==typeof e}function Et(e){return!(!e||"object"!=typeof e||"function"!=typeof e.constructor)&&(!0===e.isBigNumber&&"object"==typeof e.constructor.prototype&&!0===e.constructor.prototype.isBigNumber||"function"==typeof e.constructor.isDecimal&&!0===e.constructor.isDecimal(e))}function At(e){return e&&"object"==typeof e&&!0===Object.getPrototypeOf(e).isComplex||!1}function Ct(e){return e&&"object"==typeof e&&!0===Object.getPrototypeOf(e).isFraction||!1}function St(e){return e&&!0===e.constructor.prototype.isUnit||!1}function Mt(e){return"string"==typeof e}var Tt=Array.isArray;function Ft(e){return e&&!0===e.constructor.prototype.isMatrix||!1}function Ot(e){return Array.isArray(e)||Ft(e)}function Bt(e){return e&&e.isDenseMatrix&&!0===e.constructor.prototype.isMatrix||!1}function _t(e){return e&&e.isSparseMatrix&&!0===e.constructor.prototype.isMatrix||!1}function Rt(e){return e&&!0===e.constructor.prototype.isRange||!1}function It(e){return e&&!0===e.constructor.prototype.isIndex||!1}function zt(e){return"boolean"==typeof e}function kt(e){return e&&!0===e.constructor.prototype.isResultSet||!1}function qt(e){return e&&!0===e.constructor.prototype.isHelp||!1}function Pt(e){return"function"==typeof e}function jt(e){return e instanceof Date}function Ut(e){return e instanceof RegExp}function Lt(e){return!(!e||"object"!=typeof e||e.constructor!==Object||At(e)||Ct(e))}function Ht(e){return null===e}function Vt(e){return void 0===e}function Wt(e){return e&&!0===e.isAccessorNode&&!0===e.constructor.prototype.isNode||!1}function $t(e){return e&&!0===e.isArrayNode&&!0===e.constructor.prototype.isNode||!1}function Gt(e){return e&&!0===e.isAssignmentNode&&!0===e.constructor.prototype.isNode||!1}function Yt(e){return e&&!0===e.isBlockNode&&!0===e.constructor.prototype.isNode||!1}function Zt(e){return e&&!0===e.isConditionalNode&&!0===e.constructor.prototype.isNode||!1}function Xt(e){return e&&!0===e.isConstantNode&&!0===e.constructor.prototype.isNode||!1}function Jt(e){return Xt(e)||nr(e)&&1===e.args.length&&Xt(e.args[0])&&"-+~".includes(e.op)}function Kt(e){return e&&!0===e.isFunctionAssignmentNode&&!0===e.constructor.prototype.isNode||!1}function Qt(e){return e&&!0===e.isFunctionNode&&!0===e.constructor.prototype.isNode||!1}function er(e){return e&&!0===e.isIndexNode&&!0===e.constructor.prototype.isNode||!1}function tr(e){return e&&!0===e.isNode&&!0===e.constructor.prototype.isNode||!1}function rr(e){return e&&!0===e.isObjectNode&&!0===e.constructor.prototype.isNode||!1}function nr(e){return e&&!0===e.isOperatorNode&&!0===e.constructor.prototype.isNode||!1}function ar(e){return e&&!0===e.isParenthesisNode&&!0===e.constructor.prototype.isNode||!1}function ir(e){return e&&!0===e.isRangeNode&&!0===e.constructor.prototype.isNode||!1}function or(e){return e&&!0===e.isRelationalNode&&!0===e.constructor.prototype.isNode||!1}function sr(e){return e&&!0===e.isSymbolNode&&!0===e.constructor.prototype.isNode||!1}function ur(e){return e&&!0===e.constructor.prototype.isChain||!1}function cr(e){var t=typeof e;return"object"===t?null===e?"null":Et(e)?"BigNumber":e.constructor&&e.constructor.name?e.constructor.name:"Object":t}function lr(e){var t=typeof e;if("number"===t||"string"===t||"boolean"===t||null==e)return e;if("function"==typeof e.clone)return e.clone();if(Array.isArray(e))return e.map(function(e){return lr(e)});if(e instanceof Date)return new Date(e.valueOf());if(Et(e))return e;if(Lt(e))return fr(e,lr);throw new TypeError("Cannot clone: unknown type of value (value: ".concat(e,")"))}function fr(e,t){var r={};for(var n in e)vr(e,n)&&(r[n]=t(e[n]));return r}function pr(e,t){for(var r in t)vr(t,r)&&(e[r]=t[r]);return e}function mr(e,t){if(Array.isArray(t))throw new TypeError("Arrays are not supported by deepExtend");for(var r in t)if(vr(t,r)&&!(r in Object.prototype)&&!(r in Function.prototype))if(t[r]&&t[r].constructor===Object)void 0===e[r]&&(e[r]={}),e[r]&&e[r].constructor===Object?mr(e[r],t[r]):e[r]=t[r];else{if(Array.isArray(t[r]))throw new TypeError("Arrays are not supported by deepExtend");e[r]=t[r]}return e}function dr(e,t){var r,n,a;if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(n=0,a=e.length;n<a;n++)if(!dr(e[n],t[n]))return!1;return!0}if("function"==typeof e)return e===t;if(e instanceof Object){if(Array.isArray(t)||!(t instanceof Object))return!1;for(r in e)if(!(r in t)||!dr(e[r],t[r]))return!1;for(r in t)if(!(r in e))return!1;return!0}return e===t}function hr(e){var t={};return gr(e,t),t}function gr(e,t){for(var r in e)if(vr(e,r)){var n=e[r];"object"==typeof n&&null!==n?gr(n,t):t[r]=n}}function yr(e,t,r){var n,a=!0;Object.defineProperty(e,t,{get:function(){return a&&(n=r(),a=!1),n},set:function(e){n=e,a=!1},configurable:!0,enumerable:!0})}function vr(e,t){return e&&Object.hasOwnProperty.call(e,t)}var xr=["Matrix","Array"],br=["number","BigNumber","Fraction"];function wr(e,t){function r(r){if(r){var n=fr(e,lr);Nr(r,"matrix",xr),Nr(r,"number",br),mr(e,r);var a=fr(e,lr),i=fr(r,lr);return t("config",a,n,i),a}return fr(e,lr)}return r.MATRIX_OPTIONS=xr,r.NUMBER_OPTIONS=br,Object.keys(Nt).forEach(t=>{Object.defineProperty(r,t,{get:()=>e[t],enumerable:!0,configurable:!0})}),r}function Nr(e,t,r){void 0===e[t]||r.includes(e[t])||console.warn('Warning: Unknown value "'+e[t]+'" for configuration option "'+t+'". Available options: '+r.map(e=>JSON.stringify(e)).join(", ")+".")}var Dr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Er(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ar(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var Cr={exports:{}};Cr.exports=function(){function e(){return!0}function t(){return!1}function r(){}const n="Argument is not a typed-function.";function a(){function i(e){return"object"==typeof e&&null!==e&&e.constructor===Object}const o=[{name:"number",test:function(e){return"number"==typeof e}},{name:"string",test:function(e){return"string"==typeof e}},{name:"boolean",test:function(e){return"boolean"==typeof e}},{name:"Function",test:function(e){return"function"==typeof e}},{name:"Array",test:Array.isArray},{name:"Date",test:function(e){return e instanceof Date}},{name:"RegExp",test:function(e){return e instanceof RegExp}},{name:"Object",test:i},{name:"null",test:function(e){return null===e}},{name:"undefined",test:function(e){return void 0===e}}],s={name:"any",test:e,isAny:!0};let u,c,l=0,f={createCount:0};function p(e){const t=u.get(e);if(t)return t;let r='Unknown type "'+e+'"';const n=e.toLowerCase();let a;for(a of c)if(a.toLowerCase()===n){r+='. Did you mean "'+a+'" ?';break}throw new TypeError(r)}function m(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"any";const r=t?p(t).index:c.length,n=[];for(let t=0;t<e.length;++t){if(!e[t]||"string"!=typeof e[t].name||"function"!=typeof e[t].test)throw new TypeError("Object with properties {name: string, test: function} expected");const a=e[t].name;if(u.has(a))throw new TypeError('Duplicate type name "'+a+'"');n.push(a),u.set(a,{name:a,test:e[t].test,isAny:e[t].isAny,index:r+t,conversionsTo:[]})}const a=c.slice(r);c=c.slice(0,r).concat(n).concat(a);for(let e=r+n.length;e<c.length