text: /**
   * @copyright 2021 Timur Atalay
   * @homepage https://github.com/bornova/numara-calculator
   * @license MIT - https://github.com/bornova/numara-calculator/blob/master/LICENSE
   */
  
  appInfo = {
      productName: 'Numara',
      description:'Numara Calculator',
      version: '3.6.3',
      author: 'Timur Atalay',
      homepage: 'https://github.com/bornova/numara-calculator',
      licence: 'MIT',
      website: 'https://numara.io'
  };
  const $=t=>document.getElementById(t),ls={get:t=>JSON.parse(localStorage.getItem(t)),set:(t,e)=>{localStorage.setItem(t,JSON.stringify(e))}},DateTime=luxon.DateTime;feather.replace();const cm=CodeMirror.fromTextArea($("inputArea"),{theme:"numara",coverGutterNextToScrollbar:!0,inputStyle:"textarea",viewportMargin:1/0});cm.setValue(ls.get("input")||""),cm.execCommand("goDocEnd"),$("udfInput").setAttribute("placeholder",'// Define new functions and variables:\nmyvalue: 42,\nhello: (name) => {\n  return "hello, " + name + "!"\n}');const udfInput=CodeMirror.fromTextArea($("udfInput"),{mode:"javascript",autoCloseBrackets:!0,smartIndent:!1});$("uduInput").setAttribute("placeholder",'// Define new units:\nfoo: {\n  prefixes: "long",\n  baseName: "essence-of-foo"\n},\nbar: "40 foo",\nbaz: {\n  definition: "1 bar/hour",\n  prefixes: "long"\n}');const uduInput=CodeMirror.fromTextArea($("uduInput"),{mode:"javascript",autoCloseBrackets:!0,smartIndent:!1}),isMac=navigator.userAgent.toLowerCase().includes("mac"),isNode=navigator.userAgent.toLowerCase().includes("electron"),ipc=isNode?require("electron").ipcRenderer:null;function toggleMax(){ipc.send(ipc.sendSync("isMaximized")?"unmaximize":"maximize")}let settings;document.title=appInfo.description,$("dialog-about-title").innerHTML=appInfo.description,$("dialog-about-copyright").innerHTML=`Copyright ©️ ${DateTime.local().year} ${appInfo.author}`,$("dialog-about-appVersion").innerHTML=isNode?"Version "+appInfo.version:`Version ${appInfo.version}\n    <div class="versionCtnr">\n      <div>\n        <a href="https://github.com/bornova/numara-calculator/releases" target="_blank">Download desktop version</a>\n      </div>\n    </div>`,$("gitLink").setAttribute("href",appInfo.homepage),$("webLink").setAttribute("href",appInfo.website),$("licenseLink").setAttribute("href",appInfo.homepage+"/blob/master/LICENSE"),isNode?(ipc.on("themeUpdate",applySettings),ipc.on("fullscreen",((t,e)=>{e&&ipc.send("maximize")}))):"serviceWorker"in navigator&&navigator.serviceWorker.register("./sw.js").catch((()=>{console.log("Service worker registration failed")})),isNode&&!isMac?($("header-mac").remove(),$("header-win").style.display="block",$("header-win-title").innerHTML=appInfo.productName,$("max").style.display=ipc.sendSync("isMaximized")?"none":"block",$("unmax").style.display=ipc.sendSync("isMaximized")?"block":"none",$("winButtons").addEventListener("click",(t=>{switch(t.target.id){case"min":ipc.send("minimize");break;case"max":ipc.send("maximize");break;case"unmax":ipc.send("unmaximize");break;case"close":ipc.send("close")}t.stopPropagation()})),ipc.on("isMax",((t,e)=>{$("unmax").style.display=e?"block":"none",$("max").style.display=e?"none":"block"})),$("header-win").addEventListener("dblclick",toggleMax)):($("header-win").remove(),$("header-mac").style.display="block",$("header-mac-title").innerHTML=appInfo.productName,isNode&&$("header-mac").addEventListener("dblclick",toggleMax));const defaultSettings={app:{autocomplete:!0,closeBrackets:!0,contPrevLine:!0,currencies:!0,dateDay:!1,dateFormat:"M/d/yyyy",divider:!0,fontSize:"1.1rem",fontWeight:"400",keywordTips:!0,lineErrors:!0,lineNumbers:!0,lineWrap:!0,matchBrackets:!0,matrixType:"Matrix",numericOutput:"number",precision:"4",predictable:!1,syntax:!0,theme:"system",thouSep:!0,timeFormat:"h:mm a"},inputWidth:60,plot:{plotArea:!1,plotCross:!1,plotGrid:!1}};settings=ls.get("settings"),settings?DeepDiff.observableDiff(settings,defaultSettings,(t=>{"E"!==t.kind&&(DeepDiff.applyChange(settings,defaultSettings,t),ls.set("settings",settings))})):(settings=defaultSettings,ls.set("settings",defaultSettings)),math.createUnit("USD",{aliases:["usd"]});let currencyRates={};function getRates(){navigator.onLine?($("lastUpdated").innerHTML='<div uk-spinner="ratio: 0.3"></div>',fetch("https://www.floatrates.com/widget/1030/cfc5515dfc13ada8d7b0e50b8143d55f/usd.json").then((t=>t.json())).then((t=>{currencyRates=t;const e=["cup"];Object.keys(t).forEach((n=>{math.createUnit(t[n].code,{definition:math.unit(t[n].inverseRate+"USD"),aliases:[e.includes(t[n].code.toLowerCase())?"":t[n].code.toLowerCase()]},{override:!0}),ls.set("rateDate",t[n].date)})),applySettings(),$("lastUpdated").innerHTML=ls.get("rateDate")})).catch((t=>{$("lastUpdated").innerHTML="n/a",notify("Failed to get exchange rates ("+t+")","warning")}))):($("lastUpdated").innerHTML="No internet connection.",notify("No internet connection. Could not update exchange rates.","warning"))}function calculate(){let t=[];const e=[],n=[],i=[],a={},s={},o={lowerExp:-12,upperExp:12},r={maximumFractionDigits:settings.app.precision};function l(t){s.avg=math.evaluate(e.length>0?"("+math.mean(e)+")":0),s.total=math.evaluate(n.length>0?"("+n.join("+")+")":0),s.subtotal=math.evaluate(i.length>0?"("+i.join("+")+")":0);const o=(t=t.replace(/\bans\b/g,a.ans).replace(/\bnow\b/g,a.now).replace(/\btoday\b/g,a.today).replace(/\bavg\b/g,s.avg).replace(/\btotal\b/g,s.total).replace(/\bsubtotal\b/g,s.subtotal)).match(/\bline\d+\b/g);o&&o.forEach((e=>{t=t.replace(e,a[e])}));if(t.match(/'millisecond|second|minute|hour|day|week|month|quarter|year|decade|century|centuries|millennium|millennia'/g)){const e=t.split(/[+-]/),n=e[0].replace(/[A-Za-z]+,/,"").trim(),i=t.replace(e[0],"").trim(),s=settings.app.dateFormat,o=settings.app.dateFormat+" "+settings.app.timeFormat,r=DateTime.fromFormat(n,s),l=DateTime.fromFormat(n,o),c=r.isValid?r:l.isValid?l:null,p=String(math.evaluate(i+" to hours",a)),d=Number(p.split(" ")[0]);if(!c)return"Invalid Date";{const e=c.toFormat(settings.app.dateFormat+"hh:mm:ss:SSS").endsWith("12:00:00:000");t='"'+c.plus({hours:d}).toFormat((settings.app.dateDay?"ccc, ":"")+(e?s:o))+'"'}}return t=t.match(/[\w.]*%[ ]*of[ ]*/g)?t.replace(/%[ ]*of[ ]*/g,"/100*"):t,math.evaluate(t,a)}a.now=DateTime.local().toFormat((settings.app.dateDay?"ccc, ":"")+settings.app.dateFormat+" "+settings.app.timeFormat),a.today=DateTime.local().toFormat((settings.app.dateDay?"ccc, ":"")+settings.app.dateFormat),cm.refresh(),cm.eachLine((s=>{const c=cm.getLineNumber(s),p=c+1,d=s.height;let u="",g=s.text.trim().split("//")[0].split("#")[0];if(cm.removeLineClass(c,"gutter","lineNoError"),g)try{g=p>1&&g.charAt(0).match(/[+\-*/]/)&&cm.getLine(p-2).length>0&&settings.app.contPrevLine?a.ans+g:g;try{u=math.evaluate(g,a)}catch(t){if(g.match(/:/))try{math.evaluate(g.split(":")[0])}catch(t){g=g.substring(g.indexOf(":")+1)}for(;g.match(/\([^)]+\)/);){let t=g.substring(g.lastIndexOf("(")+1),e=g.substring(g.lastIndexOf("("));if(t=t.substring(0,t.indexOf(")")),e=e.substring(0,e.indexOf(")")+1),0===e.length)break;try{g=g.replace(e,l(t))}catch(t){break}}u=l(g)}if(void 0!==u){if(a.ans=u,a["line"+p]=u,isNaN(u)||(e.push(u),n.push(u),i.push(u)),u=function(t){const e=(t=String(t)).trim().split(" ")[0],n=t.replace(e,"");return e.includes("e")||isNaN(e)?e.match(/e-?\d+/)?parseFloat(Number(e.split("e")[0]).toFixed(settings.app.precision))+"e"+t.split("e")[1]+n:function(t){let e=t.length;'"'===t.charAt(0)&&(t=t.substring(1,e--));'"'===t.charAt(--e)&&(t=t.substring(0,e));return t}(t):settings.app.thouSep?Number(e).toLocaleString(void 0,r)+n:parseFloat(Number(e).toFixed(settings.app.precision))+n}(math.format(u,o)),u.match(/\w\(x\)/)){const t=/\w\(x\)$/.test(u)?g.trim():u.trim();u=`<a class="plotButton" data-func="${t}">Plot</a>`,a.ans=t,a["line"+p]=t}}else i.length=0,u=""}catch(t){const e=String(t).replace(/'|"/g,"`");u=settings.app.lineErrors?`<a class="lineError" data-line="${p}" data-error="${e}">Error</a>`:"",settings.app.lineErrors&&cm.addLineClass(c,"gutter","lineNoError")}else i.length=0;t+=`\n      <div style="height:${d}px">\n        <span class="${u&&!u.startsWith("<a")?"answer":""}" >${u}</span>\n      </div>`})),$("output").innerHTML=t,$("clearButton").className=""===cm.getValue()?"noAction":"action",$("printButton").className=""===cm.getValue()?"noAction":"action",$("saveButton").className=""===cm.getValue()?"noAction":"action",ls.set("input",cm.getValue())}const udfList=[],uduList=[];function applyUdf(t){try{new Function(`'use strict'; math.import({${t}}, {override: true})`)(),calculate(),ls.set("udf",t);const e=new Function(`'use strict'; return {${t}}`)();for(const t in e)udfList.push(t);UIkit.modal("#dialog-udfu").hide()}catch(t){$("udfSyntaxError").innerHTML=t}}function applyUdu(t){try{new Function(`'use strict'; math.createUnit({${t}}, {override: true})`)(),calculate(),ls.set("udu",t);const e=new Function(`'use strict'; return {${t}}`)();for(const t in e)uduList.push(t);UIkit.modal("#dialog-udfu").hide()}catch(t){$("uduSyntaxError").innerHTML=t}}UIkit.util.on("#dialog-udfu","beforeshow",(()=>{$("udfSyntaxError").innerHTML="",$("uduSyntaxError").innerHTML="";const t=ls.get("udf").trim(),e=ls.get("udu").trim();udfInput.setValue(t),uduInput.setValue(e)})),UIkit.util.on("#dialog-udfu","shown",(()=>{udfInput.refresh(),uduInput.refresh()})),ls.get("udf")||ls.set("udf",""),ls.get("udu")||ls.set("udu",""),applyUdf(ls.get("udf")),applyUdu(ls.get("udu")),CodeMirror.defineMode("numara",(()=>({token:(t,e)=>{if(t.match(/\/\/.*/)||t.match(/#.*/))return"comment";if(t.match(/\d/))return"number";if(t.match(/(?:\+|-|\*|\/|,|;|\.|:|@|~|=|>|<|&|\||_|`|'|\^|\?|!|%)/))return"operator";t.eatWhile(/\w/);const n=t.current();if(settings.app.currencies&&(n.toLowerCase()in currencyRates||"usd"===n.toLowerCase()))return"currency";try{if(math.unit(n).units.length>0)return"unit"}catch(t){}if(udfList.includes(n))return"udf";if(uduList.includes(n))return"udu";if("function"==typeof math[n]&&Object.getOwnPropertyNames(math[n]).includes("signatures"))return"function";if(n.match(/\b(?:ans|total|subtotal|avg|today|now|line\d+)\b/))return"scope";try{math.evaluate(n)}catch(t){return"variable"}return t.next(),"space"}}))),CodeMirror.defineMode("plain",(()=>({token:(t,e)=>(t.next(),"text")})));const numaraHints=["ans","now","today","total","subtotal","avg"];function applySettings(){settings=ls.get("settings"),$("style").setAttribute("href","system"===settings.app.theme?isNode&&ipc.sendSync("isDark")?"css/dark.css":"css/light.css":"light"===settings.app.theme?"css/light.css":"css/dark.css"),isNode&&ipc.send("setTheme",settings.app.theme);const t=document.querySelectorAll(".panelFont, .CodeMirror");for(const e of t)e.style.fontSize=settings.app.fontSize,e.style.fontWeight=settings.app.fontWeight;$("input").style.width=(settings.app.divider?settings.inputWidth:defaultSettings.inputWidth)+"%",$("divider").style.display=settings.app.divider?"block":"none",$("output").style.textAlign=settings.app.divider?"left":"right",cm.setOption("mode",settings.app.syntax?"numara":"plain"),cm.setOption("lineNumbers",settings.app.lineNumbers),cm.setOption("lineWrapping",settings.app.lineWrap),cm.setOption("autoCloseBrackets",settings.app.closeBrackets),cm.setOption("matchBrackets",!(!settings.app.syntax||!settings.app.matchBrackets)&&{maxScanLines:1});const e="system"===settings.app.theme?isNode&&ipc.sendSync("isDark")?"material-darker":"default":"light"===settings.app.theme?"default":"material-darker";udfInput.setOption("theme",e),uduInput.setOption("theme",e),math.config({matrix:settings.app.matrixType,number:settings.app.numericOutput,predictable:settings.app.predictable}),setTimeout(calculate,15)}function showModal(t){UIkit.modal(t,{bgClose:!1,stack:!0}).show()}Object.getOwnPropertyNames(math).forEach((t=>{"function"==typeof math[t]&&Object.getOwnPropertyNames(math[t]).includes("signatures")&&numaraHints.push(t)})),CodeMirror.registerHelper("hint","numaraHints",(t=>{const e=t.getCursor(),n=t.getLine(e.line);let i=e.ch,a=i;for(;a<n.length&&/[\w$]/.test(n.charAt(a));)++a;for(;i&&/[\w$]/.test(n.charAt(i-1));)--i;const s=i!==a&&n.slice(i,a),o=new RegExp("^"+s,"i");return{list:(s?numaraHints.filter((t=>t.match(o))):[]).sort(),from:CodeMirror.Pos(e.line,i),to:CodeMirror.Pos(e.line,a)}})),CodeMirror.commands.autocomplete=t=>{CodeMirror.showHint(t,CodeMirror.hint.numaraHints,{completeSingle:!1})},cm.on("changes",calculate),cm.on("inputRead",((t,e)=>{settings.app.autocomplete&&CodeMirror.commands.autocomplete(t)})),cm.on("update",(()=>{const t=document.getElementsByClassName("cm-function");if(t.length>0&&settings.app.keywordTips)for(const e of t)try{const t=JSON.stringify(math.help(e.innerHTML).toJSON()),n=JSON.parse(t);UIkit.tooltip(e,{title:n.description,pos:"top-left"})}catch(t){UIkit.tooltip(e,{title:"Description not available.",pos:"top-left"})}const e=document.getElementsByClassName("cm-udf");if(e.length>0&&settings.app.keywordTips)for(const t of e)UIkit.tooltip(t,{title:"User defined function.",pos:"top-left"});const n=document.getElementsByClassName("cm-udu");if(n.length>0&&settings.app.keywordTips)for(const t of n)UIkit.tooltip(t,{title:"User defined unit.",pos:"top-left"});const i=document.getElementsByClassName("cm-currency");if(i.length>0&&settings.app.keywordTips)for(const t of i)try{const e=t.innerHTML.toLowerCase(),n="usd"===e?"U.S. Dollar":currencyRates[e].name;UIkit.tooltip(t,{title:n,pos:"top-left"})}catch(e){UIkit.tooltip(t,{title:"Description not available.",pos:"top-left"})}const a=document.getElementsByClassName("cm-unit");if(a.length>0&&settings.app.keywordTips)for(const t of a)UIkit.tooltip(t,{title:`Unit '${t.innerHTML}'`,pos:"top-left"})})),applySettings(),settings.app.currencies&&getRates(),UIkit.mixin({data:{delay:500,offset:5}},"tooltip"),UIkit.util.on(".modal","hidden",(()=>{cm.focus()})),UIkit.util.on(".uk-switcher","show",(()=>{cm.getInputField().blur()}));const savedCount=()=>Object.keys(ls.get("saved")||{}).length;function updateSavedCount(){UIkit.tooltip("#openButton",{title:"Open ("+savedCount()+")"})}function populateSaved(){const t=ls.get("saved")||{},e=Object.entries(t);$("dialog-open-body").innerHTML="",e.length>0?($("dialog-open-deleteAll").disabled=!1,e.forEach((([t,e])=>{$("dialog-open-body").innerHTML+=`\n        <div class="dialog-open-wrapper" id="${t}">\n          <div data-action="load">\n            <div class="dialog-open-title">${e[0]}</div>\n            <div class="dialog-open-date">${DateTime.fromFormat(t,"yyyyMMddHHmmssSSS").toFormat("ff")}</div>\n          </div>\n          <span class="dialog-open-delete" data-action="delete"><i data-feather="x-circle"></i></span>\n        </div>`})),feather.replace()):($("dialog-open-deleteAll").disabled=!0,$("dialog-open-body").innerHTML="No saved calculations.",$("openButton").className="noAction"),updateSavedCount()}function prepSettings(){const t=["M/d/yyyy","d/M/yyyy","MMM d, yyyy"],e=["h:mm a","H:mm"],n=["Matrix","Array"],i=["number","BigNumber","Fraction"];$("themeList").value=settings.app.theme,$("fontSize").value=settings.app.fontSize,$("fontWeight").value=settings.app.fontWeight,$("dateFormat").innerHTML="";for(const e of t)$("dateFormat").innerHTML+=`<option value="${e}">${DateTime.local().toFormat(e)}</option>`;$("dateFormat").value=settings.app.dateFormat,$("timeFormat").innerHTML="";for(const t of e)$("timeFormat").innerHTML+=`<option value="${t}">${DateTime.local().toFormat(t)}</option>`;$("timeFormat").value=settings.app.timeFormat,$("dateDay").checked=settings.app.dateDay,$("syntaxButton").checked=settings.app.syntax,syntaxToggle(),$("keywordTipsButton").checked=settings.app.keywordTips,$("matchBracketsButton").checked=settings.app.matchBrackets,$("precisionRange").value=settings.app.precision,$("precision-label").innerHTML=settings.app.precision,$("numericOutput").innerHTML="";for(const t of i)$("numericOutput").innerHTML+=`<option value="${t}">${t.charAt(0).toUpperCase()+t.slice(1)}</option>`;$("numericOutput").value=settings.app.numericOutput,"BigNumber"===settings.app.numericOutput&&bigNumberWarning(),$("contPrevLineButton").checked=settings.app.contPrevLine,$("matrixType").innerHTML="";for(const t of n)$("matrixType").innerHTML+=`<option value="${t}">${t}</option>`;$("matrixType").value=settings.app.matrixType,$("predictableButton").checked=settings.app.predictable,$("thouSepButton").checked=settings.app.thouSep,$("currencyButton").checked=settings.app.currencies,$("lastUpdated").innerHTML=settings.app.currencies?ls.get("rateDate"):"",$("currencyUpdate").style.display=settings.app.currencies?"block":"none",$("autocompleteButton").checked=settings.app.autocomplete,$("closeBracketsButton").checked=settings.app.closeBrackets,$("dividerButton").checked=settings.app.divider,$("lineNoButton").checked=settings.app.lineNumbers,$("lineErrorButton").checked=settings.app.lineErrors,$("lineWrapButton").checked=settings.app.lineWrap,checkDefaultSettings(),checkWindowSize()}function checkDefaultSettings(){$("defaultSettingsButton").style.display=DeepDiff.diff(settings.app,defaultSettings.app)?"inline":"none"}function checkWindowSize(){$("resetSizeButton").style.display=isNode&&ipc.sendSync("isResized")&&!ipc.sendSync("isMaximized")?"block":"none"}function syntaxToggle(){$("keywordTipsButton").disabled=!$("syntaxButton").checked,$("matchBracketsButton").disabled=!$("syntaxButton").checked,$("keywordTipsButton").parentNode.style.opacity=$("syntaxButton").checked?"1":"0.5",$("matchBracketsButton").parentNode.style.opacity=$("syntaxButton").checked?"1":"0.5"}function bigNumberWarning(){$("bigNumWarn").style.display="BigNumber"===$("numericOutput").value?"inline-block":"none"}function saveSettings(){settings.app.theme=$("themeList").value,settings.app.fontSize=$("fontSize").value,settings.app.fontWeight=$("fontWeight").value,settings.app.dateFormat=$("dateFormat").value,settings.app.timeFormat=$("timeFormat").value,settings.app.dateDay=$("dateDay").checked,settings.app.syntax=$("syntaxButton").checked,settings.app.keywordTips=$("keywordTipsButton").checked,settings.app.matchBrackets=$("matchBracketsButton").checked,settings.app.precision=$("precisionRange").value,settings.app.numericOutput=$("numericOutput").value,settings.app.contPrevLine=$("contPrevLineButton").checked,settings.app.matrixType=$("matrixType").value,settings.app.predictable=$("predictableButton").checked,settings.app.thouSep=$("thouSepButton").checked,!settings.app.currencies&&$("currencyButton").checked?getRates():$("currencyButton").checked||(localStorage.removeItem("rateDate"),currencyRates={}),settings.app.currencies=$("currencyButton").checked,settings.app.autocomplete=$("autocompleteButton").checked,settings.app.closeBrackets=$("closeBracketsButton").checked,settings.app.divider=$("dividerButton").checked,settings.app.lineNumbers=$("lineNoButton").checked,settings.app.lineErrors=$("lineErrorButton").checked,settings.app.lineWrap=$("lineWrapButton").checked,ls.set("settings",settings),checkDefaultSettings(),applySettings()}let resizeDelay;updateSavedCount(),$("openButton").className=savedCount()>0?"action":"noAction",$("actions").addEventListener("click",(t=>{switch(t.target.id){case"clearButton":""!==cm.getValue()&&(cm.setValue(""),cm.focus(),calculate());break;case"printButton":UIkit.tooltip("#printButton").hide(),""!==cm.getValue()&&($("print-title").innerHTML=appInfo.productName,$("printBox").innerHTML=$("panel").innerHTML,isNode?(ipc.send("print"),ipc.on("printReply",((t,e)=>{e&&notify(e),$("printBox").innerHTML=""}))):window.print());break;case"saveButton":""!==cm.getValue()&&($("saveTitle").value="",showModal("#dialog-save"),$("saveTitle").focus());break;case"openButton":Object.keys(ls.get("saved")||{}).length>0&&showModal("#dialog-open");break;case"udfuButton":showModal("#dialog-udfu");break;case"settingsButton":showModal("#dialog-settings");break;case"helpButton":showModal("#dialog-help"),$("searchBox").focus();break;case"aboutButton":showModal("#dialog-about")}t.stopPropagation()})),$("output").addEventListener("click",(t=>{switch(t.target.className){case"answer":navigator.clipboard.writeText(t.target.innerText),notify(`Copied '${t.target.innerText}' to clipboard.`);break;case"plotButton":func=t.target.getAttribute("data-func");try{$("plotGrid").checked=settings.plot.plotGrid,$("plotCross").checked=settings.plot.plotCross,$("plotArea").checked=settings.plot.plotArea,plot(),showModal("#dialog-plot")}catch(t){showError(t)}break;case"lineError":showError(t.target.getAttribute("data-error"),"Error on Line "+t.target.getAttribute("data-line"))}t.stopPropagation()})),$("output").addEventListener("mousedown",(()=>{const t=document.getElementsByClassName("CodeMirror-selected");for(;t[0];)t[0].classList.remove("CodeMirror-selected")})),document.addEventListener("click",(t=>{const e=DateTime.local().toFormat("yyyyMMddHHmmssSSS"),n=ls.get("saved")||{},i=cm.getValue(),a=$("saveTitle").value.replace(/<|>/g,"").trim()||"No title";switch(t.target.id){case"dialog-save-save":n[e]=[a,i],ls.set("saved",n),UIkit.modal("#dialog-save").hide(),$("openButton").className="action",updateSavedCount(),notify("Saved");break;case"dialog-open-deleteAll":confirm("All saved calculations will be deleted.",(()=>{localStorage.removeItem("saved"),populateSaved(),UIkit.modal("#dialog-open").hide(),notify("Deleted all saved calculations")}));break;case"dialog-udfu-save-f":applyUdf(udfInput.getValue().trim());break;case"dialog-udfu-save-u":applyUdu(uduInput.getValue().trim());break;case"defaultSettingsButton":confirm("All settings will revert back to defaults.",(()=>{settings.app=defaultSettings.app,ls.set("settings",settings),applySettings(),$("currencyButton").checked||getRates(),prepSettings()}));break;case"dialog-settings-reset":confirm("All user settings and data will be lost.",(()=>{isNode?ipc.send("resetApp"):(localStorage.clear(),location.reload())}));break;case"resetSizeButton":isNode&&ipc.send("resetSize");break;case"syntaxButton":syntaxToggle();break;case"bigNumWarn":showError('Using the BigNumber may break function plotting and is not compatible with some math functions. \n      It may also cause unexpected behavior and affect overall performance.<br><br>\n      <a target="_blank" href="https://mathjs.org/docs/datatypes/bignumbers.html">Read more on BigNumbers</a>',"Caution: BigNumber Limitations");break;case"currencyButton":$("currencyUpdate").style.visibility=$("currencyButton").checked?"visible":"hidden";break;case"plotGrid":settings.plot.plotGrid=$("plotGrid").checked,ls.set("settings",settings),plot();break;case"plotCross":settings.plot.plotCross=$("plotCross").checked,ls.set("settings",settings),plot();break;case"plotArea":settings.plot.plotArea=$("plotArea").checked,ls.set("settings",settings),plot();break;case"restartButton":ipc.send("updateApp");break;case"demoButton":cm.setValue(demo),calculate(),UIkit.modal("#dialog-help").hide()}})),$("dialog-open").addEventListener("click",(t=>{let e;const n=ls.get("saved");"load"===t.target.parentNode.getAttribute("data-action")&&(e=t.target.parentNode.parentNode.id,cm.setValue(n[e][1]),calculate(),UIkit.modal("#dialog-open").hide()),"delete"===t.target.getAttribute("data-action")&&(e=t.target.parentNode.id,confirm('Calculation "'+n[e][0]+'" will be deleted.',(()=>{delete n[e],ls.set("saved",n),populateSaved()})))})),UIkit.util.on("#dialog-open","beforeshow",populateSaved),UIkit.util.on("#setswitch","beforeshow",(t=>{t.stopPropagation()})),UIkit.util.on("#dialog-settings","beforeshow",prepSettings),UIkit.util.on("#dialog-settings","hidden",(()=>{cm.focus()})),$("numericOutput").addEventListener("change",bigNumberWarning),$("precisionRange").addEventListener("input",(()=>{$("precision-label").innerHTML=$("precisionRange").value})),document.querySelectorAll(".settingItem").forEach((t=>{t.addEventListener("change",saveSettings)})),$("searchBox").addEventListener("input",(()=>{const t=$("searchBox").value.trim();if(t)try{$("searchResults").innerHTML="";const e=JSON.stringify(math.help(t).toJSON()),n=JSON.parse(e);$("searchResults").innerHTML=`\n        <div>Name:</div><div>${n.name}</div>\n        <div>Description:</div><div>${n.description}</div>\n        <div>Category:</div><div>${n.category}</div>\n        <div>Syntax:</div><div>${String(n.syntax).split(",").join(", ")}</div>\n        <div>Examples:</div><div>${String(n.examples).split(",").join(", ")}</div>\n        <div>Also see:</div><div>${String(n.seealso).split(",").join(", ")}</div>\n        `}catch(e){$("searchResults").innerHTML=`No results for "${t}"`}else $("searchResults").innerHTML="Start typing above to search..."}));let isResizing=!1;const panel=$("panel"),divider=$("divider");function resetDivider(){settings.inputWidth=defaultSettings.inputWidth,ls.set("settings",settings),applySettings()}let func,activePlot;$("divider").addEventListener("dblclick",resetDivider),$("divider").addEventListener("mousedown",(t=>{isResizing=t.target===divider})),$("panel").addEventListener("mouseup",(()=>{isResizing=!1})),$("panel").addEventListener("mousemove",(t=>{const e=settings.app.lineNumbers?12:27,n=(t.clientX-panel.offsetLeft-e)/panel.clientWidth*100,i=n<0?0:n>100?100:n;isResizing&&($("input").style.width=i+"%",settings.inputWidth=i,ls.set("settings",settings),clearTimeout(resizeDelay),resizeDelay=setTimeout(calculate,10))}));const numaraPlot=window.functionPlot;function plot(){$("plotTitle").innerHTML=func;const t=func.split("=")[1];let e=2*math.abs(math.evaluate(t,{x:0}));e!==1/0&&0!==e||(e=10);const n=activePlot?activePlot.meta.xScale.domain():[-e,e],i=activePlot?activePlot.meta.yScale.domain():[-e,e];activePlot=numaraPlot({target:"#plot",height:$("plot").clientHeight,width:$("plot").clientWidth,xAxis:{domain:n},yAxis:{domain:i},tip:{xLine:settings.plot.plotCross,yLine:settings.plot.plotCross},grid:settings.plot.plotGrid,data:[{fn:t,graphType:"polyline",closed:settings.plot.plotArea}],plugins:[numaraPlot.plugins.zoomBox()]})}let windowResizeDelay;function confirm(t,e){$("confirmMsg").innerHTML=t,showModal("#dialog-confirm");const n=t=>{e(),t.stopPropagation(),UIkit.modal("#dialog-confirm").hide(),$("confirm-yes").removeEventListener("click",n)};$("confirm-yes").addEventListener("click",n),UIkit.util.on("#dialog-confirm","hidden",(()=>{$("confirm-yes").removeEventListener("click",n)}))}function showError(t,e){UIkit.util.on("#dialog-error","beforeshow",(()=>{$("errTitle").innerHTML=e||"Error",$("errMsg").innerHTML=t})),showModal("#dialog-error")}function notify(t,e){UIkit.notification({message:t,status:e||"primary",pos:"bottom-center",timeout:3e3})}UIkit.util.on("#dialog-plot","shown",plot),UIkit.util.on("#dialog-plot","hide",(()=>{activePlot=!1})),window.addEventListener("resize",(()=>{activePlot&&$("dialog-plot").classList.contains("uk-open")&&plot(),clearTimeout(windowResizeDelay),windowResizeDelay=setTimeout(calculate,10),checkWindowSize()}));let inputScroll=!1,outputScroll=!1;const leftSide=document.getElementsByClassName("CodeMirror-scroll")[0],rightSide=$("output");leftSide.addEventListener("scroll",(()=>{inputScroll||(outputScroll=!0,rightSide.scrollTop=leftSide.scrollTop),inputScroll=!1})),rightSide.addEventListener("scroll",(()=>{outputScroll||(inputScroll=!0,leftSide.scrollTop=rightSide.scrollTop),outputScroll=!1,$("scrollTop").style.display=$("output").scrollTop>50?"block":"none"})),$("scrollTop").addEventListener("click",(()=>{$("output").scrollTop=0}));const traps={clearButton:["command+d","ctrl+d"],printButton:["command+p","ctrl+p"],saveButton:["command+s","ctrl+s"],openButton:["command+o","ctrl+o"]};Object.entries(traps).forEach((([t,e])=>{Mousetrap.bindGlobal(e,(e=>{e.preventDefault(),0===document.getElementsByClassName("uk-open").length&&$(t).click()}))})),isNode&&(ipc.send("checkUpdate"),ipc.on("notifyUpdate",(t=>{notify('Updating Numara to latest version... <a class="updateLink" onclick="$(`aboutButton`).click()">View update status</a>'),$("notificationDot").style.display="block"})),ipc.on("updateStatus",((t,e)=>{"ready"===e?($("dialog-about-updateStatus").innerHTML="Restart Numara to finish updating.",$("restartButton").style.display="inline-block",$("dialog-about").classList.contains("uk-open")||notify('Restart Numara to finish updating. <a class="updateLink" onclick="$(`restartButton`).click()">Restart Now</a>')):$("dialog-about-updateStatus").innerHTML=e})));const demo="1+2\n\n# In addition to mathjs functions, you can do:\nans // Get last answer\ntotal // Total up to this point\navg // Average up to this point\nline4 // Get answer from a line#\nsubtotal // Subtotal last block\n\n# Percentages:\n10% of 20\n40 + 30%\n\n# Dates\ntoday\nnow\ntoday - 3 weeks\nnow + 36 hours - 2 days\n\n# Currency conversion\n1 usd to try\n20 cad to usd\n\n# Plot functions\nf(x) = sin(x)\nf(x) = 2x^2 + 3x - 5\n";window.addEventListener("load",(()=>{setTimeout((()=>{document.getElementsByClassName("CodeMirror-code")[0].lastChild.scrollIntoView()}),250),setTimeout((()=>{cm.focus()}),500)}));