From 950d05d1966dff77df2c14004aa1345a353f8449 Mon Sep 17 00:00:00 2001 From: chromoxdor <33860956+chromoxdor@users.noreply.github.com> Date: Sun, 27 Jul 2025 20:25:38 +0200 Subject: [PATCH] as good as it gets :) - support for chrome, vivaldi and firefox on android (hopefully) --- static/espeasy.js | 187 +++++++++++++++++++++++++++--------------- static/espeasy.min.js | 2 +- 2 files changed, 122 insertions(+), 67 deletions(-) diff --git a/static/espeasy.js b/static/espeasy.js index 7d5117924..e738499e5 100644 --- a/static/espeasy.js +++ b/static/espeasy.js @@ -204,7 +204,7 @@ var android = /Android/.test(navigator.userAgent); function initCM() { if (android) { - if (confirm("Do you want to enable colored rules? (There are some issues with the standard Android Keyboard causing it to fail!)")) { + if (confirm("Do you want to enable colored rules?\n(There are some issues with Android causing it to fail!)\nTestet with Chrome, Firefox and Vivaldi so far.\nPlease report any issues you may have with this feature.")) { confirmR = true } else { confirmR = false @@ -375,22 +375,25 @@ function addFindButtons() { // Add Searchfield button document.addEventListener('DOMContentLoaded', () => { const form = document.getElementById('rulesselect'); + if (form) { - // Add search help button to CodeMirror editor - const btn3 = document.createElement('button'); - btn3.type = 'button'; // prevent form submission - btn3.id = 'searchBtn'; - btn3.innerHTML = "🔎︎"; // magnifier - btn3.style.padding = "2px 5px"; - btn3.className = 'button help'; // just the class, no inline style - form.appendChild(btn3); + if (confirmR) { + // Add search help button to CodeMirror editor + const btn3 = document.createElement('button'); + btn3.type = 'button'; // prevent form submission + btn3.id = 'searchBtn'; + btn3.innerHTML = "🔎︎"; // magnifier + btn3.style.padding = "2px 5px"; + btn3.className = 'button help'; // just the class, no inline style + form.appendChild(btn3); - btn3.addEventListener('click', () => { - if (typeof rEdit !== 'undefined') { - openFind(); - } - }); + btn3.addEventListener('click', () => { + if (typeof rEdit !== 'undefined') { + openFind(); + } + }); + } // Add format document button const btn = document.createElement('button'); @@ -460,83 +463,135 @@ document.addEventListener('DOMContentLoaded', () => { // Workaround of showing hints for Android devices if (android) { - document.addEventListener("input", (e) => { - if (!rEdit || !e.data || e.data.length !== 1) { + var wasKeydown = false; // Flag to track if keydown was triggered + + // Works on Android for some keys + rEdit.on("keydown", (cm, e) => { + if (["Enter", "Backspace", " "].includes(e.key)) { charBuffer = ""; + //alert("Buffer cleared via keydown:", e.key); + } + //alert("Keydown event detected: " + e.key); + wasKeydown = true; + }); + let lastCharBuffer = ""; + + const inputField = rEdit.getInputField(); + + function handleTypedChar(e, isBeforeInput = false) { + if (!rEdit.hasFocus() || !rEdit || !e.data || !wasKeydown) return; + wasKeydown = false; + const data = e.data; + const doc = rEdit.getDoc(); + const cursor = doc.getCursor(); // AFTER inserted char + const letters = /[\w%,.]/; + const token = rEdit.getTokenAt(cursor); + + // Reset on space + if (data === ' ') { + console.log("Clearing buffer due to space"); + charBuffer = ""; + lastCharBuffer = ""; return; } - const data = e.data; - const doc = rEdit.getDoc(); - let cursor = doc.getCursor(); // Cursor is AFTER inserted char + // Ignore unchanged input + if (data === lastCharBuffer && charBuffer.length > 0) return; - const letters = /[\w%,.]/; - const token = rEdit.getTokenAt(cursor); if (letters.test(data) && token.type !== "comment") { - charBuffer += data; - // Calculate starting point for re-inserting + const lastChar = cursor.ch <= 1 ? data.slice(-1) : data; + charBuffer += lastChar; + lastCharBuffer = charBuffer; + + // Remove line number bleed-in + if (charBuffer.startsWith(String(cursor.line + 1)) && cursor.ch === 0) { + charBuffer = charBuffer.slice(String(cursor.line).length); + } + + console.log("Buffer updated:", charBuffer); + const insertPos = { line: cursor.line, ch: cursor.ch - charBuffer.length + 1 }; - // Replace from where the buffer began to current position - doc.replaceRange(charBuffer, insertPos, cursor); + const insertAndHint = () => { + doc.replaceRange(charBuffer, insertPos, cursor); + rEdit.setCursor({ + line: insertPos.line, + ch: insertPos.ch + charBuffer.length + }); + rEdit.showHint({ completeSingle: false }); + }; - // Set cursor at end of buffer - rEdit.setCursor({ - line: insertPos.line, - ch: insertPos.ch + charBuffer.length - }); + // For `input`, delay slightly to avoid race with native insert + if (!isBeforeInput) { + setTimeout(insertAndHint, 0); + } else { + insertAndHint(); + } - // Show hints - rEdit.showHint({ completeSingle: false }); - } else if (!letters.test(data)) { - // Reset buffer on non-matching input (e.g., space, enter, etc.) + } else { charBuffer = ""; } - }); + } + const ua = navigator.userAgent.toLowerCase(); + const isFirefox = /firefox/.test(ua); + const isChrome = /chrome/.test(ua) && !isFirefox; + // Firefox (Android) – beforeinput preferred + if (isFirefox) { + inputField.addEventListener("beforeinput", (e) => { + e.preventDefault(); + handleTypedChar(e, true); + }); + } else if (isChrome) { + document.addEventListener("input", (e) => { + handleTypedChar(e, false); + }); + } rEdit.on('endCompletion', function () { setTimeout(() => { - rEdit.focus(); - }, 10); // small delay may help + forceKeyboardOpen(); + }, 100); // small delay may help }); - - function forceKeyboardOpen() { - const input = document.createElement("input"); - input.type = "text"; - input.style.position = "absolute"; - input.style.opacity = "0"; - input.style.height = "0"; - input.style.width = "0"; - input.style.border = "none"; - input.style.top = "0"; - input.style.left = "-9999"; - input.style.padding = "0"; - input.style.zIndex = "-1"; - input.style.fontSize = "16px"; // prevents zoom on iOS - - document.body.appendChild(input); - input.focus(); - - setTimeout(() => { - input.remove(); - rEdit.focus(); // bring focus back to CodeMirror - }, 10); - } } + + function forceKeyboardOpen() { + const input = document.createElement("input"); + input.type = "text"; + input.style.position = "absolute"; + input.style.opacity = "0"; + input.style.height = "0"; + input.style.width = "0"; + input.style.border = "none"; + input.style.top = "0"; + input.style.left = "-9999"; + input.style.padding = "0"; + input.style.zIndex = "-1"; + input.style.fontSize = "16px"; // prevents zoom on iOS + + document.body.appendChild(input); + input.focus(); + + setTimeout(() => { + input.remove(); + rEdit.focus(); // bring focus back to CodeMirror + }, 10); + } + }); function triggerFormatting() { - const doc = rEdit.getDoc(); - const scrollInfo = rEdit.getScrollInfo(); - const cursor = doc.getCursor(); - - const currentLine = cursor.ch === 0 ? cursor.line - 1 : cursor.line; - const lineText = rEdit.getLine(currentLine) || ""; + if (confirmR) { + const doc = rEdit.getDoc(); + const scrollInfo = rEdit.getScrollInfo(); + const cursor = doc.getCursor(); + const currentLine = cursor.ch === 0 ? cursor.line - 1 : cursor.line; + const lineText = rEdit.getLine(currentLine) || ""; + } // Store initial text let textarea = confirmR ? rEdit.getValue() diff --git a/static/espeasy.min.js b/static/espeasy.min.js index a7afa091f..b34b46775 100644 --- a/static/espeasy.min.js +++ b/static/espeasy.min.js @@ -1 +1 @@ -var commonAtoms=["And","Or"],commonKeywords=["If","Else","Elseif","Endif"],commonCommands=["AccessInfo","Background","Build","ClearAccessBlock","ClearRTCam","Config","ControllerDisable","ControllerEnable","DateTime","Debug","Dec","DeepSleep","DisablePriorityTask","DNS","DST","EraseSDKWiFi","ExecuteRules","FactoryReset","Gateway","I2Cscanner","Inc","IP","Let","LetStr","Load","LogEntry","LogPortStatus","LoopTimerSet","LoopTimerSet_ms","LoopTimerSetAndRun","LoopTimerSetAndRun_ms","MemInfo","MemInfoDetail","Name","Password","PostToHTTP","Publish","PublishR","Reboot","Save","SendTo","SendToHTTP","SendToUDP","SendToUDPMix","Settings","Subnet","Subscribe","TaskClear","TaskClearAll","TaskDisable","TaskEnable","TaskRun","TaskValueSet","TaskValueSetAndRun","TaskValueSetDerived","TaskValueSetPresentation","TimerPause","TimerResume","TimerSet","TimerSet_ms","TimeZone","UdpPort","UdpTest","Unit","UseNTP","WdConfig","WdRead","WiFi","WiFiAllowAP","WiFiAPMode","WiFiConnect","WiFiDisconnect","WiFiKey","WiFiKey2","WiFiMode","WiFiScan","WiFiSSID","WiFiSSID2","WiFiSTAMode","Event","AsyncEvent","GPIO","GPIOToggle","LongPulse","LongPulse_mS","Monitor","Pulse","PWM","Servo","Status","Tone","RTTTL","UnMonitor","Provision","Provision,Config","Provision,Security","Provision,Notification","Provision,Provision","Provision,Rules","Provision,CustomCdnUrl","Provision,Firmware"],commonEvents=["Clock#Time","Login#Failed","MQTT#Connected","MQTT#Disconnected","MQTTimport#Connected","MQTTimport#Disconnected","Rules#Timer","System#Boot","System#BootMode","System#Sleep","System#Wake","TaskExit#","TaskInit#","ThingspeakReply","Time#Initialized","Time#Set","WiFi#APmodeDisabled","WiFi#APmodeEnabled","WiFi#ChangedAccesspoint","WiFi#ChangedWiFichannel","WiFi#Connected","WiFi#Disconnected"],commonPlugins=["ResetPulseCounter","SetPulseCounterTotal","LogPulseStatistic","analogout","MCPGPIO","MCPGPIOToggle","MCPLongPulse","MCPLongPulse_ms","MCPPulse","Status,MCP","Monitor,MCP","MonitorRange,MCP","UnMonitorRange,MCP","UnMonitor,MCP","MCPGPIORange","MCPGPIOPattern","MCPMode","MCPModeRange","ExtGpio","ExtPwm","ExtPulse","ExtLongPulse","Status,EXT,","LCDCmd","LCD","PCFGPIO","PCFGPIOToggle","PCFLongPulse","PCFLongPulse_ms","PCFPulse","Status,PCF","Monitor,PCF","MonitorRange,PCF","UnMonitorRange,PCF","UnMonitor,PCF","PCFGPIORange","PCFGPIOpattern","PCFMode","PCFmodeRange","SerialSend","SerialSendMix","Ser2NetClientSend","SerialSend_test","pcapwm","pcafrq","mode2","OLED","OLEDCMD","OLEDCMD,on","OLEDCMD,off","OLEDCMD,clear","IRSEND","IRSENDAC","OledFramedCmd","OledFramedCmd,Display","OledFramedCmd,low","OledFramedCmd,med","OledFramedCmd,high","OledFramedCmd,Frame","OledFramedCmd,linecount","OledFramedCmd,leftalign","OledFramedCmd,align","OledFramedCmd,userDef1","OledFramedCmd,userDef2","NeoPixel","NeoPixelAll","NeoPixelLine","NeoPixelHSV","NeoPixelAllHSV","NeoPixelLineHSV","NeoPixelBright","MotorShieldCmd,DCMotor","MotorShieldCmd,Stepper","MHZCalibrateZero","MHZReset","MHZABCEnable","MHZABCDisable","Sensair_SetRelay","PMSX003","PMSX003,Wake","PMSX003,Sleep","PMSX003,Reset","encwrite","Play","Vol","Eq","Mode","Repeat","tareChanA","tareChanB","7dn","7dst","7dsd","7dtext","7ddt","7dt","7dtfont","7dtbin","7don","7doff","7output","HLWCalibrate","HLWReset","csecalibrate","cseclearpulses","csereset","WemosMotorShieldCMD","LolinMotorShieldCMD","GPS","GPS,Sleep","GPS,Wake","GPS#GotFix","GPS#LostFix","GPS#Travelled","homieValueSet","SerialProxy_Write","SerialProxy_WriteMix","SerialProxy_Test","HeatPumpir","MitsubishiHP","MitsubishiHP,temperature","MitsubishiHP,power","MitsubishiHP,mode","MitsubishiHP,fan","MitsubishiHP,vane","MitsubishiHP,widevane","Culreader_Write","Touch","Touch,Rot","Touch,Flip","Touch,Enable","Touch,Disable","Touch,On","Touch,Off","Touch,Toggle","Touch,Setgrp","Touch,Incgrp","Touch,Decgrp","Touch,Incpage","Touch,Decpage","Touch,Updatebutton","WakeOnLan","DotMatrix","DotMatrix,clear","DotMatrix,update","DotMatrix,size","DotMatrix,txt","DotMatrix,settxt","DotMatrix,content","DotMatrix,alignment","DotMatrix,anim.in","DotMatrix,anim.out","DotMatrix,speed","DotMatrix,pause","DotMatrix,font","DotMatrix,layout","DotMatrix,inverted","DotMatrix,specialeffect","DotMatrix,offset","DotMatrix,brightness","DotMatrix,repeat","DotMatrix,setbar","DotMatrix,bar","Thermo","Thermo,Up","Thermo,Down","Thermo,Mode","Thermo,ModeBtn","Thermo,Setpoint","Max1704xclearalert","scdgetabc","scdgetalt","scdgettmp","scdsetcalibration","scdsetfrc","scdgetinterval","multirelay","multirelay,on","multirelay,off","multirelay,set","multirelay,get","multirelay,loop","ShiftOut","ShiftOut,Set","ShiftOut,SetNoUpdate","ShiftOut,Update","ShiftOut,SetAll","ShiftOut,SetAllNoUpdate","ShiftOut,SetAllLow","ShiftOut,SetAllHigh","ShiftOut,SetChipCount","ShiftOut,SetHexBin","cdmrst","nfx","nfx,off","nfx,on","nfx,dim","nfx,line,","nfx,hsvline,","nfx,one,","nfx,hsvone,","nfx,all,","nfx,rgb,","nfx,fade,","nfx,hsv,","nfx,colorfade,","nfx,rainbow","nfx,kitt,","nfx,comet,","nfx,theatre,","nfx,scan,","nfx,dualscan,","nfx,twinkle,","nfx,twinklefade,","nfx,sparkle,","nfx,wipe,","nfx,dualwipe","nfx,fire","nfx,fireflicker","nfx,faketv","nfx,simpleclock","nfx,stop","nfx,statusrequest","nfx,fadetime,","nfx,fadedelay,","nfx,speed,","nfx,count,","nfx,bgcolor","ShiftIn","ShiftIn,PinEvent","ShiftIn,ChipEvent","ShiftIn,SetChipCount","ShiftIn,SampleFrequency","ShiftIn,EventPerPin","scd4x","scd4x,storesettings","scd4x,facoryreset","scd4x,selftest","scd4x,setfrc,","axp","axp,ldo2","axp,ldo3","axp,ldoio","axp,gpio0","axp,gpio1","axp,gpio2","axp,gpio3","axp,gpio4","axp,dcdc2","axp,dcdc3","axp,ldo2map","axp,ldo3map","axp,ldoiomap","axp,dcdc2map","axp,dcdc3map","axp,ldo2perc","axp,ldo3perc","axp,ldoioperc","axp,dcdc2perc","axp,dcdc3perc","I2CEncoder","I2CEncoder,bright","I2CEncoder,led1","I2CEncoder,led2","I2CEncoder,gain","I2CEncoder,set","cachereader","cachereader,readpos","cachereader,sendtaskinfo","cachereader,flush","tm1621","tm1621,write,","tm1621,writerow,","tm1621,voltamp,","tm1621,energy,","tm1621,celcius,","tm1621,fahrenheit,","tm1621,humidity,","tm1621,raw,","dac","dac,1","dac,2","sht4x","sht4x,startup","ld2410","ld2410,factoryreset","ld2410,logall","digipot","digipot,reset","digipot,shutdown","digipot,","7dextra","7dbefore","7dgroup","7digit","7color","7digitcolor","7groupcolor","gp8403","gp8403,volt,","gp8403,mvolt,","gp8403,range,","gp8403,preset,","gp8403,init,","sen5x","sen5x,startclean","sen5x,techlog,","as3935","as3935,clearstats","as3935,calibrate","as3935,setgain,","as3935,setnf,","as3935,setwd,","as3925,setsrej,","lu9685","lu9685,servo,","lu9685,enable,","lu9685,disable,","lu9685,setrange,","geni2c","geni2c,cmd,","geni2c,exec,","geni2c,log,"],pluginDispKind=["tft","ili9341","ili9342","ili9481","ili9486","ili9488","epd","eink","epaper","il3897","uc8151d","ssd1680","ws2in7","ws1in54","st77xx","st7735","st7789","st7796","neomatrix","neo","pcd8544"],pluginDispCmd=["cmd,on","cmd,off","cmd,clear","cmd,backlight","cmd,bright","cmd,deepsleep","cmd,seq_start","cmd,seq_end","cmd,inv","cmd,rot",",clear",",rot",",tpm",",txt",",txp",",txz",",txc",",txs",",txtfull",",asciitable",",font",",l",",lh",",lv",",lm",",lmr",",r",",rf",",c",",cf",",rf",",t",",tf",",rr",",rrf",",px",",pxh",",pxv",",bmp",",btn",",win",",defwin",",delwin"],commonTag=["On","Do","Endon"],commonNumber=["toBin","toHex","Constrain","XOR","AND:","OR:","Ord","bitRead","bitSet","bitClear","bitWrite","urlencode"],commonMath=["Log","Ln","Abs","Exp","Sqrt","Sq","Round","Sin","Cos","Tan","aSin","aCos","aTan","Sin_d","Cos_d","Tan_d","aSin_d","aCos_d","aTan_d","map","mapc"],commonWarning=["delay","Delay","ResetFlashWriteCounter"],taskSpecifics=["settings.Enabled","settings.Interval","settings.ValueCount","settings.Controller1.Enabled","settings.Controller2.Enabled","settings.Controller3.Enabled","settings.Controller1.Idx","settings.Controller2.Idx","settings.Controller3.Idx"],AnythingElse=["%eventvalue%","%eventpar%","%eventname%","%sysname%","%bootcause%","%systime%","%systm_hm%","%systm_hm_0%","%systm_hm_sp%","%systime_am%","%systime_am_0%","%systime_am_sp%","%systm_hm_am%","%systm_hm_am_0%","%systm_hm_am_sp%","%lcltime%","%sunrise%","%s_sunrise%","%m_sunrise%","%sunset%","%s_sunset%","%m_sunset%","%lcltime_am%","%syshour%","%syshour_0%","%sysmin%","%sysmin_0%","%syssec%","%syssec_0%","%sysday%","%sysday_0%","%sysmonth%","%sysmonth_0%","%systzoffset%","%systzoffset_s%","%sysyear%","%sysyear_0%","%sysyears%","%sysweekday%","%sysweekday_s%","%unixtime%","%unixtime_lcl%","%uptime%","%uptime_ms%","%rssi%","%ip%","%unit%","%unit_0%","%ssid%","%bssid%","%wi_ch%","%iswifi%","%vcc%","%mac%","%mac_int%","%isntp%","%ismqtt%","%dns%","%dns1%","%dns2%","%flash_freq%","%flash_size%","%flash_chip_vendor%","%flash_chip_model%","%fs_free%","%fs_size%","%cpu_id%","%cpu_freq%","%cpu_model%","%cpu_rev%","%cpu_cores%","%board_name%","%inttemp%","%islimited_build%","%isvar_double%","substring","lookup","indexOf","indexOf_ci","equals","equals_ci","strtol","timeToMin","timeToSec","%ethwifimode%","%ethconnected%","%ethduplex%","%ethspeed%","%ethstate%","%ethspeedstate%","%c_w_dir%","%c_c2f%","%c_ms2Bft%","%c_dew_th%","%c_alt_pres_sea%","%c_sea_pres_alt%","%c_cm2imp%","%c_isnum%","%c_mm2imp%","%c_m2day%","%c_m2dh%","%c_m2dhm%","%c_s2dhms%","%c_ts2date%","%c_ts2wday%","%c_random%","%c_2hex%","%c_u2ip%","%c_uname%","%c_uage%","%c_ubuild%","%c_ubuildstr%","%c_uload%","%c_utype%","%c_utypestr%","%c_strf%","var","int","str","length"];for(const e of pluginDispKind)commonPlugins=commonPlugins.concat(e);for(const e of pluginDispKind)for(const t of pluginDispCmd){let n=e+t;commonPlugins=commonPlugins.concat(n)}var rEdit,EXTRAWORDS=commonAtoms.concat(commonPlugins,commonKeywords,commonCommands,commonEvents,commonTag,commonNumber,commonMath,commonWarning,taskSpecifics,AnythingElse),confirmR=!0,android=/Android/.test(navigator.userAgent);function initCM(){android&&(confirmR=!!confirm("Do you want to enable colored rules? (There are some issues with the standard Android Keyboard causing it to fail!)")),confirmR&&(CodeMirror.commands.autocomplete=function(e){e.showHint({hint:CodeMirror.hint.anyword})},(rEdit=CodeMirror.fromTextArea(document.getElementById("rules"),{tabSize:2,indentWithTabs:!1,lineNumbers:!0,autoCloseBrackets:!0,extraKeys:{"Ctrl-Space":"autocomplete",Tab:e=>{"null"===e.getMode().name?e.execCommand("insertTab"):e.somethingSelected()?e.execCommand("indentMore"):e.execCommand("insertSoftTab")},"Shift-Tab":e=>e.execCommand("indentLess")}})).on("change",(function(){rEdit.save()})),android||rEdit.on("inputRead",(function(e,t){var n=e.getCursor(),o=e.getTokenAt(n);/[\w%,.]/.test(t.text)&&"comment"!=o.type&&e.showHint({completeSingle:!1})})),CodeMirror.keyMap.default["Ctrl-F"]=function(e){openFind()},CodeMirror.keyMap.default["Cmd-F"]=function(e){openFind()})}function closeSearchDialog(){const e=document.querySelectorAll(".CodeMirror-dialog");e.length>0&&(e.forEach((e=>e.remove())),document.body.classList.remove("dialog-opened")),rEdit.execCommand("clearSearch")}function removeHighlight(){requestAnimationFrame((()=>{document.querySelectorAll(".search-next-highlight").forEach((e=>e.classList.remove("search-next-highlight")))}))}let findDialogObserver=null;function openFind(){findDialogObserver&&(findDialogObserver.disconnect(),findDialogObserver=null),findDialogObserver=new MutationObserver((()=>{document.querySelector(".CodeMirror-dialog")||(removeHighlight(),findDialogObserver.disconnect(),findDialogObserver=null)})),findDialogObserver.observe(document.body,{childList:!0,subtree:!0}),clearSearchNextHighlight(rEdit),rEdit.execCommand("findPersistent"),addFindButtons()}function clearSearchNextHighlight(e){removeHighlight(),e.__searchNextHighlight&&(e.__searchNextHighlight.clear(),e.__searchNextHighlight=null)}function addFindButtons(){document.querySelector(".CodeMirror-selected");const e=document.querySelector(".CodeMirror-dialog");if(!e||e.querySelector(".search-button-group"))return;[{title:"Find Previous",symbol:"▲",action:()=>rEdit.execCommand("findPersistentPrev")},{title:"Find Next",symbol:"▼",action:()=>rEdit.execCommand("findPersistentNext")},{title:"Replace",symbol:"Replace",action:()=>{closeSearchDialog(),rEdit.execCommand("replace"),addFindButtons()}},{title:"Close",symbol:"❌",action:closeSearchDialog},{title:"Help",symbol:"?",action:()=>{alert("Available shortcuts:\n• Ctrl+F / Cmd+F: Open search\n• Ctrl+G / Cmd+G: Find next\n• Shift+Ctrl+G / Shift+Cmd+G: Find previous\n• Shift+Ctrl+F / Cmd+Option+F: Replace\n• Shift+Ctrl+R / Shift+Cmd+Option+F: Replace all\n• Use /re/ syntax for regexp search")}}].forEach((({title:t,symbol:n,action:o})=>{const i=document.createElement("span");i.title=t,i.className="help"===t.toLowerCase()?"button help":"button",i.innerHTML=n,i.style.cssText="\n cursor: pointer;\n user-select: none;\n ",i.addEventListener("click",(e=>{e.preventDefault(),o()})),e.appendChild(i)}))}function triggerFormatting(){const e=rEdit.getDoc(),t=rEdit.getScrollInfo(),n=e.getCursor(),o=0===n.ch?n.line-1:n.line,i=rEdit.getLine(o)||"";let r=confirmR?rEdit.getValue():document.getElementById("rules").value;if(r=initalAutocorrection(r),r=formatLogic(r),confirmR){rEdit.setValue(r);const e=o,s=0===n.ch&&i.length>0?i.length:n.ch-1;rEdit.setCursor({line:e,ch:s}),rEdit.scrollTo(t.left,t.top),rEdit.focus(),rEdit.save()}else document.getElementById("rules").value=r}function initalAutocorrection(e){for(const t of EXTRAWORDS)if("Do"===t){const t=/(^|\s)(do)(\s*)(\/\/.*)?$/gim;e=e.replace(t,((e,t,n,o,i)=>`${t}Do${o}${i??""}`))}else{const n=new RegExp(`^\\s*\\b${t}\\b`,"gmi");e=e.replace(n,(e=>e.replace(new RegExp(t,"i"),t)))}return e}function formatLogic(e){const t=" ",n=e.split("\n").map((e=>{const t=e.trimStart();return t.startsWith("//")?e:t})),o=[],i=[];let r=!1,s=null,a=[],c=[];function l(e){return e.trim().startsWith("//")}function d(e){return""===e.trim()}function m(e){return e.trim().toLowerCase().startsWith("on")}function u(e){return e.trim().toLowerCase().endsWith("do")}function f(e){return"endon"===e.trim().toLowerCase()}function h(e){return e.trim().toLowerCase().startsWith("if")}function p(e){return"else"===e.trim().toLowerCase()}function g(e){return e.trim().toLowerCase().startsWith("elseif")}function x(e){return"endif"===e.trim().toLowerCase()}let C=0;function S(){a.length>0&&(i.push(`• Missing ${a.length} Endif(s):`),i.push(` - Unclosed If block(s) starting at line(s): ${c.join(", ")}`)),a=[],c=[]}for(let e=0;e0){const e=extractFirstErrorLine(i);if(alert("Errors found:\n"+i.join("\n")),!isNaN(e))if(confirmR)setTimeout((()=>{jumpToLine(e)}),50);else{const t=document.getElementById("rules");setTimeout((()=>{jumpToLineInTextarea(t,e)}),50)}}return o.join("\n")}function jumpToLine(e){const t=Math.max(0,e-1);rEdit.setCursor({line:t,ch:0}),rEdit.focus(),rEdit.scrollIntoView({line:t,ch:0},100)}function extractFirstErrorLine(e){for(const t of e){let e=t.match(/• Line (\d+)/);if(e)return parseInt(e[1]);if(e=t.match(/starting at line (\d+)/),e)return parseInt(e[1]);if(e=t.match(/starting at line\(s\):\s*(\d+)/),e)return parseInt(e[1])}return null}function jumpToLineInTextarea(e,t){const n=e.value.split("\n"),o=Math.max(1,Math.min(t,n.length));let i=0;for(let e=0;e{const e=document.getElementById("rulesselect");if(e){const t=document.createElement("button");t.type="button",t.id="searchBtn",t.innerHTML="🔎︎",t.style.padding="2px 5px",t.className="button help",e.appendChild(t),t.addEventListener("click",(()=>{void 0!==rEdit&&openFind()}));const n=document.createElement("button");n.type="button",n.id="formatBtn",n.textContent="Format",n.className="button",e.appendChild(n),n.addEventListener("click",(()=>{triggerFormatting()}))}let t="";if(document.addEventListener("keydown",(function(e){const n=e.key;if(e.ctrlKey&&e.shiftKey&&"f"===n.toLowerCase())return e.preventDefault(),void triggerFormatting();(["Backspace","Delete","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter","Tab","Escape","Shift","Control","Alt","Meta"].includes(n)||1!==n.length)&&(t="")})),android){document.addEventListener("input",(e=>{if(!rEdit||!e.data||1!==e.data.length)return void(t="");const n=e.data,o=rEdit.getDoc();let i=o.getCursor();const r=/[\w%,.]/,s=rEdit.getTokenAt(i);if(r.test(n)&&"comment"!==s.type){t+=n;const e={line:i.line,ch:i.ch-t.length+1};o.replaceRange(t,e,i),rEdit.setCursor({line:e.line,ch:e.ch+t.length}),rEdit.showHint({completeSingle:!1})}else r.test(n)||(t="")})),rEdit.on("endCompletion",(function(){setTimeout((()=>{rEdit.focus()}),10)}))}})),function(e){"object"==typeof exports&&"object"==typeof module?e(require("codemirror")):"function"==typeof define&&define.amd?define(["codemirror"],e):e(CodeMirror)}((function(e){"use strict";e.defineMode("espeasy",(function(){var e={};function t(t,n){for(var o=0;oe.toLowerCase()));commonCommands=commonCommands.concat(n);var o=commonEvents.map((e=>e.toLowerCase()));commonEvents=commonEvents.concat(o);var i=commonPlugins.map((e=>e.toLowerCase()));commonPlugins=commonPlugins.concat(i);var r=commonAtoms.map((e=>e.toLowerCase()));commonAtoms=commonAtoms.concat(r);var s=commonKeywords.map((e=>e.toLowerCase()));commonKeywords=commonKeywords.concat(s);var a=commonTag.map((e=>e.toLowerCase()));commonTag=commonTag.concat(a);var c=commonNumber.map((e=>e.toLowerCase()));commonNumber=commonNumber.concat(c);var l=commonMath.map((e=>e.toLowerCase()));commonMath=commonMath.concat(l);var d=AnythingElse.map((e=>e.toLowerCase()));AnythingElse=AnythingElse.concat(d);var m=taskSpecifics.map((e=>e.toLowerCase()));function u(t,n){if(t.eatSpace())return null;t.sol();var o=t.next();if(/\d/.test(o)){if("0"==o)return"x"===t.next()?(t.eatWhile(/\w/),"number"):(t.eatWhile(/\d|\./),"number");if(t.eatWhile(/\d|\./),!t.match("d")&&!t.match("output")&&(t.eol()||/\D/.test(t.peek())))return"number"}if(/\w/.test(o))for(const e of EXTRAWORDS){let n=e.substring(1);(e.includes(":")||e.includes(",")||e.includes("."))&&t.match(n)}if(/\w/.test(o)&&(t.eatWhile(/[\w]/),t.match(".gpio")||t.match(".pulse")||t.match(".frq")||t.match(".pwm")))return"def";if("\\"===o)return t.next(),null;if("("===o||")"===o)return"bracket";if("{"===o||"}"===o||":"===o)return"number";if("/"==o)return/\//.test(t.peek())?(t.skipToEnd(),"comment"):"operator";if("'"==o&&(t.eatWhile(/[^']/),t.match("'")))return"attribute";if("+"===o||"="===o||"<"===o||">"===o||"-"===o||","===o||"*"===o||"!"===o)return"operator";if("%"==o){if(/\d/.test(t.next()))return"number";if(t.eatWhile(/[^\s\%]/),t.match("%"))return"hr"}if("["==o&&(t.eatWhile(/[^\s\]]/),t.eat("]")))return"hr";t.eatWhile(/\w/);var i=t.current();return/\w/.test(o)&&t.match("#")?(t.eatWhile(/[\w.#]/),"events"):"#"===o?(t.eatWhile(/\w/),"number"):e.hasOwnProperty(i)?e[i]:null}function f(e,t){return(t.tokens[0]||u)(e,t)}return taskSpecifics=taskSpecifics.concat(m),t("atom",commonAtoms),t("keyword",commonKeywords),t("builtin",commonCommands),t("events",commonEvents),t("def",commonPlugins),t("tag",commonTag),t("number",commonNumber),t("bracket",commonMath),t("warning",commonWarning),t("hr",AnythingElse),t("comment",taskSpecifics),{startState:function(){return{tokens:[]}},token:function(e,t){return f(e,t)},closeBrackets:"[]{}''\"\"``()",lineComment:"//",fold:"brace"}}))})),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):e(CodeMirror)}((function(e){var t={pairs:"()[]{}''\"\"",closeBefore:")]}'\":;>",triples:"",explode:"[]{}"},n=e.Pos;function o(e,n){return"pairs"==n&&"string"==typeof e?e:"object"==typeof e&&null!=e[n]?e[n]:t[n]}e.defineOption("autoCloseBrackets",!1,(function(t,n,s){s&&s!=e.Init&&(t.removeKeyMap(i),t.state.closeBrackets=null),n&&(r(o(n,"pairs")),t.state.closeBrackets=n,t.addKeyMap(i))}));var i={Backspace:function(t){var i=a(t);if(!i||t.getOption("disableInput"))return e.Pass;for(var r=o(i,"pairs"),s=t.listSelections(),c=0;c=0;c--){var m=s[c].head;t.replaceRange("",n(m.line,m.ch-1),n(m.line,m.ch+1),"+delete")}},Enter:function(t){var n=a(t),i=n&&o(n,"explode");if(!i||t.getOption("disableInput"))return e.Pass;for(var r=t.listSelections(),s=0;s1&&h.indexOf(i)>=0&&t.getRange(n(P.line,P.ch-2),P)==i+i){if(P.ch>2&&/\bstring/.test(t.getTokenTypeAt(n(P.line,P.ch-2))))return e.Pass;S="addFour"}else if(p){var v=0==P.ch?" ":t.getRange(n(P.line,P.ch-1),P);if(e.isWordChar(y)||v==i||e.isWordChar(v))return e.Pass;S="both"}else{if(!x||!(0===y.length||/\s/.test(y)||f.indexOf(y)>-1))return e.Pass;S="both"}else S=p&&m(t,P)?"both":h.indexOf(i)>=0&&t.getRange(P,n(P.line,P.ch+3))==i+i+i?"skipThree":"skip";if(u){if(u!=S)return e.Pass}else u=S}var M=d%2?s.charAt(d-1):i,T=d%2?i:s.charAt(d+1);t.operation((function(){if("skip"==u)c(t,1);else if("skipThree"==u)c(t,3);else if("surround"==u){for(var e=t.getSelections(),n=0;n0?{line:s.head.line,ch:s.head.ch+t}:{line:s.head.line-1};n.push({anchor:a,head:a})}e.setSelections(n,i)}function l(t){var o=e.cmpPos(t.anchor,t.head)>0;return{anchor:new n(t.anchor.line,t.anchor.ch+(o?-1:1)),head:new n(t.head.line,t.head.ch+(o?1:-1))}}function d(e,t){var o=e.getRange(n(t.line,t.ch-1),n(t.line,t.ch+1));return 2==o.length?o:null}function m(e,t){var o=e.getTokenAt(n(t.line,t.ch+1));return/\bstring/.test(o.type)&&o.start==t.ch&&(0==t.ch||!/\bstring/.test(e.getTokenTypeAt(t)))}r(t.pairs+"`")})); \ No newline at end of file +var commonAtoms=["And","Or"],commonKeywords=["If","Else","Elseif","Endif"],commonCommands=["AccessInfo","Background","Build","ClearAccessBlock","ClearRTCam","Config","ControllerDisable","ControllerEnable","DateTime","Debug","Dec","DeepSleep","DisablePriorityTask","DNS","DST","EraseSDKWiFi","ExecuteRules","FactoryReset","Gateway","I2Cscanner","Inc","IP","Let","LetStr","Load","LogEntry","LogPortStatus","LoopTimerSet","LoopTimerSet_ms","LoopTimerSetAndRun","LoopTimerSetAndRun_ms","MemInfo","MemInfoDetail","Name","Password","PostToHTTP","Publish","PublishR","Reboot","Save","SendTo","SendToHTTP","SendToUDP","SendToUDPMix","Settings","Subnet","Subscribe","TaskClear","TaskClearAll","TaskDisable","TaskEnable","TaskRun","TaskValueSet","TaskValueSetAndRun","TaskValueSetDerived","TaskValueSetPresentation","TimerPause","TimerResume","TimerSet","TimerSet_ms","TimeZone","UdpPort","UdpTest","Unit","UseNTP","WdConfig","WdRead","WiFi","WiFiAllowAP","WiFiAPMode","WiFiConnect","WiFiDisconnect","WiFiKey","WiFiKey2","WiFiMode","WiFiScan","WiFiSSID","WiFiSSID2","WiFiSTAMode","Event","AsyncEvent","GPIO","GPIOToggle","LongPulse","LongPulse_mS","Monitor","Pulse","PWM","Servo","Status","Tone","RTTTL","UnMonitor","Provision","Provision,Config","Provision,Security","Provision,Notification","Provision,Provision","Provision,Rules","Provision,CustomCdnUrl","Provision,Firmware"],commonEvents=["Clock#Time","Login#Failed","MQTT#Connected","MQTT#Disconnected","MQTTimport#Connected","MQTTimport#Disconnected","Rules#Timer","System#Boot","System#BootMode","System#Sleep","System#Wake","TaskExit#","TaskInit#","ThingspeakReply","Time#Initialized","Time#Set","WiFi#APmodeDisabled","WiFi#APmodeEnabled","WiFi#ChangedAccesspoint","WiFi#ChangedWiFichannel","WiFi#Connected","WiFi#Disconnected"],commonPlugins=["ResetPulseCounter","SetPulseCounterTotal","LogPulseStatistic","analogout","MCPGPIO","MCPGPIOToggle","MCPLongPulse","MCPLongPulse_ms","MCPPulse","Status,MCP","Monitor,MCP","MonitorRange,MCP","UnMonitorRange,MCP","UnMonitor,MCP","MCPGPIORange","MCPGPIOPattern","MCPMode","MCPModeRange","ExtGpio","ExtPwm","ExtPulse","ExtLongPulse","Status,EXT,","LCDCmd","LCD","PCFGPIO","PCFGPIOToggle","PCFLongPulse","PCFLongPulse_ms","PCFPulse","Status,PCF","Monitor,PCF","MonitorRange,PCF","UnMonitorRange,PCF","UnMonitor,PCF","PCFGPIORange","PCFGPIOpattern","PCFMode","PCFmodeRange","SerialSend","SerialSendMix","Ser2NetClientSend","SerialSend_test","pcapwm","pcafrq","mode2","OLED","OLEDCMD","OLEDCMD,on","OLEDCMD,off","OLEDCMD,clear","IRSEND","IRSENDAC","OledFramedCmd","OledFramedCmd,Display","OledFramedCmd,low","OledFramedCmd,med","OledFramedCmd,high","OledFramedCmd,Frame","OledFramedCmd,linecount","OledFramedCmd,leftalign","OledFramedCmd,align","OledFramedCmd,userDef1","OledFramedCmd,userDef2","NeoPixel","NeoPixelAll","NeoPixelLine","NeoPixelHSV","NeoPixelAllHSV","NeoPixelLineHSV","NeoPixelBright","MotorShieldCmd,DCMotor","MotorShieldCmd,Stepper","MHZCalibrateZero","MHZReset","MHZABCEnable","MHZABCDisable","Sensair_SetRelay","PMSX003","PMSX003,Wake","PMSX003,Sleep","PMSX003,Reset","encwrite","Play","Vol","Eq","Mode","Repeat","tareChanA","tareChanB","7dn","7dst","7dsd","7dtext","7ddt","7dt","7dtfont","7dtbin","7don","7doff","7output","HLWCalibrate","HLWReset","csecalibrate","cseclearpulses","csereset","WemosMotorShieldCMD","LolinMotorShieldCMD","GPS","GPS,Sleep","GPS,Wake","GPS#GotFix","GPS#LostFix","GPS#Travelled","homieValueSet","SerialProxy_Write","SerialProxy_WriteMix","SerialProxy_Test","HeatPumpir","MitsubishiHP","MitsubishiHP,temperature","MitsubishiHP,power","MitsubishiHP,mode","MitsubishiHP,fan","MitsubishiHP,vane","MitsubishiHP,widevane","Culreader_Write","Touch","Touch,Rot","Touch,Flip","Touch,Enable","Touch,Disable","Touch,On","Touch,Off","Touch,Toggle","Touch,Setgrp","Touch,Incgrp","Touch,Decgrp","Touch,Incpage","Touch,Decpage","Touch,Updatebutton","WakeOnLan","DotMatrix","DotMatrix,clear","DotMatrix,update","DotMatrix,size","DotMatrix,txt","DotMatrix,settxt","DotMatrix,content","DotMatrix,alignment","DotMatrix,anim.in","DotMatrix,anim.out","DotMatrix,speed","DotMatrix,pause","DotMatrix,font","DotMatrix,layout","DotMatrix,inverted","DotMatrix,specialeffect","DotMatrix,offset","DotMatrix,brightness","DotMatrix,repeat","DotMatrix,setbar","DotMatrix,bar","Thermo","Thermo,Up","Thermo,Down","Thermo,Mode","Thermo,ModeBtn","Thermo,Setpoint","Max1704xclearalert","scdgetabc","scdgetalt","scdgettmp","scdsetcalibration","scdsetfrc","scdgetinterval","multirelay","multirelay,on","multirelay,off","multirelay,set","multirelay,get","multirelay,loop","ShiftOut","ShiftOut,Set","ShiftOut,SetNoUpdate","ShiftOut,Update","ShiftOut,SetAll","ShiftOut,SetAllNoUpdate","ShiftOut,SetAllLow","ShiftOut,SetAllHigh","ShiftOut,SetChipCount","ShiftOut,SetHexBin","cdmrst","nfx","nfx,off","nfx,on","nfx,dim","nfx,line,","nfx,hsvline,","nfx,one,","nfx,hsvone,","nfx,all,","nfx,rgb,","nfx,fade,","nfx,hsv,","nfx,colorfade,","nfx,rainbow","nfx,kitt,","nfx,comet,","nfx,theatre,","nfx,scan,","nfx,dualscan,","nfx,twinkle,","nfx,twinklefade,","nfx,sparkle,","nfx,wipe,","nfx,dualwipe","nfx,fire","nfx,fireflicker","nfx,faketv","nfx,simpleclock","nfx,stop","nfx,statusrequest","nfx,fadetime,","nfx,fadedelay,","nfx,speed,","nfx,count,","nfx,bgcolor","ShiftIn","ShiftIn,PinEvent","ShiftIn,ChipEvent","ShiftIn,SetChipCount","ShiftIn,SampleFrequency","ShiftIn,EventPerPin","scd4x","scd4x,storesettings","scd4x,facoryreset","scd4x,selftest","scd4x,setfrc,","axp","axp,ldo2","axp,ldo3","axp,ldoio","axp,gpio0","axp,gpio1","axp,gpio2","axp,gpio3","axp,gpio4","axp,dcdc2","axp,dcdc3","axp,ldo2map","axp,ldo3map","axp,ldoiomap","axp,dcdc2map","axp,dcdc3map","axp,ldo2perc","axp,ldo3perc","axp,ldoioperc","axp,dcdc2perc","axp,dcdc3perc","I2CEncoder","I2CEncoder,bright","I2CEncoder,led1","I2CEncoder,led2","I2CEncoder,gain","I2CEncoder,set","cachereader","cachereader,readpos","cachereader,sendtaskinfo","cachereader,flush","tm1621","tm1621,write,","tm1621,writerow,","tm1621,voltamp,","tm1621,energy,","tm1621,celcius,","tm1621,fahrenheit,","tm1621,humidity,","tm1621,raw,","dac","dac,1","dac,2","sht4x","sht4x,startup","ld2410","ld2410,factoryreset","ld2410,logall","digipot","digipot,reset","digipot,shutdown","digipot,","7dextra","7dbefore","7dgroup","7digit","7color","7digitcolor","7groupcolor","gp8403","gp8403,volt,","gp8403,mvolt,","gp8403,range,","gp8403,preset,","gp8403,init,","sen5x","sen5x,startclean","sen5x,techlog,","as3935","as3935,clearstats","as3935,calibrate","as3935,setgain,","as3935,setnf,","as3935,setwd,","as3925,setsrej,","lu9685","lu9685,servo,","lu9685,enable,","lu9685,disable,","lu9685,setrange,","geni2c","geni2c,cmd,","geni2c,exec,","geni2c,log,"],pluginDispKind=["tft","ili9341","ili9342","ili9481","ili9486","ili9488","epd","eink","epaper","il3897","uc8151d","ssd1680","ws2in7","ws1in54","st77xx","st7735","st7789","st7796","neomatrix","neo","pcd8544"],pluginDispCmd=["cmd,on","cmd,off","cmd,clear","cmd,backlight","cmd,bright","cmd,deepsleep","cmd,seq_start","cmd,seq_end","cmd,inv","cmd,rot",",clear",",rot",",tpm",",txt",",txp",",txz",",txc",",txs",",txtfull",",asciitable",",font",",l",",lh",",lv",",lm",",lmr",",r",",rf",",c",",cf",",rf",",t",",tf",",rr",",rrf",",px",",pxh",",pxv",",bmp",",btn",",win",",defwin",",delwin"],commonTag=["On","Do","Endon"],commonNumber=["toBin","toHex","Constrain","XOR","AND:","OR:","Ord","bitRead","bitSet","bitClear","bitWrite","urlencode"],commonMath=["Log","Ln","Abs","Exp","Sqrt","Sq","Round","Sin","Cos","Tan","aSin","aCos","aTan","Sin_d","Cos_d","Tan_d","aSin_d","aCos_d","aTan_d","map","mapc"],commonWarning=["delay","Delay","ResetFlashWriteCounter"],taskSpecifics=["settings.Enabled","settings.Interval","settings.ValueCount","settings.Controller1.Enabled","settings.Controller2.Enabled","settings.Controller3.Enabled","settings.Controller1.Idx","settings.Controller2.Idx","settings.Controller3.Idx"],AnythingElse=["%eventvalue%","%eventpar%","%eventname%","%sysname%","%bootcause%","%systime%","%systm_hm%","%systm_hm_0%","%systm_hm_sp%","%systime_am%","%systime_am_0%","%systime_am_sp%","%systm_hm_am%","%systm_hm_am_0%","%systm_hm_am_sp%","%lcltime%","%sunrise%","%s_sunrise%","%m_sunrise%","%sunset%","%s_sunset%","%m_sunset%","%lcltime_am%","%syshour%","%syshour_0%","%sysmin%","%sysmin_0%","%syssec%","%syssec_0%","%sysday%","%sysday_0%","%sysmonth%","%sysmonth_0%","%systzoffset%","%systzoffset_s%","%sysyear%","%sysyear_0%","%sysyears%","%sysweekday%","%sysweekday_s%","%unixtime%","%unixtime_lcl%","%uptime%","%uptime_ms%","%rssi%","%ip%","%unit%","%unit_0%","%ssid%","%bssid%","%wi_ch%","%iswifi%","%vcc%","%mac%","%mac_int%","%isntp%","%ismqtt%","%dns%","%dns1%","%dns2%","%flash_freq%","%flash_size%","%flash_chip_vendor%","%flash_chip_model%","%fs_free%","%fs_size%","%cpu_id%","%cpu_freq%","%cpu_model%","%cpu_rev%","%cpu_cores%","%board_name%","%inttemp%","%islimited_build%","%isvar_double%","substring","lookup","indexOf","indexOf_ci","equals","equals_ci","strtol","timeToMin","timeToSec","%ethwifimode%","%ethconnected%","%ethduplex%","%ethspeed%","%ethstate%","%ethspeedstate%","%c_w_dir%","%c_c2f%","%c_ms2Bft%","%c_dew_th%","%c_alt_pres_sea%","%c_sea_pres_alt%","%c_cm2imp%","%c_isnum%","%c_mm2imp%","%c_m2day%","%c_m2dh%","%c_m2dhm%","%c_s2dhms%","%c_ts2date%","%c_ts2wday%","%c_random%","%c_2hex%","%c_u2ip%","%c_uname%","%c_uage%","%c_ubuild%","%c_ubuildstr%","%c_uload%","%c_utype%","%c_utypestr%","%c_strf%","var","int","str","length"];for(const e of pluginDispKind)commonPlugins=commonPlugins.concat(e);for(const e of pluginDispKind)for(const t of pluginDispCmd){let n=e+t;commonPlugins=commonPlugins.concat(n)}var rEdit,EXTRAWORDS=commonAtoms.concat(commonPlugins,commonKeywords,commonCommands,commonEvents,commonTag,commonNumber,commonMath,commonWarning,taskSpecifics,AnythingElse),confirmR=!0,android=/Android/.test(navigator.userAgent);function initCM(){android&&(confirmR=!!confirm("Do you want to enable colored rules?\n(There are some issues with Android causing it to fail!)\nTestet with Chrome, Firefox and Vivaldi so far.\nPlease report any issues you may have with this feature.")),confirmR&&(CodeMirror.commands.autocomplete=function(e){e.showHint({hint:CodeMirror.hint.anyword})},(rEdit=CodeMirror.fromTextArea(document.getElementById("rules"),{tabSize:2,indentWithTabs:!1,lineNumbers:!0,autoCloseBrackets:!0,extraKeys:{"Ctrl-Space":"autocomplete",Tab:e=>{"null"===e.getMode().name?e.execCommand("insertTab"):e.somethingSelected()?e.execCommand("indentMore"):e.execCommand("insertSoftTab")},"Shift-Tab":e=>e.execCommand("indentLess")}})).on("change",(function(){rEdit.save()})),android||rEdit.on("inputRead",(function(e,t){var n=e.getCursor(),o=e.getTokenAt(n);/[\w%,.]/.test(t.text)&&"comment"!=o.type&&e.showHint({completeSingle:!1})})),CodeMirror.keyMap.default["Ctrl-F"]=function(e){openFind()},CodeMirror.keyMap.default["Cmd-F"]=function(e){openFind()})}function closeSearchDialog(){const e=document.querySelectorAll(".CodeMirror-dialog");e.length>0&&(e.forEach((e=>e.remove())),document.body.classList.remove("dialog-opened")),rEdit.execCommand("clearSearch")}function removeHighlight(){requestAnimationFrame((()=>{document.querySelectorAll(".search-next-highlight").forEach((e=>e.classList.remove("search-next-highlight")))}))}let findDialogObserver=null;function openFind(){findDialogObserver&&(findDialogObserver.disconnect(),findDialogObserver=null),findDialogObserver=new MutationObserver((()=>{document.querySelector(".CodeMirror-dialog")||(removeHighlight(),findDialogObserver.disconnect(),findDialogObserver=null)})),findDialogObserver.observe(document.body,{childList:!0,subtree:!0}),clearSearchNextHighlight(rEdit),rEdit.execCommand("findPersistent"),addFindButtons()}function clearSearchNextHighlight(e){removeHighlight(),e.__searchNextHighlight&&(e.__searchNextHighlight.clear(),e.__searchNextHighlight=null)}function addFindButtons(){document.querySelector(".CodeMirror-selected");const e=document.querySelector(".CodeMirror-dialog");if(!e||e.querySelector(".search-button-group"))return;[{title:"Find Previous",symbol:"▲",action:()=>rEdit.execCommand("findPersistentPrev")},{title:"Find Next",symbol:"▼",action:()=>rEdit.execCommand("findPersistentNext")},{title:"Replace",symbol:"Replace",action:()=>{closeSearchDialog(),rEdit.execCommand("replace"),addFindButtons()}},{title:"Close",symbol:"❌",action:closeSearchDialog},{title:"Help",symbol:"?",action:()=>{alert("Available shortcuts:\n• Ctrl+F / Cmd+F: Open search\n• Ctrl+G / Cmd+G: Find next\n• Shift+Ctrl+G / Shift+Cmd+G: Find previous\n• Shift+Ctrl+F / Cmd+Option+F: Replace\n• Shift+Ctrl+R / Shift+Cmd+Option+F: Replace all\n• Use /re/ syntax for regexp search")}}].forEach((({title:t,symbol:n,action:o})=>{const i=document.createElement("span");i.title=t,i.className="help"===t.toLowerCase()?"button help":"button",i.innerHTML=n,i.style.cssText="\n cursor: pointer;\n user-select: none;\n ",i.addEventListener("click",(e=>{e.preventDefault(),o()})),e.appendChild(i)}))}function triggerFormatting(){if(confirmR){const e=rEdit.getDoc(),t=(rEdit.getScrollInfo(),e.getCursor()),n=0===t.ch?t.line-1:t.line;rEdit.getLine(n)}let e=confirmR?rEdit.getValue():document.getElementById("rules").value;if(e=initalAutocorrection(e),e=formatLogic(e),confirmR){rEdit.setValue(e);const t=currentLine,n=0===cursor.ch&&lineText.length>0?lineText.length:cursor.ch-1;rEdit.setCursor({line:t,ch:n}),rEdit.scrollTo(scrollInfo.left,scrollInfo.top),rEdit.focus(),rEdit.save()}else document.getElementById("rules").value=e}function initalAutocorrection(e){for(const t of EXTRAWORDS)if("Do"===t){const t=/(^|\s)(do)(\s*)(\/\/.*)?$/gim;e=e.replace(t,((e,t,n,o,i)=>`${t}Do${o}${i??""}`))}else{const n=new RegExp(`^\\s*\\b${t}\\b`,"gmi");e=e.replace(n,(e=>e.replace(new RegExp(t,"i"),t)))}return e}function formatLogic(e){const t=" ",n=e.split("\n").map((e=>{const t=e.trimStart();return t.startsWith("//")?e:t})),o=[],i=[];let r=!1,s=null,a=[],c=[];function l(e){return e.trim().startsWith("//")}function d(e){return""===e.trim()}function m(e){return e.trim().toLowerCase().startsWith("on")}function u(e){return e.trim().toLowerCase().endsWith("do")}function f(e){return"endon"===e.trim().toLowerCase()}function h(e){return e.trim().toLowerCase().startsWith("if")}function p(e){return"else"===e.trim().toLowerCase()}function g(e){return e.trim().toLowerCase().startsWith("elseif")}function x(e){return"endif"===e.trim().toLowerCase()}let C=0;function S(){a.length>0&&(i.push(`• Missing ${a.length} Endif(s):`),i.push(` - Unclosed If block(s) starting at line(s): ${c.join(", ")}`)),a=[],c=[]}for(let e=0;e0){const e=extractFirstErrorLine(i);if(alert("Errors found:\n"+i.join("\n")),!isNaN(e))if(confirmR)setTimeout((()=>{jumpToLine(e)}),50);else{const t=document.getElementById("rules");setTimeout((()=>{jumpToLineInTextarea(t,e)}),50)}}return o.join("\n")}function jumpToLine(e){const t=Math.max(0,e-1);rEdit.setCursor({line:t,ch:0}),rEdit.focus(),rEdit.scrollIntoView({line:t,ch:0},100)}function extractFirstErrorLine(e){for(const t of e){let e=t.match(/• Line (\d+)/);if(e)return parseInt(e[1]);if(e=t.match(/starting at line (\d+)/),e)return parseInt(e[1]);if(e=t.match(/starting at line\(s\):\s*(\d+)/),e)return parseInt(e[1])}return null}function jumpToLineInTextarea(e,t){const n=e.value.split("\n"),o=Math.max(1,Math.min(t,n.length));let i=0;for(let e=0;e{const e=document.getElementById("rulesselect");if(e){if(confirmR){const t=document.createElement("button");t.type="button",t.id="searchBtn",t.innerHTML="🔎︎",t.style.padding="2px 5px",t.className="button help",e.appendChild(t),t.addEventListener("click",(()=>{void 0!==rEdit&&openFind()}))}const t=document.createElement("button");t.type="button",t.id="formatBtn",t.textContent="Format",t.className="button",e.appendChild(t),t.addEventListener("click",(()=>{triggerFormatting()}))}let t="";if(document.addEventListener("keydown",(function(e){const n=e.key;if(e.ctrlKey&&e.shiftKey&&"f"===n.toLowerCase())return e.preventDefault(),void triggerFormatting();(["Backspace","Delete","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter","Tab","Escape","Shift","Control","Alt","Meta"].includes(n)||1!==n.length)&&(t="")})),android){var n=!1;rEdit.on("keydown",((e,o)=>{["Enter","Backspace"," "].includes(o.key)&&(t=""),n=!0}));let e="";const i=rEdit.getInputField();function o(o,i=!1){if(!(rEdit.hasFocus()&&rEdit&&o.data&&n))return;n=!1;const r=o.data,s=rEdit.getDoc(),a=s.getCursor(),c=rEdit.getTokenAt(a);if(" "===r)return t="",void(e="");if(!(r===e&&t.length>0))if(/[\w%,.]/.test(r)&&"comment"!==c.type){const n=a.ch<=1?r.slice(-1):r;t+=n,e=t,t.startsWith(String(a.line+1))&&0===a.ch&&(t=t.slice(String(a.line).length));const o={line:a.line,ch:a.ch-t.length+1},c=()=>{s.replaceRange(t,o,a),rEdit.setCursor({line:o.line,ch:o.ch+t.length}),rEdit.showHint({completeSingle:!1})};i?c():setTimeout(c,0)}else t=""}const r=navigator.userAgent.toLowerCase(),s=/firefox/.test(r),a=/chrome/.test(r)&&!s;s?i.addEventListener("beforeinput",(e=>{e.preventDefault(),o(e,!0)})):a&&document.addEventListener("input",(e=>{o(e,!1)})),rEdit.on("endCompletion",(function(){setTimeout((()=>{!function(){const e=document.createElement("input");e.type="text",e.style.position="absolute",e.style.opacity="0",e.style.height="0",e.style.width="0",e.style.border="none",e.style.top="0",e.style.left="-9999",e.style.padding="0",e.style.zIndex="-1",e.style.fontSize="16px",document.body.appendChild(e),e.focus(),setTimeout((()=>{e.remove(),rEdit.focus()}),10)}()}),100)}))}})),function(e){"object"==typeof exports&&"object"==typeof module?e(require("codemirror")):"function"==typeof define&&define.amd?define(["codemirror"],e):e(CodeMirror)}((function(e){"use strict";e.defineMode("espeasy",(function(){var e={};function t(t,n){for(var o=0;oe.toLowerCase()));commonCommands=commonCommands.concat(n);var o=commonEvents.map((e=>e.toLowerCase()));commonEvents=commonEvents.concat(o);var i=commonPlugins.map((e=>e.toLowerCase()));commonPlugins=commonPlugins.concat(i);var r=commonAtoms.map((e=>e.toLowerCase()));commonAtoms=commonAtoms.concat(r);var s=commonKeywords.map((e=>e.toLowerCase()));commonKeywords=commonKeywords.concat(s);var a=commonTag.map((e=>e.toLowerCase()));commonTag=commonTag.concat(a);var c=commonNumber.map((e=>e.toLowerCase()));commonNumber=commonNumber.concat(c);var l=commonMath.map((e=>e.toLowerCase()));commonMath=commonMath.concat(l);var d=AnythingElse.map((e=>e.toLowerCase()));AnythingElse=AnythingElse.concat(d);var m=taskSpecifics.map((e=>e.toLowerCase()));function u(t,n){if(t.eatSpace())return null;t.sol();var o=t.next();if(/\d/.test(o)){if("0"==o)return"x"===t.next()?(t.eatWhile(/\w/),"number"):(t.eatWhile(/\d|\./),"number");if(t.eatWhile(/\d|\./),!t.match("d")&&!t.match("output")&&(t.eol()||/\D/.test(t.peek())))return"number"}if(/\w/.test(o))for(const e of EXTRAWORDS){let n=e.substring(1);(e.includes(":")||e.includes(",")||e.includes("."))&&t.match(n)}if(/\w/.test(o)&&(t.eatWhile(/[\w]/),t.match(".gpio")||t.match(".pulse")||t.match(".frq")||t.match(".pwm")))return"def";if("\\"===o)return t.next(),null;if("("===o||")"===o)return"bracket";if("{"===o||"}"===o||":"===o)return"number";if("/"==o)return/\//.test(t.peek())?(t.skipToEnd(),"comment"):"operator";if("'"==o&&(t.eatWhile(/[^']/),t.match("'")))return"attribute";if("+"===o||"="===o||"<"===o||">"===o||"-"===o||","===o||"*"===o||"!"===o)return"operator";if("%"==o){if(/\d/.test(t.next()))return"number";if(t.eatWhile(/[^\s\%]/),t.match("%"))return"hr"}if("["==o&&(t.eatWhile(/[^\s\]]/),t.eat("]")))return"hr";t.eatWhile(/\w/);var i=t.current();return/\w/.test(o)&&t.match("#")?(t.eatWhile(/[\w.#]/),"events"):"#"===o?(t.eatWhile(/\w/),"number"):e.hasOwnProperty(i)?e[i]:null}function f(e,t){return(t.tokens[0]||u)(e,t)}return taskSpecifics=taskSpecifics.concat(m),t("atom",commonAtoms),t("keyword",commonKeywords),t("builtin",commonCommands),t("events",commonEvents),t("def",commonPlugins),t("tag",commonTag),t("number",commonNumber),t("bracket",commonMath),t("warning",commonWarning),t("hr",AnythingElse),t("comment",taskSpecifics),{startState:function(){return{tokens:[]}},token:function(e,t){return f(e,t)},closeBrackets:"[]{}''\"\"``()",lineComment:"//",fold:"brace"}}))})),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):e(CodeMirror)}((function(e){var t={pairs:"()[]{}''\"\"",closeBefore:")]}'\":;>",triples:"",explode:"[]{}"},n=e.Pos;function o(e,n){return"pairs"==n&&"string"==typeof e?e:"object"==typeof e&&null!=e[n]?e[n]:t[n]}e.defineOption("autoCloseBrackets",!1,(function(t,n,s){s&&s!=e.Init&&(t.removeKeyMap(i),t.state.closeBrackets=null),n&&(r(o(n,"pairs")),t.state.closeBrackets=n,t.addKeyMap(i))}));var i={Backspace:function(t){var i=a(t);if(!i||t.getOption("disableInput"))return e.Pass;for(var r=o(i,"pairs"),s=t.listSelections(),c=0;c=0;c--){var m=s[c].head;t.replaceRange("",n(m.line,m.ch-1),n(m.line,m.ch+1),"+delete")}},Enter:function(t){var n=a(t),i=n&&o(n,"explode");if(!i||t.getOption("disableInput"))return e.Pass;for(var r=t.listSelections(),s=0;s1&&h.indexOf(i)>=0&&t.getRange(n(b.line,b.ch-2),b)==i+i){if(b.ch>2&&/\bstring/.test(t.getTokenTypeAt(n(b.line,b.ch-2))))return e.Pass;S="addFour"}else if(p){var v=0==b.ch?" ":t.getRange(n(b.line,b.ch-1),b);if(e.isWordChar(P)||v==i||e.isWordChar(v))return e.Pass;S="both"}else{if(!x||!(0===P.length||/\s/.test(P)||f.indexOf(P)>-1))return e.Pass;S="both"}else S=p&&m(t,b)?"both":h.indexOf(i)>=0&&t.getRange(b,n(b.line,b.ch+3))==i+i+i?"skipThree":"skip";if(u){if(u!=S)return e.Pass}else u=S}var T=d%2?s.charAt(d-1):i,M=d%2?i:s.charAt(d+1);t.operation((function(){if("skip"==u)c(t,1);else if("skipThree"==u)c(t,3);else if("surround"==u){for(var e=t.getSelections(),n=0;n0?{line:s.head.line,ch:s.head.ch+t}:{line:s.head.line-1};n.push({anchor:a,head:a})}e.setSelections(n,i)}function l(t){var o=e.cmpPos(t.anchor,t.head)>0;return{anchor:new n(t.anchor.line,t.anchor.ch+(o?-1:1)),head:new n(t.head.line,t.head.ch+(o?1:-1))}}function d(e,t){var o=e.getRange(n(t.line,t.ch-1),n(t.line,t.ch+1));return 2==o.length?o:null}function m(e,t){var o=e.getTokenAt(n(t.line,t.ch+1));return/\bstring/.test(o.type)&&o.start==t.ch&&(0==t.ch||!/\bstring/.test(e.getTokenTypeAt(t)))}r(t.pairs+"`")})); \ No newline at end of file